完善双雷达仿真与自动上坡任务,更新使用文档

加入下置 MID360 前向补盲与双雷达融合,修复北侧走廊导航、坐标适配和数据时效处理。

实现接近坡脚、姿态辅助上坡与平台停车任务,增加独立快模式、命令仲裁及失效停车保护,保留测试与分阶段验收记录。

同步实车尺寸及雷达安装参数,调整 Gazebo 红方默认视角,完善根目录 README、仿真使用和实车迁移说明。
This commit is contained in:
2026-11-12 16:42:07 +08:00
parent cac93cae11
commit 6f1d837b46
95 changed files with 13667 additions and 244 deletions
+24 -1
View File
@@ -24,6 +24,14 @@ RoboCon 2027 赛季 BR 机器人的上位机代码。仓库里有**四套**定
复用方案 A 的原 Point-LIO、SCAN 和闭环控制器,支持全向横移;不是新增一套导航算法。
已有真值导航、MID360/IMU 估计导航和两侧指定坡道入口,含仿真时间、失效停车与独立物理验收。
新增下 MID360 的平地补盲模式使用 `scan_lio.launch.py dual_lidar:=true`;安装位置、前半圈裁剪、
验收路线及斜侧向低障碍的限制见 [双 MID360 说明](sim_ws/docs/DUAL_MID360.md)。
双雷达指定坡道的独立入口、三维路径及验收范围见 [双雷达坡道说明](sim_ws/docs/DUAL_TERRAIN.md)。
自动执行默认起点接近坡脚、专用控制上坡并停在平台的任务入口,见 [分段上坡任务](sim_ws/docs/RAMP_MISSION.md)。
其中 `profile:=fast` 是独立的 20 秒目标仿真配置;理想、轻度噪声两次完整路线分别为 **19.42 / 19.46 秒仿真时间**,
计时从初始化后任务开始到整车上平台并停稳确认完成,不含 Gazebo 加载与定位初始化。
默认模式及实车入口保持原配置,使用前请阅读文档中的减速区和验收边界;上述结果不代表实车成绩或每次运行的保证。
**第一次使用先读 [仿真使用与实车迁移指南](sim_ws/docs/USER_GUIDE.md)**,包括手动发目标、
带窗口自动测试、RViz、关闭重启和实车分阶段接入。以下命令在仓库根目录执行。
@@ -38,8 +46,22 @@ export GAZEBO_MASTER_URI=http://127.0.0.1:11355
ros2 launch br_sim_bringup scan_lio.launch.py
```
Gazebo 默认从红方(世界坐标 +Y)外侧上方俯看红方半场,仍可用鼠标调整视角。
上述手动入口默认单雷达,添加 `dual_lidar:=true` 启用双雷达补盲。
若要自动从默认起点行驶到北侧坡脚、上坡并停在平台,在相同环境下选择下面**其中一条**:
本入口自带双雷达、Gazebo 和 RViz,初始化完成后自动行驶,无需再发目标。
**先关闭其他仿真入口,等待启动终端退出;各入口不能同时运行。**
```bash
# 标准模式
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true
# 快模式:已知北侧路线的 20 秒目标仿真配置
ros2 launch br_sim_bringup ramp_mission.launch.py profile:=fast autostart:=true
```
若希望脚本自动发目标、验证路线,在相同环境下改用以下命令。
**先关闭手动 launch,等待启动终端完全退出;两种方式互斥。**
**先关闭其他 launch,等待启动终端完全退出。**
```bash
/usr/bin/python3 sim_ws/tools/check_lio_navigation.py --gui \
@@ -68,6 +90,7 @@ ros2 launch br_sim_bringup scan_lio.launch.py
| 跑方案 C,或看它的评估现状 | [`sru_ws/docs/USAGE.md`](sru_ws/docs/USAGE.md)、[`SOLUTION_C_ASSESSMENT.md`](sru_ws/docs/SOLUTION_C_ASSESSMENT.md) |
| 跑方案 D(建图 / 定位导航 / 行为树) | [`nav2_ws/README.md`](nav2_ws/README.md) |
| 在笔记本测试原导航程序 | [`sim_ws/README.md`](sim_ws/README.md) |
| 从起点自动上坡停车,或运行 20 秒目标快模式 | [分段上坡任务](sim_ws/docs/RAMP_MISSION.md) |
| 学习仿真操作,并把开发结果迁移到实车 | [使用与迁移指南](sim_ws/docs/USER_GUIDE.md) |
| 知道哪些东西不入库 | [`.gitignore`](.gitignore) |
@@ -13,6 +13,7 @@
#include <sensor_msgs/msg/imu.hpp>
#include "time_batching.h"
#include "sensor_timestamp.h"
using namespace std;
using namespace Eigen;
@@ -205,10 +206,7 @@ inline double get_time_sec(const builtin_interfaces::msg::Time & time)
inline rclcpp::Time get_ros_time(double timestamp)
{
int32_t sec = std::floor(timestamp);
auto nanosec_d = (timestamp - std::floor(timestamp)) * 1e9;
uint32_t nanosec = nanosec_d;
return rclcpp::Time(sec, nanosec);
return rclcpp::Time(point_lio::rounded_sensor_time_ns(timestamp), RCL_ROS_TIME);
}
#endif
@@ -9,7 +9,7 @@ namespace point_lio
class SensorTimeRateLimiter
{
public:
bool should_publish(double sensor_time, double frequency_hz)
bool should_publish(double sensor_time, double frequency_hz, bool scan_end = false)
{
if (!std::isfinite(sensor_time) || !std::isfinite(frequency_hz) || frequency_hz <= 0.0) {
return false;
@@ -23,7 +23,8 @@ public:
constexpr double kTimeEpsilon = 1.0e-9;
const double publish_period = 1.0 / frequency_hz;
if (sensor_time - last_publish_sensor_time_ + kTimeEpsilon < publish_period) {
if (sensor_time == last_publish_sensor_time_ ||
(!scan_end && sensor_time - last_publish_sensor_time_ + kTimeEpsilon < publish_period)) {
return false;
}
@@ -0,0 +1,17 @@
#pragma once
#include <cmath>
#include <cstdint>
namespace point_lio
{
// Convert the represented sensor seconds to the nearest ROS nanosecond.
// Truncating the fractional part can lose 1 ns at an exact scan endpoint,
// making a downstream strict pose bracket wait for the next complete scan.
inline std::int64_t rounded_sensor_time_ns(double timestamp)
{
const auto seconds = static_cast<std::int64_t>(std::floor(timestamp));
const auto fraction = std::llround((timestamp - std::floor(timestamp)) * 1e9);
return seconds * INT64_C(1000000000) + fraction;
}
} // namespace point_lio
@@ -43,6 +43,7 @@ const float MOV_THRESHOLD = 1.5f;
string root_dir = ROOT_DIR;
bool init_map = false, flg_first_scan = true;
static bool publish_scan_end_odom = false;
bool flg_reset = false, flg_exit = false;
@@ -632,12 +633,12 @@ template <typename T> void set_posestamp(T & out)
// 发布里程计话题
void publish_odometry(const rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr & pubOdomAftMapped,
std::shared_ptr<tf2_ros::TransformBroadcaster> & tf_br)
std::shared_ptr<tf2_ros::TransformBroadcaster> & tf_br, bool scan_end = false)
{
static point_lio::SensorTimeRateLimiter odom_rate_limiter;
const double odom_sensor_time =
publish_odometry_without_downsample ? time_current : lidar_end_time;
if (!odom_rate_limiter.should_publish(odom_sensor_time, orig_odom_freq)) {
if (!odom_rate_limiter.should_publish(odom_sensor_time, orig_odom_freq, scan_end)) {
return;
}
@@ -873,6 +874,8 @@ private:
icp_client_ = create_client<std_srvs::srv::Trigger>("/gicp_recall");
readParameters(*this);
publish_scan_end_odom = declare_parameter<bool>("odometry.publish_scan_end", false);
RCLCPP_INFO(get_logger(), "Scan-end estimated odometry publication: %s", publish_scan_end_odom ? "enabled" : "disabled");
if (blind_center_enable && blind_center.size() == 3U) {
p_pre->setBlindCenter(blind_center[0], blind_center[1], blind_center[2]);
RCLCPP_INFO(get_logger(), "[Point-LIO] Blind center enabled: [%.3f, %.3f, %.3f]",
@@ -1751,6 +1754,10 @@ void LaserMappingNode::processingLoop()
/******* Publish odometry downsample *******/
if (!publish_odometry_without_downsample) {
publish_odometry(pub_odom_aft_mapped_, tf_broadcaster_);
} else if (publish_scan_end_odom) {
// Publish the actual final processed filter state at time_current.
// Never relabel an earlier state with lidar_end_time or extrapolate.
publish_odometry(pub_odom_aft_mapped_, tf_broadcaster_, true);
}
/*** add the feature points to map ***/
@@ -41,4 +41,10 @@ ament_export_targets(export_plan_env HAS_LIBRARY_TARGET)
ament_export_dependencies(
cv_bridge Eigen3 geometry_msgs message_filters nav_msgs pcl_conversions
rclcpp sensor_msgs tf2 tf2_ros visualization_msgs)
if(BUILD_TESTING)
find_package(ament_cmake_gtest REQUIRED)
ament_add_gtest(test_cloud_ray_origins test/test_cloud_ray_origins.cpp)
target_link_libraries(test_cloud_ray_origins plan_env)
ament_target_dependencies(test_cloud_ray_origins rclcpp sensor_msgs nav_msgs)
endif()
ament_package()
@@ -0,0 +1,48 @@
#ifndef PLAN_ENV_CLOUD_RAY_ORIGINS_H
#define PLAN_ENV_CLOUD_RAY_ORIGINS_H
#include <array>
#include <cstdint>
#include <cstring>
#include <stdexcept>
#include <sensor_msgs/msg/point_cloud2.hpp>
namespace plan_env {
// Optional strict schema for multi-lidar WORLD clouds. The original one-origin
// path never constructs this reader and retains its existing contract.
class CloudRayOrigins {
public:
explicit CloudRayOrigins(const sensor_msgs::msg::PointCloud2 & cloud) : cloud_(cloud) {
if (!cloud.point_step || uint64_t(cloud.width)*cloud.point_step>cloud.row_step ||
uint64_t(cloud.row_step)*cloud.height>cloud.data.size())
throw std::invalid_argument("truncated cloud layout");
const char * names[]={"origin_x","origin_y","origin_z"};
for (unsigned axis=0;axis<3;++axis) {
unsigned found=0;
for (const auto & field:cloud.fields) if (field.name==names[axis]) {
if (field.datatype!=sensor_msgs::msg::PointField::FLOAT32 || field.count!=1 ||
uint64_t(field.offset)+sizeof(float)>cloud.point_step)
throw std::invalid_argument("invalid per-point origin field");
offsets_[axis]=field.offset;++found;
}
if (found!=1) throw std::invalid_argument("missing or duplicated per-point origin field");
}
}
std::array<float,3> at(std::size_t row,std::size_t column) const {
if (row>=cloud_.height || column>=cloud_.width) throw std::out_of_range("origin point index");
std::array<float,3> values;
const uint16_t one=1;const bool host_big=*reinterpret_cast<const uint8_t *>(&one)==0;
for (unsigned axis=0;axis<3;++axis) {
uint32_t bits;
std::memcpy(&bits,cloud_.data.data()+row*cloud_.row_step+column*cloud_.point_step+offsets_[axis],4);
if (cloud_.is_bigendian!=host_big)
bits=((bits&0xff)<<24)|((bits&0xff00)<<8)|((bits>>8)&0xff00)|(bits>>24);
std::memcpy(&values[axis],&bits,4);
}
return values;
}
private:
const sensor_msgs::msg::PointCloud2 & cloud_;
std::array<uint32_t,3> offsets_{};
};
} // namespace plan_env
#endif
@@ -95,6 +95,7 @@ struct MappingParameters {
/* mapping sensor input */
string sensor_type_;
bool cloud_is_world_;
bool cloud_has_ray_origins_{false};
bool need_extrinsic_;
Eigen::Matrix4d lidar_extrinsic_;
Eigen::Matrix4d depth_extrinsic_;
@@ -133,6 +134,7 @@ struct MappingData {
// depth image projected point cloud
vector<Eigen::Vector3d> proj_points_;
vector<Eigen::Vector3d> proj_ray_origins_;
int proj_points_cnt;
// flag buffers for speeding up raycasting
@@ -194,6 +196,8 @@ public:
void setFootprintHeading(double yaw);
int getRectangleOccupancy(Eigen::Vector3d pos, double yaw, double extra_margin = 0.0);
bool rotationIsFree(Eigen::Vector3d pos, double from, double to, double extra_margin = 0.0);
// 0 = complete sweep free, 1 = observed collision, -1 = incomplete map.
int rotationOccupancy(Eigen::Vector3d pos, double from, double to, double extra_margin = 0.0);
bool rectangleBufferInMap(Eigen::Vector3d pos);
void publishMap();
+1
View File
@@ -17,5 +17,6 @@
<depend>tf2</depend>
<depend>tf2_ros</depend>
<depend>visualization_msgs</depend>
<test_depend>ament_cmake_gtest</test_depend>
<export><build_type>ament_cmake</build_type></export>
</package>
+75 -15
View File
@@ -4,6 +4,8 @@
#include <unordered_set>
#include <plan_env/rectangular_footprint.h>
#include <limits>
#include <memory>
#include <plan_env/cloud_ray_origins.h>
#include <string>
#include <geometry_msgs/msg/transform_stamped.hpp>
@@ -79,6 +81,11 @@ void GridMap::initMap(rclcpp::Node *node)
load_parameter(node_, "grid_map.sensor_type", mp_.sensor_type_, string("lidar"));
load_parameter(node_, "grid_map.cloud_is_world", mp_.cloud_is_world_, true);
load_parameter(node_, "grid_map.cloud_has_ray_origins", mp_.cloud_has_ray_origins_, false);
bool reliable_cloud = false;
load_parameter(node_, "grid_map.cloud_reliable", reliable_cloud, false);
if (mp_.cloud_has_ray_origins_ && (!mp_.cloud_is_world_ || mp_.sensor_type_!="lidar"))
throw std::invalid_argument("per-point ray origins require world-frame lidar clouds");
load_parameter(node_, "grid_map.need_extrinsic", mp_.need_extrinsic_, true);
mp_.lidar_extrinsic_ <<
@@ -167,8 +174,10 @@ void GridMap::initMap(rclcpp::Node *node)
lidar_pose_sub_ = node_->create_subscription<nav_msgs::msg::Odometry>(
"sensor_pose", rclcpp::SensorDataQoS(),
std::bind(&GridMap::sensorPoseCallback, this, std::placeholders::_1));
auto cloud_qos = rclcpp::SensorDataQoS();
if (reliable_cloud) cloud_qos.keep_last(1).reliable();
cloud_sub_ = node_->create_subscription<sensor_msgs::msg::PointCloud2>(
"cloud", rclcpp::SensorDataQoS(),
"cloud", cloud_qos,
std::bind(&GridMap::cloudCallback, this, std::placeholders::_1));
}
@@ -317,16 +326,26 @@ int GridMap::getRectangleOccupancy(Eigen::Vector3d pos, double yaw, double extra
bool GridMap::rotationIsFree(Eigen::Vector3d pos, double from, double to, double extra_margin)
{
if (!std::isfinite(from) || !std::isfinite(to)) return false;
return rotationOccupancy(pos, from, to, extra_margin) == 0;
}
int GridMap::rotationOccupancy(Eigen::Vector3d pos, double from, double to, double extra_margin)
{
if (!pos.allFinite() || !std::isfinite(from) || !std::isfinite(to) ||
!std::isfinite(extra_margin) || extra_margin < 0) return -1;
const double angle = footprint::angleDifference(to, from);
const int steps = std::max(1, static_cast<int>(std::ceil(std::abs(angle)/0.05)));
const double radius = std::hypot(0.5*mp_.footprint_length_+mp_.footprint_margin_+extra_margin,
0.5*mp_.footprint_width_+mp_.footprint_margin_+extra_margin);
// Nearest sampled angle is at most half a step away. Cover all intervening corners.
const double pad = footprint::angularPadding(radius, std::abs(angle)/(2*steps));
for (int i = 0; i <= steps; ++i)
if (getRectangleOccupancy(pos, from+angle*i/steps, extra_margin+pad) != 0) return false;
return true;
int result = 0;
for (int i = 0; i <= steps; ++i) {
const int occupied = getRectangleOccupancy(pos, from+angle*i/steps, extra_margin+pad);
if (occupied == 1) return 1; // Known collision wins over incomplete samples.
if (occupied != 0) result = -1;
}
return result;
}
void GridMap::resetAllMapData()
@@ -681,6 +700,12 @@ void GridMap::raycastProcess()
updateSlidingMap(md_.ray_pos_);
md_.raycast_num_ += 1;
// Legacy flags are signed-byte tags. Keep the opt-in multi-origin cache
// within 1..127 and clear on reuse, rather than truncating the int counter.
const bool multi_origin_update=mp_.cloud_has_ray_origins_ && md_.use_cloud_update_;
const char multi_origin_tag=static_cast<char>(1+md_.raycast_num_%127);
if (multi_origin_update && md_.raycast_num_%127==0)
std::fill(md_.flag_traverse_.begin(),md_.flag_traverse_.end(),0);
int vox_idx;
double length;
@@ -701,27 +726,29 @@ void GridMap::raycastProcess()
for (int i = 0; i < md_.proj_points_cnt; ++i)
{
pt_w = md_.proj_points_[i];
const bool per_point_origin = mp_.cloud_has_ray_origins_ && md_.use_cloud_update_;
const Eigen::Vector3d ray_origin = per_point_origin ? md_.proj_ray_origins_.at(i) : md_.ray_pos_;
// set flag for projected point
if (!isInMap(pt_w))
{
pt_w = closetPointInMap(pt_w, md_.ray_pos_);
pt_w = closetPointInMap(pt_w, ray_origin);
length = (pt_w - md_.ray_pos_).norm();
length = (pt_w - ray_origin).norm();
if (length > mp_.max_ray_length_)
{
pt_w = (pt_w - md_.ray_pos_) / length * mp_.max_ray_length_ + md_.ray_pos_;
pt_w = (pt_w - ray_origin) / length * mp_.max_ray_length_ + ray_origin;
}
vox_idx = setCacheOccupancy(pt_w, 0);
}
else
{
length = (pt_w - md_.ray_pos_).norm();
length = (pt_w - ray_origin).norm();
if (length > mp_.max_ray_length_)
{
pt_w = (pt_w - md_.ray_pos_) / length * mp_.max_ray_length_ + md_.ray_pos_;
pt_w = (pt_w - ray_origin) / length * mp_.max_ray_length_ + ray_origin;
vox_idx = setCacheOccupancy(pt_w, 0);
}
else
@@ -738,11 +765,13 @@ void GridMap::raycastProcess()
min_y = min(min_y, pt_w(1));
min_z = min(min_z, pt_w(2));
// raycasting between ray origin and point
max_x = max(max_x, ray_origin.x());max_y = max(max_y, ray_origin.y());max_z = max(max_z, ray_origin.z());
min_x = min(min_x, ray_origin.x());min_y = min(min_y, ray_origin.y());min_z = min(min_z, ray_origin.z());
// raycasting between each physical optical origin and its endpoint
if (vox_idx != INVALID_IDX)
{
if (md_.flag_rayend_[vox_idx] == md_.raycast_num_)
if (!per_point_origin && md_.flag_rayend_[vox_idx] == md_.raycast_num_)
{
continue;
}
@@ -752,13 +781,25 @@ void GridMap::raycastProcess()
}
}
raycaster.setInput(pt_w / mp_.resolution_, md_.ray_pos_ / mp_.resolution_);
raycaster.setInput(pt_w / mp_.resolution_, ray_origin / mp_.resolution_);
while (raycaster.step(ray_pt))
{
Eigen::Vector3d tmp = (ray_pt + half) * mp_.resolution_;
length = (tmp - md_.ray_pos_).norm();
length = (tmp - ray_origin).norm();
// Different optical origins can share a traversed voxel and then diverge.
// Do not terminate those rays at the shared voxel; count each free voxel
// once per update so dense dual scans cannot overweight free evidence.
if (per_point_origin) {
Eigen::Vector3i index;posToIndex(tmp,index);
if (!isInMap(index)) continue;
const int address=toAddress(index);
if (md_.flag_traverse_[address]==multi_origin_tag) continue;
md_.flag_traverse_[address]=multi_origin_tag;
setCacheOccupancy(tmp,0);
continue;
}
vox_idx = setCacheOccupancy(tmp, 0);
if (vox_idx != INVALID_IDX)
@@ -1014,6 +1055,17 @@ void GridMap::cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr
return;
}
std::unique_ptr<plan_env::CloudRayOrigins> origins;
if (mp_.cloud_has_ray_origins_) {
try {
if (img->header.frame_id!=mp_.frame_id_) throw std::invalid_argument("wrong multi-lidar cloud frame");
origins=std::make_unique<plan_env::CloudRayOrigins>(*img);
} catch (const std::exception & error) {
RCLCPP_ERROR_THROTTLE(node_->get_logger(), *node_->get_clock(), 1000,
"[GridMap] rejected multi-lidar cloud: %s",error.what());
return; // Never silently use the upper lidar origin for lower points.
}
}
pcl::PointCloud<pcl::PointXYZ> latest_cloud;
pcl::fromROSMsg(*img, latest_cloud);
@@ -1030,6 +1082,7 @@ void GridMap::cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr
updateSlidingMap(ray_pos);
md_.proj_points_cnt = 0;
md_.proj_ray_origins_.clear();
for (size_t i = 0; i < latest_cloud.points.size(); ++i)
{
@@ -1047,7 +1100,13 @@ void GridMap::cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr
const Eigen::Vector3d pt_sensor(pt.x, pt.y, pt.z);
pt_world = sensor_r * pt_sensor + ray_pos;
}
const Eigen::Vector3d devi = pt_world - ray_pos;
Eigen::Vector3d point_origin=ray_pos;
if (origins) {
const auto raw=origins->at(i/img->width,i%img->width);
point_origin=Eigen::Vector3d(raw[0],raw[1],raw[2]);
if (!point_origin.allFinite() || !isInMap(point_origin)) continue;
}
const Eigen::Vector3d devi = pt_world - point_origin;
const double ray_length = devi.norm();
const bool in_local_range =
fabs(devi(0)) <= mp_.local_update_range_(0) && fabs(devi(1)) <= mp_.local_update_range_(1) &&
@@ -1060,6 +1119,7 @@ void GridMap::cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr
else
md_.proj_points_[md_.proj_points_cnt] = pt_world;
if (origins) md_.proj_ray_origins_.push_back(point_origin);
md_.proj_points_cnt++;
}
@@ -0,0 +1,91 @@
#include <gtest/gtest.h>
#include <chrono>
#include <thread>
#include <plan_env/cloud_ray_origins.h>
#include <plan_env/grid_map.h>
sensor_msgs::msg::PointCloud2 cloud(bool big=false) {
sensor_msgs::msg::PointCloud2 msg;msg.header.frame_id="world";
msg.height=1;msg.width=2;msg.point_step=24;msg.row_step=48;msg.is_bigendian=big;msg.data.resize(48);
const char * names[]={"x","y","z","origin_x","origin_y","origin_z"};
for (unsigned i=0;i<6;++i) {
sensor_msgs::msg::PointField field;field.name=names[i];field.offset=i*4;field.datatype=field.FLOAT32;field.count=1;msg.fields.push_back(field);
}
float values[]={2.025f,.025f,.225f,.025f,.025f,.225f, 2.025f,.025f,.225f,.025f,.025f,.825f};
for (unsigned i=0;i<12;++i) {
uint32_t bits;std::memcpy(&bits,&values[i],4);
if(big)bits=((bits&0xff)<<24)|((bits&0xff00)<<8)|((bits>>8)&0xff00)|(bits>>24);
std::memcpy(msg.data.data()+i*4,&bits,4);
}
return msg;
}
TEST(CloudRayOrigins, ReadsLittleAndBigEndianWithDifferentOrigins) {
for (bool big:{false,true}) {
auto msg=cloud(big);plan_env::CloudRayOrigins read(msg);
EXPECT_NEAR(read.at(0,0)[2],.225,1e-7);EXPECT_NEAR(read.at(0,1)[2],.825,1e-7);
}
}
TEST(CloudRayOrigins, RejectsMissingTruncatedAndDuplicatedFields) {
auto msg=cloud();msg.fields.pop_back();EXPECT_THROW(plan_env::CloudRayOrigins read(msg),std::invalid_argument);
msg=cloud();msg.data.pop_back();EXPECT_THROW(plan_env::CloudRayOrigins read(msg),std::invalid_argument);
msg=cloud();msg.fields.push_back(msg.fields.back());EXPECT_THROW(plan_env::CloudRayOrigins read(msg),std::invalid_argument);
msg=cloud();msg.fields.back().offset=24;EXPECT_THROW(plan_env::CloudRayOrigins read(msg),std::invalid_argument);
}
class RayMap : public ::testing::Test {
protected:
virtual bool multiOrigins() const {return true;}
void SetUp() override {
if(!rclcpp::ok()){int argc=0;rclcpp::init(argc,nullptr);}
rclcpp::NodeOptions options;
options.parameter_overrides({
{"grid_map.cloud_has_ray_origins",multiOrigins()},{"grid_map.need_extrinsic",false},
{"grid_map.resolution",.05},{"grid_map.sliding_map_size_x",6.0},{"grid_map.sliding_map_size_y",6.0},
{"grid_map.sliding_map_size_z",2.0},{"grid_map.ground_height",-1.0},{"grid_map.skip_pixel",2},
{"grid_map.map_sliding_en",false},{"grid_map.obstacles_inflation_z_up",0.0},
{"grid_map.obstacles_inflation_z_down",0.0},{"grid_map.double_cylinder_radius",0.0},
{"grid_map.max_ray_length",5.0},{"grid_map.p_hit",.85},{"grid_map.p_miss",.35},
{"grid_map.p_min",.12},{"grid_map.p_max",.97},{"grid_map.p_occ",.80}});
node=std::make_shared<rclcpp::Node>("multi_origin_grid_test","/multi_origin_test",options);map.initMap(node.get());
pose=node->create_publisher<nav_msgs::msg::Odometry>("sensor_pose",10);
points=node->create_publisher<sensor_msgs::msg::PointCloud2>("cloud",10);
nav_msgs::msg::Odometry odom;odom.header.frame_id="world";odom.pose.pose.orientation.w=1.;
odom.pose.pose.position.x=.025;odom.pose.pose.position.y=.025;odom.pose.pose.position.z=.825;
for(int i=0;i<30;++i){pose->publish(odom);rclcpp::spin_some(node);std::this_thread::sleep_for(std::chrono::milliseconds(10));}
}
void run(sensor_msgs::msg::PointCloud2 msg) {
for(int i=0;i<40;++i){points->publish(msg);rclcpp::spin_some(node);std::this_thread::sleep_for(std::chrono::milliseconds(10));}
rclcpp::spin_some(node);
}
std::shared_ptr<rclcpp::Node> node;GridMap map;
rclcpp::Publisher<nav_msgs::msg::Odometry>::SharedPtr pose;
rclcpp::Publisher<sensor_msgs::msg::PointCloud2>::SharedPtr points;
};
TEST_F(RayMap, BothOriginsClearTheirOwnRaysToTheSameEndpoint) {
const Eigen::Vector3d lower(1.025,.025,.225),upper(1.025,.025,.525),endpoint(2.025,.025,.225);
map.setOccupied(lower);map.setOccupied(upper);
run(cloud());
EXPECT_EQ(map.getOccupancy(lower),0);EXPECT_EQ(map.getOccupancy(upper),0);
EXPECT_EQ(map.getOccupancy(endpoint),1);
}
TEST_F(RayMap, MissingOriginsCannotFallBackToUpperSensor) {
const Eigen::Vector3d upper(1.025,.025,.525),endpoint(2.025,.025,.225);
map.setOccupied(upper);auto msg=cloud();msg.fields.pop_back();run(msg);
EXPECT_EQ(map.getOccupancy(upper),1);EXPECT_EQ(map.getOccupancy(endpoint),0);
}
TEST_F(RayMap, EndpointOnlyPriorOccupiesWithoutClearingRayToSensor) {
const Eigen::Vector3d between(1.025,.025,.525),endpoint(2.025,.025,.225);
map.setOccupied(between);auto msg=cloud();
for (unsigned i=0;i<2;++i)
std::memcpy(msg.data.data()+i*24+12,msg.data.data()+i*24,12);
run(msg);
EXPECT_EQ(map.getOccupancy(between),1);EXPECT_EQ(map.getOccupancy(endpoint),1);
}
class SingleRayMap : public RayMap {protected: bool multiOrigins() const override {return false;}};
TEST_F(SingleRayMap, DefaultIgnoresOptionalOriginsAndKeepsSingleOriginBehavior) {
const Eigen::Vector3d lower(1.025,.025,.225),upper(1.025,.025,.525),endpoint(2.025,.025,.225);
map.setOccupied(lower);map.setOccupied(upper);run(cloud());
EXPECT_EQ(map.getOccupancy(lower),1);EXPECT_EQ(map.getOccupancy(upper),0);EXPECT_EQ(map.getOccupancy(endpoint),1);
}
@@ -88,6 +88,7 @@ if(BUILD_TESTING)
add_launch_test(test/test_waypoint_parameters.py TIMEOUT 30)
add_launch_test(test/test_controller_execution.py TIMEOUT 35)
add_launch_test(test/test_rectangle_controller.py TIMEOUT 35)
add_launch_test(test/test_controller_prediction.py TIMEOUT 25)
add_launch_test(test/test_rectangle_fsm.py TIMEOUT 35)
add_launch_test(test/test_rectangle_launch.py TIMEOUT 30)
add_launch_test(test/test_goal_execution_fsm.py TIMEOUT 35)
@@ -49,9 +49,15 @@ public:
goal_slow_gain_ = declare_parameter<double>("goal_slow_gain", 2.0);
goal_v_floor_ = declare_parameter<double>("goal_v_floor", 0.05);
kp_yaw_ = declare_parameter<double>("kp_yaw", 1.5);
state_prediction_limit_ = declare_parameter<double>("state_prediction_limit", 0.0);
goal_braking_acceleration_ = declare_parameter<double>("goal_braking_acceleration", 0.0);
if (!std::isfinite(state_prediction_limit_) || state_prediction_limit_ < 0 || state_prediction_limit_ > .2 ||
!std::isfinite(goal_braking_acceleration_) || goal_braking_acceleration_ < 0 || goal_braking_acceleration_ > 2.)
throw std::runtime_error("Invalid optional prediction/braking limits");
max_vx_ = declare_parameter<double>("max_vx", 0.75);
max_vy_ = declare_parameter<double>("max_vy", 0.35);
max_vyaw_ = std::min(declare_parameter<double>("max_vyaw", 1.0), kMaxVYawLimit);
const double yaw_limit = declare_parameter<bool>("extended_yaw_limit", false) ? 2.0 : kMaxVYawLimit;
max_vyaw_ = std::min(declare_parameter<double>("max_vyaw", 1.0), yaw_limit);
finish_dist_ = declare_parameter<double>("finish_dist", 0.15);
// 终点朝向对齐。SCAN 的规划器只吃位置(rvizGoalCallback -> waypointCallback
// 只读 pose.position),到点朝向由轨迹最后一段切向决定。
@@ -203,6 +209,8 @@ private:
}
odom_pos_ << msg->pose.pose.position.x, msg->pose.pose.position.y, msg->pose.pose.position.z;
odom_yaw_ = tf2::getYaw(msg->pose.pose.orientation);
odom_source_stamp_ = rclcpp::Time(msg->header.stamp);
odom_yaw_rate_ = msg->twist.twist.angular.z;
// 实测速度:body_odom 的 twist.linear 是 body 系,转到世界系供速度阻尼使用。
// 没有阻尼时指令 = 前馈 + kp_pos*误差,前馈占主导,车速一旦快于参考点就会
// 冲过头,过冲量约 vel_des/kp_pos(0.25 m/s、kp 0.5 时约 0.5 m)。
@@ -260,6 +268,19 @@ private:
return;
}
const auto current_time = now();
// Optional control-only constant-velocity prediction of a fresh measured
// state. Never republish/relabel odometry, and never extend its freshness.
Eigen::Vector3d control_position = odom_pos_;
double control_yaw = odom_yaw_;
if (state_prediction_limit_ > 0) {
const double source_age = (current_time-odom_source_stamp_).seconds();
if (source_age < 0 || source_age > state_prediction_limit_ ||
!odom_vel_world_.allFinite() || !std::isfinite(odom_yaw_rate_)) {
publishExecutionFrozen(true); publishStop(); last_update_time_=current_time; return;
}
control_position.head<2>() += odom_vel_world_*source_age;
control_yaw = normalizeAngle(odom_yaw_+odom_yaw_rate_*source_age);
}
double dt = (current_time - last_update_time_).seconds();
if (dt < 0.0 || dt > 0.2) dt = 0.0;
@@ -273,7 +294,7 @@ private:
}
const double t_eval = std::min(exec_time_, traj_duration_);
Eigen::Vector3d pos_des = traj_[0].evaluateDeBoorT(t_eval);
double yaw_error = normalizeAngle((locked ? status_.heading : estimateDesiredYaw(t_eval, pos_des)) - odom_yaw_);
double yaw_error = normalizeAngle((locked ? status_.heading : estimateDesiredYaw(t_eval, pos_des)) - control_yaw);
// 倒车模式:期望朝向与车头几乎相反(目标在正后方)时,全向底盘不必掉头 ——
// 保持车头、直接反向平移即可。本车满足三个前提:全向底盘(vx/vy/wz 独立)、
@@ -302,14 +323,14 @@ private:
// checked spline: do not create an unchecked shortcut to the task goal.
const bool final_window = !have_status_ || status_.is_final;
const Eigen::Vector3d vel_des = traj_[1].evaluateDeBoorT(exec_time_);
const Eigen::Vector2d pos_error(pos_des.x() - odom_pos_.x(), pos_des.y() - odom_pos_.y());
const Eigen::Vector2d pos_error(pos_des.x() - control_position.x(), pos_des.y() - control_position.y());
// 到**轨迹终点**的距离,用于两处:接近目标时的限速、以及到达判定。
Eigen::Vector3d end_pt = traj_[0].evaluateDeBoorT(traj_duration_);
if (have_status_ && final_window)
end_pt << status_.goal.x, status_.goal.y, status_.goal.z;
const double dist_to_goal =
std::hypot(end_pt.x() - odom_pos_.x(), end_pt.y() - odom_pos_.y());
std::hypot(end_pt.x() - control_position.x(), end_pt.y() - control_position.y());
// 位置死区:误差小于该值时不再做位置修正,只保留前馈与阻尼。
// 全向轮横移会打滑、响应滞后,终点附近几厘米的横向误差去追只会造成
@@ -329,14 +350,20 @@ private:
// 不用平方根刹车曲线:0.8 m/s² 下 8 cm 处仍有 0.45 m/s,等于不减速;
// 线性斜坡 gain=2 时 8 cm 处限到 0.16 m/s,才真能刹住。
// v_floor 保证末段仍有爬行速度,不会提前停死。
const double v_cap = std::max(goal_v_floor_, goal_slow_gain_ * std::max(dist_to_goal, 0.0));
double v_cap = std::max(goal_v_floor_, goal_slow_gain_ * std::max(dist_to_goal, 0.0));
if (goal_braking_acceleration_ > 0) {
// Leave .10 s of actuation/reaction distance in addition to prediction.
const double a=goal_braking_acceleration_, reaction=.10;
const double brake_cap=std::sqrt(a*a*reaction*reaction+2*a*dist_to_goal)-a*reaction;
v_cap=std::min(v_cap,std::max(goal_v_floor_,brake_cap));
}
const double cmd_norm = vel_cmd.norm();
if (cmd_norm > v_cap && cmd_norm > 1e-6)
vel_cmd *= v_cap / cmd_norm;
const Eigen::Vector2d vel_world = clampNorm(vel_cmd, std::max(max_vx_, max_vy_));
const double c = std::cos(odom_yaw_);
const double s = std::sin(odom_yaw_);
const double c = std::cos(control_yaw);
const double s = std::sin(control_yaw);
geometry_msgs::msg::Twist command;
command.linear.x = std::clamp(c * vel_world.x() + s * vel_world.y(), -max_vx_, max_vx_);
command.linear.y = std::clamp(-s * vel_world.x() + c * vel_world.y(), -max_vy_, max_vy_);
@@ -370,10 +397,19 @@ private:
{
// 位置已到位。若开启终点朝向对齐且朝向误差仍超容差,则原地转,不发线速度。
double yaw_err = 0.0;
double measured_yaw_err = 0.0;
if (final_window && align_to_goal_yaw_ && (locked ? status_.target_yaw_valid : has_goal_))
yaw_err = normalizeAngle((locked ? status_.target_yaw : goal_yaw_) - odom_yaw_);
{
yaw_err = normalizeAngle((locked ? status_.target_yaw : goal_yaw_) - control_yaw);
measured_yaw_err = normalizeAngle((locked ? status_.target_yaw : goal_yaw_) - odom_yaw_);
}
if (std::abs(yaw_err) > yaw_goal_tolerance_)
// Prediction may shape commands, but cannot certify a future arrival.
// Retain the safety grant until actual measured heading/rate settle.
const bool measured_alignment_pending = state_prediction_limit_ > 0 &&
final_window && align_to_goal_yaw_ &&
(std::abs(measured_yaw_err) > yaw_goal_tolerance_ || std::abs(odom_yaw_rate_) > .03);
if (std::abs(yaw_err) > yaw_goal_tolerance_ || measured_alignment_pending)
{
// 冻结 FSM 重规划:否则对齐途中来一条新轨迹会把 exec_time_ 打回 0,
// 变成"转一点、又开一段、再转"的来回摆动
@@ -397,7 +433,7 @@ private:
}
}
// Drift outside the arrival latch must never resume translation at a rotated heading.
if (locked && std::abs(normalizeAngle(status_.heading-odom_yaw_)) > status_.heading_tolerance) {
if (locked && std::abs(normalizeAngle(status_.heading-control_yaw)) > status_.heading_tolerance) {
command.linear.x = 0.0;
command.linear.y = 0.0;
}
@@ -433,6 +469,9 @@ private:
std::int64_t traj_id_{0};
Eigen::Vector3d odom_pos_{Eigen::Vector3d::Zero()};
double odom_yaw_{0.0};
double odom_yaw_rate_{0.0};
rclcpp::Time odom_source_stamp_{0,0,RCL_ROS_TIME};
double state_prediction_limit_{0.0}, goal_braking_acceleration_{0.0};
double exec_time_{0.0};
rclcpp::Time last_update_time_{0, 0, RCL_ROS_TIME};
double time_forward_, heading_error_threshold_, kp_pos_, kp_yaw_;
@@ -126,7 +126,7 @@ namespace scan_planner
PolynomialTraj gl_traj;
double dist = (start_pt - local_target_pt).norm();
double time = pow(pp_.max_vel_, 2) / pp_.max_acc_ > dist ? sqrt(dist / pp_.max_acc_) : (dist - pow(pp_.max_vel_, 2) / pp_.max_acc_) / pp_.max_vel_ + 2 * pp_.max_vel_ / pp_.max_acc_;
double time = pow(pp_.max_vel_, 2) / pp_.max_acc_ > dist ? 2 * sqrt(dist / pp_.max_acc_) : (dist - pow(pp_.max_vel_, 2) / pp_.max_acc_) / pp_.max_vel_ + 2 * pp_.max_vel_ / pp_.max_acc_;
if (!flag_randomPolyTraj)
{
@@ -157,8 +157,14 @@ namespace scan_planner
point_set.clear();
flag_too_far = false;
Eigen::Vector3d last_pt = gl_traj.evaluate(0);
for (t = 0; t < time; t += ts)
// Uniform samples must include the actual endpoint. The old t<time
// loop fixed a pre-endpoint acceleration into the final control
// points, sometimes above the limit: refinement could never fix it.
const int intervals = std::max(6, static_cast<int>(std::ceil(time / ts)));
ts = time / intervals;
for (int sample = 0; sample <= intervals; ++sample)
{
t = sample * ts;
Eigen::Vector3d pt = gl_traj.evaluate(t);
if ((last_pt - pt).norm() > pp_.ctrl_pt_dist * 1.5)
{
@@ -169,11 +175,10 @@ namespace scan_planner
point_set.push_back(pt);
}
} while (flag_too_far || point_set.size() < 7); // To make sure the initial path has enough points.
t -= ts;
start_end_derivatives.push_back(gl_traj.evaluateVel(0));
start_end_derivatives.push_back(local_target_vel);
start_end_derivatives.push_back(gl_traj.evaluateAcc(0));
start_end_derivatives.push_back(gl_traj.evaluateAcc(t));
start_end_derivatives.push_back(gl_traj.evaluateAcc(time));
}
else // Initial path generated from previous trajectory.
{
@@ -419,11 +419,15 @@ namespace scan_planner
if (target_yaw_valid_ && std::abs(std::atan2(std::sin(target_yaw_-map->footprintHeading()),
std::cos(target_yaw_-map->footprintHeading()))) > 1e-6 &&
map->isInMap(raw_goal_) &&
!map->rotationIsFree(raw_goal_, map->footprintHeading(), target_yaw_, goal_tolerance_)) {
!globalGoalMayRemainActive(map->rotationOccupancy(
raw_goal_, map->footprintHeading(), target_yaw_, goal_tolerance_))) {
RCLCPP_WARN_THROTTLE(node_->get_logger(), *node_->get_clock(), 1000,
"Requested terminal rotation is blocked; original goal retained");
return false;
}
// A sweep extending beyond the sliding map is a distant intention, not
// permission to turn. Local endpoints and terminal rotation grants still
// require explicitly free, fully in-map geometry via rotationIsFree().
}
const int occ = planner_manager_->grid_map_->getInflateOccupancy(raw_goal_, getOdomYaw());
// -1 retains a distant task intention, not a claim that the goal is safe.
@@ -0,0 +1,89 @@
"""Optional control prediction must use source age, retain stopping and braking."""
import math
import time
import unittest
import launch
import launch_ros.actions
import launch_testing.actions
import pytest
import rclpy
from geometry_msgs.msg import Point, Twist
from nav_msgs.msg import Odometry
from rclpy.qos import DurabilityPolicy, QoSProfile
from rclpy.time import Time
from scan_planner_msgs.msg import Bspline, TrajectoryStatus
from std_msgs.msg import Int64
@pytest.mark.launch_test
def generate_test_description():
return launch.LaunchDescription([
launch_ros.actions.Node(package='scan_planner', executable='closed_loop_controller',
namespace='prediction_test', parameters=[{
'require_trajectory_status': True, 'require_locked_heading': True,
'state_prediction_limit': .2, 'goal_braking_acceleration': 1.8,
'kp_pos': 4., 'kd_vel': 0., 'max_vx': 2., 'max_vy': 2.,
'goal_slow_gain': 10., 'finish_dist': .01,
'align_to_goal_yaw': True, 'yaw_goal_tolerance': .01,
}]), launch_testing.actions.ReadyToTest()])
class TestPrediction(unittest.TestCase):
def test_source_age_prediction_and_braking(self):
rclpy.init()
node=rclpy.create_node('prediction_driver',namespace='prediction_test')
qos=QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL)
grants=node.create_publisher(TrajectoryStatus,'planning/trajectory_status',qos)
odoms=node.create_publisher(Odometry,'body_pose',10)
splines=node.create_publisher(Bspline,'planning/bspline',10)
commands=[];done=[]
node.create_subscription(Twist,'cmd_vel',commands.append,10)
node.create_subscription(Int64,'planning/trajectory_done',lambda m:done.append(m.data),10)
grant=TrajectoryStatus(goal_id=1,traj_id=1,state=TrajectoryStatus.ACTIVE,
hold_heading=True,heading=0.,heading_tolerance=.035,
correction_rotation_allowed=True,goal=Point(x=1.))
odom=Odometry();odom.pose.pose.orientation.w=1.
odom.pose.pose.position.x=.7;odom.twist.twist.linear.x=1.
spline=Bspline(order=3,traj_id=1,knots=[-.3,-.2,-.1,0.,.1,.2,.3,.4],pos_pts=[Point(x=1.) for _ in range(4)])
def spin(age,duration=.35):
until=time.monotonic()+duration
while time.monotonic()<until:
now=node.get_clock().now()
odom.header.stamp=Time(nanoseconds=now.nanoseconds-int(age*1e9)).to_msg()
grant.header.stamp=now.to_msg()
grants.publish(grant);odoms.publish(odom)
rclpy.spin_once(node,timeout_sec=.01)
try:
spin(.01,1.)
splines.publish(spline);spin(.01)
fresh=commands[-1].linear.x
self.assertGreater(fresh,.5)
brake_cap=math.sqrt(1.8**2*.1**2+2*1.8*.3)-1.8*.1
self.assertLessEqual(fresh,brake_cap+.01)
spin(.14)
self.assertGreater(commands[-1].linear.x,.1)
self.assertLess(commands[-1].linear.x,fresh-.1)
# Receipt is current in both cases; invalid SOURCE time must stop.
for age in (.25,-.05):
spin(age)
self.assertTrue(all(abs(c.linear.x)+abs(c.linear.y)+abs(c.angular.z)<1e-9 for c in commands[-5:]))
spin(.01)
self.assertGreater(commands[-1].linear.x,.1)
grant.state=TrajectoryStatus.FAILED
spin(.01)
self.assertTrue(all(abs(c.linear.x)+abs(c.linear.y)+abs(c.angular.z)<1e-9 for c in commands[-5:]))
# A predicted future heading must never certify measured arrival.
grant.state=TrajectoryStatus.ACTIVE;grant.traj_id=2;grant.is_final=True
grant.target_yaw_valid=True;grant.target_yaw=0.;grant.terminal_rotation_allowed=True
odom.pose.pose.position.x=1.;odom.twist.twist.linear.x=0.
odom.pose.pose.orientation.z=math.sin(.15/2)
odom.pose.pose.orientation.w=math.cos(.15/2)
odom.twist.twist.angular.z=-1.5
spline.traj_id=2;splines.publish(spline)
spin(.1)
self.assertNotIn(2,done)
odom.pose.pose.orientation.z=0.;odom.pose.pose.orientation.w=1.
odom.twist.twist.angular.z=0.;spin(.01)
self.assertIn(2,done)
finally:
node.destroy_node();rclpy.shutdown()
@@ -51,6 +51,8 @@ TEST_F(RectangleMap, LaneAndHeadingCacheRebuild)
EXPECT_EQ(map.getRectangleOccupancy(p, M_PI/4), 1);
EXPECT_TRUE(map.rotationIsFree(p, 0.0, 0.02));
EXPECT_FALSE(map.rotationIsFree(p, 0.0, M_PI/2)); // both endpoints fit; middle does not
EXPECT_EQ(map.rotationOccupancy(p, 0.0, M_PI/2), 1);
EXPECT_EQ(map.rotationOccupancy(p, 0.0, 0.02), 0);
map.setFootprintHeading(M_PI/4);
EXPECT_EQ(map.getInflateOccupancy(p, 0), 1);
map.setFootprintHeading(0);
@@ -65,6 +67,9 @@ TEST_F(RectangleMap, EntireFootprintMustStayInsideMap)
EXPECT_EQ(map.getInflateOccupancy(Eigen::Vector3d(4.9, 0, 0), 0), -1);
EXPECT_EQ(map.getRectangleOccupancy(Eigen::Vector3d(4.9, 0, 0), 0), -1);
EXPECT_FALSE(map.rotationIsFree(Eigen::Vector3d(4.9, 0, 0), 0, M_PI));
EXPECT_EQ(map.rotationOccupancy(Eigen::Vector3d(4.9, 0, 0), 0, M_PI), -1);
EXPECT_EQ(map.rotationOccupancy(Eigen::Vector3d(4.4, 0, 0), 0, M_PI/2, .08), -1);
EXPECT_FALSE(map.rotationIsFree(Eigen::Vector3d(4.4, 0, 0), 0, M_PI/2, .08));
EXPECT_EQ(map.getInflateOccupancy(Eigen::Vector3d(NAN, 0, 0), 0), -1);
}
@@ -28,6 +28,8 @@ def generate_test_description():
'fsm.require_perception_ready': True, 'fsm.require_controller_feedback': True,
'fsm.blocked_timeout': 1.0, 'fsm.blocked_retry_period': .1,
'grid_map.rectangle_footprint': True, 'grid_map.map_sliding_en': False,
'grid_map.sliding_map_size_x': 10., 'grid_map.sliding_map_size_y': 10.,
'manager.max_vel': .7, 'optimization.max_vel': .7,
}], output='screen')
return launch.LaunchDescription([planner, launch_testing.actions.ReadyToTest()])
@@ -64,10 +66,10 @@ class TestRectangleFSM(unittest.TestCase):
if until is not None:
assert until(), [(m.state, m.reason) for m in statuses[-10:]]
def goal(yaw=0., zero_q=False):
def goal(yaw=0., zero_q=False, x=1.):
msg = PoseStamped()
msg.header.frame_id = 'world'
msg.pose.position.x = 1.
msg.pose.position.x = x
msg.pose.orientation.w = 0. # Quaternion defaults to w=1 in this ROS installation.
if not zero_q:
msg.pose.orientation.w = math.cos(yaw/2)
@@ -76,8 +78,27 @@ class TestRectangleFSM(unittest.TestCase):
try:
spin(1.5)
goal()
# Short stop-to-stop segments previously fixed a pre-endpoint
# acceleration above the limit into the spline and timed out.
goal(x=.4875)
spin(3., until=lambda: statuses and statuses[-1].state == TrajectoryStatus.ACTIVE)
short = statuses[-1]
spin(.3, until=lambda: short.traj_id in splines)
curve = splines[short.traj_id]
dt = curve.knots[4]-curve.knots[3]
a, b, c = curve.pos_pts[-3:]
terminal_acc = [(getattr(a,k)-2*getattr(b,k)+getattr(c,k))/dt**2 for k in ('x','y','z')]
assert math.sqrt(sum(v*v for v in terminal_acc)) < .05, terminal_acc
# Goal center is inside, but its complete turn footprint is outside
# the map. Keep the distant task active without granting that turn.
goal(.01, x=4.8)
spin(3., until=lambda: statuses and statuses[-1].goal_id > short.goal_id and statuses[-1].state == TrajectoryStatus.ACTIVE)
distant_id = statuses[-1].goal_id
spin(1.2)
assert not any(s.state == TrajectoryStatus.FAILED for s in statuses if s.goal_id == distant_id)
assert not any(s.terminal_rotation_allowed for s in statuses if s.goal_id == distant_id)
goal()
spin(3., until=lambda: statuses and statuses[-1].goal_id > distant_id and statuses[-1].state == TrajectoryStatus.ACTIVE)
active = statuses[-1]
assert active.hold_heading and active.is_final
assert abs(active.heading) < 1e-8 and active.goal.x == 1.
@@ -9,6 +9,9 @@
- 区域内**额外**插入规则网格点(不删除原点),保证墙是实心的、不会因点云稀疏漏洞;
- 输出只保留 x/y/z 三个字段(SCAN 的 grid_map 只用 xyz)。
显式 preserve_ray_metadata=true 时保留双雷达完整记录;新增先验以
sensor_id=255、时间字段=0、origin=endpoint 表示,仅占据端点,不伪造观测射线。
区域在**世界系**(Point-LIO 的 camera_init)里定义。因为起点固定、台阶固定,
标一次即可;若以后换场地,改 yaml 里的 ``regions``。
@@ -24,13 +27,38 @@ regions 格式(字符串,避免 ROS 2 不支持二维数组参数)::
"""
import numpy as np
from array import array
import copy
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data
from rclpy.qos import qos_profile_sensor_data,QoSProfile
from sensor_msgs.msg import PointCloud2
from sensor_msgs_py import point_cloud2 as pc2
def append_ray_priors(msg, walls):
"""Preserve canonical dual records; append labelled, endpoint-only priors.
sensor_id=255 is a planning constraint, NOT a lidar. Its source time is
zero (no acquisition); origin=endpoint makes a zero-length occupancy ray,
preventing fictitious free-space clearing through unobserved terrain.
"""
names=('x','y','z','origin_x','origin_y','origin_z','time_sec','time_nanosec','sensor_id')
dtype=np.dtype([(n,'<f4') for n in names[:6]]+[(names[6],'<i4'),(names[7],'<u4'),(names[8],'u1')])
expected=[(n,dtype.fields[n][1],7 if i<6 else 5 if i==6 else 6 if i==7 else 2,1) for i,n in enumerate(names)]
actual=[(f.name,f.offset,f.datatype,f.count) for f in msg.fields]
if msg.header.frame_id!='world' or msg.is_bigendian or actual!=expected or msg.height!=1 or msg.point_step!=33 or msg.row_step!=33*msg.width or len(msg.data)!=msg.row_step:
raise ValueError('invalid dual WORLD cloud schema; refusing origin loss')
raw=np.frombuffer(msg.data,dtype=dtype)
if not np.isin(raw['sensor_id'],[0,1]).all():raise ValueError('unexpected input sensor identity')
xyz=np.concatenate(walls) if walls else np.empty((0,3))
priors=np.zeros(len(xyz),dtype=dtype);priors['sensor_id']=255
for i,n in enumerate(names[:3]):priors[n]=xyz[:,i];priors['origin_'+n]=xyz[:,i]
out=copy.deepcopy(msg);out.width+=len(priors);out.row_step=out.width*out.point_step
out.data=array('B',bytes(msg.data)+priors.tobytes())
return out
def _parse_regions(text):
"""'x0,x1,y0,y1; x0,x1,y0,y1' -> [(x0,x1,y0,y1), ...]"""
regions = []
@@ -64,6 +92,7 @@ class StepBlocker(Node):
self.declare_parameter('cell_size', 0.10)
self.declare_parameter('z_min', 0.0)
self.declare_parameter('max_input_points', 200000)
self.preserve_ray_metadata=self.declare_parameter('preserve_ray_metadata',False).value
in_topic = self.get_parameter('input_topic').value
out_topic = self.get_parameter('output_topic').value
@@ -87,10 +116,10 @@ class StepBlocker(Node):
'step_blocker: regions is empty -> pure passthrough. '
'Set config/step_blocker.yaml before use.')
self.pub = self.create_publisher(PointCloud2, out_topic,
qos_profile_sensor_data)
cloud_qos=QoSProfile(depth=1) if self.declare_parameter('reliable_cloud',False).value else qos_profile_sensor_data
self.pub = self.create_publisher(PointCloud2, out_topic,cloud_qos)
self.sub = self.create_subscription(
PointCloud2, in_topic, self._cb, qos_profile_sensor_data)
PointCloud2, in_topic, self._cb, cloud_qos)
self.get_logger().info(f'{in_topic} -> {out_topic}')
def _build_walls(self):
@@ -111,6 +140,13 @@ class StepBlocker(Node):
return grids
def _cb(self, msg):
if self.preserve_ray_metadata:
try:
if msg.width*msg.height>self.max_pts:raise ValueError('dual cloud exceeds input limit')
self.pub.publish(append_ray_priors(msg,self._grids))
except ValueError as exc:
self.get_logger().error(str(exc),throttle_duration_sec=2.)
return
raw = pc2.read_points(msg, field_names=('x', 'y', 'z'), skip_nans=True)
# sensor_msgs_py 有两代返回类型:
# 旧版 -> 元组生成器,可用 np.asarray(list(raw))
+62 -3
View File
@@ -18,6 +18,28 @@ flowchart LR
G -. 独立真值评分 .-> T[验收工具]
```
## 自动上坡任务
需要从默认起点自动完成“导航到坡脚 → 专用控制上坡 → 全车进入平台停车”,使用新增独立任务入口:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true
```
它会初始化后自动行驶,无需另发目标或参考路径。直道默认 0.6 m/s、坡中 0.7 m/s、
原地转向上限 0.8 rad/s,坡顶降到 0.2 m/s、停车前再降速;直道中间停车航点已取消。
用法、状态、取消及验收边界见 [分段上坡任务](docs/RAMP_MISSION.md)。不要与下列其他仿真入口并行启动。
另有独立提速配置,使用 `profile:=fast`,目标是已知北侧路线在 20 秒仿真时间内完成。
它使用更高的仿真速度、不同的减速区和短时数据等待策略;参数与实测结果见
[快模式说明](docs/RAMP_MISSION.md#10-20-秒目标的独立快模式)。默认仍为标准模式,不能将快模式限速直接用于实车。
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py profile:=fast autostart:=true
```
本轮带 Gazebo/RViz 的理想、轻度噪声路线分别为 19.42/19.46 秒仿真时间,含全车上平台和停稳确认。
## 先看懂功能包与文件归属
这套平地导航仿真由五个独立入口组成。`sim_ws/src` 放场地、机器人和仿真启动配置;
@@ -35,6 +57,7 @@ flowchart LR
模型和传感器代码的位置:
- **场地模型**:默认场景是 [`src/robocon_gazebo/worlds/robocon_robot.world`](src/robocon_gazebo/worlds/robocon_robot.world),引用 [`src/robocon_gazebo/models/robocon_ground_full/model.sdf`](src/robocon_gazebo/models/robocon_ground_full/model.sdf);网格在同一模型目录的 `meshes/`。
Gazebo 默认视角从红方(世界坐标 +Y)外侧上方俯看红方半场,可用鼠标自由调整;重启场景恢复默认视角。
- **机器人模型**:外形、底盘、传感器安装位置和插件声明在 [`src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro`](src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro)。机器人入口展开该文件,再向已运行的 Gazebo 生成实体。
- **传感器仿真**:MID360 与 IMU 插件源码分别是 [`mid360_sensor.cpp`](src/r2027_robot_description/src/mid360_sensor.cpp) 和 [`mid360_imu.cpp`](src/r2027_robot_description/src/mid360_imu.cpp),噪声档位在 [`sensor_profiles.yaml`](src/r2027_robot_description/config/sensor_profiles.yaml)。插件随机器人实体装入 Gazebo,初始不采样;第三个入口负责启用和维持采样。`minco_ws/src/perception/livox_ros_driver2/` 提供点云使用的 Livox 消息类型,并非这里的传感器仿真程序。
- **定位与规划**:Point-LIO 源码在 `minco_ws/src/perception/Point-LIO/`;SCAN 规划器、控制器及其依赖在 `minco_ws/src/scan/`。本仿真的算法参数在 `src/br_sim_bringup/config/`,RViz 配置在 [`src/br_sim_bringup/rviz/scan_lio.rviz`](src/br_sim_bringup/rviz/scan_lio.rviz)。
@@ -42,8 +65,38 @@ flowchart LR
这些是**五个运行入口,并非五个独立 ROS 功能包**:机器人和传感器共用一个包,导航组合与 RViz 配置也共用一个包。
一键入口 `ros2 launch br_sim_bringup scan_lio.launch.py` 会组合这五层;分别启动的命令见下文。
## 双雷达低位补盲
按最新实车安装,新增雷达光心离地 **19.4 cm**、前移到车体水平中心前方 **32.5 cm**,
自身正方向朝车左方。使用双雷达模式:
```bash
ros2 launch br_sim_bringup scan_lio.launch.py dual_lidar:=true
```
上雷达继续负责 Point-LIO,下雷达仅取按车体方向定义的前方 180°,两颗雷达按采样时间与独立光心
进行避障融合。省略参数仍是原单雷达模式。平地使用上述入口;车架为前部开放的简化代理,
未复刻真实铝管尺寸。接口、验收与实车接入边界见 [双 MID360 说明](docs/DUAL_MID360.md)。
旧轮子代理遮挡导致的斜侧向擦边已完成隔离对照与五条路线回归;测量值、保留的失败及
未知区域限制见 [斜侧向诊断与回归](docs/DUAL_SAFETY.md)。
双雷达北侧 `(3.5, 4.8)` 路线曾因世界高度漂移把地面当成障碍,现已改用原始点的车体系高度滤地。
已完成两次完整通行和低障碍回归;使用前完整重启入口以清空旧体素地图,见 [北侧走廊修复](docs/NORTH_CORRIDOR.md)。
双雷达已知坡道使用独立入口及三维地表路径:
```bash
ros2 launch br_sim_bringup scan_lio_terrain.launch.py dual_lidar:=true yaw:=3.141592653589793
```
红、蓝两侧整轮各 4/4 通过,含上下坡、台阶和坡边目标拒绝;下雷达断流 0.44 s 停稳并恢复。
专用限速 0.15 m/s,沿用坡道 4 cm 仿真裕度和已知通行面先验。
路径命令、低障碍过滤限制及完整证据见 [双雷达坡道说明](docs/DUAL_TERRAIN.md)。
## 当前状态
以下阶段验收来自 2026-11-08 基线;2026-11-10 实测尺寸校准及本轮复测见
[尺寸与雷达安装记录](docs/VEHICLE_GEOMETRY.md)。旧阶段通过数不等于新尺寸全量重测。
- P1 场地:完整地图已导入;8 个接触抽样跨轮次通过。
- P2 底盘:Codex 全量复测 9/9 通过,包含前进、横移、转向、停止、里程计与 TF。
- P3 雷达:两个朝向下的三维点云坐标检查通过。
@@ -185,6 +238,7 @@ Classic 暂停时不发布新的 /clock,暂停判据和证据见对应验收
| `tools/check_sim_lidar.py` | 点云坐标和场地几何检查 |
| `tools/check_scan_navigation.py` | 平地导航与数据中断停车 |
| `tools/check_narrow_navigation.py` | 窄通道与未支持地形的拒绝测试 |
| `tools/check_lio_corridor.py` | 双 MID360 + Point-LIO,生产场地北侧长走廊和物理间隙检查 |
| `tools/check_slope_drive.py` | 重力、坡中停车、接触与倾斜点云检查 |
| `tools/check_slope_navigation.py` | 两侧坡道 SCAN 上下坡与台阶禁行 |
| `tools/repair_ramp_winding.py` | 固定来源坡道网格的面朝向修复 |
@@ -194,7 +248,8 @@ Classic 暂停时不发布新的 /clock,暂停判据和证据见对应验收
| `tools/check_mid360.py` | 实际采样时刻、独立几何求交、IMU 比力和连续性 |
| `tools/check_point_lio.py` | 现有 Point-LIO 的平地/上下坡独立定位评估 |
| `tools/check_lio_navigation.py` | LIO 平地闭环、近目标短断流恢复与定位失效锁停 |
| `tools/check_lio_terrain.py` | LIO 两侧坡道、台阶/箱体拒绝和下游断流停车 |
| `tools/check_lio_terrain.py` | 单/双雷达 LIO 两侧坡道、台阶/箱体拒绝、下游或下雷达断流停车 |
| `tools/check_ramp_mission.py` | 默认起点的接近/专用上坡/平台停车,以及独立故障注入 |
| `docs/HANDOFF.md` | 当前交接与约定 |
| `docs/USER_GUIDE.md` | 从启动到实车迁移的完整操作指南 |
| `docs/CLASSIC_BASELINE.md` | 场地基线证据 |
@@ -205,6 +260,7 @@ Classic 暂停时不发布新的 /clock,暂停判据和证据见对应验收
| `docs/P6_LOCALIZATION.md` | MID360 兼容模型、IMU 与独立定位误差 |
| `docs/P6_NAVIGATION.md` | Point-LIO 平地导航入口、接口约定与验收 |
| `docs/P6_LIO_TERRAIN.md` | LIO 指定坡道的定位预算、过滤与物理验收 |
| `docs/RAMP_MISSION.md` | 自动分段上坡任务、单一指令选择器、取消与验收边界 |
| `docs/archive/fortress` | 旧方案退役说明;过期操作文档已移出源码树 |
| `log/` | 原始证据与构建日志,Git 忽略 |
| `build/classic`、`install/classic` | 三个仿真包的构建/安装前缀 |
@@ -216,8 +272,11 @@ Classic 暂停时不发布新的 /clock,暂停判据和证据见对应验收
单位米、秒、弧度,右手系 Z 向上;场地原点保持源模型不变。
红方 +Y、蓝方 −Y;坡道下降方向 +X。外部源模型和 Blender/GLB/FBX 原文件不改动。
包内坡道碰撞 OBJ 仅反转朝内的面索引,顶点坐标不变;来源差异与哈希见模型包的 SOURCE_PROVENANCE.md。
机器人 base_link 为箱体中心;0.80×0.80 m 外包络,平地落稳 z≈0.148987 m。
世界→odom 是单位静态变换;odom→base_link 由运动插件唯一发布;雷达在 base_link 上方 0.30 m。
2026-11-10 按实车测量更新:车体外包络 **0.80×0.80×0.41 m**,雷达光心前移 **0.015 m**、居中、离地 **0.48 m**。
`base_link` 保留为水平中心、名义离地 **0.15 m** 的运动参考点,不是箱体几何中心;
因此 `base_link→lidar` 为 **(0.015, 0, 0.330) m**,`base_link→mid360_imu` 为 **(0.026, 0.02329, 0.28588) m**。
世界→odom 是单位静态变换;odom→base_link 由运动插件唯一发布。
安装朝向仍按各轴平行假设,质量、轮组与底部间隙尚未实车标定;详见 [尺寸与外参](docs/VEHICLE_GEOMETRY.md)。
详细话题类型、参考点、点云过滤和仿真限制见导航说明。
## 旧方案清理
+168
View File
@@ -0,0 +1,168 @@
# 双 MID360:下雷达补充前方低障碍
上方雷达继续负责 Point-LIO 定位;新增下雷达只补充避障感知。本轮实现位于仿真工作区,
未在实车上采集双雷达数据或验证时间同步,不能据此写“实车双雷达已验收”。
## 已确认的安装
用户确认下雷达光心相对上雷达前移 0.310 m、左右不变、下降 0.286 m,
水平安装、顶部朝上、自身 +X 朝车左方,且该高度的前方无遮挡。
沿用 X 前、Y 左、Z 上;单位米、秒、弧度。
| 光心 | 相对车体水平中心,Z 从地面量 | 相对 `base_link` | 相对车体旋转 |
|---|---|---|---|
| 上雷达 `lidar` | (0.015, 0, 0.480) m | (0.015, 0, 0.330) m | 继续沿用各轴平行假设 |
| 下雷达 `lidar_low` | (0.325, 0, 0.194) m | (0.325, 0, 0.044) m | roll=0、pitch=0、yaw=+π/2 |
`base_link` 仍是名义离地 0.15 m 的运动参考点,上雷达内部 IMU 外参不变。
下雷达自带 IMU 本轮未接入定位,也未生成第二套虚假的 IMU 消息。
前方 180° 是**按车体方向,以该雷达光心为射线起点**定义的左右各 90°。
先把下雷达射线方向旋到车体系,再保留方向 X≥0。由于安装 yaw=+π/2,等价于原始下雷达点 `y≤0`。
不能裁成下雷达自身 `x≥0`,也不能先加 0.325 m 平移后按点的车体系 X≥0 裁剪。
## 启动
从仓库根目录构建后启动:
```bash
bash sim_ws/tools/build_sim.sh
source /opt/ros/humble/setup.bash
source sim_ws/install/classic/setup.bash
export ROS_DOMAIN_ID=77 ROS_LOCALHOST_ONLY=1
export GAZEBO_MASTER_URI=http://127.0.0.1:11355
ros2 launch br_sim_bringup scan_lio.launch.py dual_lidar:=true
```
`dual_lidar` 默认 false,省略时保留原单雷达模式。双雷达模式会打开对应 RViz 配置,
显示上下雷达原始云、融合障碍云和规划云。无窗口验证可加 `gui:=false with_rviz:=false`。
发目标的方法不变,平地目标高度仍为 z=0.15 m。
按五层分别启动时,场地入口不变,其余四层要选择同一模式:
```bash
ros2 launch robocon_gazebo robocon_gazebo.launch.py
ros2 launch r2027_robot_description robocon_robot.launch.py dual_lidar:=true drive:=contact z:=0.15
ros2 launch r2027_robot_description mid360_sensors.launch.py dual_lidar:=true
ros2 launch br_sim_bringup scan_lio_navigation.launch.py dual_lidar:=true
ros2 launch br_sim_bringup rviz.launch.py dual_lidar:=true
```
先后启动,不与一键入口或自动工具同时运行。双雷达指定坡道使用独立的
`scan_lio_terrain.launch.py dual_lidar:=true`,其地表过滤、限速及验收见
[DUAL_TERRAIN.md](DUAL_TERRAIN.md)。拆分部署入口仍拒绝双雷达参数。
## 数据链路与建图
```mermaid
flowchart LR
U[上 MID360 + IMU] --> L[原 Point-LIO]
L --> A[固定起点对齐与车体参考点适配]
A --> P[估计车体位姿历史]
U --> F[按真实采样时间变换两颗雷达]
D[下 MID360 原始全圈] --> C[按车体方向取前 180°]
C --> F
P --> F
F --> M[SCAN:每点使用各自射线起点]
M --> K[原规划与闭环控制]
```
定位只订阅上雷达 `/sim/mid360/lidar` 和 `/sim/mid360/imu`。
`dual_lidar_fusion.py` 用 `/sim/navigation/body_odom` 的估计位姿,为两颗雷达按每点实际采样时刻
插值位置并 SLERP 姿态,变换光心、射线和回波到 world。没有订阅真值里程计或 TF,
没有用消息接收时间替代采样时间,也不把下雷达点直接塞进原单雷达 Point-LIO。
实测上游有效 EKF 输出在帧间可有约 65 ms 的间隔;插值必须有前后位姿夹住样本且跨度≤100 ms。
更长间隔不外推,丢弃该对扫描并等待后续完整数据。双雷达按扫描起始时间配对,允许差≤50 ms;
超过时丢弃较旧扫描。输出年龄上限与下游就绪门控均使用仿真时间。
| 话题 | 类型 | 内容 |
|---|---|---|
| `/sim/mid360/lidar` | `livox_ros_driver2/msg/CustomMsg` | 上雷达完整原始扫描,光学系、原始采样时间 |
| `/sim/mid360_low/lidar` | 同上 | 下雷达完整原始扫描,`lidar_low` 系,设备标识 1 |
| `/sim/mid360_low/points` | `sensor_msgs/msg/PointCloud2` | 下雷达原始扫描的显示副本,仍保留全圈 |
| `/sim/navigation/fused_cloud` | `sensor_msgs/msg/PointCloud2` | world 系上下雷达融合,已裁下雷达前半圈并去自身包络 |
| `/sim/navigation/fused_planning_cloud` | 同上 | 融合云的规划副本;平地按原始车体系高度滤地,专用坡道按已知 world 地表过滤,仅将地面 XYZ 置 NaN |
| `/sim/dual_lidar/status` | `std_msgs/msg/String` | 输入时间、丢帧、最近输出及错误状态 |
融合云字段为 XYZ、`origin_x/y/z`(该点在 world 系的光心起点)、
`time_sec/time_nanosec`(该点原采样时间)和 `sensor_id`(0 上、1 下)。
header.stamp 是这对扫描的采样结束时刻;它不替代逐点时间。
原始反射强度等信息保留在各自原始话题,本轮融合输出不携带 intensity。
平地地面带相对名义离地 0.15 m 的 `base_link` 定义,避免定位世界高度漂移产生假障碍;
不是把世界点云压平,也不适用于任意倾斜地形。北侧长路线复现和回归见 [NORTH_CORRIDOR.md](NORTH_CORRIDOR.md)。
原始消息定义见 [ROS PointCloud2](https://github.com/ros2/common_interfaces/blob/humble/sensor_msgs/msg/PointCloud2.msg)
和 [Livox CustomMsg/CustomPoint](https://github.com/Livox-SDK/livox_ros_driver2/tree/master/msg)。
SCAN 新增默认关闭的 `grid_map.cloud_has_ray_origins`。开启时严格读取每点起点,
不把下雷达点从上雷达光心发射;缺字段或 frame 错误就拒绝该云。
两条射线即使落在同一终点体素,也不能跳过另一条不同起点的射线。
真实车体尺寸、平地 9 cm 安全裕度及原实车默认配置不变,算法包没有新增 Gazebo 依赖。
坡道沿用独立的 4 cm 仿真裕度,不能推广为实车默认值。
原适配器的 `required_planning_topic` 指向融合规划云,任一雷达停发、融合进程停止或位姿覆盖不足,
新融合云就停止;过期后控制器撤销放行,不静默退回单雷达导航。双雷达采用 0.30 s 的源数据年龄门限,
覆盖扫描打包与等待定位覆盖的约两帧延迟;端到端物理停车仍要求≤0.50 s,不能用改时间戳通过。
## 车架与感知边界
新光心在旧实心箱体内部,继续沿用它会产生不真实的遮挡。双雷达模式改用前部开放的几何代理:
名义底板离地 0.07–0.10 m、顶板 0.39–0.41 m、后挡板厚 0.02 m,保留四个简化支撑轮。双雷达模式的支撑轮代理移到 X=±0.20 m、Y=±0.30 m,
保证未测量的轮子代理不伸到新光心前方,水平前半圈的 721 条射线均确认无遮挡。
这些厚度和梁位**是建模假设,不是用户提供的方管尺寸**;只表达已确认的前方通视与后部遮挡。
碰撞与显示使用同样的开放结构,没有绕过射线求交。质量分布仍采用原箱体加支撑轮近似,并按代理轮位重算惯量;质量不是实车测量。
外包络继续为 0.80×0.80×0.41 m,规划也继续保留整个车体的保守矩形。
原始上下雷达消息保留真实车体遮挡及采样时间。下雷达后半圈只在避障支路裁掉;
真实铝管的精确遮挡要等 CAD 或梁柱尺寸后再复现。
下雷达降低安装高度会缩小近地盲区,但仍有 −7° 下视角和 0.1 m 最小测距等模型限制,
不能从一例箱体可见推导“所有近地障碍都能看见”。横移和后退方向也没有新增全向低位覆盖。
## 验证与实车接入
```bash
/usr/bin/python3 sim_ws/tools/test_dual_lidar.py
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py --out sim_ws/log/dual_manual
```
本轮没有采集 GUI 截图,也没有把 RViz 画面记作已验收。原始证据位于
`sim_ws/log/codex_dual_mid360_20261110/`。下表是最初的**已确认安装、水平前方裁剪、平地前向补盲**证据;
后续坡道证据另见 [DUAL_TERRAIN.md](DUAL_TERRAIN.md),不能用本表替代坡道验收。
| 检查 | 本轮证据与结论 |
|---|---|
| 尺寸、光心、安装旋转与前方通视 | `geometry/`,7/7;水平前半圈 721 条射线无车体代理遮挡 |
| 裁剪、运动补偿、队列与时钟顺序 | `unit_final.log`,14/14 |
| SCAN 不同起点、相同终点、缺字段拒绝及原默认分支 | `ray_origin_tests_r2.log`,5/5 |
| 实际 TF 与估计链路隔离 | `integration_r6/`,Point-LIO 仍只输入上雷达/IMU,融合没有真值/TF 输入 |
| 8 cm 箱体,上雷达盲区对照 | 上雷达 0 回波,下雷达 469 个原始回波,融合保留 493 点;统计窗口不同,不作逐点数量相等断言 |
| 占用与导航 | 箱体进入地图;内部目标拒绝;车头朝向 −Y,从 (−4.5,4.5) 正向接近并绕过 (−4.5,3.0) 的箱体,到达 (−4.5,1.5) |
| 实际到达与间隙 | 到点误差 0.06765 m,保守车体包络最小间隙 0.08925 m,终态后 0.04 s 停稳 |
| 逐点起点变换 | 对估计输入的最大变换误差 0.000000324 m;独立物理真值下最大误差 0.05881 m,后者包含定位误差,不能写成微米级定位 |
| 单独停掉下雷达 | 上雷达保持工作、无单雷达回退;0.29 s 仿真时间停稳,≤0.50 s 的既定物理阈值通过 |
| 原单雷达回归 | `single_sensor_regression/` 的 18 项通过;`single_navigation_regression_r1/` 直达通过 |
### 失败记录和未完成的安全范围
`integration_r5/` 的斜侧向接近箱体测试出现过**约 6.5 mm 保守外包框重叠**,未通过。
该轮下雷达确有点、融合坐标也正确,但只看到了障碍的一部分,不能从少量回波推导完整外边界。
后续 `integration_r6/` 在明确正前方接近的路线通过;它没有覆盖或抹去侧向失败。
当时车体代理轮位仍为 ±0.30 m,当前双雷达代理已改为 ±0.20 m。
后续已复测原侧向路线、镜像侧向、两条较宽位置的 45° 路线和正前方路线,五条均通过。
隔离恢复旧轮位会重新遮住下雷达并导致负对照失败;包络验收已改用旋转矩形和沿途扫过空间。
具体间隙、时钟顺序修复、保留的失败与采集边界见 [斜侧向诊断与回归](DUAL_SAFETY.md)。
这些通过仍不能推导“前方 180° 内任意低障碍均可安全绕行”,也不代替实车侧向低障碍验收。
原单雷达直达首轮也因规划云过期后未恢复而失败(`single_navigation_regression/`),未改阈值的补测通过;
这不构成旧模式连续重启或长时稳定性的新增证明。
其他失败/无效轮次也保留:首轮测试路线终点靠近台阶;另一起点未锁定初始定位;
初版 200 ms 年龄门限过短而反复撤销就绪;早期位姿队列过短丢中间样本。
前两项没有通过放宽定位门槛或缩小车体来掩盖,后两项分别以明确的延迟预算和可靠深队列修复。
逐点起点字段、时间与地图语义测试通过不等于实车已验收。
[本轮结构化摘要](validation/20261110_dual_mid360.json) 记录采用的具体轮次、哈希与局限。
实车迁移时,先分别确认两颗雷达独立话题、frame、设备编号、完整外参和共同时钟。
不能把两个来源都重命名成同一个 `lidar` 来掩盖安装旋转,也不能用接收时间伪造同步。
再用估计定位的车体姿态变换两套点云、保留射线起点,通过静止墙面对齐、推车、转向及低障碍箱体验证。
最后再接 SCAN 的逐点起点模式和双输入过期停车。当前未交付或验证一套实车双雷达驱动启动文件。
+152
View File
@@ -0,0 +1,152 @@
# 双雷达斜侧向擦边:诊断与回归
> 后续双雷达北侧长路线的地面过滤修复及新验收见 [NORTH_CORRIDOR.md](NORTH_CORRIDOR.md)。
> 本文五条路线及源码哈希保留为该轮历史证据;新过滤规则下重测了前向、原侧向和北侧完整路线,未将本文五例全部重跑。
本轮针对 `DUAL_MID360.md` 记录的斜侧向包络重叠开展调查。所有运行证据位于
`sim_ws/log/codex_dual_safety_20261110/`;没有采集 GUI 截图,没有实车运行,也没有提交或推送。
## 已定位的问题和处理
### 简化轮子代理遮挡下雷达
旧失败模型的轮子中心 X=±0.30 m、半径 0.10 m,最前端到 X=0.40 m;
下光心在 X=0.325 m、离地 0.194 m。轮子代理进入了原本应无遮挡的前方视野。
原始物理射线先撞轮子,随后自身过滤删除了这些回波,无法恢复被挡住的外部障碍。
原失败证据中,25×25×8 cm 箱体只形成远侧的少量占用体素,近侧边缘约少了 0.20 m。
此时继续扩大一点规划裕度不能补回缺失几何。
**当前双雷达模型此前已将轮心移到 X=±0.20 m,本轮确认其效果并补齐回归。**
轮子最前端为 X=0.30 m,位于下光心之后;车体规划包络仍为 0.80×0.80 m、裕度仍为 0.09 m。
没有让碰撞体对雷达透明,没有缩小车体,也没有把已知箱体尺寸注入运行时点云或地图。
轮位仍是满足用户已确认前方通视的代理假设,不能当作实车轮位测量。
隔离对照使用证据目录中的私有 ament 前缀,只复制并恢复旧轮位,不修改源码、安装目录或原始资源。
`historical_side_right/` 的初始箱体占用再次降到 9 个,原路线再次失败;
`baseline_side_right/` 的当前轮位形成 31 个初始占用体素,同路线到达且包络无重叠。
旧轮位恢复还会改变按轮位计算的惯量,因此不把整段动态 A/B 当成只改变光学遮挡的实验;
静止时的射线和初始点云对照用于区分遮挡影响。
该次旧轮位实验的后续真值查询间隔超限,**整轮为 INVALID**,不能写成完整负对照验收。
修复采集后再次运行 `historical_fixed_clock/`,取得有效 FAIL(退出码 30):
近侧仍缺失、初始占用为 9 个、旋转包络安全间隙判据失败,其他数据质量检查通过。
这次有效负对照与原 INVALID 轮次分开保存。
### 时钟与传感器消息到达顺序
另外确认适配器原先会丢弃先于 `/clock` 回调到达的里程计/点云。
已改为暂存最多超前 0.20 s 的原消息,等仿真时钟到达采样时间后再处理;每类队列上限 64。
新消息到达和健康定时器都会处理已到时的数据。超前过多的数据丢弃;队列溢出锁停。
不会提前发布,不改时间戳;里程计 0.20 s、原点云 0.25 s、双雷达规划云 0.30 s 的年龄门限均未放宽。
时钟跳过后已经过期的暂存数据不会变成新数据,源时间倒退仍锁停。
这修复了可复现的回调顺序缺陷;不能据此认定历史上所有过期停车都由它造成。
### 启动时存在性查询响应丢失
重启回归还遇到了 Gazebo 收到第一次实体查询、却未能把响应交给客户端的情况;
日志明确包含 `failed to send response ... timeout`,机器人尚未生成。
启动脚本现在在原有 15 s 总预算内重试**只读存在性查询**,每次最多等 3 s,并撤销超时请求。
没有把超时当成“实体不存在”,重复启动保护保留;有副作用的 `SpawnEntity` 不自动重试。
重试、总时限和禁止重复生成由三项独立测试覆盖。
## 验收方法
`test_dual_acceptance.py` 检查实际展开 SDF 中的 box/cylinder 碰撞体:
- 下雷达前半圈,方位步长 0.25°、俯角从 −7° 到 0°,共 10,815 条射线不得撞自身代理。
- 后向射线仍应被后挡板遮住;恢复旧轮位必须重新检出前方遮挡,防止测试失去区分能力。
- 包络使用随 yaw 旋转的矩形 SAT。不能把轴对齐外包框的重叠直接写成真实矩形碰撞。
- 检查两个采样点之间的穿越与旋转扫角,避免只看路径端点。
运行时以已有接触插件 `/odom` 的 100 Hz `WorldPose` 记录检查包络,与带仿真时间戳的
`/gazebo/get_entity_state` 查询交叉核对,要求位置差 <2 mm、姿态差 <5 mrad。
这两者只供验收工具使用;运行中的 Point-LIO、融合、规划和控制仍没有真值输入。
真值插值间隔上限仍为 0.12 s,实际间隔写入各轮报告。
沿采样轨迹按最多 2 mm 的角点位移细分,SAT 间隙再减去半个细分步的角点位移上界。
该结果是**采样点之间按线性位置、最短 yaw 插值的保守界**,不是任意连续动力学的形式化证明。
间隙验收阈值沿用 >0.015 m;它不代表实际始终具有 0.09 m 净空。
五条最终路线均记录到“箱体 ROI 内没有新融合点、地图仍保留旧占用”的时段,
分别为 5、2、82、100、221 帧(原侧向、镜像侧向、右/左斜向、前向)。
这是静态箱体的观测记忆证据,详见每轮 `memory_observation.json`;没有另建第二套占用地图。
它不保证动态障碍的跟踪,也不保证从未观测的区域为空。
点云、地图、样条、估计位姿、物理位姿及健康状态保存在可选的 `diagnostics.json`。
`--navigation-only` 是明确的导航子任务范围,不执行断流用例;断流停车在完整前向回归中单独验证。
## 最终采用的运行结果
| 路线 | 最小旋转包络间隙保守界 | 实际到点误差 | 结论 |
|---|---:|---:|---|
| 原侧向 `fixed_side_right/` | 24.71 cm | 5.88 cm | 12/12 PASS |
| 镜像侧向 `fixed_side_left/` | 22.58 cm | 6.17 cm | 12/12 PASS |
| 较宽位置右斜向 `fixed_diagonal_right/` | 23.79 cm | 6.77 cm | 12/12 PASS |
| 较宽位置左斜向 `fixed_diagonal_left/` | 21.15 cm | 9.23 cm | 12/12 PASS |
| 正前方 `fixed_front/` | 7.57 cm | 7.27 cm | 13/13 PASS,断流后 0.39 s 停稳 |
上述五轮都包含时钟暂存修复;随后只修改了启动只读查询重试,再执行单雷达直达和双雷达前向回归。
单雷达到点误差 5.69 cm;补测双雷达前向间隙保守界 11.73 cm、断流后 0.37 s 停稳。
**没有在启动脚本修改后将上述五轮全部重跑。** 所有断流时延均为仿真时间。
对应物理真值流最大采样间隔为 0.020 s,位姿查询交叉核对通过。
相关单元测试共 41 项:双雷达感知 14、通视与包络 7、适配器 17、启动查询 3,均通过。
两个涉及的仿真包重新构建通过;构建不替代上述运行证据。
下图采用有效旧轮位负对照和最终原侧向回归:蓝色为初始占用体素的水平投影,黑框为箱体真实边界;
右图的轨迹仅用于独立验收,没有输入导航算法。图中当前轮次为 32 个体素,前述基线轮次为 31 个,分别对应原始证据。
![旧轮位与当前轮位的地图和轨迹对照](validation/20261110_dual_side_evidence.svg)
## 复现
先按 README 构建并加载环境。每轮用新的输出目录,所有 Gazebo 用例串行执行:
```bash
ROS_DOMAIN_ID=178 ROS_LOCALHOST_ONLY=1 /usr/bin/python3 sim_ws/tools/test_dual_acceptance.py
ROS_DOMAIN_ID=178 ROS_LOCALHOST_ONLY=1 /usr/bin/python3 sim_ws/tools/test_lio_navigation_adapter.py
ROS_DOMAIN_ID=178 ROS_LOCALHOST_ONLY=1 /usr/bin/python3 sim_ws/tools/test_spawn_existing_world.py
# 原失败路线:保留原起点、目标和箱体位置。
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py \
--scenario side_right --navigation-only --diagnostics \
--out sim_ws/log/dual_side_right
# 镜像侧向路线。
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py \
--scenario side_left --navigation-only --diagnostics \
--out sim_ws/log/dual_side_left
# 两条额外 45° 路线,显式使用不同箱体/目标坐标;不覆盖原路线证据。
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py \
--scenario diagonal_right --fixture-x -3.6 --goal-x -3.9 \
--navigation-only --diagnostics --out sim_ws/log/dual_diagonal_right
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py \
--scenario diagonal_left --fixture-x -5.0 --goal-x -4.6 \
--navigation-only --diagnostics --out sim_ws/log/dual_diagonal_left
# 正前方完整用例,包括下雷达独立断流后的停车。
/usr/bin/python3 sim_ws/tools/check_dual_lidar.py \
--diagnostics --out sim_ws/log/dual_front_regression
```
`--historical-wheel-proxy` 只用于旧轮位负对照,预期不能通过当前通视/导航要求,不是推荐的启动配置。
## 保留的失败和边界
- 原箱体中心 X=−4.5 m 的 45° 路线未通过初始规划;改为 X=−3.9 m 仍未通过。
这两条路线没有发生包络重叠。按观测地图和现有矩形膨胀规则复核,在箱体附近横截面没有可用车中心位置;
因而新增更宽位置的测试,而没有缩小安全裕度。它们仍保留为未完成导航的记录。
局部截面计算保存在 `diagonal_right_wide/cross_section.json`;这不是全场任意朝向的可达性证明。
- `diagonal_right_dense/` 曾因感知数据过期在距目标约 0.15 m 处停住,整轮 FAIL;
`diagonal_right_dense_r1/` 则在生成机器人前服务超时,整轮 INVALID。后续通过不抹去这些记录。
- 早期诊断工具遇到过空地图读取异常和稀疏真值查询间隔超限,均标 INVALID。
已修复空消息读取,并采用上述高频真值与独立查询交叉核对。
- 当前下雷达仍只有前方 180°;低位近距、侧后方、动态障碍和真实车架遮挡不能由这些静态箱体用例保证。
本轮未增加“未知区域禁止横移”策略,也未实现自动朝向行进方向或独立制动距离监控层。
若要放开未知环境中的全向低障碍通行,这些仍须单独设计和验收。
- 本表未覆盖实车 launch、实车时钟同步、真实摩擦、车架尺寸、双雷达坡道或双机部署。
后续双雷达指定坡道的独立证据见 [DUAL_TERRAIN.md](DUAL_TERRAIN.md)。
具体采用的最终轮次与测量值见 [本轮结构化证据](validation/20261110_dual_safety.json)。
+142
View File
@@ -0,0 +1,142 @@
# 双 MID360:已知坡道导航
2026-11-12 新增“导航接近+专用上坡+平台停车”的独立任务入口,见 [RAMP_MISSION.md](RAMP_MISSION.md)。
本页仍介绍原 SCAN 三维参考路径入口及其历史验收,不需要为了使用新任务改动这里的限速。
这是单独启用的地形配置,复用上置 MID360 / IMU 的 Point-LIO、现有 SCAN 和闭环控制器。
上下雷达仅在避障支路融合,下雷达仍只取车前方 180°;没有接入第二颗 IMU,也没有向算法输入 Gazebo 真值。
本轮不迁移实车入口,不处理任意未知坡面或真实轮组抓地。
## 手动使用
先完整关闭平地入口。在仓库根目录、与平地导航相同的环境启动:
```bash
source /opt/ros/humble/setup.bash
source sim_ws/install/classic/setup.bash
export ROS_DOMAIN_ID=77 ROS_LOCALHOST_ONLY=1
export GAZEBO_MASTER_URI=http://127.0.0.1:11355
ros2 launch br_sim_bringup scan_lio_terrain.launch.py dual_lidar:=true yaw:=3.141592653589793
```
红侧已知起点为 world (3.5,3.5125,0.15),yaw=π 使车头和下雷达前向视野朝向上坡方向 −X。
`base_link` 是名义离地 0.15 m 的运动参考点;车体仍为 0.80×0.80×0.41 m。
两颗雷达外参继续使用 [DUAL_MID360.md](DUAL_MID360.md) 的实测光心记录。
所有算法使用仿真时间,长度米、角度弧度,world Z 向上。
在另一相同环境的终端等待 `/planning/perception_ready` 为 true,再发送:
```bash
ros2 run scan_planner reference_path_publisher.py --ros-args \
-p use_sim_time:=true -p frame_id:=world \
-p odom_topic:=/sim/navigation/body_odom -p path_topic:=/initial_path \
-p 'waypoints:=[3.5,3.5125,0.0,2.7,3.5125,0.0,-0.8,3.5125,0.597,-1.2,3.5125,0.6]'
```
每三个数为 x/y/z,**路径 z 是地表高度**,SCAN 加 0.15 m 得到运动参考点高度。
发布器默认等待实车 `/body_odom`,仿真必须显式指定上述估计里程计话题;
若看到“等待 /body_odom”,停止该发布器并用完整命令重发,无需为此重启仿真。
自动验收工具直接发布 Path,此前未覆盖手动发布器的默认订阅。修正文档后,已用上述完整命令在
隔离 ROS 域配合测试时钟/里程计确认订阅正确、实际收到四个路径点,证据在 `log/reference_path_doc_fix/`;
这次接口检查不作为新增坡道导航验收,也不修改实车默认话题。
到点停车后,下坡将上述点顺序反转;车头保持 π,因此这一返回段是倒车,下雷达没有新增后向低位覆盖。
蓝侧启动加 `y:=-3.5125`,路径内全部 Y 同步改为 −3.5125。
不要把平地 PoseStamped 目标直接替代这条三维地表路径;入口不会自动发路径。
`dual_lidar` 默认 false,省略时仍是原单雷达坡道入口。拆分部署入口仍不支持双雷达。
## 地面、射线与禁行约定
平地双雷达的原始车体系水平地面判据在俯仰或坡脚过渡时不成立。
新增 `dual_lidar_terrain.yaml` 显式选择 `ground_mode=known_terrain`,沿用既有已知坡面、平台和底层平面,
在 world 系按 6 cm 竖直残差带只过滤规划副本。完整融合云及原始消息不改变。
原始逐点时间、两个不同的世界光心起点和设备标识均保留,不能用改 frame_id 或抬高点云代替变换。
原 step_blocker 默认输出纯 XYZ。新增默认关闭的 `preserve_ray_metadata`,只在双雷达坡道打开:
- 实际雷达记录逐字节透传,包括 NaN 地面标记;sensor_id 仍为 0 上、1 下。
- 新增坡边/台阶先验明确标为 sensor_id=255;逐点时间为 0,表示没有传感器采样时刻。
- 先验使用 origin=endpoint 的零长度占据射线,只占据终点,不构造从雷达到先验的虚假自由空间。
- 输出 `/sim/navigation/terrain_planning_cloud` 是混有显式先验的规划数据,不能当作真实感知或送入 Point-LIO。
- 字段不符、输入超限时停止该帧输出,不能静默丢失原始光心。没有定时重发旧云来伪造新鲜度。
规划器保持启用逐点起点;原 SCAN/控制器实现没有另复制一份。step_blocker 未新增 Gazebo 依赖,
其原单雷达和实车默认行为不变。
双雷达扫描打包、估计位姿覆盖及禁行层造成约两帧延迟,最终规划云采用 0.30 s 源时间年龄门限,
与双雷达平地相同;原单雷达坡道仍为 0.20 s。物理断流停车仍要求 ≤0.50 s,不改源时间戳。
本配置限速 0.15 m/s,保留既有坡道单边 4 cm 裕度、0.01 rad 朝向容差、2.5 cm 体素。
平地的 9 cm 裕度及实车默认参数不改。坡道净宽 0.975 m,这套仿真配置不能直接视为实车安全配置。
## 验收与复现
自动工具自行启动、停止仿真,不能与手动 launch 并行;每次使用新的输出目录,串行运行:
```bash
/usr/bin/python3 sim_ws/tools/check_lio_terrain.py --dual-lidar --yaw 3.141592653589793 \
--lower-loss --out sim_ws/log/dual_terrain_red_manual
/usr/bin/python3 sim_ws/tools/check_lio_terrain.py --dual-lidar --yaw 3.141592653589793 \
--side blue --planning-loss --out sim_ws/log/dual_terrain_blue_manual
/usr/bin/python3 sim_ws/tools/check_lio_terrain.py --dual-lidar --yaw 3.141592653589793 \
--obstacle-only --obstacle-height 0.15 --out sim_ws/log/dual_terrain_obstacle_manual
```
每侧整轮包含上坡、台阶目标拒绝、坡边目标拒绝、下坡;不拼接不同轮次来冒充完整通过。
`--lower-loss` 仅停止下雷达,验证上雷达继续、撤销就绪、停车及同一任务重新授权;
恢复通过传感器已有 `/lidar/profile/<当前模式>` 服务完成,不重启或重置定位。
`--planning-loss` 暂停工具拥有的 step_blocker,验证最终规划支路的断流保护。
物理位置使用接触驱动已有的 100 Hz WorldPose 输出,仅供独立评分,另与带源时间的 Gazebo 实体查询核对:
位置差 <2 mm、姿态差 <5 mrad、采样间隔 ≤120 ms,再按时间配对估计;不重新拟合定位。
既有 3 cm 横向偏离、4 cm 完整车体空隙、0.5 s 故障停稳和实际坡道接触要求均保留。
报告保存原始样本、接触碰撞对、输入路径、消息状态及逐帧元数据断言。
退出码 0/30/40 分别表示通过、有效失败、采集无效;没有 GUI 截图验收。
## 使用边界
6 cm 的地表过滤带不能认证所有 ≤10 cm 低障碍;双雷达有回波不等于经过坡面过滤后仍可可靠避障。
指定箱体若通过,只证明该位置、姿态、定位误差下的样例。平地 8 cm 箱体的旧结论不能直接推广到坡道。
车架仍是用户确认前向通视下的简化代理,实际铝管遮挡和精确轮组未建模。
本次不增加全向低位视野、未知悬崖检测、坡中转向、任意目标自动寻坡或实车抓地保证。
## 2026-11-10 实测结果
证据目录为 `log/codex_dual_terrain_20261110/`;以下每个目录均是单次独立启动。
原始失败报告不覆盖,不用构建成功或画面替代物理验证。
| 轮次 | 结果 |
|---|---|
| `red_slow/` | 整轮 4/4 PASS;上/下坡真实 XY 误差 8.04/5.53 cm,完整车体最小采样空隙 6.54/6.54 cm,最大横向偏离 2.15/2.07 cm |
| `blue/` | 整轮 4/4 PASS;上/下坡真实 XY 误差 6.16/5.75 cm,完整车体最小采样空隙 7.58/7.54 cm,最大横向偏离 0.99/1.00 cm |
| 红侧单独关闭下雷达 | 上雷达继续工作,0.44 s 停稳,保持静止;恢复后原任务重新获得轨迹并到达 |
| 蓝侧暂停最终禁行层 | 0.15 s 停稳,保持静止;恢复后原任务继续 |
| `obstacle_15_window/` | 水平放置的 15 cm 箱体,固定两秒 18 对扫描,选中回波 178/178 保留,其中下雷达 93 点;目标被拒绝,未进入 ACTIVE,物理保持静止 |
| `obstacle_08_aligned/` | **底面与坡面平行、法向高 8 cm** 的额外箱体,固定两秒 19 对扫描,选中回波 161/161 保留,其中下雷达 55 点;目标拒绝和物理静止通过 |
| `obstacle_08_horizontal/` | **FAIL**:水平放置的 8 cm 箱体,119 个选中回波保留 118 个;目标仍被拒绝、未进入 ACTIVE、车辆静止,但完整保留标准未过,不能记成全通过 |
箱体判据取固定两秒内的全部配对扫描:≥10 对、总计≥15 个被选中的实际回波、其中下雷达≥5 个、
选中点全部保留,再验证占用目标拒绝与实际静止。ROI 选取箱体附近的上部回波,
数量指选中样本,不是箱体全部可见面的覆盖保证;没有挑一帧最好结果或修改源时间。
水平 8 cm 箱体的底面在世界系保持水平,因此在斜坡高端,顶面只高出当地坡面约 5.9 cm,
并非每个角都离坡面 8 cm。未保留的点为估计 world (0.872324,3.413033,0.370264),
距已知坡面的竖直残差为 0.058515 m,落入现有 0.06 m 过滤带。
该记录保留为具体限制;没有缩小过滤带来追求这个用例通过,也没有将新增贴坡箱体替换成原失败用例。
实际目标拒绝通过不能消除感知层的失败,贴坡箱体通过也不能推广到所有 ≤10 cm 障碍。
先前轮次:`red_initial/` 因评分器的稀疏实体查询出现 >120 ms 真值间隔,记 INVALID;
其运行日志另记录了 0.20 s 下游门限导致反复等待。`red_r1/` 的故障恢复脚本误用了不存在的 enable 服务,
记 INVALID,已改用现有 profile 服务。`red_r2/` 的 0.20 m/s 上坡及两项拒绝通过,
下坡最大横向偏离 3.27 cm,超过 3 cm,整轮 FAIL;没有放宽阈值,改以 0.15 m/s 完整重跑红、蓝两侧。
`obstacle_08/`、`obstacle_15/` 的单帧计数分别只有 6、9 点,未达原单帧数量要求,仍保留 FAIL;
之后改为固定两秒全帧采集。`obstacle_08_window/` 已取得 115 点但只保留 114,仍为 FAIL。
本轮 Python 测试 40 项、实际 GridMap C++ 测试 6 项通过;新增内容包括俯仰姿态下的双光心、
坡面过滤、实际记录逐字节保留、先验标识及零长度射线不清除中间占用。
红/蓝各有 117/123 组运行时元数据断言,均验证实际射线记录、时间和 sensor_id 不被禁行层重写。
坡道完整单雷达套件、此前全部平地路线、GUI、双机和实车未在本轮重跑。
`flat_regression/` 的双雷达平地前向回归 13/13 PASS:8 cm 低障碍进入地图、内部目标拒绝、实际绕行、
真实到点误差 7.80 cm、下雷达断流 0.33 s 停稳。只重跑此前前向场景,没有重跑全部斜向或北侧路线。
汇总、源码哈希、实际采集工具版本及失败索引见
[validation/20261110_dual_terrain.json](validation/20261110_dual_terrain.json)。
索引整体标为 LIMITED_ACCEPTANCE,不能读作所有低障碍及所有地形通过。
+81 -8
View File
@@ -1,8 +1,80 @@
# 当前交接(2026-11-08)
# 当前交接(分段上坡更新:2026-11-12)
当前新增独立 `profile:=fast`,默认仍是 `standard`。快模式直道 2.5、坡中 1.1 m/s,
转向 2.0 rad/s;平台低速目标仍为 0.2 m/s,但低速区从标准的 base x=-0.25 后移到 -0.90。
`final_v3_ideal/mild` 均带 Gazebo/RViz,分别 **24/24 PASS、19.42/19.46 s**(NAVIGATE 到全车上平台停稳,仿真时间)。
同版本坡上下雷达断流 **12/12 PASS、0.416 s** 停稳,恢复数据后保持 FAILED;默认标准模式整段回归 **23/23 PASS、49.11 s**。
快模式采用更大横向局部地图、提前替换接近目标、2.5 cm 到点捕获、仅控制内部的源时间延迟补偿;
预测朝向不能宣布完成,仍要求实测估计朝向/角速度满足条件。共享控制器补偿与扩展转速开关默认关闭,未启用实车。
坡道阶段源年龄 >0.14 s 先短时等待,及时恢复可从零指令再加速;>0.23 s 仍锁存失败。
没有提高物理驱动的 4 m/s² 夹限或放宽 0.50 s 断流判据来获得通过。28 项任务测试与 3 项控制器 launch 测试通过。
证据与开发失败记录见 [快模式索引](validation/20261112_ramp_fast.json)、[说明](RAMP_MISSION.md#10-20-秒目标的独立快模式)。
两轮计时余量约 0.5 s,不保证任意负载都 ≤20 s;未覆盖高速导航阶段全部故障、动态障碍或实车动力学。
新增 `ramp_mission.launch.py`:默认起点 (-4.5,4.5,0.15,0) → 三个 SCAN 接近航点 →
坡前对准 → 固定中心线闭环上坡 → 全车进入平台并停稳。直道中间停车点已取消。
共享 SCAN 修正远目标转向包络“未完整入图”与碰撞的混淆,以及短段初始轨迹的终点采样/时间估计;
没有复制算法或引入实车 Gazebo 依赖,Point-LIO 滤波算法和实车默认参数未修改。
默认 `autostart=false`,可用 start 服务;加 `autostart:=true` 会初始化后自动行驶。
NAV 0.6 m/s、坡中 0.7 m/s、坡顶 0.2 m/s、转向上限 0.8 rad/s,临近停车点再降速。
首版 0.5/0.1 m/s 的 63.26/64.54 s 证据保留为历史,提速版另行归档,不能混成同一轮结果。
最终版 `log/codex_ramp_mission_r2_20261112/*_v2/`:ideal/mild 各 21/21 PASS,48.86/52.20 s;
下雷达、任务进程、选择器故障分别 0.337/0.331/0.356 s 内停稳,坡上箱体检测停车通过。
22 项任务单元测试和 12 个规划测试目标通过;全套 13 项中的旧实车启动偏移断言失败仍如实保留。
完整数据索引见 [提速版验收](validation/20261112_ramp_mission_r2.json)。
两个新节点:`ramp_mission.py` 发布短租约和坡道指令;`mission_command_mux.py` 是唯一 `/cmd_vel` 发布者。
原控制器改由新入口重映射到私有导航指令,租约及来源超时输出零。新入口底盘前超时 0.15 s,旧入口默认 0.5 s 不变。
下雷达断流、任务进程卡住、选择器卡住和坡上箱体均有独立故障实测;故障用例从明确对准位姿生成,不充当全程测试。
数据恢复不自动解除 FAILED。用法与证据见 [RAMP_MISSION.md](RAMP_MISSION.md)。新任务仍受 6 cm 地表过滤、已知路线和简化动力学限制,未迁移实车。
后续交互运行复现下雷达原始消息延迟至 0.199 s,触发了旧 0.18 s 看门狗;当前改为 0.23 s,
新增健康失败分项快照和近未来点云等 `/clock` 的处理。此前的 `_v2` 数据对应 0.18 s 旧版,
后续 GUI/RViz 证据单列于 [上坡感知保护诊断](RAMP_MISSION.md#9-带界面上坡时的感知保护停车后续修正)。
单改原始看门狗后的轻量复测又捕获融合点云 0.301 s 过期;进一步修正 Point-LIO 的纳秒截断
和融合器两种浮点时间转换不一致造成的扫描末点覆盖等待。滤波算法与原始扫描时间字段不变。
当前任务还开启可选的实际帧末里程计补发(Point-LIO 默认关闭),避免 100 Hz 中间发布限频省略帧末状态。
实际规划支路使用可靠、深度 1 的点云传输;双雷达就绪依据实际规划副本,不附加显示点云新鲜度。
当前感知修正版证据见 [验收索引](validation/20261112_ramp_health.json):带 Gazebo/RViz 的完整路线
ideal/mild 分别为 49.70/51.20 s,全车进入平台并停稳;ideal 原报告只因发现接口返回 depth=0
被评分器误判,原 FAIL 保留,另有仅纠正可靠传输判据的离线复核;运行时队列深度未验证。
下雷达断流 12/12 PASS、0.482 s 停稳,恢复数据不自行开走;距 0.50 s 限值只有 18 ms,
不作为全部注入相位/负载的保证。单雷达原入口直达回归 10/10 PASS、误差 5.20 cm。
25 项任务、18 项融合、19 项适配器单元测试通过;两次轻量观察只计诊断,其中一次约 78 s,
不作为物理/性能验收。任务进程/选择器故障及坡上障碍仍沿用旧版记录,本轮未重跑;未上实车。
本轮未 commit、未 push,保留此前工作区改动。
此前 2026-11-10:双雷达已接通专用坡道入口,红、蓝两侧整轮各 4/4 通过(上下坡、台阶拒绝、坡边拒绝)。
上坡以 yaw=π 使下雷达朝向坡顶;同朝向下坡为倒车,不提供后向低位补盲。
限速 0.15 m/s,保留 3 cm 横向偏离标准、4 cm 完整车体空隙和 0.50 s 断流停车标准;
红侧下雷达断流 0.44 s 停稳并恢复,蓝侧最终规划支路断流 0.15 s 停稳并恢复。
step_blocker 增加默认关闭的元数据保留模式,实际点不改,先验以 sensor_id=255、无采样时刻、零长度占据射线表达。
双雷达坡道最终云年龄采用 0.30 s,原单雷达坡道仍为 0.20 s,平地/实车默认参数不改。
入口、边界和本轮证据见 [DUAL_TERRAIN.md](DUAL_TERRAIN.md),本轮未提交、未 push。
15 cm 水平箱、8 cm 贴坡箱的选中回波完整保留及目标拒绝通过;水平 8 cm 箱仅保留 118/119 点,
严格保留项 FAIL(目标拒绝仍通过),不能推广为所有 ≤10 cm 低障碍可靠。平地前向回归 13/13 通过。
此前北侧修复:双雷达北侧长走廊曾将定位漂移后的地面误判为障碍,已改为在原始车体系按名义地面高度过滤。
用户的 `(3.5,4.8)` 目标已在两次全新启动中首次通过,到点误差约 6.3 cm、最小保守间隙 ≥14.28 cm;
8 cm 低障碍和原侧向回归通过,下雷达断流 0.34 s 停稳。完整证据及重启要求见 [NORTH_CORRIDOR.md](NORTH_CORRIDOR.md)。
未改实车入口、规划/控制算法或 9 cm 裕度;本次仅针对双雷达平地支路,未将此前全部路线重新运行。
2026-11-10 新增可选双 MID360:`scan_lio.launch.py dual_lidar:=true`。下光心离地 0.194 m、
前移到水平中心 X=0.325 m、yaw=+π/2;上雷达独立定位,下雷达仅在障碍支路取车前 180°。
前向箱体补盲/绕行与下雷达单独断流停车已通过 `log/codex_dual_mid360_20261110/integration_r6/` 的 12 项检查。
斜侧向旧轮位遮挡已完成隔离对照,当前模型的左右侧向、两条较宽位置斜向和前向共五条路线通过;
已修复先于 `/clock` 到达的里程计/点云被丢弃的问题。没有放宽时间门限或缩小车体。
旋转包络、负对照及未通过记录见 [DUAL_SAFETY.md](DUAL_SAFETY.md)。
**不保证从未观测区域的全向低障碍安全通行,也没有迁移实车双雷达 launch。**
最初双雷达适配没有修改 Point-LIO;后续时间戳序列化修正见上方。SCAN 增加默认关闭的逐点射线起点读取,原实车默认配置不动。
本次双雷达和前一次尺寸校准均尚未提交,没有 push。
2026-11-10 按用户实测更新车体包络与传感器安装位置,当前坐标及本轮独立回归见
[VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md):平地导航 4/4、红侧坡道 4/4、接触底盘 9/9,
传感器/坐标/独立定位及九组低障碍边界均已重新实测通过。下方 2026-11-08 验收表是旧尺寸历史基线,不能当作新尺寸全量复测。
用户已授权 Codex 直接调查、修改、构建、运行和验收;当前未安排 DeepSeek 并行修改。
同日新增授权清理旧方案,覆盖旧交接中“旧源码与工具一律不得删除”的限制。
本轮用户明确授权更新 README 并 git commit;push 由用户执行。
2026-11-08 新增授权清理旧方案,覆盖旧交接中“旧源码与工具一律不得删除”的限制。
此前用户授权更新 README 并 git commit,对应收尾已完成;push 由用户执行。
本次尺寸校准尚未提交,也未 push。
该收尾已提交为 664eaa8。后续用户使用中发现中断自动测试遗留进程、阻塞重启的问题,
另作修复与实测,见 RESTART.md。用户随后授权将重启修复、--gui 选项及使用/迁移指南一并提交;
提交哈希以 git log 为准,push 仍由用户执行。入门操作优先阅读 USER_GUIDE.md。
@@ -47,7 +119,8 @@ P6 平地估计导航入口与证据见 `P6_NAVIGATION.md`。
- 仿真覆盖位于 `src/br_sim_bringup`,实车算法包不依赖 Gazebo。
- `r2027_robot_description` 使用原生 SDF、单刚体;默认 planar_move,坡道入口显式选择 contact。
contact 仅施加水平力与世界 Z 力矩,重力/接触决定高度与倾斜;不模拟真实轮组牵引与打滑。
- 质量 10.31 kg、质心、惯量、雷达安装均为模型假设,不是现场测量结果。
- 车体 0.80×0.80×0.41 m、光心前移 0.015 m、离地 0.48 m 来自用户测量。
base_link 名义离地 0.15 m;质量 10.31 kg、组合质心/惯量、底部间隙和安装旋转仍为模型假设。
- 机器人运动与世界点云由 Gazebo 真值和精确时间 TF 得到,未伪造 Point-LIO 字段。
这描述原真值入口;新 scan_lio 入口仅用传感器、Point-LIO 和固定已知起点先验,真值只进独立评价器。
- 平地入口 80 cm 车体、9 cm 裕度、0.01 rad 朝向容差;坡道入口单独采用 4 cm 裕度、0.3 m/s 上限。
@@ -62,11 +135,11 @@ P6 平地估计导航入口与证据见 `P6_NAVIGATION.md`。
- `mid360_sim.launch.py with_lio:=true` 是独立评估入口,暂不启动 SCAN。
射线真实每 1 ms 采样,100 ms 打包;扫描图案为明确标注的近似,通道为软件分组。
默认 ideal 无注入噪声;可选 mild/stress 径向白噪声、丢点及物理 IMU 白噪声/固定偏置,不模拟材质。
IMU 由原生 ImuSensor 求解,姿态标记不可用;内置偏置来自官方手册,整机安装高度仍是假设。
IMU 由原生 ImuSensor 求解,姿态标记不可用;内置偏置来自官方手册,整机安装位置已按用户测量更新,旋转仍为假设。
- 原 Livox CMake 新增默认 OFF 的 LIVOX_INTERFACES_ONLY;仅在仿真安装前缀设 ON,未安装硬件 SDK。
原 Point-LIO 只修改构建依赖(直接 PCL、显式 glog),没有修改滤波器,实车配置不动。
最初 Point-LIO 接入只修改构建依赖(直接 PCL、显式 glog);后续时间序列化与可选帧末发布修正见上方,没有修改滤波器,实车默认配置不动。
源码输入为 /sim/mid360/lidar 与 /sim/mid360/imu;真值只进入独立评价工具。
- Point-LIO 输出属于 camera_init、参考点是 IMU 原点;与 base_link 相差 (0.011,0.02329,0.25588) m。
- Point-LIO 输出属于 camera_init、参考点是 IMU 原点;与 base_link 相差 (0.026,0.02329,0.28588) m。
不得仅重命名 frame 或 topic 就替换 /body_odom。估计 TF 消息关闭,原 broadcaster 仍创建 /tf 发布端。
- 共享 Sim.start 修复模型生成竞态:端口与 clock 就绪后,还必须观察 spawn_entity 成功才允许查询/置位。
- 新 `lio_navigation_adapter.py` 将 IMU 原点估计转到车体中心,处理固定 world 对齐与配对去畸变点云,
@@ -95,7 +168,7 @@ P6 平地估计导航入口与证据见 `P6_NAVIGATION.md`。
2. 本机默认 `GAZEBO_MASTER_URI=http://127.0.0.1:11355`、`ROS_DOMAIN_ID=77`、`ROS_LOCALHOST_ONLY=1`。
跨机显式设置 ROS_LOCALHOST_ONLY=0;机器人入口尊重域/本地范围环境变量。
3. 只有一个 gzserver;官方 init/factory SystemPlugin 各一次,不使用 ros_gz_bridge。
4. world→odom 单位静态;odom→base_link 插件发布;base_link→lidar 静态 z=0.30。
4. world→odom 单位静态;odom→base_link 插件发布;base_link→lidar 静态 (0.015,0,0.330) m。
5. Odometry pose 属 header.frame_id,twist 属 child_frame_id;不能重命名 frame 冒充坐标变换。
6. 节点显式 use_sim_time;机器人入口时钟配置 100 Hz,场地历史基线 10 Hz。
7. 暂停时 Classic 不发布新时钟;暂停服务返回成功还需真值和时钟冻结证据。
+116
View File
@@ -0,0 +1,116 @@
# 双雷达北侧走廊:地面误判修复(2026-11-10)
适用入口:`ros2 launch br_sim_bringup scan_lio.launch.py dual_lidar:=true`。
本轮修复的是双雷达平地融合支路;没有修改 Point-LIO、SCAN 的规划实现或实车 launch。
## 用户问题与复现
从默认起点 (−4.5, 4.5),向 `(3.5, 4.8, 0.15)` 发 world 系目标,朝向 yaw=0。
旧版本会在 x≈−2.1 m 附近停住,局部规划反复失败,10 s 后 BLOCKED 超时;
重复发送同一目标仍然失败。证据:`log/codex_north_corridor_20261110/baseline/`,有效 FAIL,退出码 30。
用户命令正确。日志里的 `goal: 1.28 ...` 是约 3.5 m 规划视距生成的局部中间目标,
不是把最终目标从 3.5 改成了 1.28。任务状态仍保留最终 X/Y=(3.5, 4.8)。
平地目标 Z 由初始运动参考高度设置,实测接近 0.15 m。
当前地图中,北侧台阶/坡道外缘最远到 Y=4.0 m,外侧围墙内面为 Y=5.5 m,
这段走廊净宽约 1.5 m。它不是早期 P5 人工生成的 1.2 m 通道。
本次车头约沿 +X,80 cm 方形车体与既有安全裕度具有通行空间。
## 根因
旧双雷达规划云按固定条件 `world_z <= 0.015 m` 删除地面点。
Point-LIO 的估计高度发生漂移后,同一片真实地面被变换到高于这条过滤线的位置,
少量地面点于是被写进占用地图,并被正常的车体膨胀扩成阻塞区域。
复现中,静止后的实际 `base_link` 高度约 0.14899 m,估计高度约 0.16908 m;
一帧地面点最高约 0.01582 m,已经超过旧门限。
在确认没有真实障碍的条带 X∈(−2.8,2.0)、Y∈(4.35,5.2) 内,
地图最多出现 24 个 Z=0.025 m 的假地面占用体素。
这是定位误差与过滤参考系不匹配,并非目标未送达或消息不新鲜。
后来有些地面点重新低于门限,也不会因为重新发目标而清空已经留下的体素地图。
所以重复目标不能修复这一问题,延长 BLOCKED 超时也无助于消除根因。
## 处理方法与边界
地面分类改在原始雷达点经过安装外参、进入**车体系**之后进行,随后才使用估计位姿变换到 world:
```text
base_link 名义离地高度 = 0.150 m
地面高度带 = 0.015 m
地面条件:point_in_base.z <= -0.150 + 0.015 = -0.135 m
```
`base_link` 是已有的运动参考点,不是 41 cm 高车体的几何中心。
配置在 `br_sim_bringup/config/dual_lidar.yaml`,分别为 `nominal_base_height` 和 `ground_tolerance`。
沿用同样的 1.5 cm 地面高度带,没有靠提高世界高度门限吞掉低障碍。
- 世界系完整融合云仍保留所有原始变换结果,能继续观察定位漂移;没有压平点云 Z 或修正成真值。
- 只在规划副本中将地面点 XYZ 置 NaN,原采样时间、每点光心起点、设备 ID 保持不变。
- 两颗雷达使用各自安装位置/旋转后得到的同一车体参考系;下雷达前 180° 的裁剪规则不变。
- 车体 0.80×0.80 m、单边 0.09 m 规划裕度、朝向约束、数据年龄与断流停车门限均未改动。
这是**已知平地、当前简化车体保持水平**的过滤规则,不是任意地形的地面分割算法。
不能直接用于明显俯仰/侧倾、坡道、台阶或未知悬崖;双雷达坡道入口仍未适配。
单雷达支路的地面规则本轮没有修改,也没有将本轮长路线结果扩大为单雷达长距离验收。
实车迁移前仍须按实车参考点、安装外参与姿态变化单独验证。
## 新取得的验收证据
所有用例分别新启动仿真,不改生产地图,不注入驱动/停车指令。
使用独立实体查询验收到点停车,使用接触插件 100 Hz WorldPose 检查沿途包络并与查询交叉核对。
真值只供测试使用,未接入定位、融合、规划或控制。
| 用例 | 结果 | 测量 |
|---|---|---|
| 原目标,全新启动 1:`verified_1/` | 13/13 PASS,首次目标到达 | 到点误差 6.33 cm;走廊间隙保守界 ≥15.02 cm;37.25 s 仿真时间 |
| 原目标,全新启动 2:`verified_2/` | 13/13 PASS,首次目标到达 | 到点误差 6.30 cm;走廊间隙保守界 ≥14.28 cm;36.81 s 仿真时间 |
| 8 cm 箱体前向补盲:`low_obstacle_regression/` | 13/13 PASS | 箱体占用、内部目标拒绝、绕行均通过;下雷达断流后 0.34 s 停稳 |
| 原斜侧向箱体路线:`side_regression/` | 12/12 PASS | 包络间隙保守界 ≥23.57 cm;本例明确只验收导航,不重复执行断流用例 |
另有初版修复后的 `body_ground/` 到点通过;它未包含后来增加的完整走廊包络验收,不并入上述两次正式复测。
修复后在同一空地条带中未再观察到假地面占用。
走廊包络验收将 Y=4.0 的障碍边缘保守延伸至 X∈[−3,3],按实际 yaw 的 80 cm 方形包络计算,
并减去两次真值采样之间半个最大角点位移。它依赖采样间的线性位置/最短 yaw 插值,
不是任意连续动力学的形式化证明。实际真值采样最大间隔为 0.020 s,实体查询交叉核对误差 <0.3 mm。
单元回归共 43 项通过:双雷达 16、通视/旋转包络 7、适配器 17、启动查询 3。
新增测试包含正/负世界高度漂移、姿态估计误差,以及两颗雷达的 2 cm/8 cm 障碍顶面保留。
**2 cm 顶面保留是输入数据分类测试,不是 2 cm 障碍的实机或完整导航验收。**
原始证据目录:`sim_ws/log/codex_north_corridor_20261110/`。
每轮有实际目标、消息图、轨迹、命令、点云/地图快照、估计与物理位姿、源码哈希和清理结果。
结构化汇总见 [本轮摘要](validation/20261110_north_corridor.json)。
没有拍 GUI 截图,没有修改外部场地资源,没有 commit 或 push。
## 用户重新测试
本机已经构建。**先完整关闭旧的 `scan_lio.launch.py`,再启动整套入口**,让旧体素地图随规划节点一起重建。
只重发目标或只重启融合节点,可能继续保留之前的假占用。
```bash
cd ~/RC2027_BR_code
source /opt/ros/humble/setup.bash
source sim_ws/install/classic/setup.bash
export ROS_DOMAIN_ID=77 ROS_LOCALHOST_ONLY=1
export GAZEBO_MASTER_URI=http://127.0.0.1:11355
ros2 launch br_sim_bringup scan_lio.launch.py dual_lidar:=true
```
另一个同样加载环境的终端,等 `/planning/perception_ready` 为 true 后发原命令一次:
```bash
ros2 topic pub --once --wait-matching-subscriptions 2 --keep-alive 1 \
/move_base_simple/goal geometry_msgs/msg/PoseStamped \
'{header: {frame_id: world}, pose: {position: {x: 3.5, y: 4.8, z: 0.15}, orientation: {w: 1.0}}}'
```
自动复现工具会自行启动和结束仿真,不与手动 launch 同时运行:
```bash
/usr/bin/python3 sim_ws/tools/check_lio_corridor.py --out sim_ws/log/north_corridor_manual
```
默认就是上述起点、目标和双雷达模式。`--repeat 2` 只在失败后再次发送同目标,
用于复现用户现象;正式通过记录要求首次目标成功。
+3
View File
@@ -1,5 +1,8 @@
# 简化全向机器人验收(Codex 接管复测,2026-11-08)
> 2026-11-10 已校准实车尺寸与雷达位置,当前参数及新回归见 [VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md)。
> 本文 2026-11-08 的测量与验收表保留为历史证据。
在已验收的 Classic 完整场地上加入简化全向机器人,验证**车体系 `/cmd_vel` → 实际运动 → 里程计 →
停止行为**这条链路。本文原轮次不开导航、不接传感器、不验证爬坡。
后续新增可选 `drive:=contact`,默认仍为 planar;坡道验收见 [P5 坡道](P5_SLOPE.md)。
+11 -7
View File
@@ -1,5 +1,8 @@
# 三维点云与 SCAN 真值导航(2026-11-08)
> 2026-11-10 已校准实车尺寸与雷达位置,当前参数及新回归见 [VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md)。
> 本文 2026-11-08 的测量与验收表保留为历史证据。
用户已授权 Codex 直接实现、构建和运行。本轮仍使用完整比赛场地与 Gazebo Classic,
不启动真实雷达、Point-LIO、串口桥。算法来自原有 `minco_ws/src/scan`,没有复制第二套实现。
@@ -38,14 +41,14 @@
该轮保存采集工具启动时的 SHA256 与源码快照。各次测试结束后均确认 11355 端口释放,未杀其他进程。
P3 当前为通用瞬时三维射线雷达:CPU `ray`,720×32,水平 360°、垂直 ±30°,
0.15–20 m、10 Hz;位于 `base_link` 上方 0.30 m,姿态相同。
这是仿真安装假设,尚未代表实际雷达型号与安装外参。没有扫描畸变、IMU、ring 或逐点时间字段,
0.15–20 m、10 Hz;位于 `base_link`+(0.015,0,0.330) m,姿态相同。
位置已按实测光心离地 0.48 m 校准,但通用扫描模式尚未代表 MID360 型号,安装旋转仍是假设。没有扫描畸变、IMU、ring 或逐点时间字段,
不满足 Point-LIO 验收条件。CPU 射线不依赖 GPU 雷达渲染,图形设备未确认仍不阻塞本轮。
## 接口和参考点
单位 m/s/rad,右手系 Z 向上;地图保持原始世界坐标(红 +Y,蓝 −Y)。
机器人根与 `base_link` 同为箱体中心,落稳 z≈0.148987 m,平地 z=0。
机器人根与 `base_link` 同为水平中心的运动参考点,名义离地 0.15 m,平地 z=0。
| 话题 | 类型 | 语义 |
|---|---|---|
@@ -53,7 +56,7 @@ P3 当前为通用瞬时三维射线雷达:CPU `ray`,720×32,水平 360°
| `/cloud_registered` | 同上 | world 系,按原始时间戳查 TF 后变换;保留其他字段与时间戳 |
| `/cloud_registered_for_scan` | 同上 | 世界点云的导航支路;近零地面和车体自身回波的 XYZ 置 NaN,其他点不变 |
| `/odom` | `nav_msgs/msg/Odometry` | Gazebo 插件真值;pose 属 odom,twist 属 base_link |
| `/body_odom` | 同上 | world 系箱体中心 pose,base_link 系 twist |
| `/body_odom` | 同上 | world 系运动参考点 pose,base_link 系 twist |
| `/aft_mapped_to_init` | 同上 | world 系雷达 pose,lidar 系 twist;由真值与安装变换计算 |
| `/move_base_simple/goal` | `geometry_msgs/msg/PoseStamped` | world 系目标位置与有效目标四元数 |
| `/cmd_vel` | `geometry_msgs/msg/Twist` | 现有闭环控制器输出,车体系 vx/vy/wz |
@@ -61,7 +64,7 @@ P3 当前为通用瞬时三维射线雷达:CPU `ray`,720×32,水平 360°
| `/planning/perception_ready` | `std_msgs/msg/Bool` | 根据真实新鲜数据持续发布,失效时停止放行 |
TF:`world→odom` 单位静态,`odom→base_link` 由唯一运动插件动态发布,
`base_link→lidar` 静态 (0,0,0.30),无重复边。
`base_link→lidar` 静态 (0.015,0,0.330),无重复边。
适配器确认 world→odom 确实为单位变换后才生成世界里程计;改变该契约会拒绝样本。
雷达原始 stamp 不可用时等待精确时间 TF,超过 2 s 丢弃并告警;不回退到最新 TF。
@@ -84,7 +87,8 @@ P5 平地参数已全量重跑四条 P4 路线,4/4 PASS;证据在
地图下界 −0.1 m 和矩形模式。真实雷达/实车参数文件保持原样,实车包不依赖 Gazebo。
导航支路按完全相同的 stamp 和点索引配对原始/世界点云,以原始 lidar 系坐标移除车体包围盒回波:
`|x|,|y|≤0.42`、`−0.47≤z≤−0.20` m(安装偏移 0.30 m,车体 z∈[−0.15,0.08],2 cm 数值裕度)。
先加光心偏移 (0.015,0,0.330) m 转到车体系,再判断 `|x|,|y|≤0.42`、
`−0.17≤z≤0.28` m(整车局部 z∈[−0.15,0.26],2 cm 数值裕度)。
不使用最新位姿近似自过滤,未配对的样本不放行;原始/完整世界云不变。
地面过滤为世界 z≤0.015 m,不增加虚构障碍或补造感知字段。外围 4 cm 矮围栏仍有回波保留。
控制器停车窗收紧到 0.06 m,位于原规划器 0.08 m 完成窗内,给不同节点的里程计回调留余量。
@@ -92,7 +96,7 @@ P5 平地参数已全量重跑四条 P4 路线,4/4 PASS;证据在
**本入口限制平地**:`scan_sim.launch.py` 没有坡面通行处理;不要向台阶或坡面下发目标。
后续坡道专用入口、已知地形先验、参考路径高度与接触驱动见 [P5 坡道](P5_SLOPE.md)。
坡道工作对原 SCAN/控制器新增默认关闭的 `terrain_motion` 分支;本文平地入口保持原默认行为。
质量、轮组和雷达安装仍为简化模型假设;真值闭环通过不等于 Point-LIO 通过。
质量、轮组和雷达安装旋转仍为简化模型假设;真值闭环通过不等于 Point-LIO 通过。
P6 已另建 MID360 兼容传感器与原 Point-LIO 的独立评估入口,见 [P6 定位说明](P6_LOCALIZATION.md);
本文导航入口仍使用真值,没有自动切换定位源。
+6 -1
View File
@@ -1,5 +1,10 @@
# P5 窄通道与地形边界(2026-11-08)
> 2026-11-10 已校准实车尺寸与雷达位置,当前参数及新回归见 [VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md)。
> 本文 2026-11-08 的测量与验收表保留为历史证据。
> 当前双 MID360 + Point-LIO 在生产场地北侧约 1.5 m 走廊的通行及地面误判修复,另见 [NORTH_CORRIDOR.md](NORTH_CORRIDOR.md)。
> 它与本文临时生成的 1.2 m 通道是不同用例,不能互相替代验收。
本文记录完整比赛场地中的平地导航扩展;后续坡道工作另见 [P5 坡道](P5_SLOPE.md)。
本文中的拒绝测试仍使用平地入口,不代表坡道入口拒绝同一路线。全场通行性尚未验收。
继续使用同一份 SCAN/闭环控制实现、80 cm 方形简化车体、Gazebo Classic 和真值定位。
@@ -34,7 +39,7 @@ y∈[2.5,4.0],通道中心 x=−4.5 m。每例全新启动、结束清理,
同样要求在新鲜感知下拒绝并静止。这只确认所测目标,非全场地形防护或坡道通行验收。
全部采用独立 Gazebo 真值;不靠控制器里程计自证运动,不注入零指令帮助停车。
参考点仍为箱体中心 base_link;单位 m/s/rad,world 坐标与时间约定同 P3/P4。
参考点仍为 base_link 运动参考点(名义离地 0.15 m);单位 m/s/rad,world 坐标与时间约定同 P3/P4。
## 已取得证据
+5 -2
View File
@@ -1,5 +1,8 @@
# P5 坡道:接触物理与 SCAN 闭环(2026-11-08)
> 2026-11-10 已校准实车尺寸与雷达位置,当前参数及新回归见 [VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md)。
> 本文 2026-11-08 的测量与验收表保留为历史证据。
本阶段验证完整 Classic 场地上的红、蓝坡道与顶部落脚区;复用原有 SCAN 和闭环控制器。
定位仍为 Gazebo 真值,雷达仍为通用三维瞬时射线模型。MID360、IMU、逐点时间与 Point-LIO
属于后续 P6,本阶段没有用伪造字段绕过它们。
@@ -8,7 +11,7 @@
坡道宽 1 m、水平长 3.5 m、高 0.597 m,世界 X 从 −0.8 到 2.7;
红侧 Y∈[3,4],蓝侧 Y∈[−4,−3],坡度 atan(0.597/3.5)≈0.16894 rad。
箱体中心 base_link 为参考点;平地落稳 Z≈0.148987 m,顶部落脚区表面 Z=0.600 m。
base_link 运动参考点(名义离地 0.15 m)为参考点;平地落稳 Z≈0.148987 m,顶部落脚区表面 Z=0.600 m。
原 `ramp.obj` 的 8 个三角面全部朝内,有向体积 −1.04475 m³。
在同一驱动下原圆柱支撑进坡失败,改球形支撑也失败;仅反转网格面索引后,原圆柱支撑完成
@@ -63,7 +66,7 @@
默认红侧中心 Y=3.5125 m,蓝侧 Y=−3.5125 m;名义车体两边最小空隙各 8.75 cm。
这是低速真值模型的专用配置,不能据此缩小实车安全裕度。
坐标与时间不变:米/秒/弧度、Z 向上;world→odom 为单位静态,base_link→lidar 为 Z=0.30 m。
坐标与时间不变:米/秒/弧度、Z 向上;world→odom 为单位静态,base_link→lidar 为 (0.015,0,0.330) m(2026-11-10 校准)。
各节点显式使用仿真时间,机器人入口 `/clock` 配置 100 Hz、odom 配置 50 Hz。
## 验收证据
+4
View File
@@ -1,5 +1,8 @@
# P6:LIO 指定坡道导航验收(2026-11-08)
2026-11-10 新增显式双雷达坡道选项,见 [DUAL_TERRAIN.md](DUAL_TERRAIN.md)。
本页旧轮次数据均为单雷达证据,不能作为双雷达通过的依据;省略 `dual_lidar` 仍为单雷达。
独立入口 `scan_lio_terrain.launch.py` 复用 Point-LIO、SCAN、闭环控制器、接触驱动和 step_blocker。
本文件原“最终验收”表是此前理想模式基线。本轮参数与复测更新见文末及 RELEASE_VALIDATION.md。
原真值坡道入口、LIO 平地入口和实车参数不变。当前结论以本文件后续验收表为准,构建成功不能作为导航通过。
@@ -85,6 +88,7 @@ ros2 launch br_sim_bringup scan_lio_terrain.launch.py
```bash
ros2 run scan_planner reference_path_publisher.py --ros-args \
-p use_sim_time:=true -p frame_id:=world \
-p odom_topic:=/sim/navigation/body_odom -p path_topic:=/initial_path \
-p 'waypoints:=[3.5,3.5125,0.0,2.7,3.5125,0.0,-0.8,3.5125,0.597,-1.2,3.5125,0.6]'
```
+5 -3
View File
@@ -41,10 +41,12 @@ Gazebo IMU 具体语义核对了官方
## 坐标、时间与话题
仍为米/秒/弧度、右手系 Z 向上,完整 Classic 场地和 contact 驱动;质量与车体假设不变。
`lidar` 光学原点位于 base_link 上方 0.30 m,轴向一致,这是仿真安装假设,非实车测量。
仍为米/秒/弧度、右手系 Z 向上,完整 Classic 场地和 contact 驱动。
2026-11-10 按实测更新为 0.80×0.80×0.41 m 车体、光心前移 0.015 m、离地 0.48 m;
`base_link` 仍为名义离地 0.15 m 的运动参考点,光心相对它为 (0.015,0,0.330) m。
轴向一致仍是假设;本页旧轮次误差为历史基线,当前回归见 [尺寸校准](VEHICLE_GEOMETRY.md)。
按上述手册,IMU 在光学系的位置为 (0.011,0.02329,−0.04412) m,轴向相同;
因此 base_link→mid360_imu 平移为 (0.011,0.02329,0.25588) m。
因此 base_link→mid360_imu 平移为 (0.026,0.02329,0.28588) m。
Point-LIO 的光学到 IMU 外参为 (−0.011,−0.02329,+0.04412) m、单位旋转,方向不能颠倒。
| 话题 | 类型 | 语义 |
+5 -3
View File
@@ -16,7 +16,8 @@ Point-LIO 只订阅 `/sim/mid360/lidar`、`/sim/mid360/imu` 和时钟。
目标的高度使用既定 0.15 m,不从真值查询结果生成导航输入。
出生参数 x/y/z/yaw 同时给出**已知起点先验**,默认 (−4.5,4.5,0.15,0)。
适配器观察 LIO 连续静止 1 s(至少 20 个样本,速度/角速度<0.02、位置变化<2 cm)后,
适配器观察 LIO 连续静止 1 s(至少 20 个样本,窗口平均线速度范数<0.02 m/s、
各样本角速度范数<0.02 rad/s、相对末样本位置变化<2 cm)后,
用该先验和当时的一份估计计算固定 camera_init→world 变换。
这不是全局重定位,也不是持续真值纠偏;启动时必须确实处于所声明的已知平地起点。
该变换锁定后不再调整,不通过贴地、改 frame_id 或回环拟合掩盖后续误差。
@@ -27,8 +28,9 @@ Point-LIO 只订阅 `/sim/mid360/lidar`、`/sim/mid360/imu` 和时钟。
## 车体参考点与点云
当前模型的 IMU 相对 base_link 偏置 r_BI=(0.011,0.02329,0.25588) m,
光学原点 r_BL=(0,0,0.30) m,各轴平行。整机安装仍是仿真假设,内置偏置见 P6_LOCALIZATION.md。
2026-11-10 实测尺寸校准后,IMU 相对 base_link 偏置 r_BI=(0.026,0.02329,0.28588) m,
光学原点 r_BL=(0.015,0,0.330) m,各轴平行仍是假设;内置偏置未变。
尺寸来源与本轮复测见 [VEHICLE_GEOMETRY.md](VEHICLE_GEOMETRY.md);本页旧轮次数字保留为历史基线。
给定固定 R_WC/t_WC、LIO 的 p_CI/R_CI 与 IMU 系速度 v_I/ω_I:
+431
View File
@@ -0,0 +1,431 @@
# 导航接近、专用上坡与平台停车
本入口自动完成:**默认起点 → 北侧通道 → 坡前对准 → 上坡 → 平台停车**。
上坡阶段采用固定中心线、航向和横向闭环,结合姿态变化判断进入坡道与恢复水平;
不使用 SCAN 的上坡轨迹,也不会把“倾角回零”直接当成任务成功。
Point-LIO 定位与双雷达感知全程继续工作。此版本针对当前已知地图的红侧坡道,尚未迁移实车。
## 1. 直接运行
先关闭其他 Gazebo/导航入口,从仓库根目录加载公共环境:
```bash
cd ~/RC2027_BR_code
source /opt/ros/humble/setup.bash
source sim_ws/install/classic/setup.bash
export ROS_DOMAIN_ID=77 ROS_LOCALHOST_ONLY=1
export GAZEBO_MASTER_URI=http://127.0.0.1:11355
```
**下面的命令会在感知初始化完成后自动行驶,全程不用另发目标点或参考路径:**
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true
```
默认打开 Gazebo 和 RViz,启动双 MID360、上雷达 Point-LIO、SCAN 接近段与任务控制。
双雷达是本入口的必需配置,不需要再加 `dual_lidar:=true`。
巡航参数 `nav_speed` 默认 0.6 m/s,`ramp_speed` 默认 0.7 m/s;原地转向上限
`yaw_speed` 默认 0.8 rad/s,坡顶段 `crest_speed` 默认 0.2 m/s,接近停车点时进一步降低。
这些是仿真指令上限,不表示全程恒速或实车已验证速度。上坡加减速仍限制为 0.4 m/s²。
第一次体验也可以降低速度:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true nav_speed:=0.3 ramp_speed:=0.3
```
若希望先观察初始化,再手动开始:
```bash
# 终端一;autostart 默认 false
ros2 launch br_sim_bringup ramp_mission.launch.py
# 终端二;先加载相同公共环境
ros2 service call /ramp_mission/start std_srvs/srv/Trigger '{}'
```
开始请求可以在初始化期间提交;初始化门控满足后才行驶。
不要同时运行旧的 `scan_lio.launch.py`、`scan_lio_terrain.launch.py`,也不要再单独发送导航目标。
需要更新源码后的完整构建方法仍是 `bash sim_ws/tools/build_sim.sh`。
## 2. 观察与停止
```bash
ros2 topic echo /mission/status std_msgs/msg/String --full-length
```
正常状态顺序:
```text
IDLE → NAVIGATE → ENTRY → CLIMB → CREST → PLATFORM → SETTLE → SUCCEEDED
```
- `NAVIGATE`:SCAN 依次完成接近航点。
- `ENTRY`:车已在坡前停稳并对准,改由专用控制前进。
- `CLIMB`:连续观测到上坡俯仰,进入坡中巡航。
- `CREST`:预计坡顶前提前减速。
- `PLATFORM`:已经上过坡,位置和连续水平姿态共同确认平台阶段,继续低速清出车尾。
- `SETTLE`:估计完整车体进入平台停车区,持续零速并核实位置和速度稳定。
- `SUCCEEDED`:停车确认完成,持续保持零输出。
- `FAILED`:发生异常,保持停止,不自动恢复行驶。
中途停止:
```bash
ros2 service call /ramp_mission/cancel std_srvs/srv/Trigger '{}'
```
这是单次任务。取消或失败后,即使传感器恢复,也不会自行再跑。
重新体验时关闭整个本入口、重新启动,机器人会重新生成在默认起点。
不要拖动车体、重置世界后继续沿用原定位;已知起点对齐只在初始化时锁定一次。
## 3. 本地图的坐标与停车条件
长度米、角度弧度,world Z 向上,X 前/Y 左/Z 上为车体坐标。
默认起点为 world (-4.5,4.5,0.15),yaw=0。
接近航点为 (3.7,4.8)、(3.7,4.0)、(3.7,3.5125),最后转到 yaw=π。
直道不再设置 (-0.5,4.8) 停车点。拐角、坡前对准仍会按要求减速停稳。
远处目标转向范围尚未全部进入滑动地图时,保留目标并继续检查局部路径;
只有完整转向范围明确可通行才授予实际转向。已知障碍仍拒绝,未知空间不授权执行。
对准阶段使用紧于原体验入口的 1.5 cm 估计到点距离和 0.01 rad 终点朝向容差。
随后沿 y=3.5125 的中心线朝 −X 上坡,车体系 vx 为正,并持续控制 yaw 与横向偏差。
坡脚为 x=2.7、坡顶为 x=-0.8,升高 0.597 m,坡度约 9.68°。
上坡触发采用相对坡前基准约 −4° 的持续俯仰;平台触发要求已经进入过上坡,
位于坡顶之后、相对俯仰约 ±2° 内、俯仰角速度较低,并持续 0.15 s。
MID360 原始 IMU 没有有效 orientation。本实现使用 Point-LIO 的估计车体姿态,
原始 IMU 只用于角速度及数据新鲜度,不能把默认四元数当作水平姿态。
名义 `base_link` 高度仍为离地 0.15 m,车体包络仍为 0.80×0.80×0.41 m。
平台地面约 z=0.6,停车参考点约 z=0.75,目标车体参考位置为 (-1.30,3.5125)。
坡顶后的窄平台为 x∈[-1.8,-0.8];要求完整旋转车体包络留有 4 cm 前后及侧向余量。
因此恢复水平之后还会低速前进一段,而非立即停车、把车尾留在坡上。
停车确认使用一段成熟的估计位置/速度窗口,同时要求位置稳定、平均线速度接近零和低角速度,
再持续确认 0.6 s。单次小速度读数或水平倾角均不能单独触发成功。
## 4. 指令交接与保护
```text
原闭环控制器 → /mission/navigation_cmd_vel ┐
├→ mission_command_mux → /cmd_vel
专用坡道控制 → /mission/ramp_cmd_vel ┘ ↓
现有超时保护 → /sim/cmd_vel
```
只有 `mission_command_mux` 发布最终 `/cmd_vel`。原闭环控制器被本入口单独重映射,
上坡时即使它仍输出,也不会与坡道指令争抢底盘。
任务以短期租约选择 NAV/RAMP/STOP;来源切换清掉旧指令,失效或不匹配的输入输出零速。
任务进程卡住时租约过期停车;选择器卡住时底盘前的独立超时保护停车。
本入口的超时参数为 0.15 s,旧入口默认仍为 0.5 s。
本次保留完整 80 cm 车体。SCAN 接近段维持 9 cm 裕度;专用坡道段以实际估计包络、
已知坡道边界和额外定位预算检查侧向空间,并用独立物理评分要求至少 4 cm 实际空隙。
对准失败、未在预计范围检测到坡面、横向空间不足、异常倾斜、状态/感知过期及前方障碍均会停止任务。
坡顶前的减速由预计位置触发,按当前速度、0.4 m/s² 减速度和 0.10 s 跟踪预算提前制动,
在 x=-0.25 的坡顶低速区前降到 0.2 m/s。倾角事件用于确认阶段,不延迟到恢复水平才开始制动。
接近 (-1.30,3.5125) 停车参考点时再进一步减速,避免把 0.2 m/s 保持到停车瞬间。
可显式给出速度,允许 `nav_speed` 0.1–0.6、`ramp_speed` 0.1–0.7、
`crest_speed` 0.03–0.2 m/s(不大于坡中速度),`yaw_speed` 0.1–1.0 rad/s:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true \
nav_speed:=0.6 ramp_speed:=0.7 yaw_speed:=0.8 crest_speed:=0.2
```
限幅已贯通控制器、指令选择器与接触驱动插件;其他入口的执行器默认仍为 0.5 m/s、0.5 rad/s。
前方障碍检查使用保留逐点时间和光心的双雷达规划副本,不把已知禁行先验当作传感器回波。
检测走廊覆盖车体宽度,并包含反应时间与制动距离预算。
下雷达另有原始扫描看门狗:取本帧真实末点的采集时间,超过 0.23 s 未更新就停止任务;
不把接收时刻当作采集时刻,不虚填点时间,不等待融合点云的 0.30 s 窗口才发现下雷达断流。
`/mission/status` 的 `source_age_s` 可查看下雷达、融合点云和 IMU 的源数据年龄。
若出现 `perception_or_state_stale`,查看同一消息的 `health_failure`:
`failed_checks` 指出失败项,`sources` 给出故障瞬间的源时间、数据年龄和阈值;
`ready_flag` 表示上游感知是否就绪。这份快照在恢复数据后仍保留,日志也会输出 `Health stop in ...`。
**既有 6 cm 地表过滤带的低障碍限制仍然存在**,不能据此保证所有 ≤10 cm 障碍或无回波区域安全。
失败后不绕过保护继续直行,也不静默退回单雷达。
## 5. 自动复测
工具会自行启动、收尾仿真。不要和手动仿真并行,每次使用新输出目录:
```bash
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --out sim_ws/log/ramp_mission_manual
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --sensor-profile mild --out sim_ws/log/ramp_mission_mild_manual
```
默认无界面;加 `--gui` 显示 Gazebo。整轮不由评分器发送速度或移动机器人,
Gazebo 真值只用于核对轨迹、完整车体包络、接触和停车,算法输入仍是估计状态。
故障复测从明确生成的坡前对准位姿启动,以节省重复接近时间;**不能计作默认起点的全程验收**:
```bash
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --aligned-start --fault lower_loss --out sim_ws/log/mission_lower_loss_manual
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --aligned-start --fault mission_loss --out sim_ws/log/mission_process_loss_manual
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --aligned-start --fault mux_loss --out sim_ws/log/mission_mux_loss_manual
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --aligned-start --fault obstacle --out sim_ws/log/mission_obstacle_manual
```
下雷达用例验证上雷达继续、停止下雷达、停车、恢复数据后仍不自行行驶。
进程用例仅暂停本工具拥有的相应 PID,测完后终止,不恢复运动;不扫描杀死其他用户进程。
障碍用例在真实场地里生成 0.25×0.25×0.30 m 静态箱,要求检测后停车且没有碰到箱体。
退出码 0/30/40 分别为通过、有效失败、采集无效;单元测试不能替代这些运行时证据。
## 6. 使用范围
这是已知红侧路线的仿真实现,不是任意场地的寻坡程序。现有单雷达、普通双雷达和平地/坡道体验入口保留。
质量、支撑轮和驱动力仍是简化模型;高速轮组打滑、真实摩擦、实车倾角标定、刹车能力未据此验收。
实车迁移前需核对底盘速度闭环与零速保持、外参、时钟和故障停止,再逐级提速。
本次不把仿真提速结果直接当作实车速度建议。
## 7. 首版验收结果(旧速度,保留历史)
原始数据在 `log/codex_ramp_mission_20261112/`,机读索引和源码哈希见
[validation/20261112_ramp_mission.json](validation/20261112_ramp_mission.json)。
两个完整任务均从默认起点重新生成机器人;故障用例各自独立启动、从明确对准位姿生成。
该历史索引记录首版三个控制源码哈希,后续提速版源码已有变化;未将不同版本数据拼成同一整轮。
| 用例 | 结果 |
|---|---|
| `final/`,ideal 完整任务 | 16/16 PASS,63.26 s;坡中完整车体最小采样空隙 7.54 cm、最大横向偏离 0.93 cm;最终参考点约 (-1.332,3.503,0.749) m,全车进入平台并停稳 |
| `final_mild/`,mild 完整任务 | 16/16 PASS,64.54 s;最小采样空隙 7.66 cm、最大横向偏离 0.97 cm;最终约 (-1.320,3.507,0.749) m |
| 北侧接近段 | 两次整轮的采样间保守间隙界约 14.62/14.64 cm;使用位置/最短姿态插值和半步角点运动余量,不称为连续真值保证 |
| 全程接触 | 只接触 ground、ramp_north、顶层平台 Cube.005,未接触场地围栏;最大接触穿透约 1.04 mm,低于 5 mm 判据 |
| `lower_restore/` | 单独停止下雷达,上雷达继续;0.449 s 内停稳。恢复数据后感知重新就绪,任务保持 FAILED 和零输出,不自动行驶 |
| `mission_loss_final/` | 暂停任务进程,选择器识别租约过期,0.271 s 内停稳 |
| `mux_loss/` | 暂停速度选择器,独立底盘前超时保护持续零输出,0.292 s 内停稳 |
| `obstacle_final/` | 真实生成 30 cm 高箱体;检测后停止任务,未接触箱体,未通过写入已知障碍点来冒充感知 |
| 原单雷达入口回归 | `legacy_straight/`,原直达路线通过,到点误差 5.95 cm;没有重跑全部历史路线 |
| 单元/接口 | 17/17 PASS,包含租约、来源选择、线速度合成限幅、阶段历史、恢复不自启动及真实 ROS start/cancel 服务调用 |
任务时间按首次 NAVIGATE 到 SUCCEEDED 的事件源时间计算,不包含 Gazebo 加载、定位初始化及额外停车观测。
首轮保守配置 `handoff/` 同一任务通过,耗时 107.64 s;提高巡航速度并调整末段接近参数后约 63–65 s,
首版实测缩短约 40%。这不是全局最短时间证明;后续提速复测单独记录。
早期报告的 `elapsed_sim_s` 包含约 1.3 s 以上终态后观测,索引以原始事件重新计算,原报告不改写。
保留的调试记录:`initial/` 未找到可执行脚本,记 INVALID,随后补全执行位;
`prototype/` 因远目标转向扫过范围超出滑动地图而 FAIL,改用短接近航点;
`short_goals/` 在查明一次性终态结果被错误按 ACTIVE 租约过期处理后,终止了本工具拥有的测试,
该目录没有完整报告,不计通过。随后修正终态事件处理并增加回归测试。
`fast/`、`fast_mild/`、早期故障测试均保留,最终结果使用上表明确列出的目录。
没有新增截图、GUI/显卡验收、真实轮组测试、实车双雷达迁移或双机测试。
## 8. 直道停车、BLOCKED 与提速修复(2026-11-12 第二轮)
本轮区分了三件事:
1. 直道 (-0.5,4.8) 原本就是“到点停稳再交接”的航点,现取消,直道使用单个远目标。
2. 远目标的中心已入图、完整转向包络仍出图时,原布尔检查把它和真实碰撞一起拒绝。
新增转向占用三态 0/1/-1(完整可通行/碰撞/范围未完整入图),全局目标遇 -1 可保留,
局部执行端点和真正转向授权仍必须为 0。窄道转向碰墙的拒绝测试继续保留。
3. 提速后复现短距离目标加速度不可行:初始多项式没有采到真正终点,却固定了提前采样的
非零终端加速度。现改为包含端点的均匀采样,并取真正终点加速度;短距离三角速度
时间估计补全加速、减速两段。没有放宽动力学验收阈值或略过碰撞检查。
共享修改在 `minco_ws/src/scan/plan_env` 的转向查询和 `plan_manage` 的目标验证、初始轨迹取样;
没有复制规划器,没有给实车包增加 Gazebo 依赖。实车参数、Point-LIO 算法与原始场地模型未修改。
最终默认值是直道 0.6、坡中 0.7、坡顶 0.2 m/s,转向 0.8 rad/s。
曾试验直道 0.7 m/s,在当时版本上短段规划失败,未作为本轮交付默认值。
原始记录位于 `log/codex_ramp_mission_r2_20261112/`,失败目录 `ideal/`、`feasibility/`、
`nav06/` 和修复试跑 `endpoint_fix/` 均保留;它们不能与最终版拼接成同一轮通过。
`final_ideal/`、`final_mild/` 是加入原始扫描看门狗之前的通过记录;随后 `lower_loss/`
实测 0.502 s 停稳,按 0.50 s 判据记 FAIL,不能四舍五入写通过。加入看门狗后重新测试,
最终版使用下述带 `_v2` 的独立完整记录。
全套规划测试的 13 个测试项中,`test_test_rectangle_launch.py` 有一项既有实车启动偏移断言失败:
旧测试期待非矩形模式 body_offset_x=-0.015,当前启动文件给出 0.0。
该测试及 `vehicle_bringup.launch.py` 与本轮开始时 HEAD 一致,本轮未修改它们;
完整输出保留在 `log/ramp_r2_planner_all_tests.log`。不将此全套结果写为全通过。
最终版证据索引:[validation/20261112_ramp_mission_r2.json](validation/20261112_ramp_mission_r2.json)。
每个用例独立启动、收尾仿真;索引校验 11 个控制/模型/规划源码的哈希和评分器哈希,
并记录已安装规划器、控制器及接触驱动产物的哈希。
| 最终用例 | 本轮结果 |
|---|---|
| `final_ideal_v2/`,默认起点完整路线 | 21/21 PASS;48.86 s,直道中段未测到停车;坡中最小完整包络采样空隙 7.08 cm、最大横向偏差 1.28 cm,全车进入平台并停稳 |
| `final_mild_v2/`,轻度噪声完整路线 | 21/21 PASS;52.20 s,直道中段未测到停车;最小采样空隙 7.60 cm、最大横向偏差 0.90 cm,全车进入平台并停稳 |
| 速度与接触 | 两轮实际峰值:直道约 0.597、坡中 0.698 m/s、转向 0.791 rad/s;坡顶约 0.197–0.199 m/s;最大接触穿透约 1.04 mm,没有围栏接触 |
| `lower_loss_v2/` | 10/10 PASS;0.337 s 内停稳,上雷达继续、下雷达停止;恢复下雷达后保持 FAILED 和零输出 |
| `mission_loss_v2/` | 8/8 PASS;暂停本工具拥有的任务进程,租约过期停车,0.331 s 内停稳 |
| `mux_loss_v2/` | 8/8 PASS;暂停本工具拥有的指令选择器,独立超时保护停车,0.356 s 内停稳 |
| `obstacle_v2/` | 7/7 PASS;真实生成 30 cm 高箱体,检测后停车,未接触箱体 |
| `legacy_straight/` | 原单雷达平地入口直达回归 10/10 PASS,到点误差 5.33 cm;没有重跑所有旧路线 |
| 单元与规划回归 | 22 项任务单元/接口测试通过;12 个规划测试目标通过,含真实 FSM 的短距离终端加速度、远目标未完整入图及窄道禁止转向回归;另有上述既有实车启动断言失败 |
与首版 63.26/64.54 s 相比,这两轮约缩短 19%–23%。整段计时包括必要的拐角/对准停车和
最终停稳确认,不含启动初始化及终态后额外观察;噪声下停稳确认可能花更久,不为缩短计时删除确认。
两轮健康运行时下雷达原始扫描源年龄均明显小于 0.18 s;融合链路仍可能超过 0.25 s,
因此保留原有 0.30 s 融合窗口,由独立原始扫描看门狗及时发现断流。
这些结果只覆盖本页路线和明确的故障用例,不宣称任何 BLOCKED 都应继续行驶,也不是实车高速验收。
## 9. 带界面上坡时的感知保护停车(后续修正)
上一轮 0.18 s 下雷达看门狗在交互运行中暴露了过紧问题。按默认同时开启 Gazebo、RViz,
用仅监听状态的轻量观察器复现:`ENTRY` 开始约 2.3 s 后,下雷达末点源时间年龄达到
0.199 s,超过 0.180 s;其余检查仍通过(定位 0.104 s、IMU 0.003 s、融合点云 0.299 s,
`ready_flag=true`),所以任务主动停止并保持 FAILED。随后数据恢复,任务没有自动行驶。
该次记录在 `log/codex_ramp_health_20261112/lightweight_2/diagnostic.json`。
10 Hz 原始扫描的帧间隔为 0.1 s,单帧未及时送达任务节点会接近 0.2 s。
将原始扫描看门狗设为 0.23 s,为本次捕获的 0.199 s 延迟留余量;这不保证任意负载下的延迟都能被容忍。
定位、IMU、融合点云门限与失败锁存不变。
这个现场现象定位到“任务节点未及时收到原始扫描”;DDS 丢帧和回调调度延迟尚未做底层隔离,
不将它写成激光器硬件故障或 Point-LIO 崩溃。用户原日志没有分项快照,不能倒推原次运行的确切超时项。
另外补齐融合点云的仿真时钟排队:近未来消息先等待 `/clock`,使用原始源时间;
已过期的旧点云不能由队列中的未来消息续命。没有用接收时间重打点云时间戳。
单独将原始看门狗放到 0.23 s 的试跑 `fixed_light_1/` 又在融合点云年龄 0.301 s 时失败,
该记录保留。继续定位到两处时间表示问题:Point-LIO 浮点秒转 ROS 时间向下截断,可能把真实
扫描末点写成少 1 ns 的时间;融合器的里程计用 `sec+nanosec*1e-9`,扫描点用完整纳秒乘 `1e-9`,
两种浮点计算也可能差一个最低有效位。严格的位姿覆盖检查会因此继续等下一批里程计。
修正为 Point-LIO 按最近纳秒转换并正常处理跨秒进位;融合器将里程计、扫描点统一从完整整数纳秒转换。
Point-LIO 的滤波计算、外参、原始雷达 timebase/offset_time 均未修改;不通过外推姿态或伪造点时间来配准。
6000 个扫描末点回归中,旧方法有 1391 个截断偏差,新方法全部精确匹配,另验证 3 个跨秒/边界用例;
双雷达测试覆盖了恰好位于扫描末点的位姿必须立即满足覆盖,不能额外等一帧。
融合点云 0.30 s、定位 0.20 s、IMU 0.10 s 和感知就绪门限均未放宽。
时间修正后的 `rounded_light_2/` 还捕获到就绪信号撤销,而定位、IMU、原始扫描和融合点云均新鲜。
适配器原来同时检查上雷达配准点云(0.25 s)和最终规划点云(0.30 s)。双雷达模式的规划器
消费的是后者,上雷达配准点云只用于独立显示,因此显示支路会额外撤销导航就绪。
现在配置了外部规划支路时,按该支路和估计里程计判断就绪;单雷达模式仍检查自己的配准点云。
无效定位、实际规划点云断流仍撤销就绪。就绪变化时立即发布分项状态,便于还原短暂失败。
里程计订阅使用可靠、深度 100 的队列承接 Point-LIO 成批发布;下游点云等待 `/clock`,
融合器也等待时钟追上扫描末点后再发布。原始采集时间与逐点射线起点保持不变。
进一步的 `final_gui_ideal/` 记录中,融合副本源年龄 0.258 s 时,实际规划支路的源年龄曾达
0.318 s,适配器正确撤销了就绪;这项物理评分记 FAIL,未算最终通过。
本入口将融合规划点云 → 禁行区域附加 → SCAN/适配器的控制链统一为可靠传输、队列深度 1,
任务节点也可靠订阅融合规划副本。自动评分核对这两条话题上所有控制端点的身份和可靠传输属性。
本机发现接口返回的队列深度全部为 0,因此不能用它证明实际深度;深度 1 仅由归档源码配置确认。
显示点云与其他入口的默认传输配置保持原样;原始扫描仍保留真实采集时间。
还有一处实际等待来自里程计限频:100 Hz 中间状态最后可能发布在扫描末点前约 9 ms,
融合器保持不外推,只能等待下一帧状态覆盖这 9 ms。当前任务打开
`odometry.publish_scan_end`:每帧处理完成后,补发滤波器实际最后处理状态及其 `time_current`,
相同时间不重复发布;不把较早状态改标为 `lidar_end_time`。该参数在 Point-LIO 默认关闭,
仅本任务入口通过 `lio_scan_end_odom:=true` 开启。其余实车/旧入口的默认发布策略不变。
评分器查询真实节点参数确认开关已生效;独立时间回归同时验证帧末补发、去重和后续限频。
本轮证据索引:[validation/20261112_ramp_health.json](validation/20261112_ramp_health.json)。
原始数据在 `log/codex_ramp_health_20261112/`;18 个控制/模型/规划源码均记录哈希。
| 当前版本用例 | 结果与范围 |
|---|---|
| `scanend_gui_ideal/`,Gazebo + RViz,默认起点完整路线 | 49.70 s;运动/定位/接触等其余 22 项通过。原报告因错误要求发现接口返回 depth=1 而记 FAIL;保留原文件,另用 `qos_reassessment.json` 从原始端点证据纠正可靠传输判据后为 23/23 PASS,未重跑物理测试 |
| `scanend_gui_mild/`,Gazebo + RViz,轻度噪声完整路线 | 23/23 PASS,51.20 s |
| 两轮运动与包络 | 直道中段未测到停车;实测直道约 0.597、坡中 0.698、坡顶 0.199 m/s,转向约 0.791 rad/s;坡中最小全车包络采样间隙分别为 6.81/7.78 cm,最终全车进入平台并停稳 |
| `scanend_gui_loss/`,明确对准起点的下雷达断流 | 12/12 PASS,注入后 0.482 s 停稳;恢复雷达后保持 FAILED 和零输出。距 0.50 s 限值余量只有 18 ms,仅代表本次注入时刻与负载,不作为所有相位的最坏时间保证 |
| `legacy_straight/`,原单雷达平地入口 | 直达回归 10/10 PASS,到点误差 5.20 cm;未重跑其余旧路线 |
| 单元与时间回归 | 25 项任务、18 项融合、19 项适配器测试通过;6000 个时间端点、3 个边界及 5 个帧末发布/限频断言通过 |
两次最终版轻量观察均报告 SUCCEEDED,但不含独立物理验收;其中一次耗时约 78 s,保留为
诊断记录,不宣称任意运行都能在约 50 s 内完成。此前各次超时失败和两次未实际注入的 INVALID
记录均保留,不拼接为通过。任务/选择器进程故障及坡上障碍测试仍是第 8 节旧版本证据,本轮未重跑。
带 Gazebo、RViz 的自动评分可使用:
```bash
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --gui --with-rviz \
--out sim_ws/log/ramp_mission_gui_manual
```
断流验证记录注入时最近原始帧的真实源数据年龄,停稳标准仍为 0.50 s:
```bash
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --gui --with-rviz \
--aligned-start --fault lower_loss \
--out sim_ws/log/ramp_mission_gui_loss_manual
```
本次验收只覆盖已知路线的正常运行、轻度噪声、下雷达断流停车和原单雷达入口的一条直达回归。
短暂延迟的容许量与真实断流的停车时间需要一起衡量,不能只把门限不断收紧,也不能为避免误停而取消保护。
当前超出门限仍会停车并锁存 FAILED,不自动恢复运动。
仿真不能保证实车 100% 成功;实车应先低速核对外参、驱动方向及刹车距离,再逐步提速。
## 10. 20 秒目标的独立快模式
原命令仍使用 `profile:=standard`。在相同公共环境下,快模式单独启用:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py profile:=fast autostart:=true
```
计时从感知初始化后任务进入 `NAVIGATE` 开始,到**整车进入平台、零输出且停稳确认完成**的
`SUCCEEDED` 结束。计时使用 `/clock` 仿真时间,包含路径生成、交接和停车确认;不含 Gazebo
启动、Point-LIO 初始化时间。笔记本上的墙钟耗时还受实时因子影响,不能直接当作实车成绩。
| 参数或行为 | 标准模式 | 快模式 |
|---|---|---|
| 直道 / 坡中指令上限 | 0.6 / 0.7 m/s | 2.5 / 1.1 m/s |
| 原地转向上限 | 0.8 rad/s | 2.0 rad/s |
| SCAN 规划加速度上限 | 0.6 m/s² | 3.0 m/s² |
| 坡道指令加减速 | 0.4 m/s² | 2.0 m/s² |
| 目标位置捕获容差 | 1.5 cm | 2.5 cm |
| 停稳观测历史窗口 | 0.5 s | 0.35 s,仍检查位置范围、平均速度和角速度,之后另作停稳确认 |
| 坡前航点 | 三个航点,逐点停车 | 接近末端提前替换目标,合并一次横移停车,最终仍停稳掉头 |
| 局部地图 Y 全宽 | 3 m | 6 m,覆盖横移目标及转向包络 |
| 控制延迟补偿 | 关闭 | 仅控制内部按新鲜估计速度预测,最长 0.20 s |
快模式在约 x≥3.0、y 接近 4.8 时替换接近目标,仍由 SCAN 生成并授权下一条轨迹;
不是沿未检查的直线直接切向坡脚。9 cm 规划裕度、转向包络、坡道横向保护和整车平台边界保留。
到点容差调整是为避免掉头时微小定位波动解除到位锁存,导致控制器先回原朝向、再掉头。
控制内部预测不改写里程计、TF 或点云时间;终点朝向完成仍要求真实收到的估计朝向与角速度满足条件,
不能凭预测值提前宣布完成。共享控制器的新增补偿与扩展转速开关均默认关闭,实车入口未启用。
**减速位置也发生了变化。** 标准低速目标区从 base x=-0.25 开始;快模式改为 base x=-0.90,
此时车头已上平台,车尾仍在清坡。快模式提前按剩余距离制动,但不要求在几何坡顶前很远就已经
降到 0.2 m/s;接近最终停车点再降速。评分分别记录此位置约定,并在 x∈[-1.15,-1.02] 检查
快模式实际低速。需要原来的减速位置和速度范围时使用标准模式。
快模式坡道阶段增加**短时数据等待**:下雷达末点源年龄超过 0.14 s 时先输出零速度、保留当前阶段;
数据及时恢复且其余状态仍健康,才从零指令重新加速。源年龄超过 0.23 s 或其余健康条件不满足时,
仍锁存 FAILED,数据恢复不自行启动。`/mission/status` 的 `waiting_lower_scan` 和事件
`lower_scan_hold` 可区分短时等待与真正失败。这不是把数据时间戳刷新为接收时刻。
实验中的坡中 1.4 m/s 曾测得下雷达断流后 0.565 s 停稳,按 0.50 s 原标准记 FAIL。
当前快模式将坡中上限收回 1.1 m/s,并提前等待迟到扫描,未放宽 0.50 s 判据,也未提高物理驱动的
4 m/s² 加速度夹限来获得更好成绩。高直道速度下的所有故障时刻尚未覆盖,不把坡上单次断流结果推广到全程。
独立评分命令(输出目录须不存在):
```bash
/usr/bin/python3 sim_ws/tools/check_ramp_mission.py --profile fast --gui --with-rviz \
--out sim_ws/log/my_fast_ramp
```
快模式附加 `within_20_seconds` 判据,只有真正 `SUCCEEDED` 且不超过 20 s 才能通过;
19.95 s 与 20.12 s 不会因为四舍五入被归为同一种结果。物理查询与连续真值仍交叉对照:
快模式在原 2 mm 空间残差之外,按查询速度计入一个已配置的 1 ms 物理步长行程作为异步采样时相界,
同时保留原始最大差、额外界和扣除后的残差;标准模式原判据不变。这项调整不放宽车体间隙或穿透标准。
本模式复用简化接触驱动和传感器模型。上述限速不表示实车可达到这些速度、加速度或制动效果;
实车串口限幅、轮组动力学及高速定位能力需单独验证,不能直接拷贝此配置。
本轮当前版本证据索引:[validation/20261112_ramp_fast.json](validation/20261112_ramp_fast.json)。
日志根目录 `log/codex_ramp_fast_20261112/`,每轮独立启动、收尾,归档源码与评分器哈希。
| 当前版本用例 | 实测结果 |
|---|---|
| `final_v3_ideal/`,Gazebo + RViz,默认起点完整路线 | **24/24 PASS,19.42 s**;整车进入平台并停稳;坡道最小完整包络采样间隙 7.67 cm,最大横向偏差 0.84 cm |
| `final_v3_mild/`,Gazebo + RViz,轻度噪声完整路线 | **24/24 PASS,19.46 s**;最小间隙 8.14 cm,最大横向偏差 0.59 cm |
| 两轮运动 | 直道峰值约 2.497、坡中 1.098 m/s,转向峰值约 1.991 rad/s,平台低速采样区约 0.198 m/s;直道中段未测到停车,两轮均未触发短时数据等待 |
| `final_v3_loss/`,明确对准起点的坡上下雷达断流 | **12/12 PASS,0.416 s 停稳**;先短时等待,继续过期后锁存 FAILED;恢复数据后保持零输出 |
| `final_v3_standard/`,默认标准模式完整路线回归 | **23/23 PASS,49.11 s**;原三航点、限速、减速区和停稳策略保持原配置 |
| 控制相关测试 | 28 项任务/接口测试通过;3 项真实控制器 launch 测试通过,覆盖原轨迹反馈、矩形包络授权、源时间补偿/制动及“预测到位不能代替实测到位” |
上述两轮分别只剩 0.58/0.54 s 的时间余量,**不是任何笔记本负载下每次都能 ≤20 s 的保证**。
本轮未对快模式的所有导航阶段断流、动态障碍、任务/选择器进程故障逐项重测。
开发过程的失败和无效采集均保留并列入索引,不能与当前版本混为一轮:曾出现 20.12/20.13 s
超时、掉头时到位锁存失效导致额外转圈、1.4 m/s 下断流 0.565 s 超标;`trial_8/` 虽记录任务
19.72 s 成功,但 GUI 进程被终止后独立评分未完成,记 INVALID;`capture_ideal/`、
`capture_mild/`、`capture_loss/` 是工具误启动重叠、被端口占用保护拒绝的 INVALID,未杀占用者。
它们都不是当前版本通过证据。此前 QoS/时间修正及旧版标准模式证据仍按第 8、9 节保留。
+8 -1
View File
@@ -57,7 +57,9 @@ ros2 launch br_sim_bringup scan_lio_terrain.launch.py sensor_profile:=mild
/usr/bin/python3 sim_ws/tools/check_low_obstacles.py --out sim_ws/log/low_obstacles_manual
```
静止理想传感器、当前约 0.449 m 光学高度与 −7° 最低视角下,
以下为 2026-11-08 的旧尺寸观测(约 0.449 m 光学高度、−7° 最低视角)。
2026-11-10 改为名义离地 0.48 m,当前低障碍复测见 [尺寸校准](VEHICLE_GEOMETRY.md)。
静止理想传感器下,
依次生成独立可查询、可删除的实体箱体,采集实际回波,不驱车撞击来证明不可见。
每个箱体有唯一名称,删除后通过 GetEntityState 确认消失,避免 Gazebo 异步删除重名竞态。
@@ -66,6 +68,11 @@ ros2 launch br_sim_bringup scan_lio_terrain.launch.py sensor_profile:=mild
计算视场必须考虑箱体远端,不能把整个箱体当作中心点。
可见点不等于已验证绕障;坡道 profile 的 6 cm 地面过滤还会进一步限制低障碍保留。
2026-11-10 已用新光心高度重新运行九组箱体测试,9/9 符合独立视场预期。
其中 **8 cm / 3 m 改为 0 回波**;15 cm / 3 m、30 cm / 1.5 m、60 cm / 1.5 m 分别有
65、84、1672 个回波(各 14 帧),其他六组均无回波。几何、实体查询和删除证据见
`log/codex_measured_geometry_20261110/low_obstacles/`,当前摘要见 [尺寸校准](VEHICLE_GEOMETRY.md)。
此测试通过表示**边界已如实测量**,不表示低障碍避让已经实现。
任意未知低障碍需要额外近地/深度感知或可靠场地先验;当前单 MID360 模型无法凭空补足盲区。
+44 -3
View File
@@ -37,9 +37,16 @@ flowchart LR
| 消息 | 原 Livox CustomMsg 与 sensor_msgs/Imu,输入原 Point-LIO |
| 扫描与噪声 | 扫描轨迹为近似;默认 ideal 无注入噪声,mild/stress 为工程压力配置 |
这不是厂家精确扫描轨迹或实车噪声标定。当前雷达整机安装位置也是仿真假设。
光心位置采用用户提供的实车尺寸;扫描轨迹、车架细节和噪声仍是仿真近似。
单 MID360 存在近地视场盲区,部分低障碍没有回波;不能据此承诺未知低障碍避让。
当前实车新加的下雷达对应可选双雷达模式:完成下节构建和环境加载后,运行
`ros2 launch br_sim_bringup scan_lio.launch.py dual_lidar:=true`。
下雷达光心离地 19.4 cm、自身 +X 朝车左;软件按车体方向取前方 180°,上雷达继续定位。
原命令省略参数时仍用单雷达。具体结构、低障碍测试与实车迁移前提见
[双 MID360 补盲指南](DUAL_MID360.md)。
斜侧向代理遮挡的处理、自动回归命令和使用边界见 [斜侧向诊断与回归](DUAL_SAFETY.md)。
## 2. 准备环境与构建
本机已完成构建,可以直接进入第 3 节。换机器或修改源码后,在仓库根目录执行:
@@ -78,7 +85,7 @@ ROS 域 77 用于本机仿真,11355 是本项目的 Gazebo master 端口。
| `spawn_entity` 报 `No module named 'numpy'`,或脚本行为异常 | `export PATH=/usr/bin:$PATH`。本机 PATH 中 Python 3.13 排在前面,rclpy/numpy 只装在系统 3.10 下 |
| gzserver 立即退出,报 `X Error ... GLX ... X_GLXCreateContext` | 无桌面时先 `unset DISPLAY`。指向不可用 X 服务器的 `DISPLAY` 会让 gzserver 在渲染初始化处崩溃,`gui:=false` 并不能规避 |
| 启动报「Gazebo 端口 11355 已被占用」,但 `ps` 看不到占用进程 | 换端口:`export BR_SIM_MASTER_PORT=11801 GAZEBO_MASTER_URI=http://127.0.0.1:11801`(需与 launch 一致,所有终端同值) |
| 机器人一直不出现,规划器只打印 `no odom.` | 场地加载约需 20 s。机器人在等待 `spawn_delay`(默认 20 s)后才生成;若仍失败,用 `spawn_delay:=30` 放大 |
| 机器人一直不出现,规划器只打印 `no odom.` | 检查场地是否加载完成,查看 `spawn_existing_world` 的服务查询/生成日志;当前入口按服务就绪生成机器人,不按固定 20 s 延迟生成 |
`spawn_delay` 是 `robocon_robot.launch.py` 的 launch 参数,可直接在 `scan_lio.launch.py`
之后传 `spawn_delay:=30`(该入口已转发给机器人 launch)。
@@ -161,6 +168,25 @@ ros2 topic pub --once --wait-matching-subscriptions 2 --keep-alive 1 \
X 和朝向不变、Y 减少 1 m,机器人应基本保持车头朝向并横移。
世界坐标中 Z 向上、红方 +Y、蓝方 −Y;所有距离用米、角度用弧度。
### 3.6 自动导航到坡脚、上坡并停在平台
先关闭其他仿真入口,再运行:
```bash
ros2 launch br_sim_bringup ramp_mission.launch.py autostart:=true
```
本入口会从默认起点自动行驶,不用另发目标点或参考路径。导航到坡前后切换固定中心线控制,
保持航向和横向纠偏,坡顶前减速;倾角恢复水平且完整车体进入平台、停车稳定后才报成功。
默认直道 0.6 m/s、坡中 0.7 m/s、原地转向上限 0.8 rad/s,坡顶段 0.2 m/s,
接近平台停车点再减速。直道中途不再设置停车航点;拐角与坡前对准仍需停稳。
取消方式、各阶段含义和验收范围见 [分段上坡任务](RAMP_MISSION.md)。
这是仿真任务入口,原实车 launch 不会自动启用它。
需要尝试 20 秒目标时,可在上述命令后追加 `profile:=fast`。这会启用独立的仿真提速配置,
包含更高的直道/转向速度和调整后的平台低速段;先读
[快模式的参数与验收结果](RAMP_MISSION.md#10-20-秒目标的独立快模式)。实车迁移时须重新确认底盘能力和制动距离。
## 4. 自动测试:让脚本自己跑
自动脚本会自行启动 Gazebo、发送目标、评分并关闭仿真。**先关闭第 3 节手动启动的程序**,
@@ -247,6 +273,7 @@ ros2 topic hz /sim/mid360/imu
| data=true,但发目标没反应 | 看 trajectory_status 的本次 goal_id/state/reason;确认目标确实收到 |
| 等待两个订阅端不结束 | 完整 scan_lio 入口是否还运行;两个终端是否都使用 ROS_DOMAIN_ID=77 |
| 状态为 FAILED | 保存 reason;可能是目标占用、通道不足或规划失败,不能直接归因于话题问题 |
| 双雷达在北侧约 x=−2.1 m 堵住,反复规划失败 | 已修复世界高度漂移造成的地面误占用。完整重启 `scan_lio.launch.py dual_lidar:=true` 后重新发原目标;诊断与测量见 [北侧走廊修复](NORTH_CORRIDOR.md) |
| perception_ready 一直 false | 查看 navigation/status、原始传感器频率和启动日志;确认未暂停 |
| navigation/status 为 fault | 先解决断流/时间/位姿问题,再从已知起点重启整套程序;不要挪车或强制发布 true |
| 关闭后重启提示端口占用 | 原仿真或自动测试还没结束,先按下列命令确认占用者 |
@@ -289,13 +316,25 @@ ros2 launch br_sim_bringup scan_lio_terrain.launch.py
```bash
ros2 run scan_planner reference_path_publisher.py --ros-args \
-p use_sim_time:=true -p frame_id:=world \
-p odom_topic:=/sim/navigation/body_odom -p path_topic:=/initial_path \
-p 'waypoints:=[3.5,3.5125,0.0,2.7,3.5125,0.0,-0.8,3.5125,0.597,-1.2,3.5125,0.6]'
```
**参考路径的 z 是地表高度**,规划器按本配置再加 0.15 m;与平地目标中车体参考高度不同。
`odom_topic` 必须指向仿真估计 `/sim/navigation/body_odom`;省略会等待实车默认 `/body_odom`,路径不会发出。
此入口依赖已知通行面和坡边禁行先验,4 cm 仿真裕度不作为实车默认裕度。
两侧坡道、低障碍过滤和适用范围见 [P6_LIO_TERRAIN.md](P6_LIO_TERRAIN.md)。
双雷达坡道在同一入口显式打开参数,并让车头朝向上坡的 −X:
```bash
ros2 launch br_sim_bringup scan_lio_terrain.launch.py dual_lidar:=true yaw:=3.141592653589793
```
仍发送上面的三维路径,限速 0.15 m/s。不要沿用双雷达平地的水平滤地配置。
原地倒车下坡时,下雷达仍只看车前,不能声称有后向低位覆盖;6 cm 坡面过滤带也不能认证所有
≤10 cm 的低障碍。详细证据及复现命令见 [双雷达坡道说明](DUAL_TERRAIN.md)。
只查看场地使用 `ros2 launch robocon_gazebo robocon_gazebo.launch.py`,它不会启动导航。
`scan_sim.launch.py` / `scan_terrain.launch.py` 是真值定位对照入口;当前主要开发使用 scan_lio 系列。
各入口互斥,不能为看场地而在已运行的整套导航之外再启动一个场地 server。
@@ -421,7 +460,9 @@ IMU 单位和 Point-LIO acc_norm 必须一致;仿真 SI 比力对应的配置
记录当前实车长宽高、规划碰撞参考点、雷达光心/IMU 相对该点的位置与完整朝向。
区分“传感器内部 LiDAR→IMU 外参”和“传感器安装到车体的外参”,米/弧度、方向和参考点都要明确。
仿真的 0.80 m 车体、0.30 m 雷达偏置、0.15 m 参考高度不是当前实车测量结论。
2026-11-10 已按用户测量更新仿真:车体 0.80×0.80×0.41 m,光心相对水平中心前移 0.015 m、左右居中、离地 0.48 m。
`base_link` 仍选在名义离地 0.15 m,因此光心相对它为 (0.015,0,0.330) m;目标高度约定不变。
安装旋转、质量、质心、底部间隙和轮组参数仍需测量;详见 [尺寸与外参](VEHICLE_GEOMETRY.md)。
分别检查小幅前进、横移、转向与停止,核对 ROS 的 X 前/Y 左/Z 上以及逆时针为正的约定。
串口桥当前配置含 omega_sign=-1 的历史实车方向适配;是否仍适用要随当前固件/接线验证。
+96
View File
@@ -0,0 +1,96 @@
# 实车尺寸与雷达安装校准(2026-11-10)
用户提供车体长宽各 80 cm、高 41 cm;MID360 光心相对车体水平中心前移 1.5 cm、左右居中,
**离地 48 cm**。48 cm 不以车体几何中心或 `base_link` 为起点。
新增下雷达的安装、前方 180° 裁剪和独立验收见 [双 MID360](DUAL_MID360.md)。
本页 0.48 m 安装与箱体几何记录仍描述单雷达基线。
## 当前坐标约定
单位为米、秒、弧度,X 前、Y 左、Z 上。表中位置为机器人在水平地面上、未考虑接触压入时的名义值。
| 项 | 当前值 | 来源 |
|---|---|---|
| 车体外包络 | 0.80 × 0.80 × 0.41 m | 用户测量;用含简化支撑轮的底盘/车体表示,不含雷达支架 |
| `base_link` | 水平中心,名义离地 0.15 m | 保留已有导航运动参考点;不是箱体几何中心 |
| 光心离地位置 | 水平中心前方 0.015 m,左右 0,离地 0.480 m | 用户测量 |
| `base_link→lidar` | (0.015, 0, 0.330) m | 0.480−0.150 |
| `lidar→mid360_imu` | (0.011, 0.02329, −0.04412) m | 保留既有传感器内部手册约定 |
| `base_link→mid360_imu` | (0.026, 0.02329, 0.28588) m | 两段平移相加 |
| 光学系、IMU 系相对车体系旋转 | 单位旋转 | 尚未实测,继续使用原假设 |
保持 `base_link` 的高度可避免把现有规划目标、参考路径与车体里程计整体改成另一套高度约定。
例如平地导航目标 z=0.15 m 仍表示运动参考点高度,不是车顶或光心高度。
坡道上应使用完整姿态旋转安装平移,不能继续给世界 Z 简单相加 0.33 m。
## 几何、物理与数据接口
原生 SDF 箱体上沿离地 0.41 m,下沿继续假设离地 0.07 m,箱体高 0.34 m;
箱体几何中心相对 `base_link` 的 z=0.09 m。四个简化支撑轮保持原尺寸与轮位,合入单刚体。
41 cm 用于底盘/车体高度;当前没有雷达外壳和支架实体,光心由传感器原点及 TF 表示。
这只校准车体外包络,不代表已经复现真实内部结构、底盘离地间隙或轮组物理。
总质量仍假设为 10.31 kg。按新几何重算组合质心 z=0.024820562561 m,
绕质心惯量对角项约 (0.842665751374, 0.853225751374, 1.465173333333) kg·m²;均不是实车测量。
求解器会有接触压入,实际落稳光心高度可比名义 0.48 m 低约毫米;不能用改 TF 掩盖。
已同步物理射线采样原点、原生 IMU 位置、静态 TF、真值数据适配、平地/坡道 LIO 外参与车体回波过滤。
Point-LIO 内部光学到 IMU 的 `extrinsic_T=(-0.011,-0.02329,+0.04412)` 未变,因为传感器内部关系未变。
`/clock`、每点真实采样时间、点云坐标系和速度语义沿用原约定,实车包配置未修改。
41 cm 箱体可能产生真实自身顶面回波。原始消息与完整世界点云保留这些点,
仅规划副本按新的车体范围过滤;没有伪造回波或绕过物理射线求交。
安装变高也会扩大近地盲区,旧高度下的低障碍可见性数据不应直接沿用。
本轮暴露 Point-LIO 静止速度的逐点抖动不断重置初始化的问题。适配器改为检验完整一秒窗口的
平均线速度范数<0.02 m/s,同时保留至少 20 个样本、相对末样本位置变化<2 cm、
各样本角速度范数<0.02 rad/s 的约束。固定起点仍只锁定一次,不引入真值或在线重对齐。
坡道回归还修复了入口拆分的配置遗漏:`mid360_sim.launch.py` 按“原 MID360 配置 →
通用仿真覆盖 → 可选坡道覆盖”加载,确保使用仿真时间和 `/sim/mid360/*` 输入。
## 构建与验证
关闭已有仿真后,按 [工作区 README](../README.md) 构建三个 Classic 包并加载各安装前缀。
正常启动命令不变:
```bash
ros2 launch br_sim_bringup scan_lio.launch.py
```
独立几何检查只检查生成的 SDF 和配置,不替代实际运行:
```bash
/usr/bin/python3 sim_ws/tools/check_vehicle_geometry.py --out sim_ws/log/vehicle_geometry_manual
```
本轮均为无窗口运行,未采集 GUI 截图。三个 Classic 包构建通过;实际运行结果如下。
原始证据位于 `sim_ws/log/codex_measured_geometry_20261110/`,
带源文件/报告哈希的 [验收摘要](validation/20261110_geometry.json) 随源码保存。
| 检查 | 新实测结论 | 证据子目录 |
|---|---|---|
| 生成几何、光心/IMU 与两套外参配置、组合惯量 | 10/10 PASS,包络 0.80×0.80×0.41 m | `geometry/` |
| 适配器单元测试 | 11/11 PASS,含静止速度抖动、实际移动不锁起点、杠杆臂和自身回波 | `unit.log` |
| MID360 平地 | 16/16 PASS,物理射线、运动畸变、真实采样时间与 IMU | `sensors_flat_r1/` |
| MID360 坡道与实际 TF | 16/16 PASS,其中两项核验收到的光心/IMU 静态 TF | `sensors_slope/` |
| 通用雷达两个朝向 | 各 13/13 PASS,原始/世界点云与真值坐标一致 | `generic_lidar/` |
| 原 Point-LIO 平地独立定位 | 9/9 PASS;固定起点对齐后最大位置误差 0.01339 m | `localization_flat/` |
| Point-LIO 平地导航 | 直达、横移、返回转向、绕障 4/4 PASS;最大到点误差 0.06439 m | `navigation_r2/` |
| 接触驱动底盘 | 9/9 PASS,含车体系指令、停止、暂停与里程计/TF | `contact_drive/` |
| 红侧坡道 LIO 导航 | 上/下坡与台阶/坡边拒绝 4/4 PASS;到点误差 0.02559/0.05891 m | `terrain_red_r2/` |
| 新高度下的低障碍视场 | 九组预期均吻合,9/9;不能当作已验证避障 | `low_obstacles/` |
新光心高度下,3 cm 障碍(1.5/3 m)、8 cm 障碍(1.5/3 m)、15 cm 障碍(1.5 m)、
30 cm 障碍(0.6 m)的测试箱体均无回波。特别是旧高度下有少量回波的 **8 cm / 3 m**
现为 **0 回波**;15 cm / 3 m、30 cm / 1.5 m 和 60 cm / 1.5 m 有回波,但未据此验收绕障。
早期轮次没有改写:`navigation/`、`navigation_r1/` 因初始化门控未就绪而无效;
`terrain_red/` 因遗漏通用仿真覆盖而无效;`terrain_red_r1/` 在下坡出现独立真值插值间隔超过
120 ms,记为无效,之后完整重跑红侧四项通过,未放宽时间阈值。
首次缺少场地安装配置以及一次缺少消息安装前缀的启动失败也保留在本机日志。
2026-11-08 各阶段的旧验收数字保留为历史基线;本轮未重跑蓝侧坡道、噪声压力、
多圈/进程拆分、断流注入与全场碰撞覆盖,也未验收真实轮组和实车。
安装旋转、质量、重心与底部间隙仍待实车测量。
@@ -0,0 +1,369 @@
{
"date": "2026-11-10",
"status": "PASS_FOR_RECORDED_FRONT_APPROACH",
"scope": "Gazebo simulation: dual raw scans, per-point pose/time/origin fusion and one frontal 8 cm obstacle route; not general or real-robot safety acceptance",
"lower_optical_position_base_m": [
0.325,
0.0,
0.044
],
"lower_nominal_above_ground_m": 0.194,
"lower_yaw_rad": 1.5707963267948966,
"upper_only_point_lio": true,
"lower_sector": "vehicle-forward directions; lower local y<=0",
"geometry": {
"checks": {
"envelope": true,
"base_reference": true,
"front_horizontal_unoccluded": true,
"rear_occluded": true,
"lower_position": true,
"lower_yaw": true,
"no_solid_box": true
},
"rear_hit_m": [
0.7050000000000001
],
"front_horizontal_rays": 721
},
"integration": {
"source": "log/codex_dual_mid360_20261110/integration_r6/result.json",
"collector_sha256": "802e9e374b683e74c3b03f733b26fd364883d87f3d8b1ee365bdb138b63f078c",
"checks": {
"no_truth_feedback": true,
"actual_lower_tf": true,
"low_obstacle_only_seen_by_lower": true,
"low_obstacle_fused": true,
"low_obstacle_occupied": true,
"occupied_goal_rejected": true,
"navigation_around_low_obstacle": true,
"physical_footprint_clearance": true,
"localization_origins_match_independent_truth": true,
"fusion_origins_match_estimated_inputs": true,
"front_sector_follows_vehicle": true,
"lower_loss_stop": true
},
"runtime_sensor_tf": {
"lidar": {
"frame_id": "base_link",
"child": "lidar",
"stamp": 0.0,
"translation": [
0.015,
0.0,
0.33
],
"rotation": [
0.0,
0.0,
0.0,
1.0
]
},
"mid360_imu": {
"frame_id": "base_link",
"child": "mid360_imu",
"stamp": 0.0,
"translation": [
0.026,
0.02329,
0.28588
],
"rotation": [
0.0,
0.0,
0.0,
1.0
]
},
"lidar_low": {
"frame_id": "base_link",
"child": "lidar_low",
"stamp": 0.0,
"translation": [
0.325,
0.0,
0.044
],
"rotation": [
0.0,
0.0,
0.7071067811865475,
0.7071067811865476
]
}
},
"raw_fixture_returns": [
0,
469
],
"raw_fixture_returns_per_frame": [
[
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
26,
22,
26,
26,
24,
24,
25,
25,
24,
24,
24,
24,
25,
24,
25,
26,
25,
25,
25
]
],
"fused_fixture_returns_by_sensor": [
0,
493
],
"fixture_fused_frames": 20,
"occupied_fixture_voxels": 34,
"blocked_goal_checks": {
"rejected": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"navigation_checks": {
"acknowledged": true,
"active": true,
"succeeded": true,
"arrival": true,
"yaw": true,
"stopped": true,
"commands_observed": true,
"moved": true,
"bounded_braking": true,
"stopped_rotation": true
},
"goal": [
-4.5,
1.5,
-1.5707963267948966
],
"physical_position_error_m": 0.0676547234500218,
"physical_footprint_clearance_m": 0.08925262486531121,
"motion_geometry": {
"fusion_error_p95_m": 2.2970150916098273e-07,
"fusion_error_max_m": 3.239075119017796e-07,
"origin_error_p95_m": 0.05347473781431487,
"origin_error_max_m": 0.05880607827986198,
"front_min_m": 0.00018347158763010185,
"samples": 4684
},
"loss_stop_checks": {
"lower_stopped": true,
"upper_kept_running": true,
"readiness_revoked": true,
"stop_latency": true,
"stayed_stopped": true,
"stationary": true
},
"physical_loss_stop_s": 0.28999999999999204,
"physical_loss_stop_limit_s": 0.5,
"graph_checks": {
"no_truth_input": true,
"estimator_sensors_only": true,
"adapter_lio_only": true,
"controller_uses_estimate": true,
"planner_uses_estimate": true
},
"teardown": {
"known_pids": [
31002,
31020,
31022,
31024,
31026,
31028,
31030,
31032,
31034,
31036,
31038,
31040,
31042,
31044
],
"sigterm": [
31002,
31020,
31024,
31026,
31028,
31030,
31032,
31034,
31036,
31038,
31040,
31042,
31044
],
"sigkill": [
31020
],
"port_free": true,
"seconds": 8.17,
"never_touched_unknown_pid": true
}
},
"regressions": {
"single_sensor_checks": {
"tf_lidar": true,
"tf_mid360_imu": true,
"geometry": true,
"frame_and_count": true,
"finite_fov": true,
"timebase": true,
"actual_batch_times": true,
"frame_rate": true,
"livox_flags": true,
"ray_budget": true,
"pattern_continues": true,
"imu_specific_force": true,
"imu_frame_rate": true,
"no_attitude_oracle": true,
"imu_continuity": true,
"gyro_motion": true,
"real_scan_distortion": true,
"free_fall_imu": true
},
"single_navigation_cases": [
{
"name": "straight",
"ok": true,
"position_error_m": 0.06067192410116457
}
]
},
"unit_tests": {
"unit_final.log": {
"passed": 14,
"sha256": "aea4a04c50d256f7b1b8e46ed1c4c06f80537e0a022611f3efa19f0263c1a7d2"
},
"adapter_regression.log": {
"passed": 11,
"sha256": "b9fd7c5a4412407c40fe0ee0453cedb44dbef6ae7a9e47f783cbeb9114e550ed"
},
"ray_origin_tests_r2.log": {
"passed": 5,
"sha256": "56fd6a27022196f740a42905e97587e43e9dbe884b01e6b87f835001e813f7b1"
}
},
"known_limitations": [
{
"case": "oblique approach to partially visible 8 cm box",
"evidence": "log/codex_dual_mid360_20261110/integration_r5/result.json",
"status": "FAIL",
"footprint_clearance_m": -0.006526317177515395,
"then_support_x_m": 0.3,
"current_support_x_m": 0.2,
"current_configuration_oblique_route_retested": false,
"conclusion": "Do not claim safe passage for arbitrary front-180-degree or lateral low obstacles."
},
{
"case": "first single-lidar straight regression",
"status": "FAIL",
"reason": "planning cloud became stale; retry passed without changing thresholds",
"evidence": "log/codex_dual_mid360_20261110/single_navigation_regression/result.json"
}
],
"not_verified": [
"real aluminium-tube dimensions/occlusion",
"real dual-Livox driver and synchronization",
"lower IMU",
"dual terrain/narrow passages/split deployment",
"GUI appearance",
"arbitrary low obstacles and arbitrary goals"
],
"source_sha256": {
"minco_ws/src/scan/plan_env/CMakeLists.txt": "762d0de2dd308bf29ec3a4e8fc557f80eec644d3b0eba3b2236504c39e061e24",
"minco_ws/src/scan/plan_env/include/plan_env/cloud_ray_origins.h": "c663c10626339002feab7c7d23ab3098db201fcfeb03a17cd577482548d74a17",
"minco_ws/src/scan/plan_env/include/plan_env/grid_map.h": "5efdd6c8bae26e2de686e66a7f8a81562b55ed4196743104b43b6a16c3b142ce",
"minco_ws/src/scan/plan_env/package.xml": "36683ae25a0e99a553221b607c81ab161293c3212356d965e9440992f71a5671",
"minco_ws/src/scan/plan_env/src/grid_map.cpp": "654c1209087e5b901add4e4018e95bf764094030fd9fbe7937b54420cb23efbe",
"minco_ws/src/scan/plan_env/test/test_cloud_ray_origins.cpp": "131df17d3efb0b5f81bb3d1b4cb3bd4716f9b0788e7c27498f45cbf13ba70d7c",
"sim_ws/src/br_sim_bringup/CMakeLists.txt": "594b6a5f2b351ada39d90b838f33546a3626a0001b2f30d71272f2b5ac0b72c2",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "929dd712c103c7a4de22dbae81729ef323b6315d3f72734d17781c1cfe537068",
"sim_ws/src/br_sim_bringup/config/lio_navigation.yaml": "ffa5fc5d76a9b5cdf2e2237910886bea8eea0936e6e422293ae5f3ddf9667d0a",
"sim_ws/src/br_sim_bringup/config/lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py": "f31837e078d8fc1c3b1f28aaa5633bd977eba5bb11b0525918d52369eaa76508",
"sim_ws/src/br_sim_bringup/launch/rviz.launch.py": "5ad26f55cf314c82edf4efe4d15a736528a9982054c07d42588a8959b1021a1a",
"sim_ws/src/br_sim_bringup/launch/scan_lio.launch.py": "a36e8f201213d7a9154cebd937476b8dab13d184c10fcd39a20b66dfc6a06fb5",
"sim_ws/src/br_sim_bringup/launch/scan_lio_navigation.launch.py": "e96b7d5a603b36103365c98c69138834e1c36522dc5ee9a3dc95f7524e1b2d34",
"sim_ws/src/br_sim_bringup/launch/scan_lio_split.launch.py": "af0de3d0012c2637ee412fb9f0e71aa32ce10fa628b1da0cc09c399174e687aa",
"sim_ws/src/br_sim_bringup/launch/scan_lio_terrain.launch.py": "d136043e8824810a6a8de8c6b90f85a2cfdce1171fdf2cee0d94dab1dac32112",
"sim_ws/src/br_sim_bringup/package.xml": "3819f03281f02bae6af1582a75a821508ace44ad13fb9ab9a90d610160382ea0",
"sim_ws/src/br_sim_bringup/rviz/scan_dual_lio.rviz": "3157ed0d34e6e40625366b09694b1969250b505e62e39d1a4bf2697b227d3b31",
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "cc779dee881ad620c1a658e9c730e20feca4d48754267a33f8d455d692e869b7",
"sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py": "8f1613a708a308e37a68742dc572d9185faa91c5469ed564ae4cb10bc9462178",
"sim_ws/src/br_sim_bringup/scripts/scan_cloud_gate.py": "84483b22bceac80adcd898022375d85b7a6874811e5e3ab606a2355a5c71f446",
"sim_ws/src/r2027_robot_description/SOURCE_PROVENANCE.md": "4d09bf86674c527ae12eb422c5e082e466372c1a59c714fabc0c06a5bba1216c",
"sim_ws/src/r2027_robot_description/launch/mid360_sensors.launch.py": "c09284584ee87da15cad56729a01a29ba33f3c54f2319bca51b9a8afa9d9b28b",
"sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py": "5909e0d16082b1e3967e3cdda709022db1f0200b9c7d5b36756f05e97355e4f0",
"sim_ws/src/r2027_robot_description/scripts/mid360_control.py": "123c7fa2b7cef219230bc99c99677e2a503d493849d841674b3fae9f80bdaf70",
"sim_ws/src/r2027_robot_description/scripts/sim_data_adapter.py": "c489ec1cedb3b2619f7e2783f5f9fbcc930155481b295f7457d1ddbfb5f13594",
"sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro": "a09ccb5736585fab6ccf25328ce06f0f7dd5e65982c428a5d6f7c969f98ebe7e",
"sim_ws/src/r2027_robot_description/src/mid360_sensor.cpp": "c698709814cabd32bae1488c0a8b948cdaf0571ea6c9669d8df168f0808a8c09",
"sim_ws/tools/check_dual_lidar.py": "802e9e374b683e74c3b03f733b26fd364883d87f3d8b1ee365bdb138b63f078c",
"sim_ws/tools/check_lio_terrain.py": "8b827eb0548732bb5850b32b1d58c0ece34c2523057a7b8470314d7e102b1cf6",
"sim_ws/tools/check_low_obstacles.py": "3e6538e6e2c2e089b2fab436baf438c9f789ae7162c4bc389993179f0f1492f5",
"sim_ws/tools/check_mid360.py": "7ee5b2656be7f5ce37d9d680ddf98d279b2e3271d673dd31af22addb7a89c858",
"sim_ws/tools/check_omni_robot.py": "683162a1cadf0efb6b4383fbaf100f0a177b3a50a55cfe95c8a85986b2521aa8",
"sim_ws/tools/check_point_lio.py": "137a95eb1c71aa77485d5831944dc0b22e81a1398f97ef3f094f29be6796c49d",
"sim_ws/tools/check_scan_navigation.py": "4235c9ab085ed015c3469f5ed87293260109a7cbb00c180c147c831e5ed1c955",
"sim_ws/tools/check_sensor_noise.py": "e8f327bad7cb61f257554d0d5658cb6ab9ee2d8c94752937ebeba3245a42265a",
"sim_ws/tools/check_sim_lidar.py": "f804a942ff9a3f213b1df37a32413fb310b53c9c4c9340a82faf5a7422e02020",
"sim_ws/tools/check_slope_drive.py": "6a2105e66fa73eb041f9c14396125d08f3698172e4a52173842f5f47462807a2",
"sim_ws/tools/check_vehicle_geometry.py": "3bfb88fc0af4467cbcf8943d7db5b7040b65ca4661ee4fdd73b9517328b5da94",
"sim_ws/tools/test_dual_lidar.py": "026db233d691289b09bbb583674a5406365831e7e4db43fa45b6179a4db08f31",
"sim_ws/tools/test_lio_navigation_adapter.py": "fadbaff33ce1df975eb7b9c90068dda1c0642cac2ee5ce379518bd10a1ba2bac"
},
"evidence_sha256": {
"log/codex_dual_mid360_20261110/integration_r6/result.json": "6851a9a7ea6d063cd0dd2b4d97968f06cccadc6ede9dc3805c8e7448c93d6d52",
"log/codex_dual_mid360_20261110/integration_r6/fixture.npz": "6f8532890ff1779161bbff8c2227e0926876f80f4a274a270a4d18b9a871e9d5",
"log/codex_dual_mid360_20261110/integration_r6/motion_geometry.npz": "d672a3a142e6c81d9663d739f1feff429a53392dabdf87193c30b5beaa7c7ac8",
"log/codex_dual_mid360_20261110/geometry/result.json": "317c441a77096e53826a059a9e3e9fb60cc8d5e13db728861b82e3d0f7e86875"
},
"superseded_attempts": {
"smoke": "new Python entry lacked executable permission, fixed before runtime",
"smoke_r1": "initial interpolation bound 50 ms too short; measured estimator gaps about 65 ms",
"smoke_r2": "coverage gaps were safely dropped, no fake/extrapolated poses",
"integration": "goal near real stairs; also truth collector gap >120 ms",
"integration_r1": "different initial position never locked stationary localization",
"integration_r2": "200 ms downstream gate caused holds; single-frame sparse-hit assertion replaced by recorded multi-frame observation window",
"integration_r3": "front-sector/oblique navigation passed, but total localization error was wrongly used as sub-centimetre fusion criterion; separated analytical/estimated/physical errors; later fault goal occupied real field objects",
"integration_r4": "lower-loss stop .38 s and route passed; dropped intermediate odometry found by millimetre input comparison, fixed reliable queue",
"integration_r5": "fusion and .361 s loss-stop passed, oblique route failed with footprint overlap; retained as a safety limitation"
}
}
@@ -0,0 +1,268 @@
{
"date": "2026-11-10",
"status": "PASS",
"scope": "five explicitly specified static low-box routes in the current flat dual-lidar proxy; not unrestricted low-obstacle or real-robot safety",
"primary_routes": [
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/fixed_side_right/result.json",
"status": "PASS",
"scope": "navigation_only",
"scenario": "side_right",
"fixture_center_m": [
-4.0,
3.0
],
"goal_m_rad": [
-4.5,
1.5,
0.0
],
"passed_checks": 12,
"total_checks": 12,
"minimum_oriented_gap_bound_m": 0.24713346886299203,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.05882633582699527,
"loss_stop_latency_sim_s": null,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 352,
"max_position_error_m": 0.0003264880062448854,
"max_angle_error_rad": 1.8902755837321365e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/fixed_side_left/result.json",
"status": "PASS",
"scope": "navigation_only",
"scenario": "side_left",
"fixture_center_m": [
-5.0,
3.0
],
"goal_m_rad": [
-4.5,
1.5,
3.141592653589793
],
"passed_checks": 12,
"total_checks": 12,
"minimum_oriented_gap_bound_m": 0.22578309387075862,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.06170495480582261,
"loss_stop_latency_sim_s": null,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 440,
"max_position_error_m": 0.0002970609575736179,
"max_angle_error_rad": 1.7918607611129184e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/fixed_diagonal_right/result.json",
"status": "PASS",
"scope": "navigation_only",
"scenario": "diagonal_right",
"fixture_center_m": [
-3.6,
3.0
],
"goal_m_rad": [
-3.9,
1.5,
-0.7853981633974483
],
"passed_checks": 12,
"total_checks": 12,
"minimum_oriented_gap_bound_m": 0.23793751328387816,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.06768594722403673,
"loss_stop_latency_sim_s": null,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 329,
"max_position_error_m": 0.00029748082905305833,
"max_angle_error_rad": 1.1991500579554446e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/fixed_diagonal_left/result.json",
"status": "PASS",
"scope": "navigation_only",
"scenario": "diagonal_left",
"fixture_center_m": [
-5.0,
3.0
],
"goal_m_rad": [
-4.6,
1.5,
-2.356194490192345
],
"passed_checks": 12,
"total_checks": 12,
"minimum_oriented_gap_bound_m": 0.2115150703902867,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.09229858939412014,
"loss_stop_latency_sim_s": null,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 333,
"max_position_error_m": 0.0002974523768933953,
"max_angle_error_rad": 1.1991500579554446e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/fixed_front/result.json",
"status": "PASS",
"scope": "navigation_and_loss_stop",
"scenario": "front",
"fixture_center_m": [
-4.5,
3.0
],
"goal_m_rad": [
-4.5,
1.5,
-1.5707963267948966
],
"passed_checks": 13,
"total_checks": 13,
"minimum_oriented_gap_bound_m": 0.07566476784889768,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.07269329495120164,
"loss_stop_latency_sim_s": 0.39000000000000057,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 528,
"max_position_error_m": 0.0002970714363693476,
"max_angle_error_rad": 1.78962883901631e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
}
],
"negative_control": {
"evidence": "sim_ws/log/codex_dual_safety_20261110/historical_fixed_clock/result.json",
"expected_status": "FAIL",
"actual_status": "FAIL",
"expected_exit_code": 30,
"failed_checks": [
"navigation_around_low_obstacle",
"physical_footprint_clearance"
],
"initial_occupied_fixture_voxels": 9,
"minimum_oriented_gap_bound_m": -0.0009847759762388112
},
"additional_front_after_spawn_retry": {
"evidence": "sim_ws/log/codex_dual_safety_20261110/front_spawn_regression/result.json",
"status": "PASS",
"scope": "navigation_and_loss_stop",
"scenario": "front",
"fixture_center_m": [
-4.5,
3.0
],
"goal_m_rad": [
-4.5,
1.5,
-1.5707963267948966
],
"passed_checks": 13,
"total_checks": 13,
"minimum_oriented_gap_bound_m": 0.1172852467975843,
"maximum_truth_sample_gap_s": 0.020000000000003126,
"arrival_error_m": 0.07988175575624144,
"loss_stop_latency_sim_s": 0.36999999999999744,
"truth_service_agreement": {
"source": "contact plugin /odom: WorldPose at source simulation time; evaluation only",
"samples": 402,
"max_position_error_m": 0.0002979840462034178,
"max_angle_error_rad": 1.8792012656253608e-06
},
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6"
},
"single_lidar_regression": {
"evidence": "sim_ws/log/codex_dual_safety_20261110/single_regression_r1/result.json",
"status": "PASS",
"arrival_error_m": 0.056875615674557504
},
"source_version_note": "Primary five runs used the clock-queue fix. Only the read-only startup query retry changed afterward; single-lidar and full dual-front runs were repeated after that change. Primary five were not all rerun after the startup-only edit.",
"startup_script_sha256_during_primary_runs": "8746af40699f90789f580f7a2664e5aadcb61a103900b31d9ecf76a50b44a0e6",
"final_source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac",
"sim_ws/src/r2027_robot_description/scripts/spawn_existing_world.py": "3d9dc52df8c4746b968ec7c8881e19ad0e6d04e827729294eddbe608bc689523",
"sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro": "ef27acc9c9d9a7b102243031723adc6d02ea0ebb631d187463bcdc911b54d643",
"sim_ws/tools/check_dual_lidar.py": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6",
"sim_ws/tools/test_dual_acceptance.py": "dc059a75887adca231b2f8f70535bc00b83e4d475c03f12706e222fb3e04156c",
"sim_ws/tools/test_lio_navigation_adapter.py": "27f76a2883e54ddac579e17f08fb52f38b547662f4fcd74b86a6454df9c07316",
"sim_ws/tools/test_spawn_existing_world.py": "1d78d5e79c110db2a15191e15ee5067ab5bd2189fe1465f3be897ed0fa725e34",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "929dd712c103c7a4de22dbae81729ef323b6315d3f72734d17781c1cfe537068",
"sim_ws/src/br_sim_bringup/config/scan_sim.yaml": "501eb7fdba9928b8a12def3459ea087fa0596bebfeeba5c2300b081ba8933e75"
},
"unit_tests": {
"dual_perception_and_clearance": 21,
"adapter": 17,
"spawn_query": 3
},
"retained_nonpassing_rounds": [
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/current_diagonal_right/result.json",
"status": "INVALID",
"error": "RuntimeError('no moving vehicle for lower-lidar fault')",
"navigation_ok": false
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/diagonal_right_clear_corridor/result.json",
"status": "INVALID",
"error": "ValueError('truth gap exceeds 120 ms')",
"navigation_ok": true
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/diagonal_right_dense/result.json",
"status": "FAIL",
"error": null,
"navigation_ok": false
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/diagonal_right_dense_r1/result.json",
"status": "INVALID",
"error": "RuntimeError('launch 进程提前退出 code=0')",
"navigation_ok": null
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/diagonal_right_goal2/result.json",
"status": "INVALID",
"error": "ValueError('strides is incompatible with shape of requested array and size of buffer')",
"navigation_ok": null
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/diagonal_right_wide/result.json",
"status": "INVALID",
"error": "RuntimeError('no moving vehicle for lower-lidar fault')",
"navigation_ok": false
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/historical_side_right/result.json",
"status": "INVALID",
"error": "ValueError('truth gap exceeds 120 ms')",
"navigation_ok": false
},
{
"evidence": "sim_ws/log/codex_dual_safety_20261110/single_regression/result.json",
"status": "INVALID",
"error": "RuntimeError('launch 进程提前退出 code=0')",
"navigation_ok": null
}
],
"limits": [
"No GUI/RViz screenshot or real-robot acceptance",
"Original 45-degree corridor fixture positions remained blocked; positive diagonal cases have explicit different fixture/goal positions",
"No new unknown-area motion gate, automatic travel-heading policy or independent braking-distance monitor",
"No lower rear-half coverage; no general dynamic-obstacle or unseen-near-ground guarantee",
"Clock-order and bounded read-query retry are hardened; no claim that all restart/long-run failures are eliminated",
"Gazebo /odom used only by validation and cross-checked with independent timestamped entity queries"
]
}
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 75 KiB

@@ -0,0 +1,572 @@
{
"date": "2026-11-10",
"status": "LIMITED_ACCEPTANCE",
"navigation_status": "PASS",
"scope": "opt-in dual MID360 known red/blue ramps; 0.15 m/s, 4 cm margin, no real-robot migration",
"navigation_cases_passed": 8,
"runtime": {
"red_slow": {
"path": "sim_ws/log/codex_dual_terrain_20261110/red_slow/result.json",
"sha256": "49fd16aa0e86dcaf5b78c7d36c999873681a32cdfb50355a84a02aaf2df49853",
"status": "PASS",
"collector_sha256": "5063baa34c06140a6aed27ff83f69f0f3ee3257b3eff4e1d926d97463f156e9e",
"case_status": {
"uphill": true,
"stairs_rejected": true,
"edge_rejected": true,
"downhill": true
},
"metadata_ok": true,
"motion": {
"uphill": {
"position_error_m": 0.08042192716728477,
"min_sampled_full_body_clearance_m": 0.06535946260919595,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"downstream_hold_exercised": true,
"downstream_readiness_revoked": true,
"downstream_stop_in_time": true,
"downstream_held_still": true,
"downstream_new_grant": true,
"upper_continues_during_lower_loss": true,
"lower_really_stopped": true,
"active": true,
"physical_arrival": true,
"physical_height": true,
"ramp_pitch": true,
"ramp_height": true,
"lane": true,
"full_body_clearance": true,
"real_ramp_contacts": true,
"penetration": true
},
"fault_stop_latency_sim_s": 0.4399999999999977,
"truth_service_agreement": {
"samples": 980,
"max_position_error_m": 0.00018156585819232372,
"max_angle_error_rad": 9.135216877404346e-05,
"max_dense_gap_s": 0.020000000000003126
}
},
"stairs_rejected": {
"position_error_m": 1.3778701163993796,
"min_sampled_full_body_clearance_m": 0.06544729033478763,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 222,
"max_position_error_m": 1.1102230246251565e-16,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000010232
}
},
"edge_rejected": {
"position_error_m": 2.1537510885923887,
"min_sampled_full_body_clearance_m": 0.06544729033478763,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 219,
"max_position_error_m": 1.1102230246251565e-16,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000010232
}
},
"downhill": {
"position_error_m": 0.05531378103660248,
"min_sampled_full_body_clearance_m": 0.06544729033478763,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"active": true,
"physical_arrival": true,
"physical_height": true,
"ramp_pitch": true,
"ramp_height": true,
"lane": true,
"full_body_clearance": true,
"real_ramp_contacts": true,
"penetration": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 809,
"max_position_error_m": 0.0001845977459596773,
"max_angle_error_rad": 6.716581338676618e-05,
"max_dense_gap_s": 0.020000000000010232
}
}
},
"runtime_snapshots": {
"dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"point_lio_terrain.yaml": "17dfab42e9f92f7ad698d3de3da90809ef6c07b6e2c529ff930c0dd5bb1d40e9",
"lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac"
}
},
"blue": {
"path": "sim_ws/log/codex_dual_terrain_20261110/blue/result.json",
"sha256": "01f51790eec86602fb3cf24bf70ffc53c0dd93729be463d09db72c58be224747",
"status": "PASS",
"collector_sha256": "a8523342a00ef1a105c93885547c3a079516f3d562f2588bb46f597ab6ea8c0a",
"case_status": {
"uphill": true,
"stairs_rejected": true,
"edge_rejected": true,
"downhill": true
},
"metadata_ok": true,
"motion": {
"uphill": {
"position_error_m": 0.061577591700194154,
"min_sampled_full_body_clearance_m": 0.07582341015971589,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"downstream_hold_exercised": true,
"downstream_readiness_revoked": true,
"downstream_stop_in_time": true,
"downstream_held_still": true,
"downstream_new_grant": true,
"active": true,
"physical_arrival": true,
"physical_height": true,
"ramp_pitch": true,
"ramp_height": true,
"lane": true,
"full_body_clearance": true,
"real_ramp_contacts": true,
"penetration": true
},
"fault_stop_latency_sim_s": 0.14999999999999858,
"truth_service_agreement": {
"samples": 1000,
"max_position_error_m": 0.00019223870217010826,
"max_angle_error_rad": 0.00012206819519691851,
"max_dense_gap_s": 0.020000000000003126
}
},
"stairs_rejected": {
"position_error_m": 1.3610872755286099,
"min_sampled_full_body_clearance_m": 0.07934704702061535,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 216,
"max_position_error_m": 1.1102230246251565e-16,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000010232
}
},
"edge_rejected": {
"position_error_m": 2.1751817715469395,
"min_sampled_full_body_clearance_m": 0.07934704702061535,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 220,
"max_position_error_m": 1.1102230246251565e-16,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000010232
}
},
"downhill": {
"position_error_m": 0.057485607006650494,
"min_sampled_full_body_clearance_m": 0.0754267172163905,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"active": true,
"physical_arrival": true,
"physical_height": true,
"ramp_pitch": true,
"ramp_height": true,
"lane": true,
"full_body_clearance": true,
"real_ramp_contacts": true,
"penetration": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 749,
"max_position_error_m": 0.00017833902800726734,
"max_angle_error_rad": 0.00012227475579833423,
"max_dense_gap_s": 0.020000000000010232
}
}
},
"runtime_snapshots": {
"dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"point_lio_terrain.yaml": "17dfab42e9f92f7ad698d3de3da90809ef6c07b6e2c529ff930c0dd5bb1d40e9",
"lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac"
}
},
"obstacle_15_window": {
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_15_window/result.json",
"sha256": "e6d8ca66f44a32c5ec3535d63c1ce98b97cc427ac3f706d7a5d9be4276000296",
"status": "PASS",
"collector_sha256": "b064c6a3b96fac5e2d22fbc38f59694cd3bbf5b43d8c5342e651e72bcf619c26",
"case_status": {
"ramp_obstacle_rejected": true
},
"metadata_ok": true,
"motion": {
"ramp_obstacle_rejected": {
"position_error_m": 2.499999999999977,
"min_sampled_full_body_clearance_m": 0.08749891786607361,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 218,
"max_position_error_m": 0.0,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000003126
}
}
},
"obstacle_returns": {
"count": 178,
"retained": 178,
"by_sensor": [
85,
93
],
"criteria": "all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved",
"ok": true
},
"matched_frames": 18,
"runtime_snapshots": {
"dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"point_lio_terrain.yaml": "17dfab42e9f92f7ad698d3de3da90809ef6c07b6e2c529ff930c0dd5bb1d40e9",
"lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac"
}
},
"obstacle_08_aligned": {
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_08_aligned/result.json",
"sha256": "60f2830f6d53bfc7d41e0784fbbf35fcf358a38272d926dbaffc9828cef859ff",
"status": "PASS",
"collector_sha256": "712797a25c7c2d425fe2b08723a6d0212abcf423f7cbbfea20808d415095fc8a",
"case_status": {
"ramp_obstacle_rejected": true
},
"metadata_ok": true,
"motion": {
"ramp_obstacle_rejected": {
"position_error_m": 2.499999999999977,
"min_sampled_full_body_clearance_m": 0.08749891786607361,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 209,
"max_position_error_m": 0.0,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000003126
}
}
},
"obstacle_returns": {
"count": 161,
"retained": 161,
"by_sensor": [
106,
55
],
"criteria": "all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved",
"ok": true
},
"matched_frames": 19,
"runtime_snapshots": {
"dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"point_lio_terrain.yaml": "17dfab42e9f92f7ad698d3de3da90809ef6c07b6e2c529ff930c0dd5bb1d40e9",
"lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac"
}
},
"obstacle_08_horizontal": {
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_08_horizontal/result.json",
"sha256": "ebadef64586397478cd796e964a1db761da5b6c8fb4dc86ca2b91d3467295eef",
"status": "FAIL",
"collector_sha256": "712797a25c7c2d425fe2b08723a6d0212abcf423f7cbbfea20808d415095fc8a",
"case_status": {
"ramp_obstacle_rejected": true
},
"metadata_ok": true,
"motion": {
"ramp_obstacle_rejected": {
"position_error_m": 2.499999999999977,
"min_sampled_full_body_clearance_m": 0.08749891786607361,
"checks": {
"acknowledged": true,
"state_as_expected": true,
"truth_crosschecked": true,
"perception_fresh": true,
"original_goal_preserved": true,
"stopped": true,
"bounded_braking": true,
"estimated_lateral_error": true,
"estimated_vertical_error": true,
"never_active": true,
"stationary": true,
"zero_commands": true
},
"fault_stop_latency_sim_s": null,
"truth_service_agreement": {
"samples": 210,
"max_position_error_m": 0.0,
"max_angle_error_rad": 0.0,
"max_dense_gap_s": 0.020000000000003126
}
}
},
"obstacle_returns": {
"count": 119,
"retained": 118,
"by_sensor": [
66,
53
],
"criteria": "all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved",
"ok": false
},
"matched_frames": 18,
"runtime_snapshots": {
"dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"point_lio_terrain.yaml": "17dfab42e9f92f7ad698d3de3da90809ef6c07b6e2c529ff930c0dd5bb1d40e9",
"lio_navigation_adapter.py": "e6ba627dd18e4beae67019bab1c2a3769fbde2abe13b0487bf43b878896af9ac"
}
},
"flat_regression": {
"path": "sim_ws/log/codex_dual_terrain_20261110/flat_regression/result.json",
"sha256": "21f763d62427ccd6187c27c8ca08a18ae81393da694696b7901595d619a37fd1",
"status": "PASS",
"collector_sha256": "11741aec96fd2097039f4b6308e1b5dba5b2107e103eb03fd135b81ccab48ae6",
"case_status": {},
"metadata_ok": null,
"checks": {
"no_truth_feedback": true,
"actual_lower_tf": true,
"low_obstacle_only_seen_by_lower": true,
"low_obstacle_fused": true,
"low_obstacle_occupied": true,
"occupied_goal_rejected": true,
"navigation_around_low_obstacle": true,
"truth_service_agreement": true,
"physical_footprint_clearance": true,
"localization_origins_match_independent_truth": true,
"fusion_origins_match_estimated_inputs": true,
"front_sector_follows_vehicle": true,
"lower_loss_stop": true
},
"lower_loss_stop_latency_sim_s": 0.3299999999999983,
"position_error_m": 0.07798837965022178,
"oriented_swept_clearance": {
"min_gap_bound_m": 0.09020613910175439,
"max_sample_gap_s": 0.020000000000003126,
"method": "oriented SAT; interpolated poses padded by half-step corner travel"
},
"runtime_snapshots": {}
}
},
"retained_earlier_reports": {
"red_initial": {
"status": "INVALID",
"path": "sim_ws/log/codex_dual_terrain_20261110/red_initial/result.json",
"sha256": "85850c14d38fcbcc4476b41c6b4f975e81e1ff93f26823fc62ca3774be2abc66",
"error": "ValueError('truth gap exceeds 120 ms')"
},
"red_r1": {
"status": "INVALID",
"path": "sim_ws/log/codex_dual_terrain_20261110/red_r1/result.json",
"sha256": "9d69a7edfa2e0ab57bf48744a3eb84895302c5a795d148918ecc8c82ed0ef0e8",
"error": "RuntimeError('missing lower enable service')"
},
"red_r2": {
"status": "FAIL",
"path": "sim_ws/log/codex_dual_terrain_20261110/red_r2/result.json",
"sha256": "272136239931523474adcbc61771d86607a20724f888714b52a8c9a273e178ff",
"error": null
},
"obstacle_08": {
"status": "FAIL",
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_08/result.json",
"sha256": "668620017bba11ffb09f8daf844baebd93b310e4f66f6b4c5d5d80e847155c26",
"error": "RuntimeError('valid obstacle sample fails observation/preservation criteria')"
},
"obstacle_15": {
"status": "FAIL",
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_15/result.json",
"sha256": "86e55cf30dd481b0528e3ec494426fad81e786c9f2cc50abfa9729f1086c2965",
"error": "RuntimeError('valid obstacle sample fails observation/preservation criteria')"
},
"obstacle_08_window": {
"status": "FAIL",
"path": "sim_ws/log/codex_dual_terrain_20261110/obstacle_08_window/result.json",
"sha256": "086a7b343374c709ed866ba220fbcf2e4eabc0072fe65e63dbc32e1fd63c4a51",
"error": "RuntimeError('valid obstacle sample fails observation/preservation criteria')"
}
},
"known_failure": "Horizontal 8 cm box: 118/119 selected returns retained; occupied goal rejection passes, complete preservation fails. Its uphill end is only ~5.9 cm above ramp, inside the 6 cm surface band. Slope-aligned 8 cm box is an additional explicitly distinct fixture, not a replacement.",
"not_retested": [
"entire single-lidar terrain suite",
"all earlier flat routes",
"GUI",
"real chassis and real clock synchronization",
"distributed deployment"
],
"current_sources_sha256": {
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "ae21a28194f5991d253e304222b879fce021ad86ebf1d27a73575755f14f971d",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"sim_ws/src/br_sim_bringup/config/dual_lidar_terrain.yaml": "1e1f6da9fc7c1962049affa19fb255c0ef1f7da5c1f3382a2b61266c204b43ab",
"sim_ws/src/br_sim_bringup/config/lio_terrain.yaml": "6cbb1c5c37d4d7632366afdf0ceec90654b20adcbdcdee369df534150a043d4e",
"sim_ws/src/br_sim_bringup/launch/scan_lio_terrain.launch.py": "5598fb883095b2b7d4b388c4ac205cd2107c46187c5b492eee99c16618c54718",
"minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py": "69f6cf7f324c42f2a04eaf6964476f75e06299b7131df35a29c9af0bc11f2b61",
"minco_ws/src/scan/plan_env/src/grid_map.cpp": "654c1209087e5b901add4e4018e95bf764094030fd9fbe7937b54420cb23efbe",
"minco_ws/src/scan/plan_env/include/plan_env/cloud_ray_origins.h": "c663c10626339002feab7c7d23ab3098db201fcfeb03a17cd577482548d74a17",
"sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro": "ef27acc9c9d9a7b102243031723adc6d02ea0ebb631d187463bcdc911b54d643",
"sim_ws/tools/check_lio_terrain.py": "67e3063150ebcfb8c59228edbed5f63e1b37c37fea6e9807d5dfc25b826bddbd",
"sim_ws/tools/test_dual_terrain.py": "1e72428fa4fffd2a40efd7e0e0ee66edf8626e5e3307bb9a50660544e9257efb",
"minco_ws/src/scan/plan_env/test/test_cloud_ray_origins.cpp": "6b767d08d74946a939e4821e5406024474103b78a0d40b6094717fc862c9dc87"
},
"collector_versions": "Per-run collector_snapshot.py and collector_sha256 identify acquisition. Later changes added fixed-window obstacle collection, explicit aligned fixture and invalid-collection handling; no old reports rewritten.",
"unit_tests": {
"python_count": 40,
"cpp_count": 6,
"logs": {
"sim_ws/log/dual_terrain_unit_final.log": "accd41549fb1df4789d599a43a34c33796fed31a14f99ca02ebee90fa73908ce",
"sim_ws/log/dual_terrain_flat_units.log": "70ad77b8ed1c48c0d148ff149a80394e7f8a9df1bd62a72f996519953ec2aee1",
"sim_ws/log/dual_terrain_grid_tests_final.log": "4d3bf52bb025391dd68c7345fa35cfbfc1a0948fafa9778b916b2c6ebf7798a1"
}
},
"no_screenshots": true,
"git_commit_or_push": false
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,217 @@
{
"date": "2026-11-10",
"status": "PASS",
"scope": "dual MID360 flat north corridor with original user goal; not terrain or real robot acceptance",
"user_goal": {
"frame": "world",
"position_m": [
3.5,
4.8,
0.15
],
"yaw_rad": 0.0
},
"baseline": {
"evidence": "sim_ws/log/codex_north_corridor_20261110/baseline/result.json",
"status": "FAIL",
"attempts": 2,
"final_position_m": [
-2.1226159811030247,
4.610032527534134,
0.14898743834681832
],
"floor_stats": {
"max_occupied_floor_voxels": 24,
"xy_roi_m": [
-2.8,
2.0,
4.35,
5.2
],
"z_band_m": [
0.015,
0.05
]
},
"collector_sha256": "5ed6e48fd7fe91402f97d28b53b6b084db1de69c0fd2324d914ab0b993f1222a"
},
"verified_runs": [
{
"evidence": "sim_ws/log/codex_north_corridor_20261110/verified_1/result.json",
"status": "PASS",
"first_goal_succeeded": true,
"arrival_error_m": 0.06328600398027272,
"duration_sim_s": 37.25,
"checks": {
"acknowledged": true,
"active": true,
"succeeded": true,
"arrival": true,
"yaw": true,
"stopped": true,
"commands_observed": true,
"moved": true,
"bounded_braking": true,
"stopped_rotation": true,
"crossed_north_corridor": true,
"physical_clearance": true,
"truth_service_agreement": true
},
"physics": {
"minimum_gap_bound_m": 0.15018444075363577,
"max_truth_gap_s": 0.020000000000003126,
"query_samples": 516,
"max_query_position_error_m": 0.0002977956002337302,
"max_query_angle_error_rad": 1.8813269260033622e-06,
"band_y_m": [
4.0,
5.5
],
"scope": "flat corridor envelope; linear interpolation bound between truth samples"
},
"floor_stats": {
"max_occupied_floor_voxels": 0,
"xy_roi_m": [
-2.8,
2.0,
4.35,
5.2
],
"z_band_m": [
0.015,
0.05
]
},
"collector_sha256": "04995c3256a09ed4c3483a488c32bf58d419a2a4c07feee887de48ae313f06db",
"source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "b3c80d56c86bdaba964457b27b0a2ded3e0e86de006f9faa0152edf99543cd22",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"sim_ws/src/br_sim_bringup/config/scan_sim.yaml": "501eb7fdba9928b8a12def3459ea087fa0596bebfeeba5c2300b081ba8933e75"
}
},
{
"evidence": "sim_ws/log/codex_north_corridor_20261110/verified_2/result.json",
"status": "PASS",
"first_goal_succeeded": true,
"arrival_error_m": 0.06297862623166439,
"duration_sim_s": 36.81,
"checks": {
"acknowledged": true,
"active": true,
"succeeded": true,
"arrival": true,
"yaw": true,
"stopped": true,
"commands_observed": true,
"moved": true,
"bounded_braking": true,
"stopped_rotation": true,
"crossed_north_corridor": true,
"physical_clearance": true,
"truth_service_agreement": true
},
"physics": {
"minimum_gap_bound_m": 0.14281199215827126,
"max_truth_gap_s": 0.020000000000003126,
"query_samples": 512,
"max_query_position_error_m": 0.0002977323328920782,
"max_query_angle_error_rad": 2.0313731656018145e-06,
"band_y_m": [
4.0,
5.5
],
"scope": "flat corridor envelope; linear interpolation bound between truth samples"
},
"floor_stats": {
"max_occupied_floor_voxels": 0,
"xy_roi_m": [
-2.8,
2.0,
4.35,
5.2
],
"z_band_m": [
0.015,
0.05
]
},
"collector_sha256": "04995c3256a09ed4c3483a488c32bf58d419a2a4c07feee887de48ae313f06db",
"source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "b3c80d56c86bdaba964457b27b0a2ded3e0e86de006f9faa0152edf99543cd22",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"sim_ws/src/br_sim_bringup/config/scan_sim.yaml": "501eb7fdba9928b8a12def3459ea087fa0596bebfeeba5c2300b081ba8933e75"
}
}
],
"low_obstacle_regression": {
"evidence": "sim_ws/log/codex_north_corridor_20261110/low_obstacle_regression/result.json",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"actual_lower_tf": true,
"low_obstacle_only_seen_by_lower": true,
"low_obstacle_fused": true,
"low_obstacle_occupied": true,
"occupied_goal_rejected": true,
"navigation_around_low_obstacle": true,
"truth_service_agreement": true,
"physical_footprint_clearance": true,
"localization_origins_match_independent_truth": true,
"fusion_origins_match_estimated_inputs": true,
"front_sector_follows_vehicle": true,
"lower_loss_stop": true
},
"stop_latency_sim_s": 0.3400000000000034,
"minimum_gap_bound_m": 0.06307619277144037
},
"side_regression": {
"evidence": "sim_ws/log/codex_north_corridor_20261110/side_regression/result.json",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"actual_lower_tf": true,
"low_obstacle_only_seen_by_lower": true,
"low_obstacle_fused": true,
"low_obstacle_occupied": true,
"occupied_goal_rejected": true,
"navigation_around_low_obstacle": true,
"truth_service_agreement": true,
"physical_footprint_clearance": true,
"localization_origins_match_independent_truth": true,
"fusion_origins_match_estimated_inputs": true,
"front_sector_follows_vehicle": true
},
"minimum_gap_bound_m": 0.23566537442651195,
"scope": "navigation only; no additional loss-stop in this case"
},
"unit_tests": {
"dual_lidar": 16,
"visibility_and_clearance": 7,
"adapter": 17,
"spawn_query": 3,
"total": 43
},
"final_source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "b3c80d56c86bdaba964457b27b0a2ded3e0e86de006f9faa0152edf99543cd22",
"sim_ws/src/br_sim_bringup/config/dual_lidar.yaml": "50f0adf43636bd24f8f0c6e035e8eeb7b5dbd7cd00dd1c0d919893b289506f47",
"sim_ws/tools/check_lio_corridor.py": "04995c3256a09ed4c3483a488c32bf58d419a2a4c07feee887de48ae313f06db",
"sim_ws/tools/test_dual_lidar.py": "28afd11021cb86ea7d2bc7d55e45ecad7b56ae855763ee11b7c3490ce6b030c3"
},
"unchanged": {
"body_footprint_m": [
0.8,
0.8
],
"planner_margin_m": 0.09,
"ground_band_m": 0.015
},
"limits": [
"Flat-body ground reference assumes current horizontal simplified flat-ground model; no generic terrain segmentation",
"Single-lidar ground filter not modified by this change",
"Raw world clouds, original timestamps and optical origins remain unchanged",
"No truth inputs to navigation",
"No GUI screenshots or real-robot acceptance",
"Earlier five-route safety suite was not entirely repeated after this filter change",
"Two successful fresh starts do not prove arbitrary long-run stability"
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,842 @@
{
"status": "PASS_SCOPED",
"date": "2026-11-12",
"scope": "GUI + RViz known north-ramp mission, dual-lidar timing/readiness fixes; no real-robot claim",
"git_head": "cac93cae111ca5b1208ef01940d9d892af32db97",
"parameters": {
"lower_source_timeout_s": 0.23,
"fused_cloud_timeout_s": 0.3,
"odom_timeout_s": 0.2,
"imu_timeout_s": 0.1
},
"cases": {
"scanend_gui_ideal": {
"status": "PASS",
"original_status": "FAIL",
"report": "sim_ws/log/codex_ramp_health_20261112/scanend_gui_ideal/result.json",
"sha256": "6f7599113577994b8c9ebcd5c44272efd200570c799cbb83a3d41d51d395992a",
"collector_sha256": "d935d420e8277f7e0fbd7717e0a78019484ffda300c1f33dfb3577a2194339f8",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"aligned_start": false,
"offline_qos_reassessment": {
"path": "sim_ws/log/codex_ramp_health_20261112/scanend_gui_ideal/qos_reassessment.json",
"sha256": "6209bb8d8273e429df11ed28eaedd22fdcc1cc1593ebddd833fff9eb34e841a8",
"scope": "Offline correction of discovery QoS reliability criterion only; no physical replay and no changes to original report"
},
"critical_cloud_qos": {
"/sim/navigation/fused_planning_cloud": [
{
"kind": "publisher",
"node": "dual_lidar_fusion",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "ramp_mission",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
],
"/sim/navigation/terrain_planning_cloud": [
{
"kind": "publisher",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "lio_navigation_adapter",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "scan_planner_node",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
]
},
"scan_end_odometry_enabled": true,
"task_duration_sim_s": 49.7,
"motion_metrics": {
"straight_peak_mps": 0.597487634649999,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.7913304186705141,
"uphill_peak_mps": 0.6975194887758214,
"crest_peak_mps": 0.198678401249177,
"crest_median_mps": 0.1974522944708625
},
"ramp_clearance_m": 0.06814792520526769,
"north_corridor_gap_bound_m": 0.1350438660666763,
"maximum_ramp_lateral_error_m": 0.015183316283012172,
"fault_event": {},
"final": {
"stamp": 53.471,
"pos": [
-1.3362725285755603,
3.4973166850755346,
0.7489874383468184
],
"yaw": -3.131272041115428,
"rpy": [
-3.63186279691415e-08,
1.9381558175701663e-14,
-3.131272041115428
],
"quaternion": [
9.369751468172896e-11,
-1.815907225510332e-08,
0.9999866856493146,
-0.005160283335119911
],
"twist_world": [
2.841489149994533e-13,
-1.2893416353509863e-11,
5.2849692620088644e-05
],
"wz": 4.908999543700119e-19
},
"contact_maximum_depth_m": 0.0010300442406271787
},
"scanend_gui_mild": {
"status": "PASS",
"original_status": "PASS",
"report": "sim_ws/log/codex_ramp_health_20261112/scanend_gui_mild/result.json",
"sha256": "d28ed1e23be0c40a6894c1a1a56a6f687bbf7e4c8366d8b8b6007ebb5aaa18c2",
"collector_sha256": "f5b3d8906173de4327a407016f2e734972da1ad78c51255d22dda2c2fc963094",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"aligned_start": false,
"critical_cloud_qos": {
"/sim/navigation/fused_planning_cloud": [
{
"kind": "publisher",
"node": "dual_lidar_fusion",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "ramp_mission",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
],
"/sim/navigation/terrain_planning_cloud": [
{
"kind": "publisher",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "lio_navigation_adapter",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "scan_planner_node",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
]
},
"scan_end_odometry_enabled": true,
"task_duration_sim_s": 51.2,
"motion_metrics": {
"straight_peak_mps": 0.5974865715957057,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.7913306336667913,
"uphill_peak_mps": 0.6975539891275698,
"crest_peak_mps": 0.19870773565842284,
"crest_median_mps": 0.1974283376322899
},
"ramp_clearance_m": 0.07779464784324253,
"north_corridor_gap_bound_m": 0.12985112997447004,
"maximum_ramp_lateral_error_m": 0.009494414767903248,
"fault_event": {},
"final": {
"stamp": 55.0,
"pos": [
-1.3185547602558396,
3.5069234779974305,
0.7489874383468182
],
"yaw": -3.1385821688166176,
"rpy": [
-3.631862739257741e-08,
1.9616325808899608e-14,
-3.1385821688166176
],
"quaternion": [
2.732435021311945e-11,
-1.815929313878159e-08,
0.9999988671228927,
-0.00150524181816953
],
"twist_world": [
1.7108147164948868e-13,
-1.2909102453264056e-11,
5.28496925988371e-05
],
"wz": 4.76065126334688e-19
},
"contact_maximum_depth_m": 0.0010327845307821076
},
"scanend_gui_loss": {
"status": "PASS",
"original_status": "PASS",
"report": "sim_ws/log/codex_ramp_health_20261112/scanend_gui_loss/result.json",
"sha256": "a18521404630bab4497e005867ad0112f4654d96e41933ec96b16fcdb5ebcd2d",
"collector_sha256": "f5b3d8906173de4327a407016f2e734972da1ad78c51255d22dda2c2fc963094",
"checks": {
"no_truth_feedback": true,
"scan_end_odometry_enabled": true,
"critical_cloud_qos_reliable": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"fault_stop_latency": true,
"fault_exercised": true,
"upper_continued": true,
"lower_stopped": true,
"restored_data_without_motion": true
},
"aligned_start": true,
"critical_cloud_qos": {
"/sim/navigation/fused_planning_cloud": [
{
"kind": "publisher",
"node": "dual_lidar_fusion",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "ramp_mission",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
],
"/sim/navigation/terrain_planning_cloud": [
{
"kind": "publisher",
"node": "step_blocker",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "lio_navigation_adapter",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
},
{
"kind": "subscription",
"node": "scan_planner_node",
"reliability": "ReliabilityPolicy.RELIABLE",
"depth": 0
}
]
},
"scan_end_odometry_enabled": true,
"task_duration_sim_s": 3.980000000000001,
"motion_metrics": {
"straight_peak_mps": 0.0,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.0,
"uphill_peak_mps": 0.6975185063660005,
"crest_peak_mps": 0.0,
"crest_median_mps": null
},
"ramp_clearance_m": 0.0820635456321619,
"north_corridor_gap_bound_m": null,
"maximum_ramp_lateral_error_m": 0.004627955373306847,
"fault_event": {
"kind": "lower_loss",
"start": 6.170000000000001,
"initial": {
"stamp": 6.171,
"pos": [
1.7780411250655905,
3.5165132142190454,
0.3083986072599763
],
"yaw": -3.140640069975591,
"rpy": [
-0.00015963488787875245,
-0.1689465608185399,
-3.140640069975591
],
"quaternion": [
0.08437288113030945,
-3.934672904660504e-05,
0.9964341405680238,
-0.0004678590271280811
],
"twist_world": [
-0.6875510278455101,
-0.00029500145918747475,
0.11724446683730046
],
"wz": 0.001296648948783942
},
"lower_last_source_end": 6.072,
"lower_source_age_at_injection_s": 0.09800000000000075,
"upper_before": 5973000000,
"lower_before": 5973000000,
"upper_during_loss": 7473000000,
"lower_during_loss": 6073000000,
"restore_stamp": 7.630000000000001,
"stop_latency_s": 0.4819999999999993,
"upper_after": 8873000000,
"lower_after": 8832000000
},
"final": {
"stamp": 8.974,
"pos": [
1.52711130481976,
3.51641698253981,
0.3512003865953328
],
"yaw": -3.14054289671381,
"rpy": [
-0.0001765454898509621,
-0.168945387402001,
-3.14054289671381
],
"quaternion": [
0.08437230268852319,
-4.367279655906796e-05,
0.9964341658286082,
-0.0005155590838008418
],
"twist_world": [
9.015465489604701e-06,
-1.2819197758388362e-11,
5.284989439524054e-05
],
"wz": -1.4369617325171234e-11
},
"contact_maximum_depth_m": 0.001028302209250695
}
},
"lightweight_diagnostics": {
"scanend_light_1": {
"scope": "Lightweight diagnostic observer only, no physical acceptance verdict",
"reported_state": "SUCCEEDED",
"report": "sim_ws/log/codex_ramp_health_20261112/scanend_light_1/diagnostic.json",
"sha256": "a04d058ce688a10f1345d4e9eeabc8edc3f5b966e4ac1871ab8f355bbeb47125",
"physical_acceptance": false
},
"scanend_light_2": {
"scope": "Lightweight diagnostic observer only, no physical acceptance verdict",
"reported_state": "SUCCEEDED",
"report": "sim_ws/log/codex_ramp_health_20261112/scanend_light_2/diagnostic.json",
"sha256": "b44a351d0907306f9c9841a5afc0eb8ed579b2f34d1600dd61c26d1bb9b6f997",
"physical_acceptance": false
}
},
"source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/ramp_mission.py": "fde813875d6a8c87468138a70eac35eeb033f72376fba85a4716c2f0e9b7b65d",
"sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py": "5f5f4d4b3bb2f02ee7b22eb62c0cfdd9e703242c319f8b0c90df2d4a1be0d9e2",
"sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py": "35be521683f304e82fcfe206a33b1dc47f3560f9eb1a797afe7f6d4df9d1d753",
"sim_ws/src/r2027_robot_description/src/contact_drive.cpp": "f0da3289b62256034e2bfd6f4b4e238b62a4448b41ca447e85d851ff32e89717",
"sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro": "a6e9f375810cc8b2520a0b5776fc2e0825a2295557b1184330e8c0aa1239bc0b",
"sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py": "a26912bbcdf3382fcd1d70c50c7efaf3b41cfeaaee25956abdadc8dd20e4d030",
"sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py": "d06fb2b478575372d4a7fc940bac7f6a29bf41d2d88b196b4d629f53aaeb0e3a",
"minco_ws/src/scan/plan_env/src/grid_map.cpp": "bc46433b8926ec5ef42999f3fe8ebfd42e8e5af38cc61c83d11e2151a9da9a62",
"minco_ws/src/scan/plan_env/include/plan_env/grid_map.h": "832f3d266aa0414a2435e1fe82f7aeca2bfa889bc9589f59660e618845bd2805",
"minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp": "fd4efca1f06ac1b11af92548eb39ba0fee02114f40e968e2c53837eeda2fbe01",
"minco_ws/src/scan/plan_manage/src/planner_manager.cpp": "852b55bc7a32c4ddd2913457d4db5a6d03dcdb3deeefdef92f7eac9a8757a2b0",
"sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py": "212c33c3ef2df0aba379ff596af345909432547ace65b9a21529cd1732c87097",
"minco_ws/src/perception/Point-LIO/include/common_lib.h": "73bd1d333905b77bc4cce2f087711a68247fff55e481425967cfbf68a5f3e773",
"minco_ws/src/perception/Point-LIO/include/sensor_timestamp.h": "a49ea7e143d4cc6786075e475d27a04459ae52a2942733e02abf598170a7f17c",
"sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py": "331aece6d0f71f316ba1693c4118fcf9b55c9053e7a6d934a22b033f554cc701",
"minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py": "baca5971b6aa751e33079747bae2258f2d24d2343980b4853433c1040503c1fb",
"minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h": "209ee5b836258b187cc67e0158dc2d25f1dcdd92ae205d8dc62b24f1836de20f",
"minco_ws/src/perception/Point-LIO/src/laserMapping.cpp": "b7921e336330e18aceb19a6fdbd962f56883401a3f79fe09d13e0861b6b54b2e"
},
"scan_end_policy": "Publish only the actual final processed filter state/time_current once per frame; no extrapolation or lidar_end_time relabeling; off by default in Point-LIO",
"transport_policy": "Mission-only reliable depth-1 planning cloud chain; default real/legacy transport unchanged",
"qos_evidence_limit": "Runtime discovery confirms RELIABLE and endpoint identities; all local discovery depths are 0, so depth 1 is source configuration, not runtime discovery verification. Ideal run original FAIL retained with separate offline QoS-only reassessment.",
"pre_reliable_transport_failure": {
"report": "sim_ws/log/codex_ramp_health_20261112/final_gui_ideal/result.json",
"sha256": "96139a52fb26ed91aae3856f928d424a69dc658de728d2ab3a45a760054e351f",
"health_failure": {
"stamp": 39.39,
"ready_flag": false,
"sources": {
"ready_signal": {
"stamp": 39.39,
"age_s": 0.0,
"max_age_s": 0.15,
"ok": true
},
"estimated_odom": {
"stamp": 39.239,
"age_s": 0.15100000000000335,
"max_age_s": 0.2,
"ok": true
},
"imu": {
"stamp": 39.368,
"age_s": 0.021999999999998465,
"max_age_s": 0.1,
"ok": true
},
"fused_cloud": {
"stamp": 39.132,
"age_s": 0.25800000000000267,
"max_age_s": 0.3,
"ok": true
},
"lower_scan": {
"stamp": 39.332,
"age_s": 0.05799999999999983,
"max_age_s": 0.23,
"ok": true
}
},
"failed_checks": [
"perception_not_ready"
]
},
"readiness_events": [
{
"phase": "stale",
"reason": "",
"ready": false,
"stamp": 39.35,
"anchor_stamp": 2.053,
"odom_stamp": 39.29975,
"cloud_stamp": 39.331,
"cloud_count": 373,
"downstream_stamp": 39.032,
"required_planning_topic": "/sim/navigation/terrain_planning_cloud",
"readiness_cloud": "downstream",
"readiness_cloud_age": 0.31800000000000495,
"readiness_cloud_max_age": 0.3,
"pending_odom": 0,
"pending_cloud": 0,
"future_dropped": 0,
"known_start_base": [
-4.5,
4.5,
0.15,
0.0
],
"imu_position_base": [
0.026,
0.02329,
0.28588
],
"rotation": [
[
0.9999986870071567,
-0.001280437151804869,
0.0009932092744870237
],
[
0.0012824187534542025,
0.999997183521201,
-0.0019970858284664448
],
[
-0.0009906493342440477,
0.0019983569165067513,
0.9999975125886718
]
],
"translation": [
-4.477763433956698,
4.521494568923946,
0.4362553138964876
]
},
{
"phase": "stale",
"reason": "",
"ready": false,
"stamp": 39.650000000000006,
"anchor_stamp": 2.053,
"odom_stamp": 39.625,
"cloud_stamp": 39.631,
"cloud_count": 376,
"downstream_stamp": 39.332,
"required_planning_topic": "/sim/navigation/terrain_planning_cloud",
"readiness_cloud": "downstream",
"readiness_cloud_age": 0.31800000000000495,
"readiness_cloud_max_age": 0.3,
"pending_odom": 0,
"pending_cloud": 0,
"future_dropped": 0,
"known_start_base": [
-4.5,
4.5,
0.15,
0.0
],
"imu_position_base": [
0.026,
0.02329,
0.28588
],
"rotation": [
[
0.9999986870071567,
-0.001280437151804869,
0.0009932092744870237
],
[
0.0012824187534542025,
0.999997183521201,
-0.0019970858284664448
],
[
-0.0009906493342440477,
0.0019983569165067513,
0.9999975125886718
]
],
"translation": [
-4.477763433956698,
4.521494568923946,
0.4362553138964876
]
}
],
"accepted_as_final": false
},
"pre_fix_observations": {
"lightweight_2": {
"report": "sim_ws/log/codex_ramp_health_20261112/lightweight_2/diagnostic.json",
"sha256": "f5df2b17567c9c0ac0ba9e8744cb28a2766ebb0e52b18bda90b633cd79ab7b78",
"health_failure": {
"stamp": 41.46,
"ready_flag": true,
"sources": {
"ready_signal": {
"stamp": 41.45,
"age_s": 0.00999999999999801,
"max_age_s": 0.15,
"ok": true
},
"estimated_odom": {
"stamp": 41.356,
"age_s": 0.1039999999999992,
"max_age_s": 0.2,
"ok": true
},
"imu": {
"stamp": 41.457,
"age_s": 0.0030000000000001137,
"max_age_s": 0.1,
"ok": true
},
"fused_cloud": {
"stamp": 41.161,
"age_s": 0.2989999999999995,
"max_age_s": 0.3,
"ok": true
},
"lower_scan": {
"stamp": 41.261,
"age_s": 0.19899999999999807,
"max_age_s": 0.18,
"ok": false
}
},
"failed_checks": [
"lower_scan"
]
},
"accepted_as_final": false
},
"fixed_light_1": {
"report": "sim_ws/log/codex_ramp_health_20261112/fixed_light_1/diagnostic.json",
"sha256": "2a1b0546bec596f1f47d2f6d0f821e2df22ff09d80e770bd8cbe3691c6cf16ff",
"health_failure": {
"stamp": 38.42,
"ready_flag": true,
"sources": {
"ready_signal": {
"stamp": 38.400000000000006,
"age_s": 0.01999999999999602,
"max_age_s": 0.15,
"ok": true
},
"estimated_odom": {
"stamp": 38.318999999,
"age_s": 0.10100000100000273,
"max_age_s": 0.2,
"ok": true
},
"imu": {
"stamp": 38.418,
"age_s": 0.0020000000000024443,
"max_age_s": 0.1,
"ok": true
},
"fused_cloud": {
"stamp": 38.119,
"age_s": 0.30100000000000193,
"max_age_s": 0.3,
"ok": false
},
"lower_scan": {
"stamp": 38.319,
"age_s": 0.10099999999999909,
"max_age_s": 0.23,
"ok": true
}
},
"failed_checks": [
"fused_cloud"
]
},
"accepted_as_final": false
},
"rounded_light_2": {
"report": "sim_ws/log/codex_ramp_health_20261112/rounded_light_2/diagnostic.json",
"sha256": "9580c0fa75a07d278197deb41d2c3e47dbeaa13bc8234d4b0056dc04a16720e0",
"health_failure": {
"stamp": 6.49,
"ready_flag": false,
"sources": {
"ready_signal": {
"stamp": 6.49,
"age_s": 0.0,
"max_age_s": 0.15,
"ok": true
},
"estimated_odom": {
"stamp": 6.3395,
"age_s": 0.15050000000000008,
"max_age_s": 0.2,
"ok": true
},
"imu": {
"stamp": 6.47,
"age_s": 0.020000000000000462,
"max_age_s": 0.1,
"ok": true
},
"fused_cloud": {
"stamp": 6.233,
"age_s": 0.25700000000000056,
"max_age_s": 0.3,
"ok": true
},
"lower_scan": {
"stamp": 6.433000000000001,
"age_s": 0.056999999999999496,
"max_age_s": 0.23,
"ok": true
}
},
"failed_checks": [
"perception_not_ready"
]
},
"accepted_as_final": false
},
"transport_light_1": {
"report": "sim_ws/log/codex_ramp_health_20261112/transport_light_1/diagnostic.json",
"sha256": "cdc703e8790d545a01295fdd9f8fdccef83e1c2c352acb4130fef1b431153941",
"health_failure": {
"stamp": 38.830000000000005,
"ready_flag": false,
"sources": {
"ready_signal": {
"stamp": 38.830000000000005,
"age_s": 0.0,
"max_age_s": 0.15,
"ok": true
},
"estimated_odom": {
"stamp": 38.686,
"age_s": 0.14400000000000546,
"max_age_s": 0.2,
"ok": true
},
"imu": {
"stamp": 38.809,
"age_s": 0.0210000000000079,
"max_age_s": 0.1,
"ok": true
},
"fused_cloud": {
"stamp": 38.478,
"age_s": 0.35200000000000387,
"max_age_s": 0.3,
"ok": false
},
"lower_scan": {
"stamp": 38.778000000000006,
"age_s": 0.0519999999999996,
"max_age_s": 0.23,
"ok": true
}
},
"failed_checks": [
"perception_not_ready",
"fused_cloud"
]
},
"accepted_as_final": false
}
},
"invalid_fault_gate_attempts": {
"fixed_loss": {
"report": "sim_ws/log/codex_ramp_health_20261112/fixed_loss/result.json",
"sha256": "29df8cc40662c0123fcc6d653addc1222599f986ea280cc9a6c520e80f99b571",
"error": "KeyError('start')",
"note": "Temporary injection gate did not execute; not a physical failure or pass. Gate feature removed."
},
"fixed_loss_r1": {
"report": "sim_ws/log/codex_ramp_health_20261112/fixed_loss_r1/result.json",
"sha256": "e4668a1171a22b7ffd8263b762dc68c8f86f6fda82010219d913d7f7c31dc1d0",
"error": "RuntimeError('requested fault was not injected; the injection gate was not reached')",
"note": "Temporary injection gate did not execute; not a physical failure or pass. Gate feature removed."
}
},
"user_original_logs": {
"ramp_mission.log": {
"path": "sim_ws/log/codex_ramp_health_20261112/user_original/ramp_mission.log",
"sha256": "12768c44d3de5ef1e2f1ad493519ba9e7ded7465927e597d148026f08b8abea3"
},
"launch.log": {
"path": "sim_ws/log/codex_ramp_health_20261112/user_original/launch.log",
"sha256": "b5c8d18d700f1974e2e9bce35587e30dd71ab6ab5ebc1cffb2b89101dd38fc0f"
}
},
"original_user_run_limitation": "Old generic error contains no per-source snapshot; exact failed gate in the original run cannot be reconstructed. Matching failures reproduced independently.",
"test_logs": {
"ramp_health_stamp_test_final.log": {
"path": "sim_ws/log/ramp_health_stamp_test_final.log",
"sha256": "6dac0a7a6a6499cbc45bf50c533a93994e5576997e57f5cb7151fe1a2af9cd68"
},
"ramp_health_build_lio_end.log": {
"path": "sim_ws/log/ramp_health_build_lio_end.log",
"sha256": "91fae04e2944f3cb27086359354b568ff95a469c53f8afcc9a146c7f54940b04"
},
"ramp_health_mission_units_final.log": {
"path": "sim_ws/log/ramp_health_mission_units_final.log",
"sha256": "35519553785b501ba52bad6b2c282e0bdb941f762fac31ce65a1328fe03a0398"
},
"ramp_health_dual_units_final.log": {
"path": "sim_ws/log/ramp_health_dual_units_final.log",
"sha256": "edaf555609a9b9d56ea307a950f0917b9872abb271ba381cac03492c0b628e78"
},
"ramp_health_adapter_units_final.log": {
"path": "sim_ws/log/ramp_health_adapter_units_final.log",
"sha256": "d4ee4bb081b2c3186fcc86809357fcefa82cecf57966b993251b4169c2509010"
},
"ramp_health_build_qos.log": {
"path": "sim_ws/log/ramp_health_build_qos.log",
"sha256": "a6d90aaef3377e246b5c252d13dca233e135712ab5590ec6d85538679273fa30"
},
"ramp_health_build_planner_qos.log": {
"path": "sim_ws/log/ramp_health_build_planner_qos.log",
"sha256": "8dec7a813b5ff7cf66897fff0c3938e2244008b6872da2aa6095b31608776cea"
}
},
"unit_counts": {
"mission": 25,
"dual": 18,
"adapter": 19,
"timestamp_endpoint_roundtrips": 6000,
"timestamp_boundary_cases": 3,
"old_timestamp_mismatches": 1391,
"scan_end_publication_contract_checks": 5
},
"binaries_sha256": {
"sim_ws/install/localization/point_lio/lib/point_lio/pointlio_mapping": "7bdc4f47afb8739e522373a3370b3ffb3ea406cd199f29efb2aefb257383106a",
"sim_ws/install/classic/r2027_robot_description/lib/libbr_contact_drive.so": "65048f696b4cf519792bc62acd5c0c793a954078c2ac2149f0cc758f9da178df",
"sim_ws/install/navigation/scan_planner/lib/scan_planner/scan_planner_node": "fb8e270070dc886ac97225e4106c7bd1f44f6c974fdaa95939d6b6ae560cf9c4"
},
"legacy_straight": {
"report": "sim_ws/log/codex_ramp_health_20261112/legacy_straight/result.json",
"sha256": "a799a1833a074c16f5a8340a6e576839d4f0fbbb10fa450b9aa082dd69e7d11d",
"scope": "Original single-lidar flat entry, one straight route"
},
"limits": [
"Finite replay cases, not a worst-case timing proof for every injection phase/load",
"Lightweight run 1 reported success but took about 78 s; it is diagnostic only, not physical/performance acceptance",
"No screenshot or graphics-device certification",
"Earlier full planner suite retained one pre-existing vehicle-launch offset assertion failure; not rerun or claimed green here",
"Old r2 validation is historical source and must not be treated as current source hash verification"
]
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,654 @@
{
"status": "PASS_SCOPED",
"date": "2026-11-12",
"git_head": "cac93cae111ca5b1208ef01940d9d892af32db97",
"scope": "Known north-ramp mission only; headless simulated full routes and separately aligned fault diagnostics. No real-robot or GPU certification.",
"parameters": {
"nav_speed_mps": 0.6,
"ramp_speed_mps": 0.7,
"crest_speed_mps": 0.2,
"yaw_speed_radps": 0.8,
"lower_source_timeout_s": 0.18
},
"cases": {
"final_ideal_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/final_ideal_v2/result.json",
"report_sha256": "b8dfa5fbafe273c3b328eeb98950ad5ed8aef7b1394d75e668493bc66b479983",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"aligned_start": false,
"task_duration_sim_s": 48.86,
"motion_metrics": {
"straight_peak_mps": 0.5974687518063333,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.7913307968433138,
"uphill_peak_mps": 0.6975195525904554,
"crest_peak_mps": 0.19865943484063123,
"crest_median_mps": 0.19744442647174848
},
"ramp_clearance_m": 0.0707565494400364,
"maximum_ramp_lateral_error_m": 0.012734706075406166,
"north_corridor_gap_bound_m": 0.11719835819555743,
"final": {
"stamp": 52.861,
"pos": [
-1.3231975523283324,
3.501281981450276,
0.7489874383468182
],
"yaw": -3.1356429835959028,
"rpy": [
-3.631862749055089e-08,
1.9538490099441804e-14,
-3.1356429835959028
],
"quaternion": [
5.4011113170460895e-11,
-1.8159233422672315e-08,
0.9999955751816335,
-0.002974830609242501
],
"twist_world": [
2.1306977795228106e-13,
-1.289159222851272e-11,
5.284969263507223e-05
],
"wz": 4.811861962485738e-19
},
"fault_event": {},
"truth_service_agreement": {
"samples": 415,
"max_position_error_m": 0.0006975198608755658,
"max_angle_error_rad": 0.0010735331372864918,
"max_dense_gap_s": 0.020000000000003126
},
"contact_maximum_depth_m": 0.0010312919301116164,
"max_healthy_source_age_s": {
"lower_scan": 0.09100000000000108,
"fused_cloud": 0.2710000000000079,
"imu": 0.02400000000000091
}
},
"final_mild_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/final_mild_v2/result.json",
"report_sha256": "6d54612c2c1aa5ebc5a0912ca8c2e34d80473adaff6e3ccd2c0583de3fc4eda8",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"mission_succeeded": true,
"straight_without_intermediate_stop": true,
"requested_straight_speed_reached": true,
"requested_uphill_speed_reached": true,
"requested_turn_speed_reached": true,
"crest_speed_respected": true,
"north_corridor_clearance": true,
"no_wall_contacts": true,
"all_phases": true,
"started_at_default": true,
"final_whole_body_on_platform": true,
"platform_height": true,
"full_ramp_clearance": true,
"ramp_lateral_error": true,
"actual_ramp_contacts": true,
"contact_penetration": true
},
"aligned_start": false,
"task_duration_sim_s": 52.2,
"motion_metrics": {
"straight_peak_mps": 0.5974733051717346,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.7913295005912622,
"uphill_peak_mps": 0.6975195295365517,
"crest_peak_mps": 0.19879476055483095,
"crest_median_mps": 0.19747629863399896
},
"ramp_clearance_m": 0.07595742107726755,
"maximum_ramp_lateral_error_m": 0.008938904052378849,
"north_corridor_gap_bound_m": 0.12271899108795603,
"final": {
"stamp": 56.251,
"pos": [
-1.3242808473464918,
3.503561109399793,
0.7489874383468182
],
"yaw": -3.1350621784184916,
"rpy": [
-3.631862761229347e-08,
1.9520897859393916e-14,
-3.1350621784184916
],
"quaternion": [
5.928460820854468e-11,
-1.8159217032830356e-08,
0.999994669116491,
-0.0032652317834483404
],
"twist_world": [
2.203026470998617e-13,
-1.2897947457677835e-11,
5.28496926355128e-05
],
"wz": 4.823959899868908e-19
},
"fault_event": {},
"truth_service_agreement": {
"samples": 444,
"max_position_error_m": 0.000697532747283251,
"max_angle_error_rad": 0.0007912732824480296,
"max_dense_gap_s": 0.020000000000003126
},
"contact_maximum_depth_m": 0.001031337949243205,
"max_healthy_source_age_s": {
"lower_scan": 0.08900000000000574,
"fused_cloud": 0.26900000000000546,
"imu": 0.02300000000000324
}
},
"lower_loss_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/lower_loss_v2/result.json",
"report_sha256": "0d001c377f6fec8f50aa39a6d9af896a17366fd808f3cd8349b912966b472133",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"fault_stop_latency": true,
"fault_exercised": true,
"upper_continued": true,
"lower_stopped": true,
"restored_data_without_motion": true
},
"aligned_start": true,
"task_duration_sim_s": 3.84,
"motion_metrics": {
"straight_peak_mps": 0.0,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.0,
"uphill_peak_mps": 0.6975126098608972,
"crest_peak_mps": 0.0,
"crest_median_mps": null
},
"ramp_clearance_m": 0.08206631355424943,
"maximum_ramp_lateral_error_m": 0.005024144120719054,
"final": {
"stamp": 8.802,
"pos": [
1.6175499979316408,
3.5154283322851736,
0.335774129701886
],
"yaw": -3.1393613162496763,
"rpy": [
-0.0003752196274428159,
-0.1689450661078667,
-3.1393613162496763
],
"quaternion": [
0.08437226296740578,
-9.280944230266862e-05,
0.9964336965981413,
-0.001095861273033376
],
"twist_world": [
9.015465516121687e-06,
-1.2506310350378692e-11,
5.2849894417871115e-05
],
"wz": -1.4018885482738339e-11
},
"fault_event": {
"kind": "lower_loss",
"start": 6.130000000000001,
"initial": {
"stamp": 6.13,
"pos": [
1.7722185505687091,
3.515707995655588,
0.30939211334828126
],
"yaw": -3.139857989547242,
"rpy": [
-0.000292008857455115,
-0.16894429226910804,
-3.139857989547242
],
"quaternion": [
0.08437181640669597,
-7.230548571974128e-05,
0.9964339745308468,
-0.0008519206601234343
],
"twist_world": [
-0.6872795471678744,
-0.0015748115629487178,
0.117272019508482
],
"wz": 0.004602083585637483
},
"upper_before": 5947000000,
"lower_before": 5947000000,
"upper_during_loss": 7347000000,
"lower_during_loss": 5947000000,
"restore_stamp": 7.45,
"stop_latency_s": 0.33699999999999886,
"upper_after": 8647000000,
"lower_after": 8655000000
},
"truth_service_agreement": {
"samples": 47,
"max_position_error_m": 0.000697838202562086,
"max_angle_error_rad": 2.022857741609113e-05,
"max_dense_gap_s": 0.02000000000000135
},
"contact_maximum_depth_m": 0.0010253450524018576
},
"mission_loss_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/mission_loss_v2/result.json",
"report_sha256": "831e1449fe53183ae942d76b8040783b18548990bae11d81987b10ed20e785ad",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"fault_stop_latency": true,
"fault_exercised": true,
"lease_expiry_exercised": true
},
"aligned_start": true,
"task_duration_sim_s": null,
"motion_metrics": {
"straight_peak_mps": 0.0,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.0,
"uphill_peak_mps": 0.6975539090094934,
"crest_peak_mps": 0.0,
"crest_median_mps": null
},
"ramp_clearance_m": 0.07995131533391886,
"maximum_ramp_lateral_error_m": 0.006717925510073108,
"final": {
"stamp": 8.932,
"pos": [
1.6444309868456337,
3.5169404994973315,
0.33118900107752436
],
"yaw": -3.1383218982818453,
"rpy": [
-0.0005499897662116284,
-0.16894459215121305,
-3.1383218982818453
],
"quaternion": [
0.08437220436653449,
-0.00013603416623964024,
0.9964330044134665,
-0.0016063438579339755
],
"twist_world": [
9.015465529050653e-06,
-1.2230410710041647e-11,
5.284989442908947e-05
],
"wz": -1.3709615345608318e-11
},
"fault_event": {
"kind": "mission_loss",
"start": 6.180000000000001,
"initial": {
"stamp": 6.18,
"pos": [
1.792212229700476,
3.5175983041976204,
0.3059828896488565
],
"yaw": -3.1390849278130424,
"rpy": [
-0.00042538207236616,
-0.16893864807064043,
-3.1390849278130424
],
"quaternion": [
0.08436910832615435,
-0.00010614552057964925,
0.9964338040384015,
-0.0012314474973247728
],
"twist_world": [
-0.6875563281063883,
-0.003298313818839225,
0.11732928633260348
],
"wz": 0.005277081521529849
},
"pid": 32553,
"stop_latency_s": 0.3309999999999995,
"cleanup": "owned stopped process killed after measurement; never resumed motion"
},
"truth_service_agreement": {
"samples": 49,
"max_position_error_m": 0.0006975101439294049,
"max_angle_error_rad": 0.00030041188765681485,
"max_dense_gap_s": 0.02000000000000135
},
"contact_maximum_depth_m": 0.0010295695593448284
},
"mux_loss_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/mux_loss_v2/result.json",
"report_sha256": "63369c1c7233143b4845e5dad2bae7940a1a2f04c9c8221156f7e76f50d7f4c2",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"fault_stop_latency": true,
"fault_exercised": true,
"actuator_watchdog_exercised": true
},
"aligned_start": true,
"task_duration_sim_s": null,
"motion_metrics": {
"straight_peak_mps": 0.0,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.0,
"uphill_peak_mps": 0.6975396380813504,
"crest_peak_mps": 0.0,
"crest_median_mps": null
},
"ramp_clearance_m": 0.08130908635514533,
"maximum_ramp_lateral_error_m": 0.005473350392926957,
"final": {
"stamp": 9.098,
"pos": [
1.5894505511602757,
3.516450988843382,
0.34056709242109046
],
"yaw": -3.1397435086191883,
"rpy": [
-0.0003109568105808855,
-0.1689451953530108,
-3.1397435086191883
],
"quaternion": [
0.08437227894662419,
-7.691577340462512e-05,
0.9964338853527429,
-0.0009081575599025917
],
"twist_world": [
9.015465506652008e-06,
-1.2598697043521529e-11,
5.284989440446392e-05
],
"wz": -1.4122446785828747e-11
},
"fault_event": {
"kind": "mux_loss",
"start": 6.3500000000000005,
"initial": {
"stamp": 6.35,
"pos": [
1.7517072893262793,
3.5166911232174307,
0.3128907030707444
],
"yaw": -3.140089328385839,
"rpy": [
-0.00025305490454324034,
-0.16894473630654727,
-3.140089328385839
],
"quaternion": [
0.0843720143417648,
-6.265703269934369e-05,
0.9964340490834358,
-0.0007383069809745069
],
"twist_world": [
-0.6871348875872043,
-0.002293800199500951,
0.11726025983180759
],
"wz": 0.0022810018581059443
},
"pid": 33216,
"stop_latency_s": 0.35599999999999987,
"cleanup": "owned stopped process killed after measurement; never resumed motion"
},
"truth_service_agreement": {
"samples": 61,
"max_position_error_m": 0.0006975194537318127,
"max_angle_error_rad": 0.0003011467109919257,
"max_dense_gap_s": 0.02000000000000135
},
"contact_maximum_depth_m": 0.0010245093594700577
},
"obstacle_v2": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/obstacle_v2/result.json",
"report_sha256": "7e3d41961388b2476b89201e10c911220a9f5570df46c17ca0bf13a5ff42f12d",
"collector_sha256": "f593253b9113d3c347a7ad622f7139dddff3bb98ad37ad1387817dbe10a9d747",
"status": "PASS",
"checks": {
"no_truth_feedback": true,
"one_drive_owner": true,
"truth_crosschecked": true,
"stopped": true,
"stopped_drift": true,
"obstacle_detected": true,
"obstacle_not_contacted": true
},
"aligned_start": true,
"task_duration_sim_s": 2.7,
"motion_metrics": {
"straight_peak_mps": 0.0,
"straight_longest_stop_s": 0.0,
"nav_yaw_peak_radps": 0.0,
"uphill_peak_mps": 0.0,
"crest_peak_mps": 0.0,
"crest_median_mps": null
},
"ramp_clearance_m": 0.08336558546404405,
"maximum_ramp_lateral_error_m": 0.003956274696780504,
"final": {
"stamp": 6.621,
"pos": [
2.400854679295653,
3.5164562746119694,
0.20216473282999256
],
"yaw": -3.1411407847530515,
"rpy": [
-7.601486839154412e-05,
-0.16894546180706554,
-3.1411407847530515
],
"quaternion": [
0.08437231188421614,
-1.880930250559538e-05,
0.9964342744928721,
-0.000221922027151125
],
"twist_world": [
9.015465488871884e-06,
-1.2973214498386961e-11,
5.284989441538068e-05
],
"wz": -1.4542263054325672e-11
},
"fault_event": {
"kind": "obstacle",
"spawn_stamp": 2.6500000000000004
},
"truth_service_agreement": {
"samples": 38,
"max_position_error_m": 0.0006988835320995187,
"max_angle_error_rad": 0.0003025033528122319,
"max_dense_gap_s": 0.020000000000000462
},
"contact_maximum_depth_m": 0.0010279084133453659
}
},
"source_sha256": {
"sim_ws/src/br_sim_bringup/scripts/ramp_mission.py": "409a851828d40aae275c76d4f1a7c2e6200a0c189bea9e80a7753170c29c437f",
"sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py": "5f5f4d4b3bb2f02ee7b22eb62c0cfdd9e703242c319f8b0c90df2d4a1be0d9e2",
"sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py": "342e17695464f16a9a3b2a290c6efb3e7f3d0807b4a964dbcfb2ca3492e5d55b",
"sim_ws/src/r2027_robot_description/src/contact_drive.cpp": "f0da3289b62256034e2bfd6f4b4e238b62a4448b41ca447e85d851ff32e89717",
"sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro": "a6e9f375810cc8b2520a0b5776fc2e0825a2295557b1184330e8c0aa1239bc0b",
"sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py": "a26912bbcdf3382fcd1d70c50c7efaf3b41cfeaaee25956abdadc8dd20e4d030",
"sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py": "e1e70380f23017c12191684dfbc8d42e36bb76a48b12f5c567c99a7a0bbeffad",
"minco_ws/src/scan/plan_env/src/grid_map.cpp": "87cca925ba8179ffd21f8e07ce0d563317e738f8a690970a96af81175786c7d2",
"minco_ws/src/scan/plan_env/include/plan_env/grid_map.h": "832f3d266aa0414a2435e1fe82f7aeca2bfa889bc9589f59660e618845bd2805",
"minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp": "fd4efca1f06ac1b11af92548eb39ba0fee02114f40e968e2c53837eeda2fbe01",
"minco_ws/src/scan/plan_manage/src/planner_manager.cpp": "852b55bc7a32c4ddd2913457d4db5a6d03dcdb3deeefdef92f7eac9a8757a2b0"
},
"installed_binary_sha256": {
"sim_ws/install/navigation/scan_planner/lib/scan_planner/scan_planner_node": "5b4edabf3defc9ca504ef74e0224d463e0b58b5e06e1d61f879f3533afc6a1a3",
"sim_ws/install/navigation/scan_planner/lib/scan_planner/closed_loop_controller": "748f6290cd255f0db8a6c5b4972078632a06ea505e9923032252ce92149622e0",
"sim_ws/install/navigation/plan_env/lib/libplan_env.a": "48e43b4c63dd05696dc560bd73e0a2a42dbe44b60d428c9e0605977a4c1ccc17",
"sim_ws/install/classic/r2027_robot_description/lib/libbr_contact_drive.so": "65048f696b4cf519792bc62acd5c0c793a954078c2ac2149f0cc758f9da178df"
},
"legacy_straight": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/legacy_straight/result.json",
"sha256": "1958febda421b42173bf43a0c2fb0153f48ce1148145ea68fc71fd1ec4d5372e",
"status": "PASS",
"scope": "Original single lidar flat entry, one straight route only"
},
"logs": {
"ramp_r2_build_final.log": {
"path": "sim_ws/log/ramp_r2_build_final.log",
"sha256": "8384114bc8dd903c8869912d66541e041f29fa644b2ff7b5217ee8120d9604da"
},
"ramp_r2_build_classic.log": {
"path": "sim_ws/log/ramp_r2_build_classic.log",
"sha256": "f4671508cca88280baeadeacc1b33b0fef4e472531d02fdcbcc5fee33c86c41b"
},
"ramp_r2_planner_final_tests.log": {
"path": "sim_ws/log/ramp_r2_planner_final_tests.log",
"sha256": "429f27be0f11e78b82561a0fd21d2b9450d91ea512b2d8a1455684b22fd8ea0b"
},
"ramp_r2_planner_all_tests.log": {
"path": "sim_ws/log/ramp_r2_planner_all_tests.log",
"sha256": "8e965f20310a13020faf8e967a5f34d5533e2a26356337dfb760a320e29aec19"
},
"ramp_r2_units_final.log": {
"path": "sim_ws/log/ramp_r2_units_final.log",
"sha256": "7da9ed5e502f0737fe57d302dcf099334e927b5c9337b93110470c3ecbf99dca"
}
},
"unit_tests": {
"mission": 22,
"planner_test_targets_passed": 12
},
"full_suite_limitation": {
"passed": 12,
"total": 13,
"failed": "test_test_rectangle_launch.py: nonrectangle body_offset_x expected -0.015, actual 0.0",
"files_unchanged_since_HEAD": {
"minco_ws/src/scan/plan_manage/test/test_rectangle_launch.py": "96c6b88f4d2f65cfadea243231cae8d98cf007263ac25697dd641250674f6dcc",
"minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py": "6282c4ba5a069776a9735da8e62014b27afe6d41635d66d7facd814d4c6b13f8"
}
},
"earlier_attempts": {
"ideal": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/ideal/result.json",
"sha256": "580ea1a11d8dcab25371b4b4a145597509b60f61e10a27b5d3caa877ecc5feca",
"status": "FAIL",
"failure": "navigation_failed:blocked_timeout: global_goal_occupied_or_reference_failed",
"stop_latency_s": null,
"accepted_as_final": false
},
"feasibility": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/feasibility/result.json",
"sha256": "5adea930a21f75086d966d03622baef7841ea647f7910358208fd5eadb9807a9",
"status": "FAIL",
"failure": "navigation_failed:blocked_timeout: initial_local_plan_failed",
"stop_latency_s": null,
"accepted_as_final": false
},
"nav06": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/nav06/result.json",
"sha256": "eed7464b9e3445119e42da488c30375ec7095000ada66bf55f1cdd251c564f88",
"status": "FAIL",
"failure": "navigation_failed:blocked_timeout: global_goal_occupied_or_reference_failed",
"stop_latency_s": null,
"accepted_as_final": false
},
"endpoint_fix": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/endpoint_fix/result.json",
"sha256": "2949bd5915bee0bf30b031f606976e57674bcba7856728c60d707fcbf0fc921d",
"status": "PASS",
"failure": "platform_stopped",
"stop_latency_s": null,
"accepted_as_final": false
},
"final_ideal": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/final_ideal/result.json",
"sha256": "a6509abc4f80b12d79b9a4ef3eff9a2c45ac119c4fa733bf090e495a5714af18",
"status": "PASS",
"failure": "platform_stopped",
"stop_latency_s": null,
"accepted_as_final": false
},
"final_mild": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/final_mild/result.json",
"sha256": "625f47c38bbe278ac5ad2a15e9b947cbe9f9242d99f9c75785e245f394286f82",
"status": "PASS",
"failure": "platform_stopped",
"stop_latency_s": null,
"accepted_as_final": false
},
"lower_loss": {
"report": "sim_ws/log/codex_ramp_mission_r2_20261112/lower_loss/result.json",
"sha256": "179ec1d6ebbe98db35ed468ff7870b5e385967bff2e52749ca3505afa1c3edf7",
"status": "FAIL",
"failure": "perception_or_state_stale",
"stop_latency_s": 0.5019999999999989,
"accepted_as_final": false,
"note": "0.502 s exceeds the unchanged 0.50 s criterion; FAIL retained. Raw lower scan watchdog added, all final cases rerun."
}
},
"historical_task_durations_s": {
"old_ideal": 63.26,
"old_mild": 64.54,
"note": "Older source and speed profile; comparison is whole-task behavior, not an isolated speed-only benchmark."
}
}
+1 -1
View File
@@ -3,5 +3,5 @@ project(br_sim_bringup)
find_package(ament_cmake REQUIRED)
install(DIRECTORY launch config rviz DESTINATION share/${PROJECT_NAME}
PATTERN "__pycache__" EXCLUDE)
install(PROGRAMS scripts/scan_cloud_gate.py scripts/lio_navigation_adapter.py DESTINATION lib/${PROJECT_NAME})
install(PROGRAMS scripts/scan_cloud_gate.py scripts/lio_navigation_adapter.py scripts/dual_lidar_fusion.py scripts/ramp_mission.py scripts/mission_command_mux.py DESTINATION lib/${PROJECT_NAME})
ament_package()
@@ -0,0 +1,20 @@
# Flat-ground opt-in dual-lidar perception. Upper MID360 alone estimates motion.
lio_navigation_adapter:
ros__parameters:
required_planning_topic: /sim/navigation/fused_planning_cloud
# Raw scan batching plus LIO pose bracketing can cost two 100 ms frames.
# Keep source stamps; verify the end-to-end <=0.50 s physical loss-stop.
required_planning_max_age: 0.30
scan_planner_node:
ros__parameters:
grid_map.cloud_has_ray_origins: true
dual_lidar_fusion:
ros__parameters:
use_sim_time: true
upper_position_base: [0.015, 0.0, 0.33]
lower_position_base: [0.325, 0.0, 0.044]
lower_yaw: 1.5707963267948966
# Flat-only support plane relative to the retained motion reference point.
# Preserve the 15 mm ground band without tying it to drifting world Z.
nominal_base_height: 0.15
ground_tolerance: 0.015
@@ -0,0 +1,69 @@
# Opt-in known-ramp profile. Surveyed planes are planning priors, not lidar data.
# The 6 cm band cannot certify all obstacles <=10 cm. Flat mode is unchanged.
lio_navigation_adapter:
ros__parameters:
required_planning_topic: /sim/navigation/terrain_planning_cloud
# Two scan batches plus estimated-pose bracketing cost ~0.21 s here.
# Match the flat dual source-age gate; physical loss-stop stays <=0.50 s.
required_planning_max_age: 0.3
scan_planner_node:
ros__parameters:
# Conservative first dual-terrain envelope. Keep the original 3 cm lane
# error and 4 cm physical-clearance criteria; do not relax either.
manager.max_vel: 0.15
optimization.max_vel: 0.15
closed_loop_controller:
ros__parameters:
max_vx: 0.15
max_vy: 0.15
dual_lidar_fusion:
ros__parameters:
ground_mode: known_terrain
surface_tolerance: 0.06
traversable_planes:
- -0.8
- 2.7
- 3.0
- 4.0
- -0.17057142857142857
- 0.0
- 0.46054285714285714
- -0.8
- 2.7
- -4.0
- -3.0
- -0.17057142857142857
- 0.0
- 0.46054285714285714
- -3.0
- 3.0
- -3.0
- 3.0
- 0.0
- 0.0
- 0.6
- -1.8
- -0.8
- 3.0
- 4.0
- 0.0
- 0.0
- 0.6
- -1.8
- -0.8
- -4.0
- -3.0
- 0.0
- 0.0
- 0.6
- -7.0
- 7.0
- -8.0
- 8.0
- 0.0
- 0.0
- 0.0
step_blocker:
ros__parameters:
input_topic: /sim/navigation/fused_planning_cloud
preserve_ray_metadata: true
@@ -2,8 +2,9 @@
lio_navigation_adapter:
ros__parameters:
use_sim_time: true
imu_position_base: [0.011, 0.02329, 0.25588]
lidar_position_base: [0.0, 0.0, 0.30]
# 2026-11-10 measured optical x=.015, height=.48; base reference height=.15.
imu_position_base: [0.026, 0.02329, 0.28588]
lidar_position_base: [0.015, 0.0, 0.33]
ground_cutoff_z: 0.015
scan_planner_node:
@@ -2,8 +2,8 @@
lio_navigation_adapter:
ros__parameters:
use_sim_time: true
imu_position_base: [0.011, 0.02329, 0.25588]
lidar_position_base: [0.0, 0.0, 0.30]
imu_position_base: [0.026, 0.02329, 0.28588]
lidar_position_base: [0.015, 0.0, 0.33]
ground_cutoff_z: 0.015
# Prior LIO slope max vertical error .038 m plus 2 cm allowance.
# This intentionally cannot certify obstacles <= .10 m above known ground.
@@ -6,6 +6,7 @@ from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, Opaq
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
def generate_launch_description():
@@ -23,10 +24,13 @@ def generate_launch_description():
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'robocon_robot.launch.py')),
launch_arguments={'sensor_model': 'mid360', 'lidar': 'true', 'drive': 'contact',
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}}.items()),
'cmd_timeout':LaunchConfiguration('cmd_timeout'),
'contact_max_linear':LaunchConfiguration('contact_max_linear'),
'contact_max_yaw':LaunchConfiguration('contact_max_yaw'),
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}}.items()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'mid360_sensors.launch.py')),
launch_arguments={'sensor_profile': LaunchConfiguration('sensor_profile')}.items()),
launch_arguments={k:LaunchConfiguration(k) for k in ('sensor_profile','dual_lidar')}.items()),
]
def estimator(context):
@@ -36,13 +40,20 @@ def generate_launch_description():
return [Node(package='point_lio', executable='pointlio_mapping', name='point_lio_sim',
namespace='sim/lio', output='screen',
parameters=[os.path.join(lio, 'config', 'mid360.yaml'),
LaunchConfiguration('lio_profile')],
os.path.join(own, 'config', 'point_lio_sim.yaml'),
LaunchConfiguration('lio_profile'),
{'odometry.publish_scan_end':ParameterValue(LaunchConfiguration('lio_scan_end_odom'),value_type=bool)}],
remappings=[('/cloud_registered_full', '/sim/lio/cloud_registered_full'),
('/cloud_registered_full_lidar', '/sim/lio/cloud_registered_full_lidar')])]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('cmd_timeout',default_value='0.5'),
DeclareLaunchArgument('contact_max_linear',default_value='0.5'),
DeclareLaunchArgument('contact_max_yaw',default_value='0.5'),
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('with_lio', default_value='false'),
DeclareLaunchArgument('lio_scan_end_odom', default_value='false'),
DeclareLaunchArgument('start_sim', default_value='true'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
DeclareLaunchArgument('lio_profile', default_value=os.path.join(own, 'config', 'point_lio_sim.yaml')),
@@ -0,0 +1,71 @@
"""Opt-in known north-ramp mission. Sole drive owner is mission_command_mux."""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument,IncludeLaunchDescription,OpaqueFunction
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
own=get_package_share_directory('br_sim_bringup');scan=get_package_share_directory('scan_planner')
config=lambda name:os.path.join(own,'config',name+'.yaml')
def nodes(context):
if LaunchConfiguration('dual_lidar').perform(context).lower()!='true':raise ValueError('this mission requires dual lidar')
prior=[float(LaunchConfiguration(k).perform(context)) for k in ('x','y','z','yaw')]
profile=LaunchConfiguration('profile').perform(context)
if profile not in ('standard','fast'):raise ValueError('profile must be standard or fast')
fast=profile=='fast'
defaults=(2.5,1.1,.2,2.0) if fast else (.6,.7,.2,.8)
def speed(key,default):
value=LaunchConfiguration(key).perform(context)
return default if value=='auto' else float(value)
nav_speed,ramp_speed,crest_speed,yaw_speed=[speed(k,v) for k,v in zip(('nav_speed','ramp_speed','crest_speed','yaw_speed'),defaults)]
if not .1<=nav_speed<=(2.5 if fast else .6) or not .1<=ramp_speed<=(1.1 if fast else .7) or not .03<=crest_speed<=min(.2,ramp_speed) or not .1<=yaw_speed<=(2. if fast else 1.):raise ValueError('invalid mission speed limits for selected profile')
shared=[config('scan_sim'),config('terrain_sim'),config('lio_terrain'),config('dual_lidar'),config('dual_lidar_terrain')]
return [
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','mid360_sim.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui'),'with_lio':'true','dual_lidar':'true','cmd_timeout':'0.15',
'lio_scan_end_odom':'true',
'contact_max_linear':str(max(nav_speed,ramp_speed)),'contact_max_yaw':str(yaw_speed),
'sensor_profile':LaunchConfiguration('sensor_profile'),'lio_profile':config('point_lio_terrain'),
**{k:LaunchConfiguration(k) for k in ('x','y','z','yaw')}}.items()),
Node(package='br_sim_bringup',executable='lio_navigation_adapter.py',name='lio_navigation_adapter',output='screen',
parameters=shared+[{'initial_base_pose':prior,'planning_cloud_reliable':True}]),
Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',name='dual_lidar_fusion',output='screen',parameters=shared+[{'reliable_planning_cloud':True}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=shared+[{'reliable_cloud':True}]),
Node(package='scan_planner',executable='scan_planner_node',name='scan_planner_node',output='screen',
parameters=[os.path.join(scan,'config','planner_vehicle.yaml')]+shared+[
{'fsm.navi_mode':1,'fsm.terrain_motion':False,'grid_map.footprint_margin':.09,'grid_map.cloud_reliable':True,
'manager.max_vel':nav_speed,'optimization.max_vel':nav_speed,
'grid_map.sliding_map_size_y':6.0 if fast else 3.0,'grid_map.local_update_range_y':3.0 if fast else 1.5,
'fsm.thresh_replan':2.0 if fast else 1.0,'fsm.planning_horizon':4.0 if fast else 3.5,'manager.planning_horizon':4.0 if fast else 3.5,
'manager.max_acc':3.0 if fast else .6,'optimization.max_acc':3.0 if fast else .6}],
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),('cloud','/sim/navigation/terrain_planning_cloud')]),
Node(package='scan_planner',executable='closed_loop_controller',name='closed_loop_controller',output='screen',
parameters=[os.path.join(scan,'config','controllers_vehicle.yaml')]+shared+[
{'terrain_motion':False,'align_to_goal_yaw':True,'yaw_goal_tolerance':.015 if fast else .01,'max_vx':nav_speed,'max_vy':nav_speed,
'max_vyaw':yaw_speed,'extended_yaw_limit':fast,
'kp_yaw':5.0 if fast else 1.5,'kp_pos':1.5 if fast else .5,
'state_prediction_limit':.2 if fast else 0.,'goal_braking_acceleration':2.0 if fast else 0.,
'finish_dist':.025 if fast else .015,'goal_v_floor':.01,'goal_slow_gain':3.0 if fast else 2.0}],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/mission/navigation_cmd_vel')]),
Node(package='br_sim_bringup',executable='ramp_mission.py',name='ramp_mission',output='screen',
parameters=[{'use_sim_time':True,'profile':profile,'autostart':LaunchConfiguration('autostart'),'aligned_start':LaunchConfiguration('aligned_start'),'ramp_speed':ramp_speed,'crest_speed':crest_speed}]),
Node(package='br_sim_bringup',executable='mission_command_mux.py',name='mission_command_mux',output='screen',parameters=[{'use_sim_time':True,'max_linear':max(nav_speed,ramp_speed),'nav_max_linear':nav_speed,'max_yaw':yaw_speed}]),
]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='true'),DeclareLaunchArgument('autostart',default_value='false'),
DeclareLaunchArgument('aligned_start',default_value='false'),
DeclareLaunchArgument('profile',default_value='standard'),
DeclareLaunchArgument('nav_speed',default_value='auto'),DeclareLaunchArgument('ramp_speed',default_value='auto'),
DeclareLaunchArgument('crest_speed',default_value='auto'),DeclareLaunchArgument('yaw_speed',default_value='auto'),
DeclareLaunchArgument('gui',default_value='true'),DeclareLaunchArgument('with_rviz',default_value='true'),
DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value='4.5'),
DeclareLaunchArgument('z',default_value='0.15'),DeclareLaunchArgument('yaw',default_value='0.0'),
OpaqueFunction(function=nodes),
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','rviz.launch.py')),
condition=IfCondition(LaunchConfiguration('with_rviz')),launch_arguments={'dual_lidar':'true'}.items())])
@@ -3,17 +3,22 @@ import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import SetEnvironmentVariable
from launch.substitutions import EnvironmentVariable
from launch.actions import SetEnvironmentVariable,DeclareLaunchArgument,OpaqueFunction
from launch.substitutions import EnvironmentVariable,LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
config = os.path.join(
get_package_share_directory('br_sim_bringup'), 'rviz', 'scan_lio.rviz')
def display(context):
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
selected=config.replace('scan_lio.rviz','scan_dual_lio.rviz') if dual else config
return [Node(package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d',selected],parameters=[{'use_sim_time':True}])]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
Node(package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d', config], parameters=[{'use_sim_time': True}]),
OpaqueFunction(function=display),
])
@@ -18,13 +18,14 @@ def generate_launch_description():
os.path.join(own, 'launch', 'mid360_sim.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui'), 'with_lio': 'false',
'sensor_profile': LaunchConfiguration('sensor_profile'),
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}}.items()))
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}}.items()))
actions.append(IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(own, 'launch', 'scan_lio_navigation.launch.py')),
launch_arguments={k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}.items()))
launch_arguments={k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}.items()))
return actions
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('start_sim', default_value='true'),
DeclareLaunchArgument('with_rviz', default_value='true'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
@@ -37,5 +38,6 @@ def generate_launch_description():
OpaqueFunction(function=layers),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(own, 'launch', 'rviz.launch.py')),
condition=IfCondition(LaunchConfiguration('with_rviz'))),
condition=IfCondition(LaunchConfiguration('with_rviz')),
launch_arguments={'dual_lidar':LaunchConfiguration('dual_lidar')}.items()),
])
@@ -16,7 +16,10 @@ def generate_launch_description():
def nodes(context):
pose = [float(LaunchConfiguration(k).perform(context)) for k in ('x', 'y', 'z', 'yaw')]
return [
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
overrides=[os.path.join(own,'config','dual_lidar.yaml')] if dual else []
planning='/sim/navigation/fused_planning_cloud' if dual else '/sim/navigation/planning_cloud'
actions = [
Node(package='point_lio', executable='pointlio_mapping', name='point_lio_sim',
namespace='sim/lio', output='screen',
parameters=[os.path.join(lio, 'config', 'mid360.yaml'),
@@ -25,22 +28,27 @@ def generate_launch_description():
('/cloud_registered_full_lidar', '/sim/lio/cloud_registered_full_lidar')]),
Node(package='br_sim_bringup', executable='lio_navigation_adapter.py',
name='lio_navigation_adapter', output='screen',
parameters=[profile, {'initial_base_pose': pose}]),
parameters=[profile]+overrides+[{'initial_base_pose': pose}]),
Node(package='scan_planner', executable='scan_planner_node',
name='scan_planner_node', output='screen',
parameters=[os.path.join(scan, 'config', 'planner_vehicle.yaml'), base, profile],
parameters=[os.path.join(scan, 'config', 'planner_vehicle.yaml'), base, profile]+overrides,
remappings=[('body_pose', '/sim/navigation/body_odom'),
('sensor_pose', '/sim/navigation/sensor_odom'),
('cloud', '/sim/navigation/planning_cloud')]),
('cloud', planning)]),
Node(package='scan_planner', executable='closed_loop_controller',
name='closed_loop_controller', output='screen',
parameters=[os.path.join(scan, 'config', 'controllers_vehicle.yaml'), base, profile],
remappings=[('body_pose', '/sim/navigation/body_odom'), ('cmd_vel', '/cmd_vel')]),
]
if dual:
actions.append(Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',
name='dual_lidar_fusion',output='screen',parameters=overrides))
return actions
return LaunchDescription([
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('x', default_value='-4.5'),
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.15'),
@@ -6,6 +6,8 @@ from launch.substitutions import LaunchConfiguration
def generate_launch_description():
def hosts(context):
if LaunchConfiguration('dual_lidar').perform(context).lower()!='false':
raise ValueError('dual_lidar split-process deployment has not been validated; use flat scan_lio.launch.py')
values={k:LaunchConfiguration(k).perform(context) for k in ('x','y','z','yaw','gui','sensor_profile','terrain')}
terrain=values.pop('terrain').lower()=='true'
physical_args=[k+':='+v for k,v in values.items()]
@@ -18,5 +20,5 @@ def generate_launch_description():
'scan_lio_terrain.launch.py' if terrain else 'scan_lio_navigation.launch.py']+
navigation_args,output='screen')]
return LaunchDescription([DeclareLaunchArgument(k,default_value=v) for k,v in
[('x','-4.5'),('y','4.5'),('z','0.15'),('yaw','0.0'),('gui','false'),('sensor_profile','ideal'),('terrain','false')]]+
[('dual_lidar','false'),('x','-4.5'),('y','4.5'),('z','0.15'),('yaw','0.0'),('gui','false'),('sensor_profile','ideal'),('terrain','false')]]+
[OpaqueFunction(function=hosts)])
@@ -13,25 +13,31 @@ def generate_launch_description():
base=os.path.join(own,'config','scan_sim.yaml');terrain=os.path.join(own,'config','terrain_sim.yaml')
profile=os.path.join(own,'config','lio_terrain.yaml')
def bringup(context):
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
overrides=[os.path.join(own,'config','dual_lidar.yaml'),os.path.join(own,'config','dual_lidar_terrain.yaml')] if dual else []
prior=[float(LaunchConfiguration(k).perform(context)) for k in ('x','y','z','yaw')]
return [
actions=[
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','mid360_sim.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui'),'with_lio':'true',
'start_sim':LaunchConfiguration('start_sim'),'sensor_profile':LaunchConfiguration('sensor_profile'),
'lio_profile':os.path.join(own,'config','point_lio_terrain.yaml'),
'dual_lidar':LaunchConfiguration('dual_lidar'),
**{k:LaunchConfiguration(k) for k in ('x','y','z','yaw')}}.items()),
Node(package='br_sim_bringup',executable='lio_navigation_adapter.py',name='lio_navigation_adapter',
output='screen',parameters=[profile,{'initial_base_pose':prior}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=[terrain,profile]),
output='screen',parameters=[profile]+overrides+[{'initial_base_pose':prior}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=[terrain,profile]+overrides),
Node(package='scan_planner',executable='scan_planner_node',name='scan_planner_node',output='screen',
parameters=[os.path.join(scan,'config','planner_vehicle.yaml'),base,terrain,profile],
parameters=[os.path.join(scan,'config','planner_vehicle.yaml'),base,terrain,profile]+overrides,
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),
('cloud','/sim/navigation/terrain_planning_cloud')]),
Node(package='scan_planner',executable='closed_loop_controller',name='closed_loop_controller',output='screen',
parameters=[os.path.join(scan,'config','controllers_vehicle.yaml'),base,terrain,profile],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/cmd_vel')]),
]
if dual:actions.append(Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',name='dual_lidar_fusion',output='screen',parameters=overrides))
return actions
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('start_sim',default_value='true'),DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('gui',default_value='true'),DeclareLaunchArgument('x',default_value='3.5'),
DeclareLaunchArgument('y',default_value='3.5125'),DeclareLaunchArgument('z',default_value='0.15'),
+2
View File
@@ -10,6 +10,7 @@
<exec_depend>scan_planner</exec_depend>
<exec_depend>step_blocker</exec_depend>
<exec_depend>point_lio</exec_depend>
<exec_depend>livox_ros_driver2</exec_depend>
<exec_depend>rviz2</exec_depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
@@ -18,6 +19,7 @@
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>std_srvs</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>python3-numpy</exec_depend>
@@ -0,0 +1,158 @@
Panels:
- Class: rviz_common/Displays
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /MID360 Raw1
- /Registered Cloud1
- /Planning Cloud1
Splitter Ratio: 0.55
Tree Height: 700
Visualization Manager:
Class: ''
Displays:
- Class: rviz_default_plugins/Grid
Name: Ground Grid
Enabled: true
Alpha: 0.45
Cell Size: 1
Color: 160; 160; 164
Line Style:
Line Width: 0.03
Value: Lines
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 20
Reference Frame: <Fixed Frame>
Value: true
- Class: rviz_default_plugins/TF
Name: TF
Enabled: true
Frame Timeout: 15
Frames:
All Enabled: true
Marker Scale: 0.5
Show Arrows: true
Show Axes: true
Show Names: false
Update Interval: 0
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: MID360 Raw
Enabled: true
Alpha: 0.65
Color: 0; 160; 255
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.04
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/mid360/points
Use Fixed Frame: true
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: Fused Obstacle Cloud
Enabled: true
Alpha: 1
Color: 255; 210; 75
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.045
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/navigation/fused_cloud
Use Fixed Frame: true
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: Planning Cloud
Enabled: true
Alpha: 0.9
Color: 65; 220; 105
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.045
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/navigation/fused_planning_cloud
Use Fixed Frame: true
Value: false
- Class: rviz_default_plugins/PointCloud2
Name: MID360 Lower Raw
Enabled: true
Alpha: 0.65
Color: 255; 90; 60
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.04
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/mid360_low/points
Use Fixed Frame: true
Value: true
Enabled: true
Global Options:
Background Color: 35; 40; 48
Fixed Frame: world
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 14
Focal Point:
X: -3.5
Y: 3.5
Z: 0
Name: Current View
Pitch: 0.95
Target Frame: <Fixed Frame>
Value: Orbit (rviz_default_plugins)
Yaw: 1.57
Saved: null
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/python3
"""Deskew two raw Livox scans with estimated body poses; no truth/TF fallback.
The upper lidar alone feeds Point-LIO. Both obstacle scans retain physical ray
origins and original acquisition offsets. Missing streams revoke downstream
readiness through the existing adapter's required_planning_topic gate.
"""
from array import array
from collections import deque
import json
import math
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data,QoSProfile
from livox_ros_driver2.msg import CustomMsg
from nav_msgs.msg import Odometry
from sensor_msgs.msg import PointCloud2,PointField
from std_msgs.msg import String
from lio_navigation_adapter import quaternion,rotation
class PoseGapError(ValueError):
pass
def interpolate_poses(history,times,max_gap=.10):
"""Bracket actual per-point times, SLERP orientation, never extrapolate."""
stamps=np.array([v[0] for v in history]);times=np.asarray(times)
if len(stamps)<2 or np.any(np.diff(stamps)<=0):raise ValueError('invalid pose history')
if np.min(times)<stamps[0] or np.max(times)>stamps[-1]:raise LookupError('pose coverage pending')
hi=np.clip(np.searchsorted(stamps,times,side='right'),1,len(stamps)-1);lo=hi-1
dt=stamps[hi]-stamps[lo]
if np.max(dt)>max_gap:raise PoseGapError('pose gap exceeds maximum')
weight=(times-stamps[lo])/dt;poses=np.array([v[1] for v in history]);qs=np.array([v[2] for v in history])
a,b=qs[lo],qs[hi];dot=np.sum(a*b,axis=1);b=np.where(dot[:,None]<0,-b,b);dot=np.abs(dot)
theta=np.arccos(np.clip(dot,-1,1));den=np.sin(theta);safe=np.where(den>1e-8,den,1.)
spherical=(np.sin((1-weight)*theta)[:,None]*a+np.sin(weight*theta)[:,None]*b)/safe[:,None]
linear=(1-weight[:,None])*a+weight[:,None]*b
q=np.where((den>1e-8)[:,None],spherical,linear);q/=np.linalg.norm(q,axis=1)[:,None]
return poses[lo]+weight[:,None]*(poses[hi]-poses[lo]),q
def rotate_rows(q,xyz):
return xyz+2*np.cross(q[:,:3],np.cross(q[:,:3],xyz)+q[:,3,None]*xyz)
def project_scan(xyz,offset_ns,start_ns,history,mount,mount_rotation,front_only):
"""Return world endpoints/origins, exact times, and original body-frame Z.
Body Z is measured before the estimated world transform. It lets the
explicitly flat profile classify ground without following LIO height drift.
"""
xyz=np.asarray(xyz);offset_ns=np.asarray(offset_ns,dtype=np.int64)
if xyz.ndim!=2 or xyz.shape[1]!=3 or len(xyz)!=len(offset_ns) or not np.isfinite(xyz).all():
raise ValueError('invalid point array')
if np.any(offset_ns<0) or np.any(offset_ns>=100000000) or np.any(np.diff(offset_ns)<0):
raise ValueError('invalid acquisition offsets')
body_rays=xyz@mount_rotation.T
# Front half-plane is a DIRECTION relative to the optical origin, not the
# endpoint's translated base x. At yaw=+pi/2 it is raw lidar y<=0.
selected=body_rays[:,0]>=-1e-8 if front_only else np.ones(len(xyz),dtype=bool)
body=body_rays+mount
selected&=~((np.abs(body[:,0])<=.42)&(np.abs(body[:,1])<=.42)&(body[:,2]>=-.17)&(body[:,2]<=.28))
body=body[selected];stamps=start_ns+offset_ns[selected]
if not len(body):return np.empty((0,3)),np.empty((0,3)),stamps,np.empty(0)
pos,q=interpolate_poses(history,stamps*1e-9)
origins=pos+rotate_rows(q,np.broadcast_to(mount,body.shape))
return pos+rotate_rows(q,body),origins,stamps,body[:,2].copy()
def cloud_message(xyz,origins,times,device_ids,end_ns):
"""World-frame endpoints with world-frame origins and source time metadata."""
dtype=np.dtype([(n,'<f4') for n in ('x','y','z','origin_x','origin_y','origin_z')]+
[('time_sec','<i4'),('time_nanosec','<u4'),('sensor_id','u1')])
data=np.zeros(len(xyz),dtype=dtype)
for i,n in enumerate(('x','y','z')):data[n]=xyz[:,i];data['origin_'+n]=origins[:,i]
data['time_sec']=times//1000000000;data['time_nanosec']=times%1000000000;data['sensor_id']=device_ids
msg=PointCloud2();msg.header.frame_id='world';msg.header.stamp.sec=end_ns//1000000000;msg.header.stamp.nanosec=end_ns%1000000000
msg.height=1;msg.width=len(data);msg.point_step=dtype.itemsize;msg.row_step=msg.point_step*msg.width
for name in dtype.names:
offset=dtype.fields[name][1];datatype=PointField.FLOAT32 if offset<24 else (PointField.INT32 if name=='time_sec' else PointField.UINT32 if name=='time_nanosec' else PointField.UINT8)
msg.fields.append(PointField(name=name,offset=offset,datatype=datatype,count=1))
msg.data=array('B',data.tobytes());msg.is_dense=bool(np.isfinite(xyz).all());return msg
class DualLidarFusion(Node):
def __init__(self):
super().__init__('dual_lidar_fusion')
self.mounts=[np.array(self.declare_parameter('upper_position_base',[.015,0.,.33]).value),
np.array(self.declare_parameter('lower_position_base',[.325,0.,.044]).value)]
yaw=float(self.declare_parameter('lower_yaw',math.pi/2).value)
self.base_height=float(self.declare_parameter('nominal_base_height',.15).value)
self.ground_tolerance=float(self.declare_parameter('ground_tolerance',.015).value)
self.ground_mode=self.declare_parameter('ground_mode','flat_body').value
planes=list(self.declare_parameter('traversable_planes',[0.]*7).value)
self.surface_tolerance=float(self.declare_parameter('surface_tolerance',.06).value)
if self.ground_mode not in ('flat_body','known_terrain') or len(planes)%7 or not all(math.isfinite(v) for v in planes) or not 0<self.surface_tolerance<=.06:
raise ValueError('invalid ground mode or known terrain surfaces')
self.planes=[planes[i:i+7] for i in range(0,len(planes),7) if planes[i+1]>planes[i] and planes[i+3]>planes[i+2]]
if self.ground_mode=='known_terrain' and not self.planes:raise ValueError('known terrain needs explicit surface priors')
if not (math.isfinite(self.base_height) and math.isfinite(self.ground_tolerance) and
0<self.ground_tolerance<self.base_height):raise ValueError('invalid flat-ground reference/tolerance')
self.rotations=[np.eye(3),rotation([0.,0.,math.sin(yaw/2),math.cos(yaw/2)])]
if any(m.shape!=(3,) or not np.isfinite(m).all() for m in self.mounts) or not math.isfinite(yaw):raise ValueError('invalid extrinsics')
self.history=deque();self.scans=[deque(maxlen=10),deque(maxlen=10)];self.last=[None,None]
self.fault='';self.published=0;self.dropped=0;self.last_output=None;self.last_drop=''
self.full=self.create_publisher(PointCloud2,'/sim/navigation/fused_cloud',5)
planning_qos=QoSProfile(depth=1 if self.declare_parameter('reliable_planning_cloud',False).value else 5)
self.planning=self.create_publisher(PointCloud2,'/sim/navigation/fused_planning_cloud',planning_qos)
self.status=self.create_publisher(String,'/sim/dual_lidar/status',10)
# The estimator publishes bursts. Retain its full reliable pose sequence;
# sensor-data depth 5 discards intermediate motion during scan processing.
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,100)
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda msg,i=i:self.on_scan(i,msg),qos_profile_sensor_data)
self.create_timer(.02,self.flush);self.create_timer(.5,self.report)
def now_s(self):return self.get_clock().now().nanoseconds*1e-9
def on_pose(self,m):
if self.fault:return
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('unexpected estimated body frames')
# Use the same whole-nanosecond conversion as scan acquisition
# times. sec+fraction can differ by one floating-point ULP and
# incorrectly fail an exact scan-end pose bracket.
t=(m.header.stamp.sec*1000000000+m.header.stamp.nanosec)*1e-9;p=m.pose.pose.position;q=m.pose.pose.orientation
pos=np.array([p.x,p.y,p.z]);q=quaternion([q.x,q.y,q.z,q.w])
if not np.isfinite(pos).all():raise ValueError('nonfinite estimated pose')
# Clock delivery and odometry callbacks can be ordered differently.
# Preserve near-future source samples; flush still waits for clock
# and rejects stale poses. Never rewrite an input stamp.
if not -0.2<=self.now_s()-t<=2.:return
if self.history and t<=self.history[-1][0]:
if t==self.history[-1][0]:return
raise ValueError('estimated pose time moved backwards')
self.history.append((t,pos,q))
while len(self.history)>2 and self.history[1][0]<t-2.:self.history.popleft()
except ValueError as error:self.fault=str(error)
def on_scan(self,i,m):
if self.fault:return
t=int(m.timebase)
if m.header.frame_id!=('lidar' if i==0 else 'lidar_low') or m.point_num!=len(m.points) or m.lidar_id!=i:
self.fault='unexpected raw lidar identity/count';return
if t!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fault='lidar header/timebase mismatch';return
if self.last[i] is not None and t<=self.last[i]:
self.fault='lidar time moved backwards or repeated';return
self.last[i]=t
self.scans[i].append(m)
def flush(self):
if self.fault or len(self.history)<2:return
now=self.now_s()
while self.scans[0] and self.scans[1]:
a,b=self.scans[0][0],self.scans[1][0]
if abs(int(a.timebase)-int(b.timebase))>50000000:
self.scans[int(a.timebase)>int(b.timebase)].popleft();self.dropped+=1;continue
first=min(int(a.timebase),int(b.timebase))*1e-9
end_ns=max(int(a.timebase),int(b.timebase))+99000000
if end_ns*1e-9>now:return # Clock delivery must catch up before publishing source-stamped clouds.
if now-end_ns*1e-9>.2 or first<self.history[0][0]:
self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1;continue
if end_ns*1e-9>self.history[-1][0]:return
if not 0<=now-self.history[-1][0]<=.2:return
try:
bundles=[]
for i,m in enumerate((a,b)):
xyz=np.array([[p.x,p.y,p.z] for p in m.points],dtype=float).reshape(-1,3)
offsets=np.array([p.offset_time for p in m.points],dtype=np.int64)
bundles.append(project_scan(xyz,offsets,int(m.timebase),self.history,self.mounts[i],self.rotations[i],i==1))
xyz=np.concatenate([v[0] for v in bundles]);origins=np.concatenate([v[1] for v in bundles]);times=np.concatenate([v[2] for v in bundles])
body_z=np.concatenate([v[3] for v in bundles])
ids=np.concatenate([np.full(len(v[0]),i,dtype=np.uint8) for i,v in enumerate(bundles)])
full=cloud_message(xyz,origins,times,ids,end_ns);self.full.publish(full)
# Flat-only profile: the base motion reference is nominally
# 0.15 m above the support plane. Use original optical geometry,
# not a world-Z threshold that drifts with the LIO solution.
# Raw world cloud, ray origins and acquisition times stay intact.
ground=body_z<=-self.base_height+self.ground_tolerance
if self.ground_mode=='known_terrain':
# This explicitly selected profile uses surveyed WORLD
# surfaces. A horizontal body-plane cut is wrong when the
# vehicle pitches or a ray crosses a ramp transition.
ground=np.zeros(len(xyz),dtype=bool)
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(xyz[:,0]>=x0)&(xyz[:,0]<=x1)&(xyz[:,1]>=y0)&(xyz[:,1]<=y1)&(np.abs(xyz[:,2]-(mx*xyz[:,0]+my*xyz[:,1]+b))<=self.surface_tolerance)
planning=xyz.copy();planning[ground]=np.nan
self.planning.publish(cloud_message(planning,origins,times,ids,end_ns))
self.last_output=end_ns*1e-9;self.published+=1
self.scans[0].popleft();self.scans[1].popleft()
except LookupError:return
except PoseGapError as error:
self.last_drop=str(error);self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1
except ValueError as error:self.fault=str(error);return
def report(self):
self.status.publish(String(data=json.dumps(dict(fault=self.fault,published=self.published,dropped_pairs=self.dropped,
latest_output=self.last_output,last_sensor_timebase_ns=self.last,stamp=self.now_s(),
last_drop=self.last_drop,maximum_recent_pose_gap=max(np.diff([p[0] for p in self.history]),default=0.),
ground_mode=self.ground_mode,
lower_front_half_plane='vehicle directions x>=0; lower local y<=0'))))
def main():
rclpy.init();node=DualLidarFusion()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
@@ -72,8 +72,8 @@ class LioNavigationAdapter(Node):
def __init__(self):
super().__init__('lio_navigation_adapter')
self.prior=np.array(self.declare_parameter('initial_base_pose',[-4.5,4.5,.15,0.]).value)
self.imu=np.array(self.declare_parameter('imu_position_base',[.011,.02329,.25588]).value)
self.lidar=np.array(self.declare_parameter('lidar_position_base',[0.,0.,.30]).value)
self.imu=np.array(self.declare_parameter('imu_position_base',[.026,.02329,.28588]).value)
self.lidar=np.array(self.declare_parameter('lidar_position_base',[.015,0.,.33]).value)
if self.prior.shape!=(4,) or self.imu.shape!=(3,) or self.lidar.shape!=(3,) or not all(np.isfinite(a).all() for a in (self.prior,self.imu,self.lidar)):
raise ValueError('invalid prior or installation geometry')
self.cutoff=float(self.declare_parameter('ground_cutoff_z',.015).value)
@@ -89,7 +89,12 @@ class LioNavigationAdapter(Node):
raise ValueError('downstream planning maximum age must be in (0,0.3]')
self.downstream_stamp=None
self.alignment=None;self.fault='';self.window=deque();self.last=None
self.odom_stamp=None;self.cloud_stamp=None;self.cloud_count=0;self.last_status=-1.
self.odom_stamp=None;self.cloud_stamp=None;self.cloud_count=0;self.last_status=-1.;self.last_ready=None
self.pending_planning=deque()
# /clock and sensor callbacks are independently delivered. Keep a small
# bounded queue instead of dropping every source sample that arrives
# just before its clock tick. Nothing is published before source time.
self.pending_odom=deque();self.pending_cloud=deque();self.future_dropped=0
self.anchor_stamp=None
self.body_pub=self.create_publisher(Odometry,'/sim/navigation/body_odom',20)
self.sensor_pub=self.create_publisher(Odometry,'/sim/navigation/sensor_odom',20)
@@ -98,16 +103,19 @@ class LioNavigationAdapter(Node):
self.ready_pub=self.create_publisher(Bool,'/planning/perception_ready',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.status_pub=self.create_publisher(String,'/sim/navigation/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.tf=TransformBroadcaster(self);self.static_tf=StaticTransformBroadcaster(self)
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_odom,qos_profile_sensor_data)
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_odom,100)
self.create_subscription(PointCloud2,'/sim/lio/cloud_registered_full_lidar',self.on_cloud,qos_profile_sensor_data)
if self.planning_topic:
if self.planning_topic in ('/sim/navigation/cloud_registered','/sim/navigation/planning_cloud'):
raise ValueError('downstream gate must use a separate derived planning topic')
self.create_subscription(PointCloud2,self.planning_topic,self.on_planning_cloud,qos_profile_sensor_data)
cloud_qos=QoSProfile(depth=1) if self.declare_parameter('planning_cloud_reliable',False).value else qos_profile_sensor_data
self.create_subscription(PointCloud2,self.planning_topic,self.on_planning_cloud,cloud_qos)
self.create_timer(.05,self.health)
def on_planning_cloud(self,m):
if m.header.frame_id=='world' and m.width*m.height>0:
self.defer_until_clock(m,self.pending_planning,self.process_planning_cloud,'world')
def process_planning_cloud(self,m):
if m.width*m.height>0:
self.downstream_stamp=self.stamp(m)
@staticmethod
@@ -128,7 +136,30 @@ class LioNavigationAdapter(Node):
tr.transform.rotation.x,tr.transform.rotation.y,tr.transform.rotation.z,tr.transform.rotation.w=map(float,orientation)
return tr
def defer_until_clock(self,m,pending,handler,expected_frame,expected_child=None):
if self.fault:return
if m.header.frame_id!=expected_frame or (expected_child is not None and m.child_frame_id!=expected_child):
self.reject('unexpected LIO odometry frames' if expected_child else 'unexpected paired cloud frame');return
self.flush_pending()
if self.fault:return
t=self.stamp(m)
if t>self.now_s()+.2:
self.future_dropped+=1;return
if pending or t>self.now_s():
if len(pending)>=64:
self.reject('clock pending queue overflow');return
pending.append(m)
else:handler(m)
def flush_pending(self):
for pending,handler in ((self.pending_odom,self.process_odom),(self.pending_cloud,self.process_cloud),(self.pending_planning,self.process_planning_cloud)):
while pending and not self.fault and self.stamp(pending[0])<=self.now_s():
handler(pending.popleft())
def on_odom(self,m):
self.defer_until_clock(m,self.pending_odom,self.process_odom,'camera_init','body')
def process_odom(self,m):
if self.fault:return
try:
if m.header.frame_id!='camera_init' or m.child_frame_id!='body':raise ValueError('unexpected LIO odometry frames')
@@ -146,10 +177,14 @@ class LioNavigationAdapter(Node):
raise ValueError('LIO gap or pose discontinuity; restart with a known start pose')
self.last=(t,pos,q)
if self.alignment is None:
if np.linalg.norm(linear)>.02 or np.linalg.norm(angular)>.02:self.window.clear();return
self.window.append((t,pos,q))
if np.linalg.norm(angular)>.02:self.window.clear();return
self.window.append((t,pos,q,linear))
while len(self.window)>1 and t-self.window[1][0]>1.:self.window.popleft()
if len(self.window)<20 or t-self.window[0][0]<1.:return
# Pointwise EKF velocity jitters even when the physical body is
# still. Require a quiet full window, not a run of quiet samples.
# Keep the original speed, displacement and angular thresholds.
if np.linalg.norm(np.mean([s[3] for s in self.window],axis=0))>.02:return
if max(np.linalg.norm(s[1]-pos) for s in self.window)>.02:return
self.alignment=FixedAlignment(self.prior,self.imu,pos,q);self.anchor_stamp=t
self.static_tf.sendTransform([
@@ -178,6 +213,9 @@ class LioNavigationAdapter(Node):
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def on_cloud(self,m):
self.defer_until_clock(m,self.pending_cloud,self.process_cloud,'camera_init')
def process_cloud(self,m):
if self.fault or self.alignment is None:return
try:
t=self.stamp(m)
@@ -194,7 +232,10 @@ class LioNavigationAdapter(Node):
for i,v in enumerate(float_fields(m,names[:3],data)):v[:]=world[...,i]
out=copy.deepcopy(m);out.header.frame_id='world';out.data=array('B',data)
self.world_pub.publish(out)
self_hit=(np.abs(raw[...,0])<=.42)&(np.abs(raw[...,1])<=.42)&(raw[...,2]>=-.47)&(raw[...,2]<=-.20)
# Classify paired ORIGINAL optical points in the vehicle envelope.
# Base remains .15 m above ground; measured roof is .41 m high.
body_raw=raw+self.lidar
self_hit=(np.abs(body_raw[...,0])<=.42)&(np.abs(body_raw[...,1])<=.42)&(body_raw[...,2]>=-.17)&(body_raw[...,2]<=.28)
ground=world[...,2]<=self.cutoff
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(world[...,0]>=x0)&(world[...,0]<=x1)&(world[...,1]>=y0)&(world[...,1]<=y1)&(
@@ -205,15 +246,22 @@ class LioNavigationAdapter(Node):
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def health(self):
ready=not self.fault and self.alignment is not None and self.fresh(self.odom_stamp,.2) and self.fresh(self.cloud_stamp,.25)
if self.planning_topic:ready=ready and self.fresh(self.downstream_stamp,self.planning_max_age)
self.flush_pending()
# When an external planning stream is selected (dual fusion / terrain),
# that is the cloud actually consumed by navigation. The independent
# upper registered cloud remains a display output, not a second gate.
stamp,limit=(self.downstream_stamp,self.planning_max_age) if self.planning_topic else (self.cloud_stamp,.25)
ready=not self.fault and self.alignment is not None and self.fresh(self.odom_stamp,.2) and self.fresh(stamp,limit)
changed=ready!=self.last_ready;self.last_ready=ready
self.ready_pub.publish(Bool(data=bool(ready)))
if self.now_s()-self.last_status<.5:return
if self.now_s()-self.last_status<.5 and not changed:return
self.last_status=self.now_s()
status=dict(phase='fault' if self.fault else ('initializing' if self.alignment is None else ('active' if ready else 'stale')),
reason=self.fault,ready=bool(ready),stamp=self.now_s(),anchor_stamp=self.anchor_stamp,
odom_stamp=self.odom_stamp,cloud_stamp=self.cloud_stamp,cloud_count=self.cloud_count,
downstream_stamp=self.downstream_stamp,required_planning_topic=self.planning_topic,
readiness_cloud='downstream' if self.planning_topic else 'registered',readiness_cloud_age=None if stamp is None else self.now_s()-stamp,readiness_cloud_max_age=limit,
pending_odom=len(self.pending_odom),pending_cloud=len(self.pending_cloud),future_dropped=self.future_dropped,
known_start_base=self.prior.tolist(),imu_position_base=self.imu.tolist())
if self.alignment:status.update(rotation=self.alignment.R.tolist(),translation=self.alignment.t.tolist())
self.status_pub.publish(String(data=json.dumps(status)))
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/python3
"""One /cmd_vel owner with expiring mission leases and independent health gates."""
import json,math
from collections import deque
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import Twist,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu
from std_msgs.msg import Bool,String
from lio_navigation_adapter import quaternion
def select_command(now,lease,nav,ramp,health,max_linear=.5,max_yaw=.5):
"""Pure fail-closed arbitration. Times are ROS source/receipt seconds."""
zero=(0.,0.,0.)
if lease is None or not 0<=now-lease['stamp']<=.15:return zero,'lease_stale'
if not health:return zero,'health_not_ready'
mode=lease['mode']
if mode=='STOP':return zero,'stop_lease'
source=nav if mode=='NAV' else ramp if mode=='RAMP' else None
if source is None:return zero,'source_missing'
stamp,command=source
if stamp<lease['since'] or not 0<=now-stamp<=.12:return zero,'source_stale_or_before_grant'
if not all(math.isfinite(x) for x in command):return zero,'invalid_command'
vx,vy,wz=command;scale=min(1.,max_linear/max(math.hypot(vx,vy),1e-12))
return (vx*scale,vy*scale,max(-max_yaw,min(max_yaw,wz))),'selected_'+mode.lower()
class MissionCommandMux(Node):
def __init__(self):
super().__init__('mission_command_mux');self.lease=None;self.nav=None;self.ramp=None
self.max_linear=float(self.declare_parameter('max_linear',.5).value)
self.nav_max_linear=float(self.declare_parameter('nav_max_linear',.5).value)
self.max_yaw=float(self.declare_parameter('max_yaw',.5).value)
if not 0<self.max_linear<=2.5 or not 0<self.nav_max_linear<=self.max_linear or not 0<self.max_yaw<=2.:raise ValueError('invalid mux speed limits')
self.ready=False;self.ready_stamp=None;self.odom_stamp=None;self.imu_stamp=None;self.last_now=None
self.pending_odom=deque(maxlen=100);self.pending_imu=deque(maxlen=100)
self.output=self.create_publisher(Twist,'/cmd_vel',10)
self.status=self.create_publisher(String,'/mission/mux_status',10)
self.create_subscription(String,'/mission/control_lease',self.on_lease,1)
self.create_subscription(Twist,'/mission/navigation_cmd_vel',self.on_nav,1)
self.create_subscription(TwistStamped,'/mission/ramp_cmd_vel',self.on_ramp,1)
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_odom,20)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_timer(.02,self.tick);self.last_report=-1.
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def on_odom(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('wrong frames')
q=m.pose.pose.orientation;quaternion([q.x,q.y,q.z,q.w]);p=m.pose.pose.position
if not all(math.isfinite(v) for v in (p.x,p.y,p.z)):raise ValueError('invalid position')
self.pending_odom.append(self.stamp(m))
except ValueError:self.odom_stamp=None
def on_imu(self,m):
a=m.angular_velocity;v=m.linear_acceleration
if m.header.frame_id=='mid360_imu' and all(math.isfinite(x) for x in (a.x,a.y,a.z,v.x,v.y,v.z)):self.pending_imu.append(self.stamp(m))
else:self.imu_stamp=None;self.pending_imu.clear()
def on_lease(self,m):
try:
lease=json.loads(m.data)
if lease['mode'] not in ('STOP','NAV','RAMP') or not all(math.isfinite(lease[k]) for k in ('stamp','since')) or lease['since']>lease['stamp']:raise ValueError('invalid lease')
if self.lease and lease['stamp']<self.lease['stamp']:return
if self.lease is None or (lease['mode'],lease['since'])!=(self.lease['mode'],self.lease['since']):self.nav=None;self.ramp=None
self.lease=lease
except (ValueError,KeyError,TypeError):self.lease=None
@staticmethod
def command(m):return (m.linear.x,m.linear.y,m.angular.z)
def on_nav(self,m):self.nav=(self.now(),self.command(m))
def on_ramp(self,m):
if m.header.frame_id=='lio_base_link':self.ramp=(self.stamp(m),self.command(m.twist))
def tick(self):
now=self.now()
for queue,name in ((self.pending_odom,'odom_stamp'),(self.pending_imu,'imu_stamp')):
while queue and queue[0]<=now:setattr(self,name,queue.popleft())
if self.last_now is not None and now<self.last_now:self.lease=None;self.nav=None;self.ramp=None
self.last_now=now
fresh=lambda t,age:t is not None and 0<=now-t<=age
healthy=self.ready and fresh(self.ready_stamp,.15) and fresh(self.odom_stamp,.20) and fresh(self.imu_stamp,.10)
limit=self.nav_max_linear if self.lease and self.lease['mode']=='NAV' else self.max_linear
command,reason=select_command(now,self.lease,self.nav,self.ramp,healthy,limit,self.max_yaw)
m=Twist();m.linear.x,m.linear.y,m.angular.z=command;self.output.publish(m)
if now-self.last_report>=.1:
self.last_report=now;self.status.publish(String(data=json.dumps(dict(stamp=now,reason=reason,healthy=bool(healthy),lease=self.lease,command=command,nav_source_age_s=None if self.nav is None else now-self.nav[0],ramp_source_age_s=None if self.ramp is None else now-self.ramp[0]))))
def main():
rclpy.init();node=MissionCommandMux()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.output.publish(Twist());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/python3
"""Known-field staged mission: SCAN approach, estimated-state ramp control, stop.
No Gazebo truth, TF, entity services, or raw IMU orientation is used. All motion
is leased to a separate fail-closed mux; this node never publishes /cmd_vel.
"""
import json,math
from collections import deque
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import PoseStamped,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu,PointCloud2
from std_msgs.msg import Bool,String
from std_srvs.srv import Trigger
from scan_planner_msgs.msg import TrajectoryStatus
from livox_ros_driver2.msg import CustomMsg
from lio_navigation_adapter import quaternion,rotation,float_fields
def wrap(a):return math.atan2(math.sin(a),math.cos(a))
def attitude(q):
R=rotation(q)
return math.atan2(R[1,0],R[0,0]),math.asin(np.clip(-R[2,0],-1.,1.)),math.atan2(R[2,1],R[2,2])
def ground_height(x):
x=np.asarray(x)
return np.where(x>=2.7,0.,np.where(x<=-.8,.6,(1.6119-.597*x)/3.5))
def body_command(q,speed,y_error):
R=rotation(q)
# Requested speed is along the body ground tangent, not world horizontal.
vx=-speed*math.hypot(R[0,0],R[1,0]);vy=float(np.clip(1.5*y_error,-.06,.06))
command=np.linalg.solve(R[:2,:2],np.array([vx,vy]))
yaw,_,_=attitude(q)
return float(command[0]),float(command[1]),float(np.clip(2.*wrap(math.pi-yaw),-.25,.25))
def envelope(p,q):
R=rotation(q);center=np.asarray(p)+R@np.array([0.,0.,.055])
ext=np.abs(R)@np.array([.4,.4,.205])
return center-ext,center+ext
def speed_target(x,ramp_speed,crest_speed,fast=False):
# Brake before the selected low-speed zone: standard base x=-.25,
# experimental fast base x=-.9 (front on top, rear still clearing the ramp).
# Account for command slew and .10 s reaction; slow again at the endpoint.
deceleration=2.0 if fast else .4
distance=max(0.,x+(.9 if fast else .25))
crest_limit=math.sqrt(crest_speed**2+2*deceleration*distance)
crest_limit=max(crest_speed,crest_limit-deceleration*.10)
return min(ramp_speed,crest_limit,max(.02 if fast else .012,(5. if fast else .8)*(x+1.30)))
def obstacle_count(cloud,p,q,speed,deceleration=.4):
"""Physical-observation strip with reaction+braking distance, known ground.
Does not claim detection of every <=10 cm obstacle under the existing 6 cm
terrain filter. Explicit prior points are not fed into this guard.
"""
if cloud is None:return 0
lo,hi=envelope(p,q);distance=abs(speed)*.35+speed*speed/(2*deceleration)+.05
x,y,z=cloud.T;g=ground_height(x)
mask=np.isfinite(cloud).all(axis=1)&(z>g+.06)&(z<g+.45)&(x>=lo[0]-distance)&(x<p[0]+.1)&(y>=lo[1]-.04)&(y<=hi[1]+.04)
return int(mask.sum())
class RampMission(Node):
DIRECT={'ENTRY','CLIMB','CREST','PLATFORM'}
def __init__(self):
super().__init__('ramp_mission')
self.profile=self.declare_parameter('profile','standard').value
if self.profile not in ('standard','fast'):raise ValueError('invalid mission profile')
self.fast=self.profile=='fast'
self.ramp_acceleration=2.0 if self.fast else .4
self.autostart=self.declare_parameter('autostart',False).value
self.aligned_start=self.declare_parameter('aligned_start',False).value
self.ramp_speed=float(self.declare_parameter('ramp_speed',.7).value)
self.crest_speed=float(self.declare_parameter('crest_speed',.2).value)
if not .10<=self.ramp_speed<=(1.1 if self.fast else .7) or not .03<=self.crest_speed<=.2 or self.crest_speed>self.ramp_speed:raise ValueError('invalid drive envelope')
self.state='IDLE';self.reason='waiting_start';self.requested=bool(self.autostart)
self.pose=None;self.ready=False;self.ready_stamp=None;self.imu_stamp=None;self.gyro=None
self.lower_stamp=None;self.pending_lower=deque()
self.health_failure=None
self.lower_hold=False
self.cloud=None;self.cloud_stamp=None;self.status=None;self.nav_index=0;self.wait_goal_id=0
# Standard keeps two staging stops. Fast replaces the first approach
# goal while moving, then still stops for a checked terminal pi sweep.
self.goals=[(3.7,4.8,0.),(3.7,4.,0.),(3.7,3.5125,math.pi)]
if self.fast:self.goals=[(3.7,4.8,0.),(3.7,3.5125,math.pi)]
self.goal_sent=None;self.stable_since=None;self.enter_since=None;self.flat_since=None;self.seen_slope=False
self.pitch_zero=0.;self.start_time=None;self.last_now=None;self.events=[];self.mode='STOP';self.mode_since=0.
self.command_speed=0.;self.obstacles=0;self.last_report=-1.;self.last_control=None
self.pending_pose=deque();self.pending_imu=deque();self.pending_cloud=deque()
self.pose_window=deque()
self.goal_pub=self.create_publisher(PoseStamped,'/move_base_simple/goal',10)
self.lease_pub=self.create_publisher(String,'/mission/control_lease',1)
self.direct_pub=self.create_publisher(TwistStamped,'/mission/ramp_cmd_vel',1)
self.report_pub=self.create_publisher(String,'/mission/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,50)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(CustomMsg,'/sim/mid360_low/lidar',self.on_lower,qos_profile_sensor_data)
self.create_subscription(PointCloud2,'/sim/navigation/fused_planning_cloud',self.on_cloud,QoSProfile(depth=1))
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(TrajectoryStatus,'/planning/trajectory_status',lambda m:setattr(self,'status',m),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_service(Trigger,'/ramp_mission/start',self.start)
self.create_service(Trigger,'/ramp_mission/cancel',self.cancel)
self.create_timer(.02,self.tick)
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def start(self,req,res):
res.success=self.state=='IDLE' and not self.requested
if res.success:self.requested=True
res.message='start requested' if res.success else 'one-shot mission already requested or terminal; no automatic restart'
return res
def cancel(self,req,res):self.fail('user_cancel');res.success=True;res.message='latched stopped';return res
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def health_snapshot(self,now):
sources={'ready_signal':(self.ready_stamp,.15),'estimated_odom':(None if self.pose is None else self.pose['stamp'],.2),
'imu':(self.imu_stamp,.1),'fused_cloud':(self.cloud_stamp,.3),'lower_scan':(self.lower_stamp,.23)}
snapshot=dict(stamp=now,ready_flag=bool(self.ready),sources={},failed_checks=[] if self.ready else ['perception_not_ready'])
for name,(stamp,limit) in sources.items():
age=None if stamp is None else now-stamp
ok=age is not None and 0<=age<=limit
snapshot['sources'][name]=dict(stamp=stamp,age_s=age,max_age_s=limit,ok=ok)
if not ok:snapshot['failed_checks'].append(name)
return snapshot
def on_pose(self,m):
if len(self.pending_pose)>=100:self.fail('pose_queue_overflow');return
self.pending_pose.append(m)
def process_pose(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('pose frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear;w=m.twist.twist.angular
q=quaternion([q.x,q.y,q.z,q.w]);p=np.array([p.x,p.y,p.z]);velocity=np.array([v.x,v.y,v.z])
if not np.isfinite(p).all() or not np.isfinite(velocity).all() or not math.isfinite(w.z):raise ValueError('nonfinite pose')
t=self.stamp(m)
if self.pose is not None and t<self.pose['stamp']:raise ValueError('pose time backwards')
self.pose=dict(stamp=t,p=p,q=q,velocity=velocity,speed=float(np.linalg.norm(velocity)),wz=w.z)
self.pose_window.append(self.pose)
while self.pose_window and self.pose_window[0]['stamp']<t-(.35 if self.fast else .5):self.pose_window.popleft()
except ValueError as exc:self.fail(str(exc))
def on_imu(self,m):
if len(self.pending_imu)>=100:self.fail('imu_queue_overflow');return
self.pending_imu.append(m)
def process_imu(self,m):
g=m.angular_velocity
if m.header.frame_id!='mid360_imu' or not all(math.isfinite(v) for v in (g.x,g.y,g.z)):self.fail('invalid_imu');return
self.imu_stamp=self.stamp(m);self.gyro=np.array([g.x,g.y,g.z])
def on_lower(self,m):
# Independent of fused-cloud latency. Use the actual last acquired
# point's source time, never receipt time or an invented scan period.
if m.header.frame_id!='lidar_low' or m.lidar_id!=1 or not m.points or m.point_num!=len(m.points) or int(m.timebase)!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fail('invalid_lower_scan');return
offset=max(p.offset_time for p in m.points)
if offset>=100000000 or len(self.pending_lower)>=20:self.fail('invalid_lower_scan_timing');return
self.pending_lower.append((int(m.timebase)+int(offset))*1e-9)
def on_cloud(self,m):
if m.header.frame_id!='world':self.fail('cloud frame');return
if len(self.pending_cloud)>=10:self.fail('cloud_queue_overflow');return
self.pending_cloud.append(m)
def process_cloud(self,m):
try:
if self.cloud_stamp is not None and self.stamp(m)<self.cloud_stamp:raise ValueError('cloud time backwards')
self.cloud=np.stack(float_fields(m,('x','y','z')),axis=-1).reshape(-1,3)
self.cloud_stamp=self.stamp(m)
except ValueError as exc:self.fail(str(exc))
def transition(self,state,reason):
if self.state==state:return
self.events.append(dict(stamp=self.now(),from_state=self.state,to=state,reason=reason))
self.get_logger().info(self.state+' -> '+state+': '+reason)
self.state=state;self.reason=reason;self.stable_since=None
def fail(self,reason):
if self.state not in ('FAILED','SUCCEEDED'):self.transition('FAILED',reason)
def set_mode(self,mode,now):
if mode!=self.mode:self.mode=mode;self.mode_since=now
self.lease_pub.publish(String(data=json.dumps(dict(stamp=now,since=self.mode_since,mode=mode))))
def stationary(self):
# LIO instantaneous velocity is noisy even while physical truth is
# stopped. Require a mature position-stable window AND mean velocity;
# never accept a single low sample or the IMU flatness alone.
samples=list(self.pose_window)
if len(samples)<(15 if self.fast else 20) or samples[-1]['stamp']-samples[0]['stamp']<(.30 if self.fast else .35):return False
pos=np.array([s['p'] for s in samples]);vel=np.array([s['velocity'] for s in samples])
return bool(np.linalg.norm(np.mean(vel,axis=0))<(.02 if self.fast else .012) and np.linalg.norm(np.ptp(pos,axis=0))<.02 and max(abs(s['wz']) for s in samples)<.02)
def send_goal(self,now):
self.wait_goal_id=self.status.goal_id if self.status else 0
m=PoseStamped();m.header.frame_id='world';m.header.stamp=self.get_clock().now().to_msg()
x,y,yaw=self.goals[self.nav_index];m.pose.position.x=x;m.pose.position.y=y;m.pose.position.z=.15
m.pose.orientation.z=math.sin(yaw/2);m.pose.orientation.w=math.cos(yaw/2)
self.goal_pub.publish(m);self.goal_sent=now
self.get_logger().info('navigation waypoint %d: %.3f %.3f yaw %.3f'%(self.nav_index,x,y,yaw))
self.events.append(dict(stamp=now,goal=[x,y,yaw],event='navigation_goal'))
def tick(self):
now=self.now();dt=.02 if self.last_now is None else now-self.last_now
for queue,handler in ((self.pending_pose,self.process_pose),(self.pending_imu,self.process_imu),(self.pending_cloud,self.process_cloud)):
while queue and self.stamp(queue[0])<=now:handler(queue.popleft())
while self.pending_lower and self.pending_lower[0]<=now:
stamp=self.pending_lower.popleft()
if self.lower_stamp is not None and stamp<=self.lower_stamp:self.fail('lower_time_backwards')
self.lower_stamp=stamp
if self.last_now is not None and dt<0:self.fail('clock_backwards')
self.last_now=now;mode='STOP';command=(0.,0.,0.)
fresh=lambda t,age:t is not None and 0<=now-t<=age
health=self.health_snapshot(now);healthy=not health['failed_checks']
lower_age=None if self.lower_stamp is None else now-self.lower_stamp
holding=bool(self.fast and self.state in self.DIRECT and healthy and lower_age is not None and lower_age>.14)
if holding!=self.lower_hold:
self.events.append(dict(stamp=now,event='lower_scan_hold',active=holding,source_age_s=lower_age))
self.get_logger().info('Lower scan temporary hold: '+str(holding))
self.lower_hold=holding
try:
if self.state=='IDLE' and self.requested:
if healthy:
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=.5:
self.start_time=now
if self.aligned_start:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,_=attitude(q)
if np.linalg.norm(p[:2]-[3.7,3.5125])>.03 or abs(wrap(yaw-math.pi))>.02 or not self.stationary():self.fail('diagnostic_start_not_aligned')
else:self.pitch_zero=pitch;self.transition('ENTRY','explicit_aligned_diagnostic_start')
else:self.transition('NAVIGATE','perception_initialized');self.send_goal(now)
else:self.stable_since=None
elif self.state not in ('IDLE','FAILED','SUCCEEDED'):
if not healthy:
self.health_failure=health
self.get_logger().error('Health stop in '+self.state+': '+json.dumps(health))
self.fail('perception_or_state_stale')
elif now-self.start_time>180:self.fail('mission_timeout')
elif self.state=='NAVIGATE':
s=self.status;x,y,_=self.goals[self.nav_index]
matched=s is not None and s.goal_id>self.wait_goal_id and abs(s.goal.x-x)<1e-5 and abs(s.goal.y-y)<1e-5 and self.stamp(s)>=self.goal_sent
if now-self.goal_sent>100:self.fail('navigation_timeout')
elif matched and s.state==s.FAILED:self.fail('navigation_failed:'+s.reason)
elif matched and s.state==s.ACTIVE and fresh(self.stamp(s),.2):
mode='NAV'
if self.fast and self.nav_index==0 and self.pose['p'][0]>=3.0 and abs(self.pose['p'][1]-4.8)<.05:
# Replace the approach target without requiring a
# stop at a geometrical staging point. The next
# SCAN trajectory still needs its own safety grant.
self.events.append(dict(stamp=now,event='approach_pass_through',position=self.pose['p'].tolist()))
self.nav_index=1;self.send_goal(now);mode='STOP'
elif matched and s.state==s.SUCCEEDED:
if self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.05 if self.fast else .25):
self.nav_index+=1
if self.nav_index<len(self.goals):self.send_goal(now);self.stable_since=None
else:
yaw,pitch,_=attitude(self.pose['q'])
if abs(wrap(yaw-math.pi))>.02 or abs(self.pose['p'][1]-3.5125)>.03:self.fail('entry_alignment_outside_tolerance')
else:self.pitch_zero=pitch;self.transition('ENTRY','navigation_handoff_stopped')
else:self.stable_since=None
elif self.state in self.DIRECT:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,roll=attitude(q);lo,hi=envelope(p,q)
if abs(wrap(yaw-math.pi))>.06 or abs(roll)>.09 or abs(pitch-self.pitch_zero)>.35:self.fail('attitude_outside_corridor_envelope')
elif p[0]<3.1 and min(lo[1]-3.025,4.-hi[1])<.06:self.fail('estimated_lateral_clearance')
elif lo[0]<-1.76:self.fail('platform_end_guard')
else:
tilted=pitch-self.pitch_zero<-.07
if tilted:
if self.enter_since is None:self.enter_since=now
if now-self.enter_since>=.15:
self.seen_slope=True
if self.state=='ENTRY':self.transition('CLIMB','sustained_uphill_pitch')
else:self.enter_since=None
if not self.seen_slope and p[0]<1.8:self.fail('expected_slope_not_detected')
if self.seen_slope and p[0]<=(-.25 if not self.fast else 0.) and self.state=='CLIMB':self.transition('CREST','braking_before_crest')
flat=self.seen_slope and p[0]<-.85 and abs(pitch-self.pitch_zero)<.035 and abs(self.gyro[1])<.12
if flat:
if self.flat_since is None:self.flat_since=now
if now-self.flat_since>=.15 and self.state=='CREST':self.transition('PLATFORM','sustained_flat_after_climb')
else:self.flat_since=None
remaining=p[0]+1.30
if self.state=='PLATFORM' and remaining<=.012 and hi[0]<=-.84:
self.transition('SETTLE','whole_envelope_on_platform')
elif self.state in self.DIRECT:
control_x=p[0]
if self.fast:
# Control-only prediction, bounded by the same
# .20 s freshness gate. Source data is unchanged.
control_x+=(rotation(q)@self.pose['velocity'])[0]*max(0.,min(.2,now-self.pose['stamp']))
target=speed_target(control_x,self.ramp_speed,self.crest_speed,self.fast)
# Slew commanded longitudinal speed; final STOP and
# safety failures bypass the ramp limiter.
if self.lower_hold:self.command_speed=0.
else:self.command_speed+=float(np.clip(target-self.command_speed,-self.ramp_acceleration*max(0,dt),self.ramp_acceleration*max(0,dt)))
self.obstacles=obstacle_count(self.cloud,p,q,max(self.command_speed,self.pose['speed']),self.ramp_acceleration)
if self.obstacles:self.fail('obstacle_in_braking_corridor')
elif not self.lower_hold:command=body_command(q,self.command_speed,3.5125-p[1]);mode='RAMP'
elif self.state=='SETTLE':
p,q=self.pose['p'],self.pose['q'];lo,hi=envelope(p,q)
if lo[0]<-1.76 or hi[0]>-.84:self.fail('settling_outside_platform')
elif self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.2 if self.fast else .6):self.transition('SUCCEEDED','platform_stopped')
else:self.stable_since=None
except (ValueError,np.linalg.LinAlgError) as exc:self.fail('invalid_control:'+str(exc))
if self.state in ('FAILED','SUCCEEDED','SETTLE'):mode='STOP';command=(0.,0.,0.)
self.set_mode(mode,now)
msg=TwistStamped();msg.header.frame_id='lio_base_link';msg.header.stamp=self.get_clock().now().to_msg()
msg.twist.linear.x,msg.twist.linear.y,msg.twist.angular.z=command;self.direct_pub.publish(msg)
if now-self.last_report>=.1:
self.last_report=now
state=dict(stamp=now,state=self.state,reason=self.reason,profile=self.profile,mode=mode,healthy=bool(healthy),nav_index=self.nav_index,
elapsed_s=None if self.start_time is None else now-self.start_time,seen_slope=self.seen_slope,obstacle_returns=self.obstacles,
command=command,events=self.events)
state['source_age_s']={key:None if stamp is None else now-stamp for key,stamp in (('lower_scan',self.lower_stamp),('fused_cloud',self.cloud_stamp),('imu',self.imu_stamp))}
state['health_failure']=self.health_failure
state['waiting_lower_scan']=self.lower_hold
if self.pose is not None:state.update(estimated_position=self.pose['p'].tolist(),estimated_yaw_pitch_roll=list(attitude(self.pose['q'])),estimated_speed=self.pose['speed'])
self.report_pub.publish(String(data=json.dumps(state)))
def main():
rclpy.init();node=RampMission()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.set_mode('STOP',node.now());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
@@ -101,10 +101,9 @@ class ScanCloudGate(Node):
surface_z=mx*xyz[0]+my*xyz[1]+b
ground |= valid & (xyz[0]>=x0)&(xyz[0]<=x1)&(xyz[1]>=y0)&(xyz[1]<=y1)&(np.abs(xyz[2]-surface_z)<.015)
# Exact same point indices and acquisition stamp; no latest-pose approximation.
# Body envelope in lidar coordinates: mount z=.30, body z=[-.15,.08].
# 2 cm numerical margin includes the fixed support wheels and roof returns.
self_hit = ((np.abs(rx) <= .42) & (np.abs(ry) <= .42) &
(rz >= -.47) & (rz <= -.20))
# Optical->base translation (.015,0,.33), with 2 cm envelope padding.
self_hit = ((np.abs(rx + .015) <= .42) & (np.abs(ry) <= .42) &
(rz + .33 >= -.17) & (rz + .33 <= .28))
for v in xyz:
v[ground | self_hit] = np.nan
out = copy.deepcopy(m)
@@ -37,19 +37,20 @@
外部包**未被修改**:哈希记录见 `sim_ws/log/p2_001/deliver/MANIFEST.txt`。
## 3. 尺寸与几何(本任务决定,R1 未改动)
## 3. 当前尺寸与几何(2026-11-10 按用户测量更新)
| 项 | 取值 | 依据 |
|---|---|---|
| 水平外包络 | **0.80 × 0.80 m** | `minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml` 记录的整车最大外包络 |
| 车体箱体 | 0.80 × 0.80 × 0.16 m | 外包络即箱体 XY;高度沿用外部模型的 0.16 |
| 车体外包络 | **0.80 × 0.80 × 0.41 m** | 用户测量:含支撑轮的车体尺寸 |
| 车体箱体 | 0.80 × 0.80 × 0.34 m,局部中心 z=0.09 m | 上沿离地 0.41 m;下沿保留离地 0.07 m 的简化假设 |
| 支撑轮 | 4 × 圆柱,r = 0.10 m,宽 0.06 m | 半径沿用外部模型;**轮位重新布置** |
| 轮心位置 | x = ±0.30 m,y = ±0.30 m,z = −0.05 m | 使轮外缘与箱体边沿齐平(max\|x\| = 0.40),外包络正好 0.80 |
| `base_link` | 箱体几何中心 | 模型原点与它重合 |
| `base_link` | 水平中心、名义离地 0.15 m 的运动参考点 | 保持导航参考高度;不是箱体几何中心 |
| 名义触地面 | base_link 下方 **0.15 m** | = 轮半径 0.10 − 轮心偏移 (−0.05) |
轮心位置是**本任务的设计决定**,不是外部模型的数值(外部为 x=±0.18、y=±0.22,配 0.53×0.56 车体)。
改车体尺寸只需改 xacro 顶部四个 property。
当前尺寸和雷达安装的来源、适配与验证见 `sim_ws/docs/VEHICLE_GEOMETRY.md`。
早期沿用的 0.16 m 箱体高度已被替换;外部原始资源未修改。
## 4. 质量、质心与惯量(R1 修正为绕质心)
@@ -58,19 +59,20 @@
| 车体质量 | 5.51 kg | 沿用外部简化模型(建模假设) |
| 轮质量 | 1.2 kg × 4 | 沿用外部简化模型 |
| 总质量 M | **10.31 kg** | 5.51 + 4×1.2 |
| 质心(相对 base_link) | **(0, 0, −0.023278370514) m** | `com_z = 4·m_w·wheel_z / M`;x/y 因对称性为 0 |
| Ixx / Iyy / Izz(绕质心、轴向与 base_link 平行) | **0.757474524410 / 0.768034524410 / 1.465173333333 kg·m²** | 平行轴定理逐体累加 |
| 质心(相对 base_link) | **(0, 0, 0.024820562561) m** | `com_z = (m_b·body_z + 4·m_w·wheel_z) / M`;x/y 因对称性为 0 |
| Ixx / Iyy / Izz(绕质心、轴向与 base_link 平行) | **0.842665751374 / 0.853225751374 / 1.465173333333 kg·m²** | 平行轴定理逐体累加 |
| 非对角项 | **0** | 4 轮关于 x/y 对称,Σ m·dᵢdⱼ 相互抵消 |
**R1 改了什么**:惯性参考系从 base_link 原点移到组合质心
(`<inertial><pose>0 0 com_z 0 0 0</pose>`),张量改为绕质心。
**base_link、模型原点、collision、visual、TF 坐标一律未动**——
**当时的 base_link、模型原点、collision、visual、TF 坐标一律未动**——
`log/p2_001_r1/INERTIA_CHECK.md` 里有「修改前后几何签名一致」的核对。
> 改前那组值(ixx=iyy=0.7630613、izz=1.4651733)是**绕 base_link 原点**的,
> 不是绕质心,**不能与上表混用**。
这些仍然是**建模假设**:真车质量、重心高度、轮组、雷达位置均未确认。
质量、重心高度、轮组和安装旋转仍然是**建模假设**;车体尺寸和雷达安装平移已由用户确认。
上表惯量已按 2026-11-10 箱体尺寸重算,不是实车惯量。
P2 只验证平地运动学接口。后续 P5 接触模式与坡道实测见 `sim_ws/docs/P5_SLOPE.md`,
仍不据此评价真实轮组牵引、打滑或实车制动距离。
@@ -112,11 +114,21 @@ P2 只验证平地运动学接口。后续 P5 接触模式与坡道实测见 `si
## 8. P6 可选 MID360 兼容模式
`lidar:=true sensor_model:=mid360` 采用物理步射线和 200 Hz 原生 ImuSensor。
光学原点仍为 base_link+(0,0,0.30) m;内置 IMU 相对光学原点的偏置按官方手册
设为 (0.011,0.02329,−0.04412) m,轴向一致。车体安装仍是假设,未测量实车位置。
光学原点现为 base_link+(0.015,0,0.330) m,名义离地 0.48 m,来自用户测量;
内置 IMU 相对光学原点的偏置按既有手册约定为 (0.011,0.02329,−0.04412) m。
因此 base_link→IMU=(0.026,0.02329,0.28588) m,各轴平行仍为安装旋转假设。
采用非重复近似方向序列,不声称复现厂家光学轨迹;默认 ideal 无注入噪声,无材质反射率模型。
可选 mild/stress 在物理观测后增加径向白噪声、丢点及 IMU 白噪声/固定偏置;
参数来自本项目工程压力配置,不是厂家规格或实车标定,时间字段保持真实采样时刻。
射线在每个真实 1 ms 物理步求交、每 100 ms 打包,时间字段没有人为细分到物理步之内。
复用仓库原 Livox 消息定义,不运行硬件驱动;MID360 模式停用原瞬时点云适配器。
默认 generic 模式保持原 P3 入口,详细语义与对照证据见 `sim_ws/docs/P6_LOCALIZATION.md`。
## 9. 2026-11-10 可选双雷达补盲
`dual_lidar:=true` 添加第二个同类物理射线插件实例,位置 (0.325,0,0.044) m、yaw=+π/2。
设备话题与 frame 分开;上雷达/IMU 与原 Point-LIO 接口保持不变,下雷达本轮不接 IMU。
新增位置与旋转、该高度前方无遮挡来自用户确认;前部开放的顶板/底板/后挡板为几何代理,
厚度与梁位没有实车测量依据。双雷达支撑轮代理 X=±0.20 m,位于新光心前方通视平面之后;
原单雷达仍为 X=±0.30 m。质量分布仍用箱体加轮子近似、按轮位重算惯量,不能评价真实铝管车架物理。
单雷达模式保留原实心箱体,外部原始模型未修改。详见 `sim_ws/docs/DUAL_MID360.md`。
@@ -1,7 +1,7 @@
"""Run MID360 and IMU simulation on an already spawned robot."""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration, EnvironmentVariable
from launch.substitutions import LaunchConfiguration, EnvironmentVariable, PythonExpression
from launch_ros.actions import Node
@@ -9,8 +9,9 @@ def generate_launch_description():
return LaunchDescription([
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
Node(package='r2027_robot_description', executable='mid360_control.py',
name='mid360_control', output='screen',
arguments=[LaunchConfiguration('sensor_profile')]),
arguments=[LaunchConfiguration('sensor_profile'), PythonExpression(["'--dual' if '",LaunchConfiguration('dual_lidar'),"'.lower() == 'true' else '--single'"])]),
])
@@ -20,6 +20,7 @@ from launch.events import Shutdown
from launch.conditions import IfCondition
from launch.substitutions import LaunchConfiguration, PythonExpression, EnvironmentVariable
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
# 端口可用环境变量 BR_SIM_MASTER_PORT 覆盖(默认 11355),须与 Gazebo 场地入口一致。
MASTER_PORT = int(os.environ.get('BR_SIM_MASTER_PORT', '11355'))
@@ -46,6 +47,9 @@ def generate_launch_description():
sensor_model = LaunchConfiguration('sensor_model').perform(context)
if sensor_model not in ('generic', 'mid360'):
raise ValueError('sensor_model must be generic or mid360')
dual = LaunchConfiguration('dual_lidar').perform(context).lower()
if dual not in ('true', 'false') or (dual=='true' and (sensor_model!='mid360' or LaunchConfiguration('lidar').perform(context).lower()!='true')):
raise ValueError('dual_lidar requires lidar=true and sensor_model=mid360')
profile_name=LaunchConfiguration('sensor_profile').perform(context)
with open(os.path.join(robot_share,'config','sensor_profiles.yaml'),encoding='utf-8') as stream:
profiles=yaml.safe_load(stream)
@@ -63,9 +67,12 @@ def generate_launch_description():
noise={k:str(profile[k]) for k in ('range_stddev','dropout','accel_stddev','gyro_stddev')}
noise.update({k:' '.join(map(str,profile[k])) for k in ('accel_bias','gyro_bias')})
noise['noise_seed']=str(profile['seed'])
limits={k:float(LaunchConfiguration(k).perform(context)) for k in ('contact_max_linear','contact_max_yaw')}
if not all(math.isfinite(v) and 0<v<=limit for v,limit in zip(limits.values(),(2.5,2.))):
raise ValueError('invalid contact actuator speed limits')
model_xml = xacro.process_file(sdf_xacro, mappings={
'lidar': LaunchConfiguration('lidar').perform(context), 'drive': drive,
'sensor_model': sensor_model,**noise}).toxml()
'sensor_model': sensor_model,'dual_lidar':dual,**noise,**{k:str(v) for k,v in limits.items()}}).toxml()
fd, path = tempfile.mkstemp(prefix='r2027_omni_', suffix='.sdf')
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
stream.write(model_xml)
@@ -80,10 +87,14 @@ def generate_launch_description():
model_path_parts.append(os.environ['GAZEBO_MODEL_PATH'])
declared_args = [
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('ros_domain_id',default_value=EnvironmentVariable('ROS_DOMAIN_ID',default_value='77')),
DeclareLaunchArgument('ros_localhost_only',default_value=EnvironmentVariable('ROS_LOCALHOST_ONLY',default_value='1')),
DeclareLaunchArgument('drive', default_value='planar'),
DeclareLaunchArgument('cmd_timeout', default_value='0.5'),
DeclareLaunchArgument('contact_max_linear', default_value='0.5'),
DeclareLaunchArgument('contact_max_yaw', default_value='0.5'),
DeclareLaunchArgument('sensor_model', default_value='mid360'),
DeclareLaunchArgument('lidar', default_value='true',
description='Enable generic CPU 3D lidar and truth data adapter'),
@@ -150,7 +161,7 @@ def generate_launch_description():
parameters=[{'use_sim_time': True,
'input_topic': '/cmd_vel',
'output_topic': '/sim/cmd_vel',
'timeout': 0.5,
'timeout': ParameterValue(LaunchConfiguration('cmd_timeout'),value_type=float),
'publish_rate': 100.0}],
)
@@ -159,7 +170,7 @@ def generate_launch_description():
name='base_to_lidar', condition=IfCondition(LaunchConfiguration('lidar')),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id', 'base_link', '--child-frame-id', 'lidar',
'--x', '0', '--y', '0', '--z', '0.30',
'--x', '0.015', '--y', '0', '--z', '0.33',
'--roll', '0', '--pitch', '0', '--yaw', '0'])
adapter = Node(
package='r2027_robot_description', executable='sim_data_adapter.py',
@@ -175,13 +186,21 @@ def generate_launch_description():
LaunchConfiguration('sensor_model'), "' == 'mid360'"])),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id','base_link','--child-frame-id','mid360_imu',
'--x','0.011','--y','0.02329','--z','0.25588',
'--x','0.026','--y','0.02329','--z','0.28588',
'--roll','0','--pitch','0','--yaw','0'])
low_tf = Node(
package='tf2_ros', executable='static_transform_publisher', name='base_to_lidar_low',
condition=IfCondition(LaunchConfiguration('dual_lidar')),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id','base_link','--child-frame-id','lidar_low',
'--x','0.325','--y','0','--z','0.044',
'--roll','0','--pitch','0','--yaw','1.5707963267948966'])
return LaunchDescription(
declared_args + env_actions
+ [OpaqueFunction(function=expand_model), spawn,
RegisterEventHandler(OnProcessExit(target_action=spawn,
on_exit=lambda event, context: [EmitEvent(event=Shutdown(reason='robot spawn failed'))]
if event.returncode != 0 else [])),
world_to_odom, cmd_timeout, lidar_tf, adapter, imu_tf])
world_to_odom, cmd_timeout, lidar_tf, adapter, imu_tf, low_tf])
@@ -24,15 +24,18 @@ def main():
if profile not in ('ideal', 'mild', 'stress'):
print('sensor_profile must be ideal, mild or stress', file=sys.stderr)
return 2
dual = '--dual' in sys.argv[2:]
rclpy.init(signal_handler_options=SignalHandlerOptions.NO)
node = rclpy.create_node('mid360_control')
publisher = node.create_publisher(Empty, '/sim/mid360/heartbeat', 10)
devices = [('/sim/mid360', ('lidar','imu'))]
if dual:devices.append(('/sim/mid360_low', ('lidar',)))
publishers = [node.create_publisher(Empty, prefix+'/heartbeat', 10) for prefix,_ in devices]
try:
for component in ('lidar', 'imu'):
invoke(node, f'/sim/mid360/{component}/profile/{profile}')
for prefix,components in devices:
for component in components:invoke(node, f'{prefix}/{component}/profile/{profile}')
node.get_logger().info(f'MID360 与 IMU 已配置为 {profile}')
while rclpy.ok():
publisher.publish(Empty())
for publisher in publishers:publisher.publish(Empty())
rclpy.spin_once(node, timeout_sec=0.2)
except KeyboardInterrupt:
pass
@@ -40,11 +43,10 @@ def main():
node.get_logger().error(str(exc))
return 1
finally:
for component in ('lidar', 'imu'):
try:
invoke(node, f'/sim/mid360/{component}/disable', wait=0.2)
except BaseException:
pass
for prefix,components in devices:
for component in components:
try:invoke(node, f'{prefix}/{component}/disable', wait=0.2)
except BaseException:pass
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
@@ -3,7 +3,7 @@
The instantaneous lidar cloud is transformed with TF at its acquisition stamp.
Pose is in world; Odometry twist stays in the stated child frame. The virtual
lidar's 0.30 m mount is shared with the SDF and static TF in the robot launch.
lidar's measured mount is shared with the SDF and static TF in the robot launch.
"""
from array import array
from collections import deque
@@ -61,7 +61,7 @@ class SimDataAdapter(Node):
self.pending_cloud.append, qos_profile_sensor_data)
self.create_subscription(Odometry, '/odom', self.pending_odom.append, 50)
self.create_timer(0.02, self.flush)
self.mount = np.array([0., 0., .30])
self.mount = np.array([.015, 0., .33])
self.clouds = 0
self.odoms = 0
@@ -12,11 +12,35 @@ from geometry_msgs.msg import Pose
def call(node, client, request, timeout=15.0):
future = client.call_async(request)
rclpy.spin_until_future_complete(node, future, timeout_sec=timeout)
if not future.done() or future.exception():
raise RuntimeError(f'{client.srv_name} did not respond within {timeout:g} s')
if not future.done():
client.remove_pending_request(future)
future.cancel()
raise TimeoutError(f'{client.srv_name} did not respond within {timeout:g} s')
if future.exception():
raise RuntimeError(f'{client.srv_name} failed: {future.exception()}')
return future.result()
def query_existing_entity(node, client, request, timeout=15.0):
"""Retry only the idempotent presence query within the original deadline.
Gazebo can receive the first request before DDS discovers the response
reader. A lost response must not be interpreted as 'entity absent'. Never
apply this retry to SpawnEntity, whose side effect may already have occurred.
"""
deadline = time.monotonic() + timeout
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(f'{client.srv_name} presence query exceeded {timeout:g} s')
try:
return call(node, client, request, min(3.0, remaining))
except TimeoutError:
if time.monotonic() >= deadline:
raise
node.get_logger().warning('实体存在性查询响应超时,重试只读查询;尚未发送生成请求')
def main():
path, entity, x, y, z, yaw = sys.argv[1:7]
rclpy.init()
@@ -28,7 +52,7 @@ def main():
raise RuntimeError('场地服务未就绪;先启动 robocon_gazebo.launch.py(robocon_robot.world)')
query = GetEntityState.Request()
query.name = entity
if call(node, state, query).success:
if query_existing_entity(node, state, query).success:
raise RuntimeError(f'机器人实体 {entity} 已存在;请勿重复启动机器人入口')
request = SpawnEntity.Request()
request.name = entity
@@ -13,19 +13,22 @@
注意:那只解释了「当时观察到转向只有指令的 0.386 倍」这一现象,**内部机理尚未完全定位**,
不能推广成「独立轮 link 必然如此」。
几何(R1 未改动):
- 水平外包络 0.80 × 0.80 m(含四个支撑轮),与 planner_vehicle.yaml 一致;
- 车体箱体 0.80 × 0.80 × 0.16 m,mass 5.51 kg(建模假设);
- 四个圆柱支撑轮 r=0.10 m、宽 0.06 m、mass 1.2 kg,轮心相对车体中心 z=-0.05 m;
- base_link 位于箱体几何中心,模型原点与它重合,名义触地面在 base_link 下方 0.15 m。
2026-11-10 用户测量:外包络 0.80 × 0.80 × 0.41 m;雷达光心前移 0.015 m、离地 0.48 m。
- 保留 base_link 为水平中心、名义离地 0.15 m 的运动参考点,不再称箱体几何中心;
- 箱体下沿保留旧模型离地 0.07 m 的假设,上沿为测量总高 0.41 m;质量仍是建模假设;
- 四个圆柱支撑轮 r=0.10 m、宽 0.06 m、mass 1.2 kg,轮心相对运动参考点 z=-0.05 m;
- 模型原点与 base_link 重合,名义触地面在 base_link 下方 0.15 m。
惯量(R1 修正):惯性参考系移到**组合质心**(z = com_z),张量绕质心、轴向与 base_link 平行。
只改惯性参考系与张量;base_link、模型原点、collision、visual 和 TF 坐标一律不移动。
按当前简化几何重算惯量;不是实车质量、质心或惯量的测量。
-->
<sdf version="1.6" xmlns:xacro="http://www.ros.org/wiki/xacro">
<xacro:arg name="lidar" default="false"/>
<xacro:arg name="drive" default="planar"/>
<xacro:arg name="contact_max_linear" default="0.5"/>
<xacro:arg name="contact_max_yaw" default="0.5"/>
<xacro:arg name="sensor_model" default="generic"/>
<xacro:arg name="dual_lidar" default="false"/>
<xacro:arg name="range_stddev" default="0"/>
<xacro:arg name="dropout" default="0"/>
<xacro:arg name="accel_stddev" default="0"/>
@@ -35,14 +38,27 @@
<xacro:arg name="noise_seed" default="2027"/>
<xacro:property name="body_length" value="0.80"/>
<xacro:property name="body_width" value="0.80"/>
<xacro:property name="body_height" value="0.16"/>
<xacro:property name="base_height" value="0.15"/>
<xacro:property name="vehicle_height" value="0.41"/>
<xacro:property name="body_bottom_height" value="0.07"/>
<xacro:property name="body_height" value="${vehicle_height - body_bottom_height}"/>
<xacro:property name="body_z" value="${(vehicle_height + body_bottom_height)/2 - base_height}"/>
<xacro:property name="lidar_x" value="0.015"/>
<xacro:property name="lidar_y" value="0.0"/>
<xacro:property name="lidar_z" value="${0.48 - base_height}"/>
<xacro:property name="body_mass" value="5.51"/>
<xacro:property name="wheel_mass" value="1.2"/>
<xacro:property name="wheel_radius" value="0.10"/>
<xacro:property name="wheel_width" value="0.06"/>
<xacro:property name="wheel_x" value="0.30"/>
<!-- In dual mode keep unmeasured support proxies behind the confirmed
clear optical plane x=.325; do not fabricate laser transparency.
Historical x=.30 plus radius=.10 hid the near edge of low obstacles
during sideways approaches. x=.20 keeps max wheel x=.30 behind the
optical plane. This is a visibility proxy, not measured wheel placement.
Regression: tools/test_dual_acceptance.py. Keep the .80 m footprint. -->
<xacro:property name="wheel_x" value="${0.20 if '$(arg dual_lidar)'.lower() == 'true' else 0.30}"/>
<xacro:property name="wheel_y" value="0.30"/>
<xacro:property name="wheel_z" value="-0.05"/>
@@ -60,13 +76,13 @@
value="${wheel_mass * (3.0*wheel_radius*wheel_radius + wheel_width*wheel_width) / 12.0}"/>
<!-- 组合刚体:总质量、质心、绕质心的惯量(全部由参数算,不写近似常数)。
车体箱体 COM 在 base_link 原点 (0,0,0);四个轮子 COM 在 (±wheel_x, ±wheel_y, wheel_z),
关于 x/y 对称 ⇒ 质心只在 z 上偏移:com_z = 4·m_w·wheel_z / M。
箱体 COM 在 (0,0,body_z);四个轮子 COM 在 (±wheel_x, ±wheel_y, wheel_z),
关于 x/y 对称 ⇒ 质心只在 z 上偏移。
绕质心用平行轴:自身 COM 惯量 + m·|d|²,d 为自身 COM 指向系统质心的向量。
z 向偏移只进 Ixx/Iyy(含 dz²),不进 Izz(只含 dx²+dy²)。 -->
<xacro:property name="total_mass" value="${body_mass + 4.0*wheel_mass}"/>
<xacro:property name="com_z" value="${4.0*wheel_mass*wheel_z / total_mass}"/>
<xacro:property name="dz_body" value="${0.0 - com_z}"/>
<xacro:property name="com_z" value="${(body_mass*body_z + 4.0*wheel_mass*wheel_z) / total_mass}"/>
<xacro:property name="dz_body" value="${body_z - com_z}"/>
<xacro:property name="dz_wheel" value="${wheel_z - com_z}"/>
<xacro:property name="tot_ixx"
value="${body_ixx + body_mass*dz_body*dz_body + 4.0*(wheel_i_perp + wheel_mass*(wheel_y*wheel_y + dz_wheel*dz_wheel))}"/>
@@ -129,7 +145,7 @@
<static>false</static>
<allow_auto_disable>false</allow_auto_disable>
<!-- ===== 车体:base_link 即箱体几何中心,模型原点与它重合 ===== -->
<!-- base_link 保留运动参考点;箱体上移/增高以匹配实测外包络。 -->
<link name="base_link">
<pose>0 0 0 0 0 0</pose>
<inertial>
@@ -145,14 +161,15 @@
<izz>${tot_izz}</izz>
</inertia>
</inertial>
<xacro:unless value="$(arg dual_lidar)">
<collision name="body_collision">
<pose>0 0 0 0 0 0</pose>
<pose>0 0 ${body_z} 0 0 0</pose>
<geometry>
<box><size>${body_length} ${body_width} ${body_height}</size></box>
</geometry>
</collision>
<visual name="body_visual">
<pose>0 0 0 0 0 0</pose>
<pose>0 0 ${body_z} 0 0 0</pose>
<geometry>
<box><size>${body_length} ${body_width} ${body_height}</size></box>
</geometry>
@@ -163,16 +180,34 @@
</material>
</visual>
</xacro:unless>
<xacro:if value="$(arg dual_lidar)">
<!-- Open front is confirmed by the user; slab/rear dimensions are
explicit unmeasured proxies, not reconstructed aluminium tubes.
Keep the old inertial box approximation; no measured frame mass. -->
<xacro:macro name="frame_part" params="name xyz size">
<collision name="${name}_collision"><pose>${xyz} 0 0 0</pose>
<geometry><box><size>${size}</size></box></geometry></collision>
<visual name="${name}_visual"><pose>${xyz} 0 0 0</pose>
<geometry><box><size>${size}</size></box></geometry>
<material><ambient>0.35 0.4 0.5 1</ambient><diffuse>0.35 0.4 0.5 1</diffuse></material>
</visual>
</xacro:macro>
<xacro:frame_part name="frame_floor" xyz="0 0 -0.065" size="0.8 0.8 0.03"/>
<xacro:frame_part name="frame_roof" xyz="0 0 0.25" size="0.8 0.8 0.02"/>
<xacro:frame_part name="frame_rear" xyz="-0.39 0 0.095" size="0.02 0.8 0.29"/>
</xacro:if>
<xacro:omni_wheel name="front_left" x_sign="1" y_sign="1"/>
<xacro:omni_wheel name="front_right" x_sign="1" y_sign="-1"/>
<xacro:omni_wheel name="rear_left" x_sign="-1" y_sign="1"/>
<xacro:omni_wheel name="rear_right" x_sign="-1" y_sign="-1"/>
<!-- Generic instantaneous 3D ray sensor; this is not a MID360 timing model.
Mount is a simulation assumption: 0.30 m above base_link, axes aligned. -->
Mount follows measured optical position; axis alignment remains an assumption. -->
<xacro:if value="$(arg lidar)">
<xacro:if value="${'$(arg sensor_model)' == 'generic'}">
<sensor name="lidar" type="ray">
<pose>0 0 0.30 0 0 0</pose>
<pose>${lidar_x} ${lidar_y} ${lidar_z} 0 0 0</pose>
<always_on>true</always_on>
<visualize>false</visualize>
<update_rate>10</update_rate>
@@ -197,7 +232,7 @@
<xacro:if value="${'$(arg sensor_model)' == 'mid360'}">
<!-- Official manual: IMU is (11,23.29,-44.12) mm in optical coordinates. -->
<sensor name="mid360_imu" type="imu">
<pose>0.011 0.02329 0.25588 0 0 0</pose>
<pose>${lidar_x + 0.011} ${lidar_y + 0.02329} ${lidar_z - 0.04412} 0 0 0</pose>
<always_on>true</always_on><update_rate>200</update_rate>
<imu/>
<plugin name="mid360_imu" filename="libbr_mid360_imu.so">
@@ -209,9 +244,19 @@
</xacro:if>
</xacro:if>
</link>
<xacro:if value="$(arg dual_lidar)">
<plugin name="mid360_low_sensor" filename="libbr_mid360_sensor.so">
<lidar_position>0.325 0 0.044</lidar_position>
<lidar_rpy>0 0 1.5707963267948966</lidar_rpy>
<topic_prefix>/sim/mid360_low</topic_prefix><frame_id>lidar_low</frame_id><lidar_id>1</lidar_id>
<noise_seed>${int('$(arg noise_seed)') + 10}</noise_seed>
</plugin>
</xacro:if>
<xacro:if value="$(arg lidar)">
<xacro:if value="${'$(arg sensor_model)' == 'mid360'}">
<plugin name="mid360_sensor" filename="libbr_mid360_sensor.so">
<lidar_position>${lidar_x} ${lidar_y} ${lidar_z}</lidar_position>
<range_stddev>$(arg range_stddev)</range_stddev><dropout>$(arg dropout)</dropout>
<noise_seed>$(arg noise_seed)</noise_seed>
</plugin>
@@ -240,7 +285,10 @@
</plugin>
</xacro:if>
<xacro:if value="${'$(arg drive)' == 'contact'}">
<plugin filename="libbr_contact_drive.so" name="contact_drive"/>
<plugin filename="libbr_contact_drive.so" name="contact_drive">
<max_linear_speed>$(arg contact_max_linear)</max_linear_speed>
<max_yaw_speed>$(arg contact_max_yaw)</max_yaw_speed>
</plugin>
</xacro:if>
</model>
</sdf>
@@ -23,6 +23,12 @@ class ContactDrive : public gazebo::ModelPlugin {
link_ = model->GetLink("base_link");
if (!link_) { gzerr << "ContactDrive requires base_link\n"; return; }
node_ = gazebo_ros::Node::Get(sdf);
if (sdf->HasElement("max_linear_speed")) max_linear_ = sdf->Get<double>("max_linear_speed");
if (sdf->HasElement("max_yaw_speed")) max_yaw_ = sdf->Get<double>("max_yaw_speed");
if (!std::isfinite(max_linear_) || max_linear_ <= 0 || max_linear_ > 2.5 ||
!std::isfinite(max_yaw_) || max_yaw_ <= 0 || max_yaw_ > 2.) {
gzerr << "ContactDrive invalid speed limits\n"; return;
}
manager_ = world_->Physics()->GetContactManager();
// Request real ODE contact geometry even without a separate contact sensor.
manager_->SetNeverDropContacts(true);
@@ -65,8 +71,9 @@ class ContactDrive : public gazebo::ModelPlugin {
if (world_->SimTime().Double()-received_ >= 0 &&
world_->SimTime().Double()-received_ <= .5) cmd=cmd_;
}
const double scale=std::min(1.,max_linear_/std::max(1e-12,std::hypot(cmd.linear.x,cmd.linear.y)));
const auto desired=link_->WorldPose().Rot().RotateVector(ignition::math::Vector3d(
std::clamp(cmd.linear.x,-.5,.5),std::clamp(cmd.linear.y,-.5,.5),0));
cmd.linear.x*scale,cmd.linear.y*scale,0));
const double vx=desired.X(),vy=desired.Y();
const auto v=link_->WorldLinearVel();
const double ax=std::clamp(40*(vx-v.X()),-4.,4.);
@@ -82,7 +89,7 @@ class ContactDrive : public gazebo::ModelPlugin {
applied_force_.Set(mass*((1-ny*ny)*bx+nx*ny*by)/det,
mass*(nx*ny*bx+(1-nx*nx)*by)/det,0);
if (applied_force_.Length()>150.) applied_force_ *= 150./applied_force_.Length();
const double wz=std::clamp(cmd.angular.z,-.5,.5);
const double wz=std::clamp(cmd.angular.z,-max_yaw_,max_yaw_);
const double alpha=std::clamp(40*(wz-link_->WorldAngularVel().Z()),-5.,5.);
applied_torque_.Z(link_->GetInertial()->IZZ()*alpha);
link_->AddForce(applied_force_);
@@ -154,6 +161,7 @@ class ContactDrive : public gazebo::ModelPlugin {
std::mutex mutex_;
geometry_msgs::msg::Twist cmd_;
double received_{-1},last_pub_{-1};
double max_linear_{.5},max_yaw_{.5};
ignition::math::Vector3d applied_force_,applied_torque_;
};
GZ_REGISTER_MODEL_PLUGIN(ContactDrive)
@@ -33,29 +33,40 @@ class Mid360Sensor : public gazebo::ModelPlugin {
range_stddev_=sdf->Get<double>("range_stddev",0.).first;
dropout_=sdf->Get<double>("dropout",0.).first;
seed_=sdf->Get<unsigned>("noise_seed",2027u).first;
lidar_position_=sdf->Get<ignition::math::Vector3d>("lidar_position",{.015,0.,.33}).first;
const auto rpy=sdf->Get<ignition::math::Vector3d>("lidar_rpy",{}).first;
if(!lidar_position_.IsFinite() || !rpy.IsFinite())
throw std::invalid_argument("Invalid MID360 optical pose");
lidar_rotation_=ignition::math::Quaterniond(rpy);
topic_prefix_=sdf->Get<std::string>("topic_prefix","/sim/mid360").first;
frame_id_=sdf->Get<std::string>("frame_id","lidar").first;
lidar_id_=sdf->Get<unsigned>("lidar_id",0u).first;
if(topic_prefix_.empty() || topic_prefix_.front()!='/' || topic_prefix_.back()=='/' ||
frame_id_.empty() || lidar_id_>255u)
throw std::invalid_argument("Invalid MID360 topic prefix/frame/device id");
if(!std::isfinite(range_stddev_) || range_stddev_<0 || !std::isfinite(dropout_) || dropout_<0 || dropout_>1)
throw std::invalid_argument("Invalid MID360 range noise/dropout");
rng_.seed(seed_);
node_=gazebo_ros::Node::Get(sdf);
for (int i=0;i<3;++i) {
const std::string name=std::string("/sim/mid360/lidar/profile/")+profiles_[i];
const std::string name=topic_prefix_+"/lidar/profile/"+profiles_[i];
profile_services_[i]=node_->create_service<std_srvs::srv::Trigger>(name,
[this,i](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
profile_.store(i); response->success=true; response->message=profiles_[i]; });
profile_.store(i); enabled_.store(true); response->success=true; response->message=profiles_[i]; });
}
disable_service_=node_->create_service<std_srvs::srv::Trigger>("/sim/mid360/lidar/disable",
disable_service_=node_->create_service<std_srvs::srv::Trigger>(topic_prefix_+"/lidar/disable",
[this](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
last_heartbeat_.store(0); response->success=true; response->message="disabled"; });
heartbeat_=node_->create_subscription<std_msgs::msg::Empty>("/sim/mid360/heartbeat",10,
enabled_.store(false); last_heartbeat_.store(0); response->success=true; response->message="disabled"; });
heartbeat_=node_->create_subscription<std_msgs::msg::Empty>(topic_prefix_+"/heartbeat",10,
[this](const std_msgs::msg::Empty::SharedPtr) { last_heartbeat_.store(NowSteady()); });
ray_=boost::dynamic_pointer_cast<gazebo::physics::RayShape>(
world_->Physics()->CreateShape("ray",gazebo::physics::CollisionPtr()));
if(!ray_) { gzerr << "Physics engine does not provide RayShape\n";return; }
cloud_pub_=node_->create_publisher<livox_ros_driver2::msg::CustomMsg>("/sim/mid360/lidar",10);
view_pub_=node_->create_publisher<sensor_msgs::msg::PointCloud2>("/sim/mid360/points",5);
status_pub_=node_->create_publisher<std_msgs::msg::String>("/sim/mid360/status",10);
cloud_pub_=node_->create_publisher<livox_ros_driver2::msg::CustomMsg>(topic_prefix_+"/lidar",10);
view_pub_=node_->create_publisher<sensor_msgs::msg::PointCloud2>(topic_prefix_+"/points",5);
status_pub_=node_->create_publisher<std_msgs::msg::String>(topic_prefix_+"/status",10);
update_=gazebo::event::Events::ConnectWorldUpdateEnd(std::bind(&Mid360Sensor::Sample,this));
RCLCPP_INFO(node_->get_logger(),
"MID360-compatible sensor: 200 rays/1 ms, 100 ms frames, actual acquisition stamps; optional noise/dropout");
@@ -67,13 +78,13 @@ class Mid360Sensor : public gazebo::ModelPlugin {
std::chrono::steady_clock::now().time_since_epoch()).count(); }
void Begin(int64_t now) {
frame_=livox_ros_driver2::msg::CustomMsg();
frame_.header.frame_id="lidar";
frame_.header.frame_id=frame_id_;
frame_.header.stamp=gazebo_ros::Convert<builtin_interfaces::msg::Time>(world_->SimTime());
frame_.timebase=now;frame_.lidar_id=0;
frame_.timebase=now;frame_.lidar_id=static_cast<uint8_t>(lidar_id_);
frame_.points.reserve(20000);first_=now;last_sample_=now;rays_=0;hits_=0;dropped_=0;rejected_=0;
}
void Sample() {
if (NowSteady()-last_heartbeat_.load()>1000000000LL) { first_=-1; last_=-1; return; }
if (!enabled_.load() || NowSteady()-last_heartbeat_.load()>1000000000LL) { first_=-1; last_=-1; return; }
const int selected=profile_.load();
if (selected!=applied_profile_) {
constexpr double range_noise[]={0.,.005,.015},dropout[]={0.,.01,.05};
@@ -89,7 +100,7 @@ class Mid360Sensor : public gazebo::ModelPlugin {
if(now-first_>=100000000) { Publish();Begin(now); }
last_=now;last_sample_=now;
const auto body=link_->WorldPose();
const auto origin=body.Pos()+body.Rot().RotateVector({0,0,.30});
const auto origin=body.Pos()+body.Rot().RotateVector(lidar_position_);
constexpr double pi=3.14159265358979323846;
for(unsigned i=0;i<200;++i,++index_,++rays_) {
// Documented quasi-uniform, non-repeating approximation; channels are
@@ -98,7 +109,7 @@ class Mid360Sensor : public gazebo::ModelPlugin {
const double el=(-7+59*Fraction(.5+index_*.7548776662466927600))*pi/180;
const ignition::math::Vector3d direction(std::cos(el)*std::cos(az),
std::cos(el)*std::sin(az),std::sin(el));
const auto world_dir=body.Rot().RotateVector(direction);
const auto world_dir=(body.Rot()*lidar_rotation_).RotateVector(direction);
ray_->SetPoints(origin,origin+40*world_dir);
double distance;std::string entity;
ray_->GetIntersection(distance,entity);
@@ -154,11 +165,16 @@ class Mid360Sensor : public gazebo::ModelPlugin {
int64_t first_{-1},last_{-1},last_sample_{-1},step_ns_{};
uint64_t index_{0};unsigned rays_{0},hits_{0},dropped_{0},rejected_{0},seed_{2027};
double range_stddev_{0},dropout_{0};
ignition::math::Vector3d lidar_position_;
ignition::math::Quaterniond lidar_rotation_;
std::string topic_prefix_,frame_id_;
unsigned lidar_id_{0};
std::mt19937 rng_;
std::normal_distribution<double> normal_{0.,1.};
std::uniform_real_distribution<double> uniform_{0.,1.};
gazebo::event::ConnectionPtr update_;
const char *profiles_[3]={"ideal","mild","stress"};
std::atomic<bool> enabled_{true};
std::atomic<int> profile_{0}; int applied_profile_{-1};
std::atomic<int64_t> last_heartbeat_{0};
rclcpp::Subscription<std_msgs::msg::Empty>::SharedPtr heartbeat_;
@@ -21,6 +21,16 @@
<shadows>true</shadows>
</scene>
<!-- 默认从红方(world +Y)外侧俯看红方半场,视线指向约 (0, 2.5, 0.1)。
仅设置 GUI 初始相机;单位为米、弧度,仍可用鼠标自由调整视角。 -->
<gui fullscreen="false">
<camera name="user_camera">
<pose>0 11 10 0 0.86 -1.5707963267948966</pose>
<view_controller>orbit</view_controller>
<projection_type>perspective</projection_type>
</camera>
</gui>
<light type="directional" name="sun">
<cast_shadows>true</cast_shadows>
<pose>0 0 10 0 0 0</pose>
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/python3
"""Physical dual-MID360 perception, low-obstacle navigation and loss-stop acceptance."""
import argparse,hashlib,json,math,os,shlex,shutil,sys,time
from collections import deque
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.srv import SpawnEntity
from geometry_msgs.msg import PoseStamped
from livox_ros_driver2.msg import CustomMsg
from sensor_msgs.msg import PointCloud2
from scan_planner_msgs.msg import Bspline
from rosidl_runtime_py.convert import message_to_ordereddict
from std_msgs.msg import String
from std_srvs.srv import Trigger
from rclpy.qos import qos_profile_sensor_data
from check_omni_robot import Sim,sim_env,shutdown_probe
import check_omni_robot
from ament_index_python.packages import get_package_share_directory,get_package_prefix
from check_lio_navigation import LioNavProbe,graph_evidence
from check_scan_navigation import run_goal
from check_mid360 import rotate,interpolate,json_value
from check_sim_lidar import points
LOW=np.array([.325,0.,.044]);UP=np.array([.015,0.,.33])
R_LOW=np.array([[0.,-1.,0.],[1.,0.,0.],[0.,0.,1.]])
SCENARIOS={
'front':(-math.pi/2,(-4.5,3.)),
'side_right':(0.,(-4.,3.)),
'side_left':(math.pi,(-5.,3.)),
'diagonal_right':(-math.pi/4,(-4.5,3.)),
'diagonal_left':(-3*math.pi/4,(-4.5,3.)),
}
def rectangle_gap(position,yaw,center):
"""SAT separation of oriented 0.8 m robot and axis-aligned 0.25 m box.
Positive values bound Euclidean clearance from below; nonpositive means
touching/overlap. Unlike the historical enclosing AABB, this respects yaw.
"""
c,s=math.cos(yaw),math.sin(yaw)
axes=np.array([[1.,0.],[0.,1.],[c,s],[-s,c]])
body_axes=np.array([[c,s],[-s,c]])
radii=.4*np.abs(axes@body_axes.T).sum(axis=1)+.125*np.abs(axes).sum(axis=1)
return float(np.max(np.abs(axes@(np.asarray(position[:2])-center))-radii))
def swept_clearance(states,center):
"""Conservative bound between truth samples, with <=2 mm corner steps.
Each interpolated half-step is padded by its maximum corner displacement.
This assumes linear position/shortest yaw between samples; raw samples and
their maximum gap are retained so it is not called continuous ground truth.
"""
minimum=float('inf');max_gap=0.
for a,b in zip(states,states[1:]):
max_gap=max(max_gap,b['stamp']-a['stamp'])
delta=np.asarray(b['pos'][:2])-a['pos'][:2]
angle=math.atan2(math.sin(b['yaw']-a['yaw']),math.cos(b['yaw']-a['yaw']))
travel=float(np.linalg.norm(delta))+.4*math.sqrt(2)*abs(angle)
steps=max(1,math.ceil(travel/.002))
for t in np.linspace(0.,1.,steps+1):
gap=rectangle_gap(np.asarray(a['pos'][:2])+t*delta,a['yaw']+t*angle,center)
minimum=min(minimum,gap-travel/(2*steps))
return dict(min_gap_bound_m=minimum,max_sample_gap_s=max_gap,
method='oriented SAT; interpolated poses padded by half-step corner travel')
def historical_wheel_overlay(out):
"""A/B diagnostic only: old unmeasured wheel proxy, never edit source/install.
A private ament prefix lets the normal launch load a copy of the old xacro.
The real sensor ray-intersection code is unchanged in both arms.
"""
package='r2027_robot_description';share=Path(get_package_share_directory(package))
prefix=out/'historical_model_overlay';target=prefix/'share'/package
target.mkdir(parents=True,exist_ok=False)
for child in share.iterdir():
if child.name=='sdf':shutil.copytree(child,target/child.name)
else:(target/child.name).symlink_to(child.resolve(),target_is_directory=child.is_dir())
model=target/'sdf'/'r2027_omni_robot.sdf.xacro';text=model.read_text()
old="${0.20 if '$(arg dual_lidar)'.lower() == 'true' else 0.30}"
if text.count(old)!=1:raise ValueError('historical wheel replacement no longer matches current source')
model.write_text(text.replace(old,'0.30'))
marker=prefix/'share'/'ament_index'/'resource_index'/'packages'/package
marker.parent.mkdir(parents=True);marker.touch()
(prefix/'lib').symlink_to(Path(get_package_prefix(package))/'lib',target_is_directory=True)
(prefix/'setup.bash').write_text('source '+shlex.quote(str(Path(check_omni_robot.INSTALL)/'setup.bash'))+'\n'+
'export AMENT_PREFIX_PATH='+shlex.quote(str(prefix))+':"$AMENT_PREFIX_PATH"\n')
check_omni_robot.INSTALL=str(prefix)
return dict(path=str(model),sha256=hashlib.sha256(model.read_bytes()).hexdigest(),wheel_x_m=.30)
def fields(m,names):
lookup={f.name:f for f in m.fields}
return [np.ndarray((m.height,m.width),dtype=('>' if m.is_bigendian else '<')+'f4',buffer=m.data,
offset=lookup[n].offset,strides=(m.row_step,m.point_step)).reshape(-1) for n in names]
def samples(m):
lookup={f.name:f for f in m.fields}
def read(name,dtype):return np.ndarray((m.height,m.width),dtype=dtype,buffer=m.data,offset=lookup[name].offset,strides=(m.row_step,m.point_step)).reshape(-1)
return read('time_sec','<i4').astype(np.int64)*1000000000+read('time_nanosec','<u4'),read('sensor_id','u1')
class DualProbe(LioNavProbe):
def __init__(self):
super().__init__();self.raw=[None,None];self.raw_recent=[deque(maxlen=25),deque(maxlen=25)];self.dual_status=[];self.fused=None;self.frames=[];self.collect=False
self.truth_poses=[]
self.diagnostic_center=None;self.fused_diagnostics=[]
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda m,i=i:self.on_raw(i,m),qos_profile_sensor_data)
self.create_subscription(PointCloud2,'/sim/navigation/fused_cloud',self.on_fused,qos_profile_sensor_data)
self.create_subscription(String,'/sim/dual_lidar/status',lambda m:self.dual_status.append(json.loads(m.data)),10)
def _on_odom(self,m):
super()._on_odom(m)
if m.header.frame_id!='odom' or m.child_frame_id!='base_link':raise ValueError('unexpected physical truth frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear
quaternion=[q.x,q.y,q.z,q.w]
self.truth_poses.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[p.x,p.y,p.z],quaternion=quaternion,yaw=self.odom[-1]['yaw'],
twist_world=rotate(np.array(quaternion),np.array([v.x,v.y,v.z])).tolist(),wz=m.twist.twist.angular.z))
def on_raw(self,i,m):
self.raw[i]=m;self.raw_recent[i].append(m)
def on_fused(self,m):
self.fused=m
if self.collect:self.frames.append(m)
if self.diagnostic_center is not None:
xyz=points(m) if m.width*m.height else np.empty((0,3))
selected=(np.max(np.abs(xyz[:,:2]-self.diagnostic_center),axis=1)<.16)&(xyz[:,2]>.015)&(xyz[:,2]<.1)
self.fused_diagnostics.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=self.now(),points=xyz[selected].tolist()))
def raw_fixture_hits(m,state,i,center):
xyz=np.array([[p.x,p.y,p.z] for p in m.points]);local=xyz if i==0 else xyz@R_LOW.T
world=rotate(np.array(state['quaternion']),local+(UP if i==0 else LOW))+state['pos']
hit=(abs(world[:,0]-center[0])<.126)&(abs(world[:,1]-center[1])<.126)&(world[:,2]>.005)&(world[:,2]<.082)
return int(hit.sum())
def blocked_goal(p,x,y):
first=p.get_state();old=p.status[-1].goal_id;si=len(p.status);ci=len(p.commands)
goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg()
goal.pose.position.x=x;goal.pose.position.y=y;goal.pose.position.z=.15;goal.pose.orientation.w=1.;p.goal_pub.publish(goal)
deadline=time.monotonic()+30
while time.monotonic()<deadline:
p.pump(.05)
if p.status[-1].goal_id>old and p.status[-1].state in (p.status[-1].FAILED,p.status[-1].SUCCEEDED):break
p.pump(1.1);last=p.get_state();status=p.status[-1]
checks=dict(rejected=status.goal_id>old and status.state==status.FAILED,
never_active=not any(s.state==s.ACTIVE for s in p.status[si:]),
stationary=math.dist(first['pos'],last['pos'])<.01,
zero_commands=all(math.hypot(c['vx'],c['vy'])<.01 and abs(c['wz'])<.02 for c in p.commands[ci:]))
return dict(checks=checks,ok=all(checks.values()),reason=status.reason,initial=first,final=last)
def loss_stop(p):
first=p.get_state();goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg()
goal.pose.position.x=-4.5;goal.pose.position.y=4.5;goal.pose.position.z=.15;goal.pose.orientation.w=1.;p.goal_pub.publish(goal)
deadline=time.monotonic()+45
while time.monotonic()<deadline:
p.pump(.03);s=p.get_state()
if s and math.hypot(*s['twist_world'][:2])>.10:break
else:raise RuntimeError('no moving vehicle for lower-lidar fault')
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing independent lower disable service')
start=p.now();upper_before=int(p.raw[0].timebase);lower_before=int(p.raw[1].timebase)
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower disable failed')
states=[];ready=[];t=p.now()
while p.now()-start<1.5:
p.pump(.02);states.append(p.get_state());ready.append(p.ready)
if any(s is None for s in states):raise RuntimeError('missing physical fault samples')
latency=next((s['stamp']-start for s in states if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02),None)
late=[s for s in states if s['stamp']-start>.6]
checks=dict(lower_stopped=int(p.raw[1].timebase)-lower_before<=100000000,
upper_kept_running=int(p.raw[0].timebase)-upper_before>1000000000,
readiness_revoked=not all(ready) and not p.ready,stop_latency=latency is not None and latency<=.50,
stayed_stopped=all(math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02 for s in late),
stationary=all(math.dist(s['pos'],late[0]['pos'])<.02 for s in late))
return dict(ok=all(checks.values()),checks=checks,latency_sim_s=latency,truth=states)
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--gui',action='store_true')
ap.add_argument('--scenario',choices=SCENARIOS,default='front')
ap.add_argument('--diagnostics',action='store_true',help='record local map, planned splines and estimated/physical poses')
ap.add_argument('--historical-wheel-proxy',action='store_true',help='A/B evidence only: copy the old +/-0.30 m proxy into a private ament prefix')
ap.add_argument('--goal-y',type=float,default=1.5,help='world goal Y; retain historical route by default')
ap.add_argument('--goal-x',type=float,default=-4.5,help='world goal X; retain historical route by default')
ap.add_argument('--fixture-x',type=float,help='explicit world fixture X for additional routes; original scenarios stay unchanged')
ap.add_argument('--navigation-only',action='store_true',help='explicit navigation scope; independent lower-loss test is not executed')
args=ap.parse_args();heading,fixture_center=SCENARIOS[args.scenario]
if not all(math.isfinite(v) for v in (args.goal_x,args.goal_y)):ap.error('--goal-x/y must be finite')
if args.fixture_x is not None:
if not math.isfinite(args.fixture_x):ap.error('--fixture-x must be finite')
fixture_center=(args.fixture_x,fixture_center[1])
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True);os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',checks={},scope='navigation_only' if args.navigation_only else 'navigation_and_loss_stop',scenario=args.scenario,fixture_center=list(fixture_center),requested_goal=[args.goal_x,args.goal_y,heading],collector_sha256=hashlib.sha256(source).hexdigest());sim=Sim(str(out/'sim'));p=None
try:
if args.historical_wheel_proxy:report['historical_model']=historical_wheel_overlay(out)
ok,why=sim.start(lio_navigation=True,dual_lidar=True,gui=args.gui,spawn=(-4.5,4.5,.15,heading));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=DualProbe()
if not p.wait_clock():raise RuntimeError('no clock')
deadline=time.monotonic()+80
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.fused is not None and all(m is not None for m in p.raw):break
else:raise RuntimeError('dual perception not ready')
report['graph']=graph_evidence(out,p,'/sim/navigation/fused_planning_cloud',extra_nodes=('/dual_lidar_fusion',))
checks=report['checks'];checks['no_truth_feedback']=report['graph']['ok']
mounts={t['child']:t for t in p.tf_static_raw if t['frame_id']=='base_link'}
lower_tf=mounts.get('lidar_low');checks['actual_lower_tf']=lower_tf is not None and np.allclose(lower_tf['translation'],LOW,atol=1e-9) and np.allclose(lower_tf['rotation'],[0,0,math.sqrt(.5),math.sqrt(.5)],atol=1e-9)
report['runtime_sensor_tf']=mounts
# Stationary controlled fixture: same physical entity observed by both.
center=np.array(fixture_center);req=SpawnEntity.Request();req.name='dual_low_obstacle';req.reference_frame='world'
if args.diagnostics:p.diagnostic_center=center
req.initial_pose.position.x=float(center[0]);req.initial_pose.position.y=float(center[1]);req.initial_pose.position.z=.04;req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="dual_low_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.08</size></box></geometry></collision><visual name="box"><geometry><box><size>0.25 0.25 0.08</size></box></geometry></visual></link></model></sdf>'
response=p._call(p.spawn,req,timeout=15)
if not response or not response.success:raise RuntimeError('fixture spawn failed')
(out/'obstacle.sdf').write_text(req.xml)
maps=[];splines=[]
def on_map(m):
p.clouds['occupancy']=m
if args.diagnostics:
xyz=points(m) if m.width*m.height else np.empty((0,3))
near=(np.max(np.abs(xyz[:,:2]-center),axis=1)<2.)&(xyz[:,2]<.75)
maps.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=p.now(),points=xyz[near].tolist()))
sub=p.create_subscription(PointCloud2,'/grid_map/occupancy',on_map,qos_profile_sensor_data)
if args.diagnostics:
p.create_subscription(Bspline,'/planning/bspline',lambda m:splines.append(dict(received=p.now(),message=message_to_ordereddict(m))),10)
p.pump(1.);state=p.get_state();start_fixture_ns=round(p.now()*1e9)
p.frames.clear();p.collect=True;p.pump(2.);p.collect=False
hit_samples=[[raw_fixture_hits(m,state,i,center) for m in messages if m.timebase>=start_fixture_ns] for i,messages in enumerate(p.raw_recent)]
hits=[sum(v) for v in hit_samples]
report['raw_fixture_returns_per_frame']=hit_samples
checks['low_obstacle_only_seen_by_lower']=hits[0]==0 and hits[1]>=5;report['raw_fixture_returns']=hits
xyz=np.concatenate([points(m) for m in p.frames]);ids=np.concatenate([samples(m)[1] for m in p.frames]);report['fixture_fused_frames']=len(p.frames)
selected=(abs(xyz[:,0]-center[0])<.15)&(abs(xyz[:,1]-center[1])<.15)&(xyz[:,2]>.015)&(xyz[:,2]<.1)
checks['low_obstacle_fused']=len(p.frames)>=10 and int(np.count_nonzero(selected&(ids==1)))>=10
report['fused_fixture_returns_by_sensor']=[int(np.count_nonzero(selected&(ids==i))) for i in (0,1)]
if 'occupancy' not in p.clouds:raise RuntimeError('no independent map publication')
occupied=points(p.clouds['occupancy']);mapped=(abs(occupied[:,0]-center[0])<.16)&(abs(occupied[:,1]-center[1])<.16)&(occupied[:,2]>.015)&(occupied[:,2]<.125)
checks['low_obstacle_occupied']=int(mapped.sum())>0;report['occupied_fixture_voxels']=int(mapped.sum())
np.savez_compressed(out/'fixture.npz',fused=xyz,ids=ids,occupied=occupied)
if not args.diagnostics:p.destroy_subscription(sub);p.clouds.pop('occupancy',None)
report['blocked_goal']=blocked_goal(p,*center);checks['occupied_goal_rejected']=report['blocked_goal']['ok']
print('fixture checks',checks,flush=True)
# Capture fused samples and physical poses live; analyze only after motion.
p.frames.clear();p.collect=True;states=[p.get_state()]
route=run_goal(p,'low_obstacle_detour',args.goal_x,args.goal_y,heading,timeout=80.,goal_z=.15,settle_timeout=.2,sample_hook=states.append,sample_interval=.03)
p.collect=False
checks['navigation_around_low_obstacle']=route['ok']
clearances=[]
for s in route['samples']:
extent=.4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
clearances.append(max(abs(s['pos'][0]-center[0])-.125-extent,abs(s['pos'][1]-center[1])-.125-extent))
# /odom is the existing contact plugin's 100 Hz WorldPose stream. It is
# validation-only. Cross-check it against timestamped entity queries;
# no truth subscription or fallback is added to the running algorithms.
truth=[s for s in p.truth_poses if states[0]['stamp']-.05<=s['stamp']<=route['stop_samples'][-1]['stamp']+.05]
if len(truth)<2:raise RuntimeError('missing high-rate physical truth')
query_states=[s for s in states+route['braking_samples']+route['stop_samples'] if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
if len(query_states)<20:raise RuntimeError('insufficient independent truth service cross-checks')
query_times=np.array([s['stamp'] for s in query_states]);query_pos,query_q=interpolate(truth,query_times)
query_errors=np.linalg.norm(query_pos-np.array([s['pos'] for s in query_states]),axis=1)
query_angles=2*np.arccos(np.clip(np.abs(np.sum(query_q*np.array([s['quaternion'] for s in query_states]),axis=1)),0.,1.))
report['truth_service_agreement']=dict(source='contact plugin /odom: WorldPose at source simulation time; evaluation only',
samples=len(query_states),max_position_error_m=float(max(query_errors)),max_angle_error_rad=float(max(query_angles)))
checks['truth_service_agreement']=max(query_errors)<.002 and max(query_angles)<.005
exact=swept_clearance(truth,center)
report['oriented_swept_clearance']=exact
checks['physical_footprint_clearance']=bool(clearances) and exact['min_gap_bound_m']>.015 and exact['max_sample_gap_s']<=.12
route['min_low_obstacle_clearance_m']=min(clearances,default=None);report['navigation']=route
# Independent pose queries are requested every .03 sim seconds.
# Check physical origin alignment without using truth in any pipeline.
errors=[];fusion_errors=[];front=[];saved_origins=[];saved_estimated=[];saved_truth=[];saved_times=[];saved_ids=[]
estimated=[]
for m in p.nav_odom:
pos=m.pose.pose.position;q=m.pose.pose.orientation
estimated.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[pos.x,pos.y,pos.z],quaternion=[q.x,q.y,q.z,q.w]))
for m in p.frames[::max(1,len(p.frames)//12)]:
ns,ids=samples(m);times=ns*1e-9;valid=(times>max(truth[0]['stamp'],estimated[0]['stamp']))&(times<min(truth[-1]['stamp'],estimated[-1]['stamp']))
take=np.flatnonzero(valid)[::max(1,int(valid.sum())//400)]
if not len(take):continue
pos,q=interpolate(truth,times[take]);origin=np.stack(fields(m,('origin_x','origin_y','origin_z')),axis=-1)[take]
mount=np.where(ids[take,None]==0,UP,LOW);expected=pos+rotate(q,mount)
errors.extend(np.linalg.norm(origin-expected,axis=1))
estimated_pos,estimated_q=interpolate(estimated,times[take])
expected_estimated=estimated_pos+rotate(estimated_q,mount)
fusion_errors.extend(np.linalg.norm(origin-expected_estimated,axis=1))
saved_origins.append(origin);saved_estimated.append(expected_estimated);saved_truth.append(expected);saved_times.append(ns[take]);saved_ids.append(ids[take])
world=points(m)[take];inverse=q.copy();inverse[:,:3]*=-1;directions=rotate(inverse,world-origin)
front.extend(directions[ids[take]==1,0])
if not errors:raise RuntimeError('no time-bracketed fusion origins')
np.savez_compressed(out/'motion_geometry.npz',origin=np.concatenate(saved_origins),expected_estimated=np.concatenate(saved_estimated),
expected_physical=np.concatenate(saved_truth),sample_ns=np.concatenate(saved_times),sensor_id=np.concatenate(saved_ids),
input_estimated_poses=np.array([[v['stamp'],*v['pos'],*v['quaternion']] for v in estimated]))
# Keep the existing independent Point-LIO position bound (.10 m);
# separately require sub-millimetre fusion algebra against its input.
checks['localization_origins_match_independent_truth']=float(np.max(errors))<.10
checks['fusion_origins_match_estimated_inputs']=float(np.max(fusion_errors))<.001
checks['front_sector_follows_vehicle']=len(front)>100 and float(np.quantile(front,.001))>-.05
report['motion_geometry']=dict(fusion_error_p95_m=float(np.quantile(fusion_errors,.95)),fusion_error_max_m=float(np.max(fusion_errors)),origin_error_p95_m=float(np.quantile(errors,.95)),origin_error_max_m=float(np.max(errors)),front_min_m=min(front,default=None),samples=len(errors))
print('navigation checks',checks,flush=True)
if args.navigation_only:report['lower_loss_stop']=dict(status='NOT_RUN',reason='explicit --navigation-only scope')
else:
report['lower_loss_stop']=loss_stop(p);checks['lower_loss_stop']=report['lower_loss_stop']['ok']
report['dual_status']=p.dual_status[-6:];report['status']='PASS' if all(checks.values()) else 'FAIL'
print(json.dumps(dict(status=report['status'],checks=checks),indent=2,default=json_value),flush=True)
except Exception as error:report['error']=repr(error);print(report['error'],flush=True)
finally:
if args.diagnostics and p is not None and 'maps' in locals():
(out/'diagnostics.json').write_text(json.dumps(dict(maps=maps,splines=splines,
fused_fixture=p.fused_diagnostics,
physical_poses=p.truth_poses,
navigation_health=p.navigation_status,fusion_health=p.dual_status,
estimated_poses=[message_to_ordereddict(m) for m in p.nav_odom]),default=json_value)+'\n')
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/python3
"""Reproduce the user's north-corridor goal with estimated navigation only.
No fixture is added, no drive command is injected. Physical truth and map/cloud
snapshots are collected strictly by this evaluator, not fed to navigation.
"""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import time
import numpy as np
import rclpy
from sensor_msgs.msg import PointCloud2
from rclpy.qos import qos_profile_sensor_data
from scan_planner_msgs.msg import Bspline
from rosidl_runtime_py.convert import message_to_ordereddict
from check_dual_lidar import DualProbe
from check_lio_navigation import graph_evidence
from check_omni_robot import Sim,sim_env,shutdown_probe
from check_scan_navigation import run_goal
from check_sim_lidar import points
from check_mid360 import json_value,interpolate
class CorridorProbe(DualProbe):
def __init__(self):
super().__init__();self.snapshots=[];self.latest={};self.last_snapshot={};self.splines=[]
for topic in ('/grid_map/occupancy','/sim/navigation/fused_planning_cloud'):
self.create_subscription(PointCloud2,topic,lambda m,t=topic:self.capture(t,m),qos_profile_sensor_data)
self.create_subscription(Bspline,'/planning/bspline',lambda m:self.splines.append(
dict(received=self.now(),message=message_to_ordereddict(m))),10)
def on_fused(self,m):
super().on_fused(m)
self.capture('/sim/navigation/fused_cloud',m)
def capture(self,topic,m):
self.latest[topic]=m
if self.now()-self.last_snapshot.get(topic,-1)<.5:return
self.last_snapshot[topic]=self.now()
xyz=points(m) if m.width*m.height else np.empty((0,3))
finite=np.isfinite(xyz).all(1);roi=finite&(xyz[:,0]>-3.5)&(xyz[:,0]<4.5)&(xyz[:,1]>3.8)&(xyz[:,1]<5.6)&(xyz[:,2]>-.15)&(xyz[:,2]<.8)
self.snapshots.append(dict(topic=topic,source_stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=self.now(),frame=m.header.frame_id,points=xyz[roi].tolist()))
def verify_physical_corridor(p,route):
"""Independent source-stamped truth, checked against the entity service.
Production geometry: stair/ramp north edge <=Y=4, outer wall inner face
Y=5.5. Conservatively extend the Y=4 barrier across X=-3..3, including the
parts where the actual platform ends earlier. No runtime obstacle is added.
"""
first=route['samples'][0]['stamp'];last=route['stop_samples'][-1]['stamp']
truth=[s for s in p.truth_poses if first-.05<=s['stamp']<=last+.05]
if len(truth)<20:raise RuntimeError('insufficient high-rate physical samples')
queries=[s for s in route['samples'] if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
if len(queries)<20:raise RuntimeError('insufficient independent entity queries')
pos,q=interpolate(truth,np.array([s['stamp'] for s in queries]))
errors=np.linalg.norm(pos-np.array([s['pos'] for s in queries]),axis=1)
angles=2*np.arccos(np.clip(abs(np.sum(q*np.array([s['quaternion'] for s in queries]),axis=1)),0.,1.))
clearance=[];max_gap=0.
for a,b in zip(truth,truth[1:]):
max_gap=max(max_gap,b['stamp']-a['stamp'])
angle=abs(math.atan2(math.sin(b['yaw']-a['yaw']),math.cos(b['yaw']-a['yaw'])))
travel=math.dist(a['pos'][:2],b['pos'][:2])+.4*math.sqrt(2)*angle
for s in (a,b):
extent=.4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
if s['pos'][0]+extent>=-3. and s['pos'][0]-extent<=3.:
clearance.append(min(s['pos'][1]-extent-4.,5.5-s['pos'][1]-extent)-travel/2)
route['corridor_physics']=dict(minimum_gap_bound_m=min(clearance,default=None),
max_truth_gap_s=max_gap,query_samples=len(queries),max_query_position_error_m=float(max(errors)),
max_query_angle_error_rad=float(max(angles)),band_y_m=[4.,5.5],scope='flat corridor envelope; linear interpolation bound between truth samples')
route['checks']['crossed_north_corridor']=route['samples'][-1]['pos'][0]>3.
route['checks']['physical_clearance']=bool(clearance) and min(clearance)>=.03
route['checks']['truth_service_agreement']=max(errors)<.002 and max(angles)<.005 and max_gap<=.12
route['ok']=all(route['checks'].values())
def main():
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--out',required=True)
ap.add_argument('--repeat',type=int,default=1);ap.add_argument('--single-lidar',action='store_true')
ap.add_argument('--spawn-x',type=float,default=-4.5);ap.add_argument('--spawn-y',type=float,default=4.5)
ap.add_argument('--goal-x',type=float,default=3.5);ap.add_argument('--goal-y',type=float,default=4.8)
args=ap.parse_args()
if args.repeat<1:ap.error('--repeat must be positive')
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
report=dict(status='INVALID',cases=[],goal=[args.goal_x,args.goal_y,.15,0.],dual_lidar=not args.single_lidar,
collector_sha256=hashlib.sha256(source).hexdigest());sim=Sim(str(out/'sim'));p=None
root=Path(__file__).resolve().parents[2]
report['source_sha256']={f:hashlib.sha256((root/f).read_bytes()).hexdigest() for f in (
'sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py',
'sim_ws/src/br_sim_bringup/config/dual_lidar.yaml',
'sim_ws/src/br_sim_bringup/config/scan_sim.yaml')}
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=not args.single_lidar,
spawn=(args.spawn_x,args.spawn_y,.15,0.));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=CorridorProbe()
if not p.wait_clock():raise RuntimeError('clock unavailable')
deadline=time.monotonic()+90
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.goal_pub.get_subscription_count()>=2:break
else:raise RuntimeError('navigation never became ready')
planning='/sim/navigation/planning_cloud' if args.single_lidar else '/sim/navigation/fused_planning_cloud'
report['graph']=graph_evidence(out,p,planning,extra_nodes=() if args.single_lidar else ('/dual_lidar_fusion',))
for i in range(args.repeat):
route=run_goal(p,'north_corridor_%d'%(i+1),args.goal_x,args.goal_y,0.,timeout=100.,
goal_z=.15,settle_timeout=.2,sample_interval=.05)
verify_physical_corridor(p,route)
report['cases'].append(route)
print('attempt',i+1,'ok',route['ok'],'checks',route['checks'],'arrival',route['position_error_m'],flush=True)
if route['ok']:break
report['status']='PASS' if report['graph']['ok'] and report['cases'][-1]['ok'] else 'FAIL'
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:
(out/'diagnostics.json').write_text(json.dumps(dict(snapshots=p.snapshots,splines=p.splines,
estimated_poses=[message_to_ordereddict(m) for m in p.nav_odom],physical_poses=p.truth_poses,
navigation_health=p.navigation_status,fusion_health=p.dual_status),default=json_value)+'\n')
for topic,m in p.latest.items():
np.savez_compressed(out/(topic.strip('/').replace('/','_')+'.npz'),xyz=points(m) if m.width*m.height else np.empty((0,3)),
stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9)
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':raise SystemExit(main())
+148 -25
View File
@@ -1,11 +1,15 @@
#!/usr/bin/python3
"""Independent physical acceptance of LIO reference-path navigation on known ramps."""
import argparse,hashlib,json,math,os,signal,sys,time
from collections import deque
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.msg import ContactsState
from gazebo_msgs.srv import SpawnEntity
from std_srvs.srv import Trigger
from std_msgs.msg import String
from livox_ros_driver2.msg import CustomMsg
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Path as NavPath
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
@@ -20,21 +24,61 @@ def height(x):return 0. if x>=2.7 else (.6 if x<=-.8 else (1.6119-.597*x)/3.5)
class TerrainProbe(LioNavProbe):
def __init__(self,out):
def __init__(self,out,dual=False):
super().__init__();self.out=out;self.contacts=[];self.snapshots=[];self.next_snapshot=0.
self.dual=dual;self.raw=[None,None];self.dual_status=[];self.metadata_checks=[];self.truth_poses=[]
self.paired_clouds=deque(maxlen=50);self.pending_cloud_pairs={}
if dual:
for topic in ('/sim/navigation/fused_cloud','/sim/navigation/fused_planning_cloud','/sim/navigation/terrain_planning_cloud'):
self.create_subscription(PointCloud2,topic,lambda m,topic=topic:self.on_dual_cloud(topic,m),qos_profile_sensor_data)
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda m,i=i:self.raw.__setitem__(i,m),qos_profile_sensor_data)
self.create_subscription(String,'/sim/dual_lidar/status',lambda m:self.dual_status.append(json.loads(m.data)),10)
self.path_pub=self.create_publisher(NavPath,'/initial_path',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(ContactsState,'/sim/drive_contacts',self.contacts.append,100)
def on_dual_cloud(self,topic,m):
self.clouds[topic]=m
if topic=='/sim/navigation/terrain_planning_cloud':return
ns=m.header.stamp.sec*1000000000+m.header.stamp.nanosec
pair=self.pending_cloud_pairs.setdefault(ns,{})
pair[topic]=m
if len(pair)==2:
self.paired_clouds.append((ns,pair['/sim/navigation/fused_cloud'],pair['/sim/navigation/fused_planning_cloud']))
del self.pending_cloud_pairs[ns]
for key in sorted(self.pending_cloud_pairs)[:-20]:del self.pending_cloud_pairs[key]
def _on_odom(self,m):
super()._on_odom(m)
if m.header.frame_id!='odom' or m.child_frame_id!='base_link':raise ValueError('unexpected physical truth frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear
quaternion=np.array([q.x,q.y,q.z,q.w]);yaw=self.odom[-1]['yaw']
roll=math.atan2(2*(q.w*q.x+q.y*q.z),1-2*(q.x*q.x+q.y*q.y))
pitch=math.asin(np.clip(2*(q.w*q.y-q.z*q.x),-1.,1.))
self.truth_poses.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[p.x,p.y,p.z],quaternion=quaternion.tolist(),yaw=yaw,rpy=[roll,pitch,yaw],
twist_world=rotate(quaternion,np.array([v.x,v.y,v.z])).tolist(),wz=m.twist.twist.angular.z))
def capture(self):
if self.now()<self.next_snapshot:return
full=self.clouds.get('/sim/navigation/cloud_registered');filtered=self.clouds.get('/sim/navigation/planning_cloud')
full=self.clouds.get('/sim/navigation/fused_cloud' if self.dual else '/sim/navigation/cloud_registered')
filtered=self.clouds.get('/sim/navigation/fused_planning_cloud' if self.dual else '/sim/navigation/planning_cloud')
if full is None or filtered is None or full.header.stamp!=filtered.header.stamp:return
self.next_snapshot=self.now()+1.
name='cloud_%03d.npz'%len(self.snapshots)
np.savez_compressed(self.out/name,world=points(full),filtered=points(filtered))
self.snapshots.append(dict(file=name,stamp=full.header.stamp.sec+full.header.stamp.nanosec*1e-9))
if self.dual:
final=self.clouds.get('/sim/navigation/terrain_planning_cloud')
if final is not None and final.header.stamp==filtered.header.stamp:
def read(m,offset,dtype):return np.ndarray((m.width,),dtype=dtype,buffer=m.data,offset=offset,strides=(m.point_step,))
real_ids=read(full,32,'u1');ids=read(final,32,'u1');prior=ids==255
same=bytes(final.data[:len(filtered.data)])==bytes(filtered.data)
metadata=all(bytes(full.data[i*33+12:(i+1)*33])==bytes(filtered.data[i*33+12:(i+1)*33]) for i in range(full.width))
zero_rays=all(np.array_equal(read(final,i*4,'<f4')[prior],read(final,(i+3)*4,'<f4')[prior]) for i in range(3))
zero_time=all((read(final,offset,dtype)[prior]==0).all() for offset,dtype in ((24,'<i4'),(28,'<u4')))
self.metadata_checks.append(dict(stamp=self.now(),both_sources=bool((real_ids==0).any() and (real_ids==1).any()),
real_bytes_preserved=same,filter_metadata_preserved=metadata,explicit_prior_ids=bool(prior.any()),zero_length_priors=zero_rays,prior_has_no_acquisition_time=zero_time))
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None,lower_loss=False):
old_id=p.status[-1].goal_id if p.status else 0;si=len(p.status);ci=len(p.commands);ki=len(p.contacts);ei=len(p.nav_odom)
first=p.get_state()
if first is None:raise RuntimeError('missing initial independent truth')
@@ -50,17 +94,32 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
if s is None:raise RuntimeError('missing physical state')
states.append(s);readiness.append(dict(t=p.now(),ready=p.ready));p.capture()
if fault_sim is not None and not fault and 1.2<s['pos'][0]<1.8 and math.hypot(*s['twist_world'][:2])>.08:
pid=None
if not lower_loss:
candidates=[pid for pid in fault_sim.known if fault_sim.owns(pid) and b'/step_blocker' in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('cannot identify one owned step_blocker')
pid=candidates[0];fault.update(start=p.now(),owned_pid=pid,samples=[],readiness=[])
pid=candidates[0]
fault.update(start=p.now(),owned_pid=pid,kind='lower_lidar_loss' if lower_loss else 'downstream_loss',samples=[],readiness=[])
if lower_loss:
fault['upper_before']=int(p.raw[0].timebase);fault['lower_before']=int(p.raw[1].timebase)
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing lower disable service')
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower disable failed')
try:
os.kill(pid,signal.SIGSTOP)
if pid is not None:os.kill(pid,signal.SIGSTOP)
while p.now()-fault['start']<.8:
p.pump(.04);held=p.get_state()
if held is None:raise RuntimeError('missing independent fault state')
states.append(held);fault['samples'].append(held);fault['readiness'].append(dict(t=p.now(),ready=p.ready));p.capture()
finally:
if fault_sim.owns(pid):os.kill(pid,signal.SIGCONT)
if lower_loss:
fault['upper_after']=int(p.raw[0].timebase);fault['lower_after']=int(p.raw[1].timebase)
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/profile/'+p.sensor_profile)
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing lower enable service')
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower enable failed')
elif fault_sim.owns(pid):os.kill(pid,signal.SIGCONT)
fault['resumed']=p.now()
status=p.status[-1] if p.status else None
if status and status.goal_id>old_id and status.state in (status.SUCCEEDED,status.FAILED):break
@@ -77,19 +136,33 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
if s is None:raise RuntimeError('missing stopped state')
rest.append(s);p.capture()
statuses=p.status[si:];commands=p.commands[ci:];contacts=p.contacts[ki:];states+=braking+rest
# Dense plugin WorldPose is evaluation-only. Independently cross-check it
# against timestamped service responses, then use it to bracket estimates.
service_states=states
dense=[s for s in p.truth_poses if first['stamp']-.05<=s['stamp']<=states[-1]['stamp']+.05]
if len(dense)<20:raise RuntimeError('missing dense independent physical poses')
queries=[s for s in states if dense[0]['stamp']<=s['stamp']<=dense[-1]['stamp']]
if len(queries)<20:raise RuntimeError('insufficient service cross-checks')
qp,qq=interpolate(dense,[s['stamp'] for s in queries])
position_error=np.linalg.norm(qp-np.array([s['pos'] for s in queries]),axis=1)
angle_error=2*np.arccos(np.clip(np.abs(np.sum(qq*np.array([s['quaternion'] for s in queries]),axis=1)),0.,1.))
states=[s for s in dense if first['stamp']<=s['stamp']<=service_states[-1]['stamp']]
truth_gap=max(np.diff([s['stamp'] for s in states]))
# Align estimated and physical reference points only by their timestamps.
ts=[s['stamp'] for s in states];est=[m for m in p.nav_odom[ei:] if ts[0]<=m.header.stamp.sec+m.header.stamp.nanosec*1e-9<=ts[-1]]
if len(est)<(20 if blocked else 100):raise RuntimeError('not enough estimator/truth pairs')
times=np.array([m.header.stamp.sec+m.header.stamp.nanosec*1e-9 for m in est]);pos,q=interpolate(states,times)
estimated=np.array([[m.pose.pose.position.x,m.pose.pose.position.y,m.pose.pose.position.z] for m in est]);errors=estimated-pos
matrices=np.stack([rotate(np.broadcast_to(np.array(s['quaternion']),(3,4)),np.eye(3)).T for s in states])
extent=np.abs(matrices[:,1,:])@np.array([.4,.4,.15])
physical_y=np.array([s['pos'][1] for s in states])
# Conservative whole-vehicle bounds: local z=[-.15,+.26], not symmetric.
extent=np.abs(matrices[:,1,:])@np.array([.4,.4,.205])
physical_y=np.array([s['pos'][1] for s in states])+.055*matrices[:,1,2]
clearance=np.minimum(np.abs(physical_y)-3.025-extent,4.-np.abs(physical_y)-extent)
xy_error=math.hypot(rest[-1]['pos'][0]-xs[-1],rest[-1]['pos'][1]-target_y)
drift=max(math.dist(s['pos'],rest[0]['pos']) for s in rest)
mid=[s for s in states if -.35<s['pos'][0]<2.2]
checks=dict(acknowledged=status.goal_id>old_id,state_as_expected=status.state==(status.FAILED if blocked else status.SUCCEEDED),
truth_crosschecked=max(position_error)<.002 and max(angle_error)<.005 and truth_gap<=.12,
perception_fresh=p.ready,original_goal_preserved=abs(status.goal.x-xs[-1])<1e-6 and abs(status.goal.y-target_y)<1e-6 and abs(status.goal.z-(msg.poses[-1].pose.position.z+.15))<1e-6,
stopped=drift<.02 and all(math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02 for s in rest),
bounded_braking=latency is not None and 0<=latency<=.2,
@@ -103,13 +176,15 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
downstream_stop_in_time=stopped is not None and 0<=stopped<=.5,
downstream_held_still=bool(late) and all(math.hypot(*s['twist_world'][:2])<.01 and math.dist(s['pos'],late[0]['pos'])<.02 for s in late),
downstream_new_grant='resumed' in fault and any(s.header.stamp.sec+s.header.stamp.nanosec*1e-9>fault['resumed'] and s.state==s.ACTIVE for s in statuses))
if lower_loss:checks.update(upper_continues_during_lower_loss=fault['upper_after']-fault['upper_before']>=500000000,
lower_really_stopped=fault['lower_after']-fault['lower_before']<=100000000)
if blocked:
checks.update(never_active=not any(s.state==s.ACTIVE for s in statuses),stationary=max(math.dist(s['pos'],first['pos']) for s in states)<.02,
zero_commands=bool(commands) and all(max(abs(c[k]) for k in ('vx','vy','wz'))<1e-6 for c in commands))
else:
checks.update(active=any(s.state==s.ACTIVE for s in statuses),physical_arrival=xy_error<.10,
physical_height=abs(rest[-1]['pos'][2]-(height(xs[-1])+.15))<.03,
ramp_pitch=bool(mid) and max(abs(s['rpy'][1]-math.atan2(.597,3.5)) for s in mid)<.05,
ramp_pitch=bool(mid) and max(abs(s['rpy'][1]-math.cos(first['yaw'])*math.atan2(.597,3.5)) for s in mid)<.05,
ramp_height=bool(mid) and max(abs(s['pos'][2]-(height(s['pos'][0])+.15)) for s in mid)<.04,
lane=max(abs(s['pos'][1]-y) for s in states)<.03,
full_body_clearance=float(min(clearance))>.04,
@@ -122,8 +197,9 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
maximum_depth_m=max((d for m in contacts for c in m.states for d in c.depths),default=None),
collision_pairs=sorted({(c.collision1_name,c.collision2_name) for m in contacts for c in m.states})),
fault_event=fault,
truth_service_agreement=dict(samples=len(queries),max_position_error_m=float(max(position_error)),max_angle_error_rad=float(max(angle_error)),max_dense_gap_s=float(truth_gap)),
estimation_pairs=[dict(stamp=float(t),estimate=e.tolist(),truth_interpolated=g.tolist()) for t,e,g in zip(times,estimated,pos)],
input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses],samples=states,
input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses],samples=states,service_samples=service_states,
stopped_samples=rest,braking_samples=braking,readiness=readiness,commands=commands,
statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,state=s.state,reason=s.reason,traj_id=s.traj_id,goal_id=s.goal_id) for s in statuses])
@@ -132,59 +208,106 @@ def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--side',choices=('red','blue'),default='red')
group=ap.add_mutually_exclusive_group();group.add_argument('--up-only',action='store_true');group.add_argument('--obstacle-only',action='store_true')
ap.add_argument('--planning-loss',action='store_true')
ap.add_argument('--dual-lidar',action='store_true')
ap.add_argument('--lower-loss',action='store_true',help='disable only lower lidar during uphill; verify stop and same-task recovery')
ap.add_argument('--yaw',type=float,default=0.,help='initial heading; pi faces the front-only lower lidar uphill')
ap.add_argument('--obstacle-height',type=float,default=.6)
ap.add_argument('--obstacle-slope-aligned',action='store_true',help='explicit additional fixture: box bottom parallel to ramp, height measured normal to surface')
ap.add_argument('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
args=ap.parse_args()
if not math.isfinite(args.yaw) or abs(math.sin(args.yaw))>1e-5:ap.error('--yaw must be 0 or pi modulo 2pi for this slope acceptance')
if args.lower_loss and (not args.dual_lidar or args.planning_loss or args.obstacle_only):ap.error('--lower-loss needs --dual-lidar and uphill, without --planning-loss')
if not math.isfinite(args.obstacle_height) or not .08<=args.obstacle_height<=.6:ap.error('--obstacle-height must be .08.. .6 metres')
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True);os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
repo=Path(__file__).resolve().parents[2]
for name in ('sim_ws/src/br_sim_bringup/config/lio_terrain.yaml','sim_ws/src/br_sim_bringup/config/point_lio_terrain.yaml','sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py',
'sim_ws/src/br_sim_bringup/launch/scan_lio_terrain.launch.py'):
(out/Path(name).name).write_bytes((repo/name).read_bytes())
report=dict(status='INVALID',cases={},side=args.side,sensor_profile=args.sensor_profile,collector_sha256=hashlib.sha256(source).hexdigest())
if args.dual_lidar:
for name in ('sim_ws/src/br_sim_bringup/config/dual_lidar.yaml','sim_ws/src/br_sim_bringup/config/dual_lidar_terrain.yaml',
'sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py'):
(out/Path(name).name).write_bytes((repo/name).read_bytes())
report=dict(status='INVALID',cases={},side=args.side,dual_lidar=args.dual_lidar,yaw=args.yaw,obstacle_height=args.obstacle_height,obstacle_slope_aligned=args.obstacle_slope_aligned,sensor_profile=args.sensor_profile,collector_sha256=hashlib.sha256(source).hexdigest())
sim=Sim(str(out/'sim'));p=None;y=3.5125 if args.side=='red' else -3.5125
try:
ok,why=sim.start(navigation=True,terrain=True,lio_navigation=True,sensor_profile=args.sensor_profile,spawn=(3.5,y,.15,0.));report['startup']=why
ok,why=sim.start(navigation=True,terrain=True,lio_navigation=True,dual_lidar=args.dual_lidar,sensor_profile=args.sensor_profile,spawn=(3.5,y,.15,args.yaw));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out)
rclpy.init();p=TerrainProbe(out,args.dual_lidar);p.sensor_profile=args.sensor_profile
if not p.wait_clock():raise RuntimeError('no clock')
deadline=time.monotonic()+100
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.path_pub.get_subscription_count()>0 and len(p.nav_odom)>20:break
else:raise RuntimeError('terrain LIO pipeline not ready')
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/step_blocker',))
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/step_blocker','/dual_lidar_fusion') if args.dual_lidar else ('/step_blocker',))
if not report['graph']['ok']:raise RuntimeError('truth input or incorrect estimator wiring')
p.pump(1.)
cases=[('uphill',[3.5,2.7,-.8,-1.2],False)]
if args.obstacle_only:
req=SpawnEntity.Request();req.name='p6_terrain_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=y;req.initial_pose.position.z=height(1.)+.3
req.initial_pose.position.x=1.;req.initial_pose.position.y=y;req.initial_pose.position.z=height(1.)+args.obstacle_height/2
req.initial_pose.orientation.w=1.
if args.obstacle_slope_aligned:
angle=math.atan2(.597,3.5)
req.initial_pose.position.x+=math.sin(angle)*args.obstacle_height/2
req.initial_pose.position.z=height(1.)+math.cos(angle)*args.obstacle_height/2
req.initial_pose.orientation.y=math.sin(angle/2);req.initial_pose.orientation.w=math.cos(angle/2)
report['obstacle_fixture_pose']=dict(position=[req.initial_pose.position.x,req.initial_pose.position.y,req.initial_pose.position.z],
orientation_xyzw=[0.,req.initial_pose.orientation.y,0.,req.initial_pose.orientation.w],dimensions=[.25,.25,args.obstacle_height])
req.xml='<sdf version="1.6"><model name="p6_terrain_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></collision><visual name="box"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></visual></link></model></sdf>'
req.xml=req.xml.replace('0.25 0.25 0.6','0.25 0.25 '+str(args.obstacle_height))
response=p._call(p.spawn,req,timeout=15)
if not response or not response.success:raise RuntimeError('obstacle fixture not spawned')
(out/'obstacle.sdf').write_text(req.xml);p.pump(2.);p.capture()
(out/'obstacle.sdf').write_text(req.xml);fixture_start=p.now();p.pump(2.);p.capture()
ft='/sim/navigation/fused_cloud' if args.dual_lidar else '/sim/navigation/cloud_registered'
pt='/sim/navigation/fused_planning_cloud' if args.dual_lidar else '/sim/navigation/planning_cloud'
deadline=time.monotonic()+5
while p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp and time.monotonic()<deadline:p.pump(.02)
if p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp:raise RuntimeError('no matched obstacle cloud stamps')
full=points(p.clouds['/sim/navigation/cloud_registered']);filtered=points(p.clouds['/sim/navigation/planning_cloud'])
while p.clouds[ft].header.stamp!=p.clouds[pt].header.stamp and time.monotonic()<deadline:p.pump(.02)
if p.clouds[ft].header.stamp!=p.clouds[pt].header.stamp:raise RuntimeError('no matched obstacle cloud stamps')
full=points(p.clouds[ft]);filtered=points(p.clouds[pt])
np.savez_compressed(out/'obstacle_points.npz',world=full,filtered=filtered)
if len(full)!=len(filtered):raise RuntimeError('unpaired obstacle point clouds')
selected=(np.abs(full[:,0]-1.)<.18)&(np.abs(full[:,1]-y)<.18)&(full[:,2]>height(1.)+.12)&(full[:,2]<height(1.)+.68)
selected=(np.abs(full[:,0]-1.)<.18)&(np.abs(full[:,1]-y)<.18)&(full[:,2]>height(1.)+min(.12,args.obstacle_height-.015))&(full[:,2]<height(1.)+args.obstacle_height+.08)
count=int(np.count_nonzero(selected));retained=int(np.count_nonzero(np.isfinite(filtered[selected]).all(axis=1)))
report['obstacle_returns']=dict(count=count,retained=retained,ok=count>=15 and retained==count)
if not report['obstacle_returns']['ok']:raise RuntimeError('obstacle was not observed and preserved')
if args.dual_lidar:
# Evaluate every paired scan in a fixed two-second interval,
# not whichever sparse scanning pattern happens to be last.
records=[];worlds=[];filtered_frames=[];identities=[]
for ns,raw_cloud,planning_cloud in p.paired_clouds:
if not fixture_start<=ns*1e-9<=fixture_start+2.:continue
world=points(raw_cloud);plan=points(planning_cloud)
ids=np.ndarray((raw_cloud.width,),dtype='u1',buffer=raw_cloud.data,offset=32,strides=(raw_cloud.point_step,))
mask=(np.abs(world[:,0]-1.)<.18)&(np.abs(world[:,1]-y)<.18)&(world[:,2]>height(1.)+min(.12,args.obstacle_height-.015))&(world[:,2]<height(1.)+args.obstacle_height+.08)
records.append(dict(stamp_ns=ns,count=int(mask.sum()),retained=int(np.isfinite(plan[mask]).all(axis=1).sum()),by_sensor=[int(np.count_nonzero(mask&(ids==i))) for i in (0,1)]))
worlds.append(world);filtered_frames.append(plan);identities.append(ids)
count=sum(r['count'] for r in records);retained=sum(r['retained'] for r in records)
by_sensor=[sum(r['by_sensor'][i] for r in records) for i in (0,1)]
report['obstacle_returns']=dict(count=count,retained=retained,by_sensor=by_sensor,frames=records,
criteria='all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved',
ok=len(records)>=10 and count>=15 and by_sensor[1]>=5 and retained==count)
if worlds:np.savez_compressed(out/'obstacle_points.npz',world=np.concatenate(worlds),filtered=np.concatenate(filtered_frames),sensor_id=np.concatenate(identities))
if not report['obstacle_returns']['ok']:
print('valid obstacle sample fails observation/preservation criteria; still checking physical rejection',flush=True)
cases=[('ramp_obstacle_rejected',[3.5,2.7,1.],True)]
elif not args.up_only:cases.extend([('stairs_rejected',[-1.2,-2.5],True),('edge_rejected',[-1.2,1.],True),('downhill',[-1.2,-.8,2.7,3.5],False)])
for name,xs,blocked in cases:
result=run_path(p,xs,y,blocked,fault_sim=sim if args.planning_loss and name=='uphill' else None,
goal_y=(3.9 if y>0 else -3.9) if name=='edge_rejected' else None);report['cases'][name]=result
result=run_path(p,xs,y,blocked,fault_sim=sim if (args.planning_loss or args.lower_loss) and name=='uphill' else None,
goal_y=(3.9 if y>0 else -3.9) if name=='edge_rejected' else None,lower_loss=args.lower_loss);report['cases'][name]=result
(out/(name+'.json')).write_text(json.dumps(result,indent=2,default=json_value)+'\n');print(name,result['checks'],flush=True)
if not result['ok']:break
report['status']='PASS' if len(report['cases'])==len(cases) and all(c['ok'] for c in report['cases'].values()) else 'FAIL'
report['status']='PASS' if len(report['cases'])==len(cases) and all(c['ok'] for c in report['cases'].values()) and report.get('obstacle_returns',{'ok':True})['ok'] else 'FAIL'
if args.dual_lidar:
report['dual_metadata_checks']=p.metadata_checks;report['dual_status']=p.dual_status
report['metadata_ok']=len(p.metadata_checks)>=2 and all(all(v for k,v in c.items() if k!='stamp') for c in p.metadata_checks)
if not report['metadata_ok']:report['status']='FAIL'
report['cloud_snapshots']=p.snapshots;report['navigation_status']=p.navigation_status
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
except Exception as exc:report['status']='INVALID';report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:
report['navigation_status']=p.navigation_status
if args.dual_lidar:report.update(dual_metadata_checks=p.metadata_checks,dual_status=p.dual_status)
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
+3 -3
View File
@@ -26,8 +26,8 @@ def main():
center=np.array([state['pos'][0]+distance,state['pos'][1],height/2])
# The far TOP face can be visible even if the front face is below
# the lower FOV. Include box depth; a point-target approximation
# wrongly predicts that the 8 cm / 3 m fixture is invisible.
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]))
# can misclassify a fixture near the lower-FOV boundary.
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([.015,0.,.33]))
inverse=q.copy();inverse[:3]*=-1
corners=np.array([[center[0]+dx,center[1]+dy,height] for dx in (-.125,.125) for dy in (-.125,.125)])
local=rotate(inverse,corners-origin)
@@ -43,7 +43,7 @@ def main():
p.pump(.2);t=p.now();p.pump(1.5)
frames=[f for f in p.frames if t<f['t'] and f['t']+.1<p.now()]
if len(frames)<8:raise RuntimeError('insufficient actual scans')
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]));all_world=[]
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([.015,0.,.33]));all_world=[]
for f in frames:all_world.append(rotate(q,f['xyz'])+origin)
world=np.concatenate(all_world)
in_box=(abs(world[:,0]-center[0])<.126)&(abs(world[:,1]-center[1])<.126)&(world[:,2]>.005)&(world[:,2]<=height+.002)
+23 -5
View File
@@ -20,7 +20,7 @@ from check_omni_robot import Sim,sim_env, shutdown_probe
from check_slope_drive import SlopeProbe
ROOT=Path(__file__).resolve().parents[2]
MOUNT=np.array([0.,0.,.30])
MOUNT=np.array([.015,0.,.33])
def json_value(value):
@@ -48,11 +48,12 @@ def interpolate(states,times):
return pos[lo]+(pos[hi]-pos[lo])*w[:,None],qq
def scene_shapes():
def scene_shapes(model_path=None):
"""Read authoritative static primitives and triangles; independent of ODE ray code."""
base=ROOT/'sim_ws/src/robocon_gazebo/models/robocon_ground_full'
result=[]
for c in ET.parse(base/'model.sdf').findall('.//collision'):
if model_path is not None:base=Path(model_path).parent
for c in ET.parse(base/'model.sdf' if model_path is None else model_path).findall('.//collision'):
p=np.fromstring(c.findtext('pose','0 0 0 0 0 0'),sep=' ')
r,pitch,y=p[3:];cx,sx=np.cos(r),np.sin(r);cy,sy=np.cos(pitch),np.sin(pitch);cz,sz=np.cos(y),np.sin(y)
R=np.array([[cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx],
@@ -108,6 +109,16 @@ def ray_ranges(origins,directions,shapes):
return best
def vehicle_ranges(directions):
"""Independent local ray/box intersection, including physical roof returns.
Measured roof=.41 m, retained base=.15 m, assumed body bottom=.07 m.
Raw self hits are valid sensor observations, not outliers to hide.
"""
body=[(np.array([0.,0.,.09]),np.eye(3),'box',np.array([.4,.4,.17]))]
return ray_ranges(np.broadcast_to(MOUNT,directions.shape),directions,body)
class SensorProbe(SlopeProbe):
def __init__(self):
super().__init__();self.frames=[];self.imus=[];self.sensor_status=[]
@@ -153,10 +164,10 @@ def geometry_check(p,record,shapes,out,name):
times=f['t']+f['offsets'][idx]*1e-9
pos,q=interpolate(states,times)
origins=pos+rotate(q,np.broadcast_to(MOUNT,pos.shape));directions=rotate(q,direction)
expected=ray_ranges(origins,directions,shapes)
expected=np.minimum(ray_ranges(origins,directions,shapes),vehicle_ranges(direction))
errors.extend(np.abs(expected-ranges).tolist())
end_pos,end_q=interpolate(states,np.full(len(xyz),f['t']+.099))
wrong=ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes)
wrong=np.minimum(ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes),vehicle_ranges(direction))
instant_errors.extend(np.abs(wrong-ranges).tolist())
saved[str(i)+'_xyz']=f['xyz'];saved[str(i)+'_offset_ns']=f['offsets']
saved[str(i)+'_query_t']=times;saved[str(i)+'_expected_range']=expected
@@ -207,6 +218,13 @@ def main():
if name!='stop':geometry[name]=geometry_check(p,records[name],shapes,out,name)
frames=[f for f in p.frames if records['stationary']['t0']<=f['t']<records['stop']['t1']-.1]
checks=result['checks']
# Verify the actual transient-local TF messages, not only launch text.
mounts={item['child']:item for item in p.tf_static_raw if item['frame_id']=='base_link'}
for child,expected_mount in (('lidar',MOUNT),('mid360_imu',MOUNT+[.011,.02329,-.04412])):
mount=mounts.get(child)
checks['tf_'+child]=bool(mount is not None and np.allclose(mount['translation'],expected_mount,atol=1e-9,rtol=0)
and np.allclose(mount['rotation'],[0,0,0,1],atol=1e-9,rtol=0))
result['runtime_sensor_tf']=mounts
checks['geometry']=all(g['ok'] for g in geometry.values())
checks['frame_and_count']=all(f['frame']=='lidar' and f['point_num']==len(f['xyz']) and len(f['xyz'])>500 for f in frames)
checks['finite_fov']=all(np.isfinite(f['xyz']).all() and np.min(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))>=math.radians(-7)-1e-6 and np.max(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))<=math.radians(52)+1e-6 for f in frames)
+18 -5
View File
@@ -239,7 +239,7 @@ class Sim(object):
if value.isdigit() and self.owns(int(value)):
self.known[int(value)] = _comm(int(value))
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False):
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False, dual_lidar=False, mission=False, ramp_speed=.3, nav_speed=.3, aligned_start=False, crest_speed=.2, yaw_speed=.8, with_rviz=False, mission_profile='standard'):
if port_open(port=11355):
return False, 'master 端口 11355 已被占用;本工具不去动占用者,直接退出'
if terrain and not navigation:
@@ -252,16 +252,28 @@ class Sim(object):
raise ValueError('MID360 is currently a separate sensor/localization entry')
if sensor_profile not in ('ideal','mild','stress') or (split and not lio_navigation):
raise ValueError('invalid noise profile or split without LIO navigation')
entry = ('br_sim_bringup scan_lio_split.launch.py' if split else
if dual_lidar and (not lio_navigation or split):
raise ValueError('dual lidar acceptance requires the combined LIO entry')
if mission and (not lio_navigation or not dual_lidar or terrain or split):raise ValueError('mission requires combined flat LIO with dual lidar')
entry = ('br_sim_bringup ramp_mission.launch.py' if mission else
'br_sim_bringup scan_lio_split.launch.py' if split else
'br_sim_bringup '+('scan_lio_terrain.launch.py' if terrain else 'scan_lio.launch.py') if lio_navigation else
'br_sim_bringup mid360_sim.launch.py' if localization else
'br_sim_bringup '+('scan_terrain.launch.py' if terrain else 'scan_sim.launch.py') if navigation else
'br_sim_bringup robot_sim.launch.py')
options = ('gui:=%s' % ('true' if gui else 'false'))
if dual_lidar:options += ' dual_lidar:=true'
if mission:
if mission_profile not in ('standard','fast'):raise ValueError('invalid mission profile')
if not .1<=nav_speed<=(2.5 if mission_profile=='fast' else .6) or not .1<=ramp_speed<=(1.1 if mission_profile=='fast' else .7):raise ValueError('mission speed outside selected profile')
options+=' autostart:=true profile:=%s ramp_speed:=%g nav_speed:=%g'%(mission_profile,ramp_speed,nav_speed)
if not .03<=crest_speed<=min(.2,ramp_speed) or not .1<=yaw_speed<=(2. if mission_profile=='fast' else 1.):raise ValueError('invalid mission crest/yaw speeds')
options+=' crest_speed:=%g yaw_speed:=%g'%(crest_speed,yaw_speed)
options+=' aligned_start:='+('true' if aligned_start else 'false')
if lio_navigation:
options += ' sensor_profile:='+sensor_profile
if not terrain and not split:
options += ' with_rviz:=false'
options += ' with_rviz:='+('true' if with_rviz else 'false')
if split:options += ' terrain:='+('true' if terrain else 'false')
elif localization:
options += ' with_lio:=true sensor_profile:='+sensor_profile
@@ -1244,13 +1256,14 @@ def sh_cmd(cmd, timeout=15):
'err': (p.stderr or '').strip()[-400:]}
def check_model_geometry(out, drive='planar'):
def check_model_geometry(out, drive='planar', dual_lidar=False):
"""从展开后的 SDF 模型计算外包络,与配置值对照(不依赖 Gazebo 运行时)。"""
src = os.path.join(WS, 'src', 'r2027_robot_description', 'sdf',
'r2027_omni_robot.sdf.xacro')
expanded = os.path.join(out, 'model_expanded.sdf')
xacro = shutil.which('xacro') or '/opt/ros/humble/bin/xacro'
p = subprocess.run([xacro, src, 'drive:='+drive, '-o', expanded],
mappings=['dual_lidar:=true','lidar:=true','sensor_model:=mid360'] if dual_lidar else []
p = subprocess.run([xacro, src, 'drive:='+drive]+mappings+['-o', expanded],
env=sim_env(), capture_output=True, text=True, timeout=60)
if p.returncode != 0:
return {'ok': False, 'error': p.stderr[-400:], 'path': expanded}
+1 -1
View File
@@ -16,7 +16,7 @@ from nav_msgs.msg import Odometry
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,json_value
IMU_OFFSET=np.array([.011,.02329,.25588])
IMU_OFFSET=np.array([.026,.02329,.28588])
def matrix(q):
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/python3
"""Independent mission evaluation: truth only for scoring, no drive injection."""
import argparse,hashlib,json,math,os,sys,time
from pathlib import Path
import numpy as np
import rclpy
from std_msgs.msg import String
from gazebo_msgs.srv import SpawnEntity
from std_srvs.srv import Trigger
from rcl_interfaces.srv import GetParameters
from geometry_msgs.msg import Twist
from rclpy.qos import QoSProfile,DurabilityPolicy,ReliabilityPolicy
from check_omni_robot import Sim,sim_env,shutdown_probe
from check_lio_terrain import TerrainProbe
from check_mid360 import interpolate,json_value
from check_lio_navigation import graph_evidence
def critical_cloud_reliability_ok(evidence):
"""Check discovery evidence; history depth is not exposed by this local RMW."""
for topic, producer, consumers in (
('/sim/navigation/fused_planning_cloud', 'dual_lidar_fusion', ('step_blocker', 'ramp_mission')),
('/sim/navigation/terrain_planning_cloud', 'step_blocker', ('lio_navigation_adapter', 'scan_planner_node'))):
for kind, names in (('publisher', (producer,)), ('subscription', consumers)):
for name in names:
matches = [row for row in evidence.get(topic, []) if row['kind'] == kind and row['node'] == name]
if len(matches) != 1 or matches[0]['reliability'] != str(ReliabilityPolicy.RELIABLE):
return False
return True
def bounds(s):
from check_mid360 import rotate
R=rotate(np.broadcast_to(np.array(s['quaternion']),(3,4)),np.eye(3)).T
c=np.asarray(s['pos'])+R@np.array([0.,0.,.055]);e=np.abs(R)@np.array([.4,.4,.205])
return c-e,c+e
def motion_metrics(truth,events,fast=False):
entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
nav_start=next((e['stamp'] for e in events if e.get('to')=='NAVIGATE'),None)
nav=[s for s in truth if nav_start is not None and s['stamp']>=nav_start and (entry is None or s['stamp']<entry)]
straight=[s for s in nav if -3.5<s['pos'][0]<2.5]
uphill=[s for s in truth if entry is not None and s['stamp']>=entry and .5<s['pos'][0]<1.8]
crest=[s for s in truth if entry is not None and s['stamp']>=entry and ((-1.15<s['pos'][0]<-1.02) if fast else (-.85<s['pos'][0]<-.35))]
speed=lambda s:float(np.linalg.norm(s['twist_world']))
longest=0.;since=None
for s in straight:
if speed(s)<.05:
if since is None:since=s['stamp']
longest=max(longest,s['stamp']-since)
else:since=None
return dict(straight_peak_mps=max(map(speed,straight),default=0.),
straight_longest_stop_s=longest,nav_yaw_peak_radps=max((abs(s['wz']) for s in nav),default=0.),
uphill_peak_mps=max(map(speed,uphill),default=0.),crest_peak_mps=max(map(speed,crest),default=0.),
crest_median_mps=float(np.median([speed(s) for s in crest])) if crest else None)
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--profile',choices=('standard','fast'),default='standard')
ap.add_argument('--ramp-speed',type=float);ap.add_argument('--nav-speed',type=float)
ap.add_argument('--crest-speed',type=float,default=.2);ap.add_argument('--yaw-speed',type=float)
ap.add_argument('--gui',action='store_true');ap.add_argument('--sensor-profile',choices=('ideal','mild'),default='ideal')
ap.add_argument('--with-rviz',action='store_true',help='include RViz to reproduce the interactive launch load (requires --gui)')
ap.add_argument('--fault',choices=('none','lower_loss','mission_loss','mux_loss','obstacle'),default='none')
ap.add_argument('--aligned-start',action='store_true',help='fault diagnostics only, start physically at the staging pose; never count as a full-route pass')
args=ap.parse_args();out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
if args.nav_speed is None:args.nav_speed=2.5 if args.profile=='fast' else .6
if args.ramp_speed is None:args.ramp_speed=1.1 if args.profile=='fast' else .7
if args.yaw_speed is None:args.yaw_speed=2.0 if args.profile=='fast' else .8
if args.aligned_start and args.fault=='none':ap.error('--aligned-start is only for explicitly scoped fault diagnostics')
if args.with_rviz and not args.gui:ap.error('--with-rviz requires --gui')
if (out/'result.json').exists():ap.error('use a fresh output directory')
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',profile=args.profile,gui=args.gui,with_rviz=args.with_rviz,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,fault=args.fault,aligned_start=args.aligned_start,collector_sha256=hashlib.sha256(source).hexdigest())
root=Path(__file__).resolve().parents[2]
report['source_sha256']={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [
root/name for name in ('sim_ws/src/br_sim_bringup/scripts/ramp_mission.py','sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py','sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py',
'sim_ws/src/r2027_robot_description/src/contact_drive.cpp','sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro',
'sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py','sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py',
'minco_ws/src/scan/plan_env/src/grid_map.cpp','minco_ws/src/scan/plan_env/include/plan_env/grid_map.h','minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp',
'minco_ws/src/scan/plan_manage/src/planner_manager.cpp','minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp','sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py',
'minco_ws/src/perception/Point-LIO/include/common_lib.h','minco_ws/src/perception/Point-LIO/include/sensor_timestamp.h',
'sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py',
'minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h','minco_ws/src/perception/Point-LIO/src/laserMapping.cpp','sim_ws/src/robocon_gazebo/worlds/robocon_robot.world')]}
for name in report['source_sha256']:(out/Path(name).name).write_bytes((root/name).read_bytes())
sim=Sim(str(out/'sim'));p=None;states=[];mission=[];mux=[];fault={};actuator=[]
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=True,mission=True,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,gui=args.gui,sensor_profile=args.sensor_profile,
with_rviz=args.with_rviz,mission_profile=args.profile,
crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,
aligned_start=args.aligned_start,spawn=(3.7,3.5125,.15,math.pi) if args.aligned_start else None);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out,True)
for pub in (p.pub,p.goal_pub,p.path_pub):p.destroy_publisher(pub)
p.send=lambda *args:None
p.create_subscription(String,'/mission/status',lambda m:mission.append(json.loads(m.data)),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
p.create_subscription(String,'/mission/mux_status',lambda m:mux.append(json.loads(m.data)),10)
p.create_subscription(Twist,'/sim/cmd_vel',lambda m:actuator.append(dict(stamp=p.now(),command=[m.linear.x,m.linear.y,m.angular.z])),100)
if not p.wait_clock():raise RuntimeError('missing clock')
deadline=time.monotonic()+700;start=p.now();last_query=-1.;graph=None
fixture=False
while time.monotonic()<deadline and p.now()-start<210:
p.pump(.03)
if p.now()-last_query>=.1:
s=p.get_state()
if s is None:raise RuntimeError('missing physical entity query')
states.append(s);last_query=p.now()
if not mission:continue
state=mission[-1]['state']
if args.fault=='obstacle' and not fixture and state in ('NAVIGATE','ENTRY'):
req=SpawnEntity.Request();req.name='mission_ramp_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="mission_ramp_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.30</size></box></geometry></collision></link></model></sdf>'
res=p._call(p.spawn,req,15)
if res is None or not res.success:raise RuntimeError('fixture spawn failed')
fixture=True;fault=dict(kind='obstacle',spawn_stamp=p.now())
inject=args.fault in ('lower_loss','mission_loss','mux_loss') and not fault and state=='CLIMB' and states[-1]['pos'][0]<1.8
if inject:
fault=dict(kind=args.fault,start=p.now(),initial=states[-1])
if args.fault=='lower_loss':
raw=p.raw[1];raw_end=(int(raw.timebase)+max(point.offset_time for point in raw.points))*1e-9
fault.update(lower_last_source_end=raw_end,lower_source_age_at_injection_s=p.now()-raw_end)
fault.update(upper_before=int(p.raw[0].timebase),lower_before=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower disable failed')
else:
import signal
sim.refresh_owned()
executable=b'/ramp_mission.py' if args.fault=='mission_loss' else b'/mission_command_mux.py'
candidates=[pid for pid in sim.known if sim.owns(pid) and executable in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('mission process ownership ambiguous')
fault['pid']=candidates[0];os.kill(fault['pid'],signal.SIGSTOP)
if state in ('FAILED','SUCCEEDED'):break
if args.fault in ('mission_loss','mux_loss') and fault and p.now()-fault['start']>1.4:break
else:raise RuntimeError('mission did not terminate in acceptance time')
if args.fault!='none' and not fault:raise RuntimeError('requested fault was not injected; the injection gate was not reached')
if args.fault=='lower_loss' and fault:
p.pump(1.1)
fault.update(upper_during_loss=int(p.raw[0].timebase),lower_during_loss=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/profile/'+args.sensor_profile)
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower restore failed')
fault['restore_stamp']=p.now()
p.pump(1.3);final=p.get_state()
if final is None:raise RuntimeError('missing final entity query')
states.append(final)
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/dual_lidar_fusion','/ramp_mission','/mission_command_mux'))
publishers=p.get_publishers_info_by_topic('/cmd_vel')
cli=p.create_client(GetParameters,'/sim/lio/point_lio_sim/get_parameters')
req=GetParameters.Request();req.names=['odometry.publish_scan_end']
scan_end_params=p._call(cli,req,5)
report['scan_end_odometry_enabled']=bool(scan_end_params and scan_end_params.values and scan_end_params.values[0].bool_value)
report['critical_cloud_qos']={}
for topic,producer,consumers in (
('/sim/navigation/fused_planning_cloud','dual_lidar_fusion',('step_blocker','ramp_mission')),
('/sim/navigation/terrain_planning_cloud','step_blocker',('lio_navigation_adapter','scan_planner_node'))):
rows=[]
for kind,infos,wanted in (('publisher',p.get_publishers_info_by_topic(topic),(producer,)),('subscription',p.get_subscriptions_info_by_topic(topic),consumers)):
for name in wanted:
matches=[i for i in infos if i.node_name==name]
rows.extend(dict(kind=kind,node=i.node_name,reliability=str(i.qos_profile.reliability),depth=i.qos_profile.depth) for i in matches)
report['critical_cloud_qos'][topic]=rows
report['qos_depth_evidence']='Configured depth 1 in archived source; discovery returned depth 0 locally and does not establish runtime history depth.'
report['cmd_vel_publishers']=[dict(node=i.node_name,namespace=i.node_namespace) for i in publishers]
truth=p.truth_poses
if len(truth)<100:raise RuntimeError('missing dense physical truth')
queries=[s for s in states if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
tpos,tq=interpolate(truth,[s['stamp'] for s in queries])
error=np.linalg.norm(tpos-np.array([s['pos'] for s in queries]),axis=1)
angles=2*np.arccos(np.clip(abs(np.sum(tq*np.array([s['quaternion'] for s in queries]),axis=1)),0,1))
# Query service and update-end truth are asynchronous within the world's
# configured 1 ms physics step. Keep raw differences and bound the
# additional positional uncertainty by the measured query speed.
phase_bound=np.array([np.linalg.norm(s['twist_world'])*.001 for s in queries]) if args.profile=='fast' else np.zeros(len(queries))
report['truth_service_phase_bound']=dict(physics_step_s=.001,scope='fast only; 2 mm spatial residual plus one physics-step travel',maximum_bound_m=float(max(phase_bound)),maximum_residual_m=float(max(error-phase_bound)))
report['truth_service_agreement']=dict(samples=len(queries),max_position_error_m=float(max(error)),max_angle_error_rad=float(max(angles)),max_dense_gap_s=float(max(np.diff([s['stamp'] for s in truth]))))
tail=[s for s in truth if s['stamp']>=final['stamp']-1.]
checks=dict(no_truth_feedback=report['graph']['ok'],scan_end_odometry_enabled=report['scan_end_odometry_enabled'],critical_cloud_qos_reliable=critical_cloud_reliability_ok(report['critical_cloud_qos']),one_drive_owner=len(publishers)==1 and publishers[0].node_name=='mission_command_mux',
truth_crosschecked=bool(np.all(error<.002+phase_bound)) and max(angles)<.005 and report['truth_service_agreement']['max_dense_gap_s']<=.12,
stopped=bool(tail) and all(np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02 for s in tail),
stopped_drift=bool(tail) and max(math.dist(s['pos'],tail[0]['pos']) for s in tail)<.02)
events=mission[-1]['events'];entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
ramp=[s for s in truth if entry is not None and s['stamp']>=entry and s['pos'][0]<3.1]
clearance=[min(bounds(s)[0][1]-3.025,4.-bounds(s)[1][1]) for s in ramp]
report['ramp_clearance_m']=min(clearance,default=None)
report['maximum_ramp_lateral_error_m']=max((abs(s['pos'][1]-3.5125) for s in ramp),default=None)
pairs=sorted({(c.collision1_name,c.collision2_name) for m in p.contacts for c in m.states})
report['contacts']=dict(pairs=pairs,maximum_depth_m=max((d for m in p.contacts for c in m.states for d in c.depths),default=None))
report['final']=final;report['events']=events;report['elapsed_sim_s']=mission[-1].get('elapsed_s')
starts=[e['stamp'] for e in events if e.get('to') in ('NAVIGATE','ENTRY')]
terminal=[e['stamp'] for e in events if e.get('to') in ('SUCCEEDED','FAILED')]
report['task_duration_sim_s']=terminal[-1]-starts[0] if terminal and starts else None
report['motion_metrics']=motion_metrics(truth,events,args.profile=='fast')
if args.fault=='none':
lo,hi=bounds(final)
north=[]
for a,b in zip(truth,truth[1:]):
if entry is None or b['stamp']>entry:continue
qa=np.array(a['quaternion']);qb=np.array(b['quaternion'])
angle=2*math.acos(np.clip(abs(float(qa@qb)),0,1));pad=(math.dist(a['pos'],b['pos'])+.62*angle)/2
for s in (a,b):
blo,bhi=bounds(s)
# The inner wall ends at x=2.7; the east staging area is open.
if bhi[0]+pad>=-3. and blo[0]-pad<=2.7:north.append(min(blo[1]-4.,5.5-bhi[1])-pad)
report['north_corridor_gap_bound_m']=min(north,default=None)
mm=report['motion_metrics']
if args.profile=='fast':checks['within_20_seconds']=mission[-1]['state']=='SUCCEEDED' and report['task_duration_sim_s'] is not None and report['task_duration_sim_s']<=20.
checks.update(mission_succeeded=mission[-1]['state']=='SUCCEEDED',
straight_without_intermediate_stop=mm['straight_longest_stop_s']<=.25,
requested_straight_speed_reached=mm['straight_peak_mps']>=.85*args.nav_speed,
requested_uphill_speed_reached=mm['uphill_peak_mps']>=.85*args.ramp_speed,
requested_turn_speed_reached=mm['nav_yaw_peak_radps']>=.85*args.yaw_speed,
crest_speed_respected=mm['crest_median_mps'] is not None and mm['crest_peak_mps']<=args.crest_speed+.03,
north_corridor_clearance=bool(north) and min(north)>.03,
no_wall_contacts=all(any(name.endswith(suffix) for suffix in ('::ground','::ramp_north','::Cube.005')) for pair in pairs for name in pair if not name.startswith('r2027_omni::')),
all_phases=all(any(e.get('to')==stage for e in events) for stage in ('NAVIGATE','ENTRY','CLIMB','CREST','PLATFORM','SETTLE','SUCCEEDED')),
started_at_default=math.dist(truth[0]['pos'],[-4.5,4.5,.15])<.03,
final_whole_body_on_platform=lo[0]>=-1.76 and hi[0]<=-.84 and lo[1]>=3.065 and hi[1]<=3.96,
platform_height=abs(final['pos'][2]-.75)<.03,
full_ramp_clearance=bool(clearance) and min(clearance)>.04,
ramp_lateral_error=bool(ramp) and report['maximum_ramp_lateral_error_m']<.03,
actual_ramp_contacts=any('ramp_north' in c.collision1_name or 'ramp_north' in c.collision2_name for m in p.contacts for c in m.states),
contact_penetration=max((d for m in p.contacts for c in m.states for d in c.depths),default=1)<.005)
else:
if args.fault=='obstacle':
checks.update(obstacle_detected=mission[-1]['state']=='FAILED' and mission[-1]['reason']=='obstacle_in_braking_corridor',
obstacle_not_contacted=not any('mission_ramp_obstacle' in c.collision1_name or 'mission_ramp_obstacle' in c.collision2_name for m in p.contacts for c in m.states))
else:
stop=next((s['stamp']-fault['start'] for s in truth if s['stamp']>=fault['start'] and np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02),None)
fault['stop_latency_s']=stop;checks['fault_stop_latency']=stop is not None and 0<=stop<=.5
checks['fault_exercised']=bool(fault) and (args.fault in ('mission_loss','mux_loss') or mission[-1]['state']=='FAILED')
if args.fault=='mission_loss':checks['lease_expiry_exercised']=any(m['stamp']>fault['start']+.15 and m['reason']=='lease_stale' for m in mux)
if args.fault=='mux_loss':checks['actuator_watchdog_exercised']=any(m['stamp']>fault['start']+.15 and max(abs(v) for v in m['command'])<1e-8 for m in actuator)
if args.fault=='lower_loss':
fault.update(upper_after=int(p.raw[0].timebase),lower_after=int(p.raw[1].timebase))
checks['upper_continued']=fault['upper_during_loss']-fault['upper_before']>500000000
checks['lower_stopped']=fault['lower_during_loss']-fault['lower_before']<=100000000
checks['restored_data_without_motion']=p.ready and mission[-1]['state']=='FAILED' and fault['lower_after']>fault['lower_during_loss']
report['checks']=checks;report['status']='PASS' if all(checks.values()) else 'FAIL'
print(report['status'],checks,'task_duration',report['task_duration_sim_s'],'final',final['pos'],flush=True)
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
finally:
report.update(mission=mission,mux=mux,service_samples=states,fault_event=fault,actuator_commands=actuator)
if p is not None:
report['physical_poses']=p.truth_poses
report['navigation_status']=p.navigation_status
if args.fault in ('mission_loss','mux_loss') and 'pid' in fault and sim.owns(fault['pid']):
import signal
os.kill(fault['pid'],signal.SIGKILL);fault['cleanup']='owned stopped process killed after measurement; never resumed motion'
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())
+3 -2
View File
@@ -71,7 +71,8 @@ class NavProbe(Probe):
return req.xml
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None):
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None, sample_interval=.1):
if not 0<sample_interval<=.1:raise ValueError('sample_interval must be in (0,.1]')
first = p.get_state()
old_id = p.status[-1].goal_id if p.status else 0
start_cmd = len(p.commands)
@@ -85,7 +86,7 @@ def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settl
t0, wall_end = p.now(), time.monotonic()+300
samples = []
while p.now()-t0 < timeout and time.monotonic() < wall_end:
p.pump(.1)
p.pump(sample_interval)
truth = p.get_state()
if truth is None:
raise RuntimeError('missing independent Gazebo truth')
+3 -3
View File
@@ -6,7 +6,7 @@ import numpy as np
import yaml
import rclpy
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,json_value
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,vehicle_ranges,MOUNT,json_value
def main():
@@ -35,8 +35,8 @@ def main():
for j,f in enumerate(frames[::max(1,len(frames)//6)]):
take=np.arange(0,len(f['xyz']),max(1,len(f['xyz'])//500));xyz=f['xyz'][take];distance=np.linalg.norm(xyz,axis=1)
pos,q=interpolate(moving['states'],f['t']+f['offsets'][take]*1e-9)
origins=pos+rotate(q,np.tile([0.,0.,.3],(len(pos),1)))
directions=rotate(q,xyz/distance[:,None]);expected_range=ray_ranges(origins,directions,shapes)
origins=pos+rotate(q,np.tile(MOUNT,(len(pos),1)))
directions=rotate(q,xyz/distance[:,None]);expected_range=np.minimum(ray_ranges(origins,directions,shapes),vehicle_ranges(xyz/distance[:,None]))
valid=np.isfinite(expected_range)&(expected_range>.1)&(expected_range<40)
residuals.extend((distance-expected_range)[valid]);saved['xyz_%d'%j]=xyz;saved['expected_%d'%j]=expected_range
errors=np.array(residuals)
+2 -2
View File
@@ -69,7 +69,7 @@ def check_phase(probe, out, yaw):
pr, pw = pr[good], pw[good]
c, sn = math.cos(truth['yaw']), math.sin(truth['yaw'])
R = np.array([[c, -sn, 0], [sn, c, 0], [0, 0, 1]])
expected = (pr + [0, 0, .30]) @ R.T + truth['pos']
expected = (pr + [.015, 0, .33]) @ R.T + truth['pos']
error = float(np.max(np.linalg.norm(expected - pw, axis=1)))
floor = int(np.count_nonzero(np.abs(pw[:, 2]) < .005))
north = int(np.count_nonzero((np.abs(pw[:, 1]-5.5) < .005) & (pw[:, 2] >= -.005)
@@ -90,7 +90,7 @@ def check_phase(probe, out, yaw):
west_wall_correct=west > 2,
odom_frames=body.header.frame_id == 'world' and body.child_frame_id == 'base_link'
and sensor.header.frame_id == 'world' and sensor.child_frame_id == 'lidar',
sensor_mount=abs(shift-.30) < .001)
sensor_mount=abs(shift-.33) < .001)
np.savez_compressed(out / ('cloud_yaw_%d.npz' % round(yaw*180/math.pi)),
raw=pr, world=pw, expected=expected)
return dict(yaw=yaw, checks=checks, ok=all(checks.values()), settle=settle,
+1 -1
View File
@@ -46,7 +46,7 @@ class SlopeProbe(Probe):
if raw is None:
return
pr,pw = points(raw),points(m)
self_hit = (np.abs(pr[:,0])<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]>=-.47)&(pr[:,2]<=-.20)
self_hit = (np.abs(pr[:,0]+.015)<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]+.33>=-.17)&(pr[:,2]+.33<=.28)
roi = np.isfinite(pw).all(1)&(~self_hit)&(pw[:,0]>-.5)&(pw[:,0]<2.4)&(pw[:,1]>3.1)&(pw[:,1]<3.9)
pc=pw[roi]
if len(pc)>20:
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/python3
"""Check the measured vehicle envelope and sensor reference points before Gazebo.
Independent acceptance targets are the user's 2026-11-10 measurements. This
checks generated geometry/configuration; runtime rays/navigation remain separate.
"""
import argparse
import json
from pathlib import Path
import xml.etree.ElementTree as ET
import numpy as np
import xacro
import yaml
from check_omni_robot import check_model_geometry
ROOT = Path(__file__).resolve().parents[2]
ROBOT = ROOT / 'sim_ws/src/r2027_robot_description'
BASE_HEIGHT = .15
OPTICAL = np.array([.015, 0., .48 - BASE_HEIGHT])
IMU = OPTICAL + [.011, .02329, -.04412]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', required=True)
out = Path(parser.parse_args().out).resolve()
out.mkdir(parents=True, exist_ok=True)
checks = {}
report = {'status': 'INVALID', 'checks': checks,
'scope': 'generated SDF and configuration; not runtime acceptance'}
try:
geometry = check_model_geometry(str(out), 'contact')
report['geometry'] = geometry
checks['vehicle_envelope'] = geometry['ok'] and np.allclose(
geometry['size_xyz'], [.8, .8, .41], atol=1e-9, rtol=0)
checks['base_ground_reference'] = abs(geometry['ground_below_base_link'] - BASE_HEIGHT) < 1e-9
root = ET.fromstring(xacro.process_file(str(ROBOT / 'sdf/r2027_omni_robot.sdf.xacro'),
mappings={'lidar': 'true', 'sensor_model': 'mid360', 'drive': 'contact'}).toxml())
(out / 'mid360_expanded.sdf').write_bytes(ET.tostring(root))
optical = np.fromstring(root.findtext(".//plugin[@name='mid360_sensor']/lidar_position"), sep=' ')
imu = np.fromstring(root.findtext(".//sensor[@name='mid360_imu']/pose"), sep=' ')[:3]
checks['physical_optical_mount'] = np.allclose(optical, OPTICAL, atol=1e-9, rtol=0)
checks['physical_imu_mount'] = np.allclose(imu, IMU, atol=1e-9, rtol=0)
for name in ('lio_navigation', 'lio_terrain'):
cfg = yaml.safe_load((ROOT / f'sim_ws/src/br_sim_bringup/config/{name}.yaml').read_text())
parameters = cfg['lio_navigation_adapter']['ros__parameters']
checks[name + '_optical'] = np.allclose(parameters['lidar_position_base'], OPTICAL, atol=1e-9, rtol=0)
checks[name + '_imu'] = np.allclose(parameters['imu_position_base'], IMU, atol=1e-9, rtol=0)
inertia = root.find('.//inertial')
mass = float(inertia.findtext('mass'))
com = np.fromstring(inertia.findtext('pose'), sep=' ')[:3]
diagonal = np.array([float(inertia.findtext('inertia/' + key)) for key in ('ixx', 'iyy', 'izz')])
checks['inertia_physical'] = bool(mass > 0 and np.all(diagonal > 0) and np.all(2 * diagonal < diagonal.sum()))
checks['combined_com'] = np.allclose(com, [0., 0., (5.51*.09 + 4*1.2*(-.05))/10.31], atol=1e-9, rtol=0)
report.update(optical_base_m=optical.tolist(), imu_base_m=imu.tolist(),
nominal_optical_above_ground_m=float(optical[2] + BASE_HEIGHT),
assumed_mass_kg=mass, assumed_com_m=com.tolist(),
assumed_inertia_diagonal_kg_m2=diagonal.tolist())
report['status'] = 'PASS' if all(checks.values()) else 'FAIL'
except Exception as error:
report['error'] = repr(error)
(out / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
if __name__ == '__main__':
raise SystemExit(main())
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/python3
"""Independent regression for dual-lidar self-occlusion and clearance evidence.
Analytic intersections inspect the generated collision SDF, rather than treating
missing self returns (which are filtered downstream) as proof of clear sight.
Gazebo navigation remains a separate runtime check.
"""
import math
from pathlib import Path
import unittest
import xml.etree.ElementTree as ET
import numpy as np
import xacro
from check_dual_lidar import rectangle_gap,swept_clearance
MODEL=Path(__file__).resolve().parents[1]/'src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro'
def rotation(rpy):
r,p,y=rpy;cr,sr=math.cos(r),math.sin(r);cp,sp=math.cos(p),math.sin(p);cy,sy=math.cos(y),math.sin(y)
return np.array([[cy*cp,cy*sp*sr-sy*cr,cy*sp*cr+sy*sr],
[sy*cp,sy*sp*sr+cy*cr,sy*sp*cr-cy*sr],[-sp,cp*sr,cp*cr]])
def collision_parts(root):
# The supported proxy is one rigid body with primitive collisions.
links=root.findall('.//model/link')
if len(links)!=1 or not np.allclose(np.fromstring(links[0].findtext('pose','0 0 0 0 0 0'),sep=' '),0.):
raise ValueError('ray acceptance must be extended for changed link transforms')
parts=[]
for collision in links[0].findall('collision'):
pose=np.fromstring(collision.findtext('pose','0 0 0 0 0 0'),sep=' ')
geometry=collision.find('geometry');shape=next(iter(geometry))
if shape.tag not in ('box','cylinder'):raise ValueError('unsupported collision shape '+shape.tag)
parts.append((pose[:3],rotation(pose[3:]),shape))
return parts
def first_hit(parts,origin,direction):
candidates=[]
for center,R,shape in parts:
p=R.T@(origin-center);v=R.T@direction
if shape.tag=='box':
half=np.fromstring(shape.findtext('size'),sep=' ')/2;lo,hi=-float('inf'),float('inf')
for j in range(3):
if abs(v[j])<1e-12:
if abs(p[j])>half[j]:hi=-float('inf');break
else:
bounds=sorted(((-half[j]-p[j])/v[j],(half[j]-p[j])/v[j]))
lo=max(lo,bounds[0]);hi=min(hi,bounds[1])
if hi>=max(lo,0.):candidates.append(max(lo,0.))
else:
radius=float(shape.findtext('radius'));half=float(shape.findtext('length'))/2
a=float(v[:2]@v[:2]);b=2*float(p[:2]@v[:2]);c=float(p[:2]@p[:2])-radius**2
discriminant=b*b-4*a*c
if a>1e-14 and discriminant>=0:
for t in ((-b-math.sqrt(discriminant))/(2*a),(-b+math.sqrt(discriminant))/(2*a)):
if t>=0 and abs(p[2]+t*v[2])<=half+1e-12:candidates.append(t)
if abs(v[2])>1e-12:
for z in (-half,half):
t=(z-p[2])/v[2]
if t>=0 and np.linalg.norm(p[:2]+t*v[:2])<=radius+1e-12:candidates.append(t)
return min(candidates,default=float('inf'))
class ModelSightTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.text=xacro.process_file(str(MODEL),mappings={'dual_lidar':'true','lidar':'true','sensor_model':'mid360','drive':'contact'}).toxml()
cls.root=ET.fromstring(cls.text);cls.parts=collision_parts(cls.root)
cls.origin=np.fromstring(cls.root.findtext(".//plugin[@name='mid360_low_sensor']/lidar_position"),sep=' ')
def test_forward_horizontal_and_downward_rays_clear_proxy(self):
# Low-obstacle returns lie below the optical plane. Test the complete
# -7..0 degree band at 0.5 degree elevation / 0.25 degree azimuth steps.
blocked=[]
for elevation in np.deg2rad(np.linspace(-7.,0.,15)):
for azimuth in np.linspace(-math.pi/2,math.pi/2,721):
v=np.array([math.cos(elevation)*math.cos(azimuth),math.cos(elevation)*math.sin(azimuth),math.sin(elevation)])
if first_hit(self.parts,self.origin,v)<2.:blocked.append((azimuth,elevation))
self.assertEqual(blocked,[])
def test_rear_stays_physically_occluded(self):
self.assertAlmostEqual(first_hit(self.parts,self.origin,np.array([-1.,0.,0.])),.705,places=9)
def test_historical_wheels_reproduce_front_occlusion(self):
root=ET.fromstring(self.text)
for collision in root.findall('.//collision'):
if 'wheel' in collision.attrib['name']:
pose=np.fromstring(collision.findtext('pose'),sep=' ');pose[0]=math.copysign(.30,pose[0])
collision.find('pose').text=' '.join(map(str,pose))
parts=collision_parts(root);blocked=[]
for azimuth in np.linspace(-math.pi/2,math.pi/2,721):
v=np.array([math.cos(azimuth),math.sin(azimuth),0.])
if first_hit(parts,self.origin,v)<2.:blocked.append(azimuth)
self.assertGreater(len(blocked),0)
class ClearanceTests(unittest.TestCase):
def test_known_axis_aligned_gaps_and_overlap(self):
self.assertAlmostEqual(rectangle_gap([.7,0.],0.,[0.,0.]),.175)
self.assertAlmostEqual(rectangle_gap([.5,0.],0.,[0.,0.]),-.025)
self.assertAlmostEqual(rectangle_gap([.525,0.],0.,[0.,0.]),0.)
def test_rotated_rectangle_does_not_use_enclosing_aabb(self):
self.assertGreater(rectangle_gap([.65,.65],math.pi/4,[0.,0.]),.17)
self.assertLess(.65-.125-.4*math.sqrt(2),0.) # AABB would falsely overlap.
def test_between_sample_collision_cannot_hide_behind_clear_endpoints(self):
states=[dict(stamp=t,pos=[x,0.,.15],yaw=0.) for t,x in ((0.,-1.),(.1,1.))]
self.assertGreater(rectangle_gap(states[0]['pos'],0.,[0.,0.]),0.)
self.assertGreater(rectangle_gap(states[1]['pos'],0.,[0.,0.]),0.)
result=swept_clearance(states,[0.,0.]);self.assertLess(result['min_gap_bound_m'],0.)
def test_clearance_covers_rotation_corners(self):
states=[dict(stamp=t,pos=[0.,0.,.15],yaw=y) for t,y in ((0.,0.),(.1,math.pi/2))]
self.assertGreater(rectangle_gap([0.,0.],0.,[.65,0.]),0.)
self.assertLess(swept_clearance(states,[.65,0.])['min_gap_bound_m'],0.)
if __name__=='__main__':unittest.main()
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/python3
"""Reference-frame, deskew, schema and fail-closed tests for dual perception."""
from pathlib import Path
import math
import sys
import unittest
import numpy as np
import rclpy
from livox_ros_driver2.msg import CustomMsg,CustomPoint
from nav_msgs.msg import Odometry
from rclpy.qos import ReliabilityPolicy
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/br_sim_bringup/scripts'))
from dual_lidar_fusion import interpolate_poses,project_scan,cloud_message,DualLidarFusion
from lio_navigation_adapter import rotation
LOW=np.array([.325,0.,.044]);LEFT=rotation([0,0,math.sin(math.pi/4),math.cos(math.pi/4)])
def stationary():return [(float(t),np.zeros(3),np.array([0.,0.,0.,1.])) for t in np.arange(0.,.111,.01)]
class GeometryTests(unittest.TestCase):
def test_vehicle_front_half_is_lower_negative_y(self):
raw=np.array([[0,-1,0],[0,1,0],[1,0,0],[-1,0,0],[-1,.1,0]])
world,origins,t,_=project_scan(raw,np.arange(5)*1000000,0,stationary(),LOW,LEFT,True)
np.testing.assert_allclose(world,np.array([[1,0,0],[0,1,0],[0,-1,0]])+LOW,atol=1e-12)
np.testing.assert_allclose(origins,np.tile(LOW,(3,1)));np.testing.assert_array_equal(t,[0,2000000,3000000])
def test_front_sector_moves_with_vehicle_heading(self):
q=np.array([0,0,math.sin(math.pi/4),math.cos(math.pi/4)])
history=[(t,p,q) for t,p,_ in stationary()]
world,origins,_,_=project_scan([[0,-1,0]],[0],0,history,LOW,LEFT,True)
np.testing.assert_allclose(world,[[0,1.325,.044]],atol=1e-12)
np.testing.assert_allclose(origins,[[0,.325,.044]],atol=1e-12)
def test_motion_compensates_every_actual_sample_and_origin(self):
ts=np.arange(0.,.101,.01);history=[];raw=[];expected_origins=[];target=np.array([2.,.2,.08])
for t in ts:
q=np.array([0.,0.,math.sin(t*1.5),math.cos(t*1.5)]);R=rotation(q);p=np.array([t*.4,0.,0.])
history.append((float(t),p,q))
sample=np.array([0.,.025,.05,.075,.099])
for t in sample:
R=rotation([0,0,math.sin(t*1.5),math.cos(t*1.5)]);p=np.array([t*.4,0.,0.])
raw.append(LEFT.T@(R.T@(target-p)-LOW));expected_origins.append(p+R@LOW)
world,origins,t,_=project_scan(raw,np.rint(sample*1e9).astype(np.int64),0,history,LOW,LEFT,True)
np.testing.assert_allclose(world,np.tile(target,(len(sample),1)),atol=1e-10)
np.testing.assert_allclose(origins,expected_origins,atol=1e-10)
np.testing.assert_array_equal(t,np.rint(sample*1e9).astype(np.int64))
self.assertGreater(np.linalg.norm(origins[0]-origins[-1]),.05)
def test_pose_coverage_never_extrapolates(self):
for t in (-.01,.12):
with self.assertRaises(LookupError):interpolate_poses(stationary(),[t])
with self.assertRaises(ValueError):interpolate_poses([stationary()[0],stationary()[-1]],[.05])
def test_slerp_handles_equivalent_quaternion_signs(self):
history=stationary();history[1]=(history[1][0],history[1][1],-history[1][2])
_,q=interpolate_poses(history,[.005]);np.testing.assert_allclose(abs(q[0]),[0,0,0,1])
def test_invalid_offsets_rejected(self):
for offsets in ([-1],[100000000],[5000000,1000000]):
with self.assertRaises(ValueError):project_scan(np.tile([0,-1.,0],(len(offsets),1)),offsets,0,stationary(),LOW,LEFT,True)
def test_world_cloud_preserves_origin_time_identity(self):
times=np.array([1000000011,1099000011],dtype=np.int64)
m=cloud_message(np.array([[1,2,3],[4,5,6]]),np.tile(LOW,(2,1)),times,[0,1],1099000011)
self.assertEqual(m.header.frame_id,'world');self.assertEqual(m.header.stamp.nanosec,99000011)
fields={f.name:f for f in m.fields}
def read(name,dtype):return np.ndarray((m.width,),dtype=dtype,buffer=m.data,offset=fields[name].offset,strides=(m.point_step,))
np.testing.assert_array_equal(read('sensor_id','u1'),[0,1])
np.testing.assert_array_equal(read('time_sec','<i4'),[1,1]);np.testing.assert_array_equal(read('time_nanosec','<u4'),[11,99000011])
np.testing.assert_allclose(read('origin_z','<f4'),[.044,.044])
class Recorder:
def __init__(self):self.messages=[]
def publish(self,m):self.messages.append(m)
class NodeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):rclpy.init()
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def setUp(self):
self.node=DualLidarFusion();self.node.now_s=lambda:.11
self.node.full=Recorder();self.node.planning=Recorder();self.node.history.extend(stationary())
def tearDown(self):self.node.destroy_node()
def scan(self,i,t=0):
m=CustomMsg();m.header.frame_id='lidar' if i==0 else 'lidar_low';m.lidar_id=i
m.timebase=t;m.header.stamp.sec=t//1000000000;m.header.stamp.nanosec=t%1000000000
p=CustomPoint();p.x=2. if i==0 else 0.;p.y=0. if i==0 else -2.;p.offset_time=99000000
m.points=[p];m.point_num=1;return m
def test_pose_subscription_preserves_reliable_bursts(self):
subscription=next(s for s in self.node.subscriptions if s.topic_name=='/sim/navigation/body_odom')
self.assertEqual(subscription.qos_profile.depth,100)
self.assertEqual(subscription.qos_profile.reliability,ReliabilityPolicy.RELIABLE)
def test_clock_callback_order_does_not_drop_near_future_pose(self):
m=Odometry();m.header.frame_id='world';m.child_frame_id='lio_base_link'
m.header.stamp.nanosec=120000000;m.pose.pose.orientation.w=1.
self.node.on_pose(m)
self.assertAlmostEqual(self.node.history[-1][0],.12)
self.assertFalse(self.node.fault)
def test_pair_required_and_each_source_retained(self):
self.node.on_scan(0,self.scan(0));self.node.flush();self.assertFalse(self.node.full.messages)
self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertEqual(len(self.node.full.messages),1);self.assertEqual(self.node.full.messages[0].width,2)
# Repeated timer ticks cannot republish old data to fake freshness.
self.node.flush();self.assertEqual(len(self.node.full.messages),1)
def test_exact_scan_end_pose_does_not_wait_for_another_frame(self):
self.node.history.clear();self.node.now_s=lambda:41.4
for ns in (41260000000,41300000000,41361000000):
m=Odometry();m.header.frame_id='world';m.child_frame_id='lio_base_link'
m.header.stamp.sec=ns//1000000000;m.header.stamp.nanosec=ns%1000000000;m.pose.pose.orientation.w=1.
self.node.on_pose(m)
self.node.on_scan(0,self.scan(0,41262000000));self.node.on_scan(1,self.scan(1,41262000000))
self.node.flush();self.assertEqual(len(self.node.full.messages),1)
self.assertEqual(self.node.full.messages[0].header.stamp.nanosec,361000000)
def test_complete_pose_coverage_still_waits_for_source_clock(self):
self.node.now_s=lambda:.09
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.full.messages)
self.node.now_s=lambda:.11;self.node.flush()
self.assertEqual(len(self.node.full.messages),1)
self.assertEqual(self.node.full.messages[0].header.stamp.nanosec,99000000)
def test_incomplete_pose_history_drops_pair_then_recovers(self):
self.node.history.clear();self.node.history.extend([stationary()[0],stationary()[-1]])
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.fault);self.assertFalse(self.node.full.messages)
self.node.history.clear();self.node.history.extend((t+.1,p,q) for t,p,q in stationary())
self.node.now_s=lambda:.22
self.node.on_scan(0,self.scan(0,100000000));self.node.on_scan(1,self.scan(1,100000000));self.node.flush()
self.assertEqual(len(self.node.full.messages),1)
def test_wrong_frame_stops_publication(self):
m=self.scan(1);m.header.frame_id='lidar';self.node.on_scan(1,m)
self.assertTrue(self.node.fault);self.node.on_scan(0,self.scan(0));self.node.flush()
self.assertFalse(self.node.full.messages)
def test_timebase_mismatch_stops_publication(self):
m=self.scan(1);m.header.stamp.nanosec=1;self.node.on_scan(1,m);self.assertTrue(self.node.fault)
def test_stale_pair_never_published(self):
self.node.now_s=lambda:1.
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.full.messages)
def test_ground_uses_raw_geometry_even_with_world_height_and_tilt_error(self):
# A controlled +3 cm world offset and pitch error make a real ground
# point exceed the old 15 mm world-Z cut. The raw lower optics still
# measure the same ground and an 8 cm obstacle, separated by 80 mm.
q=np.array([0.,math.sin(-.01/2),0.,math.cos(-.01/2)])
self.node.history.clear();self.node.history.extend((t,np.array([0.,0.,.18]),q) for t,_,_ in stationary())
upper=self.scan(0);lower=self.scan(1);lower.points=[]
for height in (0.,.02,.08):
p=CustomPoint();p.x=0.;p.y=-1.;p.z=float(height-.194);p.offset_time=99000000
lower.points.append(p)
lower.point_num=len(lower.points)
self.node.on_scan(0,upper);self.node.on_scan(1,lower);self.node.flush()
full=self.node.full.messages[-1];planning=self.node.planning.messages[-1]
raw=np.stack([np.ndarray((full.width,),dtype='<f4',buffer=full.data,offset=i*4,strides=(full.point_step,)) for i in range(3)],axis=1)
filtered=np.stack([np.ndarray((planning.width,),dtype='<f4',buffer=planning.data,offset=i*4,strides=(planning.point_step,)) for i in range(3)],axis=1)
self.assertGreater(raw[1,2],.015)
self.assertTrue(np.isnan(filtered[1]).all())
self.assertTrue(np.isfinite(filtered[2:]).all()) # 2 cm and 8 cm tops kept.
for i in range(full.width):
start=i*full.point_step+12;end=(i+1)*full.point_step
self.assertEqual(bytes(full.data[start:end]),bytes(planning.data[start:end]))
self.assertEqual(full.header,planning.header)
def test_negative_world_drift_keeps_low_tops_from_both_lidars(self):
self.node.history.clear();self.node.history.extend((t,np.array([0.,0.,.11]),q) for t,_,q in stationary())
for i,optical_height in ((0,.48),(1,.194)):
m=self.scan(i);m.points=[]
for height in (0.,.02,.08):
p=CustomPoint();p.x=2. if i==0 else 0.;p.y=0. if i==0 else -2.
p.z=float(height-optical_height);p.offset_time=99000000;m.points.append(p)
m.point_num=len(m.points);self.node.on_scan(i,m)
self.node.flush();full=self.node.full.messages[-1];planning=self.node.planning.messages[-1]
def xyz(m):return np.stack([np.ndarray((m.width,),dtype='<f4',buffer=m.data,offset=i*4,strides=(m.point_step,)) for i in range(3)],axis=1)
raw=xyz(full);filtered=xyz(planning)
self.assertTrue(np.isnan(filtered[[0,3]]).all())
self.assertTrue(np.isfinite(filtered[[1,2,4,5]]).all())
self.assertTrue((raw[[1,4],2]<0.).all()) # 2 cm tops are below world zero.
if __name__=='__main__':unittest.main()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/python3
"""Known slope filtering, pitched extrinsics and explicit planning-only priors."""
from pathlib import Path
import sys,unittest
import numpy as np
import rclpy,yaml
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'sim_ws/src/br_sim_bringup/scripts'))
sys.path.insert(0,str(ROOT/'minco_ws/src/scan/step_blocker/step_blocker'))
from dual_lidar_fusion import DualLidarFusion,cloud_message,project_scan
from lio_navigation_adapter import rotation
from step_blocker_node import append_ray_priors,StepBlocker
from test_dual_lidar import Recorder,stationary
class PriorTests(unittest.TestCase):
def message(self):
return cloud_message(np.array([[1.,2.,3.],[np.nan,np.nan,np.nan]]),np.array([[0.,0.,.48],[.325,0.,.194]]),np.array([1000000001,1099000000]),[0,1],1099000000)
def test_real_bytes_and_header_unchanged(self):
m=self.message();out=append_ray_priors(m,[np.array([[2.,3.,.6]])])
self.assertEqual(bytes(out.data[:len(m.data)]),bytes(m.data));self.assertEqual(out.header,m.header)
self.assertEqual(out.width,3);self.assertEqual(out.row_step,99)
data=np.frombuffer(out.data[-33:],dtype=np.dtype({'names':['xyz','origin','sec','ns','id'],'formats':[('<f4',3),('<f4',3),'<i4','<u4','u1'],'offsets':[0,12,24,28,32],'itemsize':33}))
np.testing.assert_equal(data['xyz'],data['origin']);self.assertEqual(data['id'][0],255)
self.assertEqual(data['sec'][0],0);self.assertEqual(data['ns'][0],0)
def test_empty_walls_passthrough(self):
m=self.message();self.assertEqual(append_ray_priors(m,[]),m)
def test_corrupt_schema_rejected(self):
for kind in ('field','frame','truncated','endian','identity'):
m=self.message()
if kind=='field':m.fields.pop()
elif kind=='frame':m.header.frame_id='lidar'
elif kind=='truncated':m.data.pop()
elif kind=='endian':m.is_bigendian=True
else:m.data[32]=255
with self.subTest(kind=kind),self.assertRaises(ValueError):append_ray_priors(m,[])
def test_pitched_both_optical_origins_and_lower_sector(self):
angle=.169;R=rotation([0,np.sin(angle/2),0,np.cos(angle/2)]);q=np.array([0,np.sin(angle/2),0,np.cos(angle/2)])
h=[(0.,np.array([1.,2.,.4]),q),(.1,np.array([1.,2.,.4]),q)]
low_R=rotation([0,0,np.sqrt(.5),np.sqrt(.5)])
for mount,mount_R in ((np.array([.015,0,.33]),np.eye(3)),(np.array([.325,0,.044]),low_R)):
body=np.array([1.5,0.,-.1]);raw=mount_R.T@(body-mount)
xyz,origins,t,z=project_scan([raw],[50000000],0,h,mount,mount_R,True)
np.testing.assert_allclose(xyz,[np.array([1,2,.4])+R@body]);np.testing.assert_allclose(origins,[np.array([1,2,.4])+R@mount])
self.assertAlmostEqual(z[0],-.1)
class TerrainTests(unittest.TestCase):
@classmethod
def setUpClass(cls):rclpy.init()
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def test_known_slope_removes_ground_keeps_15cm_and_preserves_raw(self):
node=DualLidarFusion();node.now_s=lambda:.11;node.full=Recorder();node.planning=Recorder()
node.ground_mode='known_terrain';node.planes=[[-5,5,-5,5,-.17,0,.6]]
q=np.array([0,np.sin(.17/2),0,np.cos(.17/2)]);pos=np.array([0.,0.,.75]);R=rotation(q)
node.history.extend((t,pos,q) for t,_,_ in stationary())
from livox_ros_driver2.msg import CustomMsg,CustomPoint
for i,mount in enumerate(node.mounts):
m=CustomMsg();m.header.frame_id='lidar' if i==0 else 'lidar_low';m.lidar_id=i
for elevation in (0.,.15):
target=np.array([1.5,0.,.6-.17*1.5+elevation]);raw=node.rotations[i].T@(R.T@(target-pos)-mount)
p=CustomPoint();p.x,p.y,p.z=map(float,raw);p.offset_time=99000000;m.points.append(p)
m.point_num=2;node.on_scan(i,m)
node.flush()
full=node.full.messages[-1];filtered=node.planning.messages[-1]
def xyz(m):return np.stack([np.ndarray((m.width,),dtype='<f4',buffer=m.data,offset=4*i,strides=(m.point_step,)) for i in range(3)],axis=1)
self.assertTrue(np.isfinite(xyz(full)).all());self.assertTrue(np.isnan(xyz(filtered)[[0,2]]).all())
np.testing.assert_equal(xyz(filtered)[[1,3]],xyz(full)[[1,3]])
for i in range(4):self.assertEqual(bytes(full.data[i*33+12:(i+1)*33]),bytes(filtered.data[i*33+12:(i+1)*33]))
node.destroy_node()
def test_single_lidar_default_remains_xyz_mode(self):
node=StepBlocker();self.assertFalse(node.preserve_ray_metadata);node.destroy_node()
def test_survey_planes_match_existing_terrain_profile(self):
folder=ROOT/'sim_ws/src/br_sim_bringup/config'
a=yaml.safe_load((folder/'lio_terrain.yaml').read_text())['lio_navigation_adapter']['ros__parameters']
b=yaml.safe_load((folder/'dual_lidar_terrain.yaml').read_text())['dual_lidar_fusion']['ros__parameters']
self.assertEqual(a['traversable_planes'],b['traversable_planes']);self.assertEqual(a['surface_tolerance'],b['surface_tolerance'])
if __name__=='__main__':unittest.main()
+97 -7
View File
@@ -23,26 +23,27 @@ class Recorder:
class GeometryTests(unittest.TestCase):
def test_known_start_maps_imu_and_optical_origins(self):
imu=np.array([.011,.02329,.25588]);prior=np.array([-4.5,4.5,.15,math.pi/2])
imu=np.array([.026,.02329,.28588]);prior=np.array([-4.5,4.5,.15,math.pi/2])
p=np.array([.2,-.3,.02]);q=np.array([0.,0.,math.sin(.35),math.cos(.35)])
a=FixedAlignment(prior,imu,p,q)
base,bq=a.pose(p,q,-imu);lidar,_=a.pose(p,q,np.array([0.,0.,.3])-imu)
base,bq=a.pose(p,q,-imu);lidar,_=a.pose(p,q,np.array([.015,0.,.33])-imu)
np.testing.assert_allclose(base,prior[:3],atol=1e-12)
np.testing.assert_allclose(lidar,prior[:3]+[0,0,.3],atol=1e-12)
np.testing.assert_allclose(lidar,prior[:3]+[0,.015,.33],atol=1e-12)
self.assertAlmostEqual(math.atan2(rotation(bq)[1,0],rotation(bq)[0,0]),math.pi/2)
old_t=a.t.copy();later,_=a.pose(p+[1,0,0],q,-imu)
np.testing.assert_allclose(later-base,a.R@[1,0,0],atol=1e-12)
np.testing.assert_array_equal(a.t,old_t)
def test_rotating_imu_lever_arm_by_finite_difference(self):
offset=np.array([.011,.02329,.25588]);yaw=.8;w=.4;dt=1e-6
offset=np.array([.026,.02329,.28588]);yaw=.8;w=.4;dt=1e-6
def R(y):return np.array([[math.cos(y),-math.sin(y),0],[math.sin(y),math.cos(y),0],[0,0,1]])
imu_world_velocity=(R(yaw+w*dt)@offset-R(yaw-w*dt)@offset)/(2*dt)
imu_body_velocity=R(yaw).T@imu_world_velocity
base=shifted_twist(imu_body_velocity,[0,0,w],-offset)
np.testing.assert_allclose(base,[0,0,0],atol=1e-10)
lidar=shifted_twist(imu_body_velocity,[0,0,w],np.array([0,0,.3])-offset)
np.testing.assert_allclose(lidar,[0,0,0],atol=1e-10)
lidar=shifted_twist(imu_body_velocity,[0,0,w],np.array([.015,0,.33])-offset)
# A forward-offset optical origin has a genuine lateral velocity when yawing.
np.testing.assert_allclose(lidar,[0,.015*w,0],atol=1e-10)
def test_invalid_quaternions_are_rejected(self):
for values in ([0,0,0,0],[0,0,0,2],[float('nan'),0,0,1]):
@@ -66,6 +67,30 @@ class AdapterTests(unittest.TestCase):
for t in np.arange(1.,2.11,.05):self.node.on_odom(self.odom(float(t)))
self.assertIsNotNone(self.node.alignment)
def test_stationary_velocity_jitter_allows_fixed_start(self):
for i,t in enumerate(np.arange(1.,2.11,.01)):
m=self.odom(float(t));m.twist.twist.linear.x=.03 if i%2 else -.03
self.node.on_odom(m)
self.assertIsNotNone(self.node.alignment)
def test_moving_vehicle_cannot_lock_fixed_start(self):
for t in np.arange(1.,3.11,.01):
m=self.odom(float(t));m.pose.pose.position.x=.03*(t-1.)
m.twist.twist.linear.x=.03;self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
self.assertFalse(self.node.fault)
# Small position drift must not hide a sustained speed above threshold.
for t in np.arange(3.12,4.31,.01):
m=self.odom(float(t));m.twist.twist.linear.x=.03;self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
def test_position_motion_rejects_even_with_zero_mean_velocity(self):
for i,t in enumerate(np.arange(1.,3.11,.01)):
m=self.odom(float(t));m.pose.pose.position.x=.03*(t-1.)
m.twist.twist.linear.x=.03 if i%2 else -.03
self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
def test_stale_and_discontinuous_odometry_never_reanchors(self):
self.anchor();t=self.node.odom_stamp;translation=self.node.alignment.t.copy()
stale=self.odom(t);self.time=t+.3;count=len(self.node.body_pub.messages)
@@ -81,6 +106,8 @@ class AdapterTests(unittest.TestCase):
self.anchor();n=111;data=np.zeros((n,6),dtype='<f4');data[:,3]=1.
data[0,3:]=[0,0,-.3] # self return, regardless of latest robot pose
data[1,2]=-self.node.alignment.t[2] # world ground
data[2,3:]=[-.43,0,-.07] # new 41 cm roof, rear edge inside 2 cm margin
data[3,3:]=[.42,0,-.07] # outside front margin after optical x=.015 shift
m=PointCloud2();m.header.frame_id='camera_init';m.header.stamp=self.odom(self.time).header.stamp
m.height=1;m.width=n;m.point_step=24;m.row_step=24*n
m.fields=[PointField(name=name,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,name in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
@@ -89,7 +116,7 @@ class AdapterTests(unittest.TestCase):
full=self.node.world_pub.messages[-1];filtered=self.node.planning_pub.messages[-1]
self.assertEqual(filtered.header.stamp,m.header.stamp)
xyz=np.stack(float_fields(filtered,('x','y','z')),axis=-1).reshape(n,3)
self.assertTrue(np.isnan(xyz[:2]).all());self.assertTrue(np.isfinite(xyz[2:]).all())
self.assertTrue(np.isnan(xyz[:3]).all());self.assertTrue(np.isfinite(xyz[3:]).all())
for a,b in zip(float_fields(full,('lidar_x','lidar_y','lidar_z')),float_fields(filtered,('lidar_x','lidar_y','lidar_z'))):np.testing.assert_array_equal(a,b)
def test_wrong_source_frame_latches_stop(self):
@@ -125,6 +152,69 @@ class AdapterTests(unittest.TestCase):
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
self.time+=.02;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
self.node.health();self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_selected_fused_cloud_not_display_cloud_controls_readiness(self):
self.anchor();self.node.planning_topic='/sim/navigation/terrain_planning_cloud'
self.node.cloud_stamp=self.time-1.;self.node.downstream_stamp=self.time
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
self.time+=.31;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
self.node.health();self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_future_downstream_cloud_waits_for_clock(self):
self.anchor();previous=self.time;self.node.downstream_stamp=previous
m=PointCloud2();m.header.frame_id='world';m.width=1;m.height=1
m.header.stamp.sec=int(previous+.08);m.header.stamp.nanosec=round(((previous+.08)%1)*1e9)
self.node.on_planning_cloud(m);self.assertEqual(self.node.downstream_stamp,previous)
self.time=previous+.08;self.node.health();self.assertAlmostEqual(self.node.downstream_stamp,self.time)
def test_odom_before_clock_waits_then_keeps_original_stamp(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.assertEqual(len(self.node.body_pub.messages),count)
self.node.health();self.assertEqual(len(self.node.body_pub.messages),count)
self.time=previous+.08;self.node.health()
self.assertEqual(len(self.node.body_pub.messages),count+1)
self.assertEqual(self.node.body_pub.messages[-1].header.stamp,m.header.stamp)
self.assertFalse(self.node.pending_odom)
def test_cloud_before_clock_is_deferred_without_timestamp_rewrite(self):
self.anchor();previous=self.time;odom=self.odom(previous+.08);self.time=previous
self.node.on_odom(odom)
data=np.ones((111,6),dtype='<f4');m=PointCloud2();m.header=copy.deepcopy(odom.header)
m.height=1;m.width=len(data);m.point_step=24;m.row_step=24*len(data)
m.fields=[PointField(name=n,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,n in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
m.data=array('B',data.tobytes());self.node.on_cloud(m)
self.assertFalse(self.node.world_pub.messages)
self.time=previous+.08;self.node.health()
self.assertEqual(self.node.world_pub.messages[-1].header.stamp,m.header.stamp)
self.assertFalse(self.node.pending_cloud)
def test_expired_pending_data_does_not_become_fresh_after_clock_jump(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.time=previous+.4;self.node.health()
self.assertEqual(len(self.node.body_pub.messages),count)
self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_pending_source_order_cannot_hide_backwards_time(self):
self.anchor();previous=self.time
a=self.odom(previous+.08);b=self.odom(previous+.04);self.time=previous
self.node.on_odom(a);self.node.on_odom(b)
self.time=previous+.08;self.node.health()
self.assertIn('backwards',self.node.fault)
def test_far_future_samples_do_not_publish_or_fill_pending_queue(self):
self.anchor();previous=self.time;m=self.odom(previous+1.);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.assertFalse(self.node.pending_odom);self.assertEqual(self.node.future_dropped,1)
self.assertEqual(len(self.node.body_pub.messages),count)
def test_stopped_clock_pending_queue_is_bounded_and_fails_closed(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages)
for _ in range(65):self.node.on_odom(copy.deepcopy(m))
self.assertEqual(len(self.node.pending_odom),64)
self.assertIn('queue overflow',self.node.fault)
self.assertEqual(len(self.node.body_pub.messages),count)
if __name__=='__main__':unittest.main()
+30
View File
@@ -0,0 +1,30 @@
// Standalone numerical regression: no robot, ROS graph or filter execution.
#include <sensor_timestamp.h>
#include <sensor_time_rate_limiter.h>
#include <cassert>
#include <iostream>
int main()
{
int previously_truncated = 0;
for (std::int64_t frame = 0; frame < 6000; ++frame) {
const std::int64_t expected = frame * 100000000 + 99000000;
const double stamp = frame * .1 + .099;
const auto old = static_cast<std::int64_t>(std::floor(stamp)) * 1000000000 +
static_cast<std::uint32_t>((stamp - std::floor(stamp)) * 1e9);
previously_truncated += old != expected;
assert(point_lio::rounded_sensor_time_ns(stamp) == expected);
}
assert(previously_truncated > 0);
assert(point_lio::rounded_sensor_time_ns(38.319) == INT64_C(38319000000));
assert(point_lio::rounded_sensor_time_ns(.9999999996) == INT64_C(1000000000));
assert(point_lio::rounded_sensor_time_ns(1.0000000004) == INT64_C(1000000000));
point_lio::SensorTimeRateLimiter limiter;
assert(limiter.should_publish(.090,100));
assert(!limiter.should_publish(.099,100));
assert(limiter.should_publish(.099,100,true));
assert(!limiter.should_publish(.099,100,true));
assert(limiter.should_publish(.109,100));
std::cout << "6000 scan endpoint roundtrips and 3 boundary cases passed; old truncation mismatches: "
<< previously_truncated << '\n';
}
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/python3
"""Safety leases, geometry, phase history and terminal-stop tests (no Gazebo)."""
from pathlib import Path
import sys,math,unittest
import numpy as np
import rclpy
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/br_sim_bringup/scripts'))
from mission_command_mux import select_command
from ramp_mission import RampMission,body_command,envelope,obstacle_count,ground_height,speed_target
from lio_navigation_adapter import multiply,rotation
from scan_planner_msgs.msg import TrajectoryStatus
from std_srvs.srv import Trigger
from livox_ros_driver2.msg import CustomMsg,CustomPoint
from sensor_msgs_py.point_cloud2 import create_cloud_xyz32
from std_msgs.msg import Header
def qpose(pitch=0.,yaw=math.pi):
return multiply(np.array([0.,0.,math.sin(yaw/2),math.cos(yaw/2)]),np.array([0.,math.sin(pitch/2),0.,math.cos(pitch/2)]))
class Recorder:
def __init__(self):self.messages=[]
def publish(self,m):self.messages.append(m)
class MuxTests(unittest.TestCase):
def test_no_lease_health_or_expired_lease_is_zero(self):
nav=(1.,(.3,0.,0.));lease=dict(stamp=1.,since=.9,mode='NAV')
for now,l,health in ((1.,None,True),(1.,lease,False),(1.16,lease,True),(.99,lease,True)):
self.assertEqual(select_command(now,l,nav,None,health)[0],(0.,0.,0.))
def test_only_selected_source_can_drive(self):
for mode,expected in (('NAV',(.2,.1,0.)),('RAMP',(.3,0.,.1)),('STOP',(0.,0.,0.))):
self.assertEqual(select_command(1.,dict(stamp=1.,since=.9,mode=mode),(1.,(.2,.1,0.)),(1.,(.3,0.,.1)),True)[0],expected)
def test_commands_before_grant_or_stale_cannot_reappear(self):
for t in (.8,.89,1.01):
self.assertEqual(select_command(1.,dict(stamp=1.,since=.9,mode='RAMP'),None,(t,(.3,0.,0.)),True)[0],(0.,0.,0.))
def test_nonfinite_or_missing_source_is_zero(self):
lease=dict(stamp=1.,since=.9,mode='NAV')
self.assertEqual(select_command(1.,lease,None,None,True)[0],(0.,0.,0.))
self.assertEqual(select_command(1.,lease,(1.,(float('nan'),0.,0.)),None,True)[0],(0.,0.,0.))
def test_linear_norm_not_just_individual_axes_is_limited(self):
cmd,_=select_command(1.,dict(stamp=1.,since=.9,mode='NAV'),(1.,(.5,.5,1.)),None,True)
self.assertAlmostEqual(math.hypot(*cmd[:2]),.5);self.assertEqual(cmd[2],.5)
def test_opt_in_limits_and_expiry_at_fast_speed(self):
lease=dict(stamp=1.,since=.9,mode='NAV');nav=(1.,(.7,.7,1.))
cmd,_=select_command(1.,lease,nav,None,True,.7,.8)
self.assertAlmostEqual(math.hypot(*cmd[:2]),.7);self.assertEqual(cmd[2],.8)
self.assertEqual(select_command(1.16,lease,nav,None,True,.7,.8)[0],(0.,0.,0.))
cmd,_=select_command(1.,lease,(1.,(2.,2.,1.)),None,True,2.,1.)
self.assertAlmostEqual(math.hypot(*cmd[:2]),2.)
self.assertEqual(select_command(1.16,lease,(1.,cmd),None,True,2.,1.)[0],(0.,0.,0.))
class GeometryTests(unittest.TestCase):
def test_fast_profile_brakes_before_low_speed_zone_and_still_limits_final_approach(self):
self.assertEqual(speed_target(1.,1.2,.2,True),1.2)
self.assertLess(speed_target(-.7,1.2,.2,True),1.2)
self.assertLessEqual(speed_target(-1.,1.2,.2,True),.2)
self.assertLess(speed_target(-1.292,1.2,.2,True),.05)
# Full-speed braking corridor must grow when speed rises, rather than
# using only a small fixed lookahead after the experimental speed lift.
obstacle=np.array([[.4,3.5125,float(ground_height(.4))+.2]])
self.assertEqual(obstacle_count(obstacle,[1.6,3.5125,.5],qpose(-.169),.3,1.2),0)
self.assertEqual(obstacle_count(obstacle,[1.6,3.5125,.5],qpose(-.169),1.2,1.2),1)
def test_crest_braking_begins_before_crest_zone(self):
self.assertEqual(speed_target(1.,.7,.2),.7)
self.assertLess(speed_target(.2,.7,.2),.7)
self.assertEqual(speed_target(-.25,.7,.2),.2)
self.assertEqual(speed_target(-.8,.7,.2),.2)
self.assertLess(speed_target(-1.2,.7,.2),.1)
def test_pitch_correct_body_forward_and_cross_track(self):
for pitch in (0.,-.169):
q=qpose(pitch);cmd=body_command(q,.3,.01);world=rotation(q)@np.array([cmd[0],cmd[1],0.])
self.assertLess(world[0],0.);self.assertGreater(world[1],0.);self.assertAlmostEqual(cmd[0],.3,places=10)
def test_whole_body_on_platform_requires_more_than_flat_pitch(self):
for x,clear in ((-1.,False),(-1.3,True),(-1.5,False)):
lo,hi=envelope([x,3.5125,.75],qpose())
self.assertEqual(lo[0]>=-1.76 and hi[0]<=-.84,clear)
def test_obstacle_guard_keeps_floor_and_outside_rail_separate(self):
cloud=np.array([[1.1,3.5125,float(ground_height(1.1))],[1.1,3.025,.9],[1.1,3.5125,float(ground_height(1.1))+.2]])
self.assertEqual(obstacle_count(cloud,[1.6,3.5125,.5],qpose(-.169),.3),1)
class StateTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Never let service tests address a live mission on simulation domain 77.
import os
os.environ['ROS_LOCALHOST_ONLY']='1'
rclpy.init(domain_id=189)
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def setUp(self):
self.n=RampMission();self.t=10.;self.n.now=lambda:self.t
for name in ('lease_pub','direct_pub','report_pub','goal_pub'):setattr(self.n,name,Recorder())
self.n.state='ENTRY';self.n.start_time=10.;self.n.cloud=np.empty((0,3));self.n.gyro=np.zeros(3)
def tearDown(self):self.n.destroy_node()
def tick(self,x=3.7,y=3.5125,pitch=0.,speed=0.,dt=.1):
self.t+=dt;self.n.pose=dict(stamp=self.t,p=np.array([x,y,.15+float(ground_height(x))]),q=qpose(pitch),velocity=np.array([speed,0.,0.]),speed=speed,wz=0.)
self.n.pose_window.append(self.n.pose)
while self.n.pose_window and self.n.pose_window[0]['stamp']<self.t-(.35 if self.n.fast else .5):self.n.pose_window.popleft()
self.n.ready=True;self.n.ready_stamp=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t;self.n.lower_stamp=self.t;self.n.tick()
def test_initial_flat_never_means_arrival(self):
for _ in range(8):self.tick()
self.assertEqual(self.n.state,'ENTRY');self.assertFalse(self.n.seen_slope)
def test_missing_incline_is_latched_failure(self):
self.tick(x=1.7);self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.tick();self.assertEqual(self.n.state,'FAILED')
def test_sustained_incline_then_flat_still_needs_full_vehicle_clear(self):
for _ in range(4):self.tick(x=2.1,pitch=-.169)
self.assertEqual(self.n.state,'CLIMB');self.assertTrue(self.n.seen_slope)
self.tick(x=-.3,pitch=-.169);self.assertEqual(self.n.state,'CREST')
for _ in range(4):self.tick(x=-1.)
self.assertEqual(self.n.state,'PLATFORM')
self.tick(x=-1.3);self.assertEqual(self.n.state,'SETTLE')
for _ in range(10):self.tick(x=-1.3,speed=.08)
self.assertEqual(self.n.state,'SETTLE')
for _ in range(100):self.tick(x=-1.3,dt=.02)
self.assertEqual(self.n.state,'SUCCEEDED');self.assertEqual(self.n.mode,'STOP')
def test_lateral_drift_stops_before_leaving_lane(self):
self.tick(x=1.5,y=3.56,pitch=-.169);self.assertEqual(self.n.reason,'estimated_lateral_clearance');self.assertEqual(self.n.mode,'STOP')
def test_new_obstacle_revokes_ramp_drive(self):
self.n.seen_slope=True;self.n.state='CLIMB'
self.n.cloud=np.array([[1.1,3.5125,float(ground_height(1.1))+.2]])
self.tick(x=1.6,pitch=-.169,speed=.3);self.assertEqual(self.n.reason,'obstacle_in_braking_corridor');self.assertEqual(self.n.mode,'STOP')
def test_stale_state_is_not_replaced_by_open_loop_motion(self):
self.tick();self.n.ready=False;self.t+=.02;self.n.tick()
self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.tick();self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
def test_raw_lower_loss_stops_before_fused_cloud_timeout(self):
self.tick();self.t+=.24
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t
self.n.tick()
self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.assertEqual(self.n.health_failure['failed_checks'],['lower_scan'])
self.assertAlmostEqual(self.n.health_failure['sources']['lower_scan']['age_s'],.24)
captured=self.n.health_failure
self.tick();self.assertIs(self.n.health_failure,captured)
def test_fast_late_scan_holds_then_resumes_but_expiry_still_latches(self):
self.n.fast=True;self.n.ramp_speed=1.1;self.n.ramp_acceleration=2.
self.tick();self.t+=.16
for name in ('ready_stamp','imu_stamp','cloud_stamp'):setattr(self.n,name,self.t)
self.n.pose['stamp']=self.t;self.n.tick()
self.assertEqual(self.n.state,'ENTRY');self.assertEqual(self.n.mode,'STOP')
self.assertTrue(self.n.lower_hold);self.assertIsNone(self.n.health_failure)
self.tick();self.assertFalse(self.n.lower_hold);self.assertEqual(self.n.mode,'RAMP')
self.t+=.24
for name in ('ready_stamp','imu_stamp','cloud_stamp'):setattr(self.n,name,self.t)
self.n.pose['stamp']=self.t;self.n.tick()
self.assertEqual(self.n.state,'FAILED')
self.tick();self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
def test_single_delayed_lower_frame_does_not_latch_failure(self):
self.tick();self.t+=.199
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t
self.n.tick();self.assertEqual(self.n.state,'ENTRY');self.assertIsNone(self.n.health_failure)
def test_future_cloud_waits_for_clock_without_replacing_fresh_input(self):
self.tick();previous=self.n.cloud_stamp
h=Header(frame_id='world');h.stamp.sec=10;h.stamp.nanosec=150000000
self.n.on_cloud(create_cloud_xyz32(h,[[10.,10.,0.]]))
self.n.tick();self.assertEqual(self.n.cloud_stamp,previous);self.assertEqual(self.n.state,'ENTRY')
self.t=10.16;self.n.tick();self.assertAlmostEqual(self.n.cloud_stamp,10.15);self.assertEqual(self.n.state,'ENTRY')
def test_queued_future_cloud_cannot_refresh_expired_data(self):
self.tick();self.t+=.31
h=Header(frame_id='world');h.stamp.sec=11
self.n.on_cloud(create_cloud_xyz32(h,[[10.,10.,0.]]))
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.lower_stamp=self.t
self.n.tick();self.assertEqual(self.n.health_failure['failed_checks'],['fused_cloud'])
def test_lower_watchdog_preserves_actual_source_time_and_clock_order(self):
self.n.state='IDLE';self.n.requested=False
m=CustomMsg();m.header.frame_id='lidar_low';m.header.stamp.sec=10;m.header.stamp.nanosec=100000000
m.timebase=10100000000;m.lidar_id=1;m.point_num=1
point=CustomPoint();point.offset_time=23000000;m.points=[point]
self.n.on_lower(m);self.t=10.12;self.n.tick();self.assertIsNone(self.n.lower_stamp)
self.t=10.13;self.n.tick();self.assertAlmostEqual(self.n.lower_stamp,10.123)
self.n.on_lower(m);self.n.tick();self.assertEqual(self.n.reason,'lower_time_backwards')
def test_wrong_lidar_cannot_refresh_lower_watchdog(self):
m=CustomMsg();m.header.frame_id='lidar';m.lidar_id=0
self.n.on_lower(m);self.assertEqual(self.n.reason,'invalid_lower_scan')
def test_terminal_navigation_result_survives_lease_age(self):
# Terminal status is an event, unlike ACTIVE's short-lived motion grant.
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.SUCCEEDED
status.header.stamp.sec=9;status.goal.x=3.7;status.goal.y=4.8
self.n.status=status
for _ in range(60):self.tick(x=3.7,y=4.8,dt=.02)
self.assertEqual(self.n.nav_index,1)
self.assertEqual(len(self.n.goal_pub.messages),1)
def test_stale_active_grant_cannot_move(self):
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.ACTIVE
status.header.stamp.sec=9;status.goal.x=3.7;status.goal.y=4.8;self.n.status=status
self.tick(x=3.7,y=4.8);self.assertEqual(self.n.mode,'STOP')
def test_fast_pass_through_requires_fresh_grant_and_revokes_it_for_new_goal(self):
self.n.fast=True;self.n.goals=[self.n.goals[0],self.n.goals[-1]]
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.ACTIVE
status.goal.x=3.7;status.goal.y=4.8;status.header.stamp.sec=9
self.n.status=status
self.tick(x=3.05,y=4.8)
self.assertEqual(self.n.nav_index,0) # Stale grant cannot advance.
status.header.stamp.sec=10;status.header.stamp.nanosec=200000000
self.tick(x=3.05,y=4.8)
self.assertEqual(self.n.nav_index,1)
self.assertEqual(self.n.wait_goal_id,1)
self.assertEqual(self.n.mode,'STOP')
self.assertEqual(len(self.n.goal_pub.messages),1)
self.assertAlmostEqual(self.n.goal_pub.messages[0].pose.position.y,3.5125)
def test_actual_start_and_cancel_services(self):
self.n.state='IDLE';self.n.requested=False
start=self.n.create_client(Trigger,'/ramp_mission/start')
cancel=self.n.create_client(Trigger,'/ramp_mission/cancel')
self.assertTrue(start.wait_for_service(timeout_sec=2.))
future=start.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,future,timeout_sec=2.)
self.assertTrue(future.result().success);self.assertTrue(self.n.requested)
duplicate=start.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,duplicate,timeout_sec=2.)
self.assertFalse(duplicate.result().success)
future=cancel.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,future,timeout_sec=2.)
self.assertTrue(future.result().success);self.assertEqual(self.n.state,'FAILED')
if __name__=='__main__':unittest.main()
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/python3
"""Lost read-only responses may retry; a spawn must never be blindly repeated."""
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
from types import SimpleNamespace
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/r2027_robot_description/scripts'))
from spawn_existing_world import call,query_existing_entity
class Future:
def __init__(self,complete):self.complete=complete;self.cancelled=False
def done(self):return self.complete
def exception(self):return None
def result(self):return SimpleNamespace(success=False)
def cancel(self):self.cancelled=True
class Client:
srv_name='/test_service'
def __init__(self,outcomes):self.outcomes=iter(outcomes);self.requests=[];self.removed=[];self.futures=[]
def call_async(self,request):
self.requests.append(request);future=Future(next(self.outcomes));self.futures.append(future);return future
def remove_pending_request(self,future):self.removed.append(future)
class SpawnQueryTests(unittest.TestCase):
def setUp(self):
self.now=0.;self.warnings=[]
self.node=SimpleNamespace(get_logger=lambda:SimpleNamespace(warning=self.warnings.append))
self.patches=[patch('spawn_existing_world.time.monotonic',lambda:self.now),
patch('spawn_existing_world.rclpy.spin_until_future_complete',self.spin)]
for p in self.patches:p.start()
def tearDown(self):
for p in reversed(self.patches):p.stop()
def spin(self,node,future,timeout_sec):
if not future.complete:self.now+=timeout_sec
def test_lost_first_query_response_retries_and_preserves_negative_result(self):
client=Client([False,True]);request=object()
self.assertFalse(query_existing_entity(self.node,client,request).success)
self.assertEqual(client.requests,[request,request]);self.assertEqual(self.now,3.)
self.assertTrue(client.futures[0].cancelled);self.assertEqual(len(client.removed),1)
def test_repeated_read_timeouts_keep_original_total_deadline(self):
client=Client([False]*5)
with self.assertRaises(TimeoutError):query_existing_entity(self.node,client,object())
self.assertEqual(self.now,15.);self.assertEqual(len(client.requests),5)
self.assertTrue(all(f.cancelled for f in client.futures))
def test_spawn_timeout_never_repeats_side_effect(self):
client=Client([False,True])
with self.assertRaises(TimeoutError):call(self.node,client,object(),120.)
self.assertEqual(len(client.requests),1);self.assertEqual(self.now,120.)
if __name__=='__main__':unittest.main()