fix(nav): stop on invalid localization and enforce final velocity path

This commit is contained in:
mzx committed 2026-11-22 11:43:13 +08:00
1 parent b772174c1c
commit 28ac7c488e
24 files changed
+1236 -161

No files matched your search

+8
View File
@@ -107,3 +107,11 @@ python3 tools/verify_lio_stack.py --map generated/field.flmap --output generated
实测 9 个所需生命周期节点均 ACTIVE,AMCL 不存在,map→odom 仅一个发布者,没有 map→base_link 发布。交付数据中附带原始序列、收敛曲线 CSV、轨迹、逐帧状态、TF/生命周期检查 JSON 与构建日志。
Python 入口可用 `tools/verify_lio_stack.py --launcher python` 做同样的完整启动检查;验证器等待生命周期管理器报告激活完成,并继续观察稳定状态,避免在 bond 握手结束前退出。
### 导航有效性与失效保护
`/field_localization/navigation_valid` 以 10 Hz 发布,状态切换时立即更新。启动与失效后的恢复都需要连续五帧成功配准。最近成功配准超过 0.3 秒,或水平位置最大主方向的 3σ 超过 0.5 m、航向 3σ 超过 15° 时,停止更新 `map → odom`。IMU 传播与诊断里程计保留。长时间纯 IMU 传播的结果可能继续漂移,不能作为导航位姿使用。
导航时,车端转发节点仅接收碰撞监控器的最终 `/cmd_vel`。LIO 心跳失效或超时触发零速度与目标取消。速度命令自身超时也触发零速度,恢复行为中的正常等待可以继续。解除定位失效后需要重新发送已取消的目标。Shell 的 `NAV2=0` 和 Python 的 `nav2:=false` 都可通过 `MANUAL_CMD_VEL_TOPIC` 设置手动输入。
两个仿真入口启用点云可靠传输。独立运行定位节点时可用 `reliable_clouds` 匹配发布者。指定 `LIO_TRACE_PATH` 可记录每帧的预测、候选和最终状态、协方差、信息矩阵及拒绝原因,这会增加磁盘 I/O。已知初始位姿仍是连续跟踪的前提。动态障碍遮挡全部可用结构、场地退化或传感器断流时,导航将停止。
@@ -0,0 +1,64 @@
#pragma once
#include "field_localization/core/localization_core.hpp"
#include <cmath>
#include <numbers>
namespace field_localization::core {
inline Matrix6 base_pose_covariance(const LocalizationSnapshot &s,const Pose3D &base_from_imu) {
Eigen::Matrix<double,6,18> j=Eigen::Matrix<double,6,18>::Zero();
j.block<3,3>(0,0).setIdentity();
j.block<3,3>(0,6)=-s.filter.state.pose.rotation.toRotationMatrix()*skew(inverse(base_from_imu).translation);
j.block<3,3>(3,6)=base_from_imu.rotation.toRotationMatrix();
return j*s.filter.covariance*j.transpose();
}
struct HealthOptions {
double correction_timeout{0.3},imu_timeout{0.1},clock_tolerance{0.02};
double position_three_sigma{0.5},yaw_three_sigma{15*std::numbers::pi/180};
std::size_t recovery_scans{5};
};
// Independent of ROS and of publication frequency: count accepted scans, not timer ticks.
class TrackingHealth {
public:
explicit TrackingHealth(const HealthOptions &options={}):options_(options) {}
bool update(const LocalizationSnapshot &s,const Pose3D &base_from_imu,double now) {
const auto &status=s.status;
const Matrix6 p=base_pose_covariance(s,base_from_imu);
const double horizontal=0.5*(p(0,0)+p(1,1)+std::hypot(p(0,0)-p(1,1),2*p(0,1)));
Eigen::Vector3d yaw_j;
auto yaw=[](const Eigen::Quaterniond &q) {
return std::atan2(2*(q.w()*q.z()+q.x()*q.y()),1-2*(q.y()*q.y()+q.z()*q.z()));
};
for(int i=0;i<3;++i) {
Eigen::Vector3d d=Eigen::Vector3d::Zero();d[i]=1e-6;
const double a=yaw(s.pose.rotation*exp_so3(d)),b=yaw(s.pose.rotation*exp_so3(-d));
yaw_j[i]=std::remainder(a-b,2*std::numbers::pi)/2e-6;
}
const double yaw_variance=yaw_j.dot(p.bottomRightCorner<3,3>()*yaw_j);
position_sigma_=3*std::sqrt(std::max(0.0,horizontal)); yaw_sigma_=3*std::sqrt(std::max(0.0,yaw_variance));
const bool bounded=p.allFinite() && horizontal>=0 && yaw_variance>=0 &&
3*std::sqrt(horizontal)<=options_.position_three_sigma &&
3*std::sqrt(yaw_variance)<=options_.yaw_three_sigma;
const bool fresh=std::isfinite(now) && status.has_imu && status.last_correction_timestamp>=0 &&
now>=status.state_timestamp-options_.clock_tolerance && now-status.state_timestamp<=options_.imu_timeout &&
now>=status.last_correction_timestamp-options_.clock_tolerance && now-status.last_correction_timestamp<=options_.correction_timeout;
if(!fresh || !bounded) { valid_=false; consecutive_=0; }
if(status.mode!=TrackingMode::FULL) consecutive_=0;
if(status.accepted_corrections<last_accepted_) { valid_=false; consecutive_=0; }
if(status.accepted_corrections!=last_accepted_) {
if(fresh && bounded && status.mode==TrackingMode::FULL) ++consecutive_;
else consecutive_=0;
last_accepted_=status.accepted_corrections;
}
if(fresh && bounded && consecutive_>=options_.recovery_scans) valid_=true;
return valid_;
}
double position_three_sigma() const { return position_sigma_; }
double yaw_three_sigma() const { return yaw_sigma_; }
void reset() { valid_=false; consecutive_=0; last_accepted_=0; }
private:
HealthOptions options_;
double position_sigma_{0},yaw_sigma_{0};
bool valid_{false};
std::size_t consecutive_{0},last_accepted_{0};
};
} // namespace field_localization::core
@@ -9,6 +9,9 @@
#include <tf2_ros/transform_listener.hpp>
#include <tf2_ros/transform_broadcaster.hpp>
#include <deque>
#include <fstream>
#include <std_msgs/msg/bool.hpp>
#include "field_localization/core/tracking_health.hpp"
namespace field_localization::ros {
class LocalizationNode:public rclcpp::Node {
@@ -23,6 +26,8 @@ private:
void publish_estimate();
void print_localization_status();
bool check_clock();
bool navigation_valid();
void publish_health(bool heartbeat=false);
core::CoreOptions core_options_;
std::unique_ptr<core::LocalizationCore> core_;
std::unique_ptr<tf2_ros::Buffer> tf_buffer_;
@@ -33,7 +38,11 @@ private:
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_;
rclcpp::TimerBase::SharedPtr status_timer_,health_timer_;
rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr navigation_valid_pub_;
core::TrackingHealth health_;
bool last_health_{false};
std::ofstream trace_;
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_;
@@ -26,8 +26,14 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
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.integration_error_scale=declare_parameter<double>("integration_error_scale",0.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.map_translation_sigma=declare_parameter<double>("map_translation_sigma",0.02);
core_options_.registration.map_rotation_sigma=declare_parameter<double>("map_rotation_sigma",0.002);
if(!std::isfinite(core_options_.registration.map_translation_sigma) || core_options_.registration.map_translation_sigma<0 ||
!std::isfinite(core_options_.registration.map_rotation_sigma) || core_options_.registration.map_rotation_sigma<0)
throw std::invalid_argument("invalid map model uncertainty");
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");
@@ -43,10 +49,28 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
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);
core::HealthOptions health_options;
health_options.correction_timeout=declare_parameter<double>("navigation_correction_timeout",0.3);
health_options.position_three_sigma=declare_parameter<double>("navigation_position_three_sigma",0.5);
health_options.yaw_three_sigma=declare_parameter<double>("navigation_yaw_three_sigma_deg",15)*std::numbers::pi/180;
if(!std::isfinite(health_options.correction_timeout) || health_options.correction_timeout<=0 ||
!std::isfinite(health_options.position_three_sigma) || health_options.position_three_sigma<=0 ||
!std::isfinite(health_options.yaw_three_sigma) || health_options.yaw_three_sigma<=0)
throw std::invalid_argument("invalid navigation health limits");
health_=core::TrackingHealth(health_options);
navigation_valid_pub_=create_publisher<std_msgs::msg::Bool>("~/navigation_valid",rclcpp::QoS(1));
const auto trace_path=declare_parameter<std::string>("diagnostics_path","");
if(!trace_path.empty()) {
trace_.open(trace_path); trace_.exceptions(std::ios::badbit|std::ios::failbit);
core::write_filter_trace_header(trace_);
}
health_timer_=create_wall_timer(std::chrono::milliseconds(100),[this] { publish_health(true); });
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),
const bool reliable_clouds=declare_parameter<bool>("reliable_clouds",false);
const rclcpp::QoS cloud_qos=reliable_clouds ? rclcpp::QoS(5).reliable() : rclcpp::SensorDataQoS().keep_last(5);
point_cloud_sub_=create_subscription<sensor_msgs::msg::PointCloud2>(cloud_topic,cloud_qos,
[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)); });
@@ -58,7 +82,7 @@ LocalizationNode::LocalizationNode(const rclcpp::NodeOptions &options):Node("fie
});
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;
core_.reset(); health_.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(); });
@@ -125,7 +149,14 @@ void LocalizationNode::drain_scans() {
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();
core_->process_point_cloud(scans_.front());
if(trace_.is_open()) {
const auto snapshot=core_->get_snapshot();
core::write_filter_trace(trace_,end,"prediction",snapshot.status.registration_prediction,snapshot.status);
core::write_filter_trace(trace_,end,"candidate",snapshot.status.registration.estimate,snapshot.status);
core::write_filter_trace(trace_,end,"posterior",snapshot.filter,snapshot.status); trace_.flush();
}
scans_.pop_front();
}
}
void LocalizationNode::publish_estimate() {
@@ -138,16 +169,13 @@ void LocalizationNode::publish_estimate() {
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();
const core::Matrix6 covariance=core::base_pose_covariance(snapshot,core_options_.base_from_imu);
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();
}
publish_health();
if (!navigation_valid()) { pending_tf_.clear(); return; }
if (!publish_map_to_odom_) { pending_tf_.clear(); return; }
while (!pending_tf_.empty()) {
const auto &s=pending_tf_.front();
@@ -160,14 +188,34 @@ void LocalizationNode::publish_estimate() {
} catch (const tf2::TransformException &) { break; }
}
}
bool LocalizationNode::navigation_valid() {
if(!core_ || clock_rewound_) return false;
return health_.update(core_->get_snapshot(),core_options_.base_from_imu,now().seconds());
}
void LocalizationNode::publish_health(bool heartbeat) {
const bool valid=check_clock() && navigation_valid();
if(heartbeat || valid!=last_health_) {
std_msgs::msg::Bool message; message.data=valid; navigation_valid_pub_->publish(message);
}
if(last_health_ && !valid && core_) {
const auto s=core_->get_status();
RCLCPP_ERROR(get_logger(),"localization no longer valid for navigation; TF halted: state_age=%.6f correction_age=%.6f position_3sigma=%.6f yaw_3sigma_deg=%.6f reason=%s",
now().seconds()-s.state_timestamp,now().seconds()-s.last_correction_timestamp,
health_.position_three_sigma(),health_.yaw_three_sigma()*180/std::numbers::pi,core::reason_name(s.reason));
}
last_health_=valid;
}
void LocalizationNode::print_localization_status() {
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",
RCLCPP_INFO(get_logger(),"mode=%s reason=%s%s IMU=%zu rejected=%zu clouds=%zu rejected=%zu valid=%zu rmse=%s 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.point_cloud_count,s.rejected_point_cloud_count,s.last_point_count,(s.registration_residual_available ? std::to_string(s.registration_rmse)+"m" : "unavailable").c_str(),s.inlier_count,100*s.inlier_ratio,
s.degenerate_dimensions,s.keyframe_count,s.map_point_count);
if(!s.registration_residual_available) RCLCPP_INFO(get_logger(),"registration residual unavailable (not zero error)");
RCLCPP_INFO(get_logger(),"navigation_valid=%d correction_age=%.3fs NIS=%.3f rank=%d",navigation_valid(),
s.last_correction_timestamp<0 ? -1 : now().seconds()-s.last_correction_timestamp,s.registration.nis,s.registration.measurement_rank);
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);
+1 -1
View File
@@ -23,7 +23,7 @@ public:
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) {
rclcpp::QoS(20).reliable(),[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;
@@ -0,0 +1,34 @@
#include "field_localization/core/tracking_health.hpp"
#include "sentry_nav/core/motion_interlock.hpp"
#include "test_util.hpp"
#include <Eigen/Eigenvalues>
using namespace field_localization::core;
int main() {
// Health recovery counts distinct scans, not 100 Hz IMU callbacks.
TrackingHealth health;LocalizationSnapshot s;
s.status.has_imu=true;s.status.mode=TrackingMode::FULL;
s.filter.covariance=1e-6*Matrix18::Identity();
for(int i=1;i<=5;++i) {
s.status.accepted_corrections=i;s.status.last_correction_timestamp=s.status.state_timestamp=0.1*i;
CHECK(health.update(s,{},0.1*i)==(i==5));
for(int j=0;j<20;++j) CHECK(health.update(s,{},0.1*i)==(i==5));
}
CHECK(health.update(s,{},s.status.state_timestamp-0.002)); // sensor callback can precede /clock by one tick
s.status.mode=TrackingMode::IMU_ONLY;s.status.state_timestamp=0.7;
CHECK(health.update(s,{},0.7)); // bounded short IMU-only grace period
s.status.state_timestamp=0.81;CHECK(!health.update(s,{},0.81));
for(int i=6;i<=10;++i) {
s.status.mode=TrackingMode::FULL;s.status.accepted_corrections=i;
s.status.last_correction_timestamp=s.status.state_timestamp=0.1*i+0.5;
CHECK(health.update(s,{},s.status.state_timestamp)==(i==10));
}
s.filter.covariance(0,0)=0.04;CHECK(!health.update(s,{},s.status.state_timestamp));
s.filter.covariance=1e-6*Matrix18::Identity();CHECK(!health.update(s,{},s.status.state_timestamp));
sentry_nav::core::MotionInterlock gate;
gate.command(1);CHECK(!gate.allowed(1));gate.health(true,1);CHECK(gate.allowed(1.29));
CHECK(!gate.allowed(1.31));gate.command(1.31);CHECK(!gate.allowed(1.31));
gate.health(true,1.31);CHECK(gate.allowed(1.31));gate.health(false,1.32);CHECK(!gate.allowed(1.32));
CHECK(!gate.allowed(0.9));
sentry_nav::core::MotionInterlock manual(false);manual.command(2);CHECK(manual.allowed(2.1));CHECK(!manual.allowed(2.31));
return sentry_nav_test::Summary("TrackingSafety");
}
@@ -0,0 +1,11 @@
Protection and transport validation, 2026-11-22
GCC 15.2 / C++23 release build emitted zero compiler warnings.
The complete working tree passed xmake test (15/15), 15 Nav2 readiness checks,
5 supervisor checks and 9 live ROS relay checks. The relay check measured a
302 ms zero-output response after final-input publication stopped.
In an isolated Shell-launched Gazebo run the LiDAR filter process was stopped
while driving a Nav2 goal. The first zero actuator command arrived 233 ms after
fault injection. Nav2 canceled the active goal and the localization node halted
map-to-odom publication. Exactly one map-to-odom publisher and no AMCL were
observed. The bridge and filtered point cloud endpoints negotiated RELIABLE QoS.
+9
View File
@@ -384,6 +384,15 @@ target("test_ros_conversion")
ros_common()
add_tests("default", {group = "unit"})
target("test_tracking_safety")
set_targetdir("$(builddir)/bin")
set_kind("binary")
set_languages("c++23")
add_files("tests/test_tracking_safety.cpp")
add_includedirs("../sentry_nav/include")
add_deps("field_localization_core")
add_tests("default", {group = "unit"})
target("test_filter_consistency")
set_targetdir("$(builddir)/bin")
set_kind("binary")
@@ -0,0 +1,21 @@
#pragma once
#include <cmath>
namespace sentry_nav::core {
// All times are monotonic wall seconds: a paused or rewound /clock cannot defeat a stop.
class MotionInterlock {
public:
explicit MotionInterlock(bool navigation=true,double timeout=0.3):navigation_(navigation),timeout_(timeout) {}
void health(bool valid,double time) { healthy_=valid; health_time_=time; }
void command(double time) { command_time_=time; }
bool allowed(double time) const {
auto fresh=[&](double stamp) { return stamp>=0 && time>=stamp && time-stamp<=timeout_; };
return std::isfinite(time) && fresh(command_time_) && localization_valid(time);
}
bool localization_valid(double time) const {
return !navigation_ || (healthy_ && health_time_>=0 && time>=health_time_ && time-health_time_<=timeout_);
}
private:
bool navigation_,healthy_{false};
double timeout_,health_time_{-1},command_time_{-1};
};
} // namespace sentry_nav::core
@@ -21,15 +21,16 @@ namespace sentry_nav {
// 自滤参数。单位统一为米,坐标系为 base_link。
struct FilterParams {
// 车身包围盒。车身真实尺寸约 x±0.288 / y±0.26,这里留了 ~10 cm 余量:
// 雷达偏后挂在车里,车身对角距传感器约 0.56 m,盒子太小会漏掉自己的点,
// 代价地图就会把车标成障碍、导致规划失败。
float box_min_x = -0.40f;
float box_max_x = 0.40f;
float box_min_y = -0.38f;
float box_max_y = 0.38f;
// Keep the lateral limits close to the chassis (y +/-0.2605 m). Gazebo
// lidar range noise puts gimbal returns beyond its physical x=0.32 m and
// z=0.50 m limits. The recorded stationary envelope reaches x=0.357 m
// and z=0.530 m, so retain margin at the front and above the gimbal.
float box_min_x = -0.294f;
float box_max_x = 0.365f;
float box_min_y = -0.2655f;
float box_max_y = 0.2655f;
float box_min_z = -0.05f;
float box_max_z = 0.60f;
float box_max_z = 0.545f;
float keep_min_z = 0.02f; // 低于此高度视为地面/噪声
float max_range = 12.0f; // 水平距离上限
+92 -85
View File
@@ -1,95 +1,102 @@
// Copyright 2026 sentry_nav_dev
//
// cmd_vel_relay:把 Nav2 的 /cmd_vel_smoothed(及兼容的 /cmd_vel、/cmd_vel_nav)
// 转发到 ros_gz 桥用的 /model/sentry/cmd_vel。
// (C++ 版,2026-11-17 从 scripts/cmd_vel_relay.py 移植;用户要求能 C++ 就 C++。)
//
// 为什么需要:Gazebo 的 MecanumDrive 插件订阅的是「模型名/cmd_vel」(即
// /model/sentry/cmd_vel),而 ros_gz_bridge 只支持「两端同名」的桥接,
// 它无法把 ROS 的 /cmd_vel 映射到 gz 的 /model/sentry/cmd_vel。
// 所以这里做一次 ROS 侧的改名转发。
//
// 平滑命令优先:Nav2 的速度链是「控制器发 /cmd_vel(原始)→ velocity_smoother
// 订阅 /cmd_vel 并发布 /cmd_vel_smoothed(限加速度、去死区)」。车只该吃最终
// 那条命令。之前三路都转发 → 平滑前后的命令在 gz 侧交替打架,车会抖、走着
// 走着就 "Failed to make progress"。现在:/cmd_vel_smoothed 优先;它最近
// 200 ms 内有消息时丢弃其它来源;只在平滑器没输出时(如 NAV2=0 手发 /cmd_vel)
// 回退到原始命令。
//
// 参数:
// out_topic /model/sentry/cmd_vel 转发目标
// in_topics [/cmd_vel_smoothed, /cmd_vel, /cmd_vel_nav]
#include <cstdint>
// Final actuator input only. Never bypass velocity smoothing or collision_monitor.
#include "sentry_nav/core/motion_interlock.hpp"
#include <action_msgs/srv/cancel_goal.hpp>
#include <geometry_msgs/msg/twist.hpp>
#include <std_msgs/msg/bool.hpp>
#include <rclcpp/rclcpp.hpp>
#include <array>
#include <chrono>
#include <cmath>
#include <memory>
#include <string>
#include <vector>
#include <geometry_msgs/msg/twist.hpp>
#include <rclcpp/rclcpp.hpp>
namespace sentry_nav
{
class CmdVelRelay : public rclcpp::Node
{
namespace sentry_nav {
class CmdVelRelay : public rclcpp::Node {
public:
CmdVelRelay() : Node("cmd_vel_relay")
{
const std::string out_topic =
declare_parameter<std::string>("out_topic", "/model/sentry/cmd_vel");
in_topics_ = declare_parameter<std::vector<std::string>>(
"in_topics", std::vector<std::string>{"/cmd_vel_smoothed", "/cmd_vel", "/cmd_vel_nav"});
pub_ = create_publisher<geometry_msgs::msg::Twist>(out_topic, 10);
for (const std::string & topic : in_topics_) {
subs_.push_back(
create_subscription<geometry_msgs::msg::Twist>(
topic, 10,
[this, topic](const geometry_msgs::msg::Twist::SharedPtr msg) {
OnTwist(topic, msg);
}));
}
std::string joined;
for (size_t i = 0; i < in_topics_.size(); ++i) {
joined += (i == 0 ? "" : ", ") + in_topics_[i];
}
RCLCPP_INFO(
get_logger(), "cmd_vel_relay: [%s] -> %s(平滑命令优先)",
joined.c_str(), out_topic.c_str());
CmdVelRelay():Node("cmd_vel_relay") {
navigation_=declare_parameter<bool>("navigation_mode",true);
const double timeout=declare_parameter<double>("command_timeout",0.3);
if(!std::isfinite(timeout) || timeout<=0) throw std::invalid_argument("invalid command_timeout");
require_health_=declare_parameter<bool>("require_localization_health",true);
gate_=core::MotionInterlock(navigation_ && require_health_,timeout);
const auto input=declare_parameter<std::string>("in_topic","/cmd_vel");
const auto output=declare_parameter<std::string>("out_topic","/model/sentry/cmd_vel");
pub_=create_publisher<geometry_msgs::msg::Twist>(output,1);
sub_=create_subscription<geometry_msgs::msg::Twist>(input,rclcpp::QoS(1),[this](geometry_msgs::msg::Twist::ConstSharedPtr msg) {
const auto &v=*msg;
const bool finite=std::isfinite(v.linear.x) && std::isfinite(v.linear.y) && std::isfinite(v.linear.z) &&
std::isfinite(v.angular.x) && std::isfinite(v.angular.y) && std::isfinite(v.angular.z);
if(!finite) { pub_->publish(geometry_msgs::msg::Twist{}); return; }
gate_.command(seconds());
const bool allowed=gate_.allowed(seconds()) && !cancel_pending();
pub_->publish(allowed ? v : geometry_msgs::msg::Twist{});
if(navigation_ && !allowed && nonzero(v)) request_stop();
});
health_sub_=create_subscription<std_msgs::msg::Bool>("/field_localization/navigation_valid",rclcpp::QoS(1),
[this](std_msgs::msg::Bool::ConstSharedPtr msg) { gate_.health(msg->data,seconds()); });
const std::array<std::string,2> actions{"/navigate_to_pose","/navigate_through_poses"};
for(std::size_t i=0;i<actions.size();++i)
cancel_[i]=create_client<action_msgs::srv::CancelGoal>(actions[i]+"/_action/cancel_goal");
timer_=create_wall_timer(std::chrono::milliseconds(20),[this] {
const double time=seconds();
const bool allowed=gate_.allowed(time);
if(!allowed || cancel_pending()) pub_->publish(geometry_msgs::msg::Twist{});
const bool localized=gate_.localization_valid(time);
if(was_localized_ && !localized && navigation_) request_stop();
was_localized_=localized;
// A command timeout always stops motion, but can occur normally while a
// recovery waits with zero output. Only localization loss cancels the goal.
if(time-last_cancel_>=0.5) cancel_goals();
});
RCLCPP_INFO(get_logger(),"cmd_vel_relay: %s -> %s navigation_mode=%d timeout=%.3fs; final output only",
input.c_str(),output.c_str(),navigation_,timeout);
}
private:
void OnTwist(
const std::string & topic,
const geometry_msgs::msg::Twist::SharedPtr & msg)
{
const int64_t now_ns = now().nanoseconds();
if (topic == "/cmd_vel_smoothed") {
last_smoothed_ns_ = now_ns;
pub_->publish(*msg);
return;
}
// 平滑器正在输出:丢弃原始/其它来源,避免两路命令打架
if (last_smoothed_ns_ != 0 && now_ns - last_smoothed_ns_ < 200'000'000LL) {
return;
}
pub_->publish(*msg);
static double seconds() { return std::chrono::duration<double>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
static bool nonzero(const geometry_msgs::msg::Twist &v) {
return v.linear.x!=0 || v.linear.y!=0 || v.linear.z!=0 || v.angular.x!=0 || v.angular.y!=0 || v.angular.z!=0;
}
bool cancel_pending() const { return pending_[0] || pending_[1]; }
void request_stop() {
if(!cancel_pending()) {
pending_.fill(true);
RCLCPP_ERROR(get_logger(),"motion interlock: localization/command invalid; stopping and canceling navigation goals");
}
}
void cancel_goals() {
last_cancel_=seconds();
for(std::size_t i=0;i<cancel_.size();++i) {
if(inflight_[i] && last_cancel_-sent_at_[i]>1.0) {
cancel_[i]->remove_pending_request(request_ids_[i]); inflight_[i]=false;
}
if(!pending_[i] || inflight_[i] || !cancel_[i]->service_is_ready()) continue;
inflight_[i]=true;
// Zero UUID/stamp cancels goals belonging to this Nav2 action server only.
auto request=std::make_shared<action_msgs::srv::CancelGoal::Request>();
const auto request_token=cancel_[i]->async_send_request(request,[this,i](rclcpp::Client<action_msgs::srv::CancelGoal>::SharedFuture response) {
inflight_[i]=false;
if(response.get()->return_code==action_msgs::srv::CancelGoal::Response::ERROR_NONE)
pending_[i]=false;
});
request_ids_[i]=request_token.request_id; sent_at_[i]=last_cancel_;
}
}
core::MotionInterlock gate_;
bool navigation_{true},require_health_{true},was_localized_{false};
double last_cancel_{-1};
std::array<std::int64_t,2> request_ids_{};
std::array<double,2> sent_at_{};
std::array<bool,2> pending_{false,false},inflight_{false,false};
std::array<rclcpp::Client<action_msgs::srv::CancelGoal>::SharedPtr,2> cancel_;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr pub_;
std::vector<rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr> subs_;
std::vector<std::string> in_topics_;
int64_t last_smoothed_ns_ = 0;
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr sub_;
rclcpp::Subscription<std_msgs::msg::Bool>::SharedPtr health_sub_;
rclcpp::TimerBase::SharedPtr timer_;
};
} // namespace sentry_nav
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<sentry_nav::CmdVelRelay>());
rclcpp::shutdown();
return 0;
} // namespace sentry_nav
int main(int argc,char **argv) {
rclcpp::init(argc,argv);
try { rclcpp::spin(std::make_shared<sentry_nav::CmdVelRelay>()); }
catch(const std::exception &e) { std::fprintf(stderr,"cmd_vel_relay: %s\n",e.what()); rclcpp::shutdown(); return 1; }
rclcpp::shutdown(); return 0;
}
+6 -3
View File
@@ -91,10 +91,13 @@ public:
tf_buffer_ = std::make_unique<tf2_ros::Buffer>(get_clock());
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
// 用 SensorDataQoS:点云量大,BEST_EFFORT 更合适
pub_ = create_publisher<sensor_msgs::msg::PointCloud2>(output_topic_, rclcpp::SensorDataQoS());
// Reliable filtered output lets localization recover a lost UDP fragment.
// Keep a best-effort input option for external sensor drivers.
const bool reliable=declare_parameter<bool>("reliable_clouds",false);
const rclcpp::QoS input_qos=reliable ? rclcpp::QoS(5).reliable() : rclcpp::SensorDataQoS();
pub_ = create_publisher<sensor_msgs::msg::PointCloud2>(output_topic_, rclcpp::QoS(5).reliable());
sub_ = create_subscription<sensor_msgs::msg::PointCloud2>(
input_topic_, rclcpp::SensorDataQoS(),
input_topic_, input_qos,
[this](sensor_msgs::msg::PointCloud2::ConstSharedPtr msg) { OnCloud(msg); });
// /scan2d:由过滤后的点云投影出的 2D 激光,AMCL 做定位用(collision_monitor 也吃它)。
+12 -8
View File
@@ -17,10 +17,10 @@ int main() {
const SelfFilterCore filter{FilterParams{}};
// ---------- 1. 车身包围盒内的点必须剔除 ----------
// 雷达前方/侧面/上方,只要落在 x∈(-0.4,0.4) y∈(-0.38,0.38) z∈(-0.05,0.6) 就剔
// Chassis and noisy forward gimbal returns.
EXPECT_EQ(filter.Classify(0.0f, 0.0f, 0.30f), DropReason::kInsideEgoBox);
EXPECT_EQ(filter.Classify(0.35f, 0.30f, 0.50f), DropReason::kInsideEgoBox);
EXPECT_EQ(filter.Classify(-0.35f, -0.30f, 0.10f), DropReason::kInsideEgoBox);
EXPECT_EQ(filter.Classify(0.28f, 0.25f, 0.50f), DropReason::kInsideEgoBox);
EXPECT_EQ(filter.Classify(-0.28f, -0.25f, 0.10f), DropReason::kInsideEgoBox);
EXPECT_FALSE(filter.Keep(0.0f, 0.0f, 0.30f));
// ---------- 2. 盒子外的点必须保留 ----------
@@ -56,13 +56,17 @@ int main() {
EXPECT_EQ(filter.Classify(1.0f, -kInf, 0.30f), DropReason::kNonFinite);
// ---------- 6. 边界:盒面用严格不等号,落在面上算保留 ----------
EXPECT_TRUE(filter.Keep(0.40f, 0.0f, 0.30f)); // x == box_max_x
EXPECT_TRUE(filter.Keep(-0.40f, 0.0f, 0.30f)); // x == box_min_x
EXPECT_TRUE(filter.Keep(0.0f, 0.38f, 0.30f)); // y == box_max_y
EXPECT_TRUE(filter.Keep(0.0f, 0.0f, 0.60f)); // z == box_max_z
EXPECT_TRUE(filter.Keep(0.365f, 0.0f, 0.30f)); // x == box_max_x
EXPECT_TRUE(filter.Keep(-0.294f, 0.0f, 0.30f)); // x == box_min_x
EXPECT_TRUE(filter.Keep(0.0f, 0.2655f, 0.30f)); // y == box_max_y
EXPECT_TRUE(filter.Keep(0.0f, 0.0f, 0.545f)); // z == box_max_z
// 稍微往里一点就该被剔
EXPECT_EQ(filter.Classify(0.39f, 0.0f, 0.30f), DropReason::kInsideEgoBox);
EXPECT_EQ(filter.Classify(0.364f, 0.0f, 0.30f), DropReason::kInsideEgoBox);
EXPECT_TRUE(filter.Keep(0.37f, 0.0f, 0.30f)); // external obstacle before contact
EXPECT_FALSE(filter.Keep(0.357f, 0.14f, 0.530f)); // measured gimbal return envelope
EXPECT_TRUE(filter.Keep(0.0f, 0.30f, 0.30f));
EXPECT_EQ(filter.Classify(0.319f, 0.14f, 0.49f), DropReason::kInsideEgoBox);
// ---------- 7. 自定义参数的构造函数确实生效 ----------
FilterParams small;
small.max_range = 3.0f;
+38 -12
View File
@@ -76,6 +76,7 @@ SCRIPTS = PKG_SHARE / 'scripts'
if str(WS / 'tools') not in sys.path:
sys.path.insert(0, str(WS / 'tools'))
import project_env # noqa: E402 (必须在 sys.path 调整之后导入)
from dds_environment import defaults as dds_defaults # noqa: E402
BIN_DIR = project_env.find_bin_dir(WS)
GZ_VERSION_ARGS = project_env.gz_version_args()
@@ -128,6 +129,27 @@ def _validate_lio(context):
return []
def _preflight_nav2(context):
if LaunchConfiguration('nav2').perform(context).lower() in ('true', '1'):
subprocess.run(['python3', str(WS / 'tools' / 'nav2_startup.py'), '--preflight'],
env=dict(context.environment), check=True)
return []
def _start_velocity_relay(context):
navigation = LaunchConfiguration('nav2').perform(context).lower() in ('true', '1')
localization = LaunchConfiguration('localization').perform(context)
input_topic = '/cmd_vel' if navigation else context.environment.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel')
return [ExecuteProcess(
cmd=[str(BIN_DIR / 'cmd_vel_relay'),
'--ros-args', '-p', 'use_sim_time:=true',
'-p', f'navigation_mode:={str(navigation).lower()}',
'-p', f'require_localization_health:={str(localization == "lio").lower()}',
'-p', f'in_topic:={input_topic}'],
name='cmd_vel_relay', output='screen',
)]
def generate_launch_description():
headless = LaunchConfiguration('headless')
nav2 = LaunchConfiguration('nav2')
@@ -156,14 +178,15 @@ def generate_launch_description():
# 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',
cmd=['python3', str(WS / 'tools' / 'run_nav2.py'),
'--timeout', os.environ.get('SENTRY_NAV2_TIMEOUT', '120'), '--',
['map:=', map_yaml], 'use_sim_time:=true', 'autostart:=False',
['params_file:=', str(PKG_SHARE / 'config' / 'nav2_params.yaml')],
'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),
name='nav2', output='screen', condition=IfCondition(nav2_on), sigterm_timeout='20',
)
actions = [
@@ -195,13 +218,16 @@ def generate_launch_description():
description='迁移包(guodong_sentry_sim)所在目录'),
# ---------------- 环境变量 ----------------
SetEnvironmentVariable('FASTDDS_BUILTIN_TRANSPORTS',
dds_defaults(os.environ)['FASTDDS_BUILTIN_TRANSPORTS']),
SetEnvironmentVariable('GZ_SIM_RESOURCE_PATH', _gz_resource_path()),
SetEnvironmentVariable(
'GZ_PARTITION', os.environ.get('GZ_PARTITION', 'sentry')),
SetEnvironmentVariable(
'ROS_DOMAIN_ID', os.environ.get('ROS_DOMAIN_ID', '0')),
'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']),
# URDF 的网格路径靠它解析;tools/check_stack.py 也读它
SetEnvironmentVariable('SENTRY_SIM_SHARE', str(PKG_SHARE)),
OpaqueFunction(function=_preflight_nav2),
# ---------------- 1. Gazebo ----------------
# 用 run_gz.sh 包一层:它会清掉 LD_LIBRARY_PATH,
@@ -269,27 +295,23 @@ def generate_launch_description():
# ---------------- 5. /cmd_vel 改名转发 ----------------
# 插件订阅 /model/sentry/cmd_vel,而桥只支持两端同名
ExecuteProcess(
cmd=[str(BIN_DIR / 'cmd_vel_relay'),
'--ros-args', '-p', 'use_sim_time:=true'],
name='cmd_vel_relay',
output='screen',
),
OpaqueFunction(function=_start_velocity_relay),
# ---------------- 6. 点云自滤 ----------------
# 本工程没有 ament 注册,不能 ros2 run,直接跑 xmake 产物
ExecuteProcess(
cmd=[str(BIN_DIR / 'self_filter'),
'--ros-args', '-p', 'use_sim_time:=true'],
'--ros-args', '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true'],
name='self_filter',
output='screen',
),
ExecuteProcess(
cmd=[str(BIN_DIR / 'field_localization_node'), '--ros-args',
'-p', 'use_sim_time:=true', '-p', 'point_cloud_topic:=/scan/points_filtered',
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=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', "diagnostics_path:='" + os.environ.get('LIO_TRACE_PATH', '') + "'",
'-p', ['initial_x:=', LaunchConfiguration('lio_initial_x')],
'-p', ['initial_y:=', LaunchConfiguration('lio_initial_y')],
'-p', ['initial_z:=', LaunchConfiguration('lio_initial_z')],
@@ -316,6 +338,10 @@ def generate_launch_description():
# 这里再起一份会**同名冲突**(lifecycle_manager 崩在 createLifecycleServiceServers)。
# ---------------- 9. Nav2 ----------------
RegisterEventHandler(OnProcessExit(
target_action=navigation,
on_exit=[EmitEvent(event=Shutdown(reason='Nav2 supervisor exited'))],
)),
RegisterEventHandler(OnProcessExit(
target_action=navigation_ready,
on_exit=lambda event, context: [navigation] if event.returncode == 0 else [
+35 -19
View File
@@ -61,6 +61,9 @@ HEADLESS="${HEADLESS:-0}"
NAV2="${NAV2:-1}"
RVIZ="${RVIZ:-1}"
# Use exactly the same defaults as the Python launch entry point.
eval "$(python3 "$WS/tools/dds_environment.py" --shell)"
# ---------- 试运行:只打印探测结果,不启动任何东西 ----------
# 排查"路径不对/版本不对"时先跑这个,比启动一半再失败好定位:
# SENTRY_DRY_RUN=1 scripts/sentry_up.sh
@@ -88,12 +91,8 @@ if [ "${SENTRY_DRY_RUN:-0}" != "0" ]; then
exit 0
fi
# Fast DDS 的共享内存传输在部分环境会导致 action 服务发现失败:
# bt_navigator 等不到 /wait action(60 s 超时)→ lifecycle_manager 报
# "Failed to change state for node: bt_navigator" / "Aborting bringup"。
# 这里默认走 UDPv4 传输(本机小消息走 UDP,不依赖 /dev/shm),实测能稳定激活。
# 想回退共享内存:FASTDDS_BUILTIN_TRANSPORTS=SHM scripts/sentry_up.sh
export FASTDDS_BUILTIN_TRANSPORTS="${FASTDDS_BUILTIN_TRANSPORTS:-UDPv4}"
# UDPv4 is a transport default, not a guarantee that service discovery succeeds.
python3 "$WS/tools/dds_environment.py"
# ROS 环境由上面的 env_source_ros 自动 source(逻辑在 env_common.sh),
# 不再写死 /opt/ros/<发行版>/setup.bash —— 换发行版不用改脚本。
@@ -187,6 +186,10 @@ cleanup() {
}
trap cleanup EXIT INT TERM
if [ "$NAV2" = "1" ]; then
python3 "$WS/tools/nav2_startup.py" --preflight
fi
# ---------- 1. Gazebo(系统版,清掉 ROS vendor 的库路径)----------
# --force-version 的大版本号是**探测出来的**(env_gz_version_args):
# 换了 Gazebo 大版本不用改脚本;想强制指定就 GZ_FORCE_VERSION=11。
@@ -245,9 +248,10 @@ 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'
runtime_dir="${SENTRY_RUNTIME_DIR:-${WS}/generated}"
mkdir -p "$runtime_dir"
xacro "${PKG_SHARE}/urdf/sentry.urdf.xacro" > "$runtime_dir/robot_description.urdf"
python3 - "$runtime_dir/robot_description.urdf" "$runtime_dir/robot_state_publisher.json" <<'PY_PARAMS'
import json
import sys
from pathlib import Path
@@ -255,7 +259,7 @@ 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 \
--params-file "${WS}/generated/robot_state_publisher.json" &
--params-file "$runtime_dir/robot_state_publisher.json" &
PIDS+=($!)
# ---------- 5. odom -> base_link ----------
@@ -267,21 +271,28 @@ PIDS+=($!)
# ---------- 5.5 /cmd_vel 转发(Nav2 -> ros_gz 桥用的话题名)----------
echo "[sentry_up] 启动 cmd_vel 转发(${NAV_BIN_DIR}/cmd_vel_relay,C++ 版)"
$(nav_cmd cmd_vel_relay) --ros-args -p use_sim_time:=true &
RELAY_NAVIGATION=false
if [ "$NAV2" = "1" ]; then RELAY_NAVIGATION=true; fi
RELAY_HEALTH=false
if [ "$LOCALIZATION" = lio ]; then RELAY_HEALTH=true; fi
RELAY_INPUT=/cmd_vel
if [ "$RELAY_NAVIGATION" = false ]; then RELAY_INPUT="${MANUAL_CMD_VEL_TOPIC:-/cmd_vel}"; fi
$(nav_cmd cmd_vel_relay) --ros-args -p use_sim_time:=true \
-p navigation_mode:="$RELAY_NAVIGATION" -p require_localization_health:="$RELAY_HEALTH" -p in_topic:="$RELAY_INPUT" &
PIDS+=($!)
# ---------- 5.55 点云自滤(剔除车身自身回波,Nav2 避障用)----------
echo "[sentry_up] 启动点云自滤(${NAV_BIN_DIR}/self_filter)"
$(nav_cmd self_filter) --ros-args -p use_sim_time:=true &
$(nav_cmd self_filter) --ros-args -p use_sim_time:=true -p reliable_clouds:=true &
PIDS+=($!)
# ---------- 5.6 唯一 map->odom 发布者:LIO 或 AMCL ----------
if [ "$LOCALIZATION" = lio ]; then
echo "[sentry_up] LIO mode=$LIO_MODE (AMCL disabled)"
$(nav_cmd field_localization_node) --ros-args -p use_sim_time:=true \
-p point_cloud_topic:=/scan/points_filtered -p imu_topic:=/imu \
-p point_cloud_topic:=/scan/points_filtered -p imu_topic:=/imu -p reliable_clouds:=true \
-p mode:="$LIO_MODE" -p map_path:="$LIO_MAP" -p export_map_path:="$LIO_EXPORT_MAP" \
-p publish_map_to_odom:=true \
-p publish_map_to_odom:=true -p "diagnostics_path:='${LIO_TRACE_PATH:-}'" \
-p initial_x:="${LIO_INITIAL_X:--5.0}" -p initial_y:="${LIO_INITIAL_Y:-3.0}" \
-p initial_z:="${LIO_INITIAL_Z:-0.0}" -p initial_yaw:="${LIO_INITIAL_YAW:-0.0}" &
PIDS+=($!)
@@ -299,8 +310,14 @@ PIDS+=($!)
# Nav2 manages the existing 2D map_server in both localization branches.
echo "[sentry_up] 仿真进程已启动;Nav2 激活结果见后续日志。坐标系:"
echo " map —— 场地中心 = (0,0),范围 x[-6,6] y[-4,4],当前出生点在 (-5.0, 3.0)"
echo " field —— 与 map 相同(恒等变换,保留给决策代码用)"
echo "体检(含 Gazebo 真值对照):python3 tools/check_stack.py"
# ---------- 6. Nav2 ----------
if [ "$NAV2" = "1" ]; then
python3 "$WS/tools/wait_navigation_ready.py"
echo "[sentry_up] 启动 Nav2($LOCALIZATION + 栅格图)"
# 三个参数都是必需的,各有原因(踩过的坑):
# use_composition:=False 组合模式在本机起不来 —— /nav2_container 起来后一个组件都不加载,
@@ -311,9 +328,10 @@ if [ "$NAV2" = "1" ]; then
# 发现不到,lifecycle_manager 会无限等下去(日志刷
# "Waiting for service keepout_costmap_filter_info_server/get_state"),
# Nav2 永远不激活 → 所有导航目标被拒。我们不用禁入区/限速区,直接关掉。
ros2 launch nav2_bringup bringup_launch.py \
python3 "$WS/tools/run_nav2.py" --timeout "${SENTRY_NAV2_TIMEOUT:-120}" -- \
map:="${MAP_YAML}" \
use_sim_time:=true \
autostart:=False \
params_file:="${PKG_SHARE}/config/nav2_params.yaml" \
use_composition:=False \
use_localization:="$NAV2_LOCALIZATION" \
@@ -322,16 +340,14 @@ if [ "$NAV2" = "1" ]; then
use_speed_zones:=False \
slam:=False &
PIDS+=($!)
NAV2_PID=$!
if [ "$RVIZ" = "1" ] && [ "$HEADLESS" != "1" ]; then
echo "[sentry_up] 启动 RViz"
ros2 run rviz2 rviz2 -d "${PKG_SHARE}/config/sentry.rviz" --ros-args -p use_sim_time:=true &
PIDS+=($!)
fi
wait "$NAV2_PID"
fi
echo "[sentry_up] 全部启动完成。坐标系:"
echo " map —— 场地中心 = (0,0),范围 x[-6,6] y[-4,4],当前出生点在 (-5.0, 3.0)"
echo " field —— 与 map 相同(恒等变换,保留给决策代码用)"
echo "体检(含 Gazebo 真值对照):python3 tools/check_stack.py"
wait