diff --git a/README.md b/README.md index e9eed28..d4f7604 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ ## 当前定位入口 -默认定位已切换到连续跟踪的 LIO(`field_localization_node`)。必须先用 `LIO_MODE=mapping` 建立并导出 3D 地图,再以只读地图定位;缺图会明确报错。完整用法、时间/外参约定和局限见 [field_localization](src/field_localization/README.md)。 +默认定位已切换到连续跟踪的 LIO(`field_localization_node`)。Shell 和 Python 启动默认只读加载仓库随附的 `src/sentry_sim/maps/field_full.flmap`,覆盖当前 Gazebo 场地。完整用法、时间/外参约定和局限见 [field_localization](src/field_localization/README.md)。 `LOCALIZATION=amcl scripts/sentry_up.sh`(或 Python 启动参数 `localization:=amcl`)选择旧方案。下文与 `docs/定位接入AMCL.md` 中的 AMCL 参数/排障说明仅适用于该分支。每次只启动一种定位器发布 `map→odom`,两种方案均保留 Nav2 的 2D map_server。 @@ -60,7 +60,7 @@ sentry_nav_dev/ 仓库根(xmake 工程根) │ │ │ ├── sentry_nav/ 导航/决策节点(C++,唯一的可编译包) │ └── sentry_sim/ 仿真环境(147 MB,其中网格 146 MB) -├── tools/ 模型转换与调试工具(独立脚本,不参与构建) +├── tools/ 日常工具、验收和启动/构建辅助脚本 ├── generated/ 运行时产物(可随时删) ├── .vscode/ IDE 配置(不影响仿真) └── build/ xmake 构建产物(不入 git) @@ -74,7 +74,7 @@ sentry_nav_dev/ 仓库根(xmake 工程根) | `src/sentry_nav/` | 算法代码 | 在这块实现算法 | | `src/sentry_sim/` | 仿真基础设施(模型/参数/启动) | 改模型和调参时动 | | `field/` | 官方场地包副本(地图 + 3D 场地) | 官方更新时整包替换 | -| `tools/` | 辅助工具脚本 | 按需加新工具 | +| `tools/` | [工具索引](tools/README.md) | 日常命令在顶层,内部脚本与验收分别归档 | | `docs/` | 技术文档 | 有新发现就补 | | `generated/` | 运行时产物 | 可删 | | `build/` | xmake 产物 | 不入 git | @@ -132,7 +132,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 # 启动(日志自动落盘 generated/up.log) python3 tools/check_stack.py # 体检(只读) -build/bin/nav_client 2.0 2.0 # 发一个导航目标(先 xmake 编译) +build/bin/nav_client 0.0 0.0 # 发一个导航目标(先 xmake 编译) ros2 topic pub -r 10 /cmd_vel geometry_msgs/msg/Twist "{linear: {x: 0.5}}" # 手动前进 ``` diff --git a/docs/操作手册.md b/docs/操作手册.md index 2d80976..7090c9d 100644 --- a/docs/操作手册.md +++ b/docs/操作手册.md @@ -125,6 +125,8 @@ build/bin/nav_client 2.0 2.0 # 目标 x=2.0 y=2.0(场地坐标,米) 换一个开阔的点,或先在 RViz 里看一眼 /global_costmap/costmap。 ``` +发目标前,客户端还会检查 `map → base_link` 的时效。发现 LIO 心跳时,要求最近 0.3 秒内收到有效心跳。`--force` 只跳过静态地图预检。Nav2 返回的错误码和消息会随结果打印,中止、取消和超时均返回非零退出码。 + **通过预检后**长这样(地图行与预检行是实算的,位姿行是格式示意,逐条刷新): ``` @@ -225,10 +227,10 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真 ## 6. 环境变量 -**路径和版本相关的变量全部是「不设就自动探测」**,探测逻辑只有一份: -`src/sentry_sim/scripts/env_common.sh`(shell)和 `tools/project_env.py`(Python)。 -想看本机实际探到什么:`python3 tools/project_env.py` -或(不启动任何进程)`SENTRY_DRY_RUN=1 scripts/sentry_up.sh`。 +Shell 和 Python 的路径与版本探测都由 `tools/project_env.py` 实现。 +用 `python3 tools/project_env.py` 查看探测结果,或运行 `SENTRY_DRY_RUN=1 scripts/sentry_up.sh` 预演启动。 +单项查询成功返回 `0`,探测失败返回 `1`,参数错误返回 `2`。失败时 stdout 为空,错误写入 stderr。 +未构建时 `--bin-dir` 仍返回预期的 `build/bin`,已加载 ROS 时 `--ros-setup` 返回空值。 ### 行为开关 @@ -239,6 +241,7 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真 | `RVIZ` | `1` | `0` = 不起 RViz | | `ROS_DOMAIN_ID` | `0` | 两个终端必须一致才能互相看到话题 | | `GZ_PARTITION` | `sentry` | Gazebo 分区,多套仿真隔离用 | +| `BRIDGE_WAIT_TIMEOUT` | `120` | 等待 Gazebo 发布 `/clock` 的秒数。单次查询至多 2 秒,等不到时启动失败 | | `SENTRY_DRY_RUN` | `0` | `1` = 只打印探测结果然后退出,不启动任何进程 | | `SENTRY_LOG` | `1` | 启动日志自动写 `generated/up.log`(每次加分隔线)。`0` = 关闭,`<路径>` = 换位置 | | `SENTRY_SIM_SHARE` | 仓库内 `src/sentry_sim` | 数据包位置,同时导出给 `xacro` 解析网格路径 | @@ -247,24 +250,23 @@ python3 tools/check_stack.py # 一次性检查节点/话题/TF/真 | 变量 | 自动探测规则 | 说明 | |---|---|---| -| `SENTRY_FIELD_ROOT` | `field/*/src/guodong_sentry_sim` → 退 `~/Gazebo_projects/*map_transfer*/` | 场地迁移包根目录,**不绑具体包名/日期** | -| `SENTRY_MAP_YAML` | 迁移包下 `maps/*/rmul_2027.yaml`,没有就取第一个 | 换地图时直接指这个 | -| `SENTRY_BIN_DIR` | **`build/bin/`** 优先;老 checkout 退回 `build/*/*/{release,debug}` | xmake 产物目录,**不绑平台三元组**。旧名 `NAV_BIN_DIR` 仍有效 | +| `SENTRY_FIELD_ROOT` | 优先仓库内场地包,再查 `~/Gazebo_projects/*map_transfer*/` | 覆盖值必须是现有目录 | +| `SENTRY_MAP_YAML` | 依次查标准位置的 `rmul_2027.yaml`、按路径排序的同名文件、按路径排序的第一个普通 YAML 文件 | 覆盖值必须是普通文件 | +| `SENTRY_BIN_DIR` | `build/bin` → 旧布局 `release` → 旧布局 `debug`。同一模式按平台和架构路径排序,目录须有已知可执行产物 | 覆盖值必须是现有目录,优先于旧变量 `NAV_BIN_DIR` | ### 版本(不设就自动探测) | 变量 | 自动探测规则 | 说明 | |---|---|---| | `ROS_SETUP` | — | 直接指定要 source 的 `setup.bash` 全路径 | -| `ROS_DISTRO` | 环境里已有就用;否则取 `/opt/ros/*` 里版本号最大的 | 换 ROS 发行版不用改脚本 | +| `ROS_DISTRO` | 优先使用对应发行版。需自动扫描时按 ROS 安装目录名自然排序,选择最后一个 | ROS 已加载时沿用当前环境 | | `ROS_INSTALL_ROOT` | — | 非 `/opt/ros` 的 ROS 安装前缀(源码编译) | | `ROS_PREFIX` | — | **只给 `xmake` 用**:ROS 安装前缀。都不设时 xmake 依次看 `AMENT_PREFIX_PATH` → `ROS_DISTRO` → 报错 | -| `GZ_BIN` | 优先 `/usr/bin/gz` → `/usr/local/bin/gz` → `$PATH` 上的 `gz` | 为什么优先系统版:vendor 版缺 cpu-lidar 插件 | -| `GZ_FORCE_VERSION` | 取 `gz sim --version` 的主版本 | 换 Gazebo 大版本不用改脚本 | +| `GZ_BIN` | `/usr/bin/gz` → `/usr/local/bin/gz` → `/opt/gz/bin/gz` → `PATH` | 覆盖值必须指向可执行的普通文件 | +| `GZ_FORCE_VERSION` | 用选中的 Gazebo 查询主版本,最多等待 5 秒 | 查询失败时警告并继续使用 Gazebo 默认版本。设置此变量可跳过查询 | -> 上表这些变量**两条启动链都认**(`scripts/sentry_up.sh` 和 `ros2 launch`), -> 因为它们读的是同一份探测库(`env_common.sh` / `project_env.py`)。 -> 注意 `ROS_PREFIX` 是唯一的例外:它只被 `xmake` 读(构建期找 ROS 头文件用)。 +Python 入口使用已加载的 ROS 环境。`field_root:=` 和 `map:=` 优先于对应的环境变量。只指定场地时,会在该场地目录下自动找地图。 +`ROS_PREFIX` 用于 xmake 构建。 --- diff --git a/src/field_localization/README.md b/src/field_localization/README.md index c7cc898..22a2e93 100644 --- a/src/field_localization/README.md +++ b/src/field_localization/README.md @@ -18,23 +18,23 @@ xmake test ## 建图、保存与只读定位 -先显式建图,再启动只读地图定位: +当前 Gazebo 场地可直接用 `scripts/sentry_up.sh` 启动。两个入口默认只读加载 `src/sentry_sim/maps/field_full.flmap`。需要自建地图时可单独写入新路径: ```bash -LIO_MODE=mapping LIO_MAP="$PWD/generated/field.flmap" scripts/sentry_up.sh +LIO_MODE=mapping scripts/sentry_up.sh # 在机器人处于已知初始位姿后开始移动;保存当前地图: ros2 service call /field_localization/save_map std_srvs/srv/Trigger '{}' # 停止上一套进程;正常退出也会执行最终地图导出。 -LIO_MAP="$PWD/generated/field.flmap" scripts/sentry_up.sh +LIO_MAP="$PWD/generated/field_mapping.flmap" scripts/sentry_up.sh ``` -Shell 默认 `LOCALIZATION=lio`、`LIO_MODE=localization`,缺失地图立即报错。可显式用 `LOCALIZATION=amcl` 选择旧方案;不自动回退。两个分支都保留 Nav2 的 2D map_server,但只有 AMCL 分支启动 AMCL。`NAV2=0` 不启动导航,仍可运行 LIO 建图。 +Shell 默认 `LOCALIZATION=lio`、`LIO_MODE=localization`,缺失地图立即报错。建图模式默认写入 `generated/field_mapping.flmap`。可显式用 `LOCALIZATION=amcl` 选择旧方案;不自动回退。两个分支都保留 Nav2 的 2D map_server,但只有 AMCL 分支启动 AMCL。`NAV2=0` 不启动导航,仍可运行 LIO 建图。 Python 启动入口在仿真时钟和 odom/base/lidar TF 就绪后,通过与 shell 相同的独立启动进程运行 Nav2,具有对应参数: ```bash -ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_mode:=mapping lio_map:="$PWD/generated/field.flmap" -ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_map:="$PWD/generated/field.flmap" +ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_mode:=mapping +ros2 launch src/sentry_sim/launch/sentry_arena.launch.py lio_map:="$PWD/generated/field_mapping.flmap" ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl ``` @@ -42,9 +42,20 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py localization:=amcl 只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 0.5 m,或旋转严格大于 10°。初始化种子帧是唯一例外。配准失败不写图。 +### 单独生成全场 Gazebo 地图 + +```bash +python3 tools/capture_lio.py --profile mapping --full-field \ + --output generated/full_survey --map generated/field_full.flmap +python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \ + --map generated/field_full.flmap --lio-cloud-topic /scan/points_lio --output generated/full_shell +``` + +该模式在隔离的 Gazebo 空场沿重叠测站采集实际雷达扫描。测站坐标由命令指定,Gazebo 真值只核对到位误差。全场图包含南走廊的地面回波,为 LIO 提供垂直方向约束。避障用的 `/scan/points_filtered` 和 `/scan2d` 继续沿用原有的地面滤除规则。全场图对应当前仿真模型和雷达外参,改场地或更换外参后应重新采集和验收。 + ## ROS 接口与坐标约定 -- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。完整启动器显式选择 `/scan/points_filtered`。 +- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。Shell、Python 启动和录制工具均使用 `/scan/points_lio`。旧版地图可配合 `LIO_POINT_CLOUD_TOPIC=/scan/points_filtered` 显式录制或启动,Python 也可传 `lio_point_cloud_topic:=/scan/points_filtered`。 - 原始云在 `lidar_link`,自滤云在 `base_link`;适配器使用固定 TF 统一到 LiDAR 系。方位角时间估计也在 LiDAR 系完成,不重复施加安装外参。 - 默认固定帧:`map/odom/base_link/imu_link/lidar_link`,均可通过同名 frame 参数配置。外参从现有固定 TF 读取;缺失时等待,禁止假设为恒等变换。 - 内部状态原点为 IMU,`q` 将 IMU 坐标旋转到 map,`v/g` 在 map 系。误差顺序为 `p,v,theta,bg,ba,g`,右扰动态度误差。 @@ -69,9 +80,9 @@ Gazebo 的 IMU 传感器配置无噪声;正式回放使用原始数据,不 ## 离线数据、回放与独立真值 ```bash -python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap --duration 120 -python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap --duration 120 -build/bin/field_localization_replay --dataset generated/lio_evaluation --mode localization --map generated/field.flmap --output generated/lio_metrics +python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap --duration 120 +python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap --duration 120 +build/bin/field_localization_replay --dataset generated/lio_evaluation --mode localization --map src/sentry_sim/maps/field_full.flmap --output generated/lio_metrics ``` 采集前需要已有 ROS Python 环境。脚本使用独立 Gazebo partition 和 ROS domain,只清理由自己创建的进程树;创建输出目录中的 `STOP` 文件可请求停止。控制器仅用轮速里程计走西北走廊路线,真值只进入记录器。两次采集使用不同路线,地图与定位序列分开。 @@ -101,12 +112,12 @@ GCC 15.2 清洁重构建零警告,11 套 xmake 测试通过。五组带噪合 完整 Nav2 启动检查命令: ```bash -python3 tools/verify_lio_stack.py --map generated/field.flmap --output generated/lio_stack_check +python3 tools/validation/verify_lio_stack.py --map src/sentry_sim/maps/field_full.flmap --output generated/lio_stack_check ``` 实测 9 个所需生命周期节点均 ACTIVE,AMCL 不存在,map→odom 仅一个发布者,没有 map→base_link 发布。交付数据中附带原始序列、收敛曲线 CSV、轨迹、逐帧状态、TF/生命周期检查 JSON 与构建日志。 -Python 入口可用 `tools/verify_lio_stack.py --launcher python` 做同样的完整启动检查;验证器等待生命周期管理器报告激活完成,并继续观察稳定状态,避免在 bond 握手结束前退出。 +Python 入口可用 `tools/validation/verify_lio_stack.py --launcher python` 做同样的完整启动检查;验证器等待生命周期管理器报告激活完成,并继续观察稳定状态,避免在 bond 握手结束前退出。 ### 导航有效性与失效保护 @@ -121,10 +132,29 @@ Python 入口可用 `tools/verify_lio_stack.py --launcher python` 做同样的 两个入口都可运行相同的隔离验收。域编号可用 `--domain` 显式保留给并行测试;如域已有导航或定位节点,启动器会拒绝启动。 ```bash -python3 tools/run_lio_matrix.py --launcher shell --map generated/field.flmap --output generated/lio_matrix_shell -python3 tools/run_lio_matrix.py --launcher python --map generated/field.flmap --output generated/lio_matrix_python -python3 tools/validate_lio_navigation.py --launcher shell --scenario lidar_loss --goal 0 0 \ - --map generated/field.flmap --output generated/lio_lidar_loss +python3 tools/validation/run_lio_matrix.py --launcher shell --map src/sentry_sim/maps/field_full.flmap --output generated/lio_matrix_shell +python3 tools/validation/run_lio_matrix.py --launcher python --map src/sentry_sim/maps/field_full.flmap --output generated/lio_matrix_python +python3 tools/validation/validate_lio_navigation.py --launcher shell --scenario lidar_loss --goal 0 0 \ + --map src/sentry_sim/maps/field_full.flmap --output generated/lio_lidar_loss ``` 默认矩阵各跑三次空场和三次圆柱绕行,再跑一次堵塞。默认圆柱在 `(-4, -1.5)`,半径 0.22 m、高 0.8 m。每次保留启动与目标日志、录制数据、TF 发布者数、最小圆柱净距及无需轨迹对齐的 3D ATE 和 1 秒 RPE。堵塞场景要求 Nav2 返回明确中止。断流场景只停止试验自己创建的自滤节点,并用执行器收到的零速度测量停车延迟。实测位姿来自 Gazebo PosePublisher,只参与评估。 + +### 复现连续往返失效 + +`--round-trip-regression` 在同一个仿真实例中连续发送五个目标,复现中间停留的时间。支持 `clear` 和 `cylinder`,每段保存单独的目标日志、真值终点误差和轨迹指标。总报告包含停留期间的定位误差和首次定位失效时间。 + +```bash +python3 tools/validation/validate_lio_navigation.py --launcher shell --scenario clear \ + --map generated/field.flmap --output generated/lio_round_trip_clear --round-trip-regression +``` + +用 `--launcher python` 切换入口。每次使用新的输出目录。跟踪 CSV 在原有字段后附加配准阶段和拒绝原因,以及初始与末次匹配的候选平面、支撑范围拒绝、面距离拒绝和内点数。可对同一条瞬时扫描离线比较预测位姿和独立真值附近的地图支持。 + +```bash +build/bin/field_localization_replay --dataset generated/lio_round_trip_clear/dataset \ + --mode localization --map generated/field.flmap --output generated/lio_inspect \ + --inspect-scan 108.7 +``` + +将 108.7 替换为数据集 scans.csv 中要检查的时间戳。回放继续使用估计位姿运行滤波器。真值只用于对照匹配和评估轨迹。 diff --git a/src/field_localization/include/field_localization/core/eskf.hpp b/src/field_localization/include/field_localization/core/eskf.hpp index 25ae79d..4b1924c 100644 --- a/src/field_localization/include/field_localization/core/eskf.hpp +++ b/src/field_localization/include/field_localization/core/eskf.hpp @@ -13,7 +13,7 @@ struct NoiseOptions { double accel_bias_walk{1e-4}; double gravity_walk{0.0}; // Quadrature/model error for unresolved between-sample dynamics, separate from sensor noise. - double integration_error_scale{2.0}; + double integration_error_scale{1.4}; double maximum_imu_gap{0.05}; }; struct FilterSnapshot { diff --git a/src/field_localization/include/field_localization/core/registration.hpp b/src/field_localization/include/field_localization/core/registration.hpp index 36d6ae6..e7f6ee5 100644 --- a/src/field_localization/include/field_localization/core/registration.hpp +++ b/src/field_localization/include/field_localization/core/registration.hpp @@ -37,7 +37,7 @@ struct RegistrationOptions { double neighborhood_radius{0.5}; double measurement_sigma{0.02}; // Shared map/association uncertainty does not shrink with the number of scan points. - double map_translation_sigma{0.02}; + double map_translation_sigma{0.03}; double map_rotation_sigma{0.002}; double huber_threshold{0.025}; double max_plane_distance{0.12}; @@ -56,6 +56,17 @@ struct Degeneracy { }; Degeneracy detect_degeneracy(const Matrix6 &normalized_information,const RegistrationOptions &options={}); enum class RegistrationFailure { NONE, NO_CORRESPONDENCES, DEGENERATE, INNOVATION, QUALITY }; +enum class RegistrationStage { NOT_RUN, INITIAL_MATCH, ITERATION, FINAL_FUSION, COMPLETE }; + +struct AssociationCounts { + std::size_t sampled{0}; + std::size_t candidate_planes{0}; + std::size_t outside_support{0}; + std::size_t plane_distance_rejected{0}; + std::size_t inliers{0}; +}; +const char *registration_stage_name(RegistrationStage stage); +const char *registration_failure_name(RegistrationFailure failure); struct RegistrationResult { bool success{false}; FilterSnapshot estimate; @@ -69,7 +80,12 @@ struct RegistrationResult { std::size_t inliers{0}; double inlier_ratio{0}; Degeneracy degeneracy; + RegistrationStage stage{RegistrationStage::NOT_RUN}; + AssociationCounts initial_associations; + AssociationCounts last_associations; }; +AssociationCounts inspect_scan_support(const PointCloud &cloud,const Pose3D &imu_from_sensor, + const VoxelMap &map,const Pose3D &map_from_imu,const RegistrationOptions &options={}); RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &imu_from_sensor, const VoxelMap &map,const FilterSnapshot &prediction,const NoiseOptions &noise={}, const RegistrationOptions &options={}); diff --git a/src/field_localization/src/core/dataset.cpp b/src/field_localization/src/core/dataset.cpp index dbecb3f..07f5a18 100644 --- a/src/field_localization/src/core/dataset.cpp +++ b/src/field_localization/src/core/dataset.cpp @@ -129,6 +129,11 @@ void write_filter_trace_header(std::ostream &out) { for(int i=0;i<6;++i) for(int j=0;j<6;++j) out<<",H"<()+extrinsic.translation; const Eigen::Vector3d world=state.pose.rotation*body+state.pose.translation; const auto plane=map.plane(world,o.neighborhood_radius); if (!plane.valid) continue; + ++out.counts.candidate_planes; const Eigen::Vector3d offset=world-plane.center; const double residual=plane.normal.dot(offset); - if((offset-plane.normal*residual).norm()>plane.support_radius+map.resolution()) continue; - if (std::abs(residual)>o.max_plane_distance) continue; + if ((offset-plane.normal*residual).norm()>plane.support_radius+map.resolution()) { + ++out.counts.outside_support; + continue; + } + if (std::abs(residual)>o.max_plane_distance) { + ++out.counts.plane_distance_rejected; + continue; + } Vector6 j; j.head<3>()=plane.normal; j.tail<3>()=(-state.pose.rotation.toRotationMatrix()*skew(body)).transpose()*plane.normal; const double weight=std::min(1.0,o.huber_threshold/std::max(1e-12,std::abs(residual)))/ (o.measurement_sigma*o.measurement_sigma); out.h.noalias()+=weight*j*j.transpose(); out.gradient.noalias()+=weight*j*residual; - out.squared_error+=residual*residual; ++out.inliers; + out.squared_error+=residual*residual; ++out.counts.inliers; } return out; } } +AssociationCounts inspect_scan_support(const PointCloud &cloud,const Pose3D &extrinsic, + const VoxelMap &map,const Pose3D &map_from_imu,const RegistrationOptions &options) { + MotionState state; state.pose=map_from_imu; + return linearize(voxel_downsample(cloud,options.scan_voxel),extrinsic,map,state,options).counts; +} + +const char *registration_stage_name(RegistrationStage stage) { + switch (stage) { + case RegistrationStage::NOT_RUN:return "NOT_RUN"; + case RegistrationStage::INITIAL_MATCH:return "INITIAL_MATCH"; + case RegistrationStage::ITERATION:return "ITERATION"; + case RegistrationStage::FINAL_FUSION:return "FINAL_FUSION"; + case RegistrationStage::COMPLETE:return "COMPLETE"; + } + return "UNKNOWN"; +} +const char *registration_failure_name(RegistrationFailure failure) { + switch (failure) { + case RegistrationFailure::NONE:return "NONE"; + case RegistrationFailure::NO_CORRESPONDENCES:return "NO_CORRESPONDENCES"; + case RegistrationFailure::DEGENERATE:return "DEGENERATE"; + case RegistrationFailure::INNOVATION:return "INNOVATION"; + case RegistrationFailure::QUALITY:return "QUALITY"; + } + return "UNKNOWN"; +} + RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,const VoxelMap &map, const FilterSnapshot &prediction,const NoiseOptions &noise,const RegistrationOptions &o) { RegistrationResult result; result.estimate=prediction; const auto scan=voxel_downsample(cloud,o.scan_voxel); + result.stage=RegistrationStage::INITIAL_MATCH; + result.initial_associations.sampled=scan.points.size(); + result.last_associations=result.initial_associations; if (scan.points.empty() || map.size()<5) return result; ErrorStateFilter filter(noise); filter.restore(prediction); auto record=[&](const Linearization &l) { - result.inliers=l.inliers; result.inlier_ratio=static_cast(l.inliers)/scan.points.size(); - result.residual_available=l.inliers>0; - result.rmse=l.inliers ? std::sqrt(l.squared_error/l.inliers) : 0; + result.last_associations=l.counts; + result.inliers=l.counts.inliers; result.inlier_ratio=static_cast(l.counts.inliers)/scan.points.size(); + result.residual_available=l.counts.inliers>0; + result.rmse=l.counts.inliers ? std::sqrt(l.squared_error/l.counts.inliers) : 0; result.information=l.h; result.gradient=l.gradient; - result.degeneracy=detect_degeneracy(l.h/std::max(1.0,static_cast(l.inliers)),o); + result.degeneracy=detect_degeneracy(l.h/std::max(1.0,static_cast(l.counts.inliers)),o); result.estimate=filter.snapshot(); }; Matrix6 model_covariance=Matrix6::Zero(); @@ -154,12 +193,14 @@ RegistrationResult scan_to_map(const PointCloud &cloud,const Pose3D &extrinsic,c const auto before=filter.snapshot().state; const auto l=linearize(scan,extrinsic,map,before,o); record(l); - if (l.inliers(l.inliers),o); + if (iteration==0) result.initial_associations=l.counts; + if (l.counts.inliers(0).norm()<1e-4 && step.segment<3>(6).norm()<1e-4) break; } + result.stage=RegistrationStage::FINAL_FUSION; const auto final=linearize(scan,extrinsic,map,filter.snapshot().state,o); record(final); if (result.inliers(0).norm()<0.5 && change.segment<3>(6).norm()<0.35; result.failure=result.success ? RegistrationFailure::NONE : RegistrationFailure::QUALITY; + if (result.success) result.stage=RegistrationStage::COMPLETE; return result; } } // namespace field_localization::core diff --git a/src/field_localization/src/ros/localization_node.cpp b/src/field_localization/src/ros/localization_node.cpp index c19d928..f991bb1 100644 --- a/src/field_localization/src/ros/localization_node.cpp +++ b/src/field_localization/src/ros/localization_node.cpp @@ -29,7 +29,7 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie core_options_.noise.integration_error_scale=declare_parameter("integration_error_scale",core_options_.noise.integration_error_scale); core_options_.noise.accel_bias_walk=declare_parameter("accel_bias_walk",1e-4); core_options_.map_resolution=declare_parameter("map_voxel_size",0.1); - core_options_.registration.map_translation_sigma=declare_parameter("map_translation_sigma",0.02); + core_options_.registration.map_translation_sigma=declare_parameter("map_translation_sigma",core_options_.registration.map_translation_sigma); core_options_.registration.map_rotation_sigma=declare_parameter("map_rotation_sigma",0.002); if(!std::isfinite(core_options_.registration.map_translation_sigma) || core_options_.registration.map_translation_sigma<0 || !std::isfinite(core_options_.registration.map_rotation_sigma) || core_options_.registration.map_rotation_sigma<0) @@ -202,6 +202,16 @@ void LocalizationNode::publish_health(bool heartbeat) { RCLCPP_ERROR(get_logger(),"localization no longer valid for navigation; TF halted: state_age=%.6f correction_age=%.6f position_3sigma=%.6f yaw_3sigma_deg=%.6f reason=%s", now().seconds()-s.state_timestamp,now().seconds()-s.last_correction_timestamp, health_.position_three_sigma(),health_.yaw_three_sigma()*180/std::numbers::pi,core::reason_name(s.reason)); + if (s.reason==core::FailureReason::REGISTRATION_FAILED) { + const auto ®=s.registration; + const auto &initial=reg.initial_associations; + const auto &last=reg.last_associations; + RCLCPP_ERROR(get_logger(),"registration stage=%s failure=%s scan=%.9f initial(inliers=%zu planes=%zu outside_support=%zu distance_rejected=%zu) last(inliers=%zu planes=%zu outside_support=%zu distance_rejected=%zu)", + core::registration_stage_name(reg.stage),core::registration_failure_name(reg.failure), + s.last_point_cloud_timestamp,initial.inliers,initial.candidate_planes,initial.outside_support, + initial.plane_distance_rejected,last.inliers,last.candidate_planes,last.outside_support, + last.plane_distance_rejected); + } } last_health_=valid; } diff --git a/src/field_localization/src/tools/record.cpp b/src/field_localization/src/tools/record.cpp index a40514d..54915b1 100644 --- a/src/field_localization/src/tools/record.cpp +++ b/src/field_localization/src/tools/record.cpp @@ -22,7 +22,7 @@ public: imu_.exceptions(std::ios::badbit|std::ios::failbit); scans_.exceptions(std::ios::badbit|std::ios::failbit); truth_.exceptions(std::ios::badbit|std::ios::failbit); imu_<(get_clock()); listener_=std::make_unique(*buffer_); - cloud_sub_=create_subscription(declare_parameter("point_cloud_topic","/scan/points_filtered"), + cloud_sub_=create_subscription(declare_parameter("point_cloud_topic","/scan/points_lio"), rclcpp::QoS(20).reliable(),[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) { if (!ready_ || done_) return; auto cloud=ros::convert_cloud(*msg); diff --git a/src/field_localization/src/tools/replay.cpp b/src/field_localization/src/tools/replay.cpp index d1f836f..49a6b63 100644 --- a/src/field_localization/src/tools/replay.cpp +++ b/src/field_localization/src/tools/replay.cpp @@ -1,4 +1,5 @@ #include "field_localization/core/dataset.hpp" +#include #include #include #include @@ -8,6 +9,13 @@ #include #include using namespace field_localization::core; +namespace { +void print_support(const char *label,const AssociationCounts &counts) { + std::cout<{}; + std::optional inspect_time; + std::optional inspect_map; + if (args.contains("--inspect-scan")) { + if (options.map_mode!=MapMode::LOCALIZATION || options.deskew.timing!=ScanTiming::INSTANTANEOUS || !have_truth) + throw std::runtime_error("--inspect-scan requires localization with instantaneous scans and truth.tum"); + inspect_time=std::stod(args.at("--inspect-scan")); + if (!std::isfinite(*inspect_time)) throw std::runtime_error("invalid scan timestamp"); + inspect_map=read_map(args.at("--map"),error); + if (!inspect_map) throw std::runtime_error(error); + } + bool inspected=false; std::ifstream input(dataset/"imu.csv"); if (!input) throw std::runtime_error("missing imu.csv"); std::vector imu; std::string line; std::getline(input,line); while (std::getline(input,line)) { @@ -52,6 +74,30 @@ int main(int argc,char **argv) { const auto begin=std::chrono::steady_clock::now(); core.process_point_cloud(cloud); const auto diagnostic=core.get_snapshot(); + if (inspect_time && std::abs(cloud.timestamp_sec-*inspect_time)<1e-8) { + const auto truth_base=trajectory_pose(truth,end); + const auto ®=diagnostic.status.registration; + if (!truth_base || reg.stage==RegistrationStage::NOT_RUN) + throw std::runtime_error("scan has no aligned truth or registration prediction"); + const auto map_from_imu=compose(*truth_base,options.base_from_imu); + const auto &prediction=diagnostic.status.registration_prediction.state; + const auto corrected=deskew(cloud,std::array{prediction},options.deskew); + if (!corrected) throw std::runtime_error("failed to prepare instantaneous scan"); + const auto truth_support=inspect_scan_support(*corrected,options.deskew.imu_from_sensor,*inspect_map, + map_from_imu,options.registration); + const auto error_xyz=prediction.pose.translation-map_from_imu.translation; + std::cout<(s.status.registration.failure)<<','< +#include #include #include -#include + using namespace field_localization::core; -int main(int argc,char **argv) { - CHECK(argc==2);if(argc!=2) return 1; - const std::filesystem::path directory=argv[1]; - auto options=read_dataset_config(directory/"config.txt"); - FilterSnapshot checkpoint;auto &s=checkpoint.state;std::ifstream input(directory/"checkpoint.txt"); - input>>s.timestamp_sec; - for(auto *v:{&s.pose.translation,&s.velocity}) for(int i=0;i<3;++i) input>>(*v)[i]; - for(int i=0;i<4;++i) input>>s.pose.rotation.coeffs()[i]; - for(auto *v:{&s.gyro_bias,&s.accel_bias,&s.gravity}) for(int i=0;i<3;++i) input>>(*v)[i]; - for(int i=0;i<18;++i) for(int j=0;j<18;++j) input>>checkpoint.covariance(i,j); + +namespace { +struct Report { + int scans{0}; + int full{0}; + int innovation_rejections{0}; + double maximum_rotation_error{0}; + double maximum_correction_gap{0}; + double maximum_position_error{0}; + double maximum_position_three_sigma{0}; +}; + +Report evaluate_recording(const std::filesystem::path &directory,const NoiseOptions &noise, + const std::filesystem::path &map_path,const RegistrationOptions ®istration={}) { + const auto options=read_dataset_config(directory/"config.txt"); + FilterSnapshot checkpoint; + auto &state=checkpoint.state; + std::ifstream input(directory/"checkpoint.txt"); + input>>state.timestamp_sec; + for (auto *v:{&state.pose.translation,&state.velocity}) + for (int i=0;i<3;++i) input>>(*v)[i]; + for (int i=0;i<4;++i) input>>state.pose.rotation.coeffs()[i]; + for (auto *v:{&state.gyro_bias,&state.accel_bias,&state.gravity}) + for (int i=0;i<3;++i) input>>(*v)[i]; + for (int i=0;i<18;++i) + for (int j=0;j<18;++j) input>>checkpoint.covariance(i,j); CHECK(static_cast(input)); - std::string error;const auto map=read_map(directory/"map.flmap",error);CHECK(map.has_value());if(!map) return 1; - ErrorStateFilter filter;filter.restore(checkpoint); - std::vector samples;std::ifstream imu(directory/"imu.csv");std::string line;std::getline(imu,line); - while(std::getline(imu,line)) { - std::replace(line.begin(),line.end(),',',' ');std::istringstream row(line);ImuData value; + + std::string error; + const auto map=read_map(map_path,error); + CHECK(map.has_value()); + if (!map) return {}; + + std::vector samples; + std::ifstream imu(directory/"imu.csv"); + std::string line; + std::getline(imu,line); + while (std::getline(imu,line)) { + std::replace(line.begin(),line.end(),',',' '); + std::istringstream row(line); + ImuData value; row>>value.timestamp_sec>>value.angular_velocity.x()>>value.angular_velocity.y()>>value.angular_velocity.z() >>value.linear_acceleration.x()>>value.linear_acceleration.y()>>value.linear_acceleration.z(); - CHECK(static_cast(row));samples.push_back(value); + CHECK(static_cast(row)); + samples.push_back(value); } const auto truth=read_trajectory(directory/"truth.tum"); - std::ifstream scans(directory/"scans.csv");std::getline(scans,line);int full=0;double maximum=0; - while(std::getline(scans,line)) { + std::ifstream scans(directory/"scans.csv"); + std::getline(scans,line); + ErrorStateFilter filter(noise); + filter.restore(checkpoint); + Report report; + TrackingHealth health; + const auto imu_from_base=inverse(options.base_from_imu); + double last_correction=-1; + auto observe_prior=[&] { + const auto &prior=filter.snapshot(); + LocalizationSnapshot snapshot{compose(prior.state.pose,imu_from_base),prior,{}}; + health.update(snapshot,options.base_from_imu,prior.state.timestamp_sec); + report.maximum_position_three_sigma=std::max(report.maximum_position_three_sigma, + health.position_three_sigma()); + }; + while (std::getline(scans,line)) { const auto cloud=read_cloud(directory/line.substr(line.find(',')+1)); - auto a=interpolate_imu(samples,filter.snapshot().state.timestamp_sec);CHECK(a.has_value());if(!a) return 1; - for(const auto &b:samples) if(b.timestamp_sec>a->timestamp_sec && b.timestamp_sectimestamp_sec || b.timestamp_sec>=cloud.timestamp_sec) continue; + CHECK(filter.propagate(*a,b)); + observe_prior(); + a=b; } - const auto finish=interpolate_imu(samples,cloud.timestamp_sec);CHECK(finish.has_value());if(!finish) return 1; - if(finish->timestamp_sec>a->timestamp_sec) CHECK(filter.propagate(*a,*finish)); - const auto result=scan_to_map(cloud,options.deskew.imu_from_sensor,*map,filter.snapshot()); - CHECK(result.success);if(result.success) {filter.restore(result.estimate);++full;} - const auto base=compose(filter.snapshot().state.pose,inverse(options.base_from_imu)); - const auto gt=trajectory_pose(truth,cloud.timestamp_sec);CHECK(gt.has_value());if(!gt) return 1; - maximum=std::max(maximum,(base.translation-gt->translation).norm()); - CHECK(log_so3(gt->rotation.conjugate()*base.rotation).norm()<0.02); + const auto finish=interpolate_imu(samples,cloud.timestamp_sec); + CHECK(finish.has_value()); + if (!finish) return report; + if (finish->timestamp_sec>a->timestamp_sec) CHECK(filter.propagate(*a,*finish)); + observe_prior(); + const auto result=scan_to_map(cloud,options.deskew.imu_from_sensor,*map,filter.snapshot(), + noise,registration); + ++report.scans; + if (result.failure==RegistrationFailure::INNOVATION) ++report.innovation_rejections; + if (last_correction>=0) + report.maximum_correction_gap=std::max(report.maximum_correction_gap, + cloud.timestamp_sec-last_correction); + if (result.success) { + last_correction=cloud.timestamp_sec; + filter.restore(result.estimate); + ++report.full; + } + const auto base=compose(filter.snapshot().state.pose,imu_from_base); + const auto gt=trajectory_pose(truth,cloud.timestamp_sec); + CHECK(gt.has_value()); + if (!gt) return report; + report.maximum_position_error=std::max(report.maximum_position_error, + (base.translation-gt->translation).norm()); + report.maximum_rotation_error=std::max(report.maximum_rotation_error, + log_so3(gt->rotation.conjugate()*base.rotation).norm()); const Eigen::SelfAdjointEigenSolver eigen(filter.snapshot().covariance); - CHECK(eigen.info()==Eigen::Success);CHECK(eigen.eigenvalues().minCoeff()>-1e-10); + CHECK(eigen.info()==Eigen::Success); + CHECK(eigen.eigenvalues().minCoeff()>-1e-10); } - std::printf("recorded transition: FULL=%d/5 maximum_position_error=%.9g m\n",full,maximum); - CHECK(full==5);CHECK(maximum<0.10); + std::printf("%s scale=%.2f map_sigma=%.3f FULL=%d/%d innovation_rejections=%d max_position_error=%.6f m max_prior_horizontal_3sigma=%.6f m max_rotation_error=%.6f rad max_correction_gap=%.6f s\n", + directory.filename().string().c_str(),noise.integration_error_scale,registration.map_translation_sigma, + report.full,report.scans,report.innovation_rejections,report.maximum_position_error, + report.maximum_position_three_sigma,report.maximum_rotation_error,report.maximum_correction_gap); + return report; +} +} // namespace + +int main(int argc,char **argv) { + CHECK(argc==4); + if (argc!=4) return 1; + const std::filesystem::path turn=argv[1],clear_return=argv[2],cylinder_return=argv[3]; + const auto turn_report=evaluate_recording(turn,{},turn/"map.flmap"); + CHECK(turn_report.scans==5 && turn_report.full==5); + CHECK(turn_report.maximum_position_error<0.10); + CHECK(turn_report.maximum_rotation_error<0.02); + + const auto return_map=clear_return/"map.flmap"; + const auto updated=evaluate_recording(clear_return,{},return_map); + NoiseOptions previous_noise; + previous_noise.integration_error_scale=2.0; + RegistrationOptions previous_map; + previous_map.map_translation_sigma=0.02; + const auto baseline=evaluate_recording(clear_return,previous_noise,return_map,previous_map); + CHECK(updated.scans==5 && updated.full==5); + CHECK(baseline.scans==5 && baseline.full==5); + CHECK(updated.maximum_position_error<0.10); + CHECK(baseline.maximum_position_three_sigma>HealthOptions{}.position_three_sigma); + CHECK(updated.maximum_position_three_sigmaprevious_cylinder.full); + CHECK(cylinder.maximum_correction_gap=HealthOptions{}.correction_timeout-1e-9); + CHECK(cylinder.maximum_position_error<0.10); + CHECK(previous_cylinder.innovation_rejections>=1); return sentry_nav_test::Summary("RecordedUpdate"); } diff --git a/src/field_localization/tests/test_registration.cpp b/src/field_localization/tests/test_registration.cpp index 5dc94fd..4d4381c 100644 --- a/src/field_localization/tests/test_registration.cpp +++ b/src/field_localization/tests/test_registration.cpp @@ -20,6 +20,20 @@ int main() { RegistrationOptions exact_map; exact_map.map_translation_sigma=0; exact_map.map_rotation_sigma=0; const auto result=scan_to_map(scan,{},map,filter.snapshot(),{},exact_map); CHECK(result.success); CHECK(result.degeneracy.dimensions==0); + CHECK(result.stage==RegistrationStage::COMPLETE); + const auto support=inspect_scan_support(scan,{},map,initial.pose,exact_map); + CHECK(support.candidate_planes<=support.sampled); + CHECK(support.candidate_planes==support.outside_support+support.plane_distance_rejected+support.inliers); + CHECK(result.initial_associations.inliers==support.inliers); + CHECK(result.last_associations.inliers==result.inliers); + auto far=initial; + far.pose.translation.x()+=20; + filter.initialize(far); + const auto unsupported=scan_to_map(scan,{},map,filter.snapshot(),{},exact_map); + CHECK(!unsupported.success); + CHECK(unsupported.stage==RegistrationStage::INITIAL_MATCH); + CHECK(unsupported.failure==RegistrationFailure::NO_CORRESPONDENCES); + CHECK(unsupported.initial_associations.sampled>0 && unsupported.initial_associations.candidate_planes==0); const double position_error=(result.estimate.state.pose.translation-truth.translation).norm(); const double rotation_error=log_so3(truth.rotation.conjugate()*result.estimate.state.pose.rotation).norm(); std::printf("3-plane registration: translation %.9g m, rotation %.9g rad, rmse %.9g, inliers %zu\n", @@ -51,6 +65,7 @@ int main() { const auto rejected=scan_to_map(shifted,{},floor,confident,{},strict); CHECK(!rejected.success); CHECK(rejected.failure==RegistrationFailure::INNOVATION); + CHECK(rejected.stage==RegistrationStage::FINAL_FUSION); CHECK(rejected.inliers>100); CHECK(rejected.measurement_rank==3); // Rotate the whole plane; verify its null space rather than an axis label. diff --git a/src/field_localization/xmake.lua b/src/field_localization/xmake.lua index 3ed2ac5..f1701ac 100644 --- a/src/field_localization/xmake.lua +++ b/src/field_localization/xmake.lua @@ -77,10 +77,22 @@ local function ros_common() end end + if not ROS then + local distro = os.getenv("ROS_DISTRO") + if distro and distro ~= "" then + local candidate = "/opt/ros/" .. distro + if os.isdir(candidate .. "/include") + and os.isdir(candidate .. "/lib") then + + ROS = candidate + end + end + end + if not ROS then raise( "ROS installation not found. " - .. "Source ROS setup or set ROS_PREFIX." + .. "Source ROS setup or set ROS_PREFIX / ROS_DISTRO." ) end end @@ -88,7 +100,7 @@ local function ros_common() -- Resolve ROS include directories. local script = path.join( target:scriptdir(), - "../../tools/resolve_ros_includes.py" + "../../tools/_internal/resolve_ros_includes.py" ) if not os.isfile(script) then @@ -416,6 +428,11 @@ target("test_recorded_update") add_files("tests/test_recorded_update.cpp") add_deps("field_localization_core") on_load(function(target) - target:set("runargs", {path.join(os.projectdir(), "src/field_localization/tests/data/turn_contact")}) + local fixtures = path.join(os.projectdir(), "src/field_localization/tests/data") + target:set("runargs", { + path.join(fixtures, "turn_contact"), + path.join(fixtures, "return_contact"), + path.join(fixtures, "return_cylinder"), + }) end) add_tests("default", {group = "unit"}) diff --git a/src/sentry_nav/src/nav_client.cpp b/src/sentry_nav/src/nav_client.cpp index 6470a95..fa3123b 100644 --- a/src/sentry_nav/src/nav_client.cpp +++ b/src/sentry_nav/src/nav_client.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -37,6 +38,7 @@ #include #include #include +#include #include #include @@ -56,6 +58,7 @@ constexpr int kOccupiedThreshold = 65; constexpr double kClearanceSearch = 2.0; // 圆周率(避开 M_PI —— 严格 C++ 里它不是标准宏)。 constexpr double kPi = 3.14159265358979323846; +constexpr auto kLocalizationFreshness = 300ms; struct Args { @@ -166,6 +169,14 @@ int main(int argc, char * argv[]) tf2_ros::Buffer tf_buffer(node->get_clock()); tf2_ros::TransformListener tf_listener(tf_buffer); + std::optional last_health; + bool localization_valid = false; + auto health_sub = node->create_subscription( + "/field_localization/navigation_valid", rclcpp::QoS(1), + [&](const std_msgs::msg::Bool & msg) { + last_health = std::chrono::steady_clock::now(); + localization_valid = msg.data; + }); // /map 是 TRANSIENT_LOCAL 发布的,用默认 QoS 会一条都收不到。 auto map_qos = rclcpp::QoS(rclcpp::KeepLast(1)) @@ -197,7 +208,7 @@ int main(int argc, char * argv[]) map_executor.remove_node(node); if (!holder.got) { - std::printf("⚠️ 15 秒内没收到 /map,跳过预检直接发目标\n"); + std::printf("⚠️ 15 秒内没收到 /map,跳过静态地图预检\n"); } else { const auto & info = holder.last.info; const auto & data = holder.last.data; @@ -254,6 +265,54 @@ int main(int argc, char * argv[]) } std::printf("✅ 动作服务器可用\n"); + // Give discovery and the TF listener a bounded window before sending a goal. + // AMCL has no LIO heartbeat and uses the same fresh TF check. + auto localization_error = [&]() -> const char * { + if (last_health || health_sub->get_publisher_count() > 0) { + if (!last_health || std::chrono::steady_clock::now() - *last_health > kLocalizationFreshness) { + return "LIO 有效性心跳缺失或过期"; + } + if (!localization_valid) { + return "LIO 有效性心跳为 false"; + } + } + const auto now = node->now(); + if (now.nanoseconds() <= 0) { + return "未收到仿真时钟"; + } + try { + const auto transform = tf_buffer.lookupTransform("map", "base_link", rclcpp::Time(0)); + const rclcpp::Time stamp(transform.header.stamp, now.get_clock_type()); + if (stamp.nanoseconds() <= 0 || + (now - stamp).nanoseconds() > + std::chrono::duration_cast(kLocalizationFreshness).count()) + { + return "map → base_link TF 已过期"; + } + } catch (const tf2::TransformException &) { + return "map → base_link TF 不连通"; + } + return nullptr; + }; + map_executor.add_node(node); + const auto localization_deadline = std::chrono::steady_clock::now() + 5s; + const char * reason = nullptr; + do { + map_executor.spin_some(); + reason = localization_error(); + if (reason == nullptr) { + break; + } + std::this_thread::sleep_for(20ms); + } while (rclcpp::ok() && std::chrono::steady_clock::now() < localization_deadline); + map_executor.remove_node(node); + if (reason != nullptr) { + std::printf("❌ 定位不可用:%s。未发送导航目标。\n", reason); + rclcpp::shutdown(); + return 1; + } + + NavigateToPose::Goal goal; goal.pose.header.frame_id = "map"; goal.pose.header.stamp = node->now(); @@ -288,7 +347,7 @@ int main(int argc, char * argv[]) if (rclcpp::spin_until_future_complete(node, goal_future, 15s) != rclcpp::FutureReturnCode::SUCCESS) { - std::printf("❌ 目标被拒绝(耗时 %.1f s)\n", 0.0); + std::printf("❌ 等待 Nav2 确认目标超时或中断\n"); rclcpp::shutdown(); return 1; } @@ -313,19 +372,34 @@ int main(int argc, char * argv[]) const double elapsed = std::chrono::duration(std::chrono::steady_clock::now() - t_goal).count(); + int exit_code = 1; if (result_future.valid() && result_future.wait_for(0s) == std::future_status::ready) { - const auto code = result_future.get().code; + const auto result = result_future.get(); + const auto code = result.code; const char * name = "❌ 未知状态"; if (code == rclcpp_action::ResultCode::SUCCEEDED) { name = "✅ SUCCEEDED"; + exit_code = 0; } 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); + if (result.result) { + std::printf("Nav2 error_code=%u error_msg=%s\n", + static_cast(result.result->error_code), result.result->error_msg.c_str()); + } } else { - std::printf("超时未完成(180 s,已等待 %.0f s)\n", elapsed); + std::printf("超时或中断(上限 180 s,已等待 %.0f s)\n", elapsed); + if (rclcpp::ok()) { + try { + auto canceled = client->async_cancel_goal(handle); + (void)rclcpp::spin_until_future_complete(node, canceled, 1s); + } catch (const rclcpp_action::exceptions::UnknownGoalHandleError &) { + // The server can finish the goal while the timeout is being handled. + } + } } try { @@ -340,5 +414,5 @@ int main(int argc, char * argv[]) } rclcpp::shutdown(); - return 0; + return exit_code; } diff --git a/src/sentry_nav/src/self_filter.cpp b/src/sentry_nav/src/self_filter.cpp index 88383c9..13ed9c3 100644 --- a/src/sentry_nav/src/self_filter.cpp +++ b/src/sentry_nav/src/self_filter.cpp @@ -39,6 +39,8 @@ #include #include #include +#include +#include #include #include @@ -87,6 +89,19 @@ public: declare_parameter("max_range", params.max_range)); core_ = std::make_unique(params); + const auto lio_topic = declare_parameter("lio_output_topic", "/scan/points_lio"); + if (!lio_topic.empty()) { + if (lio_topic == output_topic_) { + throw std::invalid_argument("lio_output_topic must differ from the obstacle cloud topic"); + } + auto lio_params = params; + lio_params.keep_min_z = static_cast(declare_parameter("lio_keep_min_z", -0.25)); + // Keep the floor outside the body footprint without admitting underbody returns. + lio_params.box_min_z = std::min(lio_params.box_min_z, lio_params.keep_min_z); + lio_core_ = std::make_unique(lio_params); + lio_pub_ = create_publisher(lio_topic, rclcpp::QoS(5).reliable()); + RCLCPP_INFO(get_logger(), "LIO cloud: %s (keep_min_z=%.2f)", lio_topic.c_str(), lio_params.keep_min_z); + } tf_buffer_ = std::make_unique(get_clock()); tf_listener_ = std::make_shared(*tf_buffer_); @@ -149,10 +164,18 @@ private: filtered.reserve(raw.size()); // 只做遍历和搬运,判定逻辑全在 core_ 里(可单测)。 + const bool publish_lio = lio_pub_ && lio_pub_->get_subscription_count() > 0; + pcl::PointCloud lio_cloud; + if (publish_lio) { + lio_cloud.reserve(raw.size()); + } for (const auto & pt : raw) { if (core_->Keep(pt.x, pt.y, pt.z)) { filtered.push_back(pt); } + if (publish_lio && lio_core_->Keep(pt.x, pt.y, pt.z)) { + lio_cloud.push_back(pt); + } } // 统计保留率,调参时有用(DEBUG 级别,默认不刷屏) @@ -166,16 +189,27 @@ private: static_cast(total_out_), static_cast(total_in_)); - sensor_msgs::msg::PointCloud2 out; - pcl::toROSMsg(filtered, out); - out.header.stamp = msg->header.stamp; - out.header.frame_id = target_frame_; - pub_->publish(out); + PublishCloud(filtered, msg->header.stamp, *pub_); + if (publish_lio) { + PublishCloud(lio_cloud, msg->header.stamp, *lio_pub_); + } // 同一份过滤结果再投影成 2D 激光:不新增订阅/进程,数据一致。 PublishScan(filtered, msg->header.stamp); } + void PublishCloud( + const pcl::PointCloud & cloud, + const builtin_interfaces::msg::Time & stamp, + rclcpp::Publisher & publisher) + { + sensor_msgs::msg::PointCloud2 out; + pcl::toROSMsg(cloud, out); + out.header.stamp = stamp; + out.header.frame_id = target_frame_; + publisher.publish(out); + } + // 把过滤后的点云(已在 base_link 系)投影成 2D 激光: // 每个方位格取该格内最小水平距离,z 只取车体碰撞带 [scan_height_min, scan_height_max]。 // 这样投影结果与地图的「体积投影」在同一高度带,避免 AMCL 因高度失配把粒子整团迁走。 @@ -223,6 +257,7 @@ private: std::string scan_topic_; std::unique_ptr core_; + std::unique_ptr lio_core_; std::uint64_t total_in_{0}; std::uint64_t total_out_{0}; @@ -236,6 +271,7 @@ private: std::unique_ptr tf_buffer_; std::shared_ptr tf_listener_; rclcpp::Publisher::SharedPtr pub_; + rclcpp::Publisher::SharedPtr lio_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 5f6f9e4..626a5b5 100644 --- a/src/sentry_nav/xmake.lua +++ b/src/sentry_nav/xmake.lua @@ -15,6 +15,7 @@ local ros_direct_packages = { "nav_msgs", "geometry_msgs", "sensor_msgs", + "std_msgs", "tf2_ros", "tf2_sensor_msgs", "pcl_conversions", @@ -128,7 +129,7 @@ local function ros_common() local script = path.join( target:scriptdir(), - "../../tools/resolve_ros_includes.py" + "../../tools/_internal/resolve_ros_includes.py" ) if not os.isfile(script) then diff --git a/src/sentry_sim/launch/README.md b/src/sentry_sim/launch/README.md index 4067fc3..c230268 100644 --- a/src/sentry_sim/launch/README.md +++ b/src/sentry_sim/launch/README.md @@ -33,14 +33,14 @@ ros2 launch src/sentry_sim/launch/sentry_arena.launch.py --show-args # 看 | `map` | 迁移包里的 `rmul_2027.yaml` | Nav2 用的栅格图 | | `field_root` | 仓库内 `field/RMUL2027_map_transfer_20261016_STEP_R1` | 迁移包目录(找不到才退回 `~/Gazebo_projects/` 下的旧路径) | -环境变量(`GZ_PARTITION` / `ROS_DOMAIN_ID` / `SENTRY_FIELD_ROOT` / `SENTRY_MAP_YAML`) -会被继承,行为和 `sentry_up.sh` 一致。详见 `../scripts/README.md`。 +`map:=` 和 `field_root:=` 优先于对应的环境变量。未提供地图时,从实际选定的场地目录探测。 +两个启动入口使用同一套环境探测规则,`--show-args` 可独立查看参数。详见[环境变量](../../../docs/操作手册.md#6-环境变量)。 ## 和 `scripts/sentry_up.sh` 的取舍 | | `sentry_up.sh` | 本 launch 文件 | |---|---|---| -| 依赖 | 只要 bash | 要 `ros2 launch`(launch / launch_ros) | +| 依赖 | Bash、Python 3 和 ROS | `ros2 launch`(launch / launch_ros) | | 参数可见性 | 看脚本 | `--show-args` 全列出来 | | 进程管理 | `trap` 收尾 | launch 统一收尾、能看进程树 | | 被别的 launch include | ❌ | ✅ | diff --git a/src/sentry_sim/launch/sentry_arena.launch.py b/src/sentry_sim/launch/sentry_arena.launch.py index 9207c50..c36322b 100644 --- a/src/sentry_sim/launch/sentry_arena.launch.py +++ b/src/sentry_sim/launch/sentry_arena.launch.py @@ -53,12 +53,14 @@ from launch.actions import ( LogInfo, OpaqueFunction, SetEnvironmentVariable, + SetLaunchConfiguration, ) from launch.conditions import IfCondition from launch.event_handlers import OnProcessExit from launch.events import Shutdown -from launch.substitutions import (LaunchConfiguration, - PathJoinSubstitution, PythonExpression) +from launch.substitutions import ( + EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, PathJoinSubstitution, PythonExpression, +) from launch_ros.actions import Node from launch_ros.parameter_descriptions import ParameterValue @@ -68,29 +70,61 @@ from launch_ros.parameter_descriptions import ParameterValue PKG_SHARE = Path(__file__).resolve().parents[1] # src/sentry_sim WS = Path(__file__).resolve().parents[3] # 仓库根 SCRIPTS = PKG_SHARE / 'scripts' +TOOLS_DIR = WS / 'tools' +INTERNAL_TOOLS = TOOLS_DIR / '_internal' # 可移植探测:xmake 产物目录 / 场地包 / 地图 / gz 版本,一个都不写死。 # 规则与 `scripts/env_common.sh` 完全一致(同样支持 SENTRY_BIN_DIR、 # SENTRY_FIELD_ROOT、SENTRY_MAP_YAML、GZ_BIN、GZ_FORCE_VERSION 覆盖)。 -# `tools/` 不是 Python 包(本工程不用 ament),所以直接把目录塞进 sys.path。 -if str(WS / 'tools') not in sys.path: - sys.path.insert(0, str(WS / 'tools')) +# 从仓库源码加载工具模块。 +if str(TOOLS_DIR) not in sys.path: + sys.path.insert(0, str(TOOLS_DIR)) import project_env # noqa: E402 (必须在 sys.path 调整之后导入) -from dds_environment import defaults as dds_defaults # noqa: E402 +from _internal.dds_environment import defaults as dds_defaults # noqa: E402 -BIN_DIR = project_env.find_bin_dir(WS) -GZ_VERSION_ARGS = project_env.gz_version_args() +BIN_DIR = LaunchConfiguration('_sentry_bin_dir') +GZ_MAJOR_VERSION = LaunchConfiguration('_sentry_gz_major_version') -_FIELD_ROOT = project_env.find_field_root(WS) -if _FIELD_ROOT is None: - raise RuntimeError( - '找不到场地迁移包。设 SENTRY_FIELD_ROOT=<含 src/guodong_sentry_sim 的目录>。') -DEFAULT_FIELD_ROOT = str(_FIELD_ROOT) -_MAP_YAML = project_env.find_map_yaml(_FIELD_ROOT) -if _MAP_YAML is None: - raise RuntimeError(f'{_FIELD_ROOT} 下找不到任何栅格图 yaml。设 SENTRY_MAP_YAML=<路径>。') -DEFAULT_MAP_YAML = str(_MAP_YAML) +def _resolve_environment(context): + field_root = project_env.find_field_root( + WS, explicit=LaunchConfiguration('field_root').perform(context)) + map_yaml = project_env.find_map_yaml( + field_root, explicit=LaunchConfiguration('map').perform(context)) + bin_dir = project_env.find_bin_dir(WS) + nodes = ['odom_tf', 'cmd_vel_relay', 'self_filter'] + if LaunchConfiguration('localization').perform(context) == 'lio': + nodes.append('field_localization_node') + for name in nodes: + project_env.require_executable(bin_dir / name, name) + gz = project_env.find_gz_bin() + versions = project_env.gz_version_args(gz) + return [ + SetLaunchConfiguration('field_root', str(field_root)), + SetLaunchConfiguration('map', str(map_yaml)), + SetLaunchConfiguration('_sentry_bin_dir', str(bin_dir)), + SetEnvironmentVariable('GZ_BIN', str(gz)), + SetLaunchConfiguration('_sentry_gz_major_version', versions[1] if versions else ''), + ] + + +def _start_gazebo(context): + headless = LaunchConfiguration('headless').perform(context).lower() in ('true', '1') + # Keep -r in both modes so that the world starts unpaused. + args = ['-s', '-r'] if headless else ['-r'] + if major := GZ_MAJOR_VERSION.perform(context): + args.extend(['--force-version', major]) + world_path = PathJoinSubstitution([str(PKG_SHARE / 'worlds'), LaunchConfiguration('world')]) + return [ExecuteProcess( + cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', *args, world_path], + name='gazebo', output='screen', + )] + + +def _on_bridge_exit(event, context): + if event.returncode != 0 and not context.is_shutdown: + raise RuntimeError('Gazebo 桥启动或运行失败,请检查 /clock 与 ros_gz_bridge 日志。') + return [] def _robot_description(): @@ -126,12 +160,15 @@ def _validate_lio(context): path = Path(LaunchConfiguration('lio_map').perform(context)) if mode == 'localization' and not path.is_file(): raise RuntimeError(f'Missing LIO map: {path}; first select lio_mode:=mapping') + if mode == 'mapping': + export = Path(LaunchConfiguration('lio_export_map').perform(context)) + export.parent.mkdir(parents=True, exist_ok=True) return [] def _preflight_nav2(context): if LaunchConfiguration('nav2').perform(context).lower() in ('true', '1'): - subprocess.run(['python3', str(WS / 'tools' / 'nav2_startup.py'), '--preflight'], + subprocess.run(['python3', str(INTERNAL_TOOLS / 'nav2_startup.py'), '--preflight'], env=dict(context.environment), check=True) return [] @@ -141,7 +178,7 @@ def _start_velocity_relay(context): localization = LaunchConfiguration('localization').perform(context) input_topic = '/cmd_vel' if navigation else context.environment.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel') return [ExecuteProcess( - cmd=[str(BIN_DIR / 'cmd_vel_relay'), + cmd=[PathJoinSubstitution([BIN_DIR, 'cmd_vel_relay']), '--ros-args', '-p', 'use_sim_time:=true', '-p', f'navigation_mode:={str(navigation).lower()}', '-p', f'require_localization_health:={str(localization == "lio").lower()}', @@ -154,31 +191,37 @@ def generate_launch_description(): headless = LaunchConfiguration('headless') nav2 = LaunchConfiguration('nav2') rviz = LaunchConfiguration('rviz') - world = LaunchConfiguration('world') map_yaml = LaunchConfiguration('map') localization = LaunchConfiguration('localization') lio_mode = LaunchConfiguration('lio_mode') lio_map = LaunchConfiguration('lio_map') lio_export = LaunchConfiguration('lio_export_map') + lio_default_map = IfElseSubstitution( + EqualsSubstitution(lio_mode, 'mapping'), + if_value=str(WS / 'generated' / 'field_mapping.flmap'), + else_value=str(PKG_SHARE / 'maps' / 'field_full.flmap'), + ) # 布尔参数统一用 PythonExpression 判,避免 launch 把 "false" 当真值 - is_headless = PythonExpression(["'", headless, "'.lower() in ('true', '1')"]) - is_gui = PythonExpression(["'", headless, "'.lower() not in ('true', '1')"]) nav2_on = PythonExpression(["'", nav2, "'.lower() in ('true', '1')"]) rviz_on = PythonExpression([ "'", rviz, "'.lower() in ('true', '1') and '", headless, "'.lower() not in ('true', '1')"]) robot_description = _robot_description() + bridge = ExecuteProcess( + cmd=[str(SCRIPTS / 'bridge_after_gz.sh')], + name='ros_gz_bridge', output='screen', + ) navigation_ready = ExecuteProcess( - cmd=['python3', str(WS / 'tools' / 'wait_navigation_ready.py')], + cmd=['python3', str(INTERNAL_TOOLS / 'wait_navigation_ready.py')], name='wait_navigation_ready', output='screen', condition=IfCondition(nav2_on), ) # Use the same process boundary and options as the shell entry point. # The nested include path reproduced a Wait action discovery timeout on this setup. navigation = ExecuteProcess( - cmd=['python3', str(WS / 'tools' / 'run_nav2.py'), + cmd=['python3', str(INTERNAL_TOOLS / 'run_nav2.py'), '--timeout', os.environ.get('SENTRY_NAV2_TIMEOUT', '120'), '--', ['map:=', map_yaml], 'use_sim_time:=true', 'autostart:=False', ['params_file:=', str(PKG_SHARE / 'config' / 'nav2_params.yaml')], @@ -192,8 +235,13 @@ def generate_launch_description(): actions = [ DeclareLaunchArgument('localization', default_value='lio', choices=['lio', 'amcl']), DeclareLaunchArgument('lio_mode', default_value='localization', choices=['mapping', 'localization']), - DeclareLaunchArgument('lio_map', default_value=str(WS / 'generated' / 'field.flmap')), - DeclareLaunchArgument('lio_export_map', default_value=lio_map), + DeclareLaunchArgument( + 'lio_map', default_value=os.environ.get('LIO_MAP') or lio_default_map, + description='Full-field localization map or generated/field_mapping.flmap in mapping mode', + ), + DeclareLaunchArgument('lio_export_map', default_value=os.environ.get('LIO_EXPORT_MAP') or lio_map), + DeclareLaunchArgument('lio_point_cloud_topic', + default_value=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio'), DeclareLaunchArgument('lio_initial_x', default_value='-5.0'), DeclareLaunchArgument('lio_initial_y', default_value='3.0'), DeclareLaunchArgument('lio_initial_z', default_value='0.0'), @@ -211,18 +259,19 @@ def generate_launch_description(): 'world', default_value='sentry_arena.sdf', description='worlds/ 下的世界文件名'), DeclareLaunchArgument( - 'map', default_value=DEFAULT_MAP_YAML, - description='Nav2 用的栅格图 yaml'), + 'map', default_value='', + description='Nav2 栅格图 YAML,留空则从环境或场地包探测'), DeclareLaunchArgument( - 'field_root', default_value=DEFAULT_FIELD_ROOT, - description='迁移包(guodong_sentry_sim)所在目录'), + 'field_root', default_value='', + description='场地包目录,留空则从环境或仓库探测'), + OpaqueFunction(function=_resolve_environment), # ---------------- 环境变量 ---------------- SetEnvironmentVariable('FASTDDS_BUILTIN_TRANSPORTS', dds_defaults(os.environ)['FASTDDS_BUILTIN_TRANSPORTS']), SetEnvironmentVariable('GZ_SIM_RESOURCE_PATH', _gz_resource_path()), SetEnvironmentVariable( - 'GZ_PARTITION', os.environ.get('GZ_PARTITION', 'sentry')), + 'GZ_PARTITION', os.environ.get('GZ_PARTITION') or 'sentry'), SetEnvironmentVariable( 'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']), # URDF 的网格路径靠它解析;tools/check_stack.py 也读它 @@ -230,41 +279,14 @@ def generate_launch_description(): OpaqueFunction(function=_preflight_nav2), # ---------------- 1. Gazebo ---------------- - # 用 run_gz.sh 包一层:它会清掉 LD_LIBRARY_PATH, - # 否则 source 过 ROS 之后连系统版 gz 也会加载 vendor 库(缺 cpu-lidar 插件) - # ⚠️ cmd 列表里的每个元素是**独立 argv**,不会自动拼接。 - # world 是 LaunchConfiguration,所以必须用 PathJoinSubstitution - # 合成成一个参数,否则 gz 会收到三个散参数 - # (报 "The following arguments were not expected: xxx.sdf /")。 - ExecuteProcess( - cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-r', - *GZ_VERSION_ARGS, - PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])], - name='gazebo', - output='screen', - condition=IfCondition(is_gui), - ), - # ⚠️ headless 也必须带 -r(启动即运行)。 - # 少了 -r 的话 gazebo 以**暂停**状态启动:物理引擎不步进 → - # MecanumDrive 不发 /odom、传感器不出数据,但 /clock 照常发布, - # 表面上一切正常,实际整条数据链是死的。 - ExecuteProcess( - cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-s', '-r', - *GZ_VERSION_ARGS, - PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])], - name='gazebo', - output='screen', - condition=IfCondition(is_headless), - ), + OpaqueFunction(function=_start_gazebo), # ---------------- 2. ros_gz 桥 ---------------- - # bridge_after_gz.sh 自己轮询 /clock 再起桥: - # gz-transport 的发现不回补,桥先于话题存在就订阅会一直收不到数据 - ExecuteProcess( - cmd=[str(SCRIPTS / 'bridge_after_gz.sh')], - name='ros_gz_bridge', - output='screen', - ), + # 等到 /clock 出现再加载桥,否则 gz-transport 可能漏掉话题。 + RegisterEventHandler(OnProcessExit( + target_action=bridge, on_exit=_on_bridge_exit, + )), + bridge, # ---------------- 3. TF 树 ---------------- Node( @@ -286,7 +308,7 @@ def generate_launch_description(): # 如果写成嵌套列表 ['-p', 'odom_scale:=', v],会被拼成 "-podom_scale:=1.15"(没空格), # rclpy 的参数解析会直接报错。 ExecuteProcess( - cmd=[str(BIN_DIR / 'odom_tf'), '--ros-args', + cmd=[PathJoinSubstitution([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', @@ -300,15 +322,16 @@ def generate_launch_description(): # ---------------- 6. 点云自滤 ---------------- # 本工程没有 ament 注册,不能 ros2 run,直接跑 xmake 产物 ExecuteProcess( - cmd=[str(BIN_DIR / 'self_filter'), + cmd=[PathJoinSubstitution([BIN_DIR, 'self_filter']), '--ros-args', '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true'], name='self_filter', output='screen', ), ExecuteProcess( - cmd=[str(BIN_DIR / 'field_localization_node'), '--ros-args', - '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true', '-p', 'point_cloud_topic:=/scan/points_filtered', + cmd=[PathJoinSubstitution([BIN_DIR, 'field_localization_node']), '--ros-args', + '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true', + '-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')], '-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map], '-p', ['export_map_path:=', lio_export], '-p', 'publish_map_to_odom:=true', '-p', "diagnostics_path:='" + os.environ.get('LIO_TRACE_PATH', '') + "'", diff --git a/src/sentry_sim/maps/field_full.flmap b/src/sentry_sim/maps/field_full.flmap new file mode 100644 index 0000000..22d016f Binary files /dev/null and b/src/sentry_sim/maps/field_full.flmap differ diff --git a/src/sentry_sim/scripts/README.md b/src/sentry_sim/scripts/README.md index d096b39..4c3de1c 100644 --- a/src/sentry_sim/scripts/README.md +++ b/src/sentry_sim/scripts/README.md @@ -37,20 +37,10 @@ | `SENTRY_FIELD_ROOT` | 仓库内 `field/RMUL2027_map_transfer_20261016_STEP_R1` | 场地包位置。**优先用仓库自带的**,找不到才退回 `~/Gazebo_projects/` 下的旧路径 | | `SENTRY_MAP_YAML` | 上面路径下的 `maps/rmul_2027/rmul_2027.yaml` | 想换地图时直接指这个 | | `SENTRY_SIM_SHARE` | 仓库内 `src/sentry_sim` | 数据包位置。设了就以它为准;同时会导出给 `xacro`,URDF 里的网格路径靠它解析 | -| `NAV_BIN_DIR` | `<仓库根>/build/bin` | xmake 产物目录。想用别处的二进制时覆盖它 | +| `SENTRY_BIN_DIR` | `<仓库根>/build/bin` | xmake 产物目录,旧变量 `NAV_BIN_DIR` 仍可用 | +| `BRIDGE_WAIT_TIMEOUT` | `120` | 等待 Gazebo `/clock` 的秒数,两个入口共用 | -## `FIELD_ROOT` 的解析逻辑(容易踩的一点) - -```bash -FIELD_DEFAULT="$HOME/Gazebo_projects/RMUL2027_map_transfer_20261016_STEP_R1" -if [ -d "$WS/field/RMUL2027_map_transfer_20261016_STEP_R1" ]; then - FIELD_DEFAULT="$WS/field/RMUL2027_map_transfer_20261016_STEP_R1" -fi -FIELD_ROOT="${SENTRY_FIELD_ROOT:-$FIELD_DEFAULT}" -``` - -> **不能写成 `[ -d ... ] && FIELD_DEFAULT=...`** —— 脚本第 10 行有 `set -e`, -> 目录不存在时那种写法会让整个脚本静默退出(踩过)。 +场地、地图、构建目录和 Gazebo 的选择顺序见[操作手册](../../../docs/操作手册.md#6-环境变量)。 ## 退出时 Gazebo 可能残留 diff --git a/src/sentry_sim/scripts/bridge_after_gz.sh b/src/sentry_sim/scripts/bridge_after_gz.sh index b171512..340140e 100755 --- a/src/sentry_sim/scripts/bridge_after_gz.sh +++ b/src/sentry_sim/scripts/bridge_after_gz.sh @@ -5,18 +5,14 @@ # (gz-transport 的发现不回补)。先轮询 /clock,再 exec 桥。 set -e -TIMEOUT_SECONDS="${BRIDGE_WAIT_TIMEOUT:-180}" -for _ in $(seq 1 "$((TIMEOUT_SECONDS / 2))"); do - if gz topic -l 2>/dev/null | grep -qx '/clock'; then - echo "[bridge_after_gz] Gazebo 已就绪,启动桥" - break - fi - sleep 2 -done +SCRIPTS_DIR="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +# shellcheck source=./env_common.sh +. "${SCRIPTS_DIR}/env_common.sh" +GZ=$(env_gz_bin) +env_wait_gz_clock "$GZ" +echo "[bridge_after_gz] Gazebo /clock 已就绪,启动桥" echo "[bridge_after_gz] GZ_PARTITION=${GZ_PARTITION:-} ROS_DOMAIN_ID=${ROS_DOMAIN_ID:-} RMW=${RMW_IMPLEMENTATION:-}" -echo "[bridge_after_gz] LD_LIBRARY_PATH=${LD_LIBRARY_PATH:0:80}" -echo "[bridge_after_gz] gz 话题数=$(gz topic -l 2>/dev/null | wc -l)" exec ros2 run ros_gz_bridge parameter_bridge \ '/clock@rosgraph_msgs/msg/Clock[gz.msgs.Clock' \ '/model/sentry/cmd_vel@geometry_msgs/msg/Twist]gz.msgs.Twist' \ diff --git a/src/sentry_sim/scripts/env_common.sh b/src/sentry_sim/scripts/env_common.sh index 14ce42e..8c7ddbd 100644 --- a/src/sentry_sim/scripts/env_common.sh +++ b/src/sentry_sim/scripts/env_common.sh @@ -1,263 +1,67 @@ #!/usr/bin/env bash -# 可移植的环境探测 —— 所有启动脚本共享这一份,别再各写一套。 -# -# 设计原则: -# ① **一切都能被环境变量覆盖**:探测只是给个合理默认值,不是唯一真相。 -# ② **探测失败要吵**:宁可启动时明确报错,也不要带着错路径跑到一半。 -# ③ **不写死发行版/版本/平台三元组**:换台机器、换个 ROS 版本、换个 Gazebo 大版本 -# 都不该需要改脚本。 -# -# 覆盖用的环境变量: -# ROS_SETUP 直接指定要 source 的 setup.bash 全路径 -# ROS_DISTRO ROS 发行版名(配合 /opt/ros/<名>/setup.bash) -# SENTRY_BIN_DIR xmake 产物目录(默认识别 build/*/*/release) -# GZ_BIN Gazebo 可执行文件(默认优先 /usr/bin/gz) -# GZ_FORCE_VERSION gz --force-version 的值(默认自动取已安装主版本) -# SENTRY_FIELD_ROOT 场地迁移包根目录 -# SENTRY_MAP_YAML 栅格图 yaml 全路径 -# -# 用法(在脚本里): -# WS="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")/../.." && pwd)" -# source "${WS}/src/sentry_sim/scripts/env_common.sh" -# -# 注意:本文件会被 `set -e` 的脚本 source,所以任何"可能失败"的命令都要兜住。 +# Share the Python environment probes while keeping ROS setup in the caller's shell. +_SENTRY_PROJECT_ENV="$(cd -- "$(dirname -- "$(readlink -f "${BASH_SOURCE[0]}")")/../../.." && pwd)/tools/project_env.py" + +_env_query() { + # These functions can also be called from a sourced shell with unexported overrides. + ROS_SETUP="${ROS_SETUP:-}" ROS_INSTALL_ROOT="${ROS_INSTALL_ROOT:-}" \ + ROS_DISTRO="${ROS_DISTRO:-}" AMENT_PREFIX_PATH="${AMENT_PREFIX_PATH:-}" \ + SENTRY_BIN_DIR="${SENTRY_BIN_DIR:-}" NAV_BIN_DIR="${NAV_BIN_DIR:-}" \ + SENTRY_FIELD_ROOT="${SENTRY_FIELD_ROOT:-}" SENTRY_MAP_YAML="${SENTRY_MAP_YAML:-}" \ + GZ_BIN="${GZ_BIN:-}" GZ_FORCE_VERSION="${GZ_FORCE_VERSION:-}" \ + GZ_PARTITION="${GZ_PARTITION:-}" BRIDGE_WAIT_TIMEOUT="${BRIDGE_WAIT_TIMEOUT:-}" \ + python3 "$_SENTRY_PROJECT_ENV" "$@" +} -# --------------------------------------------------------------------------- -# 1. ROS 2 —— 找到并 source 一个能用的 setup.bash -# --------------------------------------------------------------------------- -# 为什么要探测:发行版名字(humble / jazzy / lyrical …)会变, -# 写死 `/opt/ros/lyrical/setup.bash` 等于把工程锁死在一台机器上。 env_source_ros() { - # ① 已经 source 过就别再动 —— 重复 source 会把 PATH 越叠越长。 - if [ -n "${AMENT_PREFIX_PATH:-}" ] && command -v ros2 >/dev/null 2>&1; then - return 0 + local setup + setup=$(_env_query --ros-setup) || return + if [ -n "$setup" ]; then + # shellcheck disable=SC1090 + . "$setup" || return + echo "[env] ROS: ${setup}" >&2 fi - - local cand="" - - # ② 显式指定优先 - if [ -n "${ROS_SETUP:-}" ]; then - if [ -f "$ROS_SETUP" ]; then - cand="$ROS_SETUP" - else - echo "[env] ❌ ROS_SETUP 指向的文件不存在: $ROS_SETUP" >&2 - return 1 - fi - fi - - # ③ 自定义安装根(非 /opt/ros 的安装,比如源码编译) - if [ -z "$cand" ] && [ -n "${ROS_INSTALL_ROOT:-}" ] \ - && [ -f "${ROS_INSTALL_ROOT}/setup.bash" ]; then - cand="${ROS_INSTALL_ROOT}/setup.bash" - fi - - # ④ 按发行版名找 - if [ -z "$cand" ] && [ -n "${ROS_DISTRO:-}" ] \ - && [ -f "/opt/ros/${ROS_DISTRO}/setup.bash" ]; then - cand="/opt/ros/${ROS_DISTRO}/setup.bash" - fi - - # ⑤ 在 /opt/ros 下扫,多个时取版本号最大的那个 - if [ -z "$cand" ]; then - cand=$(ls -1d /opt/ros/*/setup.bash 2>/dev/null | sort -V | tail -1) - fi - - if [ -z "$cand" ] || [ ! -f "$cand" ]; then - echo "[env] ❌ 找不到 ROS 2 安装(/opt/ros/*/setup.bash 全空)。" >&2 - echo "[env] 办法:先 source 你的 ROS 环境;或设 ROS_SETUP=;" >&2 - echo "[env] 或设 ROS_DISTRO=<发行版名>;或设 ROS_INSTALL_ROOT=<安装前缀>。" >&2 - return 1 - fi - - local n - n=$(ls -1d /opt/ros/*/setup.bash 2>/dev/null | wc -l) - if [ "$n" -gt 1 ] && [ -z "${ROS_SETUP:-}" ] && [ -z "${ROS_DISTRO:-}" ]; then - echo "[env] ⚠️ 机器上装了 $n 个 ROS,自动选了版本号最大的:$cand" >&2 - echo "[env] 想用别的就设 ROS_DISTRO=<名字> 或 ROS_SETUP=<全路径>。" >&2 - fi - - # shellcheck disable=SC1090 - # shellcheck disable=SC1091 - . "$cand" - echo "[env] ROS: ${cand}" >&2 } -# --------------------------------------------------------------------------- -# 2. Gazebo 可执行文件 -# --------------------------------------------------------------------------- -# 为什么要挑:source 过 ROS 之后,PATH 上的 `gz` 是 gz_tools_vendor 里那个, -# 它带着 vendor 的 RUNPATH,会去加载 gz_sim_vendor(缺 cpu-lidar 插件), -# 导致雷达传感器创建失败。所以系统装的 /usr/bin/gz 优先。 env_gz_bin() { - if [ -n "${GZ_BIN:-}" ]; then - if [ ! -x "$GZ_BIN" ]; then - echo "[env] ❌ GZ_BIN 不可执行: $GZ_BIN" >&2 - return 1 - fi - printf '%s\n' "$GZ_BIN" - return 0 - fi - - local c - for c in /usr/bin/gz /usr/local/bin/gz /opt/gz/bin/gz; do - if [ -x "$c" ]; then - printf '%s\n' "$c" - return 0 - fi - done - - c=$(command -v gz 2>/dev/null || true) - if [ -n "$c" ]; then - printf '%s\n' "$c" - return 0 - fi - - echo "[env] ❌ 找不到 Gazebo 的 gz 可执行文件。设 GZ_BIN=<路径>。" >&2 - return 1 + _env_query --gz } -# 输出 `--force-version <主版本>`,取不到就输出空(表示不传这个参数)。 -# 为什么要自动取:写死 10 的话,装了 gz 11 就跑不起来。 env_gz_version_args() { - if [ -n "${GZ_FORCE_VERSION:-}" ]; then - printf '%s\n%s\n' --force-version "$GZ_FORCE_VERSION" - return 0 - fi - - local gz v major - gz=$(env_gz_bin 2>/dev/null || true) - [ -z "$gz" ] && return 0 - - v=$("$gz" sim --version 2>/dev/null | head -1 || true) - major=$(printf '%s' "$v" | grep -oE '^[0-9]+' || true) - if [ -n "$major" ]; then - printf '%s\n%s\n' --force-version "$major" - fi - return 0 + _env_query --gz-version-args-lines +} + +env_wait_gz_clock() { + local gz="${1:?需要 Gazebo 可执行文件}" + shift + GZ_BIN="$gz" _env_query --wait-gz-clock "$@" } -# --------------------------------------------------------------------------- -# 3. xmake 产物目录 -# --------------------------------------------------------------------------- -# **现行布局固定是 `build/bin/`** —— `src/sentry_nav/xmake.lua` 里每个 target 都 -# `set_targetdir("$(builddir)/bin")`,故意不用 xmake 默认的平台三元组, -# 免得 `build/<平台>/<架构>/<模式>` 这种串被抄进文档后换机器就失效。 -# -# 这里仍然按「找某个已知产物的实际位置」来定位(而不是直接拼 build/bin), -# 这样老布局的 checkout 也还能用,而且编译模式换了也跟得上。 env_bin_dir() { - local ws="${1:?需要仓库根路径}" - - # SENTRY_BIN_DIR 是统一名字;NAV_BIN_DIR 是历史名字,保留兼容。 - if [ -n "${SENTRY_BIN_DIR:-}" ]; then - printf '%s\n' "$SENTRY_BIN_DIR" - return 0 - fi - if [ -n "${NAV_BIN_DIR:-}" ]; then - printf '%s\n' "$NAV_BIN_DIR" - return 0 - fi - - # ① 现行布局优先 - local name p - for name in self_filter nav_client patrol odom_tf field_localization_node; do - if [ -x "${ws}/build/bin/${name}" ]; then - printf '%s\n' "${ws}/build/bin" - return 0 - fi - done - - # ② 老布局:去 build/ 里找产物实际所在的那一层 - for name in self_filter nav_client patrol odom_tf field_localization_node; do - p=$(find "$ws/build" -maxdepth 4 -type f -name "$name" 2>/dev/null | head -1 || true) - if [ -n "$p" ]; then - dirname "$p" - return 0 - fi - done - - # ③ 还没编译过:返回现行布局的位置 - printf '%s\n' "${ws}/build/bin" + _env_query "${1:?需要仓库根路径}" --bin-dir } -# --------------------------------------------------------------------------- -# 4. 场地迁移包 -# --------------------------------------------------------------------------- -# 不写死 RMUL2027_map_transfer_20261016_STEP_R1:换一版迁移包(日期变了)就废。 env_field_root() { - local ws="${1:?需要仓库根路径}" - - if [ -n "${SENTRY_FIELD_ROOT:-}" ]; then - if [ ! -d "$SENTRY_FIELD_ROOT" ]; then - echo "[env] ❌ SENTRY_FIELD_ROOT 不存在: $SENTRY_FIELD_ROOT" >&2 - return 1 - fi - printf '%s\n' "$SENTRY_FIELD_ROOT" - return 0 - fi - - local d - # ① 仓库自带的 field/ 下任意一个含 guodong_sentry_sim 的包 - for d in "$ws"/field/*/src/guodong_sentry_sim; do - if [ -d "$d" ]; then - dirname "$(dirname "$d")" - return 0 - fi - done - - # ② 退回本机旧位置(任意 *_map_transfer_*) - for d in "$HOME"/Gazebo_projects/*map_transfer*/src/guodong_sentry_sim; do - if [ -d "$d" ]; then - dirname "$(dirname "$d")" - return 0 - fi - done - - echo "[env] ❌ 找不到场地迁移包。设 SENTRY_FIELD_ROOT=<含 src/guodong_sentry_sim 的目录>。" >&2 - return 1 + _env_query "${1:?需要仓库根路径}" --field } -# 输出栅格图 yaml 路径:优先 rmul_2027.yaml,否则取地图目录里第一个 env_map_yaml() { - local field_root="${1:?需要场地根路径}" - - if [ -n "${SENTRY_MAP_YAML:-}" ]; then - if [ ! -f "$SENTRY_MAP_YAML" ]; then - echo "[env] ❌ SENTRY_MAP_YAML 不存在: $SENTRY_MAP_YAML" >&2 - return 1 - fi - printf '%s\n' "$SENTRY_MAP_YAML" - return 0 - fi - - local m first="" - for m in "$field_root"/src/guodong_sentry_sim/maps/*/*.yaml; do - [ -f "$m" ] || continue - case "$m" in - */rmul_2027.yaml) printf '%s\n' "$m"; return 0 ;; - esac - if [ -z "$first" ]; then first="$m"; fi - done - - if [ -n "$first" ]; then - printf '%s\n' "$first" - return 0 - fi - - echo "[env] ❌ $field_root 下找不到任何栅格图 yaml。设 SENTRY_MAP_YAML=<路径>。" >&2 - return 1 + _env_query --map --field-root "${1:?需要场地根路径}" } -# --------------------------------------------------------------------------- -# 5. 一次性打印全部探测结果(调试用) -# --------------------------------------------------------------------------- env_report() { local ws="${1:?需要仓库根路径}" - echo " SENTRY_SIM_SHARE = ${SENTRY_SIM_SHARE:-<未设>}" - echo " ROS = ${AMENT_PREFIX_PATH%%:*}" - echo " ROS_DISTRO = ${ROS_DISTRO:-<未设>}" - echo " BIN_DIR = $(env_bin_dir "$ws")" - echo " GZ_BIN = $(env_gz_bin 2>/dev/null || echo '<找不到>')" - echo " GZ 版本参数 = $(env_gz_version_args | tr '\n' ' ')" - echo " FIELD_ROOT = $(env_field_root "$ws" 2>/dev/null || echo '<找不到>')" + printf ' SENTRY_SIM_SHARE = %s\n' "${SENTRY_SIM_SHARE:-<未设>}" + local ros="${AMENT_PREFIX_PATH:-}" + printf ' ROS = %s\n' "${ros%%:*}" + printf ' ROS_DISTRO = %s\n' "${ROS_DISTRO:-<未设>}" + local bin gz versions field + bin=$(env_bin_dir "$ws") || return + gz=$(env_gz_bin) || return + versions=$(GZ_BIN="$gz" env_gz_version_args) || return + field=$(env_field_root "$ws") || return + printf ' BIN_DIR = %s\n' "$bin" + printf ' GZ_BIN = %s\n' "$gz" + printf ' GZ 版本参数 = %s\n' "${versions//$'\n'/ }" + printf ' FIELD_ROOT = %s\n' "$field" } diff --git a/src/sentry_sim/scripts/sentry_up.sh b/src/sentry_sim/scripts/sentry_up.sh index 7758e2f..216d31c 100755 --- a/src/sentry_sim/scripts/sentry_up.sh +++ b/src/sentry_sim/scripts/sentry_up.sh @@ -15,6 +15,7 @@ set -e SELF="$(readlink -f "${BASH_SOURCE[0]}")" WS="$(cd -- "$(dirname -- "$SELF")/../../.." && pwd)" +INTERNAL_TOOLS="$WS/tools/_internal" # --------------------------------------------------------------------------- # 日志默认自动落盘:不需要再记得 `| tee generated/up.log` @@ -41,8 +42,7 @@ export SENTRY_SIM_SHARE="$PKG_SHARE" # --------------------------------------------------------------------------- # 环境探测:ROS 发行版 / 场地包 / 地图 / xmake 产物目录 / gz 版本,一个都不写死。 -# 全部逻辑在 env_common.sh 里,也能被别的脚本复用;每个值都可以用环境变量覆盖 -# (顶层注释里列了全部变量名)。 +# env_common.sh 调用 tools/project_env.py,和 Python launch 共用探测规则。 # --------------------------------------------------------------------------- # shellcheck source=./env_common.sh . "${PKG_SHARE}/scripts/env_common.sh" @@ -50,22 +50,35 @@ export SENTRY_SIM_SHARE="$PKG_SHARE" # 注意顺序:先 source ROS,后面 `ros2 run` / `xacro` 才在 PATH 上。 env_source_ros -FIELD_ROOT="$(env_field_root "$WS")" || exit 1 -MAP_YAML="$(env_map_yaml "$FIELD_ROOT")" || exit 1 -NAV_BIN_DIR="${NAV_BIN_DIR:-$(env_bin_dir "$WS")}" -GZ_EXE="$(env_gz_bin)" || exit 1 -# `--force-version <主版本>`,没装多个版本时可以留空;GZ_FORCE_VERSION 可强制指定。 -mapfile -t GZ_VER_ARGS < <(env_gz_version_args) +FIELD_ROOT="$(env_field_root "$WS")" +MAP_YAML="$(env_map_yaml "$FIELD_ROOT")" +NAV_BIN_DIR="$(env_bin_dir "$WS")" +GZ_EXE="$(env_gz_bin)" +GZ_VERSION_LINES="$(GZ_BIN="$GZ_EXE" env_gz_version_args)" +GZ_VER_ARGS=() +if [ -n "$GZ_VERSION_LINES" ]; then + mapfile -t GZ_VER_ARGS <<< "$GZ_VERSION_LINES" +fi HEADLESS="${HEADLESS:-0}" NAV2="${NAV2:-1}" RVIZ="${RVIZ:-1}" # Use exactly the same defaults as the Python launch entry point. -eval "$(python3 "$WS/tools/dds_environment.py" --shell)" +eval "$(python3 "$INTERNAL_TOOLS/dds_environment.py" --shell)" + +LOCALIZATION="${LOCALIZATION:-lio}" +LIO_MODE="${LIO_MODE:-localization}" +if [ "$LIO_MODE" = mapping ]; then + LIO_DEFAULT_MAP="$WS/generated/field_mapping.flmap" +else + LIO_DEFAULT_MAP="$PKG_SHARE/maps/field_full.flmap" +fi +LIO_MAP="${LIO_MAP:-$LIO_DEFAULT_MAP}" +LIO_EXPORT_MAP="${LIO_EXPORT_MAP:-$LIO_MAP}" +LIO_POINT_CLOUD_TOPIC="${LIO_POINT_CLOUD_TOPIC:-/scan/points_lio}" # ---------- 试运行:只打印探测结果,不启动任何东西 ---------- -# 排查"路径不对/版本不对"时先跑这个,比启动一半再失败好定位: # SENTRY_DRY_RUN=1 scripts/sentry_up.sh if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then echo "[sentry_up] 试运行(不启动任何进程)" @@ -76,13 +89,16 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then echo " GZ 版本参数 = ${GZ_VER_ARGS[*]:-<无>}" echo " FIELD_ROOT = $FIELD_ROOT" echo " MAP_YAML = $MAP_YAML" + echo " LIO_MAP = $LIO_MAP" + echo " LIO_EXPORT_MAP = $LIO_EXPORT_MAP" + echo " LIO_POINT_CLOUD_TOPIC = $LIO_POINT_CLOUD_TOPIC" echo " SENTRY_SIM_SHARE = $SENTRY_SIM_SHARE" echo " ROS_DISTRO = ${ROS_DISTRO:-<未设>}" echo " ROS 前缀 = ${AMENT_PREFIX_PATH%%:*}" echo " HEADLESS/NAV2/RVIZ = $HEADLESS/$NAV2/$RVIZ" echo " 可执行文件检查:" for _n in self_filter odom_tf cmd_vel_relay patrol; do - if [ -x "${NAV_BIN_DIR}/${_n}" ]; then + if [ -f "${NAV_BIN_DIR}/${_n}" ] && [ -x "${NAV_BIN_DIR}/${_n}" ]; then echo " ✅ ${_n}" else echo " ⚠️ ${_n} 不存在(用到它的部分会失败,先 xmake)" @@ -92,7 +108,7 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then fi # UDPv4 is a transport default, not a guarantee that service discovery succeeds. -python3 "$WS/tools/dds_environment.py" +python3 "$INTERNAL_TOOLS/dds_environment.py" # ROS 环境由上面的 env_source_ros 自动 source(逻辑在 env_common.sh), # 不再写死 /opt/ros/<发行版>/setup.bash —— 换发行版不用改脚本。 @@ -100,7 +116,7 @@ python3 "$WS/tools/dds_environment.py" # 没有资源索引,所以不能 `ros2 run`,只能直接跑路径。 nav_cmd() { local node="$1" - if [ ! -x "${NAV_BIN_DIR}/${node}" ]; then + if [ ! -f "${NAV_BIN_DIR}/${node}" ] || [ ! -x "${NAV_BIN_DIR}/${node}" ]; then echo "[sentry_up] ❌ 找不到可执行文件 ${NAV_BIN_DIR}/${node}" >&2 echo "[sentry_up] 先编译:cd ${WS} && xmake" >&2 echo "[sentry_up] 产物目录是自动探测的;不对就显式指定:" >&2 @@ -110,20 +126,25 @@ nav_cmd() { echo "${NAV_BIN_DIR}/${node}" } -export GZ_SIM_RESOURCE_PATH="${PKG_SHARE}/models:${FIELD_ROOT}/src/guodong_sentry_sim/models" +export GZ_SIM_RESOURCE_PATH="${PKG_SHARE}/models:${FIELD_ROOT}/src/guodong_sentry_sim/models${GZ_SIM_RESOURCE_PATH:+:$GZ_SIM_RESOURCE_PATH}" export GZ_PARTITION="${GZ_PARTITION:-sentry}" export ROS_DOMAIN_ID="${ROS_DOMAIN_ID:-0}" # 默认用 0,跟普通终端一致;要隔离时自己设 -LOCALIZATION="${LOCALIZATION:-lio}" -LIO_MODE="${LIO_MODE:-localization}" -LIO_MAP="${LIO_MAP:-${WS}/generated/field.flmap}" -LIO_EXPORT_MAP="${LIO_EXPORT_MAP:-${LIO_MAP}}" case "$LOCALIZATION" in lio) NAV2_LOCALIZATION=False ;; amcl) NAV2_LOCALIZATION=True ;; *) echo "LOCALIZATION must be lio or amcl" >&2; exit 1 ;; esac case "$LIO_MODE" in mapping|localization) ;; *) echo "LIO_MODE must be mapping or localization" >&2; exit 1 ;; esac -if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = localization ] && [ ! -r "$LIO_MAP" ]; then +if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = localization ] && { [ ! -f "$LIO_MAP" ] || [ ! -r "$LIO_MAP" ]; }; then echo "[sentry_up] missing LIO map: $LIO_MAP; first run LIO_MODE=mapping or choose LOCALIZATION=amcl" >&2 exit 1 fi +if [ "$LOCALIZATION" = lio ] && [ "$LIO_MODE" = mapping ]; then + mkdir -p "$(dirname -- "$LIO_EXPORT_MAP")" +fi +ODOM_TF_EXE="$(nav_cmd odom_tf)" +CMD_VEL_RELAY_EXE="$(nav_cmd cmd_vel_relay)" +SELF_FILTER_EXE="$(nav_cmd self_filter)" +if [ "$LOCALIZATION" = lio ]; then + LIO_EXE="$(nav_cmd field_localization_node)" +fi WORLD="${PKG_SHARE}/worlds/sentry_arena.sdf" PIDS=() CLEANED=0 @@ -187,7 +208,7 @@ cleanup() { trap cleanup EXIT INT TERM if [ "$NAV2" = "1" ]; then - python3 "$WS/tools/nav2_startup.py" --preflight + python3 "$INTERNAL_TOOLS/nav2_startup.py" --preflight fi # ---------- 1. Gazebo(系统版,清掉 ROS vendor 的库路径)---------- @@ -203,34 +224,9 @@ GZ_PID=$! PIDS+=("$GZ_PID") # ---------- 2. 等 Gazebo 就绪(/clock 出现)---------- -# 查话题也用 $GZ_EXE,而不是 PATH 上的 `gz`:source 过 ROS 之后 PATH 上是 -# gz_tools_vendor 那份,和真正在跑的进程不一定同一个版本,容易误判。 -echo -n "[sentry_up] 等 Gazebo 就绪" -GZ_READY=0 -for _ in $(seq 1 120); do - # Gazebo 进程提前退出 → 立刻报错,不用干等满 120 秒 - if ! kill -0 "$GZ_PID" 2>/dev/null; then - echo - echo "[sentry_up] ❌ Gazebo 启动失败,进程已退出" >&2 - wait "$GZ_PID" 2>/dev/null || true - exit 1 - fi - if env -u LD_LIBRARY_PATH "$GZ_EXE" topic -l 2>/dev/null | grep -qx '/clock'; then - GZ_READY=1 - break - fi - echo -n "." - sleep 1 -done - -if [ "$GZ_READY" != "1" ]; then - echo - echo "[sentry_up] ❌ 等待 Gazebo 超时(120 s),没看到 /clock" >&2 - echo "[sentry_up] 先确认 GZ_PARTITION=${GZ_PARTITION:-<未设>} 和其他终端一致" >&2 - echo "[sentry_up] 再确认 Gazebo 窗口/进程还活着" >&2 - exit 1 -fi -echo " OK" +echo "[sentry_up] 等 Gazebo /clock" +env_wait_gz_clock "$GZ_EXE" --gazebo-pid "$GZ_PID" +echo "[sentry_up] Gazebo /clock 已就绪" # ---------- 3. ros_gz 桥 ---------- echo "[sentry_up] 启动 ros_gz 桥" @@ -265,7 +261,7 @@ PIDS+=($!) # ---------- 5. odom -> base_link ---------- echo "[sentry_up] 启动 odom_tf(${NAV_BIN_DIR}/odom_tf,C++ 版)" # SENTRY_ODOM_SCALE != 1.0 时给里程计加比例误差(演示 AMCL 纠正漂移用) -$(nav_cmd odom_tf) --ros-args \ +"$ODOM_TF_EXE" --ros-args \ -p use_sim_time:=true -p "odom_scale:=${SENTRY_ODOM_SCALE:-1.0}" & PIDS+=($!) @@ -277,20 +273,20 @@ RELAY_HEALTH=false if [ "$LOCALIZATION" = lio ]; then RELAY_HEALTH=true; fi RELAY_INPUT=/cmd_vel if [ "$RELAY_NAVIGATION" = false ]; then RELAY_INPUT="${MANUAL_CMD_VEL_TOPIC:-/cmd_vel}"; fi -$(nav_cmd cmd_vel_relay) --ros-args -p use_sim_time:=true \ +"$CMD_VEL_RELAY_EXE" --ros-args -p use_sim_time:=true \ -p navigation_mode:="$RELAY_NAVIGATION" -p require_localization_health:="$RELAY_HEALTH" -p in_topic:="$RELAY_INPUT" & PIDS+=($!) # ---------- 5.55 点云自滤(剔除车身自身回波,Nav2 避障用)---------- echo "[sentry_up] 启动点云自滤(${NAV_BIN_DIR}/self_filter)" -$(nav_cmd self_filter) --ros-args -p use_sim_time:=true -p reliable_clouds:=true & +"$SELF_FILTER_EXE" --ros-args -p use_sim_time:=true -p reliable_clouds:=true & PIDS+=($!) # ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ---------- if [ "$LOCALIZATION" = lio ]; then - echo "[sentry_up] LIO mode=$LIO_MODE (AMCL disabled)" - $(nav_cmd field_localization_node) --ros-args -p use_sim_time:=true \ - -p point_cloud_topic:=/scan/points_filtered -p imu_topic:=/imu -p reliable_clouds:=true \ + echo "[sentry_up] LIO mode=$LIO_MODE map=$LIO_MAP cloud=$LIO_POINT_CLOUD_TOPIC (AMCL disabled)" + "$LIO_EXE" --ros-args -p use_sim_time:=true \ + -p "point_cloud_topic:=$LIO_POINT_CLOUD_TOPIC" -p imu_topic:=/imu -p reliable_clouds:=true \ -p mode:="$LIO_MODE" -p map_path:="$LIO_MAP" -p export_map_path:="$LIO_EXPORT_MAP" \ -p publish_map_to_odom:=true -p "diagnostics_path:='${LIO_TRACE_PATH:-}'" \ -p initial_x:="${LIO_INITIAL_X:--5.0}" -p initial_y:="${LIO_INITIAL_Y:-3.0}" \ @@ -317,7 +313,7 @@ echo "体检(含 Gazebo 真值对照):python3 tools/check_stack.py" # ---------- 6. Nav2 ---------- if [ "$NAV2" = "1" ]; then - python3 "$WS/tools/wait_navigation_ready.py" + python3 "$INTERNAL_TOOLS/wait_navigation_ready.py" echo "[sentry_up] 启动 Nav2($LOCALIZATION + 栅格图)" # 三个参数都是必需的,各有原因(踩过的坑): # use_composition:=False 组合模式在本机起不来 —— /nav2_container 起来后一个组件都不加载, @@ -328,7 +324,7 @@ if [ "$NAV2" = "1" ]; then # 发现不到,lifecycle_manager 会无限等下去(日志刷 # "Waiting for service keepout_costmap_filter_info_server/get_state"), # Nav2 永远不激活 → 所有导航目标被拒。我们不用禁入区/限速区,直接关掉。 - python3 "$WS/tools/run_nav2.py" --timeout "${SENTRY_NAV2_TIMEOUT:-120}" -- \ + python3 "$INTERNAL_TOOLS/run_nav2.py" --timeout "${SENTRY_NAV2_TIMEOUT:-120}" -- \ map:="${MAP_YAML}" \ use_sim_time:=true \ autostart:=False \ diff --git a/tools/README.md b/tools/README.md index b5a30f4..5a74b90 100644 --- a/tools/README.md +++ b/tools/README.md @@ -1,76 +1,176 @@ # tools/ -模型转换、调试、演示用的小工具(都是独立脚本,不参与构建)。 +最后更新:2026-11-22 -## 模型相关 +构建脚本、启动链内部件、验收脚本和回归测试。 +**除 `check_stack.py` 需要仿真在运行中外,其余命令都可以在仿真没启动时执行。** -| 脚本 | 用途 | -|---|---| -| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(唯一的建模入口) | -| `decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab/Blender) | -| `gen_sdf.sh` | URDF(xacro) → `models/sentry/model.sdf` + `generated/sentry.urdf` | +> 以下命令**全部从仓库根目录**运行。看到 `AttributeError` / `ModuleNotFoundError` 时 +> 先确认是不是在 `tools/` 里面敲的。 -## 体检 +## 目录结构 -| 脚本 | 用途 | -|---|---| -| `check_dds.sh` | ★ Fast DDS 体检:`/dev/shm` 残留段、进程、DDS 环境变量。加 `--clean` 清理残留 | -| `check_stack.py` | ★ **只读体检**:10 个 lifecycle 节点状态 + 节点总览(含 `amcl`、`lifecycle_manager`)+ 话题 + TF + 真值对照,一条命令问清"现在这套栈健康吗" | -| `project_env.py` | ★ 路径/版本探测。**排查"路径不对"先跑它**。支持直接取单个值供脚本/文档拼接:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup`,例:`NAV=$(python3 tools/project_env.py --bin-dir)/nav_client`。它同时被 `launch/` 和 `check_stack.py` import,**是依赖库不只是工具** | - -## 静态审计 - -| 脚本 | 用途 | -|---|---| -| `audit_absolute_paths.py` | 扫全仓的写死绝对路径(`/opt/ros/…`、`/home/…`、`/usr/…`)。`--all` 出完整报告 | - -> ⚠️ **这个工具目前噪音很大**:它把 ROS 话题名也当成绝对路径,全仓会产生 -> **4700+ 条**命中(`/wait`、`/odom`、`/dev/shm` …),真正要看的只有 -> `ROS 安装路径` / `用户目录路径` 这两类。查的时候这样过滤: -> `python3 tools/audit_absolute_paths.py --all | grep -A1 'ROS 安装路径\|用户目录路径'` - -> **本目录里没有 `nav_client`。** 发 Nav2 目标用的是 **xmake 编译出的二进制**, -> 源码在 `src/sentry_nav/src/nav_client.cpp`,产物**固定落在 `build/bin/nav_client`** -> (xmake 里每个 target 都 `set_targetdir("$(builddir)/bin")`,故意不用带平台三元组的默认目录)。 -> 它带地图预检(占据值 ≥65 / 未知格 / 净空 <0.5 m 直接拦下),用法见 -> [`../docs/操作手册.md`](../docs/操作手册.md) §3。 - -## 构建 / 编辑器 - -**这里已经没有构建相关的脚本了。** - -`compile_commands.json` 由 xmake 在**每次构建后自动重写** -(根 `xmake.lua` 里的 `plugin.compile_commands.autoupdate` 规则), -以前那个 `gen_compdb.sh`(合并 colcon 分包产物)已随去 colcon 一起删除。 - -改了源码结构后只要跑一次 `xmake`,再在 VS Code 里 -`Ctrl+Shift+P → clangd: Restart language server`。详见 `../.vscode/README.md`。 - -## 典型用法 - -```bash -# 机械给了新装配体 -python3 tools/build_vehicle.py --src "/run/media/mzxiang/CPBA_X64FRE/装配车" --out src/sentry_sim/meshes/full -python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025 +```text +tools/ +├── project_env.py 环境探测(库和 CLI),供 Shell、Python launch 和工具共用 +├── check_stack.py 整套栈体检(⚠️ 需要仿真在跑) +├── check_dds.sh DDS 环境 / 残留进程检查 +├── capture_lio.py 录制 LIO 建图 / 评估数据 +├── build_vehicle.py 整车 STL → 仿真网格 + 布局 JSON +├── decimate.py 网格降面 +├── gen_sdf.sh xacro → SDF / URDF +├── _internal/ 启动链内部件;被 sentry_up.sh / launch / 测试 import +├── validation/ 验收脚本(会真的拉起 Gazebo,跑完整流程) +└── tests/ 回归测试(不碰 Gazebo 运动,最快的检查) ``` -> 建模类脚本是**离线**的,不需要起仿真。体检类脚本要先按根目录 README 把仿真跑起来, -> 再在另一个终端执行。 +## 一、会被自动调用的(不用手动跑) -## 2026-11-21 精简掉了什么 +| 工具 | 谁调它 | 干什么 | +|---|---|---| +| `project_env.py` | Shell 环境库、Python launch、体检、录包、验收和测试 | 探测 ROS setup / `build/bin` / 场地包 / 地图 / gz 版本,**一个都不写死** | +| `_internal/dds_environment.py` | `sentry_up.sh`(`--shell`)、`sentry_arena.launch.py`、`nav2_startup.py`、`validate_lio_navigation.py`、`tests/test_nav2_startup.py` | DDS 默认值统一出口(`rmw_implementation`、`ROS_DOMAIN_ID`、共享内存传输) | +| `_internal/resolve_ros_includes.py` | `src/sentry_nav/xmake.lua`、`src/field_localization/xmake.lua` | 经 ament index 解析 ROS 包的头文件目录,喂给 xmake | +| `_internal/nav2_startup.py` | `sentry_up.sh`、`sentry_arena.launch.py` | Nav2 域预检(`--preflight`)+ 发现门控 + 有界就绪检查 | +| `_internal/run_nav2.py` | `sentry_up.sh`、`sentry_arena.launch.py`、`tests/test_nav2_supervisor.py` | **只监管自己那组 Nav2 进程**;有界重试后才放行导航 | +| `_internal/wait_navigation_ready.py` | `sentry_up.sh`、`sentry_arena.launch.py` | 等到仿真时钟 + 基础机器人 TF 就绪才返回 | -一次性排查脚本已全部删除(都在 git 历史里,需要时 `git show :tools/<名字>` 能捞回来): +**这六个是被 `sentry_up.sh` 和 launch 拉起来的。改它们等于改启动行为,改完必须重跑一次启动验证。** -| 删掉的 | 原因 | +## 二、手动入口(日常用) + +| 命令 | 用途 | |---|---| -| `probe_all.py` / `probe_sub.py` | 已被 `check_stack.py` 完全覆盖 | -| `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 同一次排查的三代尸体 | -| `smoke_probe.py` | 等激活+收点云+发目标 → `check_stack.py` + `nav_client` | -| `nav_diag.py` | 同 `check_stack.py` §2/§3,且还用旧坐标系 | -| `cloud_compare.py` | 0 引用 | -| `send_goal.py` | **空炮**:往 `/goal_pose` 发,Nav2 没有任何节点订阅它 | -| `tf_watch.py` / `scan_probe.py` / `cloud_probe.py` / `free_goals.py` / `mark_field_center.py` / `amcl_drift_demo.py` / `demo.py` / `drive_demo.py` | 精简(替代做法见各文档:用 `ros2 topic echo`、`tf2_echo`、RViz 的 costmap 显示、`ros2 topic pub /cmd_vel`) | -| `build_meshes.py` / `build_gimbal.py` | 旧版分件建模(只处理「底盘」或「云台」单独导出),已被 `build_vehicle.py` 的整车装配体方案取代 | +| `python3 tools/check_stack.py` | **整套栈体检**:生命周期、话题、TF、Gazebo 真值对照。⚠️ 仿真必须在跑,否则会卡在等服务上 | +| `tools/check_dds.sh` | DDS 环境、`/dev/shm`、残留进程。`--clean` 清理残留(**确认所有 ROS 进程已停**再用) | +| `python3 tools/project_env.py` | 打印全部探测结果。单项取值:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup` | +| `python3 tools/capture_lio.py --help` | 录制建图(`--profile mapping`)或评估(`--profile evaluation`)数据 | +| `python3 tools/build_vehicle.py --help` | 整车装配体 STL → 仿真网格 + 布局 JSON。`--dry-run` 只打印分类结果 | +| `python3 tools/decimate.py --help` | 顶点聚类降面:`decimate.py --grid 0.01 src.stl dst.stl` | +| `tools/gen_sdf.sh` | xacro → `models/sentry/model.sdf` + `generated/sentry.urdf` | -> **删脚本不影响已有产物**:`src/sentry_sim/meshes/base.stl`、`wheel.stl` 是已经生成好的, -> URDF 引用的是这些文件。重跑建模用 `build_vehicle.py` 即可。 +**发导航目标不用工具脚本**,用 xmake 产物 `build/bin/nav_client`。 +`xmake` 构建会自动刷新 `compile_commands.json`(clangd 靠它跳转)。 + +## 三、库模块(有 `--help` 不代表要单独跑) + +| 模块 | 被谁 import | 说明 | +|---|---|---| +| `_internal/arena_grid.py`、`_internal/arena_survey.py` | `capture_lio.py`、`validate_lio_navigation.py` | 栅格可达性、隔离仿真测站和雷达地图生成 | +| `validation/lio_metrics.py` | `validate_lio_navigation.py` | ATE / RPE / 圆柱间隙计算。**没有 CLI**,直接跑只会静默退出 | +| `project_env.py` | 见上 | 既当库又当命令 | +| `_internal/dds_environment.py` | 见上 | 既当库又当命令 | + +## 四、验收脚本(会真的拉起 Gazebo) + +| 命令 | 用途 | 耗时 | +|---|---|---| +| `python3 tools/validation/verify_lio_stack.py --map --output ` | **只验栈、不发运动指令**:Gazebo + LIO + Nav2 能不能一起起来。`--launcher {shell,python}` 选启动入口,`--rviz` 加上离屏 RViz 负载 | 分钟级 | +| `python3 tools/validation/validate_lio_navigation.py --map --output ` | **真跑导航并用仿真真值打分**。`--scenario {clear,cylinder,blocked,lidar_loss}` 选场景,`--full-field` 检查每个 1 m 瓦片的代表目标并跑全场路线,圆柱场景可调 `--obstacle-x/y/radius`,`--domain` 指定 ROS 域 | 分钟级 | +| `python3 tools/validation/run_lio_matrix.py --launcher {shell,python} --map --output ` | 每条路线/每个启动器跑 3 次冷启动,外加一次"目标不可达"检查。`--domain` 同上 | **十几分钟** | + +三个都要给 `--map`(例如 `src/sentry_sim/maps/field_full.flmap`)和 `--output`,但**输出目录的要求不同**: + +| 脚本 | 对 `--output` 的要求 | +|---|---| +| `validate_lio_navigation.py` | **必须不存在**(已存在直接报错) | +| `run_lio_matrix.py` | **必须不存在**(`output must be new`) | +| `verify_lio_stack.py` | **允许已存在**(会自动 `mkdir -p`) | + +脚本自行分配隔离的 `ROS_DOMAIN_ID`,**不会和你正在跑的仿真撞车**。 + +隔离 Gazebo 空场的全场建图与东南回放: + +```bash +python3 tools/capture_lio.py --profile mapping --full-field \ + --output generated/full_survey --map generated/field_full.flmap +python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \ + --lio-cloud-topic /scan/points_lio \ + --map generated/field_full.flmap --output generated/full_shell +python3 tools/validation/compare_lio_maps.py --dataset generated/full_shell/dataset \ + --baseline generated/field.flmap --candidate generated/field_full.flmap \ + --output generated/southeast_comparison +``` + +全场建图按已知坐标在隔离实例布置测站,使用与在线 LIO 相同的自滤点云。测站位置由命令指定,Gazebo 真值核对实际到位。在线验收使用另一实例,机器人连续行驶。回放需要至少 10 帧独立录制的东南扫描(`x >= 4`、`y <= -1.5`)。 + +## 五、回归测试 + +按跑得快 → 慢排: + +| 命令 | 需要什么 | 实测 | +|---|---|---| +| `python3 tools/tests/test_project_env.py` | Python 3 和 Bash | 临时文件和假 Gazebo 覆盖路径、退出码、版本超时与桥等待 | +| `python3 tools/tests/test_nav2_supervisor.py` | **什么都不需要**(不碰 ROS、不碰 Gazebo) | ✅ 5 项检查,约 1 秒 | +| `python3 tools/tests/test_nav2_startup.py` | ROS 环境(起隔离 domain 的服务) | ✅ 15 项检查 | +| `python3 tools/tests/test_motion_interlock.py` | ROS 环境 + `build/bin/cmd_vel_relay`(`--binary` 可指定) | 需已构建 | + +**`test_nav2_supervisor.py` 是最便宜的冒烟测试**:改完 `run_nav2.py` 先跑它。 + +### 和 C++ 单测的关系 + +C++ 侧的单测走 xmake: + +```bash +xmake test # 全部 +xmake test test_waypoint_sequencer/default # 单个(必须带 /default) +``` + +三个带 `add_tests` 的 target:`test_self_filter_core`、`test_waypoint_sequencer`、`test_geometry`。 + +Python 回归测试用上表中的命令单独运行。 + +## 六、加新工具时的规矩 + +1. **放哪个目录** + - 只给启动链用、且会被 import → `_internal/` + - 手动跑、会拉起 Gazebo → `validation/` + - 手动跑、不碰 Gazebo → `tests/` + - 构建期用的 → 本目录顶层 + +2. **跨目录 import 必须自己铺 `sys.path`**,仓库里没有安装成包: + + ```python + from pathlib import Path + import sys + sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal')) + ``` + +3. **别复制公共逻辑**。要读环境变量 / 找产物目录,一律走 `project_env`; + 要设 DDS 参数,一律走 `_internal/dds_environment.py`。这两处各只有一份实现。 + +4. **本文件是唯一索引**。加了工具就在上面的表里补一行,删了工具就把那行删掉 + —— 否则会出现「文档里有一堆打不开的文件」。 + +## 七、这个目录的历史 + +`git log --oneline -- tools/` 能看到两次大整理: + +**第一次:删掉 21 个文件**(`git log --diff-filter=D --name-only -- 'tools/*.py' 'tools/*.sh'` 可复现) + +| 类别 | 文件 | 为什么删 | +|---|---|---| +| 一次性诊断(14) | `probe_all` `probe_sub` `probe_cmd` `probe_cmd2` `cmd_probe_all` `smoke_probe` `nav_diag` `cloud_compare` `cloud_probe` `scan_probe` `tf_watch` `send_goal` `free_goals` `mark_field_center` | 功能被 `check_stack.py` 和 `validation/` 取代 | +| 演示(3) | `demo` `drive_demo` `amcl_drift_demo` | 一次性演示,舞台已拆 | +| 构建辅助(3) | `build_meshes` `build_gimbal` `gen_compdb.sh` | 前两个并入 `build_vehicle.py`;`compile_commands.json` 改由 xmake 自动刷新 | +| 节点迁移(1) | `nav_client.py` | 重写成 C++,在 `src/sentry_nav/src/` | + +**第二次:扁平布局收成三组** + +``` +_internal/ 启动链内部件(被 shell / launch / 测试 import,一般不当命令用) +validation/ 会拉起 Gazebo 的验收脚本 +tests/ 不碰 Gazebo 的回归测试 +``` + +顺带删了已跑完使命的 `audit_absolute_paths.py`(可移植性重构的一次性审计工具)。 + +如果发现 `tools/` 里还残留着已删工具的 `.pyc`,可以安全清掉: + +```bash +find . -name __pycache__ -type d -not -path './build/*' -exec rm -rf {} + +``` + +(`.gitignore` 已经排除 `__pycache__/` 和 `*.pyc`,git 从来不收它们。 +无源码的 `.pyc` 放在 `__pycache__/` 里也**不会被 import** —— Python 3 的无源码导入要求 +`.pyc` 直接放在目录里,所以这些是纯死数据。) diff --git a/tools/_internal/arena_grid.py b/tools/_internal/arena_grid.py new file mode 100644 index 0000000..381e75a --- /dev/null +++ b/tools/_internal/arena_grid.py @@ -0,0 +1,151 @@ +"""Static arena clearance and deterministic routes for isolated simulation tests.""" + +from collections import deque +from functools import cache +import heapq +import math +from pathlib import Path + +import numpy as np +import yaml + + +START = (-5.0, 3.0) +SURVEY_GOALS = ((-5., 0.), (-5., -3.), (0., -3.), (5., -3.), (5., 0.), (5., 3.), + (0., 3.), (0., 0.), (0., -3.), (-5., -3.), START) +# Revisit the reported east route in both directions before covering the perimeter. +ARENA_GOALS = ((0., 0.), (5., -3.), (0., 0.), (5., -3.), (5., 0.), (5., 3.), + (0., 3.), START, (-5., 0.), (-5., -3.), (0., -3.), (0., 0.), START) + + +class ArenaGrid: + def __init__(self, map_yaml): + path = Path(map_yaml) + config = yaml.safe_load(path.read_text()) + self.resolution = float(config['resolution']) + self.origin = tuple(config['origin'][:2]) + if config.get('mode', 'trinary') != 'trinary' or config['origin'][2] != 0: + raise ValueError('arena coverage expects an unrotated trinary occupancy map') + with (path.parent / config['image']).open('rb') as image: + def header(): + line = image.readline().split(b'#', 1)[0].strip() + while not line: + raw = image.readline() + if not raw: + raise ValueError('truncated PGM header') + line = raw.split(b'#', 1)[0].strip() + return line + if header() != b'P5': + raise ValueError('expected binary PGM occupancy map') + width, height = map(int, header().split()) + if header() != b'255': + raise ValueError('expected 8-bit PGM occupancy map') + pixels = np.frombuffer(image.read(), dtype=np.uint8).reshape(height, width) + self.size = (height, width) + probability = pixels / 255 if config.get('negate', 0) else 1 - pixels / 255 + self.free = (probability < config['free_thresh'])[::-1] + + def cell(self, point): + x, y = point + return (math.floor((y-self.origin[1])/self.resolution), + math.floor((x-self.origin[0])/self.resolution)) + + def point(self, cell): + y, x = cell + return (self.origin[0]+(x+0.5)*self.resolution, + self.origin[1]+(y+0.5)*self.resolution) + + def neighbors(self, cell): + y, x = cell + h, w = self.size + for i, j in ((y-1,x),(y+1,x),(y,x-1),(y,x+1)): + if 0 <= i < h and 0 <= j < w: + yield i, j + + @cache + def clear(self, clearance): + radius = math.ceil(clearance/self.resolution) + padded = np.pad(self.free, radius) + h, w = self.size + mask = self.free.copy() + for y in range(-radius, radius+1): + for x in range(-radius, radius+1): + if math.hypot(x, y)*self.resolution <= clearance + 1e-10: + mask &= padded[radius+y:radius+y+h, radius+x:radius+x+w] + return mask + + def coverage(self): + # Largest radius of the existing 0.65 x 0.54 m rectangular footprint. + travel = self.clear(math.hypot(0.325, 0.270)) + start = self.cell(START) + if not travel[start]: + raise ValueError('spawn pose fails the footprint clearance check') + connected = np.zeros(self.size, dtype=bool) + connected[start] = True + queue = deque([start]) + while queue: + for cell in self.neighbors(queue.popleft()): + if travel[cell] and not connected[cell]: + connected[cell] = True + queue.append(cell) + targets = connected & self.clear(0.50) + wide = self.clear(0.65) + tiles = {} + for cell in zip(*np.nonzero(targets)): + point = self.point(cell) + grid = tuple(map(math.floor, point)) + score = (not wide[cell], math.dist(point, (grid[0]+0.5, grid[1]+0.5)), point) + if grid not in tiles or score < tiles[grid]: + tiles[grid] = score + ys, xs = np.nonzero(connected) + return {'reachable_cells': int(connected.sum()), 'eligible_goal_cells': int(targets.sum()), + 'reachable_area_m2': float(connected.sum() * self.resolution**2), + 'center_coordinate_bounds_m': [self.point((min(ys), min(xs))), + self.point((max(ys), max(xs)))], + 'disconnected_goal_cells': int((self.clear(0.50)&~connected).sum()), + 'resolution_m': self.resolution, + 'samples': [tiles[tile][2] for tile in sorted(tiles)]} + + def route(self, anchors, clearance=0.55): + safe = self.clear(clearance) + points = [START] + for target in anchors: + start, end = self.cell(points[-1]), self.cell(target) + if not safe[start] or not safe[end]: + raise ValueError(f'unsafe survey anchor {points[-1]} -> {target}') + frontier = [(0, 0, start)] + distance = {start: 0} + previous = {} + while frontier: + _, cost, node = heapq.heappop(frontier) + if node == end: + break + if cost != distance[node]: + continue + for cell in self.neighbors(node): + if safe[cell] and cost+1 < distance.get(cell, math.inf): + distance[cell] = cost+1 + previous[cell] = node + estimate = abs(cell[0]-end[0])+abs(cell[1]-end[1]) + heapq.heappush(frontier, (cost+1+estimate, cost+1, cell)) + else: + raise ValueError(f'no survey route from {points[-1]} to {target}') + cells = [end] + while cells[-1] != start: + cells.append(previous[cells[-1]]) + candidates = [self.point(c) for c in reversed(cells[1:-1])] + [target] + index = 0 + while index < len(candidates): + a = points[-1] + # Advance to the furthest visible waypoint along the grid path. + for last in range(len(candidates)-1, index-1, -1): + b = candidates[last] + count = max(1, math.ceil(2*math.dist(a,b)/self.resolution)) + if all(safe[self.cell(tuple(x+(y-x)*i/count for x,y in zip(a,b)))] + for i in range(count+1)): + break + else: + raise ValueError(f'unable to simplify survey route near {a}') + points.append(b) + index = last+1 + return points[1:] diff --git a/tools/_internal/arena_survey.py b/tools/_internal/arena_survey.py new file mode 100644 index 0000000..07c5d2f --- /dev/null +++ b/tools/_internal/arena_survey.py @@ -0,0 +1,108 @@ +"""Make a Gazebo-only map from stationary LiDAR scans at commanded survey stations.""" + +import csv +import json +import math +import os +import re +import struct +import tempfile + +import numpy as np + +import project_env +from _internal.arena_grid import START, SURVEY_GOALS + +SETTLE_SECONDS = 0.8 +STATION_SECONDS = 1.5 +MAP_RESOLUTION = 0.10 + + +def stations(grid): + result = [START] + route = grid.route(SURVEY_GOALS) + for a, b in zip([START] + route, route): + steps = max(1, math.ceil(math.dist(a, b) / 1.5)) + for i in range(1, steps + 1): + point = tuple(round(x + (y - x) * i / steps, 4) for x, y in zip(a, b)) + if point not in result: + result.append(point) + return result + + +def set_station(gz, point, partition): + x, y = point + request = f'name: "sentry" position: {{ x: {x} y: {y} z: 0 }} orientation: {{ w: 1 }}' + response = project_env.run_gz( + gz, 'service', '-s', '/world/rmul_arena/set_pose', '--reqtype', 'gz.msgs.Pose', + '--reptype', 'gz.msgs.Boolean', '--timeout', '2000', '--req', request, + timeout=3, partition=partition, + ) + if response.returncode or not re.search(r'^data:\s*true\s*$', response.stdout, re.M): + raise RuntimeError(f'Gazebo did not acknowledge station {point}: {response.stdout} {response.stderr}') + + +def transform(points, pose): + translation, xyz, w = pose[:3], pose[3:6], pose[6] + twice = 2 * np.cross(xyz, points) + return points + w * twice + np.cross(xyz, twice) + translation + + +def selected_clouds(directory, survey): + with (directory / 'scans.csv').open() as stream: + scans = [(float(row['timestamp']), row['file']) for row in csv.DictReader(stream)] + for station in survey: + stamp = station['command_time'] + candidates = [scan for scan in scans if stamp + SETTLE_SECONDS <= scan[0] < stamp + STATION_SECONDS] + if len(candidates) < 3: + raise RuntimeError(f'insufficient settled scans at {station["goal"]}') + yield station['goal'], candidates[len(candidates) // 2] + + +def build_map(directory, selected, output): + config = (directory / 'config.txt').read_text().splitlines() + extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]] + if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']: + raise ValueError('survey recorder configuration is missing LiDAR extrinsics') + clouds = [] + for (x, y), (stamp, filename) in selected: + raw = (directory / filename).read_bytes() + magic, version, time, count = struct.unpack_from('<8sIdI', raw) + if magic != b'FLPC0001' or version != 1 or time != stamp or len(raw) != 24 + count * 24: + raise ValueError(f'invalid recorded scan {filename}') + rows = np.frombuffer(raw, dtype=[('time', ' 0.025: + raise RuntimeError(f'no independent truth for {filename} at {stamp:.3f}s') + error = math.dist(pose[:3], (x, y, 0)) + rotation = math.degrees(2 * math.acos(min(1.0, abs(pose[6])))) + report.append({'station': [x, y], 'timestamp': stamp, 'scan': filename, + 'position_error_m': error, 'rotation_error_deg': rotation}) + (directory / 'survey_truth.json').write_text(json.dumps(report, indent=2)) + if any(row['position_error_m'] > 0.02 or row['rotation_error_deg'] > 1 for row in report): + raise RuntimeError('commanded poses failed independent survey verification; see survey_truth.json') diff --git a/tools/dds_environment.py b/tools/_internal/dds_environment.py similarity index 100% rename from tools/dds_environment.py rename to tools/_internal/dds_environment.py diff --git a/tools/nav2_startup.py b/tools/_internal/nav2_startup.py similarity index 100% rename from tools/nav2_startup.py rename to tools/_internal/nav2_startup.py diff --git a/tools/resolve_ros_includes.py b/tools/_internal/resolve_ros_includes.py similarity index 100% rename from tools/resolve_ros_includes.py rename to tools/_internal/resolve_ros_includes.py diff --git a/tools/run_nav2.py b/tools/_internal/run_nav2.py similarity index 100% rename from tools/run_nav2.py rename to tools/_internal/run_nav2.py diff --git a/tools/wait_navigation_ready.py b/tools/_internal/wait_navigation_ready.py similarity index 100% rename from tools/wait_navigation_ready.py rename to tools/_internal/wait_navigation_ready.py diff --git a/tools/audit_absolute_paths.py b/tools/audit_absolute_paths.py deleted file mode 100755 index 5bac27a..0000000 --- a/tools/audit_absolute_paths.py +++ /dev/null @@ -1,151 +0,0 @@ -#!/usr/bin/env python3 - -from pathlib import Path -from collections import defaultdict -import argparse -import re - -ROOT = Path(__file__).resolve().parent.parent - -EXCLUDED_DIRS = { - ".git", - ".xmake", - "build", - "install", - "log", - "__pycache__", - ".cache", -} - -EXCLUDED_FILES = { - "compile_commands.json", - "CMakeCache.txt", -} - -# 匹配 Linux 绝对路径,避免匹配 URL 中的 // -PATH_PATTERN = re.compile( - r'(? 140: - excerpt = excerpt[:137] + "..." - - findings.append({ - "file": str(relative), - "line": line_no, - "path": path, - "category": category, - "excerpt": excerpt, - }) - - print("=" * 72) - print("仓库绝对路径审计报告") - print("=" * 72) - print(f"仓库:{ROOT}") - print(f"扫描文件数:{file_count}") - print(f"发现路径数:{len(findings)}") - print() - - print("[分类统计]") - for category, count in sorted(category_counts.items()): - print(f" {category:<18} {count:>5}") - print() - - limit = len(findings) if args.all else max(0, args.max_lines) - shown = findings[:limit] - - current_file = None - - for item in shown: - if item["file"] != current_file: - current_file = item["file"] - print(f"\n[{current_file}]") - - print( - f" L{item['line']:<5} " - f"[{item['category']}] {item['path']}" - ) - print(f" {item['excerpt']}") - - remaining = len(findings) - len(shown) - - print("\n" + "=" * 72) - print(f"已显示:{len(shown)} / {len(findings)}") - - if remaining: - print(f"其余隐藏:{remaining} 条") - print("需要完整报告时执行:python3 tools/audit_absolute_paths.py --all") - - print("=" * 72) - - -if __name__ == "__main__": - main() diff --git a/tools/capture_lio.py b/tools/capture_lio.py index 5557d62..3c7fc6a 100644 --- a/tools/capture_lio.py +++ b/tools/capture_lio.py @@ -2,8 +2,8 @@ """Record an isolated Gazebo mapping/evaluation run; truth is recorder-only. Source ROS first. Example: - python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap - python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap + python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap + python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap """ import argparse import math @@ -25,6 +25,8 @@ from std_srvs.srv import Trigger from tf2_msgs.msg import TFMessage import project_env +from _internal.arena_grid import ArenaGrid +from _internal import arena_survey def yaw(q): @@ -88,36 +90,75 @@ def main(): parser.add_argument('--profile', choices=['mapping', 'evaluation'], required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--map', type=Path, required=True) - parser.add_argument('--duration', type=float, default=120) + parser.add_argument('--duration', type=float) + parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC'), + help='override the recorded LiDAR topic') + parser.add_argument('--full-field', action='store_true', + help='capture stationary scans at overlapping Gazebo survey stations (mapping only)') + parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]') args = parser.parse_args() + if args.full_field and args.profile != 'mapping': + parser.error('--full-field requires --profile mapping') + if args.duration is not None and (not math.isfinite(args.duration) or args.duration <= 0): + parser.error('--duration must be positive and finite') + if args.full_field and args.map.exists(): + parser.error('full-field mapping requires a new output map path') if args.output.exists(): parser.error('output directory must not already exist') if args.profile == 'evaluation' and not args.map.is_file(): parser.error('evaluation requires an existing map') + workspace = project_env.WORKSPACE + try: + gz_exe = project_env.find_gz_bin() + bin_dir = project_env.find_bin_dir(workspace) + recorder_exe = project_env.require_executable(bin_dir/'field_localization_record', + 'field_localization_record') + survey = None + default_duration = 120.0 + if args.full_field: + survey = arena_survey.stations(ArenaGrid(project_env.find_map_yaml())) + default_duration = float(math.ceil(3 + len(survey) * (arena_survey.STATION_SECONDS + 0.7))) + if args.duration is not None and args.duration < default_duration: + parser.error(f'--duration must be at least {default_duration:.1f} simulated seconds for the survey') + print(f'mapping survey: {len(survey)} stationary LiDAR stations', flush=True) + if args.duration is None: + args.duration = default_duration + except (project_env.ProbeError, ValueError, OSError) as error: + parser.exit(1, f'{parser.prog}: {error}\n') + cloud_topic = args.lio_cloud_topic or '/scan/points_lio' args.output.mkdir(parents=True) args.map.parent.mkdir(parents=True, exist_ok=True) - workspace = Path(__file__).resolve().parents[1] - binary = project_env.find_bin_dir(workspace) session = uuid.uuid4().hex[:12] - os.environ.update(ROS_DOMAIN_ID=str(50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1', + os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=cloud_topic) + os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1', FASTDDS_BUILTIN_TRANSPORTS='UDPv4', HEADLESS='1', NAV2='0', RVIZ='0', LOCALIZATION='lio', LIO_MODE='mapping' if args.profile == 'mapping' else 'localization', LIO_MAP=str(args.map.resolve()), LIO_EXPORT_MAP=str(args.map.resolve()), - SENTRY_LOG=str((args.output/'stack.log').resolve())) - (args.output/'runtime.json').write_text(json.dumps({'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], - 'GZ_PARTITION': os.environ['GZ_PARTITION'], 'duration_sec': args.duration, - 'profile': args.profile, 'IMU_sensor_noise': 'zero', 'control_input': 'wheel odometry only'}, indent=2)) + SENTRY_LOG=str((args.output/'stack.log').resolve()), + SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve())) + if survey is not None: + # NAV2=0 and this branch starts neither AMCL nor LIO. The survey is offline. + os.environ['LOCALIZATION'] = 'amcl' + os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve())) + os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve())) + (args.output/'runtime.json').write_text(json.dumps({ + 'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], 'GZ_PARTITION': os.environ['GZ_PARTITION'], + 'duration_sec': args.duration, 'profile': args.profile, 'survey': survey, 'IMU_sensor_noise': 'zero', + 'control_input': 'known stationary survey coordinates' if survey else 'wheel odometry', + }, indent=2)) processes = [] log_handles = [] rclpy.init() driver = Driver(args.profile) + surveyed = [] try: processes.append(subprocess.Popen(['bash', str(workspace/'scripts/sentry_up.sh')], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace)) log = open(args.output/'record.log', 'w', encoding='utf8') log_handles.append(log) - recorder = subprocess.Popen([str(binary/'field_localization_record'), '--ros-args', '-p', 'use_sim_time:=true', - '-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}'], + recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true', + '-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}', + '-p', f'point_cloud_topic:={cloud_topic}'], stdout=log, stderr=subprocess.STDOUT, start_new_session=True) processes.append(recorder) deadline = time.monotonic() + max(600, args.duration*10) @@ -133,8 +174,22 @@ def main(): now = driver.get_clock().now().nanoseconds*1e-9 if start is None: start = now - driver.drive(now-start) - if now-start > last_print+10: + if survey is None: + driver.drive(now-start) + elif len(surveyed) < len(survey) and (not surveyed or + now >= surveyed[-1]['command_time'] + arena_survey.STATION_SECONDS + 0.1): + if not surveyed and (args.output/'scans.csv').stat().st_size == 0: + if now-start > 5: + raise RuntimeError(f'no LiDAR scans received on {cloud_topic}') + continue + point = survey[len(surveyed)] + arena_survey.set_station(gz_exe, point, os.environ['GZ_PARTITION']) + # Sample the newest received /clock after the synchronous service. + for _ in range(10): + rclpy.spin_once(driver, timeout_sec=0) + surveyed.append({'goal': point, 'command_time': driver.get_clock().now().nanoseconds*1e-9}) + print(f'survey station {len(surveyed)}/{len(survey)} {point}', flush=True) + if survey is None and now-start > last_print+10: last_print = now-start print(f'{args.profile}: {last_print:.1f}/{args.duration:.1f} simulated seconds; odom pose={driver.pose}', flush=True) driver.publisher.publish(Twist()) @@ -142,6 +197,14 @@ def main(): raise RuntimeError('capture deadline exceeded') if recorder.returncode or not (args.output/'complete.txt').exists(): raise RuntimeError('recorder failed; inspect record.log') + if survey is not None: + if len(surveyed) != len(survey): + raise RuntimeError(f'survey reached only {len(surveyed)}/{len(survey)} stations') + selection = list(arena_survey.selected_clouds(args.output, surveyed)) + arena_survey.evaluate_stations(args.output, selection) + point_count = arena_survey.build_map(args.output, selection, args.map) + print(f'survey complete: {len(selection)} stations, {point_count} voxels; {args.map}', flush=True) + return if args.profile == 'mapping': client = driver.create_client(Trigger, '/field_localization/save_map') if not client.wait_for_service(timeout_sec=5): @@ -158,6 +221,8 @@ def main(): raise RuntimeError(f'TF validation failed: {tf_summary}') print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True) finally: + if survey is not None: + (args.output/'survey_progress.json').write_text(json.dumps(surveyed, indent=2)) driver.publisher.publish(Twist()) for process in reversed(processes): if process.poll() is None: diff --git a/tools/check_stack.py b/tools/check_stack.py index 39a9ef6..51ea31f 100644 --- a/tools/check_stack.py +++ b/tools/check_stack.py @@ -11,7 +11,6 @@ import math import os import re -import shutil import subprocess import sys import time @@ -29,6 +28,8 @@ from sensor_msgs.msg import PointCloud2, LaserScan from nav_msgs.msg import Odometry, OccupancyGrid from tf2_ros import Buffer, TransformListener +import project_env + # 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力) # @@ -96,53 +97,17 @@ def parse_gz_pose(out): return None -def _gz_bin(): - """返回 gz 可执行文件路径(系统安装的那个),找不到返回 None。 - - 不写死 `/usr/bin/gz`:换台机器 gz 可能装在别处。 - 优先用 tools/project_env.py 的统一探测逻辑(同样支持 GZ_BIN 覆盖)。 - """ - try: - import project_env # noqa: PLC0415 (同目录模块,按需导入) - gz = project_env.find_gz_bin() - if gz is not None: - return gz - except ImportError: - pass - - for cand in ('/usr/bin/gz', '/usr/local/bin/gz'): - if os.access(cand, os.X_OK): - return cand - return shutil.which('gz') - - def gz_model_pose(model_name): - """从 Gazebo 读模型的世界位姿,返回 (x, y, z, roll, pitch, yaw) 或 None。 - - 为什么要绕道 gz:ROS 里没有独立的真值来源 —— - `map -> base_link` 是由「静态 map->odom + 轮速里程计」拼出来的, - 它无法证明车真的在哪。Gazebo 的服务端才是真值。 - - 坑:sentry_up.sh 把仿真跑在 `GZ_PARTITION`(默认 sentry)分区里, - 新开的终端如果不带这个变量,`gz model` 会报 - 「Service call to [/gazebo/worlds] timed out」,看起来像仿真没跑。 - """ - partition = os.environ.get('GZ_PARTITION', 'sentry') - env = dict(os.environ) - env['GZ_PARTITION'] = partition - # 必须用系统版 gz 并清掉 LD_LIBRARY_PATH,否则会加载 ROS vendor 的库, - # 和服务端不是同一套。 - env.pop('LD_LIBRARY_PATH', None) - gz_bin = _gz_bin() - if gz_bin is None: - return None - cmd = [str(gz_bin), 'model', '-m', model_name, '-p'] + """Read the model pose from Gazebo in the simulation partition.""" + gz = project_env.find_gz_bin() + env_partition = os.environ.get('GZ_PARTITION') or 'sentry' try: - out = subprocess.run(cmd, env=env, capture_output=True, text=True, - timeout=10).stdout - except (OSError, subprocess.SubprocessError): + result = project_env.run_gz( + gz, 'model', '-m', model_name, '-p', timeout=10, + partition=env_partition) + except (OSError, subprocess.TimeoutExpired): return None - return parse_gz_pose(out) + return parse_gz_pose(result.stdout) if result.returncode == 0 else None def main(): @@ -280,7 +245,14 @@ def main(): # ---------- 4. 定位真值对照 ---------- print('\n=== 4. 定位真值对照 ===') - truth = gz_model_pose('sentry') + try: + truth = gz_model_pose('sentry') + except project_env.ProbeError as error: + truth = None + if os.environ.get('GZ_BIN'): + problems.append(str(error)) + else: + print(f' ⚠️ {error}') tf_pos = None try: got = buf.lookup_transform('map', 'base_link', rclpy.time.Time(), @@ -292,7 +264,7 @@ def main(): if truth is None: print(' ⚠️ 拿不到 Gazebo 真值(仿真没在跑,或 GZ_PARTITION 对不上)') print(' 手动试:GZ_PARTITION=%s gz model -m sentry -p' - % os.environ.get('GZ_PARTITION', 'sentry')) + % (os.environ.get('GZ_PARTITION') or 'sentry')) else: gx, gy = truth[0], truth[1] print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy)) diff --git a/tools/project_env.py b/tools/project_env.py index a78794d..73d5c8f 100644 --- a/tools/project_env.py +++ b/tools/project_env.py @@ -1,252 +1,297 @@ #!/usr/bin/env python3 -"""可移植的环境探测(Python 版),和 `scripts/env_common.sh` 保持同一套规则。 - -规则(两边一致): - -1. **一切都能被环境变量覆盖** —— 探测只提供合理默认值,不是唯一真相。 -2. **探测失败要吵** —— 宁可启动时报错,也别带着错路径跑到一半。 -3. **不写死发行版 / 版本 / 平台三元组** —— 换机器、换 ROS 版本、 - 换 Gazebo 大版本、换迁移包日期,都不该需要改代码。 - -覆盖用的环境变量: - -=============== ========================================== -变量 作用 -=============== ========================================== -ROS_SETUP 直接指定 setup.bash 全路径 -ROS_DISTRO ROS 发行版名(配合 /opt/ros/<名>/setup.bash) -SENTRY_BIN_DIR xmake 产物目录 -GZ_BIN Gazebo 可执行文件 -GZ_FORCE_VERSION gz --force-version 的值 -SENTRY_FIELD_ROOT 场地迁移包根目录 -SENTRY_MAP_YAML 栅格图 yaml 全路径 -=============== ========================================== - -用法:: - - import sys - sys.path.insert(0, str(WS / 'tools')) - import project_env - bin_dir = project_env.find_bin_dir(WS) -""" +"""Shared environment discovery for the simulation launchers and tools.""" +import argparse +import math import os +from pathlib import Path import re import shutil +import signal import subprocess import sys -from pathlib import Path +import tempfile +import time -# xmake 会产出的可执行文件,用来反推产物目录。 -_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'field_localization_node') -# 系统 gz 的常见安装位置(按优先级)。 +WORKSPACE = Path(__file__).resolve().parents[1] +_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_relay', + 'field_localization_node', 'field_localization_record', 'field_localization_replay') _GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz') +_GZ_VERSION_TIMEOUT = 5 +_FIELD_PACKAGE = Path('src/guodong_sentry_sim') + + +class ProbeError(RuntimeError): + """A required setting is missing or points to an unusable path.""" + + +def require_file(path, name): + path = Path(path).absolute() + if not path.is_file(): + raise ProbeError(f'{name} 必须指向普通文件: {path}') + return path + + +def require_directory(path, name): + path = Path(path).absolute() + if not path.is_dir(): + raise ProbeError(f'{name} 必须指向目录: {path}') + return path + + +def is_executable(path): + return Path(path).is_file() and os.access(path, os.X_OK) + + +def require_executable(path, name): + path = Path(path).absolute() + if not is_executable(path): + raise ProbeError(f'{name} 必须指向可执行的普通文件: {path}') + return path def find_ros_setup(): - """返回要 source 的 ROS `setup.bash` 路径;找不到返回 None。 - - 优先级:`ROS_SETUP` → `ROS_INSTALL_ROOT/setup.bash` → - `/opt/ros//setup.bash` → `/opt/ros/*/setup.bash` 里版本号最大的一个。 - - 已经 source 过(`AMENT_PREFIX_PATH` 非空)时返回 None —— 调用方不该重复 source, - 否则 PATH 会越叠越长。 - """ + """Return the ROS setup path, or None when ROS is already sourced.""" + explicit = os.environ.get('ROS_SETUP') + setup = require_file(explicit, 'ROS_SETUP') if explicit else None if os.environ.get('AMENT_PREFIX_PATH') and shutil.which('ros2'): return None - - explicit = os.environ.get('ROS_SETUP') - if explicit: - p = Path(explicit) - return p if p.is_file() else None + if setup is not None: + return setup root = os.environ.get('ROS_INSTALL_ROOT') - if root and (Path(root) / 'setup.bash').is_file(): - return Path(root) / 'setup.bash' + if root: + setup = Path(root) / 'setup.bash' + if setup.is_file(): + return setup.absolute() distro = os.environ.get('ROS_DISTRO') if distro: - p = Path('/opt/ros') / distro / 'setup.bash' - if p.is_file(): - return p + setup = Path('/opt/ros') / distro / 'setup.bash' + if setup.is_file(): + return setup - found = sorted(Path('/opt/ros').glob('*/setup.bash')) - if not found: - return None - # 版本号最大 —— `lyrical` > `kilted` > `jazzy` > `iron` > `humble` 这种名字 - # 排不出来,所以退化成"取最后一个",并在多于一个时提醒调用方。 - return found[-1] + candidates = sorted( + (p for p in Path('/opt/ros').glob('*/setup.bash') if p.is_file()), + key=lambda p: ([int(part) if i % 2 else part for i, part in + enumerate(re.split(r'([0-9]+)', p.parent.name))], p.parent.name), + ) + if not candidates: + raise ProbeError('找不到 ROS 2 setup.bash。请加载 ROS 环境或设置 ROS_SETUP。') + if len(candidates) > 1: + print(f'[env] 警告: 发现多个 ROS 安装,按目录名排序选择 {candidates[-1]}', file=sys.stderr) + return candidates[-1] -def ros_setup_candidates(): - """列出机器上所有 ROS `setup.bash`,用于在多版本时给出提示。""" - return sorted(Path('/opt/ros').glob('*/setup.bash')) +def find_bin_dir(ws=WORKSPACE): + """Choose a single build directory without mixing targets from different builds.""" + for name in ('SENTRY_BIN_DIR', 'NAV_BIN_DIR'): + if override := os.environ.get(name): + return require_directory(override, name) - -def find_bin_dir(ws): - """返回 xmake 产物目录(含 `self_filter` / `nav_client` 等的那个)。 - - **现行布局是 `build/bin/`** —— `src/sentry_nav/xmake.lua` 里每个 target 都 - `set_targetdir("$(builddir)/bin")`,故意不用 xmake 默认的平台三元组, - 免得 `build/<平台>/<架构>/<模式>` 这种串被抄进文档后换机器就失效。 - - 仍然兼容老布局(`build/*/*/{release,debug}`),因为别的 checkout 可能还没重建。 - """ - env = os.environ.get('SENTRY_BIN_DIR') or os.environ.get('NAV_BIN_DIR') - if env: - return Path(env) - - build = Path(ws) / 'build' - - # ① 现行布局:build/bin/ + build = Path(ws).absolute() / 'build' unified = build / 'bin' - if unified.is_dir() and any((unified / n).is_file() for n in _KNOWN_BINARIES): + if any(is_executable(unified / name) for name in _KNOWN_BINARIES): return unified - - # ② 老布局:build/<平台>/<架构>/<模式>/ for mode in ('release', 'debug'): - for d in sorted(build.glob(f'*/*/{mode}')): - if any((d / n).is_file() for n in _KNOWN_BINARIES): - return d - - # ③ 还没编译过:返回现行布局的位置 + for candidate in sorted(build.glob(f'*/*/{mode}')): + if any(is_executable(candidate / name) for name in _KNOWN_BINARIES): + return candidate return unified def find_gz_bin(): - """返回 gz 可执行文件路径;找不到返回 None。 - - 为什么要挑:`source` 过 ROS 之后,`$PATH` 上的 `gz` 是 `gz_tools_vendor` - 里那个,带着 vendor 的 RUNPATH,会加载缺 cpu-lidar 插件的 vendor 版 gz-sim。 - 所以系统安装的位置优先。 - """ - env = os.environ.get('GZ_BIN') - if env: - p = Path(env) - return p if os.access(p, os.X_OK) else None - - for cand in _GZ_CANDIDATES: - if os.access(cand, os.X_OK): - return Path(cand) - - which = shutil.which('gz') - return Path(which) if which else None + """Prefer system Gazebo, validating an explicit override before any fallback.""" + if override := os.environ.get('GZ_BIN'): + return require_executable(override, 'GZ_BIN') + for path in _GZ_CANDIDATES: + if is_executable(path): + return Path(path) + if path := shutil.which('gz'): + return require_executable(path, 'gz') + raise ProbeError('找不到 Gazebo 的 gz 可执行文件。请设置 GZ_BIN。') -def gz_version_args(): - """返回 `['--force-version', '<主版本>']`,取不到就返回 `[]`。 +def run_gz(gz, *args, timeout, partition=None): + """Run a Gazebo query in its own process group with a wall-clock deadline.""" + env = os.environ.copy() + env.pop('LD_LIBRARY_PATH', None) + if partition is not None: + env['GZ_PARTITION'] = partition + command = [str(gz), *args] + # Files let us read results after a timeout even if a descendant still holds + # an output descriptor. Only the process group started here is signalled. + with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr: + process = subprocess.Popen(command, env=env, start_new_session=True, + stdout=stdout, stderr=stderr) + try: + process.wait(timeout=timeout) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + stdout.seek(0) + stderr.seek(0) + return subprocess.CompletedProcess(command, process.returncode, + stdout.read().decode(errors='replace'), + stderr.read().decode(errors='replace')) - 写死 10 的话,装了 gz 11 就跑不起来。`GZ_FORCE_VERSION` 可强制指定。 - """ - forced = os.environ.get('GZ_FORCE_VERSION') - if forced: - return ['--force-version', str(forced)] - gz = find_gz_bin() +def gz_version_args(gz=None): + """Return force-version arguments, or warn and let Gazebo choose its default.""" if gz is None: - return [] + gz = find_gz_bin() + if forced := os.environ.get('GZ_FORCE_VERSION'): + return ['--force-version', forced] try: - out = subprocess.run([str(gz), 'sim', '--version'], - capture_output=True, text=True, timeout=15) - except (OSError, subprocess.SubprocessError): - return [] - - lines = (out.stdout or out.stderr or '').strip().splitlines() - if not lines: - return [] - m = re.match(r'\s*(\d+)', lines[0]) - return ['--force-version', m.group(1)] if m else [] + result = run_gz(gz, 'sim', '--version', timeout=_GZ_VERSION_TIMEOUT) + if result.returncode: + reason = f'退出码 {result.returncode}' + else: + version = re.match(r'^\s*([0-9]+)(?=\.|\s|$)', result.stdout.strip() or result.stderr.strip()) + if version: + return ['--force-version', version[1]] + reason = '无法解析版本' + except subprocess.TimeoutExpired: + reason = f'超时({_GZ_VERSION_TIMEOUT:g} 秒)' + except OSError as error: + reason = str(error) + print(f'[env] 警告: {gz} sim --version {reason},使用 Gazebo 默认版本。' + '可通过 GZ_FORCE_VERSION 指定主版本。', file=sys.stderr) + return [] -def find_field_root(ws): - """返回场地迁移包根目录;找不到返回 None。 +def wait_gz_clock(gz, gazebo_pid=None): + """Wait for the selected Gazebo transport to advertise /clock.""" + raw_timeout = os.environ.get('BRIDGE_WAIT_TIMEOUT') or '120' + try: + timeout = float(raw_timeout) + except ValueError: + timeout = 0 + if not math.isfinite(timeout) or timeout <= 0: + raise ProbeError(f'BRIDGE_WAIT_TIMEOUT 必须为正数: {raw_timeout}') - 不写死 `RMUL2027_map_transfer_20261016_STEP_R1` —— 换一版迁移包日期就变了。 - 找的是「含 `src/guodong_sentry_sim` 的那一层」。 - """ - env = os.environ.get('SENTRY_FIELD_ROOT') - if env: - return Path(env) - - ws = Path(ws) - for p in sorted(ws.glob('field/*/src/guodong_sentry_sim')): - if p.is_dir(): - return p.parent.parent - - for p in sorted((Path.home() / 'Gazebo_projects').glob( - '*map_transfer*/src/guodong_sentry_sim')): - if p.is_dir(): - return p.parent.parent - - return None + deadline = time.monotonic() + timeout + while (remaining := deadline - time.monotonic()) > 0: + if gazebo_pid is not None: + try: + os.kill(gazebo_pid, 0) + except ProcessLookupError as error: + raise ProbeError('Gazebo 启动失败,进程已退出') from error + try: + # Listing topics waits for a full discovery cycle (over two seconds on this host). + result = run_gz(gz, 'topic', '-e', '-t', '/clock', '-n', '1', + timeout=min(2, remaining)) + if result.returncode == 0 and result.stdout.strip(): + return + except subprocess.TimeoutExpired: + pass + time.sleep(max(0, min(1, deadline - time.monotonic()))) + raise ProbeError( + f'等待 Gazebo /clock 超时({timeout:g} 秒),请检查 GZ_PARTITION=' + f'{os.environ.get("GZ_PARTITION") or "sentry"}') -def find_map_yaml(field_root): - """返回栅格图 yaml 路径;找不到返回 None。优先 `rmul_2027.yaml`。""" - env = os.environ.get('SENTRY_MAP_YAML') - if env: - return Path(env) +def find_field_root(ws=WORKSPACE, *, explicit=None): + if explicit: + return require_directory(explicit, 'field_root') + if override := os.environ.get('SENTRY_FIELD_ROOT'): + return require_directory(override, 'SENTRY_FIELD_ROOT') + for parent, pattern in ((Path(ws).absolute() / 'field', '*'), + (Path.home() / 'Gazebo_projects', '*map_transfer*')): + for candidate in sorted(parent.glob(pattern)): + if (candidate / _FIELD_PACKAGE).is_dir(): + return candidate + raise ProbeError('找不到场地迁移包。请设置 SENTRY_FIELD_ROOT。') + +def find_map_yaml(field_root=None, *, explicit=None, ws=WORKSPACE): + if explicit: + return require_file(explicit, 'map') + if override := os.environ.get('SENTRY_MAP_YAML'): + return require_file(override, 'SENTRY_MAP_YAML') if field_root is None: - return None - - maps = Path(field_root) / 'src' / 'guodong_sentry_sim' / 'maps' + field_root = find_field_root(ws) + maps = Path(field_root) / _FIELD_PACKAGE / 'maps' preferred = maps / 'rmul_2027' / 'rmul_2027.yaml' if preferred.is_file(): return preferred - - cands = sorted(maps.glob('*/*.yaml')) - return cands[0] if cands else None + candidates = sorted(p for p in maps.glob('*/*.yaml') if p.is_file()) + for candidate in candidates: + if candidate.name == 'rmul_2027.yaml': + return candidate + if candidates: + return candidates[0] + raise ProbeError(f'{maps} 下找不到栅格图 YAML。请设置 SENTRY_MAP_YAML。') def report(ws): - """打印所有探测结果,排查路径问题时用。""" - field_root = find_field_root(ws) setup = find_ros_setup() - if setup: - ros_line = str(setup) - elif os.environ.get('AMENT_PREFIX_PATH'): - ros_line = f'<已 source: {os.environ["AMENT_PREFIX_PATH"]}>' - else: - ros_line = '<找不到>' - print(f' ROS setup : {ros_line}') - print(f' BIN_DIR : {find_bin_dir(ws)}') - print(f' GZ_BIN : {find_gz_bin()}') - print(f' gz 版本参数 : {" ".join(gz_version_args()) or "<无>"}') + bin_dir = find_bin_dir(ws) + field_root = find_field_root(ws) + map_yaml = find_map_yaml(field_root) + gz = find_gz_bin() + versions = ' '.join(gz_version_args(gz)) + print(f'仓库根: {ws}') + print(f' ROS setup : {setup or "<已 source>"}') + print(f' BIN_DIR : {bin_dir}') + print(f' GZ_BIN : {gz}') + print(f' gz 版本参数 : {versions or "<无>"}') print(f' FIELD_ROOT : {field_root}') - print(f' MAP_YAML : {find_map_yaml(field_root)}') + print(f' MAP_YAML : {map_yaml}') + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE) + queries = parser.add_mutually_exclusive_group() + for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup'): + queries.add_argument(f'--{query}', dest='query', action='store_const', const=query) + for query in ('gz-version-args-lines', 'wait-gz-clock'): + queries.add_argument(f'--{query}', dest='query', action='store_const', const=query, + help=argparse.SUPPRESS) + parser.add_argument('--field-root', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--gazebo-pid', type=int, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if args.field_root is not None and args.query != 'map': + parser.error('--field-root requires --map') + if args.gazebo_pid is not None and (args.query != 'wait-gz-clock' or args.gazebo_pid <= 0): + parser.error('--gazebo-pid requires --wait-gz-clock and a positive PID') + + try: + ws = require_directory(args.workspace, 'workspace') + match args.query: + case 'bin-dir': + print(find_bin_dir(ws)) + case 'field': + print(find_field_root(ws)) + case 'map': + print(find_map_yaml(args.field_root, ws=ws)) + case 'gz': + print(find_gz_bin()) + case 'gz-version-args' | 'gz-version-args-lines': + separator = '\n' if args.query == 'gz-version-args-lines' else ' ' + versions = gz_version_args() + if versions: + print(separator.join(versions)) + elif args.query == 'gz-version-args': + print() + case 'ros-setup': + print(find_ros_setup() or '') + case 'wait-gz-clock': + wait_gz_clock(find_gz_bin(), args.gazebo_pid) + case None: + report(ws) + except (ProbeError, OSError) as error: + print(f'[env] {error}', file=sys.stderr) + return 1 + return 0 if __name__ == '__main__': - # 支持直接从命令行取单个值,方便写进文档当可移植的一行命令: - # NAV=$(python3 tools/project_env.py --bin-dir)/nav_client - # python3 tools/project_env.py --map / --field / --gz / --bin-dir - argv = sys.argv[1:] - ws_arg = str(Path(__file__).resolve().parents[1]) - if argv and Path(argv[0]).is_dir(): - ws_arg = argv.pop(0) - - if argv: - opt = argv[0] - if opt == '--bin-dir': - print(find_bin_dir(ws_arg)) - elif opt == '--field': - print(find_field_root(ws_arg)) - elif opt == '--map': - print(find_map_yaml(find_field_root(ws_arg))) - elif opt == '--gz': - print(find_gz_bin()) - elif opt == '--gz-version-args': - print(' '.join(gz_version_args())) - elif opt == '--ros-setup': - print(find_ros_setup() or '') - else: - print(f'未知选项 {opt},可用:--bin-dir --field --map --gz ' - '--gz-version-args --ros-setup', file=sys.stderr) - sys.exit(2) - sys.exit(0) - - print(f'仓库根: {ws_arg}') - report(ws_arg) + sys.exit(main()) diff --git a/tools/test_motion_interlock.py b/tools/tests/test_motion_interlock.py similarity index 89% rename from tools/test_motion_interlock.py rename to tools/tests/test_motion_interlock.py index 291b3c6..4670cf2 100644 --- a/tools/test_motion_interlock.py +++ b/tools/tests/test_motion_interlock.py @@ -5,14 +5,23 @@ import os from pathlib import Path import signal import subprocess +import sys import time import uuid +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import project_env + def main(): parser=argparse.ArgumentParser(description=__doc__) - parser.add_argument('--binary',type=Path,default=Path(__file__).resolve().parents[1]/'build/bin/cmd_vel_relay') + parser.add_argument('--binary', type=Path) args=parser.parse_args() + try: + binary = args.binary or project_env.find_bin_dir()/'cmd_vel_relay' + binary = project_env.require_executable(binary, 'cmd_vel_relay') + except project_env.ProbeError as error: + parser.exit(1, f'{parser.prog}: {error}\n') os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40), FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1') import rclpy @@ -31,7 +40,7 @@ def main(): return response services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel) for name in ['/navigate_to_pose','/navigate_through_poses']] - process=subprocess.Popen([str(args.binary),'--ros-args','-p','navigation_mode:=true'], + process=subprocess.Popen([str(binary),'--ros-args','-p','navigation_mode:=true'], start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True) checks=0 def check(ok,message): diff --git a/tools/test_nav2_startup.py b/tools/tests/test_nav2_startup.py similarity index 97% rename from tools/test_nav2_startup.py rename to tools/tests/test_nav2_startup.py index a2c5311..11a1e56 100644 --- a/tools/test_nav2_startup.py +++ b/tools/tests/test_nav2_startup.py @@ -9,6 +9,8 @@ import time import uuid from types import SimpleNamespace +INTERNAL_TOOLS = Path(__file__).resolve().parents[1] / '_internal' +sys.path.insert(0, str(INTERNAL_TOOLS)) from dds_environment import defaults @@ -73,7 +75,7 @@ def main(): services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters), node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)] services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed] - command = [sys.executable, str(Path(__file__).with_name('nav2_startup.py'))] + command = [sys.executable, str(INTERNAL_TOOLS / 'nav2_startup.py')] def run(arguments): process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, diff --git a/tools/test_nav2_supervisor.py b/tools/tests/test_nav2_supervisor.py similarity index 96% rename from tools/test_nav2_supervisor.py rename to tools/tests/test_nav2_supervisor.py index 3b55aaa..27d4121 100644 --- a/tools/test_nav2_supervisor.py +++ b/tools/tests/test_nav2_supervisor.py @@ -5,6 +5,7 @@ import subprocess import sys import tempfile +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal')) from run_nav2 import stop_owned, supervise diff --git a/tools/tests/test_project_env.py b/tools/tests/test_project_env.py new file mode 100644 index 0000000..051008c --- /dev/null +++ b/tools/tests/test_project_env.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +"""Exercise the shared environment probes through both CLI entry points.""" + +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time +import unittest +from unittest.mock import patch + + +TOOLS = Path(__file__).resolve().parents[1] +WORKSPACE = TOOLS.parent +SCRIPTS = WORKSPACE / 'src/sentry_sim/scripts' +sys.path.insert(0, str(TOOLS)) +import project_env + + +class EnvironmentTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory(prefix='sentry env ') + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.env = os.environ.copy() + self.env['PYTHONDONTWRITEBYTECODE'] = '1' + for name in ('ROS_SETUP', 'ROS_INSTALL_ROOT', 'ROS_DISTRO', 'AMENT_PREFIX_PATH', + 'SENTRY_BIN_DIR', 'NAV_BIN_DIR', 'SENTRY_FIELD_ROOT', 'SENTRY_MAP_YAML', + 'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION'): + self.env.pop(name, None) + + def run_command(self, command, **overrides): + return subprocess.run(command, cwd=self.root, env={**self.env, **overrides}, + capture_output=True, text=True, timeout=12) + + def cli(self, *args, **overrides): + return self.run_command([sys.executable, str(TOOLS/'project_env.py'), *map(str, args)], + **overrides) + + def shell(self, *args, **overrides): + return self.run_command(['bash', '-c', 'source "$1"; shift; "$@"', + 'env-test', str(SCRIPTS/'env_common.sh'), *map(str, args)], + **overrides) + + def executable(self, path, script='exit 0'): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text('#!/bin/bash\n' + script + '\n') + path.chmod(0o755) + return path + + def expect_value(self, result, value): + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f'{value}\n') + + def expect_error(self, result, text, code=1): + self.assertEqual(result.returncode, code, result.stderr) + self.assertEqual(result.stdout, '') + self.assertIn(text, result.stderr) + + def test_map_overrides(self): + field = self.root/'field with spaces' + field.mkdir() + yaml = self.root/'custom map.yaml' + yaml.touch() + for bad in (self.root/'missing.yaml', field): + with self.subTest(path=bad): + self.expect_error(self.cli('--map', SENTRY_MAP_YAML=str(bad)), 'SENTRY_MAP_YAML') + self.expect_error(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=str(bad)), + 'SENTRY_MAP_YAML') + self.expect_value(self.cli('--map', SENTRY_MAP_YAML=yaml.name), yaml) + self.expect_value(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=yaml.name), yaml) + with patch.dict(os.environ, {'SENTRY_MAP_YAML': str(field)}): + self.assertEqual(project_env.find_map_yaml(field, explicit=yaml), yaml) + + def test_map_search_order(self): + field = self.root/'field' + maps = field/'src/guodong_sentry_sim/maps' + canonical = maps/'rmul_2027/rmul_2027.yaml' + named_first = maps/'a/rmul_2027.yaml' + named_last = maps/'z/rmul_2027.yaml' + fallback = maps/'a/001.yaml' + for path in (canonical, named_first, named_last, fallback): + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + (maps/'a/000.yaml').mkdir() + + def expect_map(path): + self.expect_value(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), path) + self.expect_value(self.shell('env_map_yaml', field), path) + + expect_map(canonical) + canonical.unlink() + expect_map(named_first) + named_first.unlink() + expect_map(named_last) + named_last.unlink() + expect_map(fallback) + fallback.unlink() + self.expect_error(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), 'SENTRY_MAP_YAML') + self.expect_error(self.shell('env_map_yaml', field), 'SENTRY_MAP_YAML') + + def test_field_and_ros_setup_overrides(self): + field = self.root/'field' + other = self.root/'other field' + field.mkdir() + other.mkdir() + self.expect_error(self.cli('--field', SENTRY_FIELD_ROOT=str(field/'missing')), + 'SENTRY_FIELD_ROOT') + self.expect_error(self.shell('env_field_root', self.root, + SENTRY_FIELD_ROOT=str(field/'missing')), 'SENTRY_FIELD_ROOT') + self.expect_value(self.cli('--field', SENTRY_FIELD_ROOT=field.name), field) + with patch.dict(os.environ, {'SENTRY_FIELD_ROOT': str(field)}): + self.assertEqual(project_env.find_field_root(self.root, explicit=other), other) + + setup = self.root/'setup with spaces.bash' + setup.write_text('export SENTRY_SETUP_TEST=loaded\n') + for invalid in (field, self.root/'missing.bash'): + self.expect_error(self.cli('--ros-setup', ROS_SETUP=str(invalid)), 'ROS_SETUP') + self.expect_error(self.shell('env_source_ros', ROS_SETUP=str(invalid)), 'ROS_SETUP') + self.expect_value(self.cli('--ros-setup', ROS_SETUP=setup.name), setup) + result = self.run_command( + ['bash', '-c', 'source "$1"; env_source_ros && printf "%s\\n" "$SENTRY_SETUP_TEST"', + 'env-test', str(SCRIPTS/'env_common.sh')], ROS_SETUP=setup.name) + self.expect_value(result, 'loaded') + ros2 = self.executable(self.root/'ros bin/ros2') + self.expect_value(self.cli('--ros-setup', ROS_SETUP=str(setup), AMENT_PREFIX_PATH='/fake', + PATH=f'{ros2.parent}:{self.env["PATH"]}'), '') + + def test_cli_status_and_stdout(self): + self.expect_error(self.cli('--unknown'), 'unrecognized arguments', code=2) + self.expect_error(self.cli('--map', '--gz'), 'not allowed', code=2) + self.expect_error(self.cli('--gz', '--field-root', self.root), 'requires --map', code=2) + self.expect_error(self.cli('--bin-dir', SENTRY_BIN_DIR=str(self.root/'missing')), + 'SENTRY_BIN_DIR') + with (patch.object(project_env, '_GZ_CANDIDATES', ()), + patch.object(project_env.shutil, 'which', return_value=None), + patch.dict(os.environ, {'GZ_BIN': ''})): + with self.assertRaisesRegex(project_env.ProbeError, '找不到 Gazebo'): + project_env.find_gz_bin() + + def test_build_directory_priority_matches_shell(self): + build = self.root/'build' + unified = build/'bin' + + def expect_bin(path, **overrides): + self.expect_value(self.cli(self.root, '--bin-dir', **overrides), path) + self.expect_value(self.shell('env_bin_dir', self.root, **overrides), path) + + expect_bin(unified) + debug = self.executable(build/'a/first/debug/self_filter') + expect_bin(debug.parent) + release_last = self.executable(build/'z/last/release/nav_client') + release_first = self.executable(build/'a/second/release/odom_tf') + (build/'a/first/release').mkdir() + (build/'a/first/release/nav_client').touch() + expect_bin(release_first.parent) + (unified/'self_filter').mkdir(parents=True) + (unified/'nav_client').touch() + expect_bin(release_first.parent) + self.executable(unified/'cmd_vel_relay') + expect_bin(unified) + expect_bin(release_last.parent, NAV_BIN_DIR=str(release_last.parent)) + expect_bin(release_first.parent, SENTRY_BIN_DIR=str(release_first.parent), + NAV_BIN_DIR=str(release_last.parent)) + + def test_gz_executable_validation_matches_shell(self): + fake = self.executable(self.root/'fake gazebo') + alias = self.root/'link to gz' + alias.symlink_to(fake) + denied = self.root/'non-executable' + denied.touch() + for path in (self.root, denied, self.root/'missing'): + with self.subTest(path=path): + self.expect_error(self.cli('--gz', GZ_BIN=str(path)), 'GZ_BIN') + self.expect_error(self.shell('env_gz_bin', GZ_BIN=str(path)), 'GZ_BIN') + self.expect_error(self.cli('--gz-version-args', GZ_FORCE_VERSION='12', + GZ_BIN=str(path)), 'GZ_BIN') + self.expect_value(self.cli('--gz', GZ_BIN=alias.name), alias) + self.expect_value(self.shell('env_gz_bin', GZ_BIN=alias.name), alias) + + def test_version_and_explicit_override_matches_shell(self): + fake = self.executable(self.root/'fake gz', ''' +if [[ "$*" != "sim --version" || -v LD_LIBRARY_PATH ]]; then exit 4; fi +touch "$SENTRY_GZ_MARKER" +echo ' 10.5.0 ' +''') + marker = self.root/'probe-called' + env = dict(GZ_BIN=str(fake), LD_LIBRARY_PATH='/test/vendor', SENTRY_GZ_MARKER=str(marker)) + self.expect_value(self.cli('--gz-version-args', **env), '--force-version 10') + self.assertTrue(marker.is_file()) + self.expect_value(self.shell('env_gz_version_args', **env), '--force-version\n10') + marker.unlink() + self.expect_value(self.cli('--gz-version-args', GZ_FORCE_VERSION='12', **env), + '--force-version 12') + self.expect_value(self.shell('env_gz_version_args', GZ_FORCE_VERSION='12', **env), + '--force-version\n12') + self.assertFalse(marker.exists()) + + def test_version_nonzero_and_unparseable_warn_and_continue(self): + fake = self.root/'gz' + for script, reason in (("echo '10.0'; exit 7", '退出码 7'), ('echo unknown', '无法解析版本')): + self.executable(fake, script) + cli = self.cli('--gz-version-args', GZ_BIN=str(fake)) + shell = self.shell('env_gz_version_args', GZ_BIN=str(fake)) + self.expect_value(cli, '') + self.assertIn(reason, cli.stderr) + self.assertEqual(shell.returncode, 0, shell.stderr) + self.assertEqual(shell.stdout, '') + self.assertIn(reason, shell.stderr) + + def test_version_timeout_stops_owned_process_group(self): + marker = self.root/'child-pids' + fake = self.executable(self.root/'slow gz', ''' +trap '' TERM +sleep 30 & +printf '%s %s\\n' "$$" "$!" > "$SENTRY_GZ_MARKER" +wait +''') + start = time.monotonic() + result = self.shell('env_gz_version_args', GZ_BIN=str(fake), SENTRY_GZ_MARKER=str(marker)) + elapsed = time.monotonic() - start + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, '') + self.assertIn('超时', result.stderr) + self.assertGreaterEqual(elapsed, 5) + self.assertLess(elapsed, 8) + for pid in marker.read_text().split(): + try: + state = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0] + except FileNotFoundError: + continue + self.assertEqual(state, 'Z', f'Gazebo probe process {pid} is still live') + + def test_bridge_does_not_start_without_clock(self): + fake_gz = self.executable(self.root/'fake gz', ''' +[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4 +sleep 30 +''') + fake_ros2 = self.executable(self.root/'bin/ros2', 'echo "bridge started"') + env = dict(BRIDGE_WAIT_TIMEOUT='0.3', GZ_BIN=str(fake_gz), LD_LIBRARY_PATH='/vendor', + PATH=f'{fake_ros2.parent}:{self.env["PATH"]}', GZ_PARTITION='isolated_test') + start = time.monotonic() + result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env) + self.assertLess(time.monotonic() - start, 2) + self.expect_error(result, '等待 Gazebo /clock 超时') + self.assertIn('isolated_test', result.stderr) + self.executable(fake_gz, ''' +[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4 +echo 'sim { sec: 1 }' +''') + result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('bridge started', result.stdout) + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/tools/validate_lio_navigation.py b/tools/validate_lio_navigation.py deleted file mode 100644 index 3b96642..0000000 --- a/tools/validate_lio_navigation.py +++ /dev/null @@ -1,334 +0,0 @@ -#!/usr/bin/env python3 -"""Run an isolated Gazebo navigation scenario and score it using simulator truth.""" -import argparse -import hashlib -import json -import math -import os -from pathlib import Path -import signal -import subprocess -import time -import uuid -from collections import Counter - -import rclpy -from rclpy.node import Node -from rclpy.parameter import Parameter -from lifecycle_msgs.srv import GetState -from tf2_msgs.msg import TFMessage -from nav2_msgs.srv import IsPathValid -from nav_msgs.msg import Odometry -from geometry_msgs.msg import PoseStamped, Twist -from rclpy.qos import qos_profile_sensor_data -from std_msgs.msg import Bool -from rcl_interfaces.srv import GetParameters -from std_srvs.srv import Trigger -from rclpy.utilities import get_rmw_implementation_identifier -from nav2_startup import path_probe_request - -from dds_environment import defaults as dds_defaults -from lio_metrics import cylinder_clearance, metrics -from verify_lio_stack import NODES, process_environment - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--map', type=Path, required=True) - parser.add_argument('--launcher', choices=['shell', 'python'], default='shell') - parser.add_argument('--output', type=Path, required=True) - parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y')) - parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]', - help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests') - parser.add_argument('--timeout', type=float, default=420.0, - help='whole-stack validation deadline, including up to three startup attempts') - parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear') - parser.add_argument('--obstacle-x',type=float,default=-4.0) - parser.add_argument('--obstacle-y',type=float,default=-1.5) - parser.add_argument('--obstacle-radius',type=float,default=0.22) - parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load') - args = parser.parse_args() - if not args.map.is_file(): - parser.error('map missing') - if args.output.exists(): - parser.error('output must be a new directory') - args.output.mkdir(parents=True) - session = uuid.uuid4().hex[:12] - os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}', - ROS2CLI_DISABLE_DAEMON='1', - HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization', - LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()), - LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve())) - os.environ.update(dds_defaults(os.environ)) - workspace = Path(__file__).resolve().parents[1] - params_file = workspace/'src/sentry_sim/config/nav2_params.yaml' - runtime = { - 'domain': os.environ['ROS_DOMAIN_ID'], - 'partition': os.environ['GZ_PARTITION'], - 'scenario': args.scenario, - 'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius], - 'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(), - } - (args.output/'runtime.json').write_text(json.dumps(runtime, indent=2)) - log = None - record_log = open(args.output/'record.log', 'w', encoding='utf8') - recorder = subprocess.Popen([str(workspace/'build/bin/field_localization_record'), '--ros-args', - '-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset', - '-p', 'duration_sec:=600.0'], stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True) - if args.launcher == 'shell': - command = ['bash', str(workspace/'scripts/sentry_up.sh')] - else: - command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'), - 'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}'] - log = open(args.output/'stack.log', 'w', encoding='utf8') - started = time.monotonic() - process = subprocess.Popen(command, cwd=workspace, start_new_session=True, - stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT) - rclpy.init() - node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)]) - publishers = set() - samples = {'truth': [], 'estimate': []} - health_events=[] - actuator=[] - subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100) - subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid', - lambda msg:health_events.append((time.monotonic(),msg.data)),10) - subscriptions = [] - def sample(message, name): - p = message.pose.pose if name == 'estimate' else message.pose - samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec, - p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w]) - subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth', - lambda msg: sample(msg, 'truth'), qos_profile_sensor_data)) - subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry', - lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data)) - counts = {'map_to_odom': 0, 'map_to_base_link': 0} - - def on_tf(msg, info): - for transform in msg.transforms: - if transform.header.frame_id != 'map': - continue - if transform.child_frame_id == 'odom': - gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid - publishers.add(json.dumps(gid, sort_keys=True, default=str)) - counts['map_to_odom'] += 1 - if transform.child_frame_id == 'base_link': - counts['map_to_base_link'] += 1 - - subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500) - clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES} - path_client = node.create_client(IsPathValid, '/is_path_valid') - active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active') - parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters') - states = {} - processes = [] - rviz = None - goal = None - reached_readiness = False - result = {} - try: - if args.rviz: - rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d', - str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args', - '-p', 'use_sim_time:=true'], - env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'}, - start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) - deadline = time.monotonic()+args.timeout - last_check = 0.0 - stable_since = None - manager_completed = False - while time.monotonic() < deadline: - rclpy.spin_once(node, timeout_sec=0.1) - if process.poll() is not None: - raise RuntimeError('stack exited') - if time.monotonic()-last_check < 0.5: - continue - last_check = time.monotonic() - if not processes and time.monotonic()-started > 8: - processes = process_environment(process.pid) - states = {} - pending = {} - for name, client in clients.items(): - if not client.service_is_ready(): - continue - pending[name] = client.call_async(GetState.Request()) - poll_end = time.monotonic()+1 - while time.monotonic() < poll_end and any(not f.done() for f in pending.values()): - rclpy.spin_once(node, timeout_sec=0.02) - for name, future in pending.items(): - if future.done() and future.result(): - states[name] = future.result().current_state.id - else: - clients[name].remove_pending_request(future) - log_path = args.output/'stack.log' - text = log_path.read_text(errors='replace') if log_path.exists() else '' - manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line - for line in text.splitlines()) - if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]: - if stable_since is None: - stable_since = time.monotonic() - if time.monotonic()-stable_since >= 2: - reached_readiness = True - break - else: - stable_since = None - processes = process_environment(process.pid) - names = sorted(set(node.get_node_names())) - path_ready = path_client.wait_for_service(timeout_sec=2) - path_response = None - if path_ready: - future = path_client.call_async(path_probe_request()) - rclpy.spin_until_future_complete(node, future, timeout_sec=3) - if future.done() and future.result() is not None: - path_response = str(future.result()) - manager_active = False - if active_client.wait_for_service(timeout_sec=1): - future = active_client.call_async(Trigger.Request()) - rclpy.spin_until_future_complete(node, future, timeout_sec=2) - manager_active = bool(future.done() and future.result() and future.result().success) - managed_nodes = [] - if parameter_client.wait_for_service(timeout_sec=1): - future = parameter_client.call_async(GetParameters.Request(names=['node_names'])) - rclpy.spin_until_future_complete(node, future, timeout_sec=2) - if future.done() and future.result() and future.result().values: - managed_nodes = list(future.result().values[0].string_array_value) - result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started, - 'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()), - 'rmw': get_rmw_implementation_identifier(), 'processes': processes, - 'node_counts': dict(Counter(node.get_node_names())), - 'services': dict(node.get_service_names_and_types()), - 'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))), - 'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))}, - 'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response, - 'topic_qos':{topic:[{'node':p.node_name,'reliability':str(p.qos_profile.reliability)} for p in node.get_publishers_info_by_topic(topic)] for topic in ['/scan/points','/scan/points_filtered','/imu']}, - 'manager_active': manager_active, 'managed_nodes': managed_nodes, - 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names, - 'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts} - result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None - and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes) - and all(states.get(name) == 3 for name in NODES) and not result['amcl_present'] - and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0 - and counts['map_to_base_link'] == 0) - (args.output/'result.json').write_text(json.dumps(result, indent=2)) - if args.scenario in ('cylinder','blocked') and result['passed']: - # Obstacle lies on the initial straight corridor; a route around the cylinder exists. - shape = f'{args.obstacle_radius}0.8' - pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0' - if args.scenario == 'blocked': - shape = '1.6 1.6 0.8' - pose = '0 0 0.4 0 0 0' - sdf = f'true{pose}{shape}{shape}' - gz = subprocess.run(['/usr/bin/gz', 'service', '-s', '/world/rmul_arena/create', - '--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000', - '--req', 'sdf: '+json.dumps(sdf)], capture_output=True,text=True,timeout=10) - (args.output/'obstacle.log').write_text(gz.stdout+gz.stderr) - if gz.returncode or 'data: true' not in gz.stdout: - raise RuntimeError('obstacle insertion failed') - until=time.monotonic()+2 - while time.monotonic()=5 and actuator and sum(abs(v) for v in actuator[-1][1:])>0.1: - owned=process_environment(process.pid) - sensors=[p['pid'] for p in owned if p['executable'] and Path(p['executable'][0]).name=='self_filter'] - if len(sensors)!=1: - raise RuntimeError('cannot identify the owned self_filter for fault injection') - fault_time=time.monotonic();os.kill(sensors[0],signal.SIGTERM) - if goal.poll() is None: - os.killpg(goal.pid,signal.SIGINT) - goal.wait(timeout=5) - goal.stdout_text=(args.output/'goal.log').read_text() - if args.scenario == 'blocked': - terminal_time = time.monotonic() - while time.monotonic() - terminal_time < 0.5: - rclpy.spin_once(node, timeout_sec=0.02) - result['blocked_zero_output'] = bool( - actuator and actuator[-1][0] > terminal_time and actuator[-1][1:] == (0, 0, 0) - ) - result['passed'] = result['passed'] and result['blocked_zero_output'] - result.update(counts) - result['map_to_odom_publishers'] = len(publishers) - result['amcl_present'] = 'amcl' in node.get_node_names() - result['passed'] = (result['passed'] and len(publishers) == 1 - and counts['map_to_base_link'] == 0 - and not result['amcl_present']) - result['goal_exit_code'] = goal.returncode - if args.scenario=='lidar_loss': - stops=[t for t,x,y,z in actuator if fault_time is not None and t>=fault_time and x==0 and y==0 and z==0] - result['fault_stop_delay_sec']=min(stops)-fault_time if stops else None - result['fault_goal_canceled']='结果: ❌ CANCELED' in goal.stdout_text - result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout_text - result['goal_elapsed_wall_sec']=time.monotonic()-goal_start_wall - result['trajectory_metrics']=metrics(samples['estimate'],samples['truth']) - truth_goal=[row for row in samples['truth'] if row[0]>=goal_start_sim] - result['truth_goal_error_m']=math.hypot(truth_goal[-1][1]-args.goal[0],truth_goal[-1][2]-args.goal[1]) if truth_goal else None - result['minimum_cylinder_clearance_m']=min(cylinder_clearance(row,args.obstacle_x,args.obstacle_y,args.obstacle_radius) for row in truth_goal) if truth_goal and args.scenario=='cylinder' else None - result['health_failures_during_goal']=sum(not value for stamp,value in health_events if stamp>=goal_start_wall) - quality=result['trajectory_metrics'] - result['passed']=result['passed'] and quality['matched']>100 and quality['rpe_pairs']>0 and quality['maximum_position_error_m']<0.25 and quality['ate_translation_m']<0.1 - if args.scenario not in ('blocked','lidar_loss'): - result['passed']=result['passed'] and result['truth_goal_error_m'] is not None and result['truth_goal_error_m']<=0.30 - if result['minimum_cylinder_clearance_m'] is not None: - result['passed']=result['passed'] and result['minimum_cylinder_clearance_m']>=0 - result['passed'] = result['passed'] and ((args.scenario == 'blocked' and '结果: ❌ ABORTED' in goal.stdout_text) or (args.scenario == 'lidar_loss' and result['fault_goal_canceled'] and result['fault_stop_delay_sec'] is not None and result['fault_stop_delay_sec']<0.5) or (goal.returncode == 0 and result['goal_succeeded'])) - (args.output/'result.json').write_text(json.dumps(result, indent=2)) - print(json.dumps({k: v for k, v in result.items() if k not in - ('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True) - if not result['passed']: - raise RuntimeError('stack integration validation failed') - except Exception as error: - result.update(passed=False, error=str(error)) - (args.output/'result.json').write_text(json.dumps(result, indent=2)) - raise - finally: - _ = subscription, subscriptions, subscriptions_health, subscription_actuator - (args.output/'health_events.json').write_text(json.dumps(health_events)) - for name, rows in samples.items(): - with open(args.output/(name+'.tum'),'w') as output: - for row in rows: - output.write(' '.join(map(str,row))+'\n') - if goal is not None and goal.poll() is None: - os.killpg(goal.pid, signal.SIGINT) - try: - goal.wait(timeout=5) - except subprocess.TimeoutExpired: - os.killpg(goal.pid, signal.SIGKILL) - goal.wait() - if recorder.poll() is None: - os.killpg(recorder.pid, signal.SIGINT) - try: - recorder.wait(timeout=10) - except subprocess.TimeoutExpired: - os.killpg(recorder.pid, signal.SIGKILL) - recorder.wait() - record_log.close() - if process.poll() is None: - os.killpg(process.pid, signal.SIGINT) - try: - process.wait(timeout=20) - except subprocess.TimeoutExpired: - os.killpg(process.pid, signal.SIGKILL) - process.wait() - if rviz is not None: - os.killpg(rviz.pid, signal.SIGINT) - try: - rviz.wait(timeout=5) - except subprocess.TimeoutExpired: - os.killpg(rviz.pid, signal.SIGKILL) - rviz.wait() - if log: - log.close() - node.destroy_node() - rclpy.shutdown() - - -if __name__ == '__main__': - main() diff --git a/tools/validation/compare_lio_maps.py b/tools/validation/compare_lio_maps.py new file mode 100644 index 0000000..1d46b09 --- /dev/null +++ b/tools/validation/compare_lio_maps.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Replay the same recorded southeast scans against two maps.""" + +import argparse +from bisect import bisect_left +import csv +import json +from pathlib import Path +import statistics +import subprocess +import sys + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import project_env + + +def rotation(quaternion): + x, y, z, w = np.asarray(quaternion)/np.linalg.norm(quaternion) + return np.array(((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)), + (2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)), + (2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y)))) + + +def east_scans(dataset): + rows = [list(map(float, l.split())) for l in (dataset/'truth.tum').read_text().splitlines()] + if not rows: + raise ValueError('southeast evaluation requires recorded ground truth') + times = [r[0] for r in rows] + mask = set() + with (dataset/'scans.csv').open() as scans: + for entry in csv.DictReader(scans): + stamp = float(entry['timestamp']) + index = bisect_left(times, stamp) + if index == len(times) or (index > 0 and stamp-times[index-1] < times[index]-stamp): + index -= 1 + time, x, y = rows[index][:3] + if abs(time-stamp) <= 0.05 and x >= 4 and y <= -1.5: + mask.add(stamp) + return mask + + +def compare_trace(path, stamps, imu_from_base): + inliers, horizontal, horizontal_prior = [], [], [] + degenerate = x_weak = full = 0 + x, y, z = imu_from_base + skew = np.array(((0, -z, y), (z, 0, -x), (-y, x, 0))) + with path.open() as trace: + for row in csv.DictReader(trace): + phase = row['phase'] + stamp = float(row['scan_time']) + if stamp not in stamps or phase == 'candidate': + continue + p = np.array([[float(row[f'P{i}_{j}']) for j in range(18)] for i in range(18)]) + j = np.zeros((2, 18)) + j[0, 0] = j[1, 1] = 1 + j[:, 6:9] = -(rotation([float(row[k]) for k in ('qx','qy','qz','qw')])@skew)[:2, :] + sigma = 3*float(np.sqrt(max(0, np.linalg.eigvalsh(j@p@j.T)[-1]))) + if phase == 'prediction': + if row['registration_stage'] != 'NOT_RUN': + horizontal_prior.append(sigma) + continue + horizontal.append(sigma) + inliers.append(int(row['inliers'])) + full += row['mode'] == 'FULL' + dims = int(row['degenerate']) + if dims: + h = np.array([[float(row[f'H{i}_{j}']) for j in range(6)] for i in range(6)]) + if np.any(h): + vt = np.linalg.svd(h)[2] + x_weak += int(np.linalg.norm(vt[-dims:, 0]) >= 0.8) + degenerate += 1 + if not inliers: + raise RuntimeError('replay did not include the recorded southeast scans') + return {'east_scans': len(inliers), 'accepted': full, + 'median_inliers': statistics.median(inliers), 'degenerate_scans': degenerate, + 'x_weak_scans': x_weak, 'maximum_horizontal_3sigma_m': max(horizontal), + 'maximum_prior_horizontal_3sigma_m': max(horizontal_prior, default=None)} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('dataset', 'baseline', 'candidate', 'output'): + parser.add_argument(f'--{name}', type=Path, required=True) + args = parser.parse_args() + stamps = east_scans(args.dataset) + if len(stamps) < 10: + parser.error('verification dataset must contain at least ten scans in x >= 4, y <= -1.5') + transform = next(line for line in (args.dataset/'config.txt').read_text().splitlines() + if line.startswith('base_from_imu ')).split()[1:] + extrinsic = list(map(float, transform)) + imu_from_base = -rotation(extrinsic[3:]).T @ extrinsic[:3] + exe = project_env.require_executable(project_env.find_bin_dir()/'field_localization_replay', + 'field_localization_replay') + args.output.mkdir(parents=True) + reports = {} + for name, world_map in (('baseline', args.baseline), ('candidate', args.candidate)): + directory = args.output/name + subprocess.run([str(exe), '--dataset', str(args.dataset), '--mode', 'localization', + '--map', str(world_map), '--output', str(directory)], check=True) + reports[name] = compare_trace(directory/'filter_trace.csv', stamps, imu_from_base) + content = json.dumps(reports, indent=2) + (args.output/'southeast.json').write_text(content+'\n') + print(content) + + +if __name__ == '__main__': + main() diff --git a/tools/lio_metrics.py b/tools/validation/lio_metrics.py similarity index 100% rename from tools/lio_metrics.py rename to tools/validation/lio_metrics.py diff --git a/tools/run_lio_matrix.py b/tools/validation/run_lio_matrix.py similarity index 94% rename from tools/run_lio_matrix.py rename to tools/validation/run_lio_matrix.py index b7168a2..3d947e4 100644 --- a/tools/run_lio_matrix.py +++ b/tools/validation/run_lio_matrix.py @@ -21,14 +21,15 @@ def main(): parser.error('repeats must be positive') if args.output.exists():parser.error('output must be new') args.output.mkdir(parents=True) - root=Path(__file__).resolve().parents[1] + script_dir = Path(__file__).resolve().parent + root = script_dir.parents[1] results=[] for scenario in args.scenario or ['clear', 'cylinder', 'blocked']: count = args.repeats if args.repeats is not None else (3 if scenario in ('clear', 'cylinder') else 1) for index in range(1, count+1): name=f'{scenario}_{index}';folder=args.output/name with open(args.output/(name+'.log'),'w') as log: - command=[sys.executable,str(root/'tools/validate_lio_navigation.py'), + command=[sys.executable,str(script_dir/'validate_lio_navigation.py'), '--launcher',args.launcher,'--map',str(args.map.resolve()),'--output',str(folder.resolve()), '--scenario',scenario,'--goal','0','0'] if args.domain is not None: diff --git a/tools/validation/validate_lio_navigation.py b/tools/validation/validate_lio_navigation.py new file mode 100644 index 0000000..8ef359b --- /dev/null +++ b/tools/validation/validate_lio_navigation.py @@ -0,0 +1,532 @@ +#!/usr/bin/env python3 +"""Run an isolated Gazebo navigation scenario and score it using simulator truth.""" +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import signal +import subprocess +import sys +import time +import uuid +from collections import Counter + +import rclpy +from rclpy.node import Node +from rclpy.action import ActionClient +from action_msgs.msg import GoalStatus +from rclpy.parameter import Parameter +from lifecycle_msgs.srv import GetState +from tf2_msgs.msg import TFMessage +from nav2_msgs.srv import IsPathValid +from nav2_msgs.action import ComputePathToPose, FollowPath +from nav_msgs.msg import Odometry +from geometry_msgs.msg import PoseStamped, Twist +from rclpy.qos import qos_profile_sensor_data +from std_msgs.msg import Bool +from rcl_interfaces.srv import GetParameters +from std_srvs.srv import Trigger +from rclpy.utilities import get_rmw_implementation_identifier +sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'), + str(Path(__file__).resolve().parents[1])] +import project_env +from arena_grid import ARENA_GOALS, START, ArenaGrid +from nav2_startup import path_probe_request + +from dds_environment import defaults as dds_defaults +from lio_metrics import cylinder_clearance, metrics +from verify_lio_stack import NODES, process_environment + + +ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0)) +ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16) + + +def check_field_coverage(node, grid): + coverage = grid.coverage() + client = ActionClient(node, ComputePathToPose, '/compute_path_to_pose') + try: + if not client.wait_for_server(timeout_sec=8): + raise RuntimeError('compute_path_to_pose unavailable for field coverage') + + def pose(point): + message = PoseStamped() + message.header.frame_id = 'map' + message.pose.position.x, message.pose.position.y = point + message.pose.orientation.w = 1.0 + return message + + checks = [] + for point in coverage.pop('samples'): + request = ComputePathToPose.Goal() + request.start = pose(START) + request.goal = pose(point) + request.use_start = True + future = client.send_goal_async(request) + rclpy.spin_until_future_complete(node, future, timeout_sec=5) + handle = future.result() if future.done() else None + check = {'target': point, 'passed': False} + if handle is None or not handle.accepted: + check['error'] = 'goal rejected or acceptance timed out' + else: + future = handle.get_result_async() + rclpy.spin_until_future_complete(node, future, timeout_sec=5) + wrapped = future.result() if future.done() else None + if wrapped is None: + cancel = handle.cancel_goal_async() + rclpy.spin_until_future_complete(node, cancel, timeout_sec=1) + check['error'] = 'planner response timed out' + else: + outcome = wrapped.result + check.update(error_code=outcome.error_code, error=outcome.error_msg) + if wrapped.status == GoalStatus.STATUS_SUCCEEDED and outcome.path.poses: + endpoint = outcome.path.poses[-1].pose.position + check['endpoint_error_m'] = math.hypot(endpoint.x-point[0], endpoint.y-point[1]) + check['passed'] = outcome.error_code == 0 and check['endpoint_error_m'] <= 0.30 + checks.append(check) + finally: + client.destroy() + coverage.update(planned=sum(c['passed'] for c in checks), sample_count=len(checks), checks=checks) + return coverage + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--map', type=Path, required=True) + parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio') + parser.add_argument('--launcher', choices=['shell', 'python'], default='shell') + parser.add_argument('--output', type=Path, required=True) + goals = parser.add_mutually_exclusive_group() + goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y')) + goals.add_argument('--full-field', action='store_true', + help='check reachability in 1 m tiles and navigate the whole-field route') + goals.add_argument('--round-trip-regression', action='store_true', + help='run the five recorded goals without restarting the stack') + parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]', + help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests') + parser.add_argument('--timeout', type=float, default=420.0, + help='whole-stack validation deadline, including up to three startup attempts') + parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear') + parser.add_argument('--obstacle-x',type=float,default=-4.0) + parser.add_argument('--obstacle-y',type=float,default=-1.5) + parser.add_argument('--obstacle-radius',type=float,default=0.22) + parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load') + args = parser.parse_args() + if args.round_trip_regression and args.scenario not in ('clear', 'cylinder'): + parser.error('--round-trip-regression requires clear or cylinder') + if args.full_field and args.scenario != 'clear': + parser.error('--full-field starts the clear-field coverage route') + multileg = args.round_trip_regression or args.full_field + route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ()) + pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route) + if not args.map.is_file(): + parser.error('map missing') + if args.output.exists(): + parser.error('output must be a new directory') + workspace = project_env.WORKSPACE + try: + gz_exe = project_env.find_gz_bin() + bin_dir = project_env.find_bin_dir(workspace) + recorder_exe = project_env.require_executable(bin_dir/'field_localization_record', + 'field_localization_record') + grid = ArenaGrid(project_env.find_map_yaml()) if args.full_field else None + if route: + nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client') + except (project_env.ProbeError, ValueError, OSError) as error: + parser.exit(1, f'{parser.prog}: {error}\n') + args.output.mkdir(parents=True) + session = uuid.uuid4().hex[:12] + os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}', + ROS2CLI_DISABLE_DAEMON='1', + HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization', + LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()), + LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve())) + os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=args.lio_cloud_topic) + os.environ.update(dds_defaults(os.environ)) + os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve())) + os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve())) + params_file = workspace/'src/sentry_sim/config/nav2_params.yaml' + runtime = { + 'domain': os.environ['ROS_DOMAIN_ID'], + 'partition': os.environ['GZ_PARTITION'], + 'scenario': args.scenario, + 'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius], + 'goals': route, + 'pauses_wall_sec': pauses, + 'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(), + 'lio_map_sha256': hashlib.sha256(args.map.read_bytes()).hexdigest(), + 'point_cloud_topic': args.lio_cloud_topic, + } + (args.output/'runtime.json').write_text(json.dumps(runtime, indent=2)) + log = None + record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0 + record_log = open(args.output/'record.log', 'w', encoding='utf8') + recorder = subprocess.Popen([str(recorder_exe), '--ros-args', + '-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset', + '-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'], + stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True) + if args.launcher == 'shell': + command = ['bash', str(workspace/'scripts/sentry_up.sh')] + else: + command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'), + 'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}'] + log = open(args.output/'stack.log', 'w', encoding='utf8') + started = time.monotonic() + process = subprocess.Popen(command, cwd=workspace, start_new_session=True, + stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT) + rclpy.init() + node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)]) + publishers = set() + samples = {'truth': [], 'estimate': []} + health_events = [] + health_transitions = [] + actuator = [] + last_map_tf_wall = None + + def on_health(msg): + stamp = time.monotonic() + if not health_events or msg.data != health_events[-1][1]: + health_transitions.append({'wall': stamp, 'sim': sim_now(), 'valid': msg.data}) + health_events.append((stamp, msg.data)) + + def sim_now(): + return node.get_clock().now().nanoseconds * 1e-9 + + def spin_for(seconds): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if process.poll() is not None: + raise RuntimeError('stack exited during navigation') + rclpy.spin_once(node, timeout_sec=0.02) + subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100) + subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid', + on_health, 10) + subscriptions = [] + def sample(message, name): + p = message.pose.pose if name == 'estimate' else message.pose + samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec, + p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w]) + subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth', + lambda msg: sample(msg, 'truth'), qos_profile_sensor_data)) + subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry', + lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data)) + counts = {'map_to_odom': 0, 'map_to_base_link': 0} + + def on_tf(msg, info): + nonlocal last_map_tf_wall + for transform in msg.transforms: + if transform.header.frame_id != 'map': + continue + if transform.child_frame_id == 'odom': + gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid + publishers.add(json.dumps(gid, sort_keys=True, default=str)) + counts['map_to_odom'] += 1 + last_map_tf_wall = time.monotonic() + if transform.child_frame_id == 'base_link': + counts['map_to_base_link'] += 1 + + subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500) + clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES} + path_client = node.create_client(IsPathValid, '/is_path_valid') + active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active') + parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters') + states = {} + processes = [] + rviz = None + goal = None + reached_readiness = False + result = {} + try: + if args.rviz: + rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d', + str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args', + '-p', 'use_sim_time:=true'], + env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'}, + start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) + deadline = time.monotonic()+args.timeout + last_check = 0.0 + stable_since = None + manager_completed = False + while time.monotonic() < deadline: + rclpy.spin_once(node, timeout_sec=0.1) + if process.poll() is not None: + raise RuntimeError('stack exited') + if time.monotonic()-last_check < 0.5: + continue + last_check = time.monotonic() + if not processes and time.monotonic()-started > 8: + processes = process_environment(process.pid) + states = {} + pending = {} + for name, client in clients.items(): + if not client.service_is_ready(): + continue + pending[name] = client.call_async(GetState.Request()) + poll_end = time.monotonic()+1 + while time.monotonic() < poll_end and any(not f.done() for f in pending.values()): + rclpy.spin_once(node, timeout_sec=0.02) + for name, future in pending.items(): + if future.done() and future.result(): + states[name] = future.result().current_state.id + else: + clients[name].remove_pending_request(future) + log_path = args.output/'stack.log' + text = log_path.read_text(errors='replace') if log_path.exists() else '' + manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line + for line in text.splitlines()) + if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]: + if stable_since is None: + stable_since = time.monotonic() + if time.monotonic()-stable_since >= 2: + reached_readiness = True + break + else: + stable_since = None + processes = process_environment(process.pid) + names = sorted(set(node.get_node_names())) + path_ready = path_client.wait_for_service(timeout_sec=2) + path_response = None + if path_ready: + future = path_client.call_async(path_probe_request()) + rclpy.spin_until_future_complete(node, future, timeout_sec=3) + if future.done() and future.result() is not None: + path_response = str(future.result()) + manager_active = False + if active_client.wait_for_service(timeout_sec=1): + future = active_client.call_async(Trigger.Request()) + rclpy.spin_until_future_complete(node, future, timeout_sec=2) + manager_active = bool(future.done() and future.result() and future.result().success) + managed_nodes = [] + if parameter_client.wait_for_service(timeout_sec=1): + future = parameter_client.call_async(GetParameters.Request(names=['node_names'])) + rclpy.spin_until_future_complete(node, future, timeout_sec=2) + if future.done() and future.result() and future.result().values: + managed_nodes = list(future.result().values[0].string_array_value) + result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started, + 'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()), + 'rmw': get_rmw_implementation_identifier(), 'processes': processes, + 'node_counts': dict(Counter(node.get_node_names())), + 'services': dict(node.get_service_names_and_types()), + 'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))), + 'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))}, + 'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response, + 'topic_qos': { + topic: [{'node': p.node_name, 'reliability': str(p.qos_profile.reliability)} + for p in node.get_publishers_info_by_topic(topic)] + for topic in dict.fromkeys(('/scan/points', '/scan/points_filtered', args.lio_cloud_topic, '/imu')) + }, + 'manager_active': manager_active, 'managed_nodes': managed_nodes, + 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names, + 'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts} + result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None + and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes) + and all(states.get(name) == 3 for name in NODES) and not result['amcl_present'] + and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0 + and counts['map_to_base_link'] == 0) + if grid is not None and result['passed']: + coverage = check_field_coverage(node, grid) + result['field_coverage'] = coverage + print(f'field coverage: {coverage["planned"]}/{coverage["sample_count"]} representative goals planned', flush=True) + (args.output/'result.json').write_text(json.dumps(result, indent=2)) + if args.scenario in ('cylinder','blocked') and result['passed']: + # Obstacle lies on the initial straight corridor; a route around the cylinder exists. + shape = f'{args.obstacle_radius}0.8' + pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0' + if args.scenario == 'blocked': + shape = '1.6 1.6 0.8' + pose = '0 0 0.4 0 0 0' + sdf = f'true{pose}{shape}{shape}' + gz = project_env.run_gz(gz_exe, 'service', '-s', '/world/rmul_arena/create', + '--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000', + '--req', 'sdf: '+json.dumps(sdf), timeout=10) + (args.output/'obstacle.log').write_text(gz.stdout+gz.stderr) + if gz.returncode or 'data: true' not in gz.stdout: + raise RuntimeError('obstacle insertion failed') + until=time.monotonic()+2 + while time.monotonic()= 5 and actuator + and sum(abs(v) for v in actuator[-1][1:]) > 0.1): + owned = process_environment(process.pid) + sensors = [p['pid'] for p in owned if p['executable'] + and Path(p['executable'][0]).name == 'self_filter'] + if len(sensors) != 1: + raise RuntimeError('cannot identify the owned self_filter for fault injection') + fault_time = time.monotonic() + os.kill(sensors[0], signal.SIGTERM) + timed_out = goal.poll() is None + if timed_out: + os.killpg(goal.pid, signal.SIGINT) + goal.wait(timeout=5) + goal_end_wall = time.monotonic() + spin_for(0.3) + goal_end_sim = sim_now() + output = goal_log.read_text() + truth_goal = [row for row in samples['truth'] if goal_start_sim <= row[0] <= goal_end_sim] + estimate_goal = [row for row in samples['estimate'] if goal_start_sim <= row[0] <= goal_end_sim] + leg = { + 'goal': target, 'goal_exit_code': goal.returncode, + 'goal_succeeded': not timed_out and goal.returncode == 0 and '结果: ✅ SUCCEEDED' in output, + 'goal_elapsed_wall_sec': goal_end_wall-goal_start_wall, + 'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out, + 'trajectory_metrics': metrics(estimate_goal, truth_goal), + 'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None, + 'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal) + if truth_goal and args.scenario == 'cylinder' else None, + 'health_failures_during_goal': sum(not value for stamp, value in health_events + if goal_start_wall <= stamp <= goal_end_wall), + } + if args.scenario == 'blocked': + stopped = bool(actuator and actuator[-1][0] > goal_end_wall and actuator[-1][1:] == (0, 0, 0)) + result['blocked_zero_output'] = stopped + leg['passed'] = (not timed_out and '结果: ❌ ABORTED' in output and stopped + and leg['health_failures_during_goal'] == 0 + and leg['truth_goal_error_m'] is not None + and leg['truth_goal_error_m'] > 0.30) + elif args.scenario == 'lidar_loss': + spin_for(0.7) + stops = [t for t, x, y, z in actuator if fault_time is not None and t >= fault_time and x == y == z == 0] + delay = min(stops)-fault_time if stops else None + lost = next((event for event in health_transitions if fault_time is not None + and event['wall'] >= fault_time and not event['valid']), None) + canceled = '结果: ❌ CANCELED' in output + # Once TF stops, FollowPath can complete with TF_ERROR before the relay's + # cancel request returns. Both outcomes terminate the in-flight goal. + tf_abort = ('结果: ❌ ABORTED' in output + and f'Nav2 error_code={FollowPath.Result.TF_ERROR} ' in output) + terminated = bool(lost and lost['wall'] <= goal_end_wall and (canceled or tf_abort)) + result.update(fault_goal_canceled=canceled, + fault_goal_tf_aborted=tf_abort, + fault_goal_terminated=terminated, + fault_stop_delay_sec=delay, + fault_tf_halted=bool(lost and last_map_tf_wall is not None + and last_map_tf_wall <= lost['wall']+0.1)) + if lost: + retry_log = args.output/'retry_invalid_localization.log' + with retry_log.open('w') as stream: + retry = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=20) + retry_text = retry_log.read_text() + result['invalid_retry_blocked'] = (retry.returncode != 0 and '定位不可用' in retry_text + and '目标已接受' not in retry_text) + else: + result['invalid_retry_blocked'] = False + leg['passed'] = (terminated and not timed_out and delay is not None and delay < 0.5 + and result['fault_tf_halted'] and result['invalid_retry_blocked']) + else: + leg['passed'] = (leg['goal_succeeded'] and leg['truth_goal_error_m'] is not None + and leg['truth_goal_error_m'] <= 0.30 + and (leg['minimum_cylinder_clearance_m'] is None + or leg['minimum_cylinder_clearance_m'] > 0)) + quality = leg['trajectory_metrics'] + leg['passed'] = (leg['passed'] and quality['matched'] > 100 and quality['rpe_pairs'] > 0 + and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1) + legs.append(leg) + result.update(leg) + result['legs'] = legs + (args.output/'result.json').write_text(json.dumps(result, indent=2)) + print(f'leg {index+1}/{len(route)} {tuple(target)}: passed={leg["passed"]} ' + f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True) + if multileg and not leg['goal_succeeded']: + spin_for(8) + break + result.update(counts) + result['map_to_odom_publishers'] = len(publishers) + result['amcl_present'] = 'amcl' in node.get_node_names() + # Include drift during the pauses, but keep each goal's outcome independent. + if multileg: + end_sim = legs[-1]['end_sim'] + quality = metrics(*([row for row in samples[name] if start_sim <= row[0] <= end_sim] + for name in ('estimate', 'truth'))) + result['trajectory_metrics'] = quality + result['first_localization_loss'] = next( + (event for event in health_transitions if event['wall'] >= start_wall and not event['valid']), None) + clearances = [leg['minimum_cylinder_clearance_m'] for leg in legs + if leg['minimum_cylinder_clearance_m'] is not None] + result['minimum_cylinder_clearance_m'] = min(clearances) if clearances else None + result['passed'] = (quality['maximum_position_error_m'] is not None + and quality['maximum_position_error_m'] < 0.25 + and quality['ate_translation_m'] < 0.1 + and result['first_localization_loss'] is None) + if grid is not None: + result['passed'] = (result['passed'] and coverage['sample_count'] > 0 + and coverage['planned'] == coverage['sample_count']) + result['passed'] = (result['passed'] and len(legs) == len(route) and all(leg['passed'] for leg in legs) + and len(publishers) == 1 and counts['map_to_base_link'] == 0 + and not result['amcl_present']) + (args.output/'result.json').write_text(json.dumps(result, indent=2)) + print(json.dumps({k: v for k, v in result.items() if k not in + ('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True) + if not result['passed']: + raise RuntimeError('stack integration validation failed') + except Exception as error: + result.update(passed=False, error=str(error)) + (args.output/'result.json').write_text(json.dumps(result, indent=2)) + raise + finally: + _ = subscription, subscriptions, subscriptions_health, subscription_actuator + (args.output/'health_events.json').write_text(json.dumps(health_events)) + (args.output/'health_transitions.json').write_text(json.dumps(health_transitions, indent=2)) + for name, rows in samples.items(): + with open(args.output/(name+'.tum'),'w') as output: + for row in rows: + output.write(' '.join(map(str,row))+'\n') + if goal is not None and goal.poll() is None: + os.killpg(goal.pid, signal.SIGINT) + try: + goal.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(goal.pid, signal.SIGKILL) + goal.wait() + if recorder.poll() is None: + os.killpg(recorder.pid, signal.SIGINT) + try: + recorder.wait(timeout=10) + except subprocess.TimeoutExpired: + os.killpg(recorder.pid, signal.SIGKILL) + recorder.wait() + record_log.close() + if process.poll() is None: + os.killpg(process.pid, signal.SIGINT) + try: + process.wait(timeout=20) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait() + if rviz is not None: + os.killpg(rviz.pid, signal.SIGINT) + try: + rviz.wait(timeout=5) + except subprocess.TimeoutExpired: + os.killpg(rviz.pid, signal.SIGKILL) + rviz.wait() + if log: + log.close() + node.destroy_node() + rclpy.shutdown() + + +if __name__ == '__main__': + main() diff --git a/tools/verify_lio_stack.py b/tools/validation/verify_lio_stack.py similarity index 94% rename from tools/verify_lio_stack.py rename to tools/validation/verify_lio_stack.py index b542aed..c0fc256 100644 --- a/tools/verify_lio_stack.py +++ b/tools/validation/verify_lio_stack.py @@ -6,6 +6,7 @@ import os from pathlib import Path import signal import subprocess +import sys import time import uuid from collections import Counter @@ -19,6 +20,9 @@ from nav2_msgs.srv import IsPathValid from rcl_interfaces.srv import GetParameters from std_srvs.srv import Trigger from rclpy.utilities import get_rmw_implementation_identifier +sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'), + str(Path(__file__).resolve().parents[1])] +import project_env from nav2_startup import path_probe_request NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server', @@ -77,13 +81,21 @@ def main(): args = parser.parse_args() if not args.map.is_file(): parser.error('map missing') + workspace = project_env.WORKSPACE + try: + gz_exe = project_env.find_gz_bin() + bin_dir = project_env.find_bin_dir(workspace) + if args.goal is not None: + nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client') + except project_env.ProbeError as error: + parser.exit(1, f'{parser.prog}: {error}\n') args.output.mkdir(parents=True, exist_ok=True) session = uuid.uuid4().hex[:12] + os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir)) os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}', ROS2CLI_DISABLE_DAEMON='1', HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization', LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve())) - workspace = Path(__file__).resolve().parents[1] log = None if args.launcher == 'shell': command = ['bash', str(workspace/'scripts/sentry_up.sh')] @@ -202,7 +214,7 @@ def main(): and counts['map_to_base_link'] == 0) (args.output/'result.json').write_text(json.dumps(result, indent=2)) if args.goal and result['passed']: - goal = subprocess.run([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'], + goal = subprocess.run([str(nav_client), *map(str, args.goal), '0'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200) (args.output/'goal.log').write_text(goal.stdout) result['goal_exit_code'] = goal.returncode