完善双雷达仿真与自动上坡任务,更新使用文档
加入下置 MID360 前向补盲与双雷达融合,修复北侧走廊导航、坐标适配和数据时效处理。 实现接近坡脚、姿态辅助上坡与平台停车任务,增加独立快模式、命令仲裁及失效停车保护,保留测试与分阶段验收记录。 同步实车尺寸及雷达安装参数,调整 Gazebo 红方默认视角,完善根目录 README、仿真使用和实车迁移说明。
This commit is contained in:
@@ -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
|
||||
@@ -94,7 +94,8 @@ struct MappingParameters {
|
||||
|
||||
/* mapping sensor input */
|
||||
string sensor_type_;
|
||||
bool cloud_is_world_;
|
||||
bool cloud_is_world_;
|
||||
bool cloud_has_ray_origins_{false};
|
||||
bool need_extrinsic_;
|
||||
Eigen::Matrix4d lidar_extrinsic_;
|
||||
Eigen::Matrix4d depth_extrinsic_;
|
||||
@@ -132,7 +133,8 @@ struct MappingData {
|
||||
|
||||
// depth image projected point cloud
|
||||
|
||||
vector<Eigen::Vector3d> proj_points_;
|
||||
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();
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
@@ -700,28 +725,30 @@ void GridMap::raycastProcess()
|
||||
|
||||
for (int i = 0; i < md_.proj_points_cnt; ++i)
|
||||
{
|
||||
pt_w = md_.proj_points_[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);
|
||||
|
||||
@@ -1029,7 +1081,8 @@ void GridMap::cloudCallback(const sensor_msgs::msg::PointCloud2::ConstSharedPtr
|
||||
|
||||
updateSlidingMap(ray_pos);
|
||||
|
||||
md_.proj_points_cnt = 0;
|
||||
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))
|
||||
|
||||
Reference in New Issue
Block a user