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
+1 -1
View File
@@ -34,7 +34,7 @@ def yaw(q):
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.publisher = self.create_publisher(Twist, os.environ.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel'), 10)
self.origin = None
self.pose = None
self.index = 0
+5 -4
View File
@@ -24,7 +24,7 @@ df -h /dev/shm | sed 's/^/ /'
total=$(ls -1 /dev/shm 2>/dev/null | wc -l)
fast=$(ls -1 /dev/shm 2>/dev/null | grep -cE "$SEG_PATTERN")
echo " 文件总数 : $total"
echo " Fast DDS 残留段 : $fast"
echo " Fast DDS 文件数 : $fast(可能属于活跃进程,不能仅凭文件数判定残留)"
if [ "$fast" -gt 0 ]; then
echo " → 前 10 个:"
ls -1 /dev/shm | grep -E "$SEG_PATTERN" | head -10 | sed 's/^/ /'
@@ -99,10 +99,11 @@ echo "=============================================="
echo " 结论"
echo "=============================================="
if [ "$fast" -eq 0 ]; then
echo " ✅ /dev/shm 干净,没有 Fast DDS 残留。"
echo " 如果节点仍然发现不到彼此,问题不在这里 —— 换方案 B(自定义 BT 去掉 Wait)。"
echo " ✅ 未发现匹配的 Fast DDS 共享内存文件。"
echo " 这不能排除 DDS 发现或服务响应异常;UDPv4 下也可能发生。"
echo " 请查看启动日志中的缺失服务、实际 DDS 环境和 Nav2 激活结果,保留 BT 校验与恢复节点。"
else
echo " ⚠️ 发现 $fast 个 Fast DDS 残留段。"
echo " ⚠️ 发现 $fast 个 Fast DDS 文件;有活跃进程时不应当作残留清理。"
if [ "$n_pids" -eq 0 ]; then
if [ "${1:-}" = "--clean" ]; then
echo " → 开始清理…"
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Shared DDS defaults for both launchers; explicit nonempty settings take precedence."""
import argparse
import json
import os
import shlex
KEYS = ('RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'RMW_FASTRTPS_PUBLICATION_MODE',
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER',
'ROS_LOCALHOST_ONLY')
def defaults(environment):
result = dict(environment)
for key, value in (('ROS_DOMAIN_ID', '0'), ('FASTDDS_BUILTIN_TRANSPORTS', 'UDPv4')):
if not result.get(key):
result[key] = value
return result
def describe(environment):
return json.dumps({key: environment.get(key, '<ROS default>') for key in KEYS},
ensure_ascii=False, sort_keys=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--shell', action='store_true')
args = parser.parse_args()
env = defaults(os.environ)
if args.shell:
for name in ('ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS'):
print(f'export {name}={shlex.quote(env[name])}')
else:
print('[DDS] '+describe(env), flush=True)
+264
View File
@@ -0,0 +1,264 @@
#!/usr/bin/env python3
"""Nav2 domain preflight, discovery-gated startup and bounded readiness check."""
import argparse
import json
import os
import re
import time
from pathlib import Path
import rclpy
from geometry_msgs.msg import PoseStamped
from lifecycle_msgs.srv import GetState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import Log
from rcl_interfaces.srv import GetParameters
from rclpy.utilities import get_rmw_implementation_identifier
from std_srvs.srv import Trigger
from dds_environment import defaults, describe
CONFLICT_SERVICES = {
'lifecycle_manager_nav2': '/lifecycle_manager_nav2/manage_nodes',
'planner_server': '/planner_server/get_state', 'bt_navigator': '/bt_navigator/get_state',
'controller_server': '/controller_server/get_state', 'map_server': '/map_server/get_state',
'amcl': '/amcl/get_state', 'field_localization': '/field_localization/save_map',
}
def path_probe_request():
# Read-only collision query at the map origin; is_valid need not be true.
request = IsPathValid.Request()
request.path.header.frame_id = 'map'
pose = PoseStamped()
pose.header.frame_id = 'map'
pose.pose.orientation.w = 1.0
request.path.poses = [pose]
return request
def ready(managed, states, manager_active, path_responded):
return (bool(managed) and all(states.get(name) == 3 for name in managed)
and manager_active and path_responded)
def failure_details(managed, states, path_discovered, path_responded, errors):
missing = sorted({match for error in errors for match in
re.findall(r'"([^"]+)" (?:action|service) server not available', error)})
return {'managed_node_list_received': bool(managed),
'missing_dependencies': missing,
'not_active': {name: states.get(name, 'response timeout / unavailable')
for name in managed if states.get(name) != 3},
'is_path_valid_discovered': path_discovered,
'is_path_valid_responded': path_responded, 'errors': errors[-8:]}
def preflight(node, duration):
deadline = time.monotonic()+duration
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.1)
# RViz lifecycle clients can share a manager's node name; only actual servers conflict.
conflicts = sorted(name for name, service in CONFLICT_SERVICES.items()
if node.get_servers_info_by_service(service))
if conflicts:
print('[Nav2] 启动拒绝:当前 ROS_DOMAIN_ID='+os.environ['ROS_DOMAIN_ID']+
' 已有导航/定位节点:'+', '.join(conflicts)+
'。请先正常退出旧启动入口,或为独立仿真显式选择其他 ROS_DOMAIN_ID;未终止任何进程。',
flush=True)
return 1
return 0
def complete_endpoint(info):
# Request/reply endpoints must belong to the same participant, not a stale mixed pair.
return (info.endpoint_count == 2 and len(info.endpoint_gids) == 2
and all(len(gid) >= 12 for gid in info.endpoint_gids)
and info.endpoint_gids[0][:12] == info.endpoint_gids[1][:12])
def lifecycle_discovery_gaps(node, managed):
gaps = []
for name in managed:
for service in ('get_state', 'change_state'):
topic = f'/{name}/{service}'
servers = node.get_servers_info_by_service(topic)
clients = node.get_clients_info_by_service(topic)
if not any(info.node_name == name and complete_endpoint(info) for info in servers):
gaps.append(topic+' server')
if not any(info.node_name == 'lifecycle_manager_nav2' and complete_endpoint(info)
for info in clients):
gaps.append(topic+' manager client')
return gaps
def wait_active(node, timeout, activate=False, result_path=None):
started = time.monotonic()
deadline = started+timeout
parameter = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
active = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
path = node.create_client(IsPathValid, '/is_path_valid')
control = node.create_client(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes') if activate else None
startup_future = None
discovery_since = None
discovery_gaps = []
managed = []
states = {}
observed = {}
clients = {}
pending = {}
errors = []
manager_failed = False
failed_at = None
manager_active = False
path_responded = False
path_discovered = False
stable_since = None
last_poll = 0.0
def on_log(message):
nonlocal manager_failed, failed_at
if message.level >= Log.ERROR and ('bt_navigator' in message.name
or 'lifecycle_manager' in message.name):
errors.append(message.name+': '+message.msg)
del errors[:-8]
if 'Failed to bring up all requested nodes' in message.msg:
manager_failed = True
failed_at = time.monotonic()
subscription = node.create_subscription(Log, '/rosout', on_log, 100)
def submit(key, client, request):
if key not in pending and client.service_is_ready():
pending[key] = (client, client.call_async(request), time.monotonic())
def finish(code):
# Let already-sent queries complete before destroying the clients.
until = time.monotonic()+0.5
while (rclpy.ok() and time.monotonic() < until
and any(not future.done() for _, future, _ in pending.values())):
rclpy.spin_once(node, timeout_sec=0.02)
for client, future, _ in pending.values():
if not future.done():
client.remove_pending_request(future)
if result_path is not None:
result_path.write_text(json.dumps({
'passed': code == 0, 'states': states,
'retryable': (code != 0 and not manager_active
and states.get('bt_navigator') in (1, 2)
and time.monotonic()-observed.get('bt_navigator', 0.0) < 2.5),
**failure_details(managed, states, path_discovered, path_responded, errors)},
ensure_ascii=False, indent=2))
return code
print('[Nav2] 等待 Nav2 激活(全部受管节点 ACTIVE、管理器就绪、/is_path_valid 响应)', flush=True)
while rclpy.ok() and time.monotonic() < deadline:
rclpy.spin_once(node, timeout_sec=0.05)
now = time.monotonic()
for key, (client, future, stamp) in list(pending.items()):
if not future.done() and now-stamp < 2:
continue
response = future.result() if future.done() and not future.cancelled() else None
if not future.done():
client.remove_pending_request(future)
del pending[key]
observed[key] = now if response is not None else 0.0
if key == 'parameters':
if response and response.values:
managed = list(response.values[0].string_array_value)
for name in managed:
if name not in clients:
clients[name] = node.create_client(GetState, f'/{name}/get_state')
elif key == 'manager':
manager_active = bool(response and response.success)
elif key == 'path':
# Collision validity is distinct from request/response availability.
path_responded = response is not None
else:
states[key] = response.current_state.id if response else None
if now-last_poll >= 0.5:
last_poll = now
if not managed:
submit('parameters', parameter, GetParameters.Request(names=['node_names']))
submit('manager', active, Trigger.Request())
path_discovered = path.service_is_ready()
# The planner costmap does not run before activation.
if states.get('planner_server') == 3:
submit('path', path, path_probe_request())
for name, client in clients.items():
if not client.service_is_ready() or now-observed.get(name, 0.0) > 2.5:
states[name] = None
submit(name, client, GetState.Request())
if not active.service_is_ready() or now-observed.get('manager', 0.0) > 2.5:
manager_active = False
if not path_discovered or now-observed.get('path', 0.0) > 2.5:
path_responded = False
if activate and startup_future is None:
discovery_gaps = lifecycle_discovery_gaps(node, managed) if managed else ['manager node list']
warmed = (bool(managed) and not discovery_gaps and control.service_is_ready()
and observed.get('manager', 0.0) > 0
and all(states.get(name) == 1 for name in managed))
if warmed:
if discovery_since is None:
discovery_since = now
if now-discovery_since >= 1:
print('[Nav2] 状态服务已响应、管理器状态切换端点完整,发起 STARTUP', flush=True)
startup_future = control.call_async(ManageLifecycleNodes.Request(
command=ManageLifecycleNodes.Request.STARTUP))
else:
discovery_since = None
if startup_future is not None and startup_future.done():
response = startup_future.result()
if response is None or not response.success:
errors.append('lifecycle_manager_nav2: STARTUP returned failure')
manager_failed = True
if failed_at is None:
failed_at = now
if manager_failed:
# Obtain a fresh navigator state after its failed activation callback returns.
# Recovery is permitted only if the navigator is definitely not ACTIVE.
if observed.get('bt_navigator', 0.0) > failed_at or now-failed_at > 2.5:
break
continue
if ready(managed, states, manager_active, path_responded):
if stable_since is None:
stable_since = now
if now-stable_since >= 1:
print(f'[Nav2] Nav2 就绪:{len(managed)} 个受管节点 ACTIVE,'
f'/is_path_valid 已响应,耗时 {now-started:.2f}s', flush=True)
return finish(0)
else:
stable_since = None
_ = subscription
print('[Nav2] 激活失败:'+json.dumps(failure_details(
managed, states, path_discovered, path_responded, errors), ensure_ascii=False), flush=True)
if discovery_gaps and startup_future is None:
print('[Nav2] 尚未完成发现的生命周期端点:'+', '.join(discovery_gaps), flush=True)
return finish(1)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--preflight', action='store_true')
parser.add_argument('--activate', action='store_true',
help='call manager STARTUP once, after lifecycle discovery is ready (requires autostart=False)')
parser.add_argument('--result', type=Path)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('--discovery-seconds', type=float, default=3)
args = parser.parse_args()
if args.timeout <= 0 or args.discovery_seconds <= 0:
parser.error('timeouts must be positive')
os.environ.update(defaults(os.environ))
print('[DDS] '+describe(os.environ), flush=True)
rclpy.init(args=[])
node = rclpy.create_node('sentry_nav2_preflight' if args.preflight else 'sentry_nav2_readiness')
print('[DDS] actual RMW='+get_rmw_implementation_identifier(), flush=True)
try:
return preflight(node, args.discovery_seconds) if args.preflight else wait_active(
node, args.timeout, args.activate, args.result)
finally:
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
raise SystemExit(main())
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Supervise only our Nav2 process group; bounded recovery before navigation becomes active."""
import argparse
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import tempfile
import time
def stop_owned(process):
if process is None:
return
# Each child is started in a new session. No process-name matching or shared-memory cleanup.
for signum, timeout in ((signal.SIGINT, 8), (signal.SIGTERM, 2), (signal.SIGKILL, 1)):
try:
os.killpg(process.pid, signum)
except ProcessLookupError:
break
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
process.poll()
try:
os.killpg(process.pid, 0)
except ProcessLookupError:
return
time.sleep(0.05)
process.poll()
def supervise(command, checker, attempts, timeout):
navigation = None
observer = None
try:
with tempfile.TemporaryDirectory(prefix='sentry-nav2-') as directory:
for attempt in range(1, attempts+1):
result_path = Path(directory)/f'{attempt}.json'
print(f'[Nav2 supervisor] startup attempt {attempt}/{attempts}', flush=True)
navigation = subprocess.Popen(command, start_new_session=True)
observer = subprocess.Popen(
checker+['--activate', '--timeout', str(timeout), '--result', str(result_path)],
start_new_session=True)
while navigation.poll() is None and observer.poll() is None:
time.sleep(0.1)
if navigation.poll() is not None:
print('[Nav2 supervisor] Nav2 process exited before readiness; aborting', flush=True)
return 1
result = json.loads(result_path.read_text()) if result_path.is_file() else {}
if observer.returncode == 0 and result.get('passed'):
print(f'[Nav2 supervisor] ready on attempt {attempt}; startup recovery disabled', flush=True)
return navigation.wait()
stop_owned(observer)
observer = None
stop_owned(navigation)
navigation = None
if not result.get('retryable') or attempt == attempts:
print('[Nav2 supervisor] startup failed; no further retry (navigator active/unknown, '
'or attempt limit reached)', flush=True)
return 1
print('[Nav2 supervisor] navigator confirmed UNCONFIGURED/INACTIVE; '
'recreating only owned Nav2 processes. LIO/Gazebo continue running.', flush=True)
return 1
finally:
stop_owned(observer)
stop_owned(navigation)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--attempts', type=int, default=3)
parser.add_argument('--timeout', type=float, default=120)
parser.add_argument('launch_arguments', nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.attempts < 1 or args.attempts > 3 or args.timeout <= 0:
parser.error('attempts must be 1..3; timeout must be positive')
arguments = args.launch_arguments
if arguments and arguments[0] == '--':
arguments = arguments[1:]
if not arguments:
parser.error('Nav2 bringup arguments required after --')
def interrupted(signum, frame):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGTERM, signal.SIG_IGN)
raise KeyboardInterrupt
signal.signal(signal.SIGINT, interrupted)
signal.signal(signal.SIGTERM, interrupted)
try:
return supervise(['ros2', 'launch', 'nav2_bringup', 'bringup_launch.py', *arguments],
[sys.executable, str(Path(__file__).with_name('nav2_startup.py'))],
args.attempts, args.timeout)
except KeyboardInterrupt:
return 130
if __name__ == '__main__':
raise SystemExit(main())
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Isolated live relay test. No Gazebo, TF, or real actuator subscribers."""
import argparse
import os
from pathlib import Path
import signal
import subprocess
import time
import uuid
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary',type=Path,default=Path(__file__).resolve().parents[1]/'build/bin/cmd_vel_relay')
args=parser.parse_args()
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
import rclpy
from geometry_msgs.msg import Twist
from std_msgs.msg import Bool
from action_msgs.srv import CancelGoal
rclpy.init();node=rclpy.create_node('test_motion_interlock')
received=[];cancellations=[]
subscription=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda m:received.append((time.monotonic(),m.linear.x)),100)
health=node.create_publisher(Bool,'/field_localization/navigation_valid',1)
final=node.create_publisher(Twist,'/cmd_vel',1)
upstream=node.create_publisher(Twist,'/cmd_vel_smoothed',1)
raw=node.create_publisher(Twist,'/cmd_vel_nav',1)
def cancel(req,response):
cancellations.append(time.monotonic());response.return_code=0
return response
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
for name in ['/navigate_to_pose','/navigate_through_poses']]
process=subprocess.Popen([str(args.binary),'--ros-args','-p','navigation_mode:=true'],
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
checks=0
def check(ok,message):
nonlocal checks
checks+=1
if not ok: raise RuntimeError(message)
print('PASS',message,flush=True)
def drive(duration,valid=True,publish_health=True,publish_final=True):
until=time.monotonic()+duration
while time.monotonic()<until:
if publish_health:
h=Bool();h.data=valid;health.publish(h)
if publish_final:
m=Twist();m.linear.x=0.1;final.publish(m)
m=Twist();m.linear.x=1.5;upstream.publish(m);raw.publish(m)
rclpy.spin_once(node,timeout_sec=0.01)
try:
deadline=time.monotonic()+10
while final.get_subscription_count()<1 and time.monotonic()<deadline:
rclpy.spin_once(node,timeout_sec=0.02)
check(final.get_subscription_count()==1,'one final velocity subscription')
drive(0.5,publish_health=False)
check(received and all(v==0 for _,v in received),'no motion before valid localization')
# A blocked nonzero command requests cancellation; allow both services to acknowledge.
drive(0.8)
check(any(v==0.1 for _,v in received),'valid final velocity reaches actuator')
check(all(v<=0.1 for _,v in received),'raw and smoothed topics cannot bypass collision output')
before=time.monotonic();drive(0.4,valid=False)
zeros=[t for t,v in received if t>=before and v==0]
check(bool(zeros) and min(zeros)-before<0.1,'invalid health stops within 100 ms')
check(len(cancellations)>=2,'navigation action servers receive cancellation')
drive(0.5)
before=time.monotonic();drive(0.6,publish_health=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale health stops within 400 ms')
drive(0.5)
before=time.monotonic();drive(0.6,publish_final=False)
zeros=[t for t,v in received if t>=before+0.3 and v==0]
check(bool(zeros) and min(zeros)-before<0.4,'stale final command stops despite upstream traffic')
check(process.poll() is None,'relay remains alive')
print(f'{checks} live checks passed; health_stop_ms={(min(t for t,v in received if t>=before+0.3 and v==0)-before)*1000:.3f}')
finally:
if process.poll() is None:os.killpg(process.pid,signal.SIGINT)
try:process.wait(timeout=5)
except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait()
_=subscription,services
node.destroy_node();rclpy.shutdown()
if __name__=='__main__':main()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Fault-injection checks using isolated ROS services, without Gazebo or motion commands."""
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import uuid
from types import SimpleNamespace
from dds_environment import defaults
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
env = defaults({'ROS_DOMAIN_ID': '77', 'FASTDDS_BUILTIN_TRANSPORTS': 'SHM'})
CHECK(env['ROS_DOMAIN_ID'] == '77' and env['FASTDDS_BUILTIN_TRANSPORTS'] == 'SHM',
'explicit environment override lost')
os.environ.update(defaults(os.environ))
os.environ['ROS_DOMAIN_ID'] = str(50+int(uuid.uuid4().hex[:8], 16) % 50)
import rclpy
from lifecycle_msgs.msg import State
from lifecycle_msgs.srv import GetState, ChangeState
from nav2_msgs.srv import IsPathValid, ManageLifecycleNodes
from rcl_interfaces.msg import ParameterValue, ParameterType
from rcl_interfaces.srv import GetParameters
from std_srvs.srv import Trigger
from nav2_startup import ready, failure_details, complete_endpoint
managed = ['planner_server', 'bt_navigator', 'waypoint_follower']
states = dict.fromkeys(managed, 3)
CHECK(ready(managed, states, True, True), 'valid readiness rejected')
CHECK(not ready([], {}, True, True), 'missing manager node list accepted')
CHECK(not ready(managed, {**states, 'bt_navigator': 2}, True, True), 'inactive node accepted')
CHECK(not ready(managed, states, False, True), 'manager incomplete accepted')
CHECK(not ready(managed, states, True, False), 'nonresponding path service accepted')
details = failure_details(managed, {}, True, False,
['"wait" action server not available after waiting for 60.00s'])
CHECK(details['missing_dependencies'] == ['wait'], 'missing action not identified')
CHECK(complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [0]*16])),
'complete endpoint pair rejected')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=2, endpoint_gids=[[0]*16, [1]*16])),
'stale endpoints from different participants accepted')
CHECK(not complete_endpoint(SimpleNamespace(endpoint_count=1, endpoint_gids=[[0]*16])),
'half-discovered service accepted')
rclpy.init()
node = rclpy.create_node('planner_server')
executor = rclpy.executors.SingleThreadedExecutor()
executor.add_node(node)
extra_nodes = []
state_id = [3]
starts = []
def parameters(request, response):
response.values = [ParameterValue(type=ParameterType.PARAMETER_STRING_ARRAY,
string_array_value=managed)]
return response
def active(request, response):
response.success = True
return response
def state(request, response):
response.current_state = State(id=state_id[0])
return response
services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters),
node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)]
services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed]
command = [sys.executable, str(Path(__file__).with_name('nav2_startup.py'))]
def run(arguments):
process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, start_new_session=True)
try:
deadline = time.monotonic()+15
while process.poll() is None and time.monotonic() < deadline:
executor.spin_once(timeout_sec=0.02)
if process.poll() is None:
raise RuntimeError('test subprocess did not finish')
return process.returncode, process.communicate()[0]
finally:
if process.poll() is None:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
try:
code, text = run(['--preflight', '--discovery-seconds', '1'])
CHECK(code == 1 and 'planner_server' in text and '启动拒绝' in text,
'occupied domain was not rejected: '+text)
code, text = run(['--timeout', '3'])
CHECK(code == 1 and '激活失败' in text and '"is_path_valid_responded": false' in text,
'all active nodes with missing path service incorrectly reported ready: '+text)
def path(request, response):
response.success = True
response.is_valid = False # A collision result must not be confused with transport failure.
return response
services.append(node.create_service(IsPathValid, '/is_path_valid', path))
code, text = run(['--timeout', '8'])
CHECK(code == 0 and 'Nav2 就绪' in text, 'responsive service not accepted: '+text)
def startup(request, response):
starts.append(request.command)
state_id[0] = 3
response.success = True
return response
services.append(node.create_service(ManageLifecycleNodes, '/lifecycle_manager_nav2/manage_nodes', startup))
state_id[0] = 1
code, text = run(['--activate', '--timeout', '3'])
CHECK(code == 1 and not starts, 'STARTUP issued before lifecycle discovery was complete: '+text)
# Give each lifecycle server its actual node name, and create the manager's clients.
for service in services[2:5]:
node.destroy_service(service)
owners = [node]
for name in managed[1:]:
owner = rclpy.create_node(name)
extra_nodes.append(owner)
executor.add_node(owner)
owners.append(owner)
manager = rclpy.create_node('lifecycle_manager_nav2', start_parameter_services=False)
extra_nodes.append(manager)
executor.add_node(manager)
manager_clients = []
for name, owner in zip(managed, owners):
services.append(owner.create_service(GetState, f'/{name}/get_state', state))
services.append(owner.create_service(ChangeState, f'/{name}/change_state', lambda req, res: res))
manager_clients += [manager.create_client(GetState, f'/{name}/get_state'),
manager.create_client(ChangeState, f'/{name}/change_state')]
code, text = run(['--activate', '--timeout', '10'])
CHECK(code == 0 and starts == [ManageLifecycleNodes.Request.STARTUP] and 'Nav2 就绪' in text,
'gated STARTUP did not occur exactly once: '+text)
print('PASS: 15 checks including partial/stale discovery, startup gating, occupied domain, missing service, and readiness')
finally:
executor.shutdown()
for other in extra_nodes:
other.destroy_node()
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Exercise startup retry limits and process ownership without ROS or Gazebo."""
from pathlib import Path
import subprocess
import sys
import tempfile
from run_nav2 import stop_owned, supervise
def CHECK(condition, message):
if not condition:
raise RuntimeError(message)
def main():
with tempfile.TemporaryDirectory(prefix='nav2-supervisor-test-') as directory:
root = Path(directory)
navigation = root/'navigation.py'
navigation.write_text('''import signal,sys,time
signal.signal(signal.SIGINT, lambda *args: sys.exit(0))
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
time.sleep(1)
sys.exit(int(sys.argv[1]))
''')
checker = root/'checker.py'
checker.write_text('''import json,sys
from pathlib import Path
counter=Path(sys.argv[1]);mode=sys.argv[2]
n=int(counter.read_text())+1 if counter.exists() else 1
counter.write_text(str(n))
passed=mode=='ready' or mode=='recover' and n==2
retryable=mode in ('recover','exhaust')
Path(sys.argv[sys.argv.index('--result')+1]).write_text(json.dumps({'passed':passed,'retryable':retryable}))
sys.exit(0 if passed else 1)
''')
unrelated = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'],
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for mode, expected_calls, nav_exit, expected_result in [
('recover', 2, 0, 0), ('exhaust', 3, 0, 1),
('unknown', 1, 0, 1), ('ready', 1, 1, 1)]:
counter = root/(mode+'.count')
result = supervise([sys.executable, str(navigation), str(nav_exit)],
[sys.executable, str(checker), str(counter), mode], 3, 2)
CHECK(result == expected_result and int(counter.read_text()) == expected_calls,
f'{mode}: wrong retry count/result')
CHECK(unrelated.poll() is None, 'unrelated process was stopped')
finally:
stop_owned(unrelated)
print('PASS: 5 supervisor checks (recovery, limit, unknown/active refusal, no retry after ready, process ownership)')
if __name__ == '__main__':
main()
+129 -8
View File
@@ -8,16 +8,61 @@ import signal
import subprocess
import time
import uuid
from collections import Counter
import rclpy
from rclpy.node import Node
from rclpy.parameter import Parameter
from lifecycle_msgs.srv import GetState
from tf2_msgs.msg import TFMessage
from nav2_msgs.srv import IsPathValid
from rcl_interfaces.srv import GetParameters
from std_srvs.srv import Trigger
from rclpy.utilities import get_rmw_implementation_identifier
from nav2_startup import path_probe_request
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
'bt_navigator', 'behavior_server', 'waypoint_follower', 'velocity_smoother',
'collision_monitor']
'collision_monitor', 'route_server', 'docking_server', 'following_server']
ENV_KEYS = ['RMW_IMPLEMENTATION', 'ROS_DOMAIN_ID', 'FASTDDS_BUILTIN_TRANSPORTS',
'FASTDDS_DEFAULT_PROFILES_FILE', 'FASTRTPS_DEFAULT_PROFILES_FILE',
'RMW_FASTRTPS_USE_QOS_FROM_XML', 'ROS_LOCALHOST_ONLY',
'ROS_AUTOMATIC_DISCOVERY_RANGE', 'ROS_STATIC_PEERS', 'ROS_DISCOVERY_SERVER']
def process_environment(root_pid):
"""Only inspect this launch's descendants, and only middleware environment keys."""
parents = {}
for path in Path('/proc').glob('[0-9]*/status'):
try:
parent = next(line.split()[1] for line in path.read_text().splitlines()
if line.startswith('PPid:'))
parents[int(path.parent.name)] = int(parent)
except (OSError, StopIteration, ValueError):
continue
owned = {root_pid}
while True:
expanded = owned | {pid for pid, parent in parents.items() if parent in owned}
if expanded == owned:
break
owned = expanded
result = []
for pid in sorted(owned):
try:
base = Path('/proc')/str(pid)
env = dict(item.split('=', 1) for item in
(base/'environ').read_bytes().decode(errors='replace').split('\0') if '=' in item)
command = (base/'cmdline').read_bytes().decode(errors='replace').split('\0')
# Do not record full robot descriptions or unrelated environment variables.
result.append({'pid': pid, 'executable': command[:2],
'rmw_libraries': sorted({line.rsplit('/', 1)[-1] for line in
(base/'maps').read_text().splitlines()
if '/librmw_' in line and '.so' in line}),
'environment': {key: env.get(key) for key in ENV_KEYS}})
except OSError:
continue
return result
def main():
@@ -25,13 +70,17 @@ def main():
parser.add_argument('--map', type=Path, required=True)
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
parser.add_argument('--timeout', type=float, default=420.0,
help='whole-stack validation deadline, including up to three startup attempts')
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
args = parser.parse_args()
if not args.map.is_file():
parser.error('map missing')
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',
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]
@@ -42,6 +91,7 @@ def main():
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
log = open(args.output/'stack.log', 'w', encoding='utf8')
started = time.monotonic()
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
rclpy.init()
@@ -62,9 +112,21 @@ def main():
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
path_client = node.create_client(IsPathValid, '/is_path_valid')
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
states = {}
processes = []
rviz = None
result = {}
try:
deadline = time.monotonic()+120
if args.rviz:
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
'-p', 'use_sim_time:=true'],
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
deadline = time.monotonic()+args.timeout
last_check = 0.0
stable_since = None
manager_completed = False
@@ -75,13 +137,22 @@ def main():
if time.monotonic()-last_check < 0.5:
continue
last_check = time.monotonic()
if not processes and time.monotonic()-started > 8:
processes = process_environment(process.pid)
states = {}
pending = {}
for name, client in clients.items():
if not client.service_is_ready():
continue
future = client.call_async(GetState.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=1)
pending[name] = client.call_async(GetState.Request())
poll_end = time.monotonic()+1
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
rclpy.spin_once(node, timeout_sec=0.02)
for name, future in pending.items():
if future.done() and future.result():
states[name] = future.result().current_state.id
else:
clients[name].remove_pending_request(future)
log_path = args.output/'stack.log'
text = log_path.read_text(errors='replace') if log_path.exists() else ''
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
@@ -93,16 +164,59 @@ def main():
break
else:
stable_since = None
processes = process_environment(process.pid)
names = sorted(set(node.get_node_names()))
result = {'launcher': args.launcher, 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
path_ready = path_client.wait_for_service(timeout_sec=2)
path_response = None
if path_ready:
future = path_client.call_async(path_probe_request())
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
if future.done() and future.result() is not None:
path_response = str(future.result())
manager_active = False
if active_client.wait_for_service(timeout_sec=1):
future = active_client.call_async(Trigger.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
manager_active = bool(future.done() and future.result() and future.result().success)
managed_nodes = []
if parameter_client.wait_for_service(timeout_sec=1):
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
if future.done() and future.result() and future.result().values:
managed_nodes = list(future.result().values[0].string_array_value)
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
'node_counts': dict(Counter(node.get_node_names())),
'services': dict(node.get_service_names_and_types()),
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
'manager_active': manager_active, 'managed_nodes': managed_nodes,
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
result['passed'] = (manager_completed and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
result['passed'] = (manager_completed and manager_active and path_response is not None
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
and counts['map_to_base_link'] == 0)
(args.output/'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps(result, indent=2), flush=True)
if args.goal and result['passed']:
goal = subprocess.run([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200)
(args.output/'goal.log').write_text(goal.stdout)
result['goal_exit_code'] = goal.returncode
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout
result['passed'] = result['passed'] and goal.returncode == 0 and result['goal_succeeded']
(args.output/'result.json').write_text(json.dumps(result, indent=2))
print(json.dumps({k: v for k, v in result.items() if k not in
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
if not result['passed']:
raise RuntimeError('stack integration validation failed')
except Exception as error:
result.update(passed=False, error=str(error))
(args.output/'result.json').write_text(json.dumps(result, indent=2))
raise
finally:
_ = subscription
if process.poll() is None:
@@ -112,6 +226,13 @@ def main():
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
if rviz is not None:
os.killpg(rviz.pid, signal.SIGINT)
try:
rviz.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(rviz.pid, signal.SIGKILL)
rviz.wait()
if log:
log.close()
node.destroy_node()