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

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

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

同步实车尺寸及雷达安装参数,调整 Gazebo 红方默认视角,完善根目录 README、仿真使用和实车迁移说明。
This commit is contained in:
2026-11-12 16:42:07 +08:00
parent cac93cae11
commit 6f1d837b46
95 changed files with 13667 additions and 244 deletions
+1 -1
View File
@@ -3,5 +3,5 @@ project(br_sim_bringup)
find_package(ament_cmake REQUIRED)
install(DIRECTORY launch config rviz DESTINATION share/${PROJECT_NAME}
PATTERN "__pycache__" EXCLUDE)
install(PROGRAMS scripts/scan_cloud_gate.py scripts/lio_navigation_adapter.py DESTINATION lib/${PROJECT_NAME})
install(PROGRAMS scripts/scan_cloud_gate.py scripts/lio_navigation_adapter.py scripts/dual_lidar_fusion.py scripts/ramp_mission.py scripts/mission_command_mux.py DESTINATION lib/${PROJECT_NAME})
ament_package()
@@ -0,0 +1,20 @@
# Flat-ground opt-in dual-lidar perception. Upper MID360 alone estimates motion.
lio_navigation_adapter:
ros__parameters:
required_planning_topic: /sim/navigation/fused_planning_cloud
# Raw scan batching plus LIO pose bracketing can cost two 100 ms frames.
# Keep source stamps; verify the end-to-end <=0.50 s physical loss-stop.
required_planning_max_age: 0.30
scan_planner_node:
ros__parameters:
grid_map.cloud_has_ray_origins: true
dual_lidar_fusion:
ros__parameters:
use_sim_time: true
upper_position_base: [0.015, 0.0, 0.33]
lower_position_base: [0.325, 0.0, 0.044]
lower_yaw: 1.5707963267948966
# Flat-only support plane relative to the retained motion reference point.
# Preserve the 15 mm ground band without tying it to drifting world Z.
nominal_base_height: 0.15
ground_tolerance: 0.015
@@ -0,0 +1,69 @@
# Opt-in known-ramp profile. Surveyed planes are planning priors, not lidar data.
# The 6 cm band cannot certify all obstacles <=10 cm. Flat mode is unchanged.
lio_navigation_adapter:
ros__parameters:
required_planning_topic: /sim/navigation/terrain_planning_cloud
# Two scan batches plus estimated-pose bracketing cost ~0.21 s here.
# Match the flat dual source-age gate; physical loss-stop stays <=0.50 s.
required_planning_max_age: 0.3
scan_planner_node:
ros__parameters:
# Conservative first dual-terrain envelope. Keep the original 3 cm lane
# error and 4 cm physical-clearance criteria; do not relax either.
manager.max_vel: 0.15
optimization.max_vel: 0.15
closed_loop_controller:
ros__parameters:
max_vx: 0.15
max_vy: 0.15
dual_lidar_fusion:
ros__parameters:
ground_mode: known_terrain
surface_tolerance: 0.06
traversable_planes:
- -0.8
- 2.7
- 3.0
- 4.0
- -0.17057142857142857
- 0.0
- 0.46054285714285714
- -0.8
- 2.7
- -4.0
- -3.0
- -0.17057142857142857
- 0.0
- 0.46054285714285714
- -3.0
- 3.0
- -3.0
- 3.0
- 0.0
- 0.0
- 0.6
- -1.8
- -0.8
- 3.0
- 4.0
- 0.0
- 0.0
- 0.6
- -1.8
- -0.8
- -4.0
- -3.0
- 0.0
- 0.0
- 0.6
- -7.0
- 7.0
- -8.0
- 8.0
- 0.0
- 0.0
- 0.0
step_blocker:
ros__parameters:
input_topic: /sim/navigation/fused_planning_cloud
preserve_ray_metadata: true
@@ -2,8 +2,9 @@
lio_navigation_adapter:
ros__parameters:
use_sim_time: true
imu_position_base: [0.011, 0.02329, 0.25588]
lidar_position_base: [0.0, 0.0, 0.30]
# 2026-11-10 measured optical x=.015, height=.48; base reference height=.15.
imu_position_base: [0.026, 0.02329, 0.28588]
lidar_position_base: [0.015, 0.0, 0.33]
ground_cutoff_z: 0.015
scan_planner_node:
@@ -2,8 +2,8 @@
lio_navigation_adapter:
ros__parameters:
use_sim_time: true
imu_position_base: [0.011, 0.02329, 0.25588]
lidar_position_base: [0.0, 0.0, 0.30]
imu_position_base: [0.026, 0.02329, 0.28588]
lidar_position_base: [0.015, 0.0, 0.33]
ground_cutoff_z: 0.015
# Prior LIO slope max vertical error .038 m plus 2 cm allowance.
# This intentionally cannot certify obstacles <= .10 m above known ground.
@@ -6,6 +6,7 @@ from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, Opaq
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
def generate_launch_description():
@@ -23,10 +24,13 @@ def generate_launch_description():
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'robocon_robot.launch.py')),
launch_arguments={'sensor_model': 'mid360', 'lidar': 'true', 'drive': 'contact',
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}}.items()),
'cmd_timeout':LaunchConfiguration('cmd_timeout'),
'contact_max_linear':LaunchConfiguration('contact_max_linear'),
'contact_max_yaw':LaunchConfiguration('contact_max_yaw'),
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}}.items()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'mid360_sensors.launch.py')),
launch_arguments={'sensor_profile': LaunchConfiguration('sensor_profile')}.items()),
launch_arguments={k:LaunchConfiguration(k) for k in ('sensor_profile','dual_lidar')}.items()),
]
def estimator(context):
@@ -36,13 +40,20 @@ def generate_launch_description():
return [Node(package='point_lio', executable='pointlio_mapping', name='point_lio_sim',
namespace='sim/lio', output='screen',
parameters=[os.path.join(lio, 'config', 'mid360.yaml'),
LaunchConfiguration('lio_profile')],
os.path.join(own, 'config', 'point_lio_sim.yaml'),
LaunchConfiguration('lio_profile'),
{'odometry.publish_scan_end':ParameterValue(LaunchConfiguration('lio_scan_end_odom'),value_type=bool)}],
remappings=[('/cloud_registered_full', '/sim/lio/cloud_registered_full'),
('/cloud_registered_full_lidar', '/sim/lio/cloud_registered_full_lidar')])]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('cmd_timeout',default_value='0.5'),
DeclareLaunchArgument('contact_max_linear',default_value='0.5'),
DeclareLaunchArgument('contact_max_yaw',default_value='0.5'),
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('with_lio', default_value='false'),
DeclareLaunchArgument('lio_scan_end_odom', default_value='false'),
DeclareLaunchArgument('start_sim', default_value='true'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
DeclareLaunchArgument('lio_profile', default_value=os.path.join(own, 'config', 'point_lio_sim.yaml')),
@@ -0,0 +1,71 @@
"""Opt-in known north-ramp mission. Sole drive owner is mission_command_mux."""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument,IncludeLaunchDescription,OpaqueFunction
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
own=get_package_share_directory('br_sim_bringup');scan=get_package_share_directory('scan_planner')
config=lambda name:os.path.join(own,'config',name+'.yaml')
def nodes(context):
if LaunchConfiguration('dual_lidar').perform(context).lower()!='true':raise ValueError('this mission requires dual lidar')
prior=[float(LaunchConfiguration(k).perform(context)) for k in ('x','y','z','yaw')]
profile=LaunchConfiguration('profile').perform(context)
if profile not in ('standard','fast'):raise ValueError('profile must be standard or fast')
fast=profile=='fast'
defaults=(2.5,1.1,.2,2.0) if fast else (.6,.7,.2,.8)
def speed(key,default):
value=LaunchConfiguration(key).perform(context)
return default if value=='auto' else float(value)
nav_speed,ramp_speed,crest_speed,yaw_speed=[speed(k,v) for k,v in zip(('nav_speed','ramp_speed','crest_speed','yaw_speed'),defaults)]
if not .1<=nav_speed<=(2.5 if fast else .6) or not .1<=ramp_speed<=(1.1 if fast else .7) or not .03<=crest_speed<=min(.2,ramp_speed) or not .1<=yaw_speed<=(2. if fast else 1.):raise ValueError('invalid mission speed limits for selected profile')
shared=[config('scan_sim'),config('terrain_sim'),config('lio_terrain'),config('dual_lidar'),config('dual_lidar_terrain')]
return [
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','mid360_sim.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui'),'with_lio':'true','dual_lidar':'true','cmd_timeout':'0.15',
'lio_scan_end_odom':'true',
'contact_max_linear':str(max(nav_speed,ramp_speed)),'contact_max_yaw':str(yaw_speed),
'sensor_profile':LaunchConfiguration('sensor_profile'),'lio_profile':config('point_lio_terrain'),
**{k:LaunchConfiguration(k) for k in ('x','y','z','yaw')}}.items()),
Node(package='br_sim_bringup',executable='lio_navigation_adapter.py',name='lio_navigation_adapter',output='screen',
parameters=shared+[{'initial_base_pose':prior,'planning_cloud_reliable':True}]),
Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',name='dual_lidar_fusion',output='screen',parameters=shared+[{'reliable_planning_cloud':True}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=shared+[{'reliable_cloud':True}]),
Node(package='scan_planner',executable='scan_planner_node',name='scan_planner_node',output='screen',
parameters=[os.path.join(scan,'config','planner_vehicle.yaml')]+shared+[
{'fsm.navi_mode':1,'fsm.terrain_motion':False,'grid_map.footprint_margin':.09,'grid_map.cloud_reliable':True,
'manager.max_vel':nav_speed,'optimization.max_vel':nav_speed,
'grid_map.sliding_map_size_y':6.0 if fast else 3.0,'grid_map.local_update_range_y':3.0 if fast else 1.5,
'fsm.thresh_replan':2.0 if fast else 1.0,'fsm.planning_horizon':4.0 if fast else 3.5,'manager.planning_horizon':4.0 if fast else 3.5,
'manager.max_acc':3.0 if fast else .6,'optimization.max_acc':3.0 if fast else .6}],
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),('cloud','/sim/navigation/terrain_planning_cloud')]),
Node(package='scan_planner',executable='closed_loop_controller',name='closed_loop_controller',output='screen',
parameters=[os.path.join(scan,'config','controllers_vehicle.yaml')]+shared+[
{'terrain_motion':False,'align_to_goal_yaw':True,'yaw_goal_tolerance':.015 if fast else .01,'max_vx':nav_speed,'max_vy':nav_speed,
'max_vyaw':yaw_speed,'extended_yaw_limit':fast,
'kp_yaw':5.0 if fast else 1.5,'kp_pos':1.5 if fast else .5,
'state_prediction_limit':.2 if fast else 0.,'goal_braking_acceleration':2.0 if fast else 0.,
'finish_dist':.025 if fast else .015,'goal_v_floor':.01,'goal_slow_gain':3.0 if fast else 2.0}],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/mission/navigation_cmd_vel')]),
Node(package='br_sim_bringup',executable='ramp_mission.py',name='ramp_mission',output='screen',
parameters=[{'use_sim_time':True,'profile':profile,'autostart':LaunchConfiguration('autostart'),'aligned_start':LaunchConfiguration('aligned_start'),'ramp_speed':ramp_speed,'crest_speed':crest_speed}]),
Node(package='br_sim_bringup',executable='mission_command_mux.py',name='mission_command_mux',output='screen',parameters=[{'use_sim_time':True,'max_linear':max(nav_speed,ramp_speed),'nav_max_linear':nav_speed,'max_yaw':yaw_speed}]),
]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='true'),DeclareLaunchArgument('autostart',default_value='false'),
DeclareLaunchArgument('aligned_start',default_value='false'),
DeclareLaunchArgument('profile',default_value='standard'),
DeclareLaunchArgument('nav_speed',default_value='auto'),DeclareLaunchArgument('ramp_speed',default_value='auto'),
DeclareLaunchArgument('crest_speed',default_value='auto'),DeclareLaunchArgument('yaw_speed',default_value='auto'),
DeclareLaunchArgument('gui',default_value='true'),DeclareLaunchArgument('with_rviz',default_value='true'),
DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value='4.5'),
DeclareLaunchArgument('z',default_value='0.15'),DeclareLaunchArgument('yaw',default_value='0.0'),
OpaqueFunction(function=nodes),
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','rviz.launch.py')),
condition=IfCondition(LaunchConfiguration('with_rviz')),launch_arguments={'dual_lidar':'true'}.items())])
@@ -3,17 +3,22 @@ import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import SetEnvironmentVariable
from launch.substitutions import EnvironmentVariable
from launch.actions import SetEnvironmentVariable,DeclareLaunchArgument,OpaqueFunction
from launch.substitutions import EnvironmentVariable,LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
config = os.path.join(
get_package_share_directory('br_sim_bringup'), 'rviz', 'scan_lio.rviz')
def display(context):
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
selected=config.replace('scan_lio.rviz','scan_dual_lio.rviz') if dual else config
return [Node(package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d',selected],parameters=[{'use_sim_time':True}])]
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
Node(package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d', config], parameters=[{'use_sim_time': True}]),
OpaqueFunction(function=display),
])
@@ -18,13 +18,14 @@ def generate_launch_description():
os.path.join(own, 'launch', 'mid360_sim.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui'), 'with_lio': 'false',
'sensor_profile': LaunchConfiguration('sensor_profile'),
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}}.items()))
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}}.items()))
actions.append(IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(own, 'launch', 'scan_lio_navigation.launch.py')),
launch_arguments={k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}.items()))
launch_arguments={k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw', 'dual_lidar')}.items()))
return actions
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('start_sim', default_value='true'),
DeclareLaunchArgument('with_rviz', default_value='true'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
@@ -37,5 +38,6 @@ def generate_launch_description():
OpaqueFunction(function=layers),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(own, 'launch', 'rviz.launch.py')),
condition=IfCondition(LaunchConfiguration('with_rviz'))),
condition=IfCondition(LaunchConfiguration('with_rviz')),
launch_arguments={'dual_lidar':LaunchConfiguration('dual_lidar')}.items()),
])
@@ -16,7 +16,10 @@ def generate_launch_description():
def nodes(context):
pose = [float(LaunchConfiguration(k).perform(context)) for k in ('x', 'y', 'z', 'yaw')]
return [
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
overrides=[os.path.join(own,'config','dual_lidar.yaml')] if dual else []
planning='/sim/navigation/fused_planning_cloud' if dual else '/sim/navigation/planning_cloud'
actions = [
Node(package='point_lio', executable='pointlio_mapping', name='point_lio_sim',
namespace='sim/lio', output='screen',
parameters=[os.path.join(lio, 'config', 'mid360.yaml'),
@@ -25,22 +28,27 @@ def generate_launch_description():
('/cloud_registered_full_lidar', '/sim/lio/cloud_registered_full_lidar')]),
Node(package='br_sim_bringup', executable='lio_navigation_adapter.py',
name='lio_navigation_adapter', output='screen',
parameters=[profile, {'initial_base_pose': pose}]),
parameters=[profile]+overrides+[{'initial_base_pose': pose}]),
Node(package='scan_planner', executable='scan_planner_node',
name='scan_planner_node', output='screen',
parameters=[os.path.join(scan, 'config', 'planner_vehicle.yaml'), base, profile],
parameters=[os.path.join(scan, 'config', 'planner_vehicle.yaml'), base, profile]+overrides,
remappings=[('body_pose', '/sim/navigation/body_odom'),
('sensor_pose', '/sim/navigation/sensor_odom'),
('cloud', '/sim/navigation/planning_cloud')]),
('cloud', planning)]),
Node(package='scan_planner', executable='closed_loop_controller',
name='closed_loop_controller', output='screen',
parameters=[os.path.join(scan, 'config', 'controllers_vehicle.yaml'), base, profile],
remappings=[('body_pose', '/sim/navigation/body_odom'), ('cmd_vel', '/cmd_vel')]),
]
if dual:
actions.append(Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',
name='dual_lidar_fusion',output='screen',parameters=overrides))
return actions
return LaunchDescription([
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('x', default_value='-4.5'),
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.15'),
@@ -6,6 +6,8 @@ from launch.substitutions import LaunchConfiguration
def generate_launch_description():
def hosts(context):
if LaunchConfiguration('dual_lidar').perform(context).lower()!='false':
raise ValueError('dual_lidar split-process deployment has not been validated; use flat scan_lio.launch.py')
values={k:LaunchConfiguration(k).perform(context) for k in ('x','y','z','yaw','gui','sensor_profile','terrain')}
terrain=values.pop('terrain').lower()=='true'
physical_args=[k+':='+v for k,v in values.items()]
@@ -18,5 +20,5 @@ def generate_launch_description():
'scan_lio_terrain.launch.py' if terrain else 'scan_lio_navigation.launch.py']+
navigation_args,output='screen')]
return LaunchDescription([DeclareLaunchArgument(k,default_value=v) for k,v in
[('x','-4.5'),('y','4.5'),('z','0.15'),('yaw','0.0'),('gui','false'),('sensor_profile','ideal'),('terrain','false')]]+
[('dual_lidar','false'),('x','-4.5'),('y','4.5'),('z','0.15'),('yaw','0.0'),('gui','false'),('sensor_profile','ideal'),('terrain','false')]]+
[OpaqueFunction(function=hosts)])
@@ -13,25 +13,31 @@ def generate_launch_description():
base=os.path.join(own,'config','scan_sim.yaml');terrain=os.path.join(own,'config','terrain_sim.yaml')
profile=os.path.join(own,'config','lio_terrain.yaml')
def bringup(context):
dual=LaunchConfiguration('dual_lidar').perform(context).lower()=='true'
overrides=[os.path.join(own,'config','dual_lidar.yaml'),os.path.join(own,'config','dual_lidar_terrain.yaml')] if dual else []
prior=[float(LaunchConfiguration(k).perform(context)) for k in ('x','y','z','yaw')]
return [
actions=[
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(own,'launch','mid360_sim.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui'),'with_lio':'true',
'start_sim':LaunchConfiguration('start_sim'),'sensor_profile':LaunchConfiguration('sensor_profile'),
'lio_profile':os.path.join(own,'config','point_lio_terrain.yaml'),
'dual_lidar':LaunchConfiguration('dual_lidar'),
**{k:LaunchConfiguration(k) for k in ('x','y','z','yaw')}}.items()),
Node(package='br_sim_bringup',executable='lio_navigation_adapter.py',name='lio_navigation_adapter',
output='screen',parameters=[profile,{'initial_base_pose':prior}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=[terrain,profile]),
output='screen',parameters=[profile]+overrides+[{'initial_base_pose':prior}]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',output='screen',parameters=[terrain,profile]+overrides),
Node(package='scan_planner',executable='scan_planner_node',name='scan_planner_node',output='screen',
parameters=[os.path.join(scan,'config','planner_vehicle.yaml'),base,terrain,profile],
parameters=[os.path.join(scan,'config','planner_vehicle.yaml'),base,terrain,profile]+overrides,
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),
('cloud','/sim/navigation/terrain_planning_cloud')]),
Node(package='scan_planner',executable='closed_loop_controller',name='closed_loop_controller',output='screen',
parameters=[os.path.join(scan,'config','controllers_vehicle.yaml'),base,terrain,profile],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/cmd_vel')]),
]
if dual:actions.append(Node(package='br_sim_bringup',executable='dual_lidar_fusion.py',name='dual_lidar_fusion',output='screen',parameters=overrides))
return actions
return LaunchDescription([
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('start_sim',default_value='true'),DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('gui',default_value='true'),DeclareLaunchArgument('x',default_value='3.5'),
DeclareLaunchArgument('y',default_value='3.5125'),DeclareLaunchArgument('z',default_value='0.15'),
+2
View File
@@ -10,6 +10,7 @@
<exec_depend>scan_planner</exec_depend>
<exec_depend>step_blocker</exec_depend>
<exec_depend>point_lio</exec_depend>
<exec_depend>livox_ros_driver2</exec_depend>
<exec_depend>rviz2</exec_depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
@@ -18,6 +19,7 @@
<exec_depend>sensor_msgs</exec_depend>
<exec_depend>nav_msgs</exec_depend>
<exec_depend>std_msgs</exec_depend>
<exec_depend>std_srvs</exec_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>tf2_ros</exec_depend>
<exec_depend>python3-numpy</exec_depend>
@@ -0,0 +1,158 @@
Panels:
- Class: rviz_common/Displays
Name: Displays
Property Tree Widget:
Expanded:
- /Global Options1
- /MID360 Raw1
- /Registered Cloud1
- /Planning Cloud1
Splitter Ratio: 0.55
Tree Height: 700
Visualization Manager:
Class: ''
Displays:
- Class: rviz_default_plugins/Grid
Name: Ground Grid
Enabled: true
Alpha: 0.45
Cell Size: 1
Color: 160; 160; 164
Line Style:
Line Width: 0.03
Value: Lines
Normal Cell Count: 0
Offset:
X: 0
Y: 0
Z: 0
Plane: XY
Plane Cell Count: 20
Reference Frame: <Fixed Frame>
Value: true
- Class: rviz_default_plugins/TF
Name: TF
Enabled: true
Frame Timeout: 15
Frames:
All Enabled: true
Marker Scale: 0.5
Show Arrows: true
Show Axes: true
Show Names: false
Update Interval: 0
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: MID360 Raw
Enabled: true
Alpha: 0.65
Color: 0; 160; 255
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.04
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/mid360/points
Use Fixed Frame: true
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: Fused Obstacle Cloud
Enabled: true
Alpha: 1
Color: 255; 210; 75
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.045
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/navigation/fused_cloud
Use Fixed Frame: true
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: Planning Cloud
Enabled: true
Alpha: 0.9
Color: 65; 220; 105
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.045
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/navigation/fused_planning_cloud
Use Fixed Frame: true
Value: false
- Class: rviz_default_plugins/PointCloud2
Name: MID360 Lower Raw
Enabled: true
Alpha: 0.65
Color: 255; 90; 60
Color Transformer: FlatColor
Position Transformer: XYZ
Selectable: true
Size (Pixels): 3
Size (m): 0.04
Style: Flat Squares
Decay Time: 0
Topic:
Depth: 5
Durability Policy: Volatile
Filter size: 10
History Policy: Keep Last
Reliability Policy: Best Effort
Value: /sim/mid360_low/points
Use Fixed Frame: true
Value: true
Enabled: true
Global Options:
Background Color: 35; 40; 48
Fixed Frame: world
Frame Rate: 30
Name: root
Tools:
- Class: rviz_default_plugins/Interact
- Class: rviz_default_plugins/MoveCamera
- Class: rviz_default_plugins/Select
- Class: rviz_default_plugins/FocusCamera
- Class: rviz_default_plugins/Measure
Transformation:
Current:
Class: rviz_default_plugins/TF
Value: true
Views:
Current:
Class: rviz_default_plugins/Orbit
Distance: 14
Focal Point:
X: -3.5
Y: 3.5
Z: 0
Name: Current View
Pitch: 0.95
Target Frame: <Fixed Frame>
Value: Orbit (rviz_default_plugins)
Yaw: 1.57
Saved: null
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/python3
"""Deskew two raw Livox scans with estimated body poses; no truth/TF fallback.
The upper lidar alone feeds Point-LIO. Both obstacle scans retain physical ray
origins and original acquisition offsets. Missing streams revoke downstream
readiness through the existing adapter's required_planning_topic gate.
"""
from array import array
from collections import deque
import json
import math
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import qos_profile_sensor_data,QoSProfile
from livox_ros_driver2.msg import CustomMsg
from nav_msgs.msg import Odometry
from sensor_msgs.msg import PointCloud2,PointField
from std_msgs.msg import String
from lio_navigation_adapter import quaternion,rotation
class PoseGapError(ValueError):
pass
def interpolate_poses(history,times,max_gap=.10):
"""Bracket actual per-point times, SLERP orientation, never extrapolate."""
stamps=np.array([v[0] for v in history]);times=np.asarray(times)
if len(stamps)<2 or np.any(np.diff(stamps)<=0):raise ValueError('invalid pose history')
if np.min(times)<stamps[0] or np.max(times)>stamps[-1]:raise LookupError('pose coverage pending')
hi=np.clip(np.searchsorted(stamps,times,side='right'),1,len(stamps)-1);lo=hi-1
dt=stamps[hi]-stamps[lo]
if np.max(dt)>max_gap:raise PoseGapError('pose gap exceeds maximum')
weight=(times-stamps[lo])/dt;poses=np.array([v[1] for v in history]);qs=np.array([v[2] for v in history])
a,b=qs[lo],qs[hi];dot=np.sum(a*b,axis=1);b=np.where(dot[:,None]<0,-b,b);dot=np.abs(dot)
theta=np.arccos(np.clip(dot,-1,1));den=np.sin(theta);safe=np.where(den>1e-8,den,1.)
spherical=(np.sin((1-weight)*theta)[:,None]*a+np.sin(weight*theta)[:,None]*b)/safe[:,None]
linear=(1-weight[:,None])*a+weight[:,None]*b
q=np.where((den>1e-8)[:,None],spherical,linear);q/=np.linalg.norm(q,axis=1)[:,None]
return poses[lo]+weight[:,None]*(poses[hi]-poses[lo]),q
def rotate_rows(q,xyz):
return xyz+2*np.cross(q[:,:3],np.cross(q[:,:3],xyz)+q[:,3,None]*xyz)
def project_scan(xyz,offset_ns,start_ns,history,mount,mount_rotation,front_only):
"""Return world endpoints/origins, exact times, and original body-frame Z.
Body Z is measured before the estimated world transform. It lets the
explicitly flat profile classify ground without following LIO height drift.
"""
xyz=np.asarray(xyz);offset_ns=np.asarray(offset_ns,dtype=np.int64)
if xyz.ndim!=2 or xyz.shape[1]!=3 or len(xyz)!=len(offset_ns) or not np.isfinite(xyz).all():
raise ValueError('invalid point array')
if np.any(offset_ns<0) or np.any(offset_ns>=100000000) or np.any(np.diff(offset_ns)<0):
raise ValueError('invalid acquisition offsets')
body_rays=xyz@mount_rotation.T
# Front half-plane is a DIRECTION relative to the optical origin, not the
# endpoint's translated base x. At yaw=+pi/2 it is raw lidar y<=0.
selected=body_rays[:,0]>=-1e-8 if front_only else np.ones(len(xyz),dtype=bool)
body=body_rays+mount
selected&=~((np.abs(body[:,0])<=.42)&(np.abs(body[:,1])<=.42)&(body[:,2]>=-.17)&(body[:,2]<=.28))
body=body[selected];stamps=start_ns+offset_ns[selected]
if not len(body):return np.empty((0,3)),np.empty((0,3)),stamps,np.empty(0)
pos,q=interpolate_poses(history,stamps*1e-9)
origins=pos+rotate_rows(q,np.broadcast_to(mount,body.shape))
return pos+rotate_rows(q,body),origins,stamps,body[:,2].copy()
def cloud_message(xyz,origins,times,device_ids,end_ns):
"""World-frame endpoints with world-frame origins and source time metadata."""
dtype=np.dtype([(n,'<f4') for n in ('x','y','z','origin_x','origin_y','origin_z')]+
[('time_sec','<i4'),('time_nanosec','<u4'),('sensor_id','u1')])
data=np.zeros(len(xyz),dtype=dtype)
for i,n in enumerate(('x','y','z')):data[n]=xyz[:,i];data['origin_'+n]=origins[:,i]
data['time_sec']=times//1000000000;data['time_nanosec']=times%1000000000;data['sensor_id']=device_ids
msg=PointCloud2();msg.header.frame_id='world';msg.header.stamp.sec=end_ns//1000000000;msg.header.stamp.nanosec=end_ns%1000000000
msg.height=1;msg.width=len(data);msg.point_step=dtype.itemsize;msg.row_step=msg.point_step*msg.width
for name in dtype.names:
offset=dtype.fields[name][1];datatype=PointField.FLOAT32 if offset<24 else (PointField.INT32 if name=='time_sec' else PointField.UINT32 if name=='time_nanosec' else PointField.UINT8)
msg.fields.append(PointField(name=name,offset=offset,datatype=datatype,count=1))
msg.data=array('B',data.tobytes());msg.is_dense=bool(np.isfinite(xyz).all());return msg
class DualLidarFusion(Node):
def __init__(self):
super().__init__('dual_lidar_fusion')
self.mounts=[np.array(self.declare_parameter('upper_position_base',[.015,0.,.33]).value),
np.array(self.declare_parameter('lower_position_base',[.325,0.,.044]).value)]
yaw=float(self.declare_parameter('lower_yaw',math.pi/2).value)
self.base_height=float(self.declare_parameter('nominal_base_height',.15).value)
self.ground_tolerance=float(self.declare_parameter('ground_tolerance',.015).value)
self.ground_mode=self.declare_parameter('ground_mode','flat_body').value
planes=list(self.declare_parameter('traversable_planes',[0.]*7).value)
self.surface_tolerance=float(self.declare_parameter('surface_tolerance',.06).value)
if self.ground_mode not in ('flat_body','known_terrain') or len(planes)%7 or not all(math.isfinite(v) for v in planes) or not 0<self.surface_tolerance<=.06:
raise ValueError('invalid ground mode or known terrain surfaces')
self.planes=[planes[i:i+7] for i in range(0,len(planes),7) if planes[i+1]>planes[i] and planes[i+3]>planes[i+2]]
if self.ground_mode=='known_terrain' and not self.planes:raise ValueError('known terrain needs explicit surface priors')
if not (math.isfinite(self.base_height) and math.isfinite(self.ground_tolerance) and
0<self.ground_tolerance<self.base_height):raise ValueError('invalid flat-ground reference/tolerance')
self.rotations=[np.eye(3),rotation([0.,0.,math.sin(yaw/2),math.cos(yaw/2)])]
if any(m.shape!=(3,) or not np.isfinite(m).all() for m in self.mounts) or not math.isfinite(yaw):raise ValueError('invalid extrinsics')
self.history=deque();self.scans=[deque(maxlen=10),deque(maxlen=10)];self.last=[None,None]
self.fault='';self.published=0;self.dropped=0;self.last_output=None;self.last_drop=''
self.full=self.create_publisher(PointCloud2,'/sim/navigation/fused_cloud',5)
planning_qos=QoSProfile(depth=1 if self.declare_parameter('reliable_planning_cloud',False).value else 5)
self.planning=self.create_publisher(PointCloud2,'/sim/navigation/fused_planning_cloud',planning_qos)
self.status=self.create_publisher(String,'/sim/dual_lidar/status',10)
# The estimator publishes bursts. Retain its full reliable pose sequence;
# sensor-data depth 5 discards intermediate motion during scan processing.
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,100)
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda msg,i=i:self.on_scan(i,msg),qos_profile_sensor_data)
self.create_timer(.02,self.flush);self.create_timer(.5,self.report)
def now_s(self):return self.get_clock().now().nanoseconds*1e-9
def on_pose(self,m):
if self.fault:return
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('unexpected estimated body frames')
# Use the same whole-nanosecond conversion as scan acquisition
# times. sec+fraction can differ by one floating-point ULP and
# incorrectly fail an exact scan-end pose bracket.
t=(m.header.stamp.sec*1000000000+m.header.stamp.nanosec)*1e-9;p=m.pose.pose.position;q=m.pose.pose.orientation
pos=np.array([p.x,p.y,p.z]);q=quaternion([q.x,q.y,q.z,q.w])
if not np.isfinite(pos).all():raise ValueError('nonfinite estimated pose')
# Clock delivery and odometry callbacks can be ordered differently.
# Preserve near-future source samples; flush still waits for clock
# and rejects stale poses. Never rewrite an input stamp.
if not -0.2<=self.now_s()-t<=2.:return
if self.history and t<=self.history[-1][0]:
if t==self.history[-1][0]:return
raise ValueError('estimated pose time moved backwards')
self.history.append((t,pos,q))
while len(self.history)>2 and self.history[1][0]<t-2.:self.history.popleft()
except ValueError as error:self.fault=str(error)
def on_scan(self,i,m):
if self.fault:return
t=int(m.timebase)
if m.header.frame_id!=('lidar' if i==0 else 'lidar_low') or m.point_num!=len(m.points) or m.lidar_id!=i:
self.fault='unexpected raw lidar identity/count';return
if t!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fault='lidar header/timebase mismatch';return
if self.last[i] is not None and t<=self.last[i]:
self.fault='lidar time moved backwards or repeated';return
self.last[i]=t
self.scans[i].append(m)
def flush(self):
if self.fault or len(self.history)<2:return
now=self.now_s()
while self.scans[0] and self.scans[1]:
a,b=self.scans[0][0],self.scans[1][0]
if abs(int(a.timebase)-int(b.timebase))>50000000:
self.scans[int(a.timebase)>int(b.timebase)].popleft();self.dropped+=1;continue
first=min(int(a.timebase),int(b.timebase))*1e-9
end_ns=max(int(a.timebase),int(b.timebase))+99000000
if end_ns*1e-9>now:return # Clock delivery must catch up before publishing source-stamped clouds.
if now-end_ns*1e-9>.2 or first<self.history[0][0]:
self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1;continue
if end_ns*1e-9>self.history[-1][0]:return
if not 0<=now-self.history[-1][0]<=.2:return
try:
bundles=[]
for i,m in enumerate((a,b)):
xyz=np.array([[p.x,p.y,p.z] for p in m.points],dtype=float).reshape(-1,3)
offsets=np.array([p.offset_time for p in m.points],dtype=np.int64)
bundles.append(project_scan(xyz,offsets,int(m.timebase),self.history,self.mounts[i],self.rotations[i],i==1))
xyz=np.concatenate([v[0] for v in bundles]);origins=np.concatenate([v[1] for v in bundles]);times=np.concatenate([v[2] for v in bundles])
body_z=np.concatenate([v[3] for v in bundles])
ids=np.concatenate([np.full(len(v[0]),i,dtype=np.uint8) for i,v in enumerate(bundles)])
full=cloud_message(xyz,origins,times,ids,end_ns);self.full.publish(full)
# Flat-only profile: the base motion reference is nominally
# 0.15 m above the support plane. Use original optical geometry,
# not a world-Z threshold that drifts with the LIO solution.
# Raw world cloud, ray origins and acquisition times stay intact.
ground=body_z<=-self.base_height+self.ground_tolerance
if self.ground_mode=='known_terrain':
# This explicitly selected profile uses surveyed WORLD
# surfaces. A horizontal body-plane cut is wrong when the
# vehicle pitches or a ray crosses a ramp transition.
ground=np.zeros(len(xyz),dtype=bool)
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(xyz[:,0]>=x0)&(xyz[:,0]<=x1)&(xyz[:,1]>=y0)&(xyz[:,1]<=y1)&(np.abs(xyz[:,2]-(mx*xyz[:,0]+my*xyz[:,1]+b))<=self.surface_tolerance)
planning=xyz.copy();planning[ground]=np.nan
self.planning.publish(cloud_message(planning,origins,times,ids,end_ns))
self.last_output=end_ns*1e-9;self.published+=1
self.scans[0].popleft();self.scans[1].popleft()
except LookupError:return
except PoseGapError as error:
self.last_drop=str(error);self.scans[0].popleft();self.scans[1].popleft();self.dropped+=1
except ValueError as error:self.fault=str(error);return
def report(self):
self.status.publish(String(data=json.dumps(dict(fault=self.fault,published=self.published,dropped_pairs=self.dropped,
latest_output=self.last_output,last_sensor_timebase_ns=self.last,stamp=self.now_s(),
last_drop=self.last_drop,maximum_recent_pose_gap=max(np.diff([p[0] for p in self.history]),default=0.),
ground_mode=self.ground_mode,
lower_front_half_plane='vehicle directions x>=0; lower local y<=0'))))
def main():
rclpy.init();node=DualLidarFusion()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
@@ -72,8 +72,8 @@ class LioNavigationAdapter(Node):
def __init__(self):
super().__init__('lio_navigation_adapter')
self.prior=np.array(self.declare_parameter('initial_base_pose',[-4.5,4.5,.15,0.]).value)
self.imu=np.array(self.declare_parameter('imu_position_base',[.011,.02329,.25588]).value)
self.lidar=np.array(self.declare_parameter('lidar_position_base',[0.,0.,.30]).value)
self.imu=np.array(self.declare_parameter('imu_position_base',[.026,.02329,.28588]).value)
self.lidar=np.array(self.declare_parameter('lidar_position_base',[.015,0.,.33]).value)
if self.prior.shape!=(4,) or self.imu.shape!=(3,) or self.lidar.shape!=(3,) or not all(np.isfinite(a).all() for a in (self.prior,self.imu,self.lidar)):
raise ValueError('invalid prior or installation geometry')
self.cutoff=float(self.declare_parameter('ground_cutoff_z',.015).value)
@@ -89,7 +89,12 @@ class LioNavigationAdapter(Node):
raise ValueError('downstream planning maximum age must be in (0,0.3]')
self.downstream_stamp=None
self.alignment=None;self.fault='';self.window=deque();self.last=None
self.odom_stamp=None;self.cloud_stamp=None;self.cloud_count=0;self.last_status=-1.
self.odom_stamp=None;self.cloud_stamp=None;self.cloud_count=0;self.last_status=-1.;self.last_ready=None
self.pending_planning=deque()
# /clock and sensor callbacks are independently delivered. Keep a small
# bounded queue instead of dropping every source sample that arrives
# just before its clock tick. Nothing is published before source time.
self.pending_odom=deque();self.pending_cloud=deque();self.future_dropped=0
self.anchor_stamp=None
self.body_pub=self.create_publisher(Odometry,'/sim/navigation/body_odom',20)
self.sensor_pub=self.create_publisher(Odometry,'/sim/navigation/sensor_odom',20)
@@ -98,16 +103,19 @@ class LioNavigationAdapter(Node):
self.ready_pub=self.create_publisher(Bool,'/planning/perception_ready',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.status_pub=self.create_publisher(String,'/sim/navigation/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.tf=TransformBroadcaster(self);self.static_tf=StaticTransformBroadcaster(self)
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_odom,qos_profile_sensor_data)
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_odom,100)
self.create_subscription(PointCloud2,'/sim/lio/cloud_registered_full_lidar',self.on_cloud,qos_profile_sensor_data)
if self.planning_topic:
if self.planning_topic in ('/sim/navigation/cloud_registered','/sim/navigation/planning_cloud'):
raise ValueError('downstream gate must use a separate derived planning topic')
self.create_subscription(PointCloud2,self.planning_topic,self.on_planning_cloud,qos_profile_sensor_data)
cloud_qos=QoSProfile(depth=1) if self.declare_parameter('planning_cloud_reliable',False).value else qos_profile_sensor_data
self.create_subscription(PointCloud2,self.planning_topic,self.on_planning_cloud,cloud_qos)
self.create_timer(.05,self.health)
def on_planning_cloud(self,m):
if m.header.frame_id=='world' and m.width*m.height>0:
self.defer_until_clock(m,self.pending_planning,self.process_planning_cloud,'world')
def process_planning_cloud(self,m):
if m.width*m.height>0:
self.downstream_stamp=self.stamp(m)
@staticmethod
@@ -128,7 +136,30 @@ class LioNavigationAdapter(Node):
tr.transform.rotation.x,tr.transform.rotation.y,tr.transform.rotation.z,tr.transform.rotation.w=map(float,orientation)
return tr
def defer_until_clock(self,m,pending,handler,expected_frame,expected_child=None):
if self.fault:return
if m.header.frame_id!=expected_frame or (expected_child is not None and m.child_frame_id!=expected_child):
self.reject('unexpected LIO odometry frames' if expected_child else 'unexpected paired cloud frame');return
self.flush_pending()
if self.fault:return
t=self.stamp(m)
if t>self.now_s()+.2:
self.future_dropped+=1;return
if pending or t>self.now_s():
if len(pending)>=64:
self.reject('clock pending queue overflow');return
pending.append(m)
else:handler(m)
def flush_pending(self):
for pending,handler in ((self.pending_odom,self.process_odom),(self.pending_cloud,self.process_cloud),(self.pending_planning,self.process_planning_cloud)):
while pending and not self.fault and self.stamp(pending[0])<=self.now_s():
handler(pending.popleft())
def on_odom(self,m):
self.defer_until_clock(m,self.pending_odom,self.process_odom,'camera_init','body')
def process_odom(self,m):
if self.fault:return
try:
if m.header.frame_id!='camera_init' or m.child_frame_id!='body':raise ValueError('unexpected LIO odometry frames')
@@ -146,10 +177,14 @@ class LioNavigationAdapter(Node):
raise ValueError('LIO gap or pose discontinuity; restart with a known start pose')
self.last=(t,pos,q)
if self.alignment is None:
if np.linalg.norm(linear)>.02 or np.linalg.norm(angular)>.02:self.window.clear();return
self.window.append((t,pos,q))
if np.linalg.norm(angular)>.02:self.window.clear();return
self.window.append((t,pos,q,linear))
while len(self.window)>1 and t-self.window[1][0]>1.:self.window.popleft()
if len(self.window)<20 or t-self.window[0][0]<1.:return
# Pointwise EKF velocity jitters even when the physical body is
# still. Require a quiet full window, not a run of quiet samples.
# Keep the original speed, displacement and angular thresholds.
if np.linalg.norm(np.mean([s[3] for s in self.window],axis=0))>.02:return
if max(np.linalg.norm(s[1]-pos) for s in self.window)>.02:return
self.alignment=FixedAlignment(self.prior,self.imu,pos,q);self.anchor_stamp=t
self.static_tf.sendTransform([
@@ -178,6 +213,9 @@ class LioNavigationAdapter(Node):
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def on_cloud(self,m):
self.defer_until_clock(m,self.pending_cloud,self.process_cloud,'camera_init')
def process_cloud(self,m):
if self.fault or self.alignment is None:return
try:
t=self.stamp(m)
@@ -194,7 +232,10 @@ class LioNavigationAdapter(Node):
for i,v in enumerate(float_fields(m,names[:3],data)):v[:]=world[...,i]
out=copy.deepcopy(m);out.header.frame_id='world';out.data=array('B',data)
self.world_pub.publish(out)
self_hit=(np.abs(raw[...,0])<=.42)&(np.abs(raw[...,1])<=.42)&(raw[...,2]>=-.47)&(raw[...,2]<=-.20)
# Classify paired ORIGINAL optical points in the vehicle envelope.
# Base remains .15 m above ground; measured roof is .41 m high.
body_raw=raw+self.lidar
self_hit=(np.abs(body_raw[...,0])<=.42)&(np.abs(body_raw[...,1])<=.42)&(body_raw[...,2]>=-.17)&(body_raw[...,2]<=.28)
ground=world[...,2]<=self.cutoff
for x0,x1,y0,y1,mx,my,b in self.planes:
ground|=(world[...,0]>=x0)&(world[...,0]<=x1)&(world[...,1]>=y0)&(world[...,1]<=y1)&(
@@ -205,15 +246,22 @@ class LioNavigationAdapter(Node):
except (ValueError,TypeError,KeyError) as exc:self.reject(str(exc))
def health(self):
ready=not self.fault and self.alignment is not None and self.fresh(self.odom_stamp,.2) and self.fresh(self.cloud_stamp,.25)
if self.planning_topic:ready=ready and self.fresh(self.downstream_stamp,self.planning_max_age)
self.flush_pending()
# When an external planning stream is selected (dual fusion / terrain),
# that is the cloud actually consumed by navigation. The independent
# upper registered cloud remains a display output, not a second gate.
stamp,limit=(self.downstream_stamp,self.planning_max_age) if self.planning_topic else (self.cloud_stamp,.25)
ready=not self.fault and self.alignment is not None and self.fresh(self.odom_stamp,.2) and self.fresh(stamp,limit)
changed=ready!=self.last_ready;self.last_ready=ready
self.ready_pub.publish(Bool(data=bool(ready)))
if self.now_s()-self.last_status<.5:return
if self.now_s()-self.last_status<.5 and not changed:return
self.last_status=self.now_s()
status=dict(phase='fault' if self.fault else ('initializing' if self.alignment is None else ('active' if ready else 'stale')),
reason=self.fault,ready=bool(ready),stamp=self.now_s(),anchor_stamp=self.anchor_stamp,
odom_stamp=self.odom_stamp,cloud_stamp=self.cloud_stamp,cloud_count=self.cloud_count,
downstream_stamp=self.downstream_stamp,required_planning_topic=self.planning_topic,
readiness_cloud='downstream' if self.planning_topic else 'registered',readiness_cloud_age=None if stamp is None else self.now_s()-stamp,readiness_cloud_max_age=limit,
pending_odom=len(self.pending_odom),pending_cloud=len(self.pending_cloud),future_dropped=self.future_dropped,
known_start_base=self.prior.tolist(),imu_position_base=self.imu.tolist())
if self.alignment:status.update(rotation=self.alignment.R.tolist(),translation=self.alignment.t.tolist())
self.status_pub.publish(String(data=json.dumps(status)))
+99
View File
@@ -0,0 +1,99 @@
#!/usr/bin/python3
"""One /cmd_vel owner with expiring mission leases and independent health gates."""
import json,math
from collections import deque
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import Twist,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu
from std_msgs.msg import Bool,String
from lio_navigation_adapter import quaternion
def select_command(now,lease,nav,ramp,health,max_linear=.5,max_yaw=.5):
"""Pure fail-closed arbitration. Times are ROS source/receipt seconds."""
zero=(0.,0.,0.)
if lease is None or not 0<=now-lease['stamp']<=.15:return zero,'lease_stale'
if not health:return zero,'health_not_ready'
mode=lease['mode']
if mode=='STOP':return zero,'stop_lease'
source=nav if mode=='NAV' else ramp if mode=='RAMP' else None
if source is None:return zero,'source_missing'
stamp,command=source
if stamp<lease['since'] or not 0<=now-stamp<=.12:return zero,'source_stale_or_before_grant'
if not all(math.isfinite(x) for x in command):return zero,'invalid_command'
vx,vy,wz=command;scale=min(1.,max_linear/max(math.hypot(vx,vy),1e-12))
return (vx*scale,vy*scale,max(-max_yaw,min(max_yaw,wz))),'selected_'+mode.lower()
class MissionCommandMux(Node):
def __init__(self):
super().__init__('mission_command_mux');self.lease=None;self.nav=None;self.ramp=None
self.max_linear=float(self.declare_parameter('max_linear',.5).value)
self.nav_max_linear=float(self.declare_parameter('nav_max_linear',.5).value)
self.max_yaw=float(self.declare_parameter('max_yaw',.5).value)
if not 0<self.max_linear<=2.5 or not 0<self.nav_max_linear<=self.max_linear or not 0<self.max_yaw<=2.:raise ValueError('invalid mux speed limits')
self.ready=False;self.ready_stamp=None;self.odom_stamp=None;self.imu_stamp=None;self.last_now=None
self.pending_odom=deque(maxlen=100);self.pending_imu=deque(maxlen=100)
self.output=self.create_publisher(Twist,'/cmd_vel',10)
self.status=self.create_publisher(String,'/mission/mux_status',10)
self.create_subscription(String,'/mission/control_lease',self.on_lease,1)
self.create_subscription(Twist,'/mission/navigation_cmd_vel',self.on_nav,1)
self.create_subscription(TwistStamped,'/mission/ramp_cmd_vel',self.on_ramp,1)
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_odom,20)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_timer(.02,self.tick);self.last_report=-1.
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def on_odom(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('wrong frames')
q=m.pose.pose.orientation;quaternion([q.x,q.y,q.z,q.w]);p=m.pose.pose.position
if not all(math.isfinite(v) for v in (p.x,p.y,p.z)):raise ValueError('invalid position')
self.pending_odom.append(self.stamp(m))
except ValueError:self.odom_stamp=None
def on_imu(self,m):
a=m.angular_velocity;v=m.linear_acceleration
if m.header.frame_id=='mid360_imu' and all(math.isfinite(x) for x in (a.x,a.y,a.z,v.x,v.y,v.z)):self.pending_imu.append(self.stamp(m))
else:self.imu_stamp=None;self.pending_imu.clear()
def on_lease(self,m):
try:
lease=json.loads(m.data)
if lease['mode'] not in ('STOP','NAV','RAMP') or not all(math.isfinite(lease[k]) for k in ('stamp','since')) or lease['since']>lease['stamp']:raise ValueError('invalid lease')
if self.lease and lease['stamp']<self.lease['stamp']:return
if self.lease is None or (lease['mode'],lease['since'])!=(self.lease['mode'],self.lease['since']):self.nav=None;self.ramp=None
self.lease=lease
except (ValueError,KeyError,TypeError):self.lease=None
@staticmethod
def command(m):return (m.linear.x,m.linear.y,m.angular.z)
def on_nav(self,m):self.nav=(self.now(),self.command(m))
def on_ramp(self,m):
if m.header.frame_id=='lio_base_link':self.ramp=(self.stamp(m),self.command(m.twist))
def tick(self):
now=self.now()
for queue,name in ((self.pending_odom,'odom_stamp'),(self.pending_imu,'imu_stamp')):
while queue and queue[0]<=now:setattr(self,name,queue.popleft())
if self.last_now is not None and now<self.last_now:self.lease=None;self.nav=None;self.ramp=None
self.last_now=now
fresh=lambda t,age:t is not None and 0<=now-t<=age
healthy=self.ready and fresh(self.ready_stamp,.15) and fresh(self.odom_stamp,.20) and fresh(self.imu_stamp,.10)
limit=self.nav_max_linear if self.lease and self.lease['mode']=='NAV' else self.max_linear
command,reason=select_command(now,self.lease,self.nav,self.ramp,healthy,limit,self.max_yaw)
m=Twist();m.linear.x,m.linear.y,m.angular.z=command;self.output.publish(m)
if now-self.last_report>=.1:
self.last_report=now;self.status.publish(String(data=json.dumps(dict(stamp=now,reason=reason,healthy=bool(healthy),lease=self.lease,command=command,nav_source_age_s=None if self.nav is None else now-self.nav[0],ramp_source_age_s=None if self.ramp is None else now-self.ramp[0]))))
def main():
rclpy.init();node=MissionCommandMux()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.output.publish(Twist());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
+324
View File
@@ -0,0 +1,324 @@
#!/usr/bin/python3
"""Known-field staged mission: SCAN approach, estimated-state ramp control, stop.
No Gazebo truth, TF, entity services, or raw IMU orientation is used. All motion
is leased to a separate fail-closed mux; this node never publishes /cmd_vel.
"""
import json,math
from collections import deque
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from geometry_msgs.msg import PoseStamped,TwistStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Imu,PointCloud2
from std_msgs.msg import Bool,String
from std_srvs.srv import Trigger
from scan_planner_msgs.msg import TrajectoryStatus
from livox_ros_driver2.msg import CustomMsg
from lio_navigation_adapter import quaternion,rotation,float_fields
def wrap(a):return math.atan2(math.sin(a),math.cos(a))
def attitude(q):
R=rotation(q)
return math.atan2(R[1,0],R[0,0]),math.asin(np.clip(-R[2,0],-1.,1.)),math.atan2(R[2,1],R[2,2])
def ground_height(x):
x=np.asarray(x)
return np.where(x>=2.7,0.,np.where(x<=-.8,.6,(1.6119-.597*x)/3.5))
def body_command(q,speed,y_error):
R=rotation(q)
# Requested speed is along the body ground tangent, not world horizontal.
vx=-speed*math.hypot(R[0,0],R[1,0]);vy=float(np.clip(1.5*y_error,-.06,.06))
command=np.linalg.solve(R[:2,:2],np.array([vx,vy]))
yaw,_,_=attitude(q)
return float(command[0]),float(command[1]),float(np.clip(2.*wrap(math.pi-yaw),-.25,.25))
def envelope(p,q):
R=rotation(q);center=np.asarray(p)+R@np.array([0.,0.,.055])
ext=np.abs(R)@np.array([.4,.4,.205])
return center-ext,center+ext
def speed_target(x,ramp_speed,crest_speed,fast=False):
# Brake before the selected low-speed zone: standard base x=-.25,
# experimental fast base x=-.9 (front on top, rear still clearing the ramp).
# Account for command slew and .10 s reaction; slow again at the endpoint.
deceleration=2.0 if fast else .4
distance=max(0.,x+(.9 if fast else .25))
crest_limit=math.sqrt(crest_speed**2+2*deceleration*distance)
crest_limit=max(crest_speed,crest_limit-deceleration*.10)
return min(ramp_speed,crest_limit,max(.02 if fast else .012,(5. if fast else .8)*(x+1.30)))
def obstacle_count(cloud,p,q,speed,deceleration=.4):
"""Physical-observation strip with reaction+braking distance, known ground.
Does not claim detection of every <=10 cm obstacle under the existing 6 cm
terrain filter. Explicit prior points are not fed into this guard.
"""
if cloud is None:return 0
lo,hi=envelope(p,q);distance=abs(speed)*.35+speed*speed/(2*deceleration)+.05
x,y,z=cloud.T;g=ground_height(x)
mask=np.isfinite(cloud).all(axis=1)&(z>g+.06)&(z<g+.45)&(x>=lo[0]-distance)&(x<p[0]+.1)&(y>=lo[1]-.04)&(y<=hi[1]+.04)
return int(mask.sum())
class RampMission(Node):
DIRECT={'ENTRY','CLIMB','CREST','PLATFORM'}
def __init__(self):
super().__init__('ramp_mission')
self.profile=self.declare_parameter('profile','standard').value
if self.profile not in ('standard','fast'):raise ValueError('invalid mission profile')
self.fast=self.profile=='fast'
self.ramp_acceleration=2.0 if self.fast else .4
self.autostart=self.declare_parameter('autostart',False).value
self.aligned_start=self.declare_parameter('aligned_start',False).value
self.ramp_speed=float(self.declare_parameter('ramp_speed',.7).value)
self.crest_speed=float(self.declare_parameter('crest_speed',.2).value)
if not .10<=self.ramp_speed<=(1.1 if self.fast else .7) or not .03<=self.crest_speed<=.2 or self.crest_speed>self.ramp_speed:raise ValueError('invalid drive envelope')
self.state='IDLE';self.reason='waiting_start';self.requested=bool(self.autostart)
self.pose=None;self.ready=False;self.ready_stamp=None;self.imu_stamp=None;self.gyro=None
self.lower_stamp=None;self.pending_lower=deque()
self.health_failure=None
self.lower_hold=False
self.cloud=None;self.cloud_stamp=None;self.status=None;self.nav_index=0;self.wait_goal_id=0
# Standard keeps two staging stops. Fast replaces the first approach
# goal while moving, then still stops for a checked terminal pi sweep.
self.goals=[(3.7,4.8,0.),(3.7,4.,0.),(3.7,3.5125,math.pi)]
if self.fast:self.goals=[(3.7,4.8,0.),(3.7,3.5125,math.pi)]
self.goal_sent=None;self.stable_since=None;self.enter_since=None;self.flat_since=None;self.seen_slope=False
self.pitch_zero=0.;self.start_time=None;self.last_now=None;self.events=[];self.mode='STOP';self.mode_since=0.
self.command_speed=0.;self.obstacles=0;self.last_report=-1.;self.last_control=None
self.pending_pose=deque();self.pending_imu=deque();self.pending_cloud=deque()
self.pose_window=deque()
self.goal_pub=self.create_publisher(PoseStamped,'/move_base_simple/goal',10)
self.lease_pub=self.create_publisher(String,'/mission/control_lease',1)
self.direct_pub=self.create_publisher(TwistStamped,'/mission/ramp_cmd_vel',1)
self.report_pub=self.create_publisher(String,'/mission/status',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(Odometry,'/sim/navigation/body_odom',self.on_pose,50)
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
self.create_subscription(CustomMsg,'/sim/mid360_low/lidar',self.on_lower,qos_profile_sensor_data)
self.create_subscription(PointCloud2,'/sim/navigation/fused_planning_cloud',self.on_cloud,QoSProfile(depth=1))
self.create_subscription(Bool,'/planning/perception_ready',self.on_ready,QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(TrajectoryStatus,'/planning/trajectory_status',lambda m:setattr(self,'status',m),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_service(Trigger,'/ramp_mission/start',self.start)
self.create_service(Trigger,'/ramp_mission/cancel',self.cancel)
self.create_timer(.02,self.tick)
def now(self):return self.get_clock().now().nanoseconds*1e-9
@staticmethod
def stamp(m):return m.header.stamp.sec+m.header.stamp.nanosec*1e-9
def start(self,req,res):
res.success=self.state=='IDLE' and not self.requested
if res.success:self.requested=True
res.message='start requested' if res.success else 'one-shot mission already requested or terminal; no automatic restart'
return res
def cancel(self,req,res):self.fail('user_cancel');res.success=True;res.message='latched stopped';return res
def on_ready(self,m):self.ready=m.data;self.ready_stamp=self.now()
def health_snapshot(self,now):
sources={'ready_signal':(self.ready_stamp,.15),'estimated_odom':(None if self.pose is None else self.pose['stamp'],.2),
'imu':(self.imu_stamp,.1),'fused_cloud':(self.cloud_stamp,.3),'lower_scan':(self.lower_stamp,.23)}
snapshot=dict(stamp=now,ready_flag=bool(self.ready),sources={},failed_checks=[] if self.ready else ['perception_not_ready'])
for name,(stamp,limit) in sources.items():
age=None if stamp is None else now-stamp
ok=age is not None and 0<=age<=limit
snapshot['sources'][name]=dict(stamp=stamp,age_s=age,max_age_s=limit,ok=ok)
if not ok:snapshot['failed_checks'].append(name)
return snapshot
def on_pose(self,m):
if len(self.pending_pose)>=100:self.fail('pose_queue_overflow');return
self.pending_pose.append(m)
def process_pose(self,m):
try:
if m.header.frame_id!='world' or m.child_frame_id!='lio_base_link':raise ValueError('pose frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear;w=m.twist.twist.angular
q=quaternion([q.x,q.y,q.z,q.w]);p=np.array([p.x,p.y,p.z]);velocity=np.array([v.x,v.y,v.z])
if not np.isfinite(p).all() or not np.isfinite(velocity).all() or not math.isfinite(w.z):raise ValueError('nonfinite pose')
t=self.stamp(m)
if self.pose is not None and t<self.pose['stamp']:raise ValueError('pose time backwards')
self.pose=dict(stamp=t,p=p,q=q,velocity=velocity,speed=float(np.linalg.norm(velocity)),wz=w.z)
self.pose_window.append(self.pose)
while self.pose_window and self.pose_window[0]['stamp']<t-(.35 if self.fast else .5):self.pose_window.popleft()
except ValueError as exc:self.fail(str(exc))
def on_imu(self,m):
if len(self.pending_imu)>=100:self.fail('imu_queue_overflow');return
self.pending_imu.append(m)
def process_imu(self,m):
g=m.angular_velocity
if m.header.frame_id!='mid360_imu' or not all(math.isfinite(v) for v in (g.x,g.y,g.z)):self.fail('invalid_imu');return
self.imu_stamp=self.stamp(m);self.gyro=np.array([g.x,g.y,g.z])
def on_lower(self,m):
# Independent of fused-cloud latency. Use the actual last acquired
# point's source time, never receipt time or an invented scan period.
if m.header.frame_id!='lidar_low' or m.lidar_id!=1 or not m.points or m.point_num!=len(m.points) or int(m.timebase)!=m.header.stamp.sec*1000000000+m.header.stamp.nanosec:
self.fail('invalid_lower_scan');return
offset=max(p.offset_time for p in m.points)
if offset>=100000000 or len(self.pending_lower)>=20:self.fail('invalid_lower_scan_timing');return
self.pending_lower.append((int(m.timebase)+int(offset))*1e-9)
def on_cloud(self,m):
if m.header.frame_id!='world':self.fail('cloud frame');return
if len(self.pending_cloud)>=10:self.fail('cloud_queue_overflow');return
self.pending_cloud.append(m)
def process_cloud(self,m):
try:
if self.cloud_stamp is not None and self.stamp(m)<self.cloud_stamp:raise ValueError('cloud time backwards')
self.cloud=np.stack(float_fields(m,('x','y','z')),axis=-1).reshape(-1,3)
self.cloud_stamp=self.stamp(m)
except ValueError as exc:self.fail(str(exc))
def transition(self,state,reason):
if self.state==state:return
self.events.append(dict(stamp=self.now(),from_state=self.state,to=state,reason=reason))
self.get_logger().info(self.state+' -> '+state+': '+reason)
self.state=state;self.reason=reason;self.stable_since=None
def fail(self,reason):
if self.state not in ('FAILED','SUCCEEDED'):self.transition('FAILED',reason)
def set_mode(self,mode,now):
if mode!=self.mode:self.mode=mode;self.mode_since=now
self.lease_pub.publish(String(data=json.dumps(dict(stamp=now,since=self.mode_since,mode=mode))))
def stationary(self):
# LIO instantaneous velocity is noisy even while physical truth is
# stopped. Require a mature position-stable window AND mean velocity;
# never accept a single low sample or the IMU flatness alone.
samples=list(self.pose_window)
if len(samples)<(15 if self.fast else 20) or samples[-1]['stamp']-samples[0]['stamp']<(.30 if self.fast else .35):return False
pos=np.array([s['p'] for s in samples]);vel=np.array([s['velocity'] for s in samples])
return bool(np.linalg.norm(np.mean(vel,axis=0))<(.02 if self.fast else .012) and np.linalg.norm(np.ptp(pos,axis=0))<.02 and max(abs(s['wz']) for s in samples)<.02)
def send_goal(self,now):
self.wait_goal_id=self.status.goal_id if self.status else 0
m=PoseStamped();m.header.frame_id='world';m.header.stamp=self.get_clock().now().to_msg()
x,y,yaw=self.goals[self.nav_index];m.pose.position.x=x;m.pose.position.y=y;m.pose.position.z=.15
m.pose.orientation.z=math.sin(yaw/2);m.pose.orientation.w=math.cos(yaw/2)
self.goal_pub.publish(m);self.goal_sent=now
self.get_logger().info('navigation waypoint %d: %.3f %.3f yaw %.3f'%(self.nav_index,x,y,yaw))
self.events.append(dict(stamp=now,goal=[x,y,yaw],event='navigation_goal'))
def tick(self):
now=self.now();dt=.02 if self.last_now is None else now-self.last_now
for queue,handler in ((self.pending_pose,self.process_pose),(self.pending_imu,self.process_imu),(self.pending_cloud,self.process_cloud)):
while queue and self.stamp(queue[0])<=now:handler(queue.popleft())
while self.pending_lower and self.pending_lower[0]<=now:
stamp=self.pending_lower.popleft()
if self.lower_stamp is not None and stamp<=self.lower_stamp:self.fail('lower_time_backwards')
self.lower_stamp=stamp
if self.last_now is not None and dt<0:self.fail('clock_backwards')
self.last_now=now;mode='STOP';command=(0.,0.,0.)
fresh=lambda t,age:t is not None and 0<=now-t<=age
health=self.health_snapshot(now);healthy=not health['failed_checks']
lower_age=None if self.lower_stamp is None else now-self.lower_stamp
holding=bool(self.fast and self.state in self.DIRECT and healthy and lower_age is not None and lower_age>.14)
if holding!=self.lower_hold:
self.events.append(dict(stamp=now,event='lower_scan_hold',active=holding,source_age_s=lower_age))
self.get_logger().info('Lower scan temporary hold: '+str(holding))
self.lower_hold=holding
try:
if self.state=='IDLE' and self.requested:
if healthy:
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=.5:
self.start_time=now
if self.aligned_start:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,_=attitude(q)
if np.linalg.norm(p[:2]-[3.7,3.5125])>.03 or abs(wrap(yaw-math.pi))>.02 or not self.stationary():self.fail('diagnostic_start_not_aligned')
else:self.pitch_zero=pitch;self.transition('ENTRY','explicit_aligned_diagnostic_start')
else:self.transition('NAVIGATE','perception_initialized');self.send_goal(now)
else:self.stable_since=None
elif self.state not in ('IDLE','FAILED','SUCCEEDED'):
if not healthy:
self.health_failure=health
self.get_logger().error('Health stop in '+self.state+': '+json.dumps(health))
self.fail('perception_or_state_stale')
elif now-self.start_time>180:self.fail('mission_timeout')
elif self.state=='NAVIGATE':
s=self.status;x,y,_=self.goals[self.nav_index]
matched=s is not None and s.goal_id>self.wait_goal_id and abs(s.goal.x-x)<1e-5 and abs(s.goal.y-y)<1e-5 and self.stamp(s)>=self.goal_sent
if now-self.goal_sent>100:self.fail('navigation_timeout')
elif matched and s.state==s.FAILED:self.fail('navigation_failed:'+s.reason)
elif matched and s.state==s.ACTIVE and fresh(self.stamp(s),.2):
mode='NAV'
if self.fast and self.nav_index==0 and self.pose['p'][0]>=3.0 and abs(self.pose['p'][1]-4.8)<.05:
# Replace the approach target without requiring a
# stop at a geometrical staging point. The next
# SCAN trajectory still needs its own safety grant.
self.events.append(dict(stamp=now,event='approach_pass_through',position=self.pose['p'].tolist()))
self.nav_index=1;self.send_goal(now);mode='STOP'
elif matched and s.state==s.SUCCEEDED:
if self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.05 if self.fast else .25):
self.nav_index+=1
if self.nav_index<len(self.goals):self.send_goal(now);self.stable_since=None
else:
yaw,pitch,_=attitude(self.pose['q'])
if abs(wrap(yaw-math.pi))>.02 or abs(self.pose['p'][1]-3.5125)>.03:self.fail('entry_alignment_outside_tolerance')
else:self.pitch_zero=pitch;self.transition('ENTRY','navigation_handoff_stopped')
else:self.stable_since=None
elif self.state in self.DIRECT:
p,q=self.pose['p'],self.pose['q'];yaw,pitch,roll=attitude(q);lo,hi=envelope(p,q)
if abs(wrap(yaw-math.pi))>.06 or abs(roll)>.09 or abs(pitch-self.pitch_zero)>.35:self.fail('attitude_outside_corridor_envelope')
elif p[0]<3.1 and min(lo[1]-3.025,4.-hi[1])<.06:self.fail('estimated_lateral_clearance')
elif lo[0]<-1.76:self.fail('platform_end_guard')
else:
tilted=pitch-self.pitch_zero<-.07
if tilted:
if self.enter_since is None:self.enter_since=now
if now-self.enter_since>=.15:
self.seen_slope=True
if self.state=='ENTRY':self.transition('CLIMB','sustained_uphill_pitch')
else:self.enter_since=None
if not self.seen_slope and p[0]<1.8:self.fail('expected_slope_not_detected')
if self.seen_slope and p[0]<=(-.25 if not self.fast else 0.) and self.state=='CLIMB':self.transition('CREST','braking_before_crest')
flat=self.seen_slope and p[0]<-.85 and abs(pitch-self.pitch_zero)<.035 and abs(self.gyro[1])<.12
if flat:
if self.flat_since is None:self.flat_since=now
if now-self.flat_since>=.15 and self.state=='CREST':self.transition('PLATFORM','sustained_flat_after_climb')
else:self.flat_since=None
remaining=p[0]+1.30
if self.state=='PLATFORM' and remaining<=.012 and hi[0]<=-.84:
self.transition('SETTLE','whole_envelope_on_platform')
elif self.state in self.DIRECT:
control_x=p[0]
if self.fast:
# Control-only prediction, bounded by the same
# .20 s freshness gate. Source data is unchanged.
control_x+=(rotation(q)@self.pose['velocity'])[0]*max(0.,min(.2,now-self.pose['stamp']))
target=speed_target(control_x,self.ramp_speed,self.crest_speed,self.fast)
# Slew commanded longitudinal speed; final STOP and
# safety failures bypass the ramp limiter.
if self.lower_hold:self.command_speed=0.
else:self.command_speed+=float(np.clip(target-self.command_speed,-self.ramp_acceleration*max(0,dt),self.ramp_acceleration*max(0,dt)))
self.obstacles=obstacle_count(self.cloud,p,q,max(self.command_speed,self.pose['speed']),self.ramp_acceleration)
if self.obstacles:self.fail('obstacle_in_braking_corridor')
elif not self.lower_hold:command=body_command(q,self.command_speed,3.5125-p[1]);mode='RAMP'
elif self.state=='SETTLE':
p,q=self.pose['p'],self.pose['q'];lo,hi=envelope(p,q)
if lo[0]<-1.76 or hi[0]>-.84:self.fail('settling_outside_platform')
elif self.stationary():
if self.stable_since is None:self.stable_since=now
if now-self.stable_since>=(.2 if self.fast else .6):self.transition('SUCCEEDED','platform_stopped')
else:self.stable_since=None
except (ValueError,np.linalg.LinAlgError) as exc:self.fail('invalid_control:'+str(exc))
if self.state in ('FAILED','SUCCEEDED','SETTLE'):mode='STOP';command=(0.,0.,0.)
self.set_mode(mode,now)
msg=TwistStamped();msg.header.frame_id='lio_base_link';msg.header.stamp=self.get_clock().now().to_msg()
msg.twist.linear.x,msg.twist.linear.y,msg.twist.angular.z=command;self.direct_pub.publish(msg)
if now-self.last_report>=.1:
self.last_report=now
state=dict(stamp=now,state=self.state,reason=self.reason,profile=self.profile,mode=mode,healthy=bool(healthy),nav_index=self.nav_index,
elapsed_s=None if self.start_time is None else now-self.start_time,seen_slope=self.seen_slope,obstacle_returns=self.obstacles,
command=command,events=self.events)
state['source_age_s']={key:None if stamp is None else now-stamp for key,stamp in (('lower_scan',self.lower_stamp),('fused_cloud',self.cloud_stamp),('imu',self.imu_stamp))}
state['health_failure']=self.health_failure
state['waiting_lower_scan']=self.lower_hold
if self.pose is not None:state.update(estimated_position=self.pose['p'].tolist(),estimated_yaw_pitch_roll=list(attitude(self.pose['q'])),estimated_speed=self.pose['speed'])
self.report_pub.publish(String(data=json.dumps(state)))
def main():
rclpy.init();node=RampMission()
try:rclpy.spin(node)
except KeyboardInterrupt:pass
finally:
node.set_mode('STOP',node.now());node.destroy_node()
if rclpy.ok():rclpy.shutdown()
if __name__=='__main__':main()
@@ -101,10 +101,9 @@ class ScanCloudGate(Node):
surface_z=mx*xyz[0]+my*xyz[1]+b
ground |= valid & (xyz[0]>=x0)&(xyz[0]<=x1)&(xyz[1]>=y0)&(xyz[1]<=y1)&(np.abs(xyz[2]-surface_z)<.015)
# Exact same point indices and acquisition stamp; no latest-pose approximation.
# Body envelope in lidar coordinates: mount z=.30, body z=[-.15,.08].
# 2 cm numerical margin includes the fixed support wheels and roof returns.
self_hit = ((np.abs(rx) <= .42) & (np.abs(ry) <= .42) &
(rz >= -.47) & (rz <= -.20))
# Optical->base translation (.015,0,.33), with 2 cm envelope padding.
self_hit = ((np.abs(rx + .015) <= .42) & (np.abs(ry) <= .42) &
(rz + .33 >= -.17) & (rz + .33 <= .28))
for v in xyz:
v[ground | self_hit] = np.nan
out = copy.deepcopy(m)
@@ -37,19 +37,20 @@
外部包**未被修改**:哈希记录见 `sim_ws/log/p2_001/deliver/MANIFEST.txt`。
## 3. 尺寸与几何(本任务决定,R1 未改动)
## 3. 当前尺寸与几何(2026-11-10 按用户测量更新)
| 项 | 取值 | 依据 |
|---|---|---|
| 水平外包络 | **0.80 × 0.80 m** | `minco_ws/src/scan/plan_manage/config/planner_vehicle.yaml` 记录的整车最大外包络 |
| 车体箱体 | 0.80 × 0.80 × 0.16 m | 外包络即箱体 XY;高度沿用外部模型的 0.16 |
| 车体外包络 | **0.80 × 0.80 × 0.41 m** | 用户测量:含支撑轮的车体尺寸 |
| 车体箱体 | 0.80 × 0.80 × 0.34 m,局部中心 z=0.09 m | 上沿离地 0.41 m;下沿保留离地 0.07 m 的简化假设 |
| 支撑轮 | 4 × 圆柱,r = 0.10 m,宽 0.06 m | 半径沿用外部模型;**轮位重新布置** |
| 轮心位置 | x = ±0.30 m,y = ±0.30 m,z = −0.05 m | 使轮外缘与箱体边沿齐平(max\|x\| = 0.40),外包络正好 0.80 |
| `base_link` | 箱体几何中心 | 模型原点与它重合 |
| `base_link` | 水平中心、名义离地 0.15 m 的运动参考点 | 保持导航参考高度;不是箱体几何中心 |
| 名义触地面 | base_link 下方 **0.15 m** | = 轮半径 0.10 − 轮心偏移 (−0.05) |
轮心位置是**本任务的设计决定**,不是外部模型的数值(外部为 x=±0.18、y=±0.22,配 0.53×0.56 车体)。
改车体尺寸只需改 xacro 顶部四个 property。
当前尺寸和雷达安装的来源、适配与验证见 `sim_ws/docs/VEHICLE_GEOMETRY.md`。
早期沿用的 0.16 m 箱体高度已被替换;外部原始资源未修改。
## 4. 质量、质心与惯量(R1 修正为绕质心)
@@ -58,19 +59,20 @@
| 车体质量 | 5.51 kg | 沿用外部简化模型(建模假设) |
| 轮质量 | 1.2 kg × 4 | 沿用外部简化模型 |
| 总质量 M | **10.31 kg** | 5.51 + 4×1.2 |
| 质心(相对 base_link) | **(0, 0, −0.023278370514) m** | `com_z = 4·m_w·wheel_z / M`;x/y 因对称性为 0 |
| Ixx / Iyy / Izz(绕质心、轴向与 base_link 平行) | **0.757474524410 / 0.768034524410 / 1.465173333333 kg·m²** | 平行轴定理逐体累加 |
| 质心(相对 base_link) | **(0, 0, 0.024820562561) m** | `com_z = (m_b·body_z + 4·m_w·wheel_z) / M`;x/y 因对称性为 0 |
| Ixx / Iyy / Izz(绕质心、轴向与 base_link 平行) | **0.842665751374 / 0.853225751374 / 1.465173333333 kg·m²** | 平行轴定理逐体累加 |
| 非对角项 | **0** | 4 轮关于 x/y 对称,Σ m·dᵢdⱼ 相互抵消 |
**R1 改了什么**:惯性参考系从 base_link 原点移到组合质心
(`<inertial><pose>0 0 com_z 0 0 0</pose>`),张量改为绕质心。
**base_link、模型原点、collision、visual、TF 坐标一律未动**——
**当时的 base_link、模型原点、collision、visual、TF 坐标一律未动**——
`log/p2_001_r1/INERTIA_CHECK.md` 里有「修改前后几何签名一致」的核对。
> 改前那组值(ixx=iyy=0.7630613、izz=1.4651733)是**绕 base_link 原点**的,
> 不是绕质心,**不能与上表混用**。
这些仍然是**建模假设**:真车质量、重心高度、轮组、雷达位置均未确认。
质量、重心高度、轮组和安装旋转仍然是**建模假设**;车体尺寸和雷达安装平移已由用户确认。
上表惯量已按 2026-11-10 箱体尺寸重算,不是实车惯量。
P2 只验证平地运动学接口。后续 P5 接触模式与坡道实测见 `sim_ws/docs/P5_SLOPE.md`,
仍不据此评价真实轮组牵引、打滑或实车制动距离。
@@ -112,11 +114,21 @@ P2 只验证平地运动学接口。后续 P5 接触模式与坡道实测见 `si
## 8. P6 可选 MID360 兼容模式
`lidar:=true sensor_model:=mid360` 采用物理步射线和 200 Hz 原生 ImuSensor。
光学原点仍为 base_link+(0,0,0.30) m;内置 IMU 相对光学原点的偏置按官方手册
设为 (0.011,0.02329,−0.04412) m,轴向一致。车体安装仍是假设,未测量实车位置。
光学原点现为 base_link+(0.015,0,0.330) m,名义离地 0.48 m,来自用户测量;
内置 IMU 相对光学原点的偏置按既有手册约定为 (0.011,0.02329,−0.04412) m。
因此 base_link→IMU=(0.026,0.02329,0.28588) m,各轴平行仍为安装旋转假设。
采用非重复近似方向序列,不声称复现厂家光学轨迹;默认 ideal 无注入噪声,无材质反射率模型。
可选 mild/stress 在物理观测后增加径向白噪声、丢点及 IMU 白噪声/固定偏置;
参数来自本项目工程压力配置,不是厂家规格或实车标定,时间字段保持真实采样时刻。
射线在每个真实 1 ms 物理步求交、每 100 ms 打包,时间字段没有人为细分到物理步之内。
复用仓库原 Livox 消息定义,不运行硬件驱动;MID360 模式停用原瞬时点云适配器。
默认 generic 模式保持原 P3 入口,详细语义与对照证据见 `sim_ws/docs/P6_LOCALIZATION.md`。
## 9. 2026-11-10 可选双雷达补盲
`dual_lidar:=true` 添加第二个同类物理射线插件实例,位置 (0.325,0,0.044) m、yaw=+π/2。
设备话题与 frame 分开;上雷达/IMU 与原 Point-LIO 接口保持不变,下雷达本轮不接 IMU。
新增位置与旋转、该高度前方无遮挡来自用户确认;前部开放的顶板/底板/后挡板为几何代理,
厚度与梁位没有实车测量依据。双雷达支撑轮代理 X=±0.20 m,位于新光心前方通视平面之后;
原单雷达仍为 X=±0.30 m。质量分布仍用箱体加轮子近似、按轮位重算惯量,不能评价真实铝管车架物理。
单雷达模式保留原实心箱体,外部原始模型未修改。详见 `sim_ws/docs/DUAL_MID360.md`。
@@ -1,7 +1,7 @@
"""Run MID360 and IMU simulation on an already spawned robot."""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration, EnvironmentVariable
from launch.substitutions import LaunchConfiguration, EnvironmentVariable, PythonExpression
from launch_ros.actions import Node
@@ -9,8 +9,9 @@ def generate_launch_description():
return LaunchDescription([
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value='77')),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
Node(package='r2027_robot_description', executable='mid360_control.py',
name='mid360_control', output='screen',
arguments=[LaunchConfiguration('sensor_profile')]),
arguments=[LaunchConfiguration('sensor_profile'), PythonExpression(["'--dual' if '",LaunchConfiguration('dual_lidar'),"'.lower() == 'true' else '--single'"])]),
])
@@ -20,6 +20,7 @@ from launch.events import Shutdown
from launch.conditions import IfCondition
from launch.substitutions import LaunchConfiguration, PythonExpression, EnvironmentVariable
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
# 端口可用环境变量 BR_SIM_MASTER_PORT 覆盖(默认 11355),须与 Gazebo 场地入口一致。
MASTER_PORT = int(os.environ.get('BR_SIM_MASTER_PORT', '11355'))
@@ -46,6 +47,9 @@ def generate_launch_description():
sensor_model = LaunchConfiguration('sensor_model').perform(context)
if sensor_model not in ('generic', 'mid360'):
raise ValueError('sensor_model must be generic or mid360')
dual = LaunchConfiguration('dual_lidar').perform(context).lower()
if dual not in ('true', 'false') or (dual=='true' and (sensor_model!='mid360' or LaunchConfiguration('lidar').perform(context).lower()!='true')):
raise ValueError('dual_lidar requires lidar=true and sensor_model=mid360')
profile_name=LaunchConfiguration('sensor_profile').perform(context)
with open(os.path.join(robot_share,'config','sensor_profiles.yaml'),encoding='utf-8') as stream:
profiles=yaml.safe_load(stream)
@@ -63,9 +67,12 @@ def generate_launch_description():
noise={k:str(profile[k]) for k in ('range_stddev','dropout','accel_stddev','gyro_stddev')}
noise.update({k:' '.join(map(str,profile[k])) for k in ('accel_bias','gyro_bias')})
noise['noise_seed']=str(profile['seed'])
limits={k:float(LaunchConfiguration(k).perform(context)) for k in ('contact_max_linear','contact_max_yaw')}
if not all(math.isfinite(v) and 0<v<=limit for v,limit in zip(limits.values(),(2.5,2.))):
raise ValueError('invalid contact actuator speed limits')
model_xml = xacro.process_file(sdf_xacro, mappings={
'lidar': LaunchConfiguration('lidar').perform(context), 'drive': drive,
'sensor_model': sensor_model,**noise}).toxml()
'sensor_model': sensor_model,'dual_lidar':dual,**noise,**{k:str(v) for k,v in limits.items()}}).toxml()
fd, path = tempfile.mkstemp(prefix='r2027_omni_', suffix='.sdf')
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
stream.write(model_xml)
@@ -80,10 +87,14 @@ def generate_launch_description():
model_path_parts.append(os.environ['GAZEBO_MODEL_PATH'])
declared_args = [
DeclareLaunchArgument('dual_lidar',default_value='false'),
DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('ros_domain_id',default_value=EnvironmentVariable('ROS_DOMAIN_ID',default_value='77')),
DeclareLaunchArgument('ros_localhost_only',default_value=EnvironmentVariable('ROS_LOCALHOST_ONLY',default_value='1')),
DeclareLaunchArgument('drive', default_value='planar'),
DeclareLaunchArgument('cmd_timeout', default_value='0.5'),
DeclareLaunchArgument('contact_max_linear', default_value='0.5'),
DeclareLaunchArgument('contact_max_yaw', default_value='0.5'),
DeclareLaunchArgument('sensor_model', default_value='mid360'),
DeclareLaunchArgument('lidar', default_value='true',
description='Enable generic CPU 3D lidar and truth data adapter'),
@@ -150,7 +161,7 @@ def generate_launch_description():
parameters=[{'use_sim_time': True,
'input_topic': '/cmd_vel',
'output_topic': '/sim/cmd_vel',
'timeout': 0.5,
'timeout': ParameterValue(LaunchConfiguration('cmd_timeout'),value_type=float),
'publish_rate': 100.0}],
)
@@ -159,7 +170,7 @@ def generate_launch_description():
name='base_to_lidar', condition=IfCondition(LaunchConfiguration('lidar')),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id', 'base_link', '--child-frame-id', 'lidar',
'--x', '0', '--y', '0', '--z', '0.30',
'--x', '0.015', '--y', '0', '--z', '0.33',
'--roll', '0', '--pitch', '0', '--yaw', '0'])
adapter = Node(
package='r2027_robot_description', executable='sim_data_adapter.py',
@@ -175,13 +186,21 @@ def generate_launch_description():
LaunchConfiguration('sensor_model'), "' == 'mid360'"])),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id','base_link','--child-frame-id','mid360_imu',
'--x','0.011','--y','0.02329','--z','0.25588',
'--x','0.026','--y','0.02329','--z','0.28588',
'--roll','0','--pitch','0','--yaw','0'])
low_tf = Node(
package='tf2_ros', executable='static_transform_publisher', name='base_to_lidar_low',
condition=IfCondition(LaunchConfiguration('dual_lidar')),
parameters=[{'use_sim_time': True}],
arguments=['--frame-id','base_link','--child-frame-id','lidar_low',
'--x','0.325','--y','0','--z','0.044',
'--roll','0','--pitch','0','--yaw','1.5707963267948966'])
return LaunchDescription(
declared_args + env_actions
+ [OpaqueFunction(function=expand_model), spawn,
RegisterEventHandler(OnProcessExit(target_action=spawn,
on_exit=lambda event, context: [EmitEvent(event=Shutdown(reason='robot spawn failed'))]
if event.returncode != 0 else [])),
world_to_odom, cmd_timeout, lidar_tf, adapter, imu_tf])
world_to_odom, cmd_timeout, lidar_tf, adapter, imu_tf, low_tf])
@@ -24,15 +24,18 @@ def main():
if profile not in ('ideal', 'mild', 'stress'):
print('sensor_profile must be ideal, mild or stress', file=sys.stderr)
return 2
dual = '--dual' in sys.argv[2:]
rclpy.init(signal_handler_options=SignalHandlerOptions.NO)
node = rclpy.create_node('mid360_control')
publisher = node.create_publisher(Empty, '/sim/mid360/heartbeat', 10)
devices = [('/sim/mid360', ('lidar','imu'))]
if dual:devices.append(('/sim/mid360_low', ('lidar',)))
publishers = [node.create_publisher(Empty, prefix+'/heartbeat', 10) for prefix,_ in devices]
try:
for component in ('lidar', 'imu'):
invoke(node, f'/sim/mid360/{component}/profile/{profile}')
for prefix,components in devices:
for component in components:invoke(node, f'{prefix}/{component}/profile/{profile}')
node.get_logger().info(f'MID360 与 IMU 已配置为 {profile}')
while rclpy.ok():
publisher.publish(Empty())
for publisher in publishers:publisher.publish(Empty())
rclpy.spin_once(node, timeout_sec=0.2)
except KeyboardInterrupt:
pass
@@ -40,11 +43,10 @@ def main():
node.get_logger().error(str(exc))
return 1
finally:
for component in ('lidar', 'imu'):
try:
invoke(node, f'/sim/mid360/{component}/disable', wait=0.2)
except BaseException:
pass
for prefix,components in devices:
for component in components:
try:invoke(node, f'{prefix}/{component}/disable', wait=0.2)
except BaseException:pass
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
@@ -3,7 +3,7 @@
The instantaneous lidar cloud is transformed with TF at its acquisition stamp.
Pose is in world; Odometry twist stays in the stated child frame. The virtual
lidar's 0.30 m mount is shared with the SDF and static TF in the robot launch.
lidar's measured mount is shared with the SDF and static TF in the robot launch.
"""
from array import array
from collections import deque
@@ -61,7 +61,7 @@ class SimDataAdapter(Node):
self.pending_cloud.append, qos_profile_sensor_data)
self.create_subscription(Odometry, '/odom', self.pending_odom.append, 50)
self.create_timer(0.02, self.flush)
self.mount = np.array([0., 0., .30])
self.mount = np.array([.015, 0., .33])
self.clouds = 0
self.odoms = 0
@@ -12,11 +12,35 @@ from geometry_msgs.msg import Pose
def call(node, client, request, timeout=15.0):
future = client.call_async(request)
rclpy.spin_until_future_complete(node, future, timeout_sec=timeout)
if not future.done() or future.exception():
raise RuntimeError(f'{client.srv_name} did not respond within {timeout:g} s')
if not future.done():
client.remove_pending_request(future)
future.cancel()
raise TimeoutError(f'{client.srv_name} did not respond within {timeout:g} s')
if future.exception():
raise RuntimeError(f'{client.srv_name} failed: {future.exception()}')
return future.result()
def query_existing_entity(node, client, request, timeout=15.0):
"""Retry only the idempotent presence query within the original deadline.
Gazebo can receive the first request before DDS discovers the response
reader. A lost response must not be interpreted as 'entity absent'. Never
apply this retry to SpawnEntity, whose side effect may already have occurred.
"""
deadline = time.monotonic() + timeout
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(f'{client.srv_name} presence query exceeded {timeout:g} s')
try:
return call(node, client, request, min(3.0, remaining))
except TimeoutError:
if time.monotonic() >= deadline:
raise
node.get_logger().warning('实体存在性查询响应超时,重试只读查询;尚未发送生成请求')
def main():
path, entity, x, y, z, yaw = sys.argv[1:7]
rclpy.init()
@@ -28,7 +52,7 @@ def main():
raise RuntimeError('场地服务未就绪;先启动 robocon_gazebo.launch.py(robocon_robot.world)')
query = GetEntityState.Request()
query.name = entity
if call(node, state, query).success:
if query_existing_entity(node, state, query).success:
raise RuntimeError(f'机器人实体 {entity} 已存在;请勿重复启动机器人入口')
request = SpawnEntity.Request()
request.name = entity
@@ -13,19 +13,22 @@
注意:那只解释了「当时观察到转向只有指令的 0.386 倍」这一现象,**内部机理尚未完全定位**,
不能推广成「独立轮 link 必然如此」。
几何(R1 未改动):
- 水平外包络 0.80 × 0.80 m(含四个支撑轮),与 planner_vehicle.yaml 一致;
- 车体箱体 0.80 × 0.80 × 0.16 m,mass 5.51 kg(建模假设);
- 四个圆柱支撑轮 r=0.10 m、宽 0.06 m、mass 1.2 kg,轮心相对车体中心 z=-0.05 m;
- base_link 位于箱体几何中心,模型原点与它重合,名义触地面在 base_link 下方 0.15 m。
2026-11-10 用户测量:外包络 0.80 × 0.80 × 0.41 m;雷达光心前移 0.015 m、离地 0.48 m。
- 保留 base_link 为水平中心、名义离地 0.15 m 的运动参考点,不再称箱体几何中心;
- 箱体下沿保留旧模型离地 0.07 m 的假设,上沿为测量总高 0.41 m;质量仍是建模假设;
- 四个圆柱支撑轮 r=0.10 m、宽 0.06 m、mass 1.2 kg,轮心相对运动参考点 z=-0.05 m;
- 模型原点与 base_link 重合,名义触地面在 base_link 下方 0.15 m。
惯量(R1 修正):惯性参考系移到**组合质心**(z = com_z),张量绕质心、轴向与 base_link 平行。
只改惯性参考系与张量;base_link、模型原点、collision、visual 和 TF 坐标一律不移动。
按当前简化几何重算惯量;不是实车质量、质心或惯量的测量。
-->
<sdf version="1.6" xmlns:xacro="http://www.ros.org/wiki/xacro">
<xacro:arg name="lidar" default="false"/>
<xacro:arg name="drive" default="planar"/>
<xacro:arg name="contact_max_linear" default="0.5"/>
<xacro:arg name="contact_max_yaw" default="0.5"/>
<xacro:arg name="sensor_model" default="generic"/>
<xacro:arg name="dual_lidar" default="false"/>
<xacro:arg name="range_stddev" default="0"/>
<xacro:arg name="dropout" default="0"/>
<xacro:arg name="accel_stddev" default="0"/>
@@ -35,14 +38,27 @@
<xacro:arg name="noise_seed" default="2027"/>
<xacro:property name="body_length" value="0.80"/>
<xacro:property name="body_width" value="0.80"/>
<xacro:property name="body_height" value="0.16"/>
<xacro:property name="base_height" value="0.15"/>
<xacro:property name="vehicle_height" value="0.41"/>
<xacro:property name="body_bottom_height" value="0.07"/>
<xacro:property name="body_height" value="${vehicle_height - body_bottom_height}"/>
<xacro:property name="body_z" value="${(vehicle_height + body_bottom_height)/2 - base_height}"/>
<xacro:property name="lidar_x" value="0.015"/>
<xacro:property name="lidar_y" value="0.0"/>
<xacro:property name="lidar_z" value="${0.48 - base_height}"/>
<xacro:property name="body_mass" value="5.51"/>
<xacro:property name="wheel_mass" value="1.2"/>
<xacro:property name="wheel_radius" value="0.10"/>
<xacro:property name="wheel_width" value="0.06"/>
<xacro:property name="wheel_x" value="0.30"/>
<!-- In dual mode keep unmeasured support proxies behind the confirmed
clear optical plane x=.325; do not fabricate laser transparency.
Historical x=.30 plus radius=.10 hid the near edge of low obstacles
during sideways approaches. x=.20 keeps max wheel x=.30 behind the
optical plane. This is a visibility proxy, not measured wheel placement.
Regression: tools/test_dual_acceptance.py. Keep the .80 m footprint. -->
<xacro:property name="wheel_x" value="${0.20 if '$(arg dual_lidar)'.lower() == 'true' else 0.30}"/>
<xacro:property name="wheel_y" value="0.30"/>
<xacro:property name="wheel_z" value="-0.05"/>
@@ -60,13 +76,13 @@
value="${wheel_mass * (3.0*wheel_radius*wheel_radius + wheel_width*wheel_width) / 12.0}"/>
<!-- 组合刚体:总质量、质心、绕质心的惯量(全部由参数算,不写近似常数)。
车体箱体 COM 在 base_link 原点 (0,0,0);四个轮子 COM 在 (±wheel_x, ±wheel_y, wheel_z),
关于 x/y 对称 ⇒ 质心只在 z 上偏移:com_z = 4·m_w·wheel_z / M。
箱体 COM 在 (0,0,body_z);四个轮子 COM 在 (±wheel_x, ±wheel_y, wheel_z),
关于 x/y 对称 ⇒ 质心只在 z 上偏移。
绕质心用平行轴:自身 COM 惯量 + m·|d|²,d 为自身 COM 指向系统质心的向量。
z 向偏移只进 Ixx/Iyy(含 dz²),不进 Izz(只含 dx²+dy²)。 -->
<xacro:property name="total_mass" value="${body_mass + 4.0*wheel_mass}"/>
<xacro:property name="com_z" value="${4.0*wheel_mass*wheel_z / total_mass}"/>
<xacro:property name="dz_body" value="${0.0 - com_z}"/>
<xacro:property name="com_z" value="${(body_mass*body_z + 4.0*wheel_mass*wheel_z) / total_mass}"/>
<xacro:property name="dz_body" value="${body_z - com_z}"/>
<xacro:property name="dz_wheel" value="${wheel_z - com_z}"/>
<xacro:property name="tot_ixx"
value="${body_ixx + body_mass*dz_body*dz_body + 4.0*(wheel_i_perp + wheel_mass*(wheel_y*wheel_y + dz_wheel*dz_wheel))}"/>
@@ -129,7 +145,7 @@
<static>false</static>
<allow_auto_disable>false</allow_auto_disable>
<!-- ===== 车体:base_link 即箱体几何中心,模型原点与它重合 ===== -->
<!-- base_link 保留运动参考点;箱体上移/增高以匹配实测外包络。 -->
<link name="base_link">
<pose>0 0 0 0 0 0</pose>
<inertial>
@@ -145,14 +161,15 @@
<izz>${tot_izz}</izz>
</inertia>
</inertial>
<xacro:unless value="$(arg dual_lidar)">
<collision name="body_collision">
<pose>0 0 0 0 0 0</pose>
<pose>0 0 ${body_z} 0 0 0</pose>
<geometry>
<box><size>${body_length} ${body_width} ${body_height}</size></box>
</geometry>
</collision>
<visual name="body_visual">
<pose>0 0 0 0 0 0</pose>
<pose>0 0 ${body_z} 0 0 0</pose>
<geometry>
<box><size>${body_length} ${body_width} ${body_height}</size></box>
</geometry>
@@ -163,16 +180,34 @@
</material>
</visual>
</xacro:unless>
<xacro:if value="$(arg dual_lidar)">
<!-- Open front is confirmed by the user; slab/rear dimensions are
explicit unmeasured proxies, not reconstructed aluminium tubes.
Keep the old inertial box approximation; no measured frame mass. -->
<xacro:macro name="frame_part" params="name xyz size">
<collision name="${name}_collision"><pose>${xyz} 0 0 0</pose>
<geometry><box><size>${size}</size></box></geometry></collision>
<visual name="${name}_visual"><pose>${xyz} 0 0 0</pose>
<geometry><box><size>${size}</size></box></geometry>
<material><ambient>0.35 0.4 0.5 1</ambient><diffuse>0.35 0.4 0.5 1</diffuse></material>
</visual>
</xacro:macro>
<xacro:frame_part name="frame_floor" xyz="0 0 -0.065" size="0.8 0.8 0.03"/>
<xacro:frame_part name="frame_roof" xyz="0 0 0.25" size="0.8 0.8 0.02"/>
<xacro:frame_part name="frame_rear" xyz="-0.39 0 0.095" size="0.02 0.8 0.29"/>
</xacro:if>
<xacro:omni_wheel name="front_left" x_sign="1" y_sign="1"/>
<xacro:omni_wheel name="front_right" x_sign="1" y_sign="-1"/>
<xacro:omni_wheel name="rear_left" x_sign="-1" y_sign="1"/>
<xacro:omni_wheel name="rear_right" x_sign="-1" y_sign="-1"/>
<!-- Generic instantaneous 3D ray sensor; this is not a MID360 timing model.
Mount is a simulation assumption: 0.30 m above base_link, axes aligned. -->
Mount follows measured optical position; axis alignment remains an assumption. -->
<xacro:if value="$(arg lidar)">
<xacro:if value="${'$(arg sensor_model)' == 'generic'}">
<sensor name="lidar" type="ray">
<pose>0 0 0.30 0 0 0</pose>
<pose>${lidar_x} ${lidar_y} ${lidar_z} 0 0 0</pose>
<always_on>true</always_on>
<visualize>false</visualize>
<update_rate>10</update_rate>
@@ -197,7 +232,7 @@
<xacro:if value="${'$(arg sensor_model)' == 'mid360'}">
<!-- Official manual: IMU is (11,23.29,-44.12) mm in optical coordinates. -->
<sensor name="mid360_imu" type="imu">
<pose>0.011 0.02329 0.25588 0 0 0</pose>
<pose>${lidar_x + 0.011} ${lidar_y + 0.02329} ${lidar_z - 0.04412} 0 0 0</pose>
<always_on>true</always_on><update_rate>200</update_rate>
<imu/>
<plugin name="mid360_imu" filename="libbr_mid360_imu.so">
@@ -209,9 +244,19 @@
</xacro:if>
</xacro:if>
</link>
<xacro:if value="$(arg dual_lidar)">
<plugin name="mid360_low_sensor" filename="libbr_mid360_sensor.so">
<lidar_position>0.325 0 0.044</lidar_position>
<lidar_rpy>0 0 1.5707963267948966</lidar_rpy>
<topic_prefix>/sim/mid360_low</topic_prefix><frame_id>lidar_low</frame_id><lidar_id>1</lidar_id>
<noise_seed>${int('$(arg noise_seed)') + 10}</noise_seed>
</plugin>
</xacro:if>
<xacro:if value="$(arg lidar)">
<xacro:if value="${'$(arg sensor_model)' == 'mid360'}">
<plugin name="mid360_sensor" filename="libbr_mid360_sensor.so">
<lidar_position>${lidar_x} ${lidar_y} ${lidar_z}</lidar_position>
<range_stddev>$(arg range_stddev)</range_stddev><dropout>$(arg dropout)</dropout>
<noise_seed>$(arg noise_seed)</noise_seed>
</plugin>
@@ -240,7 +285,10 @@
</plugin>
</xacro:if>
<xacro:if value="${'$(arg drive)' == 'contact'}">
<plugin filename="libbr_contact_drive.so" name="contact_drive"/>
<plugin filename="libbr_contact_drive.so" name="contact_drive">
<max_linear_speed>$(arg contact_max_linear)</max_linear_speed>
<max_yaw_speed>$(arg contact_max_yaw)</max_yaw_speed>
</plugin>
</xacro:if>
</model>
</sdf>
@@ -23,6 +23,12 @@ class ContactDrive : public gazebo::ModelPlugin {
link_ = model->GetLink("base_link");
if (!link_) { gzerr << "ContactDrive requires base_link\n"; return; }
node_ = gazebo_ros::Node::Get(sdf);
if (sdf->HasElement("max_linear_speed")) max_linear_ = sdf->Get<double>("max_linear_speed");
if (sdf->HasElement("max_yaw_speed")) max_yaw_ = sdf->Get<double>("max_yaw_speed");
if (!std::isfinite(max_linear_) || max_linear_ <= 0 || max_linear_ > 2.5 ||
!std::isfinite(max_yaw_) || max_yaw_ <= 0 || max_yaw_ > 2.) {
gzerr << "ContactDrive invalid speed limits\n"; return;
}
manager_ = world_->Physics()->GetContactManager();
// Request real ODE contact geometry even without a separate contact sensor.
manager_->SetNeverDropContacts(true);
@@ -65,8 +71,9 @@ class ContactDrive : public gazebo::ModelPlugin {
if (world_->SimTime().Double()-received_ >= 0 &&
world_->SimTime().Double()-received_ <= .5) cmd=cmd_;
}
const double scale=std::min(1.,max_linear_/std::max(1e-12,std::hypot(cmd.linear.x,cmd.linear.y)));
const auto desired=link_->WorldPose().Rot().RotateVector(ignition::math::Vector3d(
std::clamp(cmd.linear.x,-.5,.5),std::clamp(cmd.linear.y,-.5,.5),0));
cmd.linear.x*scale,cmd.linear.y*scale,0));
const double vx=desired.X(),vy=desired.Y();
const auto v=link_->WorldLinearVel();
const double ax=std::clamp(40*(vx-v.X()),-4.,4.);
@@ -82,7 +89,7 @@ class ContactDrive : public gazebo::ModelPlugin {
applied_force_.Set(mass*((1-ny*ny)*bx+nx*ny*by)/det,
mass*(nx*ny*bx+(1-nx*nx)*by)/det,0);
if (applied_force_.Length()>150.) applied_force_ *= 150./applied_force_.Length();
const double wz=std::clamp(cmd.angular.z,-.5,.5);
const double wz=std::clamp(cmd.angular.z,-max_yaw_,max_yaw_);
const double alpha=std::clamp(40*(wz-link_->WorldAngularVel().Z()),-5.,5.);
applied_torque_.Z(link_->GetInertial()->IZZ()*alpha);
link_->AddForce(applied_force_);
@@ -154,6 +161,7 @@ class ContactDrive : public gazebo::ModelPlugin {
std::mutex mutex_;
geometry_msgs::msg::Twist cmd_;
double received_{-1},last_pub_{-1};
double max_linear_{.5},max_yaw_{.5};
ignition::math::Vector3d applied_force_,applied_torque_;
};
GZ_REGISTER_MODEL_PLUGIN(ContactDrive)
@@ -33,29 +33,40 @@ class Mid360Sensor : public gazebo::ModelPlugin {
range_stddev_=sdf->Get<double>("range_stddev",0.).first;
dropout_=sdf->Get<double>("dropout",0.).first;
seed_=sdf->Get<unsigned>("noise_seed",2027u).first;
lidar_position_=sdf->Get<ignition::math::Vector3d>("lidar_position",{.015,0.,.33}).first;
const auto rpy=sdf->Get<ignition::math::Vector3d>("lidar_rpy",{}).first;
if(!lidar_position_.IsFinite() || !rpy.IsFinite())
throw std::invalid_argument("Invalid MID360 optical pose");
lidar_rotation_=ignition::math::Quaterniond(rpy);
topic_prefix_=sdf->Get<std::string>("topic_prefix","/sim/mid360").first;
frame_id_=sdf->Get<std::string>("frame_id","lidar").first;
lidar_id_=sdf->Get<unsigned>("lidar_id",0u).first;
if(topic_prefix_.empty() || topic_prefix_.front()!='/' || topic_prefix_.back()=='/' ||
frame_id_.empty() || lidar_id_>255u)
throw std::invalid_argument("Invalid MID360 topic prefix/frame/device id");
if(!std::isfinite(range_stddev_) || range_stddev_<0 || !std::isfinite(dropout_) || dropout_<0 || dropout_>1)
throw std::invalid_argument("Invalid MID360 range noise/dropout");
rng_.seed(seed_);
node_=gazebo_ros::Node::Get(sdf);
for (int i=0;i<3;++i) {
const std::string name=std::string("/sim/mid360/lidar/profile/")+profiles_[i];
const std::string name=topic_prefix_+"/lidar/profile/"+profiles_[i];
profile_services_[i]=node_->create_service<std_srvs::srv::Trigger>(name,
[this,i](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
profile_.store(i); response->success=true; response->message=profiles_[i]; });
profile_.store(i); enabled_.store(true); response->success=true; response->message=profiles_[i]; });
}
disable_service_=node_->create_service<std_srvs::srv::Trigger>("/sim/mid360/lidar/disable",
disable_service_=node_->create_service<std_srvs::srv::Trigger>(topic_prefix_+"/lidar/disable",
[this](const std::shared_ptr<std_srvs::srv::Trigger::Request>,
std::shared_ptr<std_srvs::srv::Trigger::Response> response) {
last_heartbeat_.store(0); response->success=true; response->message="disabled"; });
heartbeat_=node_->create_subscription<std_msgs::msg::Empty>("/sim/mid360/heartbeat",10,
enabled_.store(false); last_heartbeat_.store(0); response->success=true; response->message="disabled"; });
heartbeat_=node_->create_subscription<std_msgs::msg::Empty>(topic_prefix_+"/heartbeat",10,
[this](const std_msgs::msg::Empty::SharedPtr) { last_heartbeat_.store(NowSteady()); });
ray_=boost::dynamic_pointer_cast<gazebo::physics::RayShape>(
world_->Physics()->CreateShape("ray",gazebo::physics::CollisionPtr()));
if(!ray_) { gzerr << "Physics engine does not provide RayShape\n";return; }
cloud_pub_=node_->create_publisher<livox_ros_driver2::msg::CustomMsg>("/sim/mid360/lidar",10);
view_pub_=node_->create_publisher<sensor_msgs::msg::PointCloud2>("/sim/mid360/points",5);
status_pub_=node_->create_publisher<std_msgs::msg::String>("/sim/mid360/status",10);
cloud_pub_=node_->create_publisher<livox_ros_driver2::msg::CustomMsg>(topic_prefix_+"/lidar",10);
view_pub_=node_->create_publisher<sensor_msgs::msg::PointCloud2>(topic_prefix_+"/points",5);
status_pub_=node_->create_publisher<std_msgs::msg::String>(topic_prefix_+"/status",10);
update_=gazebo::event::Events::ConnectWorldUpdateEnd(std::bind(&Mid360Sensor::Sample,this));
RCLCPP_INFO(node_->get_logger(),
"MID360-compatible sensor: 200 rays/1 ms, 100 ms frames, actual acquisition stamps; optional noise/dropout");
@@ -67,13 +78,13 @@ class Mid360Sensor : public gazebo::ModelPlugin {
std::chrono::steady_clock::now().time_since_epoch()).count(); }
void Begin(int64_t now) {
frame_=livox_ros_driver2::msg::CustomMsg();
frame_.header.frame_id="lidar";
frame_.header.frame_id=frame_id_;
frame_.header.stamp=gazebo_ros::Convert<builtin_interfaces::msg::Time>(world_->SimTime());
frame_.timebase=now;frame_.lidar_id=0;
frame_.timebase=now;frame_.lidar_id=static_cast<uint8_t>(lidar_id_);
frame_.points.reserve(20000);first_=now;last_sample_=now;rays_=0;hits_=0;dropped_=0;rejected_=0;
}
void Sample() {
if (NowSteady()-last_heartbeat_.load()>1000000000LL) { first_=-1; last_=-1; return; }
if (!enabled_.load() || NowSteady()-last_heartbeat_.load()>1000000000LL) { first_=-1; last_=-1; return; }
const int selected=profile_.load();
if (selected!=applied_profile_) {
constexpr double range_noise[]={0.,.005,.015},dropout[]={0.,.01,.05};
@@ -89,7 +100,7 @@ class Mid360Sensor : public gazebo::ModelPlugin {
if(now-first_>=100000000) { Publish();Begin(now); }
last_=now;last_sample_=now;
const auto body=link_->WorldPose();
const auto origin=body.Pos()+body.Rot().RotateVector({0,0,.30});
const auto origin=body.Pos()+body.Rot().RotateVector(lidar_position_);
constexpr double pi=3.14159265358979323846;
for(unsigned i=0;i<200;++i,++index_,++rays_) {
// Documented quasi-uniform, non-repeating approximation; channels are
@@ -98,7 +109,7 @@ class Mid360Sensor : public gazebo::ModelPlugin {
const double el=(-7+59*Fraction(.5+index_*.7548776662466927600))*pi/180;
const ignition::math::Vector3d direction(std::cos(el)*std::cos(az),
std::cos(el)*std::sin(az),std::sin(el));
const auto world_dir=body.Rot().RotateVector(direction);
const auto world_dir=(body.Rot()*lidar_rotation_).RotateVector(direction);
ray_->SetPoints(origin,origin+40*world_dir);
double distance;std::string entity;
ray_->GetIntersection(distance,entity);
@@ -154,11 +165,16 @@ class Mid360Sensor : public gazebo::ModelPlugin {
int64_t first_{-1},last_{-1},last_sample_{-1},step_ns_{};
uint64_t index_{0};unsigned rays_{0},hits_{0},dropped_{0},rejected_{0},seed_{2027};
double range_stddev_{0},dropout_{0};
ignition::math::Vector3d lidar_position_;
ignition::math::Quaterniond lidar_rotation_;
std::string topic_prefix_,frame_id_;
unsigned lidar_id_{0};
std::mt19937 rng_;
std::normal_distribution<double> normal_{0.,1.};
std::uniform_real_distribution<double> uniform_{0.,1.};
gazebo::event::ConnectionPtr update_;
const char *profiles_[3]={"ideal","mild","stress"};
std::atomic<bool> enabled_{true};
std::atomic<int> profile_{0}; int applied_profile_{-1};
std::atomic<int64_t> last_heartbeat_{0};
rclcpp::Subscription<std_msgs::msg::Empty>::SharedPtr heartbeat_;
@@ -21,6 +21,16 @@
<shadows>true</shadows>
</scene>
<!-- 默认从红方(world +Y)外侧俯看红方半场,视线指向约 (0, 2.5, 0.1)。
仅设置 GUI 初始相机;单位为米、弧度,仍可用鼠标自由调整视角。 -->
<gui fullscreen="false">
<camera name="user_camera">
<pose>0 11 10 0 0.86 -1.5707963267948966</pose>
<view_controller>orbit</view_controller>
<projection_type>perspective</projection_type>
</camera>
</gui>
<light type="directional" name="sun">
<cast_shadows>true</cast_shadows>
<pose>0 0 10 0 0 0</pose>