feat(localization): integrate LIO ROS TF, replay and validated AMCL replacement
GCC 15.2 C++23 clean rebuild: zero warnings. All 11 xmake test suites pass. Independent 120 s Gazebo replay: ATE 0.005279 m / 0.191335 deg; 1 s RPE 0.005358 m / 0.099086 deg. Both startup entry points validate Nav2 activation, no AMCL, and a single map-to-odom publisher.
This commit is contained in:
1 parent
55e9456e4a
commit
b833e6f658
30 files changed
+1314
-329
No files matched your search
@@ -9,6 +9,12 @@
|
||||
|
||||
---
|
||||
|
||||
## 当前定位入口
|
||||
|
||||
默认定位已切换到连续跟踪的 LIO(`field_localization_node`)。必须先用 `LIO_MODE=mapping` 建立并导出 3D 地图,再以只读地图定位;缺图会明确报错。完整用法、时间/外参约定和局限见 [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。
|
||||
|
||||
## 0. 开发环境
|
||||
|
||||
### 0.1 操作系统
|
||||
@@ -27,15 +33,15 @@
|
||||
| Gazebo(ROS vendor) | **10.5.0** | `/opt/ros/lyrical/opt/gz_*_vendor/` |
|
||||
| ros_gz / ros_gz_sim | 3.0.10 | `/opt/ros/lyrical` |
|
||||
| Nav2 | 1.5.2 | `ros-lyrical-navigation2` / `nav2-bringup` |
|
||||
| slam_toolbox | 2.10.0 | 备用(当前不用,定位走里程计真值) |
|
||||
| slam_toolbox | 2.10.0 | 备用(当前默认 LIO,AMCL 可选) |
|
||||
| RViz2 | 15.2.6 | |
|
||||
| CMake | 4.2.3 | 系统自带。**本工程不用**(构建全走 xmake) |
|
||||
| GCC / G++ | 15.2.0 | |
|
||||
| GNU Make | 4.4.1 | |
|
||||
| Python | 3.14.4 | `/usr/bin/python3`(系统版) |
|
||||
| Git | 2.53.0 | |
|
||||
| **C++ 标准** | **C++23** | 仓库根 `xmake.lua` 的 `set_languages("c++23")`<br>⚠️ **下限 C++17**:rclcpp 要 17、PCL 1.15 用 `#error` 硬拦,改成 11/14 **编译不过** ,于是用23 |
|
||||
| **xmake** | **3.1.1** | `~/.local/bin/xmake`。**全工程唯一的构建系统**,在仓库根跑 `xmake`(核心库 + 两个节点 + 223 项单测,增量 0.5 秒)。`sentry_sim` 是纯数据包,不需要编译 |
|
||||
| **C++ 标准** | **C++23** | 仓库根 `xmake.lua` 的 `set_languages("c++23")`<br>**固定要求 C++23**,不能降为 C++17/20 |
|
||||
| **xmake** | **3.1.1** | `~/.local/bin/xmake`。**全工程唯一的构建系统**,在仓库根跑 `xmake`(导航与定位核心库、节点、离线工具及单元测试)。`sentry_sim` 是纯数据包,不需要编译 |
|
||||
|
||||
## 1. 目录结构
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 定位接入(AMCL)
|
||||
|
||||
> 本文适用于显式选择 `LOCALIZATION=amcl` 的旧定位分支。当前默认 LIO,使用说明见 [field_localization](../src/field_localization/README.md)。不要同时启动两个 map→odom 发布者。
|
||||
|
||||
> **状态**:🟢 **已修复(2026-11-19)** —— `scan2d` 改为由 `self_filter` 从 3D 点云投影生成
|
||||
> (取 `z ∈ [0.05, 0.50] m` 车体碰撞带、360 方位取最小距离),消除了「雷达看不见 0.42 m
|
||||
> 悬空平板、地图却有」的高度失配跑飞。原问题复盘见 §4.1 的更正与
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# 场地 LiDAR–IMU 定位
|
||||
|
||||
本包使用 C++23、标准库和 Eigen 3.4;core 完全不依赖 ROS。在线流程为 IMU 中值传播、扫描去畸变、体素地图点到面残差和 18 维迭代误差状态滤波。没有全局重定位、回环或多假设初始化。初始位姿必须已知,且 map 始终以场地中心为原点。
|
||||
|
||||
## 构建与测试
|
||||
|
||||
在仓库根配置已有 ROS 环境,然后运行:
|
||||
|
||||
```bash
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
xmake
|
||||
xmake test
|
||||
```
|
||||
|
||||
编译使用 GCC 15.2、`-std=c++23 -Wall -Wextra`,release 核心启用 `-O2`。Eigen 通过系统 pkg-config 发现;不会从网络安装算法依赖。所有产物位于 `build/bin/`。项目二进制直接执行,不使用 ament、colcon 或 `ros2 run` 注册。
|
||||
|
||||
测试使用现有计数框架的 `CHECK/CHECK_NEAR` 包装,release 下也执行。`test_eskf` 和 `test_lio_synthetic` 默认把五组随机种子的收敛数据写到 `/tmp/field_lio_bias_filter.csv` 和 `/tmp/field_lio_bias_end_to_end.csv`;直接执行时可用第一个位置参数指定 CSV 路径。
|
||||
|
||||
## 建图、保存与只读定位
|
||||
|
||||
先显式建图,再启动只读地图定位:
|
||||
|
||||
```bash
|
||||
LIO_MODE=mapping LIO_MAP="$PWD/generated/field.flmap" 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
|
||||
```
|
||||
|
||||
Shell 默认 `LOCALIZATION=lio`、`LIO_MODE=localization`,缺失地图立即报错。可显式用 `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 localization:=amcl
|
||||
```
|
||||
|
||||
默认初始 base_link 位姿为 `(-5,3,0)`、零 RPY,与当前世界出生点对应。Shell 使用 `LIO_INITIAL_X/Y/Z/YAW`,Python 使用 `lio_initial_x/y/z/yaw`,节点另外支持 `initial_roll/pitch`。改变出生点必须同时更新初始位姿。首帧只用来建立已知位姿下的种子地图,不能从单帧猜测其全局位置。
|
||||
|
||||
只读定位绝不往地图插点。建图只在无退化、质量门槛通过后插入关键帧,位移必须严格大于 0.5 m,或旋转严格大于 10°。初始化种子帧是唯一例外。配准失败不写图。
|
||||
|
||||
## ROS 接口与坐标约定
|
||||
|
||||
- 默认输入:`point_cloud_topic=/scan/points`、`imu_topic=/imu`。完整启动器显式选择 `/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`,右扰动态度误差。
|
||||
- `get_pose()` 返回 `map → base_link`;`get_snapshot()` 在一把互斥锁内返回配套的位姿、滤波状态、协方差与状态时间。
|
||||
- 只发布 TF `map → odom`:`T_map_odom = T_map_base × inverse(T_odom_base)`,两个变换使用同一时间。`publish_map_to_odom=false` 可关闭;不能与 AMCL 同时发布。
|
||||
- `/field_localization/odometry` 为 map 系车体位姿及变换后的位姿协方差;twist 未填充,不能用于速度反馈(速度状态可通过 core 快照读取)。不额外广播 body TF。
|
||||
- 每 5 秒打印模式、降级原因、有效点数、残差 RMSE、内点数/比例、退化维数与子空间基、关键帧数和地图点数,同时输出 `/field_localization/status` 摘要。
|
||||
- 支持 `--ros-args -p use_sim_time:=true`。只有消息/ROS 仿真时间参与状态计算。检测到 `/clock` 回跳后停止输出;必须显式调用 `/field_localization/reset` 或重启,以配置的已知初始位姿重新开始。
|
||||
|
||||
`process_imu/process_point_cloud` 的 bool 表示输入是否被接受,不等于完成 LiDAR 更新。`TrackingMode::FULL` 表示当前存在有效 LiDAR 约束,仍可能有部分退化;具体退化方向由状态中的矩阵列表示,不能直接当作三个欧拉角轴。`IMU_ONLY` 表示仅预测。
|
||||
|
||||
## 时间、噪声与退化
|
||||
|
||||
Gazebo 的 IMU 传感器配置无噪声;正式回放使用原始数据,不人为加噪。滤波过程噪声仍可配置,用于表达模型和状态不确定性。默认 gyro/accel 噪声密度为 0.003 rad/s/√Hz 和 0.03 m/s²/√Hz,零偏随机游走为 `1e-5/1e-4`。这些参数不代表修改传感器数据。
|
||||
|
||||
默认 `scan_timing=instantaneous`,整帧按 header 同刻处理,不给仿真点云制造滚动扫描畸变。可选 `azimuth`,参数为 `scan_period_sec=0.1`、`scan_start_angle_rad=-pi`、`scan_counterclockwise=true`、`scan_stamp_at_end=true`。必须与设备真实扫描约定匹配。纯 core 还支持真实逐点绝对时间戳模式。
|
||||
|
||||
去畸变包含初速度、重力、旋转、平移和固定杆臂。保留最近 2 秒 IMU/状态,延迟扫描在对应时刻更新后重传播,不把旧量测直接作用于当前状态。ROS 扫描队列最多 5 帧,等待 IMU 覆盖最多 0.2 秒仿真时间。
|
||||
|
||||
默认地图和扫描体素为 0.1 m,邻域 0.5 m;最多 10 次迭代,至少 50 个内点、内点率 20%、残差 RMSE 不超过 0.1 m。Huber 阈值 0.05 m。信息矩阵按内点数归一化,以 1 m 特征长度统一平移/旋转尺度;SVD 相对阈值 `1e-4`、绝对阈值 `1e-6`。不可观位姿增益和修正被投影掉,并使用投影后增益执行 Joseph 协方差更新。
|
||||
|
||||
## 离线数据、回放与独立真值
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
采集前需要已有 ROS Python 环境。脚本使用独立 Gazebo partition 和 ROS domain,只清理由自己创建的进程树;创建输出目录中的 `STOP` 文件可请求停止。控制器仅用轮速里程计走西北走廊路线,真值只进入记录器。两次采集使用不同路线,地图与定位序列分开。
|
||||
|
||||
独立真值来自 Gazebo 自带 PosePublisher,100 Hz,桥接至 `/evaluation/ground_truth` 的 PoseStamped。模型原点与 base_link 重合,世界与 map 原点一致。真值不进入定位器,不发布到 TF,也不用 `/odom` 代替真值。
|
||||
|
||||
数据集:`config.txt` 保存版本、已知初始位姿、固定外参及扫描时间模型;`imu.csv` 保存 IMU 系原始测量;`scans.csv` 索引 `clouds/*.flpc`;`truth.tum` 保存世界系真值。FLPC v1 使用固定小端标量:8 字节 magic、uint32 版本、double header 时间、uint32 点数;每点为 double 绝对时间及四个 float32。地图 FLMAP v1 为 8 字节 magic、uint32 版本、double 体素边长、uint64 点数,随后为 map 系 xyz double。均不序列化 Eigen 内存。
|
||||
|
||||
回放工具不依赖 ROS,不读取轮速作为定位量测。输出 `trajectory.tum/status.csv/metrics.txt`;报告未对齐的平移 ATE、旋转测地角 ATE、1 秒相对位姿 RPE,旋转以度报告。真值线性平移/四元数 slerp 插值,最大真值间隔 0.05 秒。没有真值或足够对应关系时不能声称验证精度。
|
||||
|
||||
## 已知局限与失败行为
|
||||
|
||||
- 初始位姿错误、机器人被搬移、大幅时间/外参错误可能失锁;不做全局重定位。显式 reset 也只回到配置的已知初始位姿。
|
||||
- 平面、走廊、重复结构可能不可观;仅更新可观方向,其他方向靠 IMU 并逐渐漂移。全部约束失败进入 IMU_ONLY。
|
||||
- 同时估计重力和加计零偏需要运动激励。六轴收敛只对有充分三维激励的带噪合成测试验收,不能由平面、零噪声仿真推导出来。
|
||||
- 超过 0.3 秒无有效 LiDAR 更新进入 IMU_ONLY;无效云立即降级。IMU 间隔超过 0.05 秒不跨缺口积分,持位并增大不确定度。状态过期 0.1 秒或缺少同刻 odom TF 时停止广播过时位姿。
|
||||
- 地图没有回环优化、动态物体剔除或在线外参标定,建图可积累漂移。固定地图改变后不会自动重建。
|
||||
- 方位角去畸变是缺少真实逐点时间时的近似;错误扫描方向、起始角和 header 语义会引入伪畸变。
|
||||
- 本次实测路线覆盖西北走廊;不能据此声称全场每处、真机噪声、绑架恢复或快速运动已验证。
|
||||
|
||||
## 本机验收记录(2026-11-22)
|
||||
|
||||
GCC 15.2 清洁重构建零警告,11 套 xmake 测试通过。五组带噪合成端到端测试各 600 帧均通过零偏门槛。独立的 120 秒 Gazebo 定位序列包含 1,034 帧有效扫描,未做事后轨迹对齐:平移 ATE RMSE 0.005279 m,旋转 ATE RMSE 0.191335°;1 秒 RPE 为 0.005358 m / 0.099086°。FULL 比例与真值匹配覆盖率均为 100%,地图文件哈希不变。此精度仅代表本次西北走廊、零噪声 IMU 条件。
|
||||
|
||||
在同一录制数据的独立故障注入回放中,把相对第 30–32 秒的 17 帧点云替换为空云,17 帧全部进入 IMU_ONLY,后续恢复 FULL,未执行全局搜索;全段平移 ATE RMSE 增至 0.014314 m。
|
||||
|
||||
完整 Nav2 启动检查命令:
|
||||
|
||||
```bash
|
||||
python3 tools/verify_lio_stack.py --map generated/field.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 握手结束前退出。
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include "field_localization/core/localization_core.hpp"
|
||||
namespace field_localization::core {
|
||||
// Versioned little-endian scalar encoding; never serializes Eigen object memory.
|
||||
void write_cloud(const PointCloud &cloud,const std::filesystem::path &path);
|
||||
PointCloud read_cloud(const std::filesystem::path &path);
|
||||
void write_dataset_config(const CoreOptions &options,const std::filesystem::path &path);
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path);
|
||||
struct TrajectorySample { double time; Pose3D pose; };
|
||||
std::vector<TrajectorySample> read_trajectory(const std::filesystem::path &path);
|
||||
void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample);
|
||||
std::optional<Pose3D> trajectory_pose(std::span<const TrajectorySample> trajectory,double time,
|
||||
double maximum_gap=0.05);
|
||||
struct Evaluation {
|
||||
std::size_t total{0},matched{0},relative_pairs{0};
|
||||
double ate_translation{0},ate_rotation_rad{0},rpe_translation{0},rpe_rotation_rad{0};
|
||||
};
|
||||
Evaluation evaluate(std::span<const TrajectorySample> estimate,std::span<const TrajectorySample> truth);
|
||||
const char *mode_name(TrackingMode mode);
|
||||
const char *reason_name(FailureReason reason);
|
||||
} // namespace field_localization::core
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
#include <geometry_msgs/msg/transform.hpp>
|
||||
namespace field_localization::ros {
|
||||
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg);
|
||||
core::Pose3D from_transform(const geometry_msgs::msg::Transform &transform);
|
||||
geometry_msgs::msg::Transform to_transform(const core::Pose3D &pose);
|
||||
} // namespace field_localization::ros
|
||||
@@ -1,42 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include "field_localization/core/localization_core.hpp"
|
||||
#include "field_localization/core/types.hpp"
|
||||
|
||||
#include "field_localization/ros/conversion.hpp"
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <sensor_msgs/msg/imu.hpp>
|
||||
#include <sensor_msgs/msg/point_cloud2.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <nav_msgs/msg/odometry.hpp>
|
||||
#include <std_msgs/msg/string.hpp>
|
||||
#include <std_srvs/srv/trigger.hpp>
|
||||
#include <tf2_ros/buffer.hpp>
|
||||
#include <tf2_ros/transform_listener.hpp>
|
||||
#include <tf2_ros/transform_broadcaster.hpp>
|
||||
#include <deque>
|
||||
|
||||
namespace field_localization::ros {
|
||||
|
||||
class LocalizationNode : public rclcpp::Node {
|
||||
class LocalizationNode:public rclcpp::Node {
|
||||
public:
|
||||
explicit LocalizationNode(
|
||||
const rclcpp::NodeOptions &options = rclcpp::NodeOptions());
|
||||
|
||||
explicit LocalizationNode(const rclcpp::NodeOptions &options=rclcpp::NodeOptions());
|
||||
~LocalizationNode() override;
|
||||
private:
|
||||
bool ensure_core();
|
||||
void on_point_cloud(sensor_msgs::msg::PointCloud2::ConstSharedPtr msg);
|
||||
|
||||
void on_imu(sensor_msgs::msg::Imu::ConstSharedPtr msg);
|
||||
|
||||
void drain_scans();
|
||||
void publish_estimate();
|
||||
void print_localization_status();
|
||||
|
||||
rclcpp::TimerBase::SharedPtr status_timer_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr
|
||||
point_cloud_sub_;
|
||||
|
||||
bool check_clock();
|
||||
core::CoreOptions core_options_;
|
||||
std::unique_ptr<core::LocalizationCore> core_;
|
||||
std::unique_ptr<tf2_ros::Buffer> tf_buffer_;
|
||||
std::unique_ptr<tf2_ros::TransformListener> tf_listener_;
|
||||
std::unique_ptr<tf2_ros::TransformBroadcaster> broadcaster_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr point_cloud_sub_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub_;
|
||||
|
||||
std::string point_cloud_topic_;
|
||||
std::string imu_topic_;
|
||||
core::LocalizationCore core_;
|
||||
|
||||
std::size_t point_cloud_count_{0};
|
||||
std::size_t imu_count_{0};
|
||||
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr odometry_pub_;
|
||||
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr status_pub_;
|
||||
rclcpp::Service<std_srvs::srv::Trigger>::SharedPtr save_service_,reset_service_;
|
||||
rclcpp::TimerBase::SharedPtr status_timer_;
|
||||
std::deque<core::PointCloud> scans_;
|
||||
std::deque<core::LocalizationSnapshot> pending_tf_;
|
||||
std::string map_frame_,odom_frame_,base_frame_,imu_frame_,lidar_frame_,map_path_,export_path_;
|
||||
bool publish_map_to_odom_{false},clock_rewound_{false};
|
||||
double last_clock_{-1},last_published_{-1};
|
||||
};
|
||||
|
||||
} // namespace field_localization::ros
|
||||
@@ -0,0 +1,137 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace field_localization::core {
|
||||
namespace {
|
||||
template<class T> void write(std::ostream &out,T value) {
|
||||
auto bytes=std::bit_cast<std::array<char,sizeof(T)>>(value);
|
||||
if constexpr(std::endian::native==std::endian::big) std::reverse(bytes.begin(),bytes.end());
|
||||
out.write(bytes.data(),bytes.size());
|
||||
}
|
||||
template<class T> T read(std::istream &in) {
|
||||
std::array<char,sizeof(T)> bytes{}; in.read(bytes.data(),bytes.size());
|
||||
if (!in) throw std::runtime_error("truncated cloud");
|
||||
if constexpr(std::endian::native==std::endian::big) std::reverse(bytes.begin(),bytes.end());
|
||||
return std::bit_cast<T>(bytes);
|
||||
}
|
||||
Pose3D parse_pose(std::istream &in) {
|
||||
Pose3D p; double x=0,y=0,z=0,w=0;
|
||||
in>>p.translation.x()>>p.translation.y()>>p.translation.z()>>x>>y>>z>>w;
|
||||
p.rotation=Eigen::Quaterniond{w,x,y,z};
|
||||
if (!in || !p.translation.allFinite() || !p.rotation.coeffs().allFinite() || p.rotation.norm()<1e-12)
|
||||
throw std::runtime_error("invalid pose record");
|
||||
p.rotation.normalize(); return p;
|
||||
}
|
||||
void pose_fields(std::ostream &out,const Pose3D &p) {
|
||||
out<<std::setprecision(17)<<p.translation.x()<<' '<<p.translation.y()<<' '<<p.translation.z()<<' '
|
||||
<<p.rotation.x()<<' '<<p.rotation.y()<<' '<<p.rotation.z()<<' '<<p.rotation.w();
|
||||
}
|
||||
}
|
||||
void write_cloud(const PointCloud &cloud,const std::filesystem::path &path) {
|
||||
if (!std::isfinite(cloud.timestamp_sec) || cloud.points.size()>1000000) throw std::runtime_error("invalid cloud record");
|
||||
std::ofstream out(path,std::ios::binary); out.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
out.write("FLPC0001",8); write<std::uint32_t>(out,1); write<double>(out,cloud.timestamp_sec);
|
||||
write<std::uint32_t>(out,static_cast<std::uint32_t>(cloud.points.size()));
|
||||
for (const auto &p:cloud.points) {
|
||||
write<double>(out,p.timestamp_sec);
|
||||
for (int j=0;j<3;++j) write<float>(out,p.position[j]);
|
||||
write<float>(out,p.intensity);
|
||||
}
|
||||
}
|
||||
PointCloud read_cloud(const std::filesystem::path &path) {
|
||||
std::ifstream in(path,std::ios::binary); std::array<char,8> magic{};
|
||||
in.read(magic.data(),magic.size());
|
||||
if (std::string(magic.data(),magic.size())!="FLPC0001" || read<std::uint32_t>(in)!=1)
|
||||
throw std::runtime_error("unsupported cloud format");
|
||||
PointCloud cloud; cloud.frame_id="lidar_link"; cloud.timestamp_sec=read<double>(in);
|
||||
const auto count=read<std::uint32_t>(in);
|
||||
if (!std::isfinite(cloud.timestamp_sec) || count>1000000 || std::filesystem::file_size(path)!=24+std::uint64_t(count)*24)
|
||||
throw std::runtime_error("invalid cloud size");
|
||||
cloud.points.reserve(count);
|
||||
for (std::uint32_t i=0;i<count;++i) {
|
||||
PointXYZI p; p.timestamp_sec=read<double>(in);
|
||||
for (int j=0;j<3;++j) p.position[j]=read<float>(in);
|
||||
p.intensity=read<float>(in);
|
||||
cloud.points.push_back(p);
|
||||
}
|
||||
return cloud;
|
||||
}
|
||||
void write_dataset_config(const CoreOptions &o,const std::filesystem::path &path) {
|
||||
std::ofstream out(path); out.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
out<<"FIELD_LIO_DATASET 1\ninitial_pose "; pose_fields(out,o.initial_pose);
|
||||
out<<"\nbase_from_imu "; pose_fields(out,o.base_from_imu);
|
||||
out<<"\nimu_from_lidar "; pose_fields(out,o.deskew.imu_from_sensor);
|
||||
out<<"\nscan_timing "<<static_cast<int>(o.deskew.timing)<<' '<<o.deskew.period_sec<<' '
|
||||
<<o.deskew.start_angle_rad<<' '<<o.deskew.counterclockwise<<' '<<o.deskew.stamp_at_end<<'\n';
|
||||
}
|
||||
CoreOptions read_dataset_config(const std::filesystem::path &path) {
|
||||
std::ifstream in(path); std::string token; int version=0;
|
||||
in>>token>>version;
|
||||
if (!in || token!="FIELD_LIO_DATASET" || version!=1) throw std::runtime_error("unsupported dataset");
|
||||
CoreOptions o;
|
||||
auto named_pose=[&](const char *name) { in>>token; if (token!=name) throw std::runtime_error("invalid dataset extrinsics"); return parse_pose(in); };
|
||||
o.initial_pose=named_pose("initial_pose"); o.base_from_imu=named_pose("base_from_imu");
|
||||
o.deskew.imu_from_sensor=named_pose("imu_from_lidar");
|
||||
int timing=0; in>>token>>timing>>o.deskew.period_sec>>o.deskew.start_angle_rad>>o.deskew.counterclockwise>>o.deskew.stamp_at_end;
|
||||
if (!in || token!="scan_timing" || timing<0 || timing>2 || !std::isfinite(o.deskew.period_sec) || o.deskew.period_sec<=0)
|
||||
throw std::runtime_error("invalid dataset timing");
|
||||
o.deskew.timing=static_cast<ScanTiming>(timing); return o;
|
||||
}
|
||||
void write_trajectory_sample(std::ostream &out,const TrajectorySample &sample) {
|
||||
out<<std::setprecision(17)<<sample.time<<' '; pose_fields(out,sample.pose); out<<'\n';
|
||||
}
|
||||
std::vector<TrajectorySample> read_trajectory(const std::filesystem::path &path) {
|
||||
std::ifstream in(path); if (!in) throw std::runtime_error("cannot open trajectory: "+path.string());
|
||||
std::vector<TrajectorySample> result; std::string line;
|
||||
while (std::getline(in,line)) {
|
||||
if (line.empty() || line[0]=='#') continue;
|
||||
std::istringstream row(line); double time=0; row>>time; auto pose=parse_pose(row);
|
||||
if (!std::isfinite(time) || (!result.empty() && time<=result.back().time)) throw std::runtime_error("trajectory time order");
|
||||
result.push_back({time,pose});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
std::optional<Pose3D> trajectory_pose(std::span<const TrajectorySample> samples,double time,double gap) {
|
||||
const auto b=std::lower_bound(samples.begin(),samples.end(),time,[](const auto &s,double t) { return s.time<t; });
|
||||
if (b==samples.end()) return std::nullopt;
|
||||
if (std::abs(b->time-time)<1e-9) return b->pose;
|
||||
if (b==samples.begin()) return std::nullopt;
|
||||
const auto &a=*(b-1);
|
||||
if (b->time-a.time>gap+1e-9) return std::nullopt;
|
||||
const double u=(time-a.time)/(b->time-a.time);
|
||||
return Pose3D{a.pose.rotation.slerp(u,b->pose.rotation),(1-u)*a.pose.translation+u*b->pose.translation};
|
||||
}
|
||||
Evaluation evaluate(std::span<const TrajectorySample> estimate,std::span<const TrajectorySample> truth) {
|
||||
Evaluation result; result.total=estimate.size();
|
||||
for (const auto &s:estimate) {
|
||||
const auto gt=trajectory_pose(truth,s.time); if (!gt) continue;
|
||||
result.ate_translation+=(s.pose.translation-gt->translation).squaredNorm();
|
||||
result.ate_rotation_rad+=log_so3(gt->rotation.conjugate()*s.pose.rotation).squaredNorm(); ++result.matched;
|
||||
const auto next_est=trajectory_pose(estimate,s.time+1.0,0.15),next_gt=trajectory_pose(truth,s.time+1.0);
|
||||
if (!next_est || !next_gt) continue;
|
||||
const Pose3D relative_truth=compose(inverse(*gt),*next_gt),relative_est=compose(inverse(s.pose),*next_est);
|
||||
const Pose3D error=compose(inverse(relative_truth),relative_est);
|
||||
result.rpe_translation+=error.translation.squaredNorm(); result.rpe_rotation_rad+=log_so3(error.rotation).squaredNorm();
|
||||
++result.relative_pairs;
|
||||
}
|
||||
if (result.matched) { result.ate_translation=std::sqrt(result.ate_translation/result.matched); result.ate_rotation_rad=std::sqrt(result.ate_rotation_rad/result.matched); }
|
||||
if (result.relative_pairs) { result.rpe_translation=std::sqrt(result.rpe_translation/result.relative_pairs); result.rpe_rotation_rad=std::sqrt(result.rpe_rotation_rad/result.relative_pairs); }
|
||||
return result;
|
||||
}
|
||||
const char *mode_name(TrackingMode mode) { return mode==TrackingMode::FULL ? "FULL" : "IMU_ONLY"; }
|
||||
const char *reason_name(FailureReason reason) {
|
||||
switch(reason) {
|
||||
case FailureReason::INITIALIZING:return "INITIALIZING"; case FailureReason::NONE:return "NONE";
|
||||
case FailureReason::NO_VALID_POINTS:return "NO_VALID_POINTS"; case FailureReason::INVALID_INPUT:return "INVALID_INPUT";
|
||||
case FailureReason::TIME_ORDER:return "TIME_ORDER"; case FailureReason::IMU_GAP:return "IMU_GAP";
|
||||
case FailureReason::IMU_COVERAGE:return "IMU_COVERAGE"; case FailureReason::REGISTRATION_FAILED:return "REGISTRATION_FAILED";
|
||||
case FailureReason::LIDAR_TIMEOUT:return "LIDAR_TIMEOUT"; case FailureReason::MAP_UNAVAILABLE:return "MAP_UNAVAILABLE";
|
||||
}
|
||||
return "UNKNOWN";
|
||||
}
|
||||
} // namespace field_localization::core
|
||||
@@ -0,0 +1,49 @@
|
||||
#include "field_localization/ros/conversion.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
#include <stdexcept>
|
||||
namespace field_localization::ros {
|
||||
core::PointCloud convert_cloud(const sensor_msgs::msg::PointCloud2 &msg) {
|
||||
const auto field=[&](const char *name,bool required)->const sensor_msgs::msg::PointField* {
|
||||
const auto it=std::find_if(msg.fields.begin(),msg.fields.end(),[&](const auto &f) { return f.name==name; });
|
||||
if (it==msg.fields.end()) { if (required) throw std::runtime_error("missing XYZ field"); return nullptr; }
|
||||
if (it->datatype!=sensor_msgs::msg::PointField::FLOAT32 || it->count<1 ||
|
||||
std::uint64_t(it->offset)+4>msg.point_step) {
|
||||
if (required) throw std::runtime_error("XYZ must be bounded FLOAT32 fields");
|
||||
return nullptr;
|
||||
}
|
||||
return &*it;
|
||||
};
|
||||
const auto *x=field("x",true),*y=field("y",true),*z=field("z",true),*intensity=field("intensity",false);
|
||||
if (msg.point_step==0 || std::uint64_t(msg.width)*msg.height>1000000 ||
|
||||
std::uint64_t(msg.width)*msg.point_step>msg.row_step ||
|
||||
std::uint64_t(msg.row_step)*msg.height>msg.data.size()) throw std::runtime_error("invalid PointCloud2 layout");
|
||||
const auto value=[&](std::size_t offset) {
|
||||
std::array<std::uint8_t,4> bytes{}; std::copy_n(msg.data.data()+offset,4,bytes.data());
|
||||
if (msg.is_bigendian!=(std::endian::native==std::endian::big)) std::reverse(bytes.begin(),bytes.end());
|
||||
return std::bit_cast<float>(bytes);
|
||||
};
|
||||
core::PointCloud cloud;
|
||||
cloud.timestamp_sec=msg.header.stamp.sec+1e-9*msg.header.stamp.nanosec; cloud.frame_id=msg.header.frame_id;
|
||||
cloud.points.reserve(std::size_t(msg.width)*msg.height);
|
||||
for (std::uint32_t row=0;row<msg.height;++row) for (std::uint32_t column=0;column<msg.width;++column) {
|
||||
const std::size_t offset=std::size_t(row)*msg.row_step+std::size_t(column)*msg.point_step;
|
||||
core::PointXYZI p; p.timestamp_sec=cloud.timestamp_sec;
|
||||
p.position={value(offset+x->offset),value(offset+y->offset),value(offset+z->offset)};
|
||||
p.intensity=intensity ? value(offset+intensity->offset) : 0;
|
||||
if (p.position.allFinite() && std::isfinite(p.intensity)) cloud.points.push_back(p);
|
||||
}
|
||||
return cloud;
|
||||
}
|
||||
core::Pose3D from_transform(const geometry_msgs::msg::Transform &t) {
|
||||
core::Pose3D p{Eigen::Quaterniond{t.rotation.w,t.rotation.x,t.rotation.y,t.rotation.z},
|
||||
Eigen::Vector3d{t.translation.x,t.translation.y,t.translation.z}};
|
||||
if (!p.translation.allFinite() || !p.rotation.coeffs().allFinite() || p.rotation.norm()<1e-12)
|
||||
throw std::runtime_error("invalid TF transform");
|
||||
p.rotation.normalize(); return p;
|
||||
}
|
||||
geometry_msgs::msg::Transform to_transform(const core::Pose3D &p) {
|
||||
geometry_msgs::msg::Transform t; t.translation.x=p.translation.x(); t.translation.y=p.translation.y(); t.translation.z=p.translation.z();
|
||||
t.rotation.w=p.rotation.w(); t.rotation.x=p.rotation.x(); t.rotation.y=p.rotation.y(); t.rotation.z=p.rotation.z(); return t;
|
||||
}
|
||||
} // namespace field_localization::ros
|
||||
@@ -1,234 +1,175 @@
|
||||
#include "field_localization/ros/localization_node.hpp"
|
||||
|
||||
#include <sensor_msgs/point_cloud2_iterator.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <functional>
|
||||
#include <numbers>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace {
|
||||
|
||||
const sensor_msgs::msg::PointField *
|
||||
find_field(const sensor_msgs::msg::PointCloud2 &cloud,
|
||||
const std::string &name) {
|
||||
const auto it =
|
||||
std::find_if(cloud.fields.begin(), cloud.fields.end(),
|
||||
[&name](const auto &field) { return field.name == name; });
|
||||
|
||||
return it != cloud.fields.end() ? &(*it) : nullptr;
|
||||
}
|
||||
|
||||
bool is_float32_field(const sensor_msgs::msg::PointField *field,
|
||||
std::uint32_t point_step) {
|
||||
if (field == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return field->datatype == sensor_msgs::msg::PointField::FLOAT32 &&
|
||||
field->count >= 1 &&
|
||||
static_cast<std::size_t>(field->offset) + sizeof(float) <= point_step;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace field_localization::ros {
|
||||
LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options)
|
||||
: Node("field_localization", options) {
|
||||
point_cloud_topic_ =
|
||||
declare_parameter<std::string>("point_cloud_topic", "/livox/lidar");
|
||||
|
||||
imu_topic_ = declare_parameter<std::string>("imu_topic", "/livox/imu");
|
||||
|
||||
// Subscribe to LiDAR point clouds.
|
||||
point_cloud_sub_ = create_subscription<sensor_msgs::msg::PointCloud2>(
|
||||
point_cloud_topic_, rclcpp::SensorDataQoS(),
|
||||
std::bind(&LocalizationNode::on_point_cloud, this,
|
||||
std::placeholders::_1));
|
||||
|
||||
// Subscribe to IMU measurements.
|
||||
imu_sub_ = create_subscription<sensor_msgs::msg::Imu>(
|
||||
imu_topic_, rclcpp::SensorDataQoS(),
|
||||
std::bind(&LocalizationNode::on_imu, this, std::placeholders::_1));
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Field localization node started.");
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Point cloud topic: %s",
|
||||
point_cloud_topic_.c_str());
|
||||
|
||||
RCLCPP_INFO(get_logger(), "IMU topic: %s", imu_topic_.c_str());
|
||||
|
||||
status_timer_ = create_wall_timer(
|
||||
std::chrono::seconds(5),
|
||||
std::bind(&LocalizationNode::print_localization_status, this));
|
||||
LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("field_localization",options) {
|
||||
map_frame_=declare_parameter<std::string>("map_frame","map"); odom_frame_=declare_parameter<std::string>("odom_frame","odom");
|
||||
base_frame_=declare_parameter<std::string>("base_frame","base_link"); imu_frame_=declare_parameter<std::string>("imu_frame","imu_link");
|
||||
lidar_frame_=declare_parameter<std::string>("lidar_frame","lidar_link");
|
||||
const auto mode=declare_parameter<std::string>("mode","localization");
|
||||
if (mode!="mapping" && mode!="localization") throw std::invalid_argument("mode must be mapping or localization");
|
||||
core_options_.map_mode=mode=="mapping" ? core::MapMode::MAPPING : core::MapMode::LOCALIZATION;
|
||||
map_path_=declare_parameter<std::string>("map_path",""); export_path_=declare_parameter<std::string>("export_map_path","");
|
||||
if (mode=="localization" && map_path_.empty()) throw std::invalid_argument("localization requires map_path; run explicit mapping first");
|
||||
if (mode=="localization") {
|
||||
std::string error;
|
||||
if (!core::read_map(map_path_,error)) throw std::runtime_error(error);
|
||||
}
|
||||
publish_map_to_odom_=declare_parameter<bool>("publish_map_to_odom",true);
|
||||
auto &pose=core_options_.initial_pose;
|
||||
pose.translation={declare_parameter<double>("initial_x",-5),declare_parameter<double>("initial_y",3),declare_parameter<double>("initial_z",0)};
|
||||
const double roll=declare_parameter<double>("initial_roll",0),pitch=declare_parameter<double>("initial_pitch",0),yaw=declare_parameter<double>("initial_yaw",0);
|
||||
pose.rotation=core::exp_so3({0,0,yaw})*core::exp_so3({0,pitch,0})*core::exp_so3({roll,0,0});
|
||||
core_options_.noise.gyro=declare_parameter<double>("gyro_noise_density",0.003);
|
||||
core_options_.noise.accel=declare_parameter<double>("accel_noise_density",0.03);
|
||||
core_options_.noise.gyro_bias_walk=declare_parameter<double>("gyro_bias_walk",1e-5);
|
||||
core_options_.noise.accel_bias_walk=declare_parameter<double>("accel_bias_walk",1e-4);
|
||||
core_options_.map_resolution=declare_parameter<double>("map_voxel_size",0.1);
|
||||
core_options_.registration.scan_voxel=declare_parameter<double>("scan_voxel_size",0.1);
|
||||
const auto timing=declare_parameter<std::string>("scan_timing","instantaneous");
|
||||
if (timing!="instantaneous" && timing!="azimuth") throw std::invalid_argument("scan_timing must be instantaneous or azimuth");
|
||||
core_options_.deskew.timing=timing=="azimuth" ? core::ScanTiming::AZIMUTH : core::ScanTiming::INSTANTANEOUS;
|
||||
core_options_.deskew.period_sec=declare_parameter<double>("scan_period_sec",0.1);
|
||||
core_options_.deskew.start_angle_rad=declare_parameter<double>("scan_start_angle_rad",-std::numbers::pi);
|
||||
core_options_.deskew.counterclockwise=declare_parameter<bool>("scan_counterclockwise",true);
|
||||
core_options_.deskew.stamp_at_end=declare_parameter<bool>("scan_stamp_at_end",true);
|
||||
if (!pose.translation.allFinite() || !pose.rotation.coeffs().allFinite()) throw std::invalid_argument("invalid initial pose");
|
||||
// Validate process-noise options before the first sensor callback.
|
||||
const core::ErrorStateFilter validate_noise(core_options_.noise); (void)validate_noise;
|
||||
tf_buffer_=std::make_unique<tf2_ros::Buffer>(get_clock());
|
||||
tf_listener_=std::make_unique<tf2_ros::TransformListener>(*tf_buffer_);
|
||||
broadcaster_=std::make_unique<tf2_ros::TransformBroadcaster>(this);
|
||||
odometry_pub_=create_publisher<nav_msgs::msg::Odometry>("~/odometry",10);
|
||||
status_pub_=create_publisher<std_msgs::msg::String>("~/status",10);
|
||||
const auto cloud_topic=declare_parameter<std::string>("point_cloud_topic","/scan/points");
|
||||
const auto imu_topic=declare_parameter<std::string>("imu_topic","/imu");
|
||||
point_cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(cloud_topic,rclcpp::SensorDataQoS().keep_last(5),
|
||||
[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) { on_point_cloud(std::move(msg)); });
|
||||
imu_sub_=create_subscription<sensor_msgs::msg::Imu>(imu_topic,rclcpp::SensorDataQoS().keep_last(400),
|
||||
[this](sensor_msgs::msg::Imu::ConstSharedPtr msg) { on_imu(std::move(msg)); });
|
||||
save_service_=create_service<std_srvs::srv::Trigger>("~/save_map",[this](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
|
||||
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
|
||||
if (!core_ || export_path_.empty()) { response->message="core not initialized or export_map_path empty"; return; }
|
||||
response->success=core_->export_map(export_path_,response->message);
|
||||
if (response->success) response->message=export_path_;
|
||||
});
|
||||
reset_service_=create_service<std_srvs::srv::Trigger>("~/reset",[this](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
|
||||
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
|
||||
core_.reset(); scans_.clear(); pending_tf_.clear(); clock_rewound_=false; last_clock_=-1; last_published_=-1;
|
||||
response->success=true; response->message="reset to configured known initial pose; no global search";
|
||||
});
|
||||
status_timer_=create_wall_timer(std::chrono::seconds(5),[this] { print_localization_status(); });
|
||||
RCLCPP_INFO(get_logger(),"mode=%s cloud=%s imu=%s TF=%s->%s enabled=%d; initial pose must be known",
|
||||
mode.c_str(),cloud_topic.c_str(),imu_topic.c_str(),map_frame_.c_str(),odom_frame_.c_str(),publish_map_to_odom_);
|
||||
}
|
||||
|
||||
void LocalizationNode::on_point_cloud(
|
||||
sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
core::PointCloud cloud;
|
||||
|
||||
cloud.timestamp_sec = rclcpp::Time(msg->header.stamp).seconds();
|
||||
|
||||
cloud.frame_id = msg->header.frame_id;
|
||||
|
||||
// 查找点云字段
|
||||
const auto *field_x = find_field(*msg, "x");
|
||||
const auto *field_y = find_field(*msg, "y");
|
||||
const auto *field_z = find_field(*msg, "z");
|
||||
const auto *field_intensity = find_field(*msg, "intensity");
|
||||
|
||||
// 检查 XYZ 字段
|
||||
if (!is_float32_field(field_x, msg->point_step) ||
|
||||
!is_float32_field(field_y, msg->point_step) ||
|
||||
!is_float32_field(field_z, msg->point_step)) {
|
||||
RCLCPP_ERROR(get_logger(), "PointCloud2 requires FLOAT32 x/y/z fields.");
|
||||
return;
|
||||
LocalizationNode::~LocalizationNode() {
|
||||
if (core_ && core_options_.map_mode==core::MapMode::MAPPING && !export_path_.empty()) {
|
||||
std::string error;
|
||||
if (!core_->export_map(export_path_,error)) RCLCPP_ERROR(get_logger(),"map export failed: %s",error.c_str());
|
||||
}
|
||||
|
||||
// 检查 intensity 字段
|
||||
if (field_intensity != nullptr &&
|
||||
!is_float32_field(field_intensity, msg->point_step)) {
|
||||
RCLCPP_WARN(get_logger(),
|
||||
"Unsupported intensity datatype. Intensity will be ignored.");
|
||||
field_intensity = nullptr;
|
||||
}
|
||||
bool LocalizationNode::check_clock() {
|
||||
const double time=now().seconds();
|
||||
if (last_clock_>=0 && time<last_clock_-1e-6) {
|
||||
clock_rewound_=true; scans_.clear(); pending_tf_.clear();
|
||||
RCLCPP_ERROR(get_logger(),"simulation time rewound; output halted, explicit ~/reset or restart required");
|
||||
}
|
||||
|
||||
// 检查点云内存布局
|
||||
const std::size_t minimum_row_size =
|
||||
static_cast<std::size_t>(msg->width) * msg->point_step;
|
||||
|
||||
const std::size_t required_data_size =
|
||||
static_cast<std::size_t>(msg->row_step) * msg->height;
|
||||
|
||||
if (msg->point_step == 0 || msg->row_step < minimum_row_size ||
|
||||
msg->data.size() < required_data_size) {
|
||||
RCLCPP_ERROR(get_logger(), "Invalid PointCloud2 memory layout.");
|
||||
return;
|
||||
}
|
||||
|
||||
const bool has_intensity = field_intensity != nullptr;
|
||||
|
||||
cloud.points.reserve(static_cast<std::size_t>(msg->width) * msg->height);
|
||||
|
||||
last_clock_=time; return !clock_rewound_;
|
||||
}
|
||||
bool LocalizationNode::ensure_core() {
|
||||
if (core_) return true;
|
||||
try {
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_x(*msg, "x");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_y(*msg, "y");
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_z(*msg, "z");
|
||||
|
||||
if (has_intensity) {
|
||||
sensor_msgs::PointCloud2ConstIterator<float> iter_intensity(*msg,
|
||||
"intensity");
|
||||
|
||||
for (; iter_x != iter_x.end();
|
||||
++iter_x, ++iter_y, ++iter_z, ++iter_intensity) {
|
||||
core::PointXYZI point;
|
||||
|
||||
point.position.x() = *iter_x;
|
||||
point.position.y() = *iter_y;
|
||||
point.position.z() = *iter_z;
|
||||
point.intensity = *iter_intensity;
|
||||
|
||||
point.timestamp_sec = cloud.timestamp_sec;
|
||||
|
||||
if (!point.position.allFinite() || !std::isfinite(point.intensity)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cloud.points.push_back(std::move(point));
|
||||
}
|
||||
} else {
|
||||
for (; iter_x != iter_x.end(); ++iter_x, ++iter_y, ++iter_z) {
|
||||
core::PointXYZI point;
|
||||
|
||||
point.position.x() = *iter_x;
|
||||
point.position.y() = *iter_y;
|
||||
point.position.z() = *iter_z;
|
||||
|
||||
point.timestamp_sec = cloud.timestamp_sec;
|
||||
|
||||
if (!point.position.allFinite() || !std::isfinite(point.intensity)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cloud.points.push_back(std::move(point));
|
||||
}
|
||||
core_options_.base_from_imu=from_transform(tf_buffer_->lookupTransform(base_frame_,imu_frame_,tf2::TimePointZero).transform);
|
||||
core_options_.deskew.imu_from_sensor=from_transform(tf_buffer_->lookupTransform(imu_frame_,lidar_frame_,tf2::TimePointZero).transform);
|
||||
core_=std::make_unique<core::LocalizationCore>(core_options_);
|
||||
if (core_options_.map_mode==core::MapMode::LOCALIZATION) {
|
||||
std::string error; if (!core_->load_map(map_path_,error)) { core_.reset(); throw std::runtime_error(error); }
|
||||
}
|
||||
} catch (const std::runtime_error &error) {
|
||||
RCLCPP_ERROR(get_logger(), "Failed to convert PointCloud2: %s",
|
||||
error.what());
|
||||
return;
|
||||
return true;
|
||||
} catch (const std::exception &e) {
|
||||
RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"waiting for fixed extrinsics/map: %s",e.what()); return false;
|
||||
}
|
||||
|
||||
if (cloud.points.empty()) {
|
||||
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000,
|
||||
"Received an empty or invalid point cloud.");
|
||||
return;
|
||||
}
|
||||
|
||||
++point_cloud_count_;
|
||||
|
||||
if (!core_.process_point_cloud(cloud)) {
|
||||
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000,
|
||||
"Rejected point cloud");
|
||||
return;
|
||||
}
|
||||
|
||||
RCLCPP_INFO_THROTTLE(
|
||||
get_logger(), *get_clock(), 5000,
|
||||
"Received %zu point clouds, latest cloud contains %zu points.",
|
||||
point_cloud_count_, cloud.points.size());
|
||||
}
|
||||
|
||||
void LocalizationNode::on_point_cloud(sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
if (!check_clock() || !ensure_core()) return;
|
||||
try {
|
||||
auto cloud=convert_cloud(*msg);
|
||||
if (cloud.frame_id!=lidar_frame_ && cloud.frame_id!=base_frame_ && cloud.frame_id!=imu_frame_)
|
||||
throw std::runtime_error("unexpected cloud frame; configure lidar_frame explicitly");
|
||||
const auto extrinsic=from_transform(tf_buffer_->lookupTransform(lidar_frame_,cloud.frame_id,tf2::TimePointZero).transform);
|
||||
for (auto &p:cloud.points) p.position=(extrinsic.rotation*p.position.cast<double>()+extrinsic.translation).cast<float>();
|
||||
cloud.frame_id=lidar_frame_;
|
||||
if (scans_.size()>=5) { scans_.pop_front(); RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"scan queue overflow"); }
|
||||
scans_.push_back(std::move(cloud)); drain_scans(); publish_estimate();
|
||||
} catch (const std::exception &e) { RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"cloud rejected: %s",e.what()); }
|
||||
}
|
||||
void LocalizationNode::on_imu(sensor_msgs::msg::Imu::ConstSharedPtr msg) {
|
||||
core::ImuData imu;
|
||||
|
||||
imu.timestamp_sec = rclcpp::Time(msg->header.stamp).seconds();
|
||||
|
||||
imu.frame_id = msg->header.frame_id;
|
||||
|
||||
imu.angular_velocity =
|
||||
Eigen::Vector3d{msg->angular_velocity.x, msg->angular_velocity.y,
|
||||
msg->angular_velocity.z};
|
||||
|
||||
imu.linear_acceleration =
|
||||
Eigen::Vector3d{msg->linear_acceleration.x, msg->linear_acceleration.y,
|
||||
msg->linear_acceleration.z};
|
||||
|
||||
++imu_count_;
|
||||
|
||||
if (!core_.process_imu(imu)) {
|
||||
RCLCPP_WARN_THROTTLE(get_logger(), *get_clock(), 5000,
|
||||
"Rejected IMU message");
|
||||
return;
|
||||
if (!check_clock() || !ensure_core()) return;
|
||||
try {
|
||||
const auto extrinsic=from_transform(tf_buffer_->lookupTransform(imu_frame_,msg->header.frame_id,tf2::TimePointZero).transform);
|
||||
if (extrinsic.translation.norm()>1e-6) throw std::runtime_error("IMU frame must refer to configured IMU origin");
|
||||
core::ImuData imu; imu.timestamp_sec=msg->header.stamp.sec+1e-9*msg->header.stamp.nanosec; imu.frame_id=imu_frame_;
|
||||
imu.angular_velocity=extrinsic.rotation*Eigen::Vector3d{msg->angular_velocity.x,msg->angular_velocity.y,msg->angular_velocity.z};
|
||||
imu.linear_acceleration=extrinsic.rotation*Eigen::Vector3d{msg->linear_acceleration.x,msg->linear_acceleration.y,msg->linear_acceleration.z};
|
||||
if (!core_->process_imu(imu)) RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"IMU rejected: %s",core::reason_name(core_->get_status().reason));
|
||||
drain_scans(); publish_estimate();
|
||||
} catch (const std::exception &e) { RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"IMU conversion rejected: %s",e.what()); }
|
||||
}
|
||||
void LocalizationNode::drain_scans() {
|
||||
while (!scans_.empty()) {
|
||||
const auto s=core_->get_status(); const double end=core::scan_window(scans_.front(),core_options_.deskew).second;
|
||||
if (!s.has_imu || s.last_imu_timestamp<end) {
|
||||
if (now().seconds()-end>0.2) { scans_.pop_front(); RCLCPP_WARN_THROTTLE(get_logger(),*get_clock(),5000,"scan expired waiting for IMU"); continue; }
|
||||
break;
|
||||
}
|
||||
core_->process_point_cloud(scans_.front()); scans_.pop_front();
|
||||
}
|
||||
}
|
||||
void LocalizationNode::publish_estimate() {
|
||||
if (!core_) return;
|
||||
const auto snapshot=core_->get_snapshot();
|
||||
if (!snapshot.status.has_imu || now().seconds()-snapshot.status.state_timestamp>0.1) { pending_tf_.clear(); return; }
|
||||
if (snapshot.status.state_timestamp>last_published_) {
|
||||
const auto stamp=rclcpp::Time(static_cast<std::int64_t>(std::llround(snapshot.status.state_timestamp*1e9)),RCL_ROS_TIME);
|
||||
nav_msgs::msg::Odometry odom; odom.header.stamp=stamp; odom.header.frame_id=map_frame_; odom.child_frame_id=base_frame_;
|
||||
const auto transform=to_transform(snapshot.pose);
|
||||
odom.pose.pose.position.x=transform.translation.x; odom.pose.pose.position.y=transform.translation.y; odom.pose.pose.position.z=transform.translation.z;
|
||||
odom.pose.pose.orientation=transform.rotation;
|
||||
Eigen::Matrix<double,6,18> jacobian=Eigen::Matrix<double,6,18>::Zero();
|
||||
jacobian.block<3,3>(0,0).setIdentity();
|
||||
const auto imu_from_base=core::inverse(core_options_.base_from_imu);
|
||||
jacobian.block<3,3>(0,6)=-snapshot.filter.state.pose.rotation.toRotationMatrix()*core::skew(imu_from_base.translation);
|
||||
jacobian.block<3,3>(3,6)=core_options_.base_from_imu.rotation.toRotationMatrix();
|
||||
const core::Matrix6 covariance=jacobian*snapshot.filter.covariance*jacobian.transpose();
|
||||
for (int i=0;i<6;++i) for (int j=0;j<6;++j) odom.pose.covariance[6*i+j]=covariance(i,j);
|
||||
odometry_pub_->publish(odom); last_published_=snapshot.status.state_timestamp;
|
||||
pending_tf_.push_back(snapshot); if (pending_tf_.size()>30) pending_tf_.pop_front();
|
||||
}
|
||||
if (!publish_map_to_odom_) { pending_tf_.clear(); return; }
|
||||
while (!pending_tf_.empty()) {
|
||||
const auto &s=pending_tf_.front();
|
||||
if (now().seconds()-s.status.state_timestamp>0.1) { pending_tf_.pop_front(); continue; }
|
||||
const auto stamp=rclcpp::Time(static_cast<std::int64_t>(std::llround(s.status.state_timestamp*1e9)),RCL_ROS_TIME);
|
||||
try {
|
||||
const auto odom_from_base=from_transform(tf_buffer_->lookupTransform(odom_frame_,base_frame_,stamp).transform);
|
||||
geometry_msgs::msg::TransformStamped tf; tf.header.stamp=stamp; tf.header.frame_id=map_frame_; tf.child_frame_id=odom_frame_;
|
||||
tf.transform=to_transform(core::compose(s.pose,core::inverse(odom_from_base))); broadcaster_->sendTransform(tf); pending_tf_.pop_front();
|
||||
} catch (const tf2::TransformException &) { break; }
|
||||
}
|
||||
|
||||
RCLCPP_INFO_THROTTLE(get_logger(), *get_clock(), 5000,
|
||||
"Received %zu IMU messages. "
|
||||
"Gyro: [%.3f, %.3f, %.3f] rad/s",
|
||||
imu_count_, imu.angular_velocity.x(),
|
||||
imu.angular_velocity.y(), imu.angular_velocity.z());
|
||||
}
|
||||
|
||||
void LocalizationNode::print_localization_status() {
|
||||
const auto status = core_.get_status();
|
||||
|
||||
RCLCPP_INFO(get_logger(), "========== Localization Status ==========");
|
||||
|
||||
RCLCPP_INFO(
|
||||
get_logger(), "IMU: received=%zu, rejected=%zu, last_timestamp=%.6f",
|
||||
status.imu_count, status.rejected_imu_count, status.last_imu_timestamp);
|
||||
|
||||
RCLCPP_INFO(get_logger(),
|
||||
"PointCloud: received=%zu, rejected=%zu, last_timestamp=%.6f",
|
||||
status.point_cloud_count, status.rejected_point_cloud_count,
|
||||
status.last_point_cloud_timestamp);
|
||||
|
||||
RCLCPP_INFO(get_logger(), "Latest valid point count: %zu",
|
||||
status.last_point_count);
|
||||
|
||||
RCLCPP_INFO(get_logger(), "==========================================");
|
||||
if (!core_) { RCLCPP_INFO(get_logger(),"localization waiting for fixed sensor TF"); return; }
|
||||
const auto s=core_->get_status(); std::ostringstream directions;
|
||||
for (int i=0;i<s.degenerate_dimensions;++i) directions<<'['<<s.degenerate_basis.col(i).transpose()<<"] ";
|
||||
RCLCPP_INFO(get_logger(),"mode=%s reason=%s%s IMU=%zu rejected=%zu clouds=%zu rejected=%zu valid=%zu rmse=%.5fm inliers=%zu (%.1f%%) degenerate=%d keyframes=%zu map=%zu",
|
||||
core::mode_name(s.mode),core::reason_name(s.reason),clock_rewound_ ? " CLOCK_REWOUND" : "",s.imu_count,s.rejected_imu_count,
|
||||
s.point_cloud_count,s.rejected_point_cloud_count,s.last_point_count,s.registration_rmse,s.inlier_count,100*s.inlier_ratio,
|
||||
s.degenerate_dimensions,s.keyframe_count,s.map_point_count);
|
||||
RCLCPP_INFO(get_logger(),"null directions [map dx dy dz, IMU droll dpitch dyaw]: %s",directions.str().c_str());
|
||||
std_msgs::msg::String message; message.data=std::string(core::mode_name(s.mode))+","+core::reason_name(s.reason)+","+std::to_string(s.degenerate_dimensions);
|
||||
status_pub_->publish(message);
|
||||
}
|
||||
|
||||
} // namespace field_localization::ros
|
||||
@@ -8,7 +8,8 @@ int main(int argc, char **argv) {
|
||||
rclcpp::init(argc, argv);
|
||||
|
||||
try {
|
||||
auto node = std::make_shared<field_localization::ros::LocalizationNode>();
|
||||
rclcpp::NodeOptions options;
|
||||
auto node = std::make_shared<field_localization::ros::LocalizationNode>(options);
|
||||
|
||||
rclcpp::spin(node);
|
||||
} catch (const std::exception &error) {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "field_localization/ros/conversion.hpp"
|
||||
#include <rclcpp/rclcpp.hpp>
|
||||
#include <sensor_msgs/msg/imu.hpp>
|
||||
#include <geometry_msgs/msg/pose_stamped.hpp>
|
||||
#include <tf2_ros/buffer.hpp>
|
||||
#include <tf2_ros/transform_listener.hpp>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <thread>
|
||||
using namespace field_localization;
|
||||
class Recorder:public rclcpp::Node {
|
||||
public:
|
||||
explicit Recorder(const rclcpp::NodeOptions &options):Node("field_localization_record",options) {
|
||||
directory_=declare_parameter<std::string>("output_directory","");
|
||||
if (directory_.empty() || std::filesystem::exists(directory_/"imu.csv")) throw std::runtime_error("output_directory must be new");
|
||||
duration_=declare_parameter<double>("duration_sec",120);
|
||||
if (!std::isfinite(duration_) || duration_<=0) throw std::runtime_error("invalid duration");
|
||||
config_.initial_pose.translation={declare_parameter<double>("initial_x",-5),declare_parameter<double>("initial_y",3),declare_parameter<double>("initial_z",0)};
|
||||
config_.initial_pose.rotation=core::exp_so3({0,0,declare_parameter<double>("initial_yaw",0)});
|
||||
std::filesystem::create_directories(directory_/"clouds");
|
||||
imu_.open(directory_/"imu.csv"); scans_.open(directory_/"scans.csv"); truth_.open(directory_/"truth.tum");
|
||||
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_<<std::setprecision(17)<<"timestamp,gx,gy,gz,ax,ay,az\n"; scans_<<std::setprecision(17)<<"timestamp,file\n";
|
||||
buffer_=std::make_unique<tf2_ros::Buffer>(get_clock()); listener_=std::make_unique<tf2_ros::TransformListener>(*buffer_);
|
||||
cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(declare_parameter<std::string>("point_cloud_topic","/scan/points_filtered"),
|
||||
rclcpp::SensorDataQoS().keep_last(20),[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) {
|
||||
if (!ready_ || done_) return;
|
||||
auto cloud=ros::convert_cloud(*msg);
|
||||
if (cloud.timestamp_sec<start_ || cloud.timestamp_sec<=last_scan_ || cloud.timestamp_sec>start_+duration_) return;
|
||||
const auto tf=ros::from_transform(buffer_->lookupTransform("lidar_link",cloud.frame_id,tf2::TimePointZero).transform);
|
||||
for (auto &p:cloud.points) p.position=(tf.rotation*p.position.cast<double>()+tf.translation).cast<float>();
|
||||
cloud.frame_id="lidar_link";
|
||||
const auto file="clouds/"+std::to_string(scan_count_++)+".flpc"; core::write_cloud(cloud,directory_/file);
|
||||
scans_<<cloud.timestamp_sec<<','<<file<<'\n'; scans_.flush(); last_scan_=cloud.timestamp_sec;
|
||||
});
|
||||
imu_sub_=create_subscription<sensor_msgs::msg::Imu>("/imu",rclcpp::SensorDataQoS().keep_last(1000),
|
||||
[this](sensor_msgs::msg::Imu::ConstSharedPtr msg) {
|
||||
if (done_) return;
|
||||
const double t=msg->header.stamp.sec+1e-9*msg->header.stamp.nanosec;
|
||||
if (t<=last_imu_) return;
|
||||
if (!ready_) {
|
||||
try {
|
||||
config_.base_from_imu=ros::from_transform(buffer_->lookupTransform("base_link","imu_link",tf2::TimePointZero).transform);
|
||||
config_.deskew.imu_from_sensor=ros::from_transform(buffer_->lookupTransform("imu_link","lidar_link",tf2::TimePointZero).transform);
|
||||
} catch (const tf2::TransformException &) { return; }
|
||||
core::write_dataset_config(config_,directory_/"config.txt"); start_=t; ready_=true;
|
||||
RCLCPP_INFO(get_logger(),"recording started at sim %.3f for %.1f sec",start_,duration_);
|
||||
}
|
||||
if (t>start_+duration_+0.1) { imu_complete_=true; return; }
|
||||
if (msg->header.frame_id!="imu_link") throw std::runtime_error("recorder expects imu_link input");
|
||||
const auto &w=msg->angular_velocity; const auto &a=msg->linear_acceleration;
|
||||
imu_<<t<<','<<w.x<<','<<w.y<<','<<w.z<<','<<a.x<<','<<a.y<<','<<a.z<<'\n';
|
||||
last_imu_=t; if (++imu_count_%100==0) imu_.flush();
|
||||
});
|
||||
truth_sub_=create_subscription<geometry_msgs::msg::PoseStamped>("/evaluation/ground_truth",1000,
|
||||
[this](geometry_msgs::msg::PoseStamped::ConstSharedPtr msg) {
|
||||
if (done_) return;
|
||||
const double t=msg->header.stamp.sec+1e-9*msg->header.stamp.nanosec;
|
||||
if (t<=last_truth_) return;
|
||||
if (ready_ && t>start_+duration_+0.1) { truth_complete_=true; return; }
|
||||
const auto &p=msg->pose; core::Pose3D pose{Eigen::Quaterniond{p.orientation.w,p.orientation.x,p.orientation.y,p.orientation.z},
|
||||
Eigen::Vector3d{p.position.x,p.position.y,p.position.z}};
|
||||
if (!pose.translation.allFinite() || !pose.rotation.coeffs().allFinite() || pose.rotation.norm()<1e-12) throw std::runtime_error("invalid independent truth");
|
||||
pose.rotation.normalize(); core::write_trajectory_sample(truth_,{t,pose}); last_truth_=t;
|
||||
});
|
||||
timer_=create_wall_timer(std::chrono::milliseconds(200),[this] {
|
||||
if (imu_complete_ && truth_complete_) {
|
||||
imu_.flush(); scans_.flush(); truth_.flush(); done_=true;
|
||||
std::ofstream(directory_/"complete.txt")<<"imu="<<imu_count_<<" scans="<<scan_count_<<"\nIMU sensor noise: zero (Gazebo configuration)\n";
|
||||
}
|
||||
});
|
||||
}
|
||||
bool done() const { return done_; }
|
||||
private:
|
||||
std::filesystem::path directory_;
|
||||
core::CoreOptions config_;
|
||||
double duration_{120},start_{0},last_imu_{-1},last_scan_{-1},last_truth_{-1};
|
||||
std::size_t imu_count_{0},scan_count_{0};
|
||||
bool ready_{false},done_{false},imu_complete_{false},truth_complete_{false};
|
||||
std::ofstream imu_,scans_,truth_;
|
||||
std::unique_ptr<tf2_ros::Buffer> buffer_;
|
||||
std::unique_ptr<tf2_ros::TransformListener> listener_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::PointCloud2>::SharedPtr cloud_sub_;
|
||||
rclcpp::Subscription<sensor_msgs::msg::Imu>::SharedPtr imu_sub_;
|
||||
rclcpp::Subscription<geometry_msgs::msg::PoseStamped>::SharedPtr truth_sub_;
|
||||
rclcpp::TimerBase::SharedPtr timer_;
|
||||
};
|
||||
int main(int argc,char **argv) {
|
||||
rclcpp::init(argc,argv); int result=0;
|
||||
try {
|
||||
rclcpp::NodeOptions options;
|
||||
auto node=std::make_shared<Recorder>(options);
|
||||
rclcpp::executors::SingleThreadedExecutor executor; executor.add_node(node);
|
||||
while (rclcpp::ok() && !node->done()) { executor.spin_some(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); }
|
||||
} catch (const std::exception &e) { std::fprintf(stderr,"recording failed: %s\n",e.what()); result=1; }
|
||||
rclcpp::shutdown(); return result;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include <chrono>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <numbers>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <unordered_map>
|
||||
using namespace field_localization::core;
|
||||
int main(int argc,char **argv) {
|
||||
try {
|
||||
std::unordered_map<std::string,std::string> args;
|
||||
for (int i=1;i<argc;i+=2) {
|
||||
if (i+1>=argc) throw std::runtime_error("arguments require values");
|
||||
args[argv[i]]=argv[i+1];
|
||||
}
|
||||
if (!args.contains("--dataset") || !args.contains("--mode") || !args.contains("--map") || !args.contains("--output"))
|
||||
throw std::runtime_error("usage: field_localization_replay --dataset DIR --mode mapping|localization --map FILE --output DIR");
|
||||
const std::filesystem::path dataset=args.at("--dataset"),output=args.at("--output");
|
||||
auto options=read_dataset_config(dataset/"config.txt");
|
||||
if (args.at("--mode")!="mapping" && args.at("--mode")!="localization") throw std::runtime_error("invalid mode");
|
||||
options.map_mode=args.at("--mode")=="mapping" ? MapMode::MAPPING : MapMode::LOCALIZATION;
|
||||
LocalizationCore core(options); std::string error;
|
||||
if (options.map_mode==MapMode::LOCALIZATION && !core.load_map(args.at("--map"),error)) throw std::runtime_error(error);
|
||||
std::ifstream input(dataset/"imu.csv"); if (!input) throw std::runtime_error("missing imu.csv");
|
||||
std::vector<ImuData> imu; std::string line; std::getline(input,line);
|
||||
while (std::getline(input,line)) {
|
||||
std::replace(line.begin(),line.end(),',',' '); std::istringstream row(line); ImuData sample;
|
||||
row>>sample.timestamp_sec>>sample.angular_velocity.x()>>sample.angular_velocity.y()>>sample.angular_velocity.z()
|
||||
>>sample.linear_acceleration.x()>>sample.linear_acceleration.y()>>sample.linear_acceleration.z();
|
||||
if (!row || !valid_imu(sample) || (!imu.empty() && sample.timestamp_sec<=imu.back().timestamp_sec)) throw std::runtime_error("invalid IMU sequence");
|
||||
imu.push_back(sample);
|
||||
}
|
||||
std::filesystem::create_directories(output);
|
||||
std::ofstream trajectory(output/"trajectory.tum"),status(output/"status.csv");
|
||||
trajectory.exceptions(std::ios::badbit|std::ios::failbit); status.exceptions(std::ios::badbit|std::ios::failbit);
|
||||
status<<"scan_time,state_time,mode,reason,rmse,inliers,inlier_ratio,degenerate,bgx,bgy,bgz,bax,bay,baz,elapsed_ms\n";
|
||||
std::ifstream scans(dataset/"scans.csv"); if (!scans) throw std::runtime_error("missing scans.csv"); std::getline(scans,line);
|
||||
std::size_t index=0,total=0,full=0; std::vector<TrajectorySample> estimated; std::vector<double> latency;
|
||||
while (std::getline(scans,line)) {
|
||||
const auto comma=line.find(','); if (comma==std::string::npos) throw std::runtime_error("invalid scan index");
|
||||
const auto relative=std::filesystem::path(line.substr(comma+1));
|
||||
if (relative.is_absolute() || relative.string().find("..")!=std::string::npos) throw std::runtime_error("unsafe scan path");
|
||||
auto cloud=read_cloud(dataset/relative); const double end=scan_window(cloud,options.deskew).second;
|
||||
while (index<imu.size() && (!core.get_status().has_imu || core.get_status().last_imu_timestamp<end)) {
|
||||
if (!core.process_imu(imu[index++])) throw std::runtime_error("IMU rejected during replay");
|
||||
}
|
||||
const auto begin=std::chrono::steady_clock::now(); core.process_point_cloud(cloud);
|
||||
const double ms=std::chrono::duration<double,std::milli>(std::chrono::steady_clock::now()-begin).count(); latency.push_back(ms);
|
||||
const auto s=core.get_snapshot(); const auto &state=s.filter.state;
|
||||
if (s.status.mode==TrackingMode::FULL) ++full;
|
||||
++total;
|
||||
if (estimated.empty() || s.status.state_timestamp>estimated.back().time) {
|
||||
estimated.push_back({s.status.state_timestamp,s.pose}); write_trajectory_sample(trajectory,estimated.back());
|
||||
}
|
||||
status<<std::setprecision(12)<<cloud.timestamp_sec<<','<<s.status.state_timestamp<<','<<mode_name(s.status.mode)<<','<<reason_name(s.status.reason)
|
||||
<<','<<s.status.registration_rmse<<','<<s.status.inlier_count<<','<<s.status.inlier_ratio<<','<<s.status.degenerate_dimensions<<','
|
||||
<<state.gyro_bias.x()<<','<<state.gyro_bias.y()<<','<<state.gyro_bias.z()<<','<<state.accel_bias.x()<<','<<state.accel_bias.y()<<','<<state.accel_bias.z()<<','<<ms<<'\n';
|
||||
}
|
||||
if (options.map_mode==MapMode::MAPPING && !core.export_map(args.at("--map"),error)) throw std::runtime_error(error);
|
||||
if (total==0) throw std::runtime_error("empty replay");
|
||||
std::sort(latency.begin(),latency.end());
|
||||
std::ostringstream report; report<<std::setprecision(9)<<"scans="<<total<<" FULL="<<full<<" FULL_ratio="<<double(full)/total
|
||||
<<" scan_p95_ms="<<latency[static_cast<std::size_t>(0.95*(latency.size()-1))]<<'\n';
|
||||
if (std::filesystem::exists(dataset/"truth.tum")) {
|
||||
const auto truth=read_trajectory(dataset/"truth.tum"); const auto metric=evaluate(estimated,truth);
|
||||
if (metric.matched==0 || metric.relative_pairs==0) throw std::runtime_error("insufficient matching ground truth");
|
||||
report<<"matched="<<metric.matched<<'/'<<metric.total<<" coverage="<<double(metric.matched)/metric.total<<" RPE_pairs="<<metric.relative_pairs<<'\n'
|
||||
<<"ATE_translation_RMSE_m="<<metric.ate_translation<<" ATE_rotation_RMSE_deg="<<metric.ate_rotation_rad*180/std::numbers::pi<<'\n'
|
||||
<<"RPE_1s_translation_RMSE_m="<<metric.rpe_translation<<" RPE_1s_rotation_RMSE_deg="<<metric.rpe_rotation_rad*180/std::numbers::pi<<'\n';
|
||||
} else report<<"ground_truth=UNVERIFIED\n";
|
||||
std::cout<<report.str(); std::ofstream(output/"metrics.txt")<<report.str(); return 0;
|
||||
} catch (const std::exception &e) { std::cerr<<e.what()<<'\n'; return 1; }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "field_localization/core/dataset.hpp"
|
||||
#include "test_util.hpp"
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
using namespace field_localization::core;
|
||||
int main() {
|
||||
const auto dir=std::filesystem::temp_directory_path()/"field_lio_dataset_tests";
|
||||
std::filesystem::create_directories(dir);
|
||||
PointCloud cloud; cloud.timestamp_sec=1;
|
||||
PointXYZI p; p.timestamp_sec=0.99; p.position={0.01F,-2,3}; p.intensity=4; cloud.points.push_back(p);
|
||||
p.position.x()=std::numeric_limits<float>::infinity(); cloud.points.push_back(p);
|
||||
write_cloud(cloud,dir/"scan.flpc"); const auto read=read_cloud(dir/"scan.flpc");
|
||||
CHECK(read.points.size()==2); CHECK_NEAR(read.timestamp_sec,1,1e-12);
|
||||
CHECK_NEAR(read.points[0].timestamp_sec,0.99,1e-12); CHECK(read.points[0].position==cloud.points[0].position);
|
||||
CHECK(!read.points[1].position.allFinite());
|
||||
CoreOptions options; options.initial_pose.translation={-5,3,0}; options.deskew.imu_from_sensor.translation={-0.0935,-0.1512,0.2552};
|
||||
write_dataset_config(options,dir/"config.txt"); const auto config=read_dataset_config(dir/"config.txt");
|
||||
CHECK(config.initial_pose.translation==options.initial_pose.translation);
|
||||
CHECK(config.deskew.imu_from_sensor.translation==options.deskew.imu_from_sensor.translation);
|
||||
std::vector<TrajectorySample> truth,estimate;
|
||||
for (int i=0;i<=200;++i) {
|
||||
const double t=0.01*i; Pose3D pose{exp_so3({0.01*t,-0.03*t,0.1*t}),Eigen::Vector3d{t,0.2*t,0.1*t*t}};
|
||||
truth.push_back({t,pose}); pose.translation.x()+=0.1; estimate.push_back({t,pose});
|
||||
}
|
||||
const auto metric=evaluate(estimate,truth);
|
||||
CHECK(metric.matched==estimate.size()); CHECK(metric.relative_pairs>0);
|
||||
CHECK_NEAR(metric.ate_translation,0.1,1e-12); CHECK_NEAR(metric.ate_rotation_rad,0,1e-12);
|
||||
CHECK(metric.rpe_translation<1e-12); CHECK(metric.rpe_rotation_rad<1e-12);
|
||||
const std::vector<TrajectorySample> sparse{{0,{}},{1,{}}}; CHECK(!trajectory_pose(sparse,0.5));
|
||||
{ std::ofstream out(dir/"broken"); out<<"FLPC0001"; }
|
||||
bool rejected=false; try { (void)read_cloud(dir/"broken"); } catch (const std::exception &) { rejected=true; }
|
||||
CHECK(rejected); std::filesystem::remove_all(dir);
|
||||
return sentry_nav_test::Summary("DatasetAndMetrics");
|
||||
}
|
||||
@@ -80,6 +80,23 @@ int main() {
|
||||
CHECK(!stationary.process_point_cloud(empty));
|
||||
CHECK(stationary.get_status().reason==FailureReason::NO_VALID_POINTS);
|
||||
CHECK(stationary.get_pose().translation.allFinite());
|
||||
LocalizationCore moving;
|
||||
ImuData accelerated; accelerated.linear_acceleration={1,0,9.81};
|
||||
for (int i=0;i<=100;++i) {
|
||||
accelerated.timestamp_sec=0.01*i;
|
||||
CHECK(moving.process_imu(accelerated));
|
||||
}
|
||||
CHECK_NEAR(moving.get_pose().translation.x(),0.5,1e-9);
|
||||
CHECK_NEAR(moving.get_snapshot().filter.state.velocity.x(),1,1e-9);
|
||||
CHECK(moving.get_status().mode==TrackingMode::IMU_ONLY);
|
||||
accelerated.timestamp_sec=0.5;
|
||||
CHECK(!moving.process_imu(accelerated));
|
||||
CHECK(moving.get_status().reason==FailureReason::TIME_ORDER);
|
||||
PointCloud backwards=cloud; backwards.timestamp_sec=0.5;
|
||||
CHECK(!core.process_point_cloud(backwards));
|
||||
CHECK(core.get_status().mode==TrackingMode::IMU_ONLY);
|
||||
CHECK(core.get_status().reason==FailureReason::TIME_ORDER);
|
||||
CHECK(core.get_pose().translation.allFinite());
|
||||
// 7. 检查重置
|
||||
core.reset();
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#include "field_localization/ros/conversion.hpp"
|
||||
#include "test_util.hpp"
|
||||
#include <array>
|
||||
#include <bit>
|
||||
using namespace field_localization;
|
||||
int main() {
|
||||
sensor_msgs::msg::PointCloud2 msg; msg.width=2; msg.height=2; msg.point_step=16; msg.row_step=40;
|
||||
msg.is_bigendian=true; msg.data.resize(80); msg.header.stamp.sec=3;
|
||||
for (const auto &[name,offset]:{std::pair{"x",0U},std::pair{"y",4U},std::pair{"z",8U},std::pair{"intensity",12U}}) {
|
||||
sensor_msgs::msg::PointField f; f.name=name; f.offset=offset; f.datatype=sensor_msgs::msg::PointField::FLOAT32; f.count=1; msg.fields.push_back(f);
|
||||
}
|
||||
for (std::size_t row=0;row<2;++row) for (std::size_t col=0;col<2;++col) for (std::size_t k=0;k<4;++k) {
|
||||
auto bytes=std::bit_cast<std::array<std::uint8_t,4>>(static_cast<float>(row*10+col+k));
|
||||
if constexpr(std::endian::native==std::endian::little) std::reverse(bytes.begin(),bytes.end());
|
||||
std::copy(bytes.begin(),bytes.end(),msg.data.begin()+static_cast<std::ptrdiff_t>(row*40+col*16+k*4));
|
||||
}
|
||||
const auto cloud=ros::convert_cloud(msg); CHECK(cloud.points.size()==4);
|
||||
CHECK_NEAR(cloud.points[2].position.x(),10,1e-6); CHECK_NEAR(cloud.points[3].intensity,14,1e-6);
|
||||
msg.data.resize(10); bool rejected=false;
|
||||
try { (void)ros::convert_cloud(msg); } catch (const std::exception &) { rejected=true; } CHECK(rejected);
|
||||
const core::Pose3D map_from_base{core::exp_so3({0,0,0.3}),Eigen::Vector3d{1,2,0}};
|
||||
const core::Pose3D odom_from_base{core::exp_so3({0,0,0.2}),Eigen::Vector3d{0.5,1,0}};
|
||||
const auto map_from_odom=core::compose(map_from_base,core::inverse(odom_from_base));
|
||||
const auto recovered=core::compose(ros::from_transform(ros::to_transform(map_from_odom)),odom_from_base);
|
||||
CHECK((recovered.translation-map_from_base.translation).norm()<1e-12);
|
||||
CHECK(core::log_so3(recovered.rotation.conjugate()*map_from_base.rotation).norm()<1e-12);
|
||||
return sentry_nav_test::Summary("RosConversion");
|
||||
}
|
||||
@@ -13,6 +13,8 @@ end
|
||||
|
||||
local ros_direct_packages = {
|
||||
"rclcpp",
|
||||
"std_srvs",
|
||||
"tf2",
|
||||
"sensor_msgs",
|
||||
"nav_msgs",
|
||||
"geometry_msgs",
|
||||
@@ -20,6 +22,12 @@ local ros_direct_packages = {
|
||||
}
|
||||
|
||||
local message_packages = {
|
||||
"statistics_msgs",
|
||||
"rosgraph_msgs",
|
||||
"rcl_interfaces",
|
||||
"service_msgs",
|
||||
"type_description_interfaces",
|
||||
"std_srvs",
|
||||
"sensor_msgs",
|
||||
"nav_msgs",
|
||||
"geometry_msgs",
|
||||
@@ -213,7 +221,11 @@ local function ros_common()
|
||||
|
||||
local config = get_ros_config()
|
||||
|
||||
target:add("includedirs", config.includes)
|
||||
local project_include = path.join(target:scriptdir(), "include")
|
||||
for _, dir in ipairs(config.includes) do
|
||||
if dir ~= project_include then target:add("sysincludedirs", dir) end
|
||||
end
|
||||
target:add("includedirs", project_include)
|
||||
|
||||
target:add(
|
||||
"defines",
|
||||
@@ -222,6 +234,7 @@ local function ros_common()
|
||||
|
||||
target:add("linkdirs", config.prefix .. "/lib")
|
||||
target:add("rpathdirs", config.prefix .. "/lib")
|
||||
target:add("runenvs", "LD_LIBRARY_PATH", config.prefix .. "/lib")
|
||||
|
||||
target:add(
|
||||
"linkgroups",
|
||||
@@ -243,6 +256,7 @@ target("field_localization_core")
|
||||
set_languages("c++23")
|
||||
|
||||
add_files("src/core/*.cpp")
|
||||
add_cxxflags("-fPIC")
|
||||
|
||||
add_includedirs("include", {public = true})
|
||||
add_packages("pkgconfig::eigen3", {public = true})
|
||||
@@ -272,7 +286,7 @@ target("field_localization_ros")
|
||||
set_kind("shared")
|
||||
set_languages("c++23")
|
||||
|
||||
add_files("src/ros/localization_node.cpp")
|
||||
add_files("src/ros/localization_node.cpp", "src/ros/conversion.cpp")
|
||||
|
||||
add_deps("field_localization_core")
|
||||
|
||||
@@ -336,3 +350,36 @@ target("test_map_management")
|
||||
add_files("tests/test_map_management.cpp")
|
||||
add_deps("field_localization_core")
|
||||
add_tests("default", {group = "unit"})
|
||||
|
||||
|
||||
target("field_localization_replay")
|
||||
set_targetdir("$(builddir)/bin")
|
||||
set_kind("binary")
|
||||
set_languages("c++23")
|
||||
add_files("src/tools/replay.cpp")
|
||||
add_deps("field_localization_core")
|
||||
|
||||
target("field_localization_record")
|
||||
set_targetdir("$(builddir)/bin")
|
||||
set_kind("binary")
|
||||
set_languages("c++23")
|
||||
add_files("src/tools/record.cpp")
|
||||
add_deps("field_localization_ros")
|
||||
ros_common()
|
||||
|
||||
target("test_dataset")
|
||||
set_targetdir("$(builddir)/bin")
|
||||
set_kind("binary")
|
||||
set_languages("c++23")
|
||||
add_files("tests/test_dataset.cpp")
|
||||
add_deps("field_localization_core")
|
||||
add_tests("default", {group = "unit"})
|
||||
|
||||
target("test_ros_conversion")
|
||||
set_targetdir("$(builddir)/bin")
|
||||
set_kind("binary")
|
||||
set_languages("c++23")
|
||||
add_files("tests/test_ros_conversion.cpp")
|
||||
add_deps("field_localization_ros")
|
||||
ros_common()
|
||||
add_tests("default", {group = "unit"})
|
||||
@@ -185,14 +185,17 @@ int main(int argc, char * argv[])
|
||||
holder.got = true;
|
||||
});
|
||||
|
||||
rclcpp::executors::SingleThreadedExecutor map_executor;
|
||||
map_executor.add_node(node);
|
||||
const auto wait_start = std::chrono::steady_clock::now();
|
||||
while (!holder.got &&
|
||||
std::chrono::steady_clock::now() - wait_start < 15s)
|
||||
{
|
||||
rclcpp::spin_some(node);
|
||||
map_executor.spin_some();
|
||||
std::this_thread::sleep_for(20ms);
|
||||
}
|
||||
|
||||
map_executor.remove_node(node);
|
||||
if (!holder.got) {
|
||||
std::printf("⚠️ 15 秒内没收到 /map,跳过预检直接发目标\n");
|
||||
} else {
|
||||
|
||||
@@ -314,7 +314,11 @@ local function ros_common()
|
||||
|
||||
local config = get_ros_config()
|
||||
|
||||
target:add("includedirs", config.includes)
|
||||
local project_include = path.join(target:scriptdir(), "include")
|
||||
for _, dir in ipairs(config.includes) do
|
||||
if dir ~= project_include then target:add("sysincludedirs", dir) end
|
||||
end
|
||||
target:add("includedirs", project_include)
|
||||
|
||||
target:add(
|
||||
"defines",
|
||||
|
||||
@@ -34,12 +34,9 @@
|
||||
|
||||
坐标系
|
||||
------
|
||||
同时发布两条静态变换:
|
||||
|
||||
map → odom 平移 (-5.0, 3.0) 仿真里用里程计当真值,替代 AMCL
|
||||
map → field 恒等变换 两者都已是「场地中心 = 零点」
|
||||
|
||||
`map` 是官方栅格图坐标系(西南内角 = (0,0)),`field` 是给决策代码用的直觉坐标系。
|
||||
map → odom 由显式选择的 LIO / AMCL 定位器发布,不能同时启动。
|
||||
map → field 为恒等变换。map / field 都以场地中心为原点。
|
||||
Nav2 等待仿真时钟和 odom/base/lidar TF 就绪后启动。
|
||||
"""
|
||||
|
||||
import os
|
||||
@@ -47,17 +44,19 @@ import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from ament_index_python.packages import get_package_share_directory
|
||||
from launch import LaunchDescription
|
||||
from launch.actions import (
|
||||
DeclareLaunchArgument,
|
||||
ExecuteProcess,
|
||||
IncludeLaunchDescription,
|
||||
EmitEvent,
|
||||
RegisterEventHandler,
|
||||
LogInfo,
|
||||
OpaqueFunction,
|
||||
SetEnvironmentVariable,
|
||||
)
|
||||
from launch.conditions import IfCondition
|
||||
from launch.launch_description_sources import PythonLaunchDescriptionSource
|
||||
from launch.event_handlers import OnProcessExit
|
||||
from launch.events import Shutdown
|
||||
from launch.substitutions import (LaunchConfiguration,
|
||||
PathJoinSubstitution, PythonExpression)
|
||||
from launch_ros.actions import Node
|
||||
@@ -120,12 +119,25 @@ def _gz_resource_path():
|
||||
return parts
|
||||
|
||||
|
||||
def _validate_lio(context):
|
||||
if LaunchConfiguration('localization').perform(context) == 'lio':
|
||||
mode = LaunchConfiguration('lio_mode').perform(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')
|
||||
return []
|
||||
|
||||
|
||||
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')
|
||||
|
||||
# 布尔参数统一用 PythonExpression 判,避免 launch 把 "false" 当真值
|
||||
is_headless = PythonExpression(["'", headless, "'.lower() in ('true', '1')"])
|
||||
@@ -137,7 +149,33 @@ def generate_launch_description():
|
||||
|
||||
robot_description = _robot_description()
|
||||
|
||||
navigation_ready = ExecuteProcess(
|
||||
cmd=['python3', str(WS / '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=['ros2', 'launch', 'nav2_bringup', 'bringup_launch.py',
|
||||
['map:=', map_yaml], 'use_sim_time:=true',
|
||||
['params_file:=', str(PKG_SHARE / 'config' / 'nav2_params.yaml')],
|
||||
'use_composition:=False',
|
||||
['use_localization:=', PythonExpression(["'", localization, "' == 'amcl'"])],
|
||||
'serve_static_map:=True', 'use_keepout_zones:=False',
|
||||
'use_speed_zones:=False', 'slam:=False'],
|
||||
name='nav2', output='screen', condition=IfCondition(nav2_on),
|
||||
)
|
||||
|
||||
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_initial_x', default_value='-5.0'),
|
||||
DeclareLaunchArgument('lio_initial_y', default_value='3.0'),
|
||||
DeclareLaunchArgument('lio_initial_z', default_value='0.0'),
|
||||
DeclareLaunchArgument('lio_initial_yaw', default_value='0.0'),
|
||||
OpaqueFunction(function=_validate_lio),
|
||||
# ---------------- 参数 ----------------
|
||||
DeclareLaunchArgument(
|
||||
'headless', default_value='false',
|
||||
@@ -247,15 +285,20 @@ def generate_launch_description():
|
||||
output='screen',
|
||||
),
|
||||
|
||||
# ---------------- 7. 静态变换 ----------------
|
||||
# map -> odom 由 AMCL 发布(use_localization:=True),这里**不能**再发一份,
|
||||
# 否则两个发布者打架。要回到"作弊定位"就把 use_localization 改 False 并放开下面:
|
||||
# Node(package='tf2_ros', executable='static_transform_publisher',
|
||||
# name='map_to_odom',
|
||||
# arguments=['--x','1.0','--y','1.0','--z','0.0',
|
||||
# '--yaw','0.0','--pitch','0.0','--roll','0.0',
|
||||
# '--frame-id','map','--child-frame-id','odom'],
|
||||
# parameters=[{'use_sim_time': True}], output='screen'),
|
||||
ExecuteProcess(
|
||||
cmd=[str(BIN_DIR / 'field_localization_node'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', 'point_cloud_topic:=/scan/points_filtered',
|
||||
'-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map],
|
||||
'-p', ['export_map_path:=', lio_export], '-p', 'publish_map_to_odom:=true',
|
||||
'-p', ['initial_x:=', LaunchConfiguration('lio_initial_x')],
|
||||
'-p', ['initial_y:=', LaunchConfiguration('lio_initial_y')],
|
||||
'-p', ['initial_z:=', LaunchConfiguration('lio_initial_z')],
|
||||
'-p', ['initial_yaw:=', LaunchConfiguration('lio_initial_yaw')]],
|
||||
name='field_localization', output='screen',
|
||||
condition=IfCondition(PythonExpression(["'", localization, "' == 'lio'"])),
|
||||
),
|
||||
|
||||
# ---------------- 7. map -> field 恒等别名 ----------------
|
||||
# map -> field:恒等变换(map 已以场地中心为原点)
|
||||
Node(
|
||||
package='tf2_ros',
|
||||
@@ -269,29 +312,16 @@ def generate_launch_description():
|
||||
),
|
||||
|
||||
# ---------------- 8. 静态地图服务 ----------------
|
||||
# 由 bringup 提供:serve_static_map 默认跟随 use_localization,
|
||||
# 所以 use_localization:=True 时 bringup 自己起 map_server + amcl。
|
||||
# 两个分支均由 bringup 提供 map_server,只有 AMCL 分支启动 amcl。
|
||||
# 这里再起一份会**同名冲突**(lifecycle_manager 崩在 createLifecycleServiceServers)。
|
||||
|
||||
# ---------------- 9. Nav2 ----------------
|
||||
IncludeLaunchDescription(
|
||||
PythonLaunchDescriptionSource(os.path.join(
|
||||
get_package_share_directory('nav2_bringup'),
|
||||
'launch', 'bringup_launch.py')),
|
||||
launch_arguments={
|
||||
'map': map_yaml,
|
||||
'use_sim_time': 'true',
|
||||
'params_file': str(PKG_SHARE / 'config' / 'nav2_params.yaml'),
|
||||
# 组合模式在本机起不来(容器一个组件都不加载),分进程更稳
|
||||
'use_composition': 'False',
|
||||
'use_localization': 'True',
|
||||
# 这两个子系统本工程用不上,少两个 lifecycle 节点少两处启动风险
|
||||
'use_keepout_zones': 'False',
|
||||
'use_speed_zones': 'False',
|
||||
'slam': 'False',
|
||||
}.items(),
|
||||
condition=IfCondition(nav2_on),
|
||||
),
|
||||
RegisterEventHandler(OnProcessExit(
|
||||
target_action=navigation_ready,
|
||||
on_exit=lambda event, context: [navigation] if event.returncode == 0 else [
|
||||
EmitEvent(event=Shutdown(reason='simulation clock/TF readiness failed'))],
|
||||
)),
|
||||
navigation_ready,
|
||||
|
||||
# ---------------- 10. RViz ----------------
|
||||
Node(
|
||||
|
||||
@@ -387,5 +387,14 @@
|
||||
<frame name='lidar_link' attached_to='lidar_joint'>
|
||||
<pose>0 0 0 0 0 0</pose>
|
||||
</frame>
|
||||
<!-- Evaluation only: independent world pose, never consumed by localization. -->
|
||||
<plugin filename="gz-sim-pose-publisher-system" name="gz::sim::systems::PosePublisher">
|
||||
<publish_model_pose>true</publish_model_pose>
|
||||
<publish_link_pose>false</publish_link_pose>
|
||||
<publish_nested_model_pose>false</publish_nested_model_pose>
|
||||
<use_pose_vector_msg>false</use_pose_vector_msg>
|
||||
<update_frequency>100</update_frequency>
|
||||
<topic>/evaluation/ground_truth</topic>
|
||||
</plugin>
|
||||
</model>
|
||||
</sdf>
|
||||
@@ -24,4 +24,5 @@ exec ros2 run ros_gz_bridge parameter_bridge \
|
||||
'/scan@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \
|
||||
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
|
||||
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
|
||||
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \
|
||||
--ros-args -p use_sim_time:=true
|
||||
@@ -160,7 +160,7 @@ env_bin_dir() {
|
||||
|
||||
# ① 现行布局优先
|
||||
local name p
|
||||
for name in self_filter nav_client patrol odom_tf; do
|
||||
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
|
||||
@@ -168,7 +168,7 @@ env_bin_dir() {
|
||||
done
|
||||
|
||||
# ② 老布局:去 build/ 里找产物实际所在的那一层
|
||||
for name in self_filter nav_client patrol odom_tf; do
|
||||
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"
|
||||
|
||||
@@ -115,6 +115,16 @@ export GZ_SIM_RESOURCE_PATH="${PKG_SHARE}/models:${FIELD_ROOT}/src/guodong_sentr
|
||||
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
|
||||
echo "[sentry_up] missing LIO map: $LIO_MAP; first run LIO_MODE=mapping or choose LOCALIZATION=amcl" >&2
|
||||
exit 1
|
||||
fi
|
||||
WORLD="${PKG_SHARE}/worlds/sentry_arena.sdf"
|
||||
PIDS=()
|
||||
CLEANED=0
|
||||
@@ -228,14 +238,24 @@ ros2 run ros_gz_bridge parameter_bridge \
|
||||
'/scan@sensor_msgs/msg/LaserScan[gz.msgs.LaserScan' \
|
||||
'/imu@sensor_msgs/msg/Imu[gz.msgs.IMU' \
|
||||
'/scan/points@sensor_msgs/msg/PointCloud2[gz.msgs.PointCloudPacked' \
|
||||
'/evaluation/ground_truth@geometry_msgs/msg/PoseStamped[gz.msgs.Pose' \
|
||||
--ros-args -p use_sim_time:=true &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 4. robot_state_publisher(TF 树)----------
|
||||
echo "[sentry_up] 启动 robot_state_publisher"
|
||||
# XML must be passed as a typed string; CLI YAML parsing breaks on XML comments.
|
||||
mkdir -p "${WS}/generated"
|
||||
xacro "${PKG_SHARE}/urdf/sentry.urdf.xacro" > "${WS}/generated/robot_description.urdf"
|
||||
python3 - "${WS}/generated/robot_description.urdf" "${WS}/generated/robot_state_publisher.json" <<'PY_PARAMS'
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
text = Path(sys.argv[1]).read_text()
|
||||
Path(sys.argv[2]).write_text(json.dumps({'robot_state_publisher': {'ros__parameters': {'robot_description': text, 'use_sim_time': True}}}))
|
||||
PY_PARAMS
|
||||
ros2 run robot_state_publisher robot_state_publisher --ros-args \
|
||||
-p robot_description:="$(xacro "${PKG_SHARE}/urdf/sentry.urdf.xacro")" \
|
||||
-p use_sim_time:=true &
|
||||
--params-file "${WS}/generated/robot_state_publisher.json" &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5. odom -> base_link ----------
|
||||
@@ -255,15 +275,17 @@ echo "[sentry_up] 启动点云自滤(${NAV_BIN_DIR}/self_filter)"
|
||||
$(nav_cmd self_filter) --ros-args -p use_sim_time:=true &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5.6 map->odom:由 AMCL 发布,不要在这里再发一份 ----------
|
||||
# 2026-11-18 起启用 AMCL(use_localization:=True):
|
||||
# · map->odom 由 nav2_amcl 根据 /scan2d 对栅格图做粒子滤波后发布
|
||||
# · 如果这里再发一个静态 map->odom,两个发布者会打架(TF 跳变/重复)
|
||||
# 想回到旧的「作弊定位」,把下面这行注释放开、并把 use_localization 改回 False:
|
||||
#
|
||||
# ros2 run tf2_ros static_transform_publisher \
|
||||
# --x 0.9 --y 4.0 --z 0.0 --yaw 0.0 --pitch 0.0 --roll 0.0 \
|
||||
# --frame-id map --child-frame-id odom --ros-args -p use_sim_time:=true &
|
||||
# ---------- 5.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 mode:="$LIO_MODE" -p map_path:="$LIO_MAP" -p export_map_path:="$LIO_EXPORT_MAP" \
|
||||
-p publish_map_to_odom:=true \
|
||||
-p initial_x:="${LIO_INITIAL_X:--5.0}" -p initial_y:="${LIO_INITIAL_Y:-3.0}" \
|
||||
-p initial_z:="${LIO_INITIAL_Z:-0.0}" -p initial_yaw:="${LIO_INITIAL_YAW:-0.0}" &
|
||||
PIDS+=($!)
|
||||
fi
|
||||
|
||||
# ---------- 5.65 map->field 恒等变换(两者都是「场地中心 = 零点」)----------
|
||||
# 世界与地图都已整体平移 (-6,-4)(官方包原定义是西南内角 = (0,0)),
|
||||
@@ -275,26 +297,11 @@ ros2 run tf2_ros static_transform_publisher \
|
||||
--frame-id map --child-frame-id field --ros-args -p use_sim_time:=true &
|
||||
PIDS+=($!)
|
||||
|
||||
# ---------- 5.7 静态地图服务:由 bringup 提供,不要自己再起 ----------
|
||||
# nav2_bringup 的 serve_static_map 默认跟随 use_localization,
|
||||
# 所以 use_localization:=True 时 bringup 会自己起 map_server + amcl + 一个
|
||||
# lifecycle_manager_localization。这里再起一份就会**同名节点/服务冲突**,
|
||||
# 典型症状是 lifecycle_manager 崩在 createLifecycleServiceServers()
|
||||
# 报 "could not create service"。
|
||||
#
|
||||
# 只有回到 use_localization:=False 时,才需要在这里手工补 map_server:
|
||||
#
|
||||
# echo "[sentry_up] 启动 map_server($MAP_YAML)"
|
||||
# ros2 run nav2_map_server map_server --ros-args \
|
||||
# -p yaml_filename:="${MAP_YAML}" -p use_sim_time:=true -p frame_id:=map &
|
||||
# PIDS+=($!)
|
||||
# ros2 run nav2_lifecycle_manager lifecycle_manager --ros-args \
|
||||
# -p node_names:="['map_server']" -p autostart:=true -p bond_timeout:=30.0 &
|
||||
# PIDS+=($!)
|
||||
# Nav2 manages the existing 2D map_server in both localization branches.
|
||||
|
||||
# ---------- 6. Nav2 ----------
|
||||
if [ "$NAV2" = "1" ]; then
|
||||
echo "[sentry_up] 启动 Nav2(AMCL + 栅格图)"
|
||||
echo "[sentry_up] 启动 Nav2($LOCALIZATION + 栅格图)"
|
||||
# 三个参数都是必需的,各有原因(踩过的坑):
|
||||
# use_composition:=False 组合模式在本机起不来 —— /nav2_container 起来后一个组件都不加载,
|
||||
# 日志停在 process started 就没了。分进程模式正常。
|
||||
@@ -309,7 +316,8 @@ if [ "$NAV2" = "1" ]; then
|
||||
use_sim_time:=true \
|
||||
params_file:="${PKG_SHARE}/config/nav2_params.yaml" \
|
||||
use_composition:=False \
|
||||
use_localization:=True \
|
||||
use_localization:="$NAV2_LOCALIZATION" \
|
||||
serve_static_map:=True \
|
||||
use_keepout_zones:=False \
|
||||
use_speed_zones:=False \
|
||||
slam:=False &
|
||||
|
||||
@@ -174,6 +174,15 @@
|
||||
<gazebo reference="wheel_br"><mu1>1.2</mu1><mu2>1.2</mu2></gazebo>
|
||||
|
||||
<gazebo>
|
||||
<!-- Evaluation only: independent world pose, never consumed by localization. -->
|
||||
<plugin filename="gz-sim-pose-publisher-system" name="gz::sim::systems::PosePublisher">
|
||||
<publish_model_pose>true</publish_model_pose>
|
||||
<publish_link_pose>false</publish_link_pose>
|
||||
<publish_nested_model_pose>false</publish_nested_model_pose>
|
||||
<use_pose_vector_msg>false</use_pose_vector_msg>
|
||||
<update_frequency>100</update_frequency>
|
||||
<topic>/evaluation/ground_truth</topic>
|
||||
</plugin>
|
||||
<plugin filename="gz-sim-mecanum-drive-system" name="gz::sim::systems::MecanumDrive">
|
||||
<front_left_joint>wheel_fl_joint</front_left_joint>
|
||||
<front_right_joint>wheel_fr_joint</front_right_joint>
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""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
|
||||
"""
|
||||
import argparse
|
||||
import math
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from std_srvs.srv import Trigger
|
||||
from tf2_msgs.msg import TFMessage
|
||||
|
||||
import project_env
|
||||
|
||||
|
||||
def yaw(q):
|
||||
return math.atan2(2 * (q.w*q.z + q.x*q.y), 1 - 2 * (q.y*q.y + q.z*q.z))
|
||||
|
||||
|
||||
class Driver(Node):
|
||||
def __init__(self, profile):
|
||||
super().__init__('field_lio_evaluation_driver', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
self.publisher = self.create_publisher(Twist, '/model/sentry/cmd_vel', 10)
|
||||
self.origin = None
|
||||
self.pose = None
|
||||
self.index = 0
|
||||
self.tf_publishers = set()
|
||||
self.map_odom_messages = 0
|
||||
self.forbidden_tf = 0
|
||||
self.tf_subscription = self.create_subscription(TFMessage, '/tf', self.on_tf, 500)
|
||||
# Verified against the existing occupancy map with room for the body footprint.
|
||||
self.route = ([(-4.4, 3.0), (-4.4, 0.7), (-5.15, 0.7), (-5.15, 3.0), (-5.0, 3.0)]
|
||||
if profile == 'mapping' else
|
||||
[(-4.6, 2.8), (-4.6, 1.0), (-5.1, 1.0), (-5.1, 2.8), (-5.0, 3.0)])
|
||||
self.subscription = self.create_subscription(Odometry, '/odom', self.on_odom, qos_profile_sensor_data)
|
||||
|
||||
def on_tf(self, msg, info):
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id == 'map' and transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
self.tf_publishers.add(json.dumps(gid, sort_keys=True, default=str) if isinstance(gid, dict) else str(gid))
|
||||
self.map_odom_messages += 1
|
||||
if transform.header.frame_id == 'map' and transform.child_frame_id == 'base_link':
|
||||
self.forbidden_tf += 1
|
||||
|
||||
def on_odom(self, msg):
|
||||
p = msg.pose.pose
|
||||
if self.origin is None:
|
||||
self.origin = (p.position.x, p.position.y, yaw(p.orientation))
|
||||
x, y, angle = self.origin
|
||||
dx, dy = p.position.x-x, p.position.y-y
|
||||
self.pose = (-5 + math.cos(angle)*dx + math.sin(angle)*dy,
|
||||
3 - math.sin(angle)*dx + math.cos(angle)*dy,
|
||||
yaw(p.orientation)-angle)
|
||||
|
||||
def drive(self, elapsed):
|
||||
command = Twist()
|
||||
if elapsed >= 5 and self.pose and elapsed % 30 > 2:
|
||||
x, y, angle = self.pose
|
||||
tx, ty = self.route[self.index]
|
||||
distance = math.hypot(tx-x, ty-y)
|
||||
if distance < 0.08:
|
||||
self.index = (self.index+1) % len(self.route)
|
||||
else:
|
||||
error = math.atan2(math.sin(math.atan2(ty-y, tx-x)-angle), math.cos(math.atan2(ty-y, tx-x)-angle))
|
||||
command.angular.z = max(-0.4, min(0.4, 1.5*error))
|
||||
if abs(error) < 0.3:
|
||||
command.linear.x = min(0.20, 0.8*distance)
|
||||
self.publisher.publish(command)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
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)
|
||||
args = parser.parse_args()
|
||||
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')
|
||||
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',
|
||||
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))
|
||||
processes = []
|
||||
log_handles = []
|
||||
rclpy.init()
|
||||
driver = Driver(args.profile)
|
||||
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}'],
|
||||
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
processes.append(recorder)
|
||||
deadline = time.monotonic() + max(600, args.duration*10)
|
||||
start = None
|
||||
last_print = 0
|
||||
while time.monotonic() < deadline and recorder.poll() is None:
|
||||
if (args.output/'STOP').exists():
|
||||
raise RuntimeError('capture stopped through STOP file')
|
||||
rclpy.spin_once(driver, timeout_sec=0.02)
|
||||
if processes[0].poll() is not None:
|
||||
raise RuntimeError('simulation stack exited; inspect stack.log')
|
||||
if (args.output/'config.txt').exists():
|
||||
now = driver.get_clock().now().nanoseconds*1e-9
|
||||
if start is None:
|
||||
start = now
|
||||
driver.drive(now-start)
|
||||
if 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())
|
||||
if recorder.poll() is None:
|
||||
raise RuntimeError('capture deadline exceeded')
|
||||
if recorder.returncode or not (args.output/'complete.txt').exists():
|
||||
raise RuntimeError('recorder failed; inspect record.log')
|
||||
if args.profile == 'mapping':
|
||||
client = driver.create_client(Trigger, '/field_localization/save_map')
|
||||
if not client.wait_for_service(timeout_sec=5):
|
||||
raise RuntimeError('LIO save_map service unavailable')
|
||||
future = client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(driver, future, timeout_sec=10)
|
||||
if not future.done() or not future.result().success:
|
||||
raise RuntimeError('LIO map export failed')
|
||||
tf_summary = {'map_to_odom_publishers': len(driver.tf_publishers),
|
||||
'map_to_odom_messages': driver.map_odom_messages,
|
||||
'map_to_base_link_messages': driver.forbidden_tf}
|
||||
(args.output/'tf_validation.json').write_text(json.dumps(tf_summary, indent=2))
|
||||
if len(driver.tf_publishers) != 1 or driver.map_odom_messages == 0 or driver.forbidden_tf:
|
||||
raise RuntimeError(f'TF validation failed: {tf_summary}')
|
||||
print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True)
|
||||
finally:
|
||||
driver.publisher.publish(Twist())
|
||||
for process in reversed(processes):
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
for process in reversed(processes):
|
||||
try:
|
||||
process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
for handle in log_handles:
|
||||
handle.close()
|
||||
driver.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+15
-6
@@ -37,7 +37,6 @@ from tf2_ros import Buffer, TransformListener
|
||||
# 只报了 7 个节点的状态 —— 一眼看不出问题其实出在定位那一组。
|
||||
EXPECTED_ACTIVE = [
|
||||
'map_server',
|
||||
'amcl',
|
||||
'controller_server',
|
||||
'planner_server',
|
||||
'smoother_server',
|
||||
@@ -164,9 +163,14 @@ def main():
|
||||
return None, '调用超时'
|
||||
return fut.result().current_state, None
|
||||
|
||||
# Give DDS discovery a chance before choosing the expected localization branch.
|
||||
for _ in range(10):
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
names_now = set(node.get_node_names())
|
||||
expected_active = EXPECTED_ACTIVE + (['amcl'] if 'amcl' in names_now else [])
|
||||
# ---------- 1. 生命周期 ----------
|
||||
print('=== 1. 生命周期状态 ===')
|
||||
for name in EXPECTED_ACTIVE:
|
||||
for name in expected_active:
|
||||
st, err = active(name)
|
||||
if st is None:
|
||||
print(' %-20s ❌ %s' % (name, err))
|
||||
@@ -177,6 +181,12 @@ def main():
|
||||
print(' %-20s ⚠️ %s' % (name, st.label))
|
||||
problems.append(f'{name} 是 {st.label},不是 ACTIVE')
|
||||
|
||||
names_now = set(node.get_node_names())
|
||||
if 'field_localization' in names_now and 'amcl' in names_now:
|
||||
problems.append('LIO 与 AMCL 同时运行;检查 map->odom 发布者互斥')
|
||||
elif 'amcl' not in names_now and 'field_localization' not in names_now:
|
||||
problems.append('LIO / AMCL 定位器均未发现')
|
||||
|
||||
# ---------- 1.5 节点总览:定位"卡在谁身上" ----------
|
||||
# 光看生命周期状态不够 —— 如果某个节点**压根没起来**,
|
||||
# 上面只会说"服务不存在",看不出是谁没被编排。这里把家底列出来。
|
||||
@@ -193,14 +203,14 @@ def main():
|
||||
else:
|
||||
print(' 生命周期管理器: ❌ 一个都没有(Nav2 不会自己配置)')
|
||||
problems.append('没有 lifecycle_manager 在跑')
|
||||
missing = [n for n in EXPECTED_ACTIVE if n not in names]
|
||||
missing = [n for n in expected_active if n not in names]
|
||||
if missing:
|
||||
print(f' ⚠️ 期望存在但没起: {", ".join(missing)}')
|
||||
for n in missing:
|
||||
problems.append(f'{n} 没在跑')
|
||||
extra = [n for n in names
|
||||
if any(k in n for k in ('amcl', 'server', 'navigator', 'manager'))
|
||||
and n not in EXPECTED_ACTIVE and 'lifecycle_manager' not in n]
|
||||
and n not in expected_active and 'lifecycle_manager' not in n]
|
||||
if extra:
|
||||
print(f' 其他相关节点: {", ".join(extra)}')
|
||||
else:
|
||||
@@ -295,8 +305,7 @@ def main():
|
||||
print(' [TF] map -> base_link (%.3f, %.3f)' % tf_pos)
|
||||
print(' [偏差] %.3f m %s' % (dev, flag))
|
||||
if dev >= 0.05:
|
||||
note = ('现在定位是"作弊"的(静态 map->odom + 轮速里程计),'
|
||||
'偏差会随时间累积且不自愈')
|
||||
note = '定位与 Gazebo 独立真值存在偏差;检查定位状态与传感器时间同步'
|
||||
print(' %s' % note)
|
||||
problems.append('TF 位置与 Gazebo 真值差 %.2f m' % dev)
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
# xmake 会产出的可执行文件,用来反推产物目录。
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf')
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'field_localization_node')
|
||||
|
||||
# 系统 gz 的常见安装位置(按优先级)。
|
||||
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Live integration check: isolated Gazebo + LIO + Nav2, no motion commands."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
|
||||
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
|
||||
'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother',
|
||||
'collision_monitor']
|
||||
|
||||
|
||||
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)
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
FASTDDS_BUILTIN_TRANSPORTS='UDPv4', 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')]
|
||||
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')
|
||||
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()
|
||||
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}
|
||||
states = {}
|
||||
try:
|
||||
deadline = time.monotonic()+120
|
||||
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()
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
future = client.call_async(GetState.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=1)
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
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:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
names = sorted(set(node.get_node_names()))
|
||||
result = {'launcher': args.launcher, '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'] = (manager_completed 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))
|
||||
print(json.dumps(result, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
finally:
|
||||
_ = subscription
|
||||
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 log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exit successfully only after simulation clock and basic robot TF are available."""
|
||||
import time
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from rclpy.time import Time
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
|
||||
def main():
|
||||
rclpy.init()
|
||||
node = Node('wait_navigation_ready', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
buffer = Buffer(node=node)
|
||||
listener = TransformListener(buffer, node)
|
||||
result = 1
|
||||
try:
|
||||
deadline = time.monotonic()+180
|
||||
while rclpy.ok() and time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if (node.get_clock().now().nanoseconds > 0
|
||||
and buffer.can_transform('odom', 'base_link', Time())
|
||||
and buffer.can_transform('base_link', 'lidar_link', Time())):
|
||||
print('simulation clock and odom/base/lidar TF ready', flush=True)
|
||||
result = 0
|
||||
break
|
||||
if result:
|
||||
print('simulation clock/TF readiness timeout', flush=True)
|
||||
finally:
|
||||
_ = listener
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user