From af171dc11df6ec1eb80b80cf3a853a11c0be3eaf Mon Sep 17 00:00:00 2001 From: walunt5 Date: Thu, 5 Nov 2026 11:59:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(plan=5Fmanage):=20=E7=9B=AE=E6=A0=87?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=20FSM=20=E4=B8=8E=E7=9F=A9=E5=BD=A2=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E6=8E=A5=E5=85=A5=E3=80=90=E5=AE=9E=E9=AA=8C=E6=80=A7?= =?UTF-8?q?=EF=BC=8C=E6=9C=AA=E9=AA=8C=E6=94=B6=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 状态机:新增 EMERGENCY_STOP / BLOCKED;用户目标与轨迹解耦(raw_goal_ + goal_id_),只有新的目标/途经点能改写终点;新增 beginGoal、validateGlobalTarget、 getLocalTarget、enterBlocked、publishTrajectoryStatus、trajectoryDoneCallback; 订阅 planning/perception_ready 与轨迹完成信号,发布 planning/trajectory_status。 新增门控 require_perception_ready / require_controller_feedback, blocked_timeout / blocked_retry_period / goal_tolerance 可配。 A*:终点不再被沿着 start_to_end 逐步外推直到自由,占用或出图直接拒绝 (caller owns the endpoint,越过终点可能穿墙并给出别的任务的路径)。 矩形模型:launch 增加 use_obstacle_cloud / use_rectangle_footprint / use_self_filter 三个开关,矩形模式强制要求点云与感知就绪,参数互相校验。 planner_vehicle.yaml 尺寸依据由「圆形车半径 0.53 m」更正为 80 cm 方形外包络, 并明确标注 R=0.62 是尚未按新尺寸重新验收的既有值。 状态:默认关闭(use_rectangle_footprint:=false)。现场 43 s 静止录包结论为 「当前版本不能据此进入窄道运动测试」,矩形实现与朝向保持仍需独立验收。 本条提交记录的是当前事实,不代表验收通过。 测试:新增 7 个(2 个 gtest + 5 个 launch_test),均在 CMakeLists 注册。 --- .../scan/path_searching/src/dyn_a_star.cpp | 21 +- minco_ws/src/scan/plan_manage/CMakeLists.txt | 10 + .../plan_manage/config/planner_vehicle.yaml | 16 +- .../plan_manage/goal_execution_utils.h | 24 + .../include/plan_manage/scan_replan_fsm.h | 31 +- .../plan_manage/launch/run_vehicle.launch.py | 22 +- .../launch/vehicle_bringup.launch.py | 97 +++- minco_ws/src/scan/plan_manage/package.xml | 4 + .../src/closed_loop_controller.cpp | 94 +++- .../scan/plan_manage/src/scan_replan_fsm.cpp | 455 ++++++++++++------ .../test/test_controller_execution.py | 138 ++++++ .../test/test_goal_execution_fsm.py | 153 ++++++ .../test/test_goal_execution_utils.cpp | 21 + .../test/test_rectangle_controller.py | 131 +++++ .../test/test_rectangle_footprint.cpp | 122 +++++ .../plan_manage/test/test_rectangle_fsm.py | 129 +++++ .../plan_manage/test/test_rectangle_launch.py | 75 +++ .../test_reference_path_publisher_launch.py | 2 +- .../launch/step_blocker.launch.py | 7 +- 19 files changed, 1364 insertions(+), 188 deletions(-) create mode 100644 minco_ws/src/scan/plan_manage/include/plan_manage/goal_execution_utils.h create mode 100644 minco_ws/src/scan/plan_manage/test/test_controller_execution.py create mode 100644 minco_ws/src/scan/plan_manage/test/test_goal_execution_fsm.py create mode 100644 minco_ws/src/scan/plan_manage/test/test_goal_execution_utils.cpp create mode 100644 minco_ws/src/scan/plan_manage/test/test_rectangle_controller.py create mode 100644 minco_ws/src/scan/plan_manage/test/test_rectangle_footprint.cpp create mode 100644 minco_ws/src/scan/plan_manage/test/test_rectangle_fsm.py create mode 100644 minco_ws/src/scan/plan_manage/test/test_rectangle_launch.py diff --git a/minco_ws/src/scan/path_searching/src/dyn_a_star.cpp b/minco_ws/src/scan/path_searching/src/dyn_a_star.cpp index 4aedbf9..0e711c4 100644 --- a/minco_ws/src/scan/path_searching/src/dyn_a_star.cpp +++ b/minco_ws/src/scan/path_searching/src/dyn_a_star.cpp @@ -121,23 +121,14 @@ bool AStar::ConvertToIndexAndAdjustStartEndPoints(Vector3d start_pt, Vector3d en } while (occ); } + // The caller owns the endpoint. Searching beyond it can cross a wall and + // return a path for a different task. Reject occupied/out-of-map endpoints. occ = checkOccupancy(Index2Coord(end_idx), path_yaw); - if (occ) + if (occ != 0) { - //ROS_WARN("End point is insdide an obstacle."); - do - { - end_pt += start_to_end * step_size_; - if (!Coord2Index(end_pt, end_idx)) - return false; - - occ = checkOccupancy(Index2Coord(end_idx), path_yaw); - if (occ == -1) - { - RCLCPP_WARN(rclcpp::get_logger("path_searching"), "[Astar] End point outside the map region."); - return false; - } - } while (occ); + RCLCPP_WARN(rclcpp::get_logger("path_searching"), + "[Astar] End point is not free (%d); rejecting without moving it.", occ); + return false; } return true; diff --git a/minco_ws/src/scan/plan_manage/CMakeLists.txt b/minco_ws/src/scan/plan_manage/CMakeLists.txt index 4434d28..dd9eacb 100644 --- a/minco_ws/src/scan/plan_manage/CMakeLists.txt +++ b/minco_ws/src/scan/plan_manage/CMakeLists.txt @@ -63,6 +63,11 @@ if(BUILD_TESTING) find_package(ament_cmake_gtest REQUIRED) find_package(ament_cmake_pytest REQUIRED) find_package(launch_testing_ament_cmake REQUIRED) + ament_add_gtest(test_rectangle_footprint test/test_rectangle_footprint.cpp) + ament_target_dependencies(test_rectangle_footprint plan_env rclcpp) + ament_add_gtest(test_goal_execution_utils test/test_goal_execution_utils.cpp) + target_include_directories(test_goal_execution_utils PRIVATE include) + target_link_libraries(test_goal_execution_utils Eigen3::Eigen) ament_add_gtest(test_reference_path_utils test/test_reference_path_utils.cpp) target_include_directories(test_reference_path_utils PRIVATE include) ament_target_dependencies(test_reference_path_utils nav_msgs traj_utils) @@ -78,6 +83,11 @@ if(BUILD_TESTING) add_launch_test(test/test_planner_startup.py TIMEOUT 30) add_launch_test(test/test_reference_path_publisher_launch.py TIMEOUT 30) 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_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) endif() ament_package() diff --git a/minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml b/minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml index d5625fe..6d5c6d4 100644 --- a/minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml +++ b/minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml @@ -33,18 +33,22 @@ scan_planner_node: grid_map.map_sliding_thresh: 0.2 # ---- 车体碰撞模型(轮式,按实车量)---------------------------------- - # 车体近似为**圆形**:半径 0.53 m(实测)。 - # 代码里 footprint 是胶囊:front = pos + offset·heading,rear = pos - offset·heading, - # 总长 = 2·offset + 2·radius。车体是圆,故 offset 必须为 0,退化为单圆柱; - # 若沿用 0.20,footprint 会变成 1.46 m × 1.06 m,远处的窄道会被误判过不去。 + # 2026-11-01 用户确认:整车最大外包络为 0.80 × 0.80 m,包含突出件。 + # 先前“圆形车、物理半径 0.53 m”的注释不能继续当作尺寸依据。 + # 若 body_pose 位于方形几何中心,四角外接圆半径为 sqrt(0.4²+0.4²)=0.566 m; + # 不能仅按半宽把圆形半径改成 0.40,否则会漏掉四角。 + # 当前仍保留 offset=0 的单圆近似和既有 R=0.62,尚未接入矩形碰撞模型。 + # offset 非零时只在 front/rear 两点查询圆形膨胀层,不能据此精确表达方形。 # 【两个图层,别混淆】 # grid_map/occupancy —— 障碍**原样**,用来判断"障碍在哪、多大" # grid_map/occupancy_inflate —— 障碍外扩 R 后的区域,表示"车**中心**不能进入的范围", # 所以它必然比障碍粗一圈(粗多少 = R),这不是 bug。 # # 唯一膨胀数 R(障碍外扩 R,扩完车被当点): - # R = 车体物理半径 0.53 + 安全裕度 0.09 = 0.62 - # 0.53 时零裕度,实测跟踪误差即擦碰;0.62 需 1.24 m 通道,此前实测最稳。 + # R = 0.62 为保留的既有参数,不是按新确认尺寸重新验收后的值。 + # 按居中的 80 cm 方形外包络,其相对外接圆的径向裕度约 5.4 cm。 + # 用户已复核通道净宽为 1.20 m,小于当前圆模型直径 1.24 m,故本模型会拒绝。 + # 矩形 footprint + 明确裕度 + 实际 yaw/转向检查需独立实现和验收。 grid_map.double_cylinder_radius: 0.62 grid_map.double_cylinder_offset: 0.0 # 横向额外裕度,叠加在 R 上(总和才是实际膨胀)。当前 0 ⇒ 总膨胀 = 0.62。 diff --git a/minco_ws/src/scan/plan_manage/include/plan_manage/goal_execution_utils.h b/minco_ws/src/scan/plan_manage/include/plan_manage/goal_execution_utils.h new file mode 100644 index 0000000..73d64e9 --- /dev/null +++ b/minco_ws/src/scan/plan_manage/include/plan_manage/goal_execution_utils.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include + +namespace scan_planner +{ +// Reference time is never evidence that the physical robot reached the task goal. +inline bool reachedTaskPosition(const Eigen::Vector3d &position, + const Eigen::Vector3d &goal, double tolerance) +{ + return position.allFinite() && goal.allFinite() && tolerance > 0.0 && + (position.head<2>() - goal.head<2>()).norm() <= tolerance; +} + +// A distant goal may remain an intention outside the sliding map. Every executed +// local endpoint must, however, have an explicitly free (zero) occupancy result. +// This preserves the grid map's existing policy for unknown cells inside it. +inline bool globalGoalMayRemainActive(int occupancy) +{ + return occupancy == 0 || occupancy == -1; +} +inline bool localEndpointIsFree(int occupancy) { return occupancy == 0; } +} // namespace scan_planner diff --git a/minco_ws/src/scan/plan_manage/include/plan_manage/scan_replan_fsm.h b/minco_ws/src/scan/plan_manage/include/plan_manage/scan_replan_fsm.h index 06f63a9..5c74c96 100644 --- a/minco_ws/src/scan/plan_manage/include/plan_manage/scan_replan_fsm.h +++ b/minco_ws/src/scan/plan_manage/include/plan_manage/scan_replan_fsm.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include #include #include @@ -36,7 +38,8 @@ namespace scan_planner GEN_NEW_TRAJ, REPLAN_TRAJ, EXEC_TRAJ, - EMERGENCY_STOP + EMERGENCY_STOP, + BLOCKED }; enum NAVI_MODE { @@ -80,9 +83,23 @@ namespace scan_planner Eigen::Quaterniond odom_orient_; Eigen::Vector3d init_pt_, start_pt_, start_vel_, start_acc_, start_yaw_; // start state + // Only a new user goal/waypoint may change raw_goal_ or end_pt_. + Eigen::Vector3d raw_goal_{Eigen::Vector3d::Zero()}; Eigen::Vector3d end_pt_, end_vel_; // goal state + uint64_t goal_id_{0}; + double goal_tolerance_{0.08}, blocked_timeout_{10.0}, blocked_retry_period_{0.5}; + bool require_perception_ready_{false}, perception_ready_{false}; + bool require_controller_feedback_{false}; + bool last_trajectory_final_{false}; + bool target_yaw_valid_{false}; + double target_yaw_{0.0}; + rclcpp::Time odom_update_{0, 0, RCL_ROS_TIME}; + int64_t completed_trajectory_id_{-1}; + rclcpp::Time blocked_since_, next_retry_, perception_update_; + std::string blocked_reason_; Eigen::Vector3d local_target_pt_, local_target_vel_; // local target state std::vector active_waypoints_; + std::vector reference_waypoints_; int current_wp_; bool flag_escape_emergency_; @@ -95,6 +112,9 @@ namespace scan_planner rclcpp::Subscription::SharedPtr path_sub_; rclcpp::Subscription::SharedPtr go2_execution_frozen_sub_; rclcpp::Publisher::SharedPtr bspline_pub_; + rclcpp::Publisher::SharedPtr trajectory_status_pub_; + rclcpp::Subscription::SharedPtr trajectory_done_sub_; + rclcpp::Subscription::SharedPtr perception_ready_sub_; rclcpp::Publisher::SharedPtr data_disp_pub_; rclcpp::Publisher::SharedPtr self_inflation_pub_; @@ -113,8 +133,13 @@ namespace scan_planner bool planGlobalTrajByWaypoints(const std::vector &waypoints); bool planNextWaypoint(); bool isWaypointSequenceMode() const; - bool adjustGlobalTargetIfOccupied(); - void getLocalTarget(); + bool validateGlobalTarget(); + bool getLocalTarget(); + void beginGoal(const Eigen::Vector3d &goal); + void enterBlocked(const std::string &reason); + bool perceptionIsReady() const; + void publishTrajectoryStatus(uint8_t state, const std::string &reason); + void trajectoryDoneCallback(const std_msgs::msg::Int64::ConstSharedPtr &msg); void finishProcess(); void publishSelfInflationMarker(); double getOdomYaw() const; diff --git a/minco_ws/src/scan/plan_manage/launch/run_vehicle.launch.py b/minco_ws/src/scan/plan_manage/launch/run_vehicle.launch.py index 2b01f11..ece042e 100644 --- a/minco_ws/src/scan/plan_manage/launch/run_vehicle.launch.py +++ b/minco_ws/src/scan/plan_manage/launch/run_vehicle.launch.py @@ -54,7 +54,13 @@ def generate_launch_description(): DeclareLaunchArgument('max_vyaw', default_value='0.50', description='转向角速度上限 [rad/s]。受代码硬上限 1.0 约束,且须 <= 底盘 max_wz_rad_s'), DeclareLaunchArgument('collision_radius', default_value='0.62', - description='碰撞半径 [m] = 物理 0.53 + 0.09 安全裕度'), + description='圆形模式碰撞半径 [m];矩形模式使用实测81x80cm外包络'), + DeclareLaunchArgument('use_rectangle_footprint', default_value='false', + description='实验:81x80cm矩形、9cm裕度、任务开始朝向保持;需感知就绪'), + DeclareLaunchArgument('footprint_length', default_value='0.81', + description='矩形物理长[m];按38.5+42.5cm测量'), + DeclareLaunchArgument('footprint_width', default_value='0.80', + description='矩形物理宽[m];按40+40cm测量'), DeclareLaunchArgument('body_height', default_value='0.41', description='轨迹高出地面的高度 [m];仅 navi_mode=3 抬参考路径 z,斜坡需 > R·tanθ+0.15'), DeclareLaunchArgument('cloud_topic', default_value='/cloud_registered', @@ -63,6 +69,8 @@ def generate_launch_description(): description='雷达里程计(Point-LIO 输出),给 sensor_pose'), DeclareLaunchArgument('body_odom_topic', default_value='/body_odom', description='车体中心里程计(body_odom 节点输出),给 body_pose'), + DeclareLaunchArgument('require_perception_ready', default_value='false', + description='实验感知支路必须持续就绪才允许运行'), ] planner = Node( @@ -74,6 +82,9 @@ def generate_launch_description(): planner_yaml, { 'fsm.navi_mode': ParameterValue(navi_mode, value_type=int), + 'fsm.require_controller_feedback': True, + 'fsm.require_perception_ready': ParameterValue( + LaunchConfiguration('require_perception_ready'), value_type=bool), 'manager.max_vel': ParameterValue(max_vel, value_type=float), 'manager.max_acc': ParameterValue(max_acc, value_type=float), 'optimization.max_vel': ParameterValue(max_vel, value_type=float), @@ -81,6 +92,10 @@ def generate_launch_description(): 'grid_map.double_cylinder_radius': ParameterValue(collision_radius, value_type=float), 'grid_map.body_height': ParameterValue(body_height, value_type=float), + 'grid_map.footprint_length': ParameterValue(LaunchConfiguration('footprint_length'), value_type=float), + 'grid_map.footprint_width': ParameterValue(LaunchConfiguration('footprint_width'), value_type=float), + 'grid_map.rectangle_footprint': ParameterValue( + LaunchConfiguration('use_rectangle_footprint'), value_type=bool), }, ], remappings=[ @@ -98,6 +113,11 @@ def generate_launch_description(): name='closed_loop_controller', output='screen', parameters=[controllers_yaml, { + 'require_trajectory_status': True, + 'require_locked_heading': ParameterValue( + LaunchConfiguration('use_rectangle_footprint'), value_type=bool), + 'require_perception_ready': ParameterValue( + LaunchConfiguration('require_perception_ready'), value_type=bool), 'max_vx': ParameterValue(max_vel, value_type=float), 'max_vy': ParameterValue(max_vy, value_type=float), 'max_vyaw': ParameterValue(max_vyaw, value_type=float), diff --git a/minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py b/minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py index 7d2d0ad..1f6bde0 100644 --- a/minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py +++ b/minco_ws/src/scan/plan_manage/launch/vehicle_bringup.launch.py @@ -19,11 +19,12 @@ """ from launch import LaunchDescription -from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, TimerAction +from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, TimerAction, OpaqueFunction from launch.conditions import IfCondition from launch.launch_description_sources import PythonLaunchDescriptionSource -from launch.substitutions import LaunchConfiguration +from launch.substitutions import LaunchConfiguration, PythonExpression from launch_ros.actions import Node +from launch_ros.parameter_descriptions import ParameterValue from launch_ros.substitutions import FindPackageShare @@ -57,12 +58,66 @@ def _default_body_offset(name, fallback='0.0'): return fallback +def _measured_rectangle_geometry(): + """Optical measurements -> IMU-relative center, without changing circle defaults.""" + import os + import yaml + from ament_index_python.packages import get_package_share_directory + path = os.path.join(get_package_share_directory('obstacle_cloud'), 'config', 'flat_corridor.yaml') + with open(path) as stream: + cfg = yaml.safe_load(stream)['obstacle_cloud']['ros__parameters'] + tx, ty, _ = cfg['lidar_to_imu_translation'] + return {'length': cfg['self_front']+cfg['self_rear'], + 'width': cfg['self_left']+cfg['self_right'], + 'offset_x': tx+(cfg['self_front']-cfg['self_rear'])/2, + 'offset_y': ty+(cfg['self_left']-cfg['self_right'])/2} + + +def _validate_measured_extrinsic(): + import os + import yaml + from ament_index_python.packages import get_package_share_directory + with open(os.path.join(get_package_share_directory('point_lio'), 'config', 'mid360.yaml')) as stream: + mapping = yaml.safe_load(stream)['/**']['ros__parameters']['mapping'] + with open(os.path.join(get_package_share_directory('obstacle_cloud'), 'config', 'flat_corridor.yaml')) as stream: + cfg = yaml.safe_load(stream)['obstacle_cloud']['ros__parameters'] + expected = [1., 0., 0., 0., 1., 0., 0., 0., 1.] + if (mapping.get('extrinsic_est_en', True) or + len(mapping['extrinsic_R']) != 9 or len(mapping['extrinsic_T']) != 3 or + any(abs(a-b)>1e-9 for a,b in zip(mapping['extrinsic_R'], expected)) or + any(abs(a-b)>1e-9 for a,b in zip(mapping['extrinsic_T'], cfg['lidar_to_imu_translation']))): + raise RuntimeError('Measured vehicle profile requires matching fixed Point-LIO lidar/IMU extrinsic') + + +def _validate_rectangle(context): + rectangle = LaunchConfiguration('use_rectangle_footprint').perform(context).lower() == 'true' + self_filter = LaunchConfiguration('use_self_filter').perform(context).lower() == 'true' + if rectangle or self_filter: + _validate_measured_extrinsic() + if rectangle: + if LaunchConfiguration('use_obstacle_cloud').perform(context).lower() != 'true': + raise RuntimeError('Rectangle mode requires use_obstacle_cloud:=true') + if LaunchConfiguration('navi_mode').perform(context) != '1': + raise RuntimeError('Rectangle mode currently requires navi_mode:=1') + if LaunchConfiguration('use_self_filter').perform(context).lower() == 'true' and \ + LaunchConfiguration('use_obstacle_cloud').perform(context).lower() != 'true': + raise RuntimeError('Self filtering requires use_obstacle_cloud:=true') + return [] + + def generate_launch_description(): launch_chassis = LaunchConfiguration('launch_chassis') launch_scan = LaunchConfiguration('launch_scan') launch_blocker = LaunchConfiguration('launch_blocker') scan_delay = LaunchConfiguration('scan_delay') step_regions = _default_step_regions() + measured = _measured_rectangle_geometry() + + def rectangle_offset(name): + return PythonExpression([ + "'", str(measured[name]), "' if '", LaunchConfiguration('use_rectangle_footprint'), + "'.lower() == 'true' else '", _default_body_offset(name), "'"]) + declared = [ DeclareLaunchArgument('launch_chassis', default_value='true', @@ -71,6 +126,12 @@ def generate_launch_description(): description='是否启动 SCAN(只测 LIO 时可关)'), DeclareLaunchArgument('launch_blocker', default_value='true', description='是否启动台阶封堵(把台阶从点云里堵死)'), + DeclareLaunchArgument('use_rectangle_footprint', default_value='false', + description='实验矩形碰撞及朝向保持;配合use_obstacle_cloud:=true'), + DeclareLaunchArgument('use_self_filter', default_value='false', + description='实验:实体柱生成前按实测车体去自身点;边界不明时暂停'), + DeclareLaunchArgument('use_obstacle_cloud', default_value='false', + description='实验:全分辨率点云、平路地面分离;先静止验收'), DeclareLaunchArgument('launch_rviz', default_value='false', description='同时启动 RViz(用 rviz/vehicle.rviz 车辆专用配置)'), DeclareLaunchArgument('scan_delay', default_value='5.0', @@ -89,11 +150,11 @@ def generate_launch_description(): DeclareLaunchArgument('step_regions', default_value=step_regions, description='台阶矩形,世界系;留空则不封堵'), DeclareLaunchArgument('body_offset_x', - default_value=_default_body_offset('offset_x'), - description='车体中心在雷达系下的 x [m]'), + default_value=rectangle_offset('offset_x'), + description='车体中心在输入里程计(IMU)系下的x;矩形默认按实测外参换算'), DeclareLaunchArgument('body_offset_y', - default_value=_default_body_offset('offset_y'), - description='车体中心在雷达系下的 y [m]'), + default_value=rectangle_offset('offset_y'), + description='车体中心在输入里程计(IMU)系下的y;矩形默认按实测外参换算'), DeclareLaunchArgument('body_offset_z', default_value=_default_body_offset('offset_z'), description='车体中心在雷达系下的 z [m]'), @@ -134,6 +195,14 @@ def generate_launch_description(): ) # ---- 3. 台阶封堵:/cloud_registered -> /cloud_registered_for_scan ------ + obstacle_cloud = Node( + package='obstacle_cloud', executable='obstacle_cloud', name='obstacle_cloud', + output='screen', condition=IfCondition(LaunchConfiguration('use_obstacle_cloud')), + additional_env={'OPENBLAS_NUM_THREADS': '1'}, + parameters=[[FindPackageShare('obstacle_cloud'), '/config/flat_corridor.yaml'], { + 'self_filter_enable': ParameterValue(LaunchConfiguration('use_self_filter'), value_type=bool), + }], + ) blocker = IncludeLaunchDescription( PythonLaunchDescriptionSource([ FindPackageShare('step_blocker'), '/launch', @@ -142,6 +211,10 @@ def generate_launch_description(): condition=IfCondition(launch_blocker), launch_arguments={ 'regions': LaunchConfiguration('step_regions'), + 'blocker_input_topic': PythonExpression([ + "'/cloud_obstacles_for_scan' if '", LaunchConfiguration('use_obstacle_cloud'), + "'.lower() == 'true' else '/cloud_registered'", + ]), }.items(), ) @@ -162,8 +235,16 @@ def generate_launch_description(): 'max_vy': LaunchConfiguration('max_vy'), 'max_vyaw': LaunchConfiguration('max_vyaw'), 'collision_radius': LaunchConfiguration('collision_radius'), + 'use_rectangle_footprint': LaunchConfiguration('use_rectangle_footprint'), + 'footprint_length': str(measured['length']), + 'footprint_width': str(measured['width']), 'body_height': LaunchConfiguration('body_height'), - 'cloud_topic': LaunchConfiguration('cloud_topic'), + 'cloud_topic': PythonExpression([ + "'/cloud_obstacles_for_scan' if '", LaunchConfiguration('use_obstacle_cloud'), + "'.lower() == 'true' and '", launch_blocker, + "'.lower() != 'true' else '", LaunchConfiguration('cloud_topic'), "'", + ]), + 'require_perception_ready': LaunchConfiguration('use_obstacle_cloud'), 'odom_topic': LaunchConfiguration('odom_topic'), }.items(), ), @@ -190,4 +271,4 @@ def generate_launch_description(): ) return LaunchDescription( - declared + [lio, tf_bridge, body_odom_node, blocker, scan, chassis, rviz]) + declared + [OpaqueFunction(function=_validate_rectangle), lio, tf_bridge, body_odom_node, obstacle_cloud, blocker, scan, chassis, rviz]) diff --git a/minco_ws/src/scan/plan_manage/package.xml b/minco_ws/src/scan/plan_manage/package.xml index 6b8e63a..d4a41e2 100644 --- a/minco_ws/src/scan/plan_manage/package.xml +++ b/minco_ws/src/scan/plan_manage/package.xml @@ -30,10 +30,14 @@ launch_ros robot_state_publisher rviz2 + obstacle_cloud launch_testing_ament_cmake ament_cmake_gtest ament_cmake_pytest python3-pytest + sensor_msgs_py + rcl_interfaces + python3-yaml ament_cmake diff --git a/minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp b/minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp index 2eb1c26..e12167b 100644 --- a/minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp +++ b/minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp @@ -10,7 +10,9 @@ #include #include #include +#include #include +#include #include #include @@ -56,6 +58,11 @@ public: // 目标四元数指定的 yaw。默认 false,保持"只给位置"的既有行为不变。 align_to_goal_yaw_ = declare_parameter("align_to_goal_yaw", false); yaw_goal_tolerance_ = declare_parameter("yaw_goal_tolerance", 0.10); + // Vehicle launch requires explicit authorization for this exact spline. + // Standalone legacy users may still publish only planning/bspline. + require_trajectory_status_ = declare_parameter("require_trajectory_status", false); + require_perception_ready_ = declare_parameter("require_perception_ready", false); + require_locked_heading_ = declare_parameter("require_locked_heading", false); bspline_sub_ = create_subscription( "planning/bspline", 10, @@ -67,6 +74,20 @@ public: goal_sub_ = create_subscription( "move_base_simple/goal", 10, std::bind(&ClosedLoopController::goalYawCallback, this, std::placeholders::_1)); + status_sub_ = create_subscription( + "planning/trajectory_status", rclcpp::QoS(1).reliable().transient_local(), + [this](scan_planner_msgs::msg::TrajectoryStatus::ConstSharedPtr msg) { + status_ = *msg; + have_status_ = true; + }); + trajectory_done_pub_ = create_publisher("planning/trajectory_done", 10); + if (require_perception_ready_) + perception_sub_ = create_subscription( + "planning/perception_ready", rclcpp::QoS(1).reliable().transient_local(), + [this](std_msgs::msg::Bool::ConstSharedPtr msg) { + perception_ready_ = msg->data; + perception_update_ = now(); + }); cmd_vel_pub_ = create_publisher("cmd_vel", 20); execution_frozen_pub_ = create_publisher("planning/go2_execution_frozen", 10); cmd_timer_ = create_wall_timer(std::chrono::milliseconds(10), @@ -169,6 +190,13 @@ private: void odomCallback(const nav_msgs::msg::Odometry::ConstSharedPtr msg) { + if (require_locked_heading_ || (have_status_ && status_.hold_heading)) { + const auto &p = msg->pose.pose.position; + const auto &q = msg->pose.pose.orientation; + const Eigen::Quaterniond orientation(q.w, q.x, q.y, q.z); + if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z) || + !orientation.coeffs().allFinite() || orientation.norm() < 1e-6) return; + } 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); // 实测速度:body_odom 的 twist.linear 是 body 系,转到世界系供速度阻尼使用。 @@ -179,6 +207,7 @@ private: const double bvx = msg->twist.twist.linear.x; const double bvy = msg->twist.twist.linear.y; odom_vel_world_ << c * bvx - s * bvy, s * bvx + c * bvy; + odom_update_ = now(); have_odom_ = true; } @@ -200,10 +229,24 @@ private: void cmdCallback() { - if (!receive_traj_ || !have_odom_) + const bool status_allows_motion = !have_status_ ? !require_trajectory_status_ : + status_.state == scan_planner_msgs::msg::TrajectoryStatus::ACTIVE && + status_.traj_id == traj_id_; + const double perception_age = (now() - perception_update_).seconds(); + const bool perception_allows_motion = !require_perception_ready_ || + (perception_ready_ && perception_age >= 0.0 && perception_age <= 0.3); + const bool locked = require_locked_heading_ || (have_status_ && status_.hold_heading); + const double grant_age = have_status_ ? (now()-rclcpp::Time(status_.header.stamp)).seconds() : 1e9; + const double odom_age = (now()-odom_update_).seconds(); + const bool footprint_allows_motion = !locked || + (have_status_ && status_.hold_heading && status_.heading_tolerance > 0 && + status_.heading_tolerance <= 0.1 && std::isfinite(status_.heading) && + grant_age >= 0 && grant_age <= 0.2 && odom_age >= 0 && odom_age <= 0.2); + if (!receive_traj_ || !have_odom_ || !status_allows_motion || !perception_allows_motion || !footprint_allows_motion) { - publishExecutionFrozen(false); + publishExecutionFrozen(locked); publishStop(); + last_update_time_ = now(); return; } const auto current_time = now(); @@ -220,17 +263,20 @@ private: } const double t_eval = std::min(exec_time_, traj_duration_); Eigen::Vector3d pos_des = traj_[0].evaluateDeBoorT(t_eval); - double yaw_error = normalizeAngle(estimateDesiredYaw(t_eval, pos_des) - odom_yaw_); + double yaw_error = normalizeAngle((locked ? status_.heading : estimateDesiredYaw(t_eval, pos_des)) - odom_yaw_); // 倒车模式:期望朝向与车头几乎相反(目标在正后方)时,全向底盘不必掉头 —— // 保持车头、直接反向平移即可。本车满足三个前提:全向底盘(vx/vy/wz 独立)、 // 碰撞模型为圆(double_cylinder_offset=0,朝向不影响占位)、雷达 360°。 // 判据取 120°,避免把正常的急转弯误判成倒车。 - if (allow_reverse_ && std::abs(yaw_error) > reverse_yaw_threshold_) + if (!locked && allow_reverse_ && std::abs(yaw_error) > reverse_yaw_threshold_) yaw_error = 0.0; - const double yaw_command = std::clamp(kp_yaw_ * yaw_error, -max_vyaw_, max_vyaw_); - if (std::abs(yaw_error) > heading_error_threshold_) + const double yaw_command = locked && !status_.correction_rotation_allowed ? 0.0 : + std::clamp(kp_yaw_ * yaw_error, -max_vyaw_, max_vyaw_); + // During terminal alignment, heading may intentionally leave the translation envelope. + if (!(locked && arrived_) && std::abs(yaw_error) > + (locked ? status_.heading_tolerance : heading_error_threshold_)) { publishExecutionFrozen(true); publishStop(yaw_command); @@ -242,11 +288,16 @@ private: exec_time_ = std::min(traj_duration_, exec_time_ + dt); last_update_time_ = current_time; pos_des = traj_[0].evaluateDeBoorT(exec_time_); + // Only the final local window owns the task endpoint. Keep following the + // 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::Vector3d end_pt = traj_[0].evaluateDeBoorT(traj_duration_); + 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()); @@ -299,8 +350,8 @@ private: { // 位置已到位。若开启终点朝向对齐且朝向误差仍超容差,则原地转,不发线速度。 double yaw_err = 0.0; - if (align_to_goal_yaw_ && has_goal_) - yaw_err = normalizeAngle(goal_yaw_ - odom_yaw_); + 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_); if (std::abs(yaw_err) > yaw_goal_tolerance_) { @@ -308,23 +359,46 @@ private: // 变成"转一点、又开一段、再转"的来回摆动 publishExecutionFrozen(true); geometry_msgs::msg::Twist align_cmd; - align_cmd.angular.z = std::clamp(kp_yaw_ * yaw_err, -max_vyaw_, max_vyaw_); + if (!locked || status_.terminal_rotation_allowed) + align_cmd.angular.z = std::clamp(kp_yaw_ * yaw_err, -max_vyaw_, max_vyaw_); cmd_vel_pub_->publish(align_cmd); return; } publishExecutionFrozen(false); command = geometry_msgs::msg::Twist(); + // Repeat feedback until the FSM revokes this trajectory; a missed + // volatile message must not leave a completed task stuck in EXEC_TRAJ. + if (dist_to_goal < finish_dist_) + { + std_msgs::msg::Int64 done; + done.data = traj_id_; + trajectory_done_pub_->publish(done); + } + } + // 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) { + command.linear.x = 0.0; + command.linear.y = 0.0; } cmd_vel_pub_->publish(command); } rclcpp::Publisher::SharedPtr cmd_vel_pub_; rclcpp::Publisher::SharedPtr execution_frozen_pub_; + rclcpp::Publisher::SharedPtr trajectory_done_pub_; + rclcpp::Subscription::SharedPtr status_sub_; + scan_planner_msgs::msg::TrajectoryStatus status_; + bool require_trajectory_status_{false}, have_status_{false}; + rclcpp::Subscription::SharedPtr perception_sub_; + bool require_perception_ready_{false}, perception_ready_{false}; + rclcpp::Time perception_update_{0, 0, RCL_ROS_TIME}; rclcpp::Subscription::SharedPtr bspline_sub_; rclcpp::Subscription::SharedPtr odom_sub_; rclcpp::Subscription::SharedPtr goal_sub_; rclcpp::TimerBase::SharedPtr cmd_timer_; + bool require_locked_heading_{false}; + rclcpp::Time odom_update_{0, 0, RCL_ROS_TIME}; bool receive_traj_{false}; bool have_odom_{false}; bool align_to_goal_yaw_{false}; diff --git a/minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp b/minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp index b0f6f04..52c413a 100644 --- a/minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp +++ b/minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,7 @@ namespace scan_planner need_hover_stop_ = false; replan_fail_count_ = 0; last_freeze_update_time_ = node_->now(); + blocked_since_ = next_retry_ = perception_update_ = node_->now(); /* fsm param */ navi_mode_ = load_parameter(node_, "fsm.navi_mode", -1); @@ -42,6 +44,13 @@ namespace scan_planner emergency_time_ = load_parameter(node_, "fsm.emergency_time", 1.0); enable_fail_safe_ = load_parameter(node_, "fsm.fail_safe", true); max_replan_fail_count_ = load_parameter(node_, "fsm.max_replan_fail_count", 1000); + goal_tolerance_ = load_parameter(node_, "fsm.goal_tolerance", 0.08); + blocked_timeout_ = load_parameter(node_, "fsm.blocked_timeout", 10.0); + blocked_retry_period_ = load_parameter(node_, "fsm.blocked_retry_period", 0.5); + require_perception_ready_ = load_parameter(node_, "fsm.require_perception_ready", false); + require_controller_feedback_ = load_parameter(node_, "fsm.require_controller_feedback", false); + if (goal_tolerance_ <= 0 || blocked_timeout_ <= 0 || blocked_retry_period_ <= 0) + throw std::runtime_error("goal tolerance and blocked retry/timeout must be positive"); self_inflation_z_up_ = load_parameter(node_, "grid_map.obstacles_inflation_z_up", 0.0); self_inflation_z_down_ = load_parameter(node_, "grid_map.obstacles_inflation_z_down", 0.0); self_double_cylinder_radius_ = load_parameter(node_, "grid_map.double_cylinder_radius", 0.0); @@ -71,6 +80,9 @@ namespace scan_planner visualization_.reset(new PlanningVisualization(node_)); planner_manager_.reset(new SCANPlannerManager); planner_manager_->initPlanModules(node_, visualization_); + if (planner_manager_->grid_map_->usesRectangleFootprint() && + (navi_mode_ != NAVI_MODE::MANUAL_TARGET || !require_controller_feedback_ || !require_perception_ready_)) + throw std::runtime_error("Rectangle mode requires manual goals, controller feedback and perception readiness"); /* callback */ exec_timer_ = node_->create_wall_timer(std::chrono::milliseconds(10), @@ -85,6 +97,18 @@ namespace scan_planner std::bind(&SCANReplanFSM::go2ExecutionFrozenCallback, this, std::placeholders::_1)); bspline_pub_ = node_->create_publisher("planning/bspline", 10); + trajectory_status_pub_ = node_->create_publisher( + "planning/trajectory_status", rclcpp::QoS(1).reliable().transient_local()); + trajectory_done_sub_ = node_->create_subscription( + "planning/trajectory_done", 10, + std::bind(&SCANReplanFSM::trajectoryDoneCallback, this, std::placeholders::_1)); + perception_ready_sub_ = node_->create_subscription( + "planning/perception_ready", rclcpp::QoS(1).reliable().transient_local(), + [this](const std_msgs::msg::Bool::ConstSharedPtr msg) { + perception_ready_ = msg->data; + perception_update_ = node_->now(); + }); + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::HOLD, "waiting_for_target"); data_disp_pub_ = node_->create_publisher("planning/data_display", 100); self_inflation_pub_ = node_->create_publisher( "self_inflation", rclcpp::QoS(1).reliable().transient_local()); @@ -123,7 +147,7 @@ namespace scan_planner } else { - RCLCPP_ERROR(node_->get_logger(), "Unable to generate global trajectory to first preset waypoint"); + enterBlocked("first_preset_waypoint_unavailable"); } } @@ -161,11 +185,22 @@ namespace scan_planner init_pt_ = odom_pos_; bool success = false; - end_pt_ << msg->poses[0].pose.position.x, msg->poses[0].pose.position.y, rviz_goal_height_; + const Eigen::Vector3d requested(msg->poses[0].pose.position.x, + msg->poses[0].pose.position.y, rviz_goal_height_); + if (!requested.allFinite()) return; + beginGoal(requested); + const auto &q = msg->poses[0].pose.orientation; + Eigen::Quaterniond goal_q(q.w, q.x, q.y, q.z); + target_yaw_valid_ = goal_q.coeffs().allFinite() && goal_q.norm() > 1e-6; + if (target_yaw_valid_) { + goal_q.normalize(); + const auto heading = goal_q.toRotationMatrix().col(0).eval(); + target_yaw_ = std::atan2(heading.y(), heading.x()); + } success = planner_manager_->planGlobalTraj(odom_pos_, odom_vel_, Eigen::Vector3d::Zero(), end_pt_, Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero()); if (success) - success = adjustGlobalTargetIfOccupied(); + success = validateGlobalTarget(); visualization_->displayGoalPoint(end_pt_, Eigen::Vector4d(0, 0.5, 0.5, 1), 0.3, 0); @@ -186,17 +221,15 @@ namespace scan_planner have_new_target_ = true; /*** FSM ***/ - if (exec_state_ == WAIT_TARGET) + if (exec_state_ != INIT) changeFSMExecState(GEN_NEW_TRAJ, "TRIG"); - else if (exec_state_ == EXEC_TRAJ) - changeFSMExecState(REPLAN_TRAJ, "TRIG"); // visualization_->displayGoalPoint(end_pt_, Eigen::Vector4d(1, 0, 0, 1), 0.3, 0); visualization_->displayGlobalPathList(gloabl_traj, 0.1, 0); } else { - RCLCPP_ERROR(node_->get_logger(), "Unable to generate global trajectory"); + enterBlocked("global_goal_occupied_or_reference_failed"); } } @@ -208,7 +241,6 @@ namespace scan_planner return false; } - end_pt_ = waypoints.back(); std::vector reference_waypoints(waypoints.begin() + 1, waypoints.end()); for (size_t i = 0; i < waypoints.size(); i++) @@ -230,7 +262,7 @@ namespace scan_planner return false; } - if (!adjustGlobalTargetIfOccupied()) + if (!validateGlobalTarget()) return false; constexpr double step_size_t = 0.1; @@ -258,7 +290,7 @@ namespace scan_planner return false; } - end_pt_ = active_waypoints_[current_wp_]; + beginGoal(active_waypoints_[current_wp_]); setStartStateFromOdomOrCurrentTraj(); bool success = planner_manager_->planGlobalTraj( @@ -276,7 +308,7 @@ namespace scan_planner return false; } - if (!adjustGlobalTargetIfOccupied()) + if (!validateGlobalTarget()) return false; constexpr double step_size_t = 0.1; @@ -303,44 +335,100 @@ namespace scan_planner return navi_mode_ == NAVI_MODE::PRESET_TARGET; } - bool SCANReplanFSM::adjustGlobalTargetIfOccupied() + void SCANReplanFSM::beginGoal(const Eigen::Vector3d &goal) { - auto map = planner_manager_->grid_map_; - auto &global_data = planner_manager_->global_data_; - const double duration = global_data.global_duration_; - if (!map || duration < 1e-3) - return true; + raw_goal_ = end_pt_ = goal; + target_yaw_valid_ = false; + ++goal_id_; + have_target_ = true; + have_new_target_ = true; + completed_trajectory_id_ = -1; + replan_fail_count_ = 0; + need_hover_stop_ = false; + flag_escape_emergency_ = true; + last_trajectory_final_ = false; + blocked_since_ = node_->now(); + // A new goal must never continue executing the previous goal's spline. + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::HOLD, "new_goal"); + planner_manager_->grid_map_->setFootprintHeading(getOdomYaw()); + } - constexpr double sample_dt = 0.05; - const int sample_num = std::max(1, static_cast(std::ceil(duration / sample_dt))); - const Eigen::Vector3d final_pt = global_data.global_traj_.evaluate(duration); - const Eigen::Vector3d final_prev = global_data.global_traj_.evaluate(duration * (sample_num - 1) / sample_num); - const int final_occ = map->getInflateOccupancy(final_pt, estimateYawFromSegment(final_prev, final_pt)); - if (final_occ <= 0) - return true; + bool SCANReplanFSM::perceptionIsReady() const + { + return !require_perception_ready_ || + (perception_ready_ && (node_->now() - perception_update_).seconds() >= 0.0 && + (node_->now() - perception_update_).seconds() <= 0.3); + } - for (int i = sample_num; i >= 0; --i) - { - const double t = duration * i / sample_num; - const double prev_t = duration * std::max(0, i - 1) / sample_num; - const Eigen::Vector3d pt = global_data.global_traj_.evaluate(t); - const Eigen::Vector3d prev_pt = global_data.global_traj_.evaluate(prev_t); - - if (map->getInflateOccupancy(pt, estimateYawFromSegment(prev_pt, pt)) == 0) - { - const Eigen::Vector3d raw_end = end_pt_; - end_pt_ = pt; - global_data.global_duration_ = t; - global_data.last_progress_time_ = std::min(global_data.last_progress_time_, t); - RCLCPP_WARN(node_->get_logger(), - "Target [%.2f, %.2f, %.2f] is occupied; using [%.2f, %.2f, %.2f]", - raw_end(0), raw_end(1), raw_end(2), end_pt_(0), end_pt_(1), end_pt_(2)); - return true; - } + void SCANReplanFSM::publishTrajectoryStatus(uint8_t state, const std::string &reason) + { + scan_planner_msgs::msg::TrajectoryStatus msg; + msg.header.stamp = node_->now(); + msg.header.frame_id = self_inflation_frame_id_; + msg.goal_id = goal_id_; + msg.traj_id = state == msg.ACTIVE ? planner_manager_->local_data_.traj_id_ : -1; + msg.state = state; + msg.is_final = last_trajectory_final_; + msg.goal.x = raw_goal_.x(); msg.goal.y = raw_goal_.y(); msg.goal.z = raw_goal_.z(); + msg.reason = reason; + auto map = planner_manager_->grid_map_; + msg.hold_heading = map->usesRectangleFootprint(); + msg.heading = map->footprintHeading(); + msg.heading_tolerance = map->footprintYawTolerance(); + msg.target_yaw_valid = target_yaw_valid_; + msg.target_yaw = target_yaw_; + if (msg.hold_heading && state == msg.ACTIVE) { + msg.correction_rotation_allowed = map->rotationIsFree(odom_pos_, getOdomYaw(), msg.heading); + if (last_trajectory_final_ && target_yaw_valid_ && + (odom_pos_-raw_goal_).head<2>().norm() < 2*goal_tolerance_) + msg.terminal_rotation_allowed = map->rotationIsFree(odom_pos_, getOdomYaw(), target_yaw_); } + trajectory_status_pub_->publish(msg); + } - RCLCPP_ERROR(node_->get_logger(), - "Target is occupied and no collision-free point was found on the global trajectory"); + void SCANReplanFSM::trajectoryDoneCallback(const std_msgs::msg::Int64::ConstSharedPtr &msg) + { + if (exec_state_ == EXEC_TRAJ && msg->data == planner_manager_->local_data_.traj_id_) + completed_trajectory_id_ = msg->data; + } + + void SCANReplanFSM::enterBlocked(const std::string &reason) + { + if (exec_state_ != BLOCKED) blocked_since_ = node_->now(); + next_retry_ = node_->now() + rclcpp::Duration::from_seconds(blocked_retry_period_); + blocked_reason_ = reason; + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::HOLD, reason); + RCLCPP_WARN(node_->get_logger(), + "Goal %lu blocked: %s; preserving original [%.3f, %.3f, %.3f]", + static_cast(goal_id_), reason.c_str(), + raw_goal_.x(), raw_goal_.y(), raw_goal_.z()); + changeFSMExecState(BLOCKED, "BLOCKED"); + } + + bool SCANReplanFSM::validateGlobalTarget() + { + if (!perceptionIsReady()) return false; + auto map = planner_manager_->grid_map_; + if (map->usesRectangleFootprint()) { + const double age = (node_->now()-odom_update_).seconds(); + if (age < 0 || age > 0.2 || map->getRectangleOccupancy(odom_pos_, getOdomYaw()) != 0) return false; + // Arrival anywhere inside the position tolerance must permit the requested turn. + 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_)) { + RCLCPP_WARN_THROTTLE(node_->get_logger(), *node_->get_clock(), 1000, + "Requested terminal rotation is blocked; original goal retained"); + return false; + } + } + 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. + // getLocalTarget separately requires an in-map, explicitly free endpoint. + if (globalGoalMayRemainActive(occ)) return true; + RCLCPP_WARN_THROTTLE(node_->get_logger(), *node_->get_clock(), 1000, + "Original goal [%.3f, %.3f, %.3f] occupied; keeping it unchanged", + raw_goal_.x(), raw_goal_.y(), raw_goal_.z()); return false; } @@ -375,31 +463,33 @@ namespace scan_planner msg->poses.size(), waypoints.size()); trigger_ = true; - end_pt_ = waypoints.back(); - bool success = planGlobalTrajByWaypoints(waypoints); + beginGoal(waypoints.back()); + reference_waypoints_ = waypoints; + bool success = planGlobalTrajByWaypoints(reference_waypoints_); if (success) { /*** FSM ***/ - if (exec_state_ == WAIT_TARGET) - { + if (exec_state_ != INIT) changeFSMExecState(GEN_NEW_TRAJ, "TRIG"); - } - else if (exec_state_ == EXEC_TRAJ) - { - changeFSMExecState(REPLAN_TRAJ, "TRIG"); - } RCLCPP_INFO(node_->get_logger(), "Reference path accepted"); } else { - RCLCPP_ERROR(node_->get_logger(), "Unable to generate global trajectory from reference path"); + enterBlocked("reference_goal_occupied_or_reference_failed"); } } void SCANReplanFSM::odometryCallback(const nav_msgs::msg::Odometry::ConstSharedPtr &msg) { + if (planner_manager_->grid_map_->usesRectangleFootprint()) { + const auto &p = msg->pose.pose.position; + const auto &q = msg->pose.pose.orientation; + const Eigen::Quaterniond orientation(q.w, q.x, q.y, q.z); + if (!std::isfinite(p.x) || !std::isfinite(p.y) || !std::isfinite(p.z) || + !orientation.coeffs().allFinite() || orientation.norm() < 1e-6) return; + } odom_pos_(0) = msg->pose.pose.position.x; odom_pos_(1) = msg->pose.pose.position.y; odom_pos_(2) = msg->pose.pose.position.z; @@ -422,6 +512,19 @@ namespace scan_planner odom_orient_.y() = msg->pose.pose.orientation.y; odom_orient_.z() = msg->pose.pose.orientation.z; + if (planner_manager_->grid_map_->usesRectangleFootprint()) { + odom_orient_.normalize(); + // body_odom copies Point-LIO's body-frame twist; planning states are world-frame. + const double yaw = getOdomYaw(); + const double vx = odom_vel_.x(), vy = odom_vel_.y(); + odom_vel_.x() = std::cos(yaw)*vx - std::sin(yaw)*vy; + odom_vel_.y() = std::sin(yaw)*vx + std::cos(yaw)*vy; + if (!have_odom_) { + planner_manager_->grid_map_->setFootprintHeading(getOdomYaw()); + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::HOLD, "waiting_for_target"); + } + } + odom_update_ = node_->now(); have_odom_ = true; publishSelfInflationMarker(); if (navi_mode_ == NAVI_MODE::PRESET_TARGET && !preset_started_) @@ -496,6 +599,18 @@ namespace scan_planner Eigen::Vector3d front = center + self_double_cylinder_offset_ * heading; Eigen::Vector3d rear = center - self_double_cylinder_offset_ * heading; + if (planner_manager_->grid_map_->usesRectangleFootprint()) { + const auto map = planner_manager_->grid_map_; + marker.type = visualization_msgs::msg::Marker::CUBE; + marker.scale.x = map->footprintLength() + 2*map->footprintMargin(); + marker.scale.y = map->footprintWidth() + 2*map->footprintMargin(); + marker.pose.orientation.z = std::sin(getOdomYaw()/2); + marker.pose.orientation.w = std::cos(getOdomYaw()/2); + marker.pose.position.x = center.x(); marker.pose.position.y = center.y(); marker.pose.position.z = center.z(); + marker.id = 0; + self_inflation_pub_->publish(marker); + return; + } marker.id = 0; marker.pose.position.x = front(0); marker.pose.position.y = front(1); @@ -517,9 +632,11 @@ namespace scan_planner else continuously_called_times_ = 1; - static string state_str[7] = {"INIT", "WAIT_TARGET", "GEN_NEW_TRAJ", "REPLAN_TRAJ", "EXEC_TRAJ", "EMERGENCY_STOP"}; + static string state_str[7] = {"INIT", "WAIT_TARGET", "GEN_NEW_TRAJ", "REPLAN_TRAJ", "EXEC_TRAJ", "EMERGENCY_STOP", "BLOCKED"}; int pre_s = int(exec_state_); exec_state_ = new_state; + if (new_state == EMERGENCY_STOP) + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::HOLD, "emergency_stop"); cout << "[" + pos_call + "]: from " + state_str[pre_s] + " to " + state_str[int(new_state)] << endl; } @@ -530,7 +647,7 @@ namespace scan_planner void SCANReplanFSM::printFSMExecState() { - static string state_str[7] = {"INIT", "WAIT_TARGET", "GEN_NEW_TRAJ", "REPLAN_TRAJ", "EXEC_TRAJ", "EMERGENCY_STOP"}; + static string state_str[7] = {"INIT", "WAIT_TARGET", "GEN_NEW_TRAJ", "REPLAN_TRAJ", "EXEC_TRAJ", "EMERGENCY_STOP", "BLOCKED"}; cout << "[FSM]: state: " + state_str[int(exec_state_)] << endl; } @@ -551,6 +668,10 @@ namespace scan_planner fsm_num = 0; } + if (have_target_ && exec_state_ != BLOCKED && exec_state_ != INIT && + !perceptionIsReady()) + enterBlocked("perception_not_ready_or_stale"); + switch (exec_state_) { case INIT: @@ -581,6 +702,11 @@ namespace scan_planner case GEN_NEW_TRAJ: { setStartStateFromOdomOrCurrentTraj(); + if (!validateGlobalTarget()) + { + enterBlocked("global_goal_occupied_or_perception_not_ready"); + break; + } // Eigen::Vector3d rot_x = odom_orient_.toRotationMatrix().block(0, 0, 3, 1); // start_yaw_(0) = atan2(rot_x(1), rot_x(0)); @@ -603,7 +729,7 @@ namespace scan_planner else { replan_fail_count_++; - changeFSMExecState(GEN_NEW_TRAJ, "FSM"); + enterBlocked("initial_local_plan_failed"); } break; } @@ -619,12 +745,47 @@ namespace scan_planner else { replan_fail_count_++; - changeFSMExecState(REPLAN_TRAJ, "FSM"); + enterBlocked("local_replan_failed"); } break; } + case BLOCKED: + { + if ((node_->now() - blocked_since_).seconds() >= blocked_timeout_) + { + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::FAILED, + "blocked_timeout: " + blocked_reason_); + have_target_ = false; + trigger_ = false; + RCLCPP_ERROR(node_->get_logger(), "Goal %lu failed after %.2fs blocked; original goal retained", + static_cast(goal_id_), blocked_timeout_); + changeFSMExecState(WAIT_TARGET, "FAILED"); + break; + } + if (node_->now() < next_retry_ || !perceptionIsReady()) break; + // Never rebuild a reference path as a straight line: retain its complete route. + start_pt_ = odom_pos_; + start_vel_ = odom_vel_; + start_acc_.setZero(); + bool success = validateGlobalTarget(); + if (success && navi_mode_ != NAVI_MODE::REFERENCE_PATH) + success = planner_manager_->planGlobalTraj(start_pt_, start_vel_, start_acc_, raw_goal_, + Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero()); + if (success && navi_mode_ == NAVI_MODE::REFERENCE_PATH) + success = planGlobalTrajByWaypoints(reference_waypoints_); + if (success) success = callReboundReplan(true, false); + if (success) + { + replan_fail_count_ = 0; + changeFSMExecState(EXEC_TRAJ, "RECOVERED"); + } + else + next_retry_ = node_->now() + rclcpp::Duration::from_seconds(blocked_retry_period_); + break; + } + case EXEC_TRAJ: { /* determine if need to replan */ @@ -635,67 +796,33 @@ namespace scan_planner Eigen::Vector3d pos = info->position_traj_.evaluateDeBoorT(t_cur); - if (isWaypointSequenceMode() && - current_wp_ + 1 < (int)active_waypoints_.size() && - (end_pt_ - odom_pos_).norm() < 0.5) + const bool controller_done = completed_trajectory_id_ == info->traj_id_ || + (!require_controller_feedback_ && last_trajectory_final_ && + reachedTaskPosition(odom_pos_, raw_goal_, goal_tolerance_)); + if (controller_done && last_trajectory_final_ && + reachedTaskPosition(odom_pos_, raw_goal_, goal_tolerance_)) { - current_wp_++; - if (planNextWaypoint()) + if (isWaypointSequenceMode() && current_wp_ + 1 < (int)active_waypoints_.size()) { - changeFSMExecState(GEN_NEW_TRAJ, "FSM"); + ++current_wp_; + if (planNextWaypoint()) changeFSMExecState(GEN_NEW_TRAJ, "NEXT_WAYPOINT"); + else enterBlocked("next_waypoint_unavailable"); return; } - replan_fail_count_++; - changeFSMExecState(GEN_NEW_TRAJ, "FSM"); - return; - } - - /* && (end_pt_ - pos).norm() < 0.5 */ - if (t_cur > info->duration_ - 1e-2) - { - const auto &global_data = planner_manager_->global_data_; - const bool reference_path_has_next_window = - navi_mode_ == NAVI_MODE::REFERENCE_PATH && - global_data.last_progress_time_ < global_data.global_duration_ - 1e-3; - - // In reference-path mode, a local B-spline covers only one planning - // horizon. Finishing that spline does not mean that the complete PCT - // route has been reached: request the next local window and keep the - // global target active. - if (reference_path_has_next_window) - { - RCLCPP_INFO(node_->get_logger(), - "Local reference window complete (%.2f/%.2fs); continuing along the global path", - global_data.last_progress_time_, global_data.global_duration_); - changeFSMExecState(REPLAN_TRAJ, "FSM"); - return; - } - - if (isWaypointSequenceMode() && current_wp_ + 1 < (int)active_waypoints_.size()) - { - current_wp_++; - if (planNextWaypoint()) - { - changeFSMExecState(GEN_NEW_TRAJ, "FSM"); - return; - } - replan_fail_count_++; - changeFSMExecState(GEN_NEW_TRAJ, "FSM"); - return; - } - - if (isWaypointSequenceMode()) - { - active_waypoints_.clear(); - current_wp_ = 0; - } - have_target_ = false; - - changeFSMExecState(WAIT_TARGET, "FSM"); + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::SUCCEEDED, "original_goal_reached"); + changeFSMExecState(WAIT_TARGET, "SUCCEEDED"); return; } - else if ((end_pt_ - pos).norm() < no_replan_thresh_) + if (controller_done || t_cur > info->duration_ - 1e-2) + { + // The controller owns spatial arrival and terminal yaw. Reaching a + // reference time cannot complete a task or disable collision monitoring. + if (last_trajectory_final_ && !controller_done) break; + changeFSMExecState(REPLAN_TRAJ, "NEXT_LOCAL_WINDOW"); + return; + } + if ((end_pt_ - pos).norm() < no_replan_thresh_) { // cout << "near end" << endl; return; @@ -812,7 +939,7 @@ namespace scan_planner return false; } - if (!adjustGlobalTargetIfOccupied()) + if (!validateGlobalTarget()) return false; bool success = callReboundReplan(true, false); @@ -832,8 +959,13 @@ namespace scan_planner start_vel_ = odom_vel_; start_acc_.setZero(); + // A new rectangle task revoked the previous spline with HOLD. Its frozen + // reference velocity is not evidence of actual motion at the new start. + if (have_new_target_ && planner_manager_->grid_map_->usesRectangleFootprint()) + return; + LocalTrajData *info = &planner_manager_->local_data_; - if (info->start_time_.seconds() < 1e-5 || info->duration_ <= 1e-5) + if (exec_state_ == BLOCKED || info->start_time_.seconds() < 1e-5 || info->duration_ <= 1e-5) return; const double raw_t_cur = (node_->now() - info->start_time_).seconds(); @@ -859,16 +991,53 @@ namespace scan_planner LocalTrajData *info = &planner_manager_->local_data_; auto map = planner_manager_->grid_map_; - if (exec_state_ == WAIT_TARGET || info->start_time_.seconds() < 1e-5) + if (exec_state_ == WAIT_TARGET || exec_state_ == BLOCKED || info->start_time_.seconds() < 1e-5) return; + if (map->usesRectangleFootprint()) { + const double age = (node_->now()-odom_update_).seconds(); + if (age < 0 || age > 0.2 || !perceptionIsReady() || + map->getRectangleOccupancy(odom_pos_, getOdomYaw()) != 0) { + enterBlocked("actual_footprint_occupied_or_odometry_stale"); + return; + } + } /* ---------- check trajectory ---------- */ constexpr double time_step = 0.01; double t_cur = (node_->now() - info->start_time_).seconds(); + if (exec_state_ == EXEC_TRAJ && last_trajectory_final_ && t_cur >= info->duration_) + { + const Eigen::Vector3d endpoint = info->position_traj_.evaluateDeBoorT(info->duration_); + const int samples = std::max(1, static_cast(std::ceil((endpoint - odom_pos_).norm() / 0.025))); + for (int i = 0; i <= samples; ++i) + { + const Eigen::Vector3d p = odom_pos_ + (endpoint - odom_pos_) * (double(i) / samples); + if (map->getInflateOccupancy(p, getOdomYaw()) != 0) + { + enterBlocked("terminal_correction_not_free"); + return; + } + } + } + if (map->usesRectangleFootprint()) { + const Eigen::Vector3d reference = info->position_traj_.evaluateDeBoorT(std::clamp(t_cur, 0.0, info->duration_)); + const int samples = std::max(1, static_cast(std::ceil((reference-odom_pos_).norm()/0.025))); + for (int i = 0; i <= samples; ++i) + if (map->getInflateOccupancy(odom_pos_+(reference-odom_pos_)*(double(i)/samples), getOdomYaw()) != 0) { + enterBlocked("tracking_correction_not_free"); + return; + } + if (last_trajectory_final_ && target_yaw_valid_ && + (odom_pos_-raw_goal_).head<2>().norm() < 2*goal_tolerance_ && + !map->rotationIsFree(odom_pos_, getOdomYaw(), target_yaw_)) { + enterBlocked("terminal_rotation_sweep_blocked"); + return; + } + } double t_2_3 = info->duration_ * 2 / 3; for (double t = t_cur; t < info->duration_; t += time_step) { - if (t_cur < t_2_3 && t >= t_2_3) // If t_cur < t_2_3, only the first 2/3 partition of the trajectory is considered valid and will get checked. + if (!map->usesRectangleFootprint() && t_cur < t_2_3 && t >= t_2_3) // Legacy circle checks the first 2/3 partition. break; Eigen::Vector3d pos = info->position_traj_.evaluateDeBoorT(t); @@ -897,12 +1066,14 @@ namespace scan_planner break; } } + if (map->usesRectangleFootprint() && exec_state_ == EXEC_TRAJ) + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::ACTIVE, "footprint_checked"); } bool SCANReplanFSM::callReboundReplan(bool flag_use_poly_init, bool flag_randomPolyTraj) { - getLocalTarget(); + if (!validateGlobalTarget() || !getLocalTarget()) return false; bool plan_success = planner_manager_->reboundReplan(start_pt_, start_vel_, start_acc_, local_target_pt_, local_target_vel_, (have_new_target_ || flag_use_poly_init), flag_randomPolyTraj); @@ -915,6 +1086,14 @@ namespace scan_planner auto info = &planner_manager_->local_data_; + if ((local_target_pt_ - raw_goal_).norm() < 1e-3 && + (info->position_traj_.evaluateDeBoorT(info->duration_) - raw_goal_).head<2>().norm() + > 0.5 * goal_tolerance_) + { + RCLCPP_WARN(node_->get_logger(), "Final spline misses original goal; rejecting it"); + return false; + } + /* publish traj */ scan_planner_msgs::msg::Bspline bspline; bspline.order = 3; @@ -939,7 +1118,11 @@ namespace scan_planner bspline.knots.push_back(knots(i)); } + completed_trajectory_id_ = -1; + last_trajectory_final_ = (local_target_pt_ - raw_goal_).norm() < 1e-3; bspline_pub_->publish(bspline); + if (!planner_manager_->grid_map_->usesRectangleFootprint()) + publishTrajectoryStatus(scan_planner_msgs::msg::TrajectoryStatus::ACTIVE, "trajectory_accepted"); visualization_->displayOptimalTraj(info->position_traj_, 0); } @@ -983,7 +1166,7 @@ namespace scan_planner return true; } - void SCANReplanFSM::getLocalTarget() + bool SCANReplanFSM::getLocalTarget() { const double max_vel = planner_manager_->pp_.max_vel_; const double max_acc = planner_manager_->pp_.max_acc_; @@ -1034,32 +1217,16 @@ namespace scan_planner bool found_free_target = false; double adjusted_t = target_t; - for (double dt = 0.0; dt <= duration; dt += t_step) + for (double t = target_t; t >= std::max(0.0, t_proj); t -= t_step) { - double t_forward = target_t + dt; - if (t_forward <= duration) + const Eigen::Vector3d pt = planner_manager_->global_data_.getPosition(t); + if ((pt - start_pt_).head<2>().norm() < 0.2) continue; + if (localEndpointIsFree(targetOccupancy(pt))) { - Eigen::Vector3d pt = planner_manager_->global_data_.getPosition(t_forward); - if (targetOccupancy(pt) == 0) - { - local_target_pt_ = pt; - adjusted_t = t_forward; - found_free_target = true; - break; - } - } - - double t_backward = target_t - dt; - if (t_backward >= std::max(0.0, t_proj)) - { - Eigen::Vector3d pt = planner_manager_->global_data_.getPosition(t_backward); - if (targetOccupancy(pt) == 0) - { - local_target_pt_ = pt; - adjusted_t = t_backward; - found_free_target = true; - break; - } + local_target_pt_ = pt; + adjusted_t = t; + found_free_target = true; + break; } } @@ -1072,7 +1239,8 @@ namespace scan_planner else { RCLCPP_WARN_THROTTLE(node_->get_logger(), *node_->get_clock(), 1000, - "Local target is in collision and no nearby free target was found"); + "Local target is not free and no in-map endpoint exists within the horizon"); + return false; } } @@ -1092,6 +1260,7 @@ namespace scan_planner local_target_vel_ = local_target_vel_.normalized() * max_vel; // cout << "AA" << endl; } + return localEndpointIsFree(targetOccupancy(local_target_pt_)); } } // namespace scan_planner diff --git a/minco_ws/src/scan/plan_manage/test/test_controller_execution.py b/minco_ws/src/scan/plan_manage/test/test_controller_execution.py new file mode 100644 index 0000000..bfc694d --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_controller_execution.py @@ -0,0 +1,138 @@ +"""Exercise the real controller process; never launch a chassis or hardware.""" +import math +import time +import unittest + +import launch +import launch_ros.actions +import launch_testing +import launch_testing.actions +import pytest +import rclpy +from geometry_msgs.msg import Point, PoseStamped, Twist +from nav_msgs.msg import Odometry +from rclpy.qos import DurabilityPolicy, QoSProfile +from scan_planner_msgs.msg import Bspline, TrajectoryStatus +from std_msgs.msg import Bool, Int64 + + +@pytest.mark.launch_test +def generate_test_description(): + controller = launch_ros.actions.Node( + package='scan_planner', executable='closed_loop_controller', + namespace='execution_test', parameters=[{ + 'require_trajectory_status': True, 'align_to_goal_yaw': True, + 'require_perception_ready': True, + 'finish_dist': .08, 'kp_pos': .5, 'max_vx': .5, + }], output='screen') + return launch.LaunchDescription([controller, launch_testing.actions.ReadyToTest()]) + + +class TestControllerExecution(unittest.TestCase): + def test_authorization_local_window_and_terminal_yaw(self): + rclpy.init() + node = rclpy.create_node('controller_test_driver', namespace='execution_test') + qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + status_pub = node.create_publisher(TrajectoryStatus, 'planning/trajectory_status', qos) + ready_pub = node.create_publisher(Bool, 'planning/perception_ready', qos) + spline_pub = node.create_publisher(Bspline, 'planning/bspline', 10) + odom_pub = node.create_publisher(Odometry, 'body_pose', 10) + goal_pub = node.create_publisher(PoseStamped, 'move_base_simple/goal', 10) + cmds, done = [], [] + node.create_subscription(Twist, 'cmd_vel', cmds.append, 10) + node.create_subscription(Int64, 'planning/trajectory_done', lambda m: done.append(m.data), 10) + odom = Odometry() + odom.pose.pose.orientation.w = 1. + perception_ready = True + + def spin(duration=.25): + until = time.monotonic() + duration + while time.monotonic() < until: + odom.header.stamp = node.get_clock().now().to_msg() + odom_pub.publish(odom) + ready_pub.publish(Bool(data=perception_ready)) + rclpy.spin_once(node, timeout_sec=.01) + + def spline(tid, x=1.): + m = Bspline(order=3, traj_id=tid) + m.knots = [-.3, -.2, -.1, 0., .1, .2, .3, .4] + m.pos_pts = [Point(x=x) for _ in range(4)] + spline_pub.publish(m) + + def status(tid, state=TrajectoryStatus.ACTIVE, final=True, goal=1.): + status_pub.publish(TrajectoryStatus(traj_id=tid, state=state, is_final=final, + goal=Point(x=goal), goal_id=1)) + + def stopped(): + assert cmds + assert all(abs(m.linear.x) + abs(m.linear.y) + abs(m.angular.z) < 1e-9 for m in cmds[-5:]) + + try: + spin(1.) # DDS discovery + spline(11) + spin() + stopped() # No authorization. + status(12) + spin() + stopped() # A different spline's authorization cannot release it. + status(11) + spin() + assert cmds[-1].linear.x > 0 + status(-1, TrajectoryStatus.HOLD) + spin() + stopped() + status(11) + spline(12) + spin() + stopped() # A new spline does not inherit old authorization. + + goal = PoseStamped() + goal.pose.orientation.z = math.sin(math.pi / 4) + goal.pose.orientation.w = math.cos(math.pi / 4) + goal_pub.publish(goal) + odom.pose.pose.position.x = 1. + status(12, final=False, goal=5.) + spin() + assert 12 in done # Intermediate window ends without terminal rotation. + stopped() + + spline(13, x=.5) + status(13, final=True, goal=1.) + odom.pose.pose.position.x = .5 + spin() + assert 13 not in done # Local endpoint is not the original task goal. + + spline(14) + status(14) + odom.pose.pose.position.x = 1. + spin() + assert abs(cmds[-1].angular.z) > .1 + assert 14 not in done # Position alone cannot finish required yaw. + odom.pose.pose.orientation.z = math.sin(math.pi / 4) + odom.pose.pose.orientation.w = math.cos(math.pi / 4) + spin() + assert 14 in done + stopped() + + # Preserve the documented all-zero quaternion behavior. + zero_goal = PoseStamped() + zero_goal.pose.orientation.w = 0. # Explicit zero: default Quaternion.w is 1. + goal_pub.publish(zero_goal) + odom.pose.pose.orientation.z = 0. + odom.pose.pose.orientation.w = 1. + spline(15) + status(15) + spin() + assert 15 in done + stopped() + + spline(16, x=2.) + status(16, goal=2.) + spin() + assert cmds[-1].linear.x > 0 + perception_ready = False + spin() + stopped() # Independent of the planner's event loop. + finally: + node.destroy_node() + rclpy.shutdown() diff --git a/minco_ws/src/scan/plan_manage/test/test_goal_execution_fsm.py b/minco_ws/src/scan/plan_manage/test/test_goal_execution_fsm.py new file mode 100644 index 0000000..f611c59 --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_goal_execution_fsm.py @@ -0,0 +1,153 @@ +"""Fake poses/clouds exercise the actual FSM, without a controller or chassis.""" +import os +import time +import unittest +import yaml + +import launch +import launch_ros.actions +import launch_testing +import launch_testing.actions +import pytest +import rclpy +from geometry_msgs.msg import PoseStamped +from nav_msgs.msg import Odometry +from rclpy.qos import DurabilityPolicy, QoSProfile +from scan_planner_msgs.msg import Bspline, TrajectoryStatus +from sensor_msgs.msg import PointCloud2 +from sensor_msgs_py.point_cloud2 import create_cloud_xyz32 +from std_msgs.msg import Bool, Header, Int64 + + +@pytest.mark.launch_test +def generate_test_description(): + config = os.path.join(os.path.dirname(__file__), '..', 'config', 'planner_vehicle.yaml') + with open(config) as stream: + params = yaml.safe_load(stream)['scan_planner_node']['ros__parameters'] + planner = launch_ros.actions.Node( + package='scan_planner', executable='scan_planner_node', name='scan_planner_node', + namespace='goal_execution_test', parameters=[params, { + 'fsm.require_perception_ready': True, 'fsm.blocked_timeout': 1.2, + 'fsm.require_controller_feedback': True, + 'fsm.blocked_retry_period': .1, + # This test jumps fake poses to local endpoints. Keep the map fixed + # so those nonphysical jumps do not test sliding-buffer behavior. + 'grid_map.map_sliding_en': False, + 'grid_map.sliding_map_size_x': 14.0, + }], output='screen') + return launch.LaunchDescription([planner, launch_testing.actions.ReadyToTest()]) + + +class TestGoalExecutionFSM(unittest.TestCase): + def test_original_goal_timeout_local_windows_and_recovery(self): + rclpy.init() + node = rclpy.create_node('fsm_test_driver', namespace='goal_execution_test') + qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + ready_pub = node.create_publisher(Bool, 'planning/perception_ready', qos) + odom_pub = node.create_publisher(Odometry, 'body_pose', 10) + sensor_pub = node.create_publisher(Odometry, 'sensor_pose', 10) + cloud_pub = node.create_publisher(PointCloud2, 'cloud', 10) + goal_pub = node.create_publisher(PoseStamped, 'move_base_simple/goal', 10) + done_pub = node.create_publisher(Int64, 'planning/trajectory_done', 10) + statuses, splines = [], {} + node.create_subscription(TrajectoryStatus, 'planning/trajectory_status', statuses.append, qos) + node.create_subscription(Bspline, 'planning/bspline', lambda m: splines.update({m.traj_id: m}), 10) + odom = Odometry() + odom.header.frame_id = 'world' + odom.pose.pose.orientation.w = 1. + ready = False + confirm_final_arrival = False + points = [[4.025, .025, .025]] + + def spin(duration=.1, until=None): + end = time.monotonic() + duration + while time.monotonic() < end: + odom.header.stamp = node.get_clock().now().to_msg() + odom_pub.publish(odom) + sensor_pub.publish(odom) + ready_pub.publish(Bool(data=ready)) + if (confirm_final_arrival and statuses and + statuses[-1].state == TrajectoryStatus.ACTIVE and statuses[-1].is_final): + # The real controller repeats current-ID feedback until + # revoked; do not manufacture a one-shot feedback race. + done_pub.publish(Int64(data=statuses[-1].traj_id)) + cloud_pub.publish(create_cloud_xyz32(Header(frame_id='world', stamp=odom.header.stamp), points)) + rclpy.spin_once(node, timeout_sec=.01) + if until is not None and until(): + return + if until is not None: + assert until(), [(s.state, s.goal.x, s.reason) for s in statuses[-10:]] + + def goal(x): + m = PoseStamped() + m.header.frame_id = 'world' + m.pose.position.x = x + m.pose.orientation.w = 1. + goal_pub.publish(m) + + try: + spin(1.) + goal(2.) + spin(3., until=lambda: statuses and statuses[-1].state == TrajectoryStatus.FAILED) + assert statuses[-1].goal.x == 2. + assert not any(s.state in (TrajectoryStatus.ACTIVE, TrajectoryStatus.SUCCEEDED) for s in statuses) + + ready = True + points = [[-4.025, 3.025, .025]] # Leave forward travel free. + spin(.3) + goal(5.) # Requires more than one local planning window. + spin(3., until=lambda: statuses[-1].state == TrajectoryStatus.ACTIVE) + active = statuses[-1] + assert active.goal.x == 5. and not active.is_final + spin(.1, until=lambda: active.traj_id in splines) + spline = splines[active.traj_id] + pts = spline.pos_pts + odom.pose.pose.position.x = (pts[-3].x + 4*pts[-2].x + pts[-1].x)/6 + odom.pose.pose.position.y = (pts[-3].y + 4*pts[-2].y + pts[-1].y)/6 + spin(.2) + done_pub.publish(Int64(data=active.traj_id)) + spin(3., until=lambda: statuses[-1].state == TrajectoryStatus.ACTIVE and statuses[-1].is_final) + final = statuses[-1] + assert final.goal.x == 5. + assert not any(s.state == TrajectoryStatus.SUCCEEDED for s in statuses) + # A local window cannot count as task completion. + spin(.2) + assert statuses[-1].state == TrajectoryStatus.ACTIVE + odom.pose.pose.position.x = 5. + odom.pose.pose.position.y = 0. + spin(.1) + confirm_final_arrival = True + spin(2., until=lambda: statuses[-1].state == TrajectoryStatus.SUCCEEDED) + confirm_final_arrival = False + assert statuses[-1].goal.x == 5. + + # A genuine occupied endpoint stays unchanged and fails explicitly. + odom.pose.pose.position.x = 0. + points = [[2.025, .025, .025]] + spin(.7) + start = len(statuses) + goal(2.) + spin(3., until=lambda: statuses[-1].state == TrajectoryStatus.FAILED) + assert statuses[-1].goal.x == 2. + assert not any(s.state == TrajectoryStatus.ACTIVE for s in statuses[start:]) + + old_goal_id = statuses[-1].goal_id + goal(2.) + spin(.3, until=lambda: statuses[-1].goal_id > old_goal_id) + recovering_id = statuses[-1].goal_id + points = [[4.025, .025, .025]] # Rays clear the former obstacle cell. + spin(2., until=lambda: statuses[-1].state == TrajectoryStatus.ACTIVE) + assert statuses[-1].goal_id == recovering_id + assert statuses[-1].goal.x == 2. # Same task recovers, without resending/shrinking. + + # The final-spline accuracy guard must accept the established + # point-test distances; this checks planning, not real tracking. + for distance in (.5, 1., 1.5, 3.): + previous_id = statuses[-1].goal_id + goal(distance) + spin(2., until=lambda: statuses[-1].goal_id > previous_id and + statuses[-1].state == TrajectoryStatus.ACTIVE) + assert statuses[-1].is_final and statuses[-1].goal.x == distance + finally: + node.destroy_node() + rclpy.shutdown() diff --git a/minco_ws/src/scan/plan_manage/test/test_goal_execution_utils.cpp b/minco_ws/src/scan/plan_manage/test/test_goal_execution_utils.cpp new file mode 100644 index 0000000..16871cc --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_goal_execution_utils.cpp @@ -0,0 +1,21 @@ +#include +#include +#include + +TEST(TaskArrival, UsesActualHorizontalPositionAndRejectsNonfinite) +{ + const Eigen::Vector3d goal(5.0, 0, -0.19); + EXPECT_FALSE(scan_planner::reachedTaskPosition({3.54, -0.02, -0.2}, goal, .08)); + EXPECT_TRUE(scan_planner::reachedTaskPosition({5.01, .02, -.5}, goal, .08)); + EXPECT_FALSE(scan_planner::reachedTaskPosition( + {std::numeric_limits::quiet_NaN(), 0, 0}, goal, .08)); +} + +TEST(TaskOccupancy, DistantIntentDoesNotAuthorizeALocalEndpoint) +{ + EXPECT_TRUE(scan_planner::globalGoalMayRemainActive(-1)); + EXPECT_FALSE(scan_planner::localEndpointIsFree(-1)); + EXPECT_FALSE(scan_planner::globalGoalMayRemainActive(1)); + EXPECT_FALSE(scan_planner::localEndpointIsFree(1)); + EXPECT_TRUE(scan_planner::localEndpointIsFree(0)); +} diff --git a/minco_ws/src/scan/plan_manage/test/test_rectangle_controller.py b/minco_ws/src/scan/plan_manage/test/test_rectangle_controller.py new file mode 100644 index 0000000..26be9ee --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_rectangle_controller.py @@ -0,0 +1,131 @@ +"""Locked-heading integration, with fresh grants; no chassis/hardware launched.""" +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 scan_planner_msgs.msg import Bspline, TrajectoryStatus +from std_msgs.msg import Bool, Int64 + + +@pytest.mark.launch_test +def generate_test_description(): + controller = launch_ros.actions.Node( + package='scan_planner', executable='closed_loop_controller', + namespace='rectangle_controller_test', parameters=[{ + 'require_trajectory_status': True, 'require_locked_heading': True, + 'require_perception_ready': True, 'align_to_goal_yaw': True, + 'allow_reverse': True, 'finish_dist': .08, 'max_vyaw': .5, + }], output='screen') + return launch.LaunchDescription([controller, launch_testing.actions.ReadyToTest()]) + + +class TestRectangleController(unittest.TestCase): + def test_heading_rotation_and_stale_grants(self): + rclpy.init() + node = rclpy.create_node('rectangle_controller_driver', namespace='rectangle_controller_test') + qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + status_pub = node.create_publisher(TrajectoryStatus, 'planning/trajectory_status', qos) + odom_pub = node.create_publisher(Odometry, 'body_pose', 10) + ready_pub = node.create_publisher(Bool, 'planning/perception_ready', qos) + spline_pub = node.create_publisher(Bspline, 'planning/bspline', 10) + cmds, done = [], [] + node.create_subscription(Twist, 'cmd_vel', cmds.append, 10) + node.create_subscription(Int64, 'planning/trajectory_done', lambda m: done.append(m.data), 10) + odom = Odometry() + odom.pose.pose.orientation.w = 1. + grant = TrajectoryStatus(goal_id=7, traj_id=21, state=TrajectoryStatus.ACTIVE, + hold_heading=True, heading=0., heading_tolerance=.035, + correction_rotation_allowed=True, goal=Point(y=1.)) + publish_grant, publish_odom = True, True + + def spin(duration=.3): + until = time.monotonic() + duration + while time.monotonic() < until: + stamp = node.get_clock().now().to_msg() + if publish_grant: + grant.header.stamp = stamp + status_pub.publish(grant) + if publish_odom: + odom.header.stamp = stamp + odom_pub.publish(odom) + ready_pub.publish(Bool(data=True)) + rclpy.spin_once(node, timeout_sec=.01) + + def stopped(): + assert len(cmds) >= 5 + assert all(abs(m.linear.x)+abs(m.linear.y)+abs(m.angular.z) < 1e-9 for m in cmds[-5:]) + + def spline(tid, x=0., y=1.): + spline_pub.publish(Bspline(order=3, traj_id=tid, + knots=[-.3, -.2, -.1, 0., .1, .2, .3, .4], + pos_pts=[Point(x=x, y=y) for _ in range(4)])) + + try: + spin(1.) + spline(21) + spin() + assert cmds[-1].linear.y > 0.1 + assert abs(cmds[-1].angular.z) < 1e-9 # 90-degree translation keeps body yaw. + publish_grant = False + spin(.4) + stopped() + publish_grant = True + grant.traj_id = 20 + spin() + stopped() + grant.traj_id = 21 + grant.hold_heading = False + spin() + stopped() + grant.hold_heading = True + publish_odom = False + spin(.4) + stopped() + publish_odom = True + odom.pose.pose.orientation.z = math.sin(.1/2) + odom.pose.pose.orientation.w = math.cos(.1/2) + grant.correction_rotation_allowed = False + spin() + stopped() # Heading drift outside budget; blocked turn cannot translate. + grant.correction_rotation_allowed = True + spin() + assert abs(cmds[-1].linear.y) < 1e-9 + assert cmds[-1].angular.z < -.05 + + odom.pose.pose.orientation.z = 0. + odom.pose.pose.orientation.w = 1. + odom.pose.pose.position.y = 1. + grant.traj_id = 22 + grant.is_final = True + grant.target_yaw_valid = True + grant.target_yaw = math.pi/2 + grant.terminal_rotation_allowed = False + spline(22) + spin() + stopped() + assert 22 not in done + grant.terminal_rotation_allowed = True + spin() + assert cmds[-1].angular.z > .1 + # Alignment must continue after leaving the held translation heading. + odom.pose.pose.orientation.z = math.sin(.6/2) + odom.pose.pose.orientation.w = math.cos(.6/2) + spin() + assert cmds[-1].angular.z > .1 + assert abs(cmds[-1].linear.y) < 1e-9 + odom.pose.pose.orientation.z = math.sin(math.pi/4) + odom.pose.pose.orientation.w = math.cos(math.pi/4) + spin() + assert 22 in done + stopped() + finally: + node.destroy_node() + rclpy.shutdown() diff --git a/minco_ws/src/scan/plan_manage/test/test_rectangle_footprint.cpp b/minco_ws/src/scan/plan_manage/test/test_rectangle_footprint.cpp new file mode 100644 index 0000000..b4e4c5d --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_rectangle_footprint.cpp @@ -0,0 +1,122 @@ +#include +#include +#include +#include +#include + +class RectangleMap : public ::testing::Test +{ +protected: + void SetUp() override + { + if (!rclcpp::ok()) { int argc = 0; rclcpp::init(argc, nullptr); } + rclcpp::NodeOptions options; + options.parameter_overrides({ + {"grid_map.rectangle_footprint", true}, {"grid_map.need_extrinsic", false}, {"grid_map.resolution", 0.05}, + {"grid_map.sliding_map_size_x", 10.0}, {"grid_map.sliding_map_size_y", 10.0}, + {"grid_map.sliding_map_size_z", 2.0}, {"grid_map.ground_height", -1.0}, + {"grid_map.skip_pixel", 2}, {"grid_map.obstacles_inflation_z_up", 0.15}, + {"grid_map.obstacles_inflation_z_down", 0.05}, {"grid_map.double_cylinder_radius", 0.62}, + {"grid_map.p_hit", 0.65}, {"grid_map.p_miss", 0.35}, {"grid_map.p_min", 0.12}, + {"grid_map.p_max", 0.97}, {"grid_map.p_occ", 0.80}}); + node = std::make_shared("rectangle_grid_test", options); + map.initMap(node.get()); + } + void lane() + { + for (int i = -45; i <= 45; ++i) { + map.setOccupied(Eigen::Vector3d(i*0.05+0.025, 0.625, 0.025)); + map.setOccupied(Eigen::Vector3d(i*0.05+0.025, -0.625, 0.025)); + } + } + std::shared_ptr node; + GridMap map; +}; + +TEST(FootprintGeometry, ClosedVoxelsAndCorners) +{ + EXPECT_TRUE(footprint::intersects(0.515, 0.0, 0, 0.49, 0.49, 0.025)); + EXPECT_FALSE(footprint::intersects(0.516, 0.0, 0, 0.49, 0.49, 0.025)); + EXPECT_TRUE(footprint::intersects(0.50, 0.50, 0, 0.49, 0.49, 0.025)); + EXPECT_FALSE(footprint::intersects(0.50, 0.50, M_PI/4, 0.49, 0.49, 0.025)); + EXPECT_NEAR(footprint::angleDifference(-M_PI+0.01, M_PI-0.01), 0.02, 1e-10); +} + +TEST_F(RectangleMap, LaneAndHeadingCacheRebuild) +{ + lane(); + const Eigen::Vector3d p(0.025, 0.025, 0.025); + EXPECT_EQ(map.getInflateOccupancy(p, M_PI/4), 0); // path tangent cannot change held body yaw + EXPECT_EQ(map.getRectangleOccupancy(p, 0), 0); + 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 + map.setFootprintHeading(M_PI/4); + EXPECT_EQ(map.getInflateOccupancy(p, 0), 1); + map.setFootprintHeading(0); + EXPECT_EQ(map.getInflateOccupancy(p, M_PI/4), 0); + EXPECT_EQ(map.getOccupancy(Eigen::Vector3d(0.025, 0.625, 0.025)), 1); + map.setOccupancy(Eigen::Vector3d(0.025, 0.625, 0.025), 0); + EXPECT_EQ(map.getOccupancy(Eigen::Vector3d(0.025, 0.625, 0.025)), 0); +} + +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.getInflateOccupancy(Eigen::Vector3d(NAN, 0, 0), 0), -1); +} + +TEST_F(RectangleMap, AsymmetricVerticalInflationAndDeletion) +{ + const Eigen::Vector3d p(0.025, 0.025, 0.025); + map.setOccupied(Eigen::Vector3d(0.025, 0.025, 0.125)); + EXPECT_EQ(map.getInflateOccupancy(p, 0), 0); + EXPECT_EQ(map.getRectangleOccupancy(p, 0), 0); + map.setOccupied(Eigen::Vector3d(0.025, 0.025, -0.125)); + EXPECT_EQ(map.getInflateOccupancy(p, 0), 1); + EXPECT_EQ(map.getRectangleOccupancy(p, 0), 1); + map.setFootprintHeading(0.2); + map.setOccupancy(Eigen::Vector3d(0.025, 0.025, -0.125), 0); + EXPECT_EQ(map.getInflateOccupancy(p, 0), 0); +} + +TEST_F(RectangleMap, CachedFreeCoversSubcellPositionsAndYawBudget) +{ + lane(); + const double tol = map.footprintYawTolerance(); + for (int iy = -14; iy <= 14; ++iy) { + const Eigen::Vector3d center(0.025, iy*0.05+0.025, 0.025); + if (map.getInflateOccupancy(center, 0) != 0) continue; + for (double dx : {-0.02499, 0.0, 0.02499}) + for (double dy : {-0.02499, 0.0, 0.02499}) + for (double yaw : {-tol, -tol/2, 0.0, tol/2, tol}) + EXPECT_EQ(map.getRectangleOccupancy(center+Eigen::Vector3d(dx,dy,0), yaw), 0); + } +} + +TEST_F(RectangleMap, SlidingReinflatesRetainedObstaclesIntoNewCells) +{ + const Eigen::Vector3d source(4.975, 4.975, 0.025); + const Eigen::Vector3d query(5.475, 5.475, 0.025); + map.setOccupied(source); + EXPECT_EQ(map.getInflateOccupancy(query, 0), -1); + auto pub = node->create_publisher("sensor_pose", 10); + nav_msgs::msg::Odometry pose; + pose.pose.pose.orientation.w = 1; + pose.pose.pose.position.x = 2; + pose.pose.pose.position.y = 2; + const auto end = std::chrono::steady_clock::now()+std::chrono::seconds(2); + while (std::chrono::steady_clock::now() < end && map.getOrigin().x() < -4) { + pub->publish(pose); + rclcpp::spin_some(node); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + ASSERT_GT(map.getOrigin().x(), -4); + EXPECT_EQ(map.getOccupancy(source), 1); + EXPECT_EQ(map.getRectangleOccupancy(query, 0), 1); + EXPECT_EQ(map.getInflateOccupancy(query, 0), 1); + map.setOccupancy(source, 0); + EXPECT_EQ(map.getInflateOccupancy(query, 0), 0); // no double-count at diagonal strip overlap +} diff --git a/minco_ws/src/scan/plan_manage/test/test_rectangle_fsm.py b/minco_ws/src/scan/plan_manage/test/test_rectangle_fsm.py new file mode 100644 index 0000000..e57471b --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_rectangle_fsm.py @@ -0,0 +1,129 @@ +"""Real planner on a synthetic 120 cm lane; no hardware or controller.""" +import math +import os +import time +import unittest +import yaml +import launch +import launch_ros.actions +import launch_testing.actions +import pytest +import rclpy +from geometry_msgs.msg import PoseStamped +from nav_msgs.msg import Odometry +from rclpy.qos import DurabilityPolicy, QoSProfile +from scan_planner_msgs.msg import Bspline, TrajectoryStatus +from sensor_msgs.msg import PointCloud2 +from sensor_msgs_py.point_cloud2 import create_cloud_xyz32 +from std_msgs.msg import Bool, Header + + +@pytest.mark.launch_test +def generate_test_description(): + with open(os.path.join(os.path.dirname(__file__), '..', 'config', 'planner_vehicle.yaml')) as f: + params = yaml.safe_load(f)['scan_planner_node']['ros__parameters'] + planner = launch_ros.actions.Node( + package='scan_planner', executable='scan_planner_node', + namespace='rectangle_fsm_test', parameters=[params, { + '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, + }], output='screen') + return launch.LaunchDescription([planner, launch_testing.actions.ReadyToTest()]) + + +class TestRectangleFSM(unittest.TestCase): + def test_lane_terminal_sweep_and_held_heading(self): + rclpy.init() + node = rclpy.create_node('rectangle_fsm_driver', namespace='rectangle_fsm_test') + qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + ready_pub = node.create_publisher(Bool, 'planning/perception_ready', qos) + odom_pub = node.create_publisher(Odometry, 'body_pose', 10) + sensor_pub = node.create_publisher(Odometry, 'sensor_pose', 10) + cloud_pub = node.create_publisher(PointCloud2, 'cloud', 10) + goal_pub = node.create_publisher(PoseStamped, 'move_base_simple/goal', 10) + statuses, splines = [], {} + node.create_subscription(TrajectoryStatus, 'planning/trajectory_status', statuses.append, qos) + node.create_subscription(Bspline, 'planning/bspline', lambda m: splines.update({m.traj_id: m}), 10) + odom = Odometry() + odom.header.frame_id = 'world' + odom.pose.pose.orientation.w = 1. + points = [[i*.05+.025, y, .025] for i in range(-30, 70) for y in (-.625, .625)] + + def spin(duration=.25, until=None): + end = time.monotonic()+duration + while time.monotonic() < end: + odom.header.stamp = node.get_clock().now().to_msg() + odom_pub.publish(odom) + sensor_pub.publish(odom) + ready_pub.publish(Bool(data=True)) + cloud_pub.publish(create_cloud_xyz32(Header(frame_id='world', stamp=odom.header.stamp), points)) + rclpy.spin_once(node, timeout_sec=.01) + if until is not None and until(): + return + if until is not None: + assert until(), [(m.state, m.reason) for m in statuses[-10:]] + + def goal(yaw=0., zero_q=False): + msg = PoseStamped() + msg.header.frame_id = 'world' + msg.pose.position.x = 1. + 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) + msg.pose.orientation.z = math.sin(yaw/2) + goal_pub.publish(msg) + + try: + spin(1.5) + goal() + spin(3., until=lambda: statuses 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. + assert active.correction_rotation_allowed + # Same-lane endpoint fits at both 0 and 90 degrees, but its corners + # sweep into the walls at intermediate angles. Refuse before driving. + old_id = active.goal_id + goal(math.pi/2) + spin(3., until=lambda: statuses[-1].goal_id > old_id and statuses[-1].state == TrajectoryStatus.FAILED) + blocked_id = statuses[-1].goal_id + assert not any(s.state == TrajectoryStatus.ACTIVE for s in statuses if s.goal_id == blocked_id) + assert statuses[-1].goal.x == 1. + # Position-only goals retain the documented zero-quaternion semantics. + goal(zero_q=True) + spin(3., until=lambda: statuses[-1].goal_id > blocked_id and statuses[-1].state == TrajectoryStatus.ACTIVE) + assert not statuses[-1].target_yaw_valid + tid = statuses[-1].traj_id + spin(.3, until=lambda: tid in splines) + spline = splines[tid] + # Fake odometry is stationary. A new task must not inherit the + # nonzero reference velocity of the cancelled first task. + a, b = spline.pos_pts[0], spline.pos_pts[2] + dt = spline.knots[4]-spline.knots[3] + assert math.hypot(b.x-a.x, b.y-a.y)/(2*dt) < .02 + held_id = statuses[-1].goal_id + # A new diagonal body heading physically cannot fit this lane. + odom.pose.pose.orientation.w = math.cos(math.pi/8) + odom.pose.pose.orientation.z = math.sin(math.pi/8) + spin(.15) + goal(zero_q=True) + spin(3., until=lambda: statuses[-1].goal_id > held_id and statuses[-1].state == TrajectoryStatus.FAILED) + assert statuses[-1].goal.x == 1. + previous_id = statuses[-1].goal_id + odom.pose.pose.orientation.w = math.cos(math.pi/4) + odom.pose.pose.orientation.z = math.sin(math.pi/4) + odom.twist.twist.linear.x = .1 # body-forward = world +y at yaw=90 degrees + spin(.2) + goal(zero_q=True) + spin(3., until=lambda: statuses[-1].goal_id > previous_id and statuses[-1].state == TrajectoryStatus.ACTIVE) + tid = statuses[-1].traj_id + spin(.3, until=lambda: tid in splines) + spline = splines[tid] + a, b = spline.pos_pts[0], spline.pos_pts[2] + dt = spline.knots[4]-spline.knots[3] + assert abs((b.x-a.x)/(2*dt)) < .02 + assert abs((b.y-a.y)/(2*dt)-.1) < .02 + finally: + node.destroy_node() + rclpy.shutdown() diff --git a/minco_ws/src/scan/plan_manage/test/test_rectangle_launch.py b/minco_ws/src/scan/plan_manage/test/test_rectangle_launch.py new file mode 100644 index 0000000..a6a4f10 --- /dev/null +++ b/minco_ws/src/scan/plan_manage/test/test_rectangle_launch.py @@ -0,0 +1,75 @@ +"""Exercise the actual vehicle planner/controller launch, with no hardware includes.""" +import importlib.util +import os +import time +import unittest +import launch +from launch.actions import IncludeLaunchDescription +from launch.launch_description_sources import PythonLaunchDescriptionSource +import launch_testing.actions +import pytest +import rclpy +from rcl_interfaces.srv import GetParameters +from std_msgs.msg import Bool + + +@pytest.mark.launch_test +def generate_test_description(): + path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'launch', 'run_vehicle.launch.py')) + vehicle = IncludeLaunchDescription(PythonLaunchDescriptionSource(path), launch_arguments={ + 'use_rectangle_footprint': 'true', 'require_perception_ready': 'true', + }.items()) + return launch.LaunchDescription([vehicle, launch_testing.actions.ReadyToTest()]) + + +class TestRectangleVehicleLaunch(unittest.TestCase): + def test_effective_mode_flags_and_measured_size(self): + rclpy.init() + node = rclpy.create_node('rectangle_launch_driver') + frozen = [] + node.create_subscription(Bool, '/planning/go2_execution_frozen', lambda m: frozen.append(m.data), 10) + try: + def parameters(name, keys): + client = node.create_client(GetParameters, name+'/get_parameters') + assert client.wait_for_service(timeout_sec=5.) + future = client.call_async(GetParameters.Request(names=keys)) + rclpy.spin_until_future_complete(node, future, timeout_sec=5.) + assert future.done() + return future.result().values + controller = parameters('/closed_loop_controller', ['require_locked_heading', 'require_trajectory_status', 'require_perception_ready']) + assert all(p.bool_value for p in controller) + planner = parameters('/scan_planner_node', ['grid_map.rectangle_footprint', 'grid_map.footprint_length', 'grid_map.footprint_width']) + assert planner[0].bool_value + assert abs(planner[1].double_value-.81) < 1e-9 + assert abs(planner[2].double_value-.80) < 1e-9 + end = time.monotonic()+2. + while time.monotonic() < end and len(frozen) < 5: + rclpy.spin_once(node, timeout_sec=.01) + assert frozen and all(frozen[-5:]), frozen[-5:] + finally: + node.destroy_node() + rclpy.shutdown() + + def test_bringup_profile_offsets_use_imu_origin(self): + path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'launch', 'vehicle_bringup.launch.py')) + spec = importlib.util.spec_from_file_location('vehicle_bringup_measurement_test', path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + g = mod._measured_rectangle_geometry() + self.assertAlmostEqual(g['length'], .81) + self.assertAlmostEqual(g['width'], .8) + self.assertAlmostEqual(g['offset_x'], -.031) + self.assertAlmostEqual(g['offset_y'], -.02329) + mod._validate_measured_extrinsic() + description = mod.generate_launch_description() + from launch.actions import DeclareLaunchArgument + for rectangle, expected in [('true', (-.031, -.02329)), ('false', (-.015, 0.))]: + context = launch.LaunchContext() + context.launch_configurations['use_rectangle_footprint'] = rectangle + context.launch_configurations['use_obstacle_cloud'] = 'true' + for action in description.entities: + if isinstance(action, DeclareLaunchArgument): + action.execute(context) + self.assertAlmostEqual(float(context.launch_configurations['body_offset_x']), expected[0]) + self.assertAlmostEqual(float(context.launch_configurations['body_offset_y']), expected[1]) + mod._validate_rectangle(context) diff --git a/minco_ws/src/scan/plan_manage/test/test_reference_path_publisher_launch.py b/minco_ws/src/scan/plan_manage/test/test_reference_path_publisher_launch.py index 3819507..354ffc4 100644 --- a/minco_ws/src/scan/plan_manage/test/test_reference_path_publisher_launch.py +++ b/minco_ws/src/scan/plan_manage/test/test_reference_path_publisher_launch.py @@ -74,7 +74,7 @@ class TestReferencePathPublisher(unittest.TestCase): Path, "initial_path", received.append, path_qos ) odom_publisher = node.create_publisher( - Odometry, "body_pose", qos_profile_sensor_data + Odometry, "/body_odom", qos_profile_sensor_data ) executor = SingleThreadedExecutor(context=self.context) executor.add_node(node) diff --git a/minco_ws/src/scan/step_blocker/launch/step_blocker.launch.py b/minco_ws/src/scan/step_blocker/launch/step_blocker.launch.py index fe0ef7a..50c2dc2 100644 --- a/minco_ws/src/scan/step_blocker/launch/step_blocker.launch.py +++ b/minco_ws/src/scan/step_blocker/launch/step_blocker.launch.py @@ -39,6 +39,10 @@ def generate_launch_description(): 'regions', default_value=_yaml_default(default_params, 'regions', ''), description='台阶矩形,世界系 "xmin,xmax,ymin,ymax[; ...]"'), + DeclareLaunchArgument( + 'blocker_input_topic', + default_value=_yaml_default(default_params, 'input_topic', '/cloud_registered'), + description='台阶封堵输入点云,独立于其他节点的 cloud_topic'), ] node = Node( @@ -48,7 +52,8 @@ def generate_launch_description(): output='screen', parameters=[ LaunchConfiguration('blocker_params_file'), - {'regions': LaunchConfiguration('regions')}, + {'regions': LaunchConfiguration('regions'), + 'input_topic': LaunchConfiguration('blocker_input_topic')}, ], )