修改功能包分布和整合launch

This commit is contained in:
walunt5
2026-11-10 10:57:49 +08:00
parent ca61aa63b5
commit cac93cae11
27 changed files with 717 additions and 201 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.8)
project(br_sim_bringup)
find_package(ament_cmake REQUIRED)
install(DIRECTORY launch config DESTINATION share/${PROJECT_NAME}
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})
ament_package()
@@ -1,38 +1,55 @@
"""Independent MID360-compatible sensors and optional Point-LIO evaluation; no SCAN."""
"""Combined Classic world, robot and MID360 sensors, with optional Point-LIO."""
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.actions import DeclareLaunchArgument, IncludeLaunchDescription, OpaqueFunction
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')
own = get_package_share_directory('br_sim_bringup')
def simulation(context):
if LaunchConfiguration('start_sim').perform(context).lower()!='true':return []
robot=get_package_share_directory('r2027_robot_description')
return [IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(robot,'launch','robocon_robot.launch.py')),
launch_arguments={'sensor_profile':LaunchConfiguration('sensor_profile'),'gui':LaunchConfiguration('gui'),'lidar':'true','sensor_model':'mid360','drive':'contact',
'x':LaunchConfiguration('x'),'y':LaunchConfiguration('y'),'z':LaunchConfiguration('z'),'yaw':LaunchConfiguration('yaw')}.items())]
if LaunchConfiguration('start_sim').perform(context).lower() != 'true':
return []
world = get_package_share_directory('robocon_gazebo')
robot = get_package_share_directory('r2027_robot_description')
return [
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(world, 'launch', 'robocon_gazebo.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui')}.items()),
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()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'mid360_sensors.launch.py')),
launch_arguments={'sensor_profile': LaunchConfiguration('sensor_profile')}.items()),
]
def estimator(context):
if LaunchConfiguration('with_lio').perform(context).lower()!='true':return []
lio=get_package_share_directory('point_lio')
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'),os.path.join(own,'config','point_lio_sim.yaml'),
LaunchConfiguration('lio_profile')],
# Three absolute publishers in the existing implementation need explicit remaps.
remappings=[('/cloud_registered_full','/sim/lio/cloud_registered_full'),
('/cloud_registered_full_lidar','/sim/lio/cloud_registered_full_lidar')])]
if LaunchConfiguration('with_lio').perform(context).lower() != 'true':
return []
lio = get_package_share_directory('point_lio')
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')],
remappings=[('/cloud_registered_full', '/sim/lio/cloud_registered_full'),
('/cloud_registered_full_lidar', '/sim/lio/cloud_registered_full_lidar')])]
return LaunchDescription([
DeclareLaunchArgument('gui',default_value='true'),
DeclareLaunchArgument('with_lio',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')),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value='4.5'),
DeclareLaunchArgument('z',default_value='0.17'),DeclareLaunchArgument('yaw',default_value='0.0'),
OpaqueFunction(function=simulation),
OpaqueFunction(function=estimator)])
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('with_lio', 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')),
DeclareLaunchArgument('x', default_value='-4.5'),
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.17'),
DeclareLaunchArgument('yaw', default_value='0.0'),
DeclareLaunchArgument('spawn_delay', default_value='0.0'),
OpaqueFunction(function=simulation), OpaqueFunction(function=estimator),
])
@@ -0,0 +1,41 @@
"""Compatibility one-command world + robot bringup for robot and lidar checks."""
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.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
def generate_launch_description():
world = get_package_share_directory('robocon_gazebo')
robot = get_package_share_directory('r2027_robot_description')
def sensor(context):
if (LaunchConfiguration('lidar').perform(context).lower() == 'true' and
LaunchConfiguration('sensor_model').perform(context) == 'mid360'):
return [IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'mid360_sensors.launch.py')),
launch_arguments={'sensor_profile': LaunchConfiguration('sensor_profile')}.items())]
return []
return LaunchDescription([
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('world', default_value=os.path.join(world, 'worlds', 'robocon_robot.world')),
DeclareLaunchArgument('lidar', default_value='false'),
DeclareLaunchArgument('drive', default_value='planar'),
DeclareLaunchArgument('sensor_model', default_value='generic'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
DeclareLaunchArgument('x', default_value='-4.5'),
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.17'),
DeclareLaunchArgument('yaw', default_value='0.0'),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(world, 'launch', 'robocon_gazebo.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui'), 'world': LaunchConfiguration('world')}.items()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'robocon_robot.launch.py')),
launch_arguments={k: LaunchConfiguration(k) for k in
('lidar', 'drive', 'sensor_model', 'sensor_profile', 'x', 'y', 'z', 'yaw')}.items()),
OpaqueFunction(function=sensor),
])
@@ -0,0 +1,19 @@
"""Display the already running four-layer simulation in RViz only."""
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_ros.actions import Node
def generate_launch_description():
config = os.path.join(
get_package_share_directory('br_sim_bringup'), 'rviz', 'scan_lio.rviz')
return LaunchDescription([
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}]),
])
@@ -1,36 +1,41 @@
"""Flat SCAN closed loop from Point-LIO only; truth remains an independent observer."""
"""One command for the five simulation layers; optional headless mode for tests."""
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.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')
base=os.path.join(own,'config','scan_sim.yaml');profile=os.path.join(own,'config','lio_navigation.yaml')
def bringup(context):
pose=[float(LaunchConfiguration(k).perform(context)) for k in ('x','y','z','yaw')]
return [
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'),
**{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':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],
remappings=[('body_pose','/sim/navigation/body_odom'),('sensor_pose','/sim/navigation/sensor_odom'),
('cloud','/sim/navigation/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,profile],
remappings=[('body_pose','/sim/navigation/body_odom'),('cmd_vel','/cmd_vel')]),
]
own = get_package_share_directory('br_sim_bringup')
def layers(context):
actions = []
if LaunchConfiguration('start_sim').perform(context).lower() == 'true':
actions.append(IncludeLaunchDescription(PythonLaunchDescriptionSource(
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()))
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()))
return actions
return LaunchDescription([
DeclareLaunchArgument('start_sim',default_value='true'),DeclareLaunchArgument('sensor_profile',default_value='ideal'),
DeclareLaunchArgument('gui',default_value='true'),
DeclareLaunchArgument('x',default_value='-4.5'),DeclareLaunchArgument('y',default_value='4.5'),
DeclareLaunchArgument('z',default_value='0.15',description='Known settled base height in this flat profile'),
DeclareLaunchArgument('yaw',default_value='0.0'),OpaqueFunction(function=bringup)])
DeclareLaunchArgument('start_sim', default_value='true'),
DeclareLaunchArgument('with_rviz', default_value='true'),
DeclareLaunchArgument('sensor_profile', default_value='ideal'),
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('x', default_value='-4.5'),
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.15'),
DeclareLaunchArgument('yaw', default_value='0.0'),
DeclareLaunchArgument('spawn_delay', default_value='0.0'),
OpaqueFunction(function=layers),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(own, 'launch', 'rviz.launch.py')),
condition=IfCondition(LaunchConfiguration('with_rviz'))),
])
@@ -0,0 +1,49 @@
"""Pure software Point-LIO, navigation adapter, SCAN and controller."""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, OpaqueFunction, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration, EnvironmentVariable
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')
lio = get_package_share_directory('point_lio')
base = os.path.join(own, 'config', 'scan_sim.yaml')
profile = os.path.join(own, 'config', 'lio_navigation.yaml')
def nodes(context):
pose = [float(LaunchConfiguration(k).perform(context)) for k in ('x', 'y', 'z', 'yaw')]
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'),
os.path.join(own, 'config', 'point_lio_sim.yaml')],
remappings=[('/cloud_registered_full', '/sim/lio/cloud_registered_full'),
('/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}]),
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],
remappings=[('body_pose', '/sim/navigation/body_odom'),
('sensor_pose', '/sim/navigation/sensor_odom'),
('cloud', '/sim/navigation/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, profile],
remappings=[('body_pose', '/sim/navigation/body_odom'), ('cmd_vel', '/cmd_vel')]),
]
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('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),
])
@@ -0,0 +1,34 @@
"""Start the full MID360 navigation simulation and RViz with ready-made displays."""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription, SetEnvironmentVariable
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import EnvironmentVariable, LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
share = get_package_share_directory('br_sim_bringup')
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('gazebo_gui', default_value='false'),
DeclareLaunchArgument('start_sim', 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'),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(share, 'launch', 'scan_lio.launch.py')),
condition=IfCondition(LaunchConfiguration('start_sim')),
launch_arguments={'gui': LaunchConfiguration('gazebo_gui'), 'with_rviz': 'false',
'sensor_profile': LaunchConfiguration('sensor_profile'),
**{k: LaunchConfiguration(k) for k in ('x', 'y', 'z', 'yaw')}}.items()),
Node(package='rviz2', executable='rviz2', name='rviz2', output='screen',
arguments=['-d', os.path.join(share, 'rviz', 'scan_lio.rviz')],
parameters=[{'use_sim_time': True}]),
])
@@ -8,11 +8,15 @@ def generate_launch_description():
def hosts(context):
values={k:LaunchConfiguration(k).perform(context) for k in ('x','y','z','yaw','gui','sensor_profile','terrain')}
terrain=values.pop('terrain').lower()=='true'
args=[k+':='+v for k,v in values.items()]
return [ExecuteProcess(cmd=['ros2','launch','r2027_robot_description','robocon_robot.launch.py',
'lidar:=true','drive:=contact','sensor_model:=mid360']+args,output='screen'),
physical_args=[k+':='+v for k,v in values.items()]
navigation_args=[k+':='+values[k] for k in ('x','y','z','yaw')]
if terrain:
navigation_args += ['start_sim:=false']
return [ExecuteProcess(cmd=['ros2','launch','br_sim_bringup','mid360_sim.launch.py',
'with_lio:=false']+physical_args,output='screen'),
ExecuteProcess(cmd=['ros2','launch','br_sim_bringup',
'scan_lio_terrain.launch.py' if terrain else 'scan_lio.launch.py','start_sim:=false']+args,output='screen')]
'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')]]+
[OpaqueFunction(function=hosts)])
@@ -11,6 +11,7 @@ from launch_ros.actions import Node
def generate_launch_description():
robot = get_package_share_directory('r2027_robot_description')
world = get_package_share_directory('robocon_gazebo')
scan = get_package_share_directory('scan_planner')
own = get_package_share_directory('br_sim_bringup')
overrides = os.path.join(own, 'config', 'scan_sim.yaml')
@@ -23,10 +24,13 @@ def generate_launch_description():
DeclareLaunchArgument('y', default_value='4.5'),
DeclareLaunchArgument('z', default_value='0.15'),
DeclareLaunchArgument('yaw', default_value='0.0'),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(world, 'launch', 'robocon_gazebo.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui'), 'paused': LaunchConfiguration('paused')}.items()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(
os.path.join(robot, 'launch', 'robocon_robot.launch.py')),
launch_arguments={'gui': LaunchConfiguration('gui'),
'paused': LaunchConfiguration('paused'), 'lidar': 'true',
'paused': LaunchConfiguration('paused'), 'lidar': 'true', 'sensor_model': 'generic',
'x': LaunchConfiguration('x'), 'y': LaunchConfiguration('y'),
'z': LaunchConfiguration('z'), 'yaw': LaunchConfiguration('yaw')}.items()),
Node(package='br_sim_bringup', executable='scan_cloud_gate.py',
@@ -11,6 +11,7 @@ from launch_ros.actions import Node
def generate_launch_description():
own=get_package_share_directory('br_sim_bringup')
robot=get_package_share_directory('r2027_robot_description')
world=get_package_share_directory('robocon_gazebo')
scan=get_package_share_directory('scan_planner')
base=os.path.join(own,'config','scan_sim.yaml')
terrain=os.path.join(own,'config','terrain_sim.yaml')
@@ -20,8 +21,10 @@ def generate_launch_description():
DeclareLaunchArgument('x',default_value='3.5'),DeclareLaunchArgument('y',default_value='3.5125'),
DeclareLaunchArgument('z',default_value='0.15'),
DeclareLaunchArgument('yaw',default_value='0.0'),
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(world,'launch','robocon_gazebo.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui')}.items()),
IncludeLaunchDescription(PythonLaunchDescriptionSource(os.path.join(robot,'launch','robocon_robot.launch.py')),
launch_arguments={'gui':LaunchConfiguration('gui'),'lidar':'true','drive':'contact',
launch_arguments={'gui':LaunchConfiguration('gui'),'lidar':'true','sensor_model':'generic','drive':'contact',
'x':LaunchConfiguration('x'),'y':LaunchConfiguration('y'),'z':LaunchConfiguration('z'),'yaw':LaunchConfiguration('yaw')}.items()),
Node(package='br_sim_bringup',executable='scan_cloud_gate.py',name='scan_cloud_gate',parameters=[base,terrain]),
Node(package='step_blocker',executable='step_blocker',name='step_blocker',parameters=[terrain]),
+1
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>rviz2</exec_depend>
<exec_depend>launch</exec_depend>
<exec_depend>launch_ros</exec_depend>
<exec_depend>ament_index_python</exec_depend>
@@ -0,0 +1,130 @@
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: Registered 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/cloud_registered
Use Fixed Frame: true
Value: true
- Class: rviz_default_plugins/PointCloud2
Name: Planning Cloud
Enabled: false
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/planning_cloud
Use Fixed Frame: true
Value: false
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: ~
@@ -13,6 +13,7 @@ find_package(tf2_ros REQUIRED)
find_package(livox_ros_driver2 REQUIRED)
find_package(sensor_msgs REQUIRED)
find_package(std_msgs REQUIRED)
find_package(std_srvs REQUIRED)
add_library(br_contact_drive SHARED src/contact_drive.cpp)
target_include_directories(br_contact_drive PRIVATE ${GAZEBO_INCLUDE_DIRS})
@@ -23,13 +24,13 @@ install(TARGETS br_contact_drive LIBRARY DESTINATION lib)
add_library(br_mid360_sensor SHARED src/mid360_sensor.cpp)
target_include_directories(br_mid360_sensor PRIVATE ${GAZEBO_INCLUDE_DIRS})
target_link_libraries(br_mid360_sensor ${GAZEBO_LIBRARIES})
ament_target_dependencies(br_mid360_sensor gazebo_ros rclcpp livox_ros_driver2 sensor_msgs std_msgs)
ament_target_dependencies(br_mid360_sensor gazebo_ros rclcpp livox_ros_driver2 sensor_msgs std_msgs std_srvs)
install(TARGETS br_mid360_sensor LIBRARY DESTINATION lib)
add_library(br_mid360_imu SHARED src/mid360_imu.cpp)
target_include_directories(br_mid360_imu PRIVATE ${GAZEBO_INCLUDE_DIRS})
target_link_libraries(br_mid360_imu ${GAZEBO_LIBRARIES})
ament_target_dependencies(br_mid360_imu gazebo_ros rclcpp sensor_msgs)
ament_target_dependencies(br_mid360_imu gazebo_ros rclcpp sensor_msgs std_msgs std_srvs)
install(TARGETS br_mid360_imu LIBRARY DESTINATION lib)
# SIM-P2-001: 只装本包自己的资源。
@@ -40,7 +41,7 @@ install(DIRECTORY launch sdf config
PATTERN "__pycache__" EXCLUDE
PATTERN "*.pyc" EXCLUDE)
install(PROGRAMS scripts/cmd_vel_timeout.py scripts/sim_data_adapter.py
install(PROGRAMS scripts/cmd_vel_timeout.py scripts/sim_data_adapter.py scripts/spawn_existing_world.py scripts/mid360_control.py
DESTINATION lib/${PROJECT_NAME})
install(FILES SOURCE_PROVENANCE.md
@@ -0,0 +1,16 @@
"""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_ros.actions import Node
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('sensor_profile', default_value='ideal'),
Node(package='r2027_robot_description', executable='mid360_control.py',
name='mid360_control', output='screen',
arguments=[LaunchConfiguration('sensor_profile')]),
])
@@ -1,43 +1,8 @@
"""启动简化全向机器人(SIM-P2-001)。
入口:
ros2 launch r2027_robot_description robocon_robot.launch.py
ros2 launch r2027_robot_description robocon_robot.launch.py gui:=false paused:=true
参数:
drive planar(默认平地)或 contact(重力/接触决定高度和倾斜)
gui 是否启动 gzclient(默认 true)
paused 是否以暂停状态启动 gzserver(默认 false)
verbose gzserver 详细日志(默认 false)
world 覆盖 world(默认 robocon_gazebo/worlds/robocon_robot.world)
x / y / z / yaw 出生位姿(默认 -4.5 / 4.5 / 0.17 / 0.0)
entity 模型名(默认 r2027_omni)
启动的节点:
gzserver(官方 gazebo_ros gzserver.launch.py,init/factory 各一次,force_system:=false)
spawn_entity.py(-file,插入 xacro 展开后的 SDF 模型)
static_transform_publisher(world -> odom,单位变换)
cmd_vel_timeout(/cmd_vel -> /sim/cmd_vel,仿真时间超时零速)
为什么模型是 SDF 而不是 URDF:
URDF 的 <gazebo reference="link"><mu1>/<mu2>/<kp>/<kd> 在本机链路上**不会**进入物理引擎
(`gz sdf -p` 转换出的 collision 没有 <surface>,且 μ=0.05 与 μ=0.0 实测位移完全相同)。
轮子因此退回默认 μ=1.0,planar_move 设定的速度每 10 ms 被摩擦拉低,2 s 只走出 0.31 m。
改原生 SDF 后接触参数真正生效。代价是不再有 robot_state_publisher 的 URDF 关节树,
而任务要求的 TF 只有 world->odom(静态)与 odom->base_link(插件发布),
不含轮子帧,因此不需要 robot_state_publisher。
设计约束:
1. 只起一个 gzserver;不启动 ros_gz_bridge、不加载 Fortress。
2. odom->base_link 只由插件发布,world->odom 只由静态变换发布,没有第二处重复。
3. 世界文件只比 robocon_track_full.world 多一个 libgazebo_ros_state.so world 插件。
4. GAZEBO_MASTER_URI=11355、ROS_DOMAIN_ID=77、ROS_LOCALHOST_ONLY=1 与已验收基线一致。
"""
"""向已运行的 Gazebo Classic 场地生成机器人,不创建第二个 server。"""
import os
import tempfile
import math
import socket
import yaml
import xacro
@@ -45,16 +10,20 @@ from ament_index_python.packages import get_package_share_directory, get_package
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
IncludeLaunchDescription,
SetEnvironmentVariable,
OpaqueFunction,
RegisterEventHandler,
EmitEvent,
)
from launch.event_handlers import OnProcessExit
from launch.events import Shutdown
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PythonExpression, EnvironmentVariable
from launch_ros.actions import Node
GAZEBO_MASTER_URI = 'http://127.0.0.1:11355'
# 端口可用环境变量 BR_SIM_MASTER_PORT 覆盖(默认 11355),须与 Gazebo 场地入口一致。
MASTER_PORT = int(os.environ.get('BR_SIM_MASTER_PORT', '11355'))
GAZEBO_MASTER_URI = f'http://127.0.0.1:{MASTER_PORT}'
DEFAULT_X = '-4.5'
DEFAULT_Y = '4.5'
@@ -62,23 +31,9 @@ DEFAULT_Z = '0.17'
DEFAULT_YAW = '0.0'
def require_free_master(context):
# Check before starting sensors/estimators: they must not consume an older
# world's clock or IMU while a second gzserver fails to bind its port.
with socket.socket() as connection:
connection.settimeout(0.3)
if connection.connect_ex(('127.0.0.1', 11355)) == 0:
raise RuntimeError(
'Gazebo 端口 11355 已被占用:已有仿真或自动测试仍在运行。'
'请在原启动终端按 Ctrl+C,等待退出后重试。'
'可用 ss -ltnp "sport = :11355" 查看占用者;本入口不会终止已有进程。')
return []
def generate_launch_description():
gz_share = get_package_share_directory('robocon_gazebo')
robot_share = get_package_share_directory('r2027_robot_description')
gazebo_ros_share = get_package_share_directory('gazebo_ros')
sdf_xacro = os.path.join(robot_share, 'sdf', 'r2027_omni_robot.sdf.xacro')
# 展开期就确定下来,写成一个文件交给 spawn_entity(-file),
@@ -129,8 +84,8 @@ def generate_launch_description():
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('sensor_model', default_value='generic'),
DeclareLaunchArgument('lidar', default_value='false',
DeclareLaunchArgument('sensor_model', default_value='mid360'),
DeclareLaunchArgument('lidar', default_value='true',
description='Enable generic CPU 3D lidar and truth data adapter'),
DeclareLaunchArgument('gui', default_value='true'),
DeclareLaunchArgument('paused', default_value='false'),
@@ -141,6 +96,10 @@ def generate_launch_description():
DeclareLaunchArgument('z', default_value=DEFAULT_Z),
DeclareLaunchArgument('yaw', default_value=DEFAULT_YAW),
DeclareLaunchArgument('entity', default_value='r2027_omni'),
# 场地较大、加载耗时(本机约 20 s)。gzserver 尚未就绪时调用 /spawn_entity
# 会一直挂起且因 use_sim_time 永不超时,所以延迟再生成机器人。
DeclareLaunchArgument('spawn_delay', default_value='0.0',
description='兼容旧命令;现在由服务就绪检查决定生成时机'),
]
env_actions = [
@@ -157,42 +116,16 @@ def generate_launch_description():
SetEnvironmentVariable('PATH', '/usr/bin:' + os.environ.get('PATH', '')),
]
gzserver = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
os.path.join(gazebo_ros_share, 'launch', 'gzserver.launch.py')),
launch_arguments={
'world': LaunchConfiguration('world'),
'verbose': LaunchConfiguration('verbose'),
'pause': LaunchConfiguration('paused'),
'init': 'true',
'factory': 'true',
'force_system': 'false',
'params_file': os.path.join(robot_share, 'config', 'gazebo.yaml'),
'server_required': 'true',
}.items(),
)
gzclient = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
os.path.join(gazebo_ros_share, 'launch', 'gzclient.launch.py')),
condition=IfCondition(LaunchConfiguration('gui')),
launch_arguments={'gui_required': 'true'}.items(),
)
spawn = Node(
package='gazebo_ros',
executable='spawn_entity.py',
name='spawn_entity',
package='r2027_robot_description',
executable='spawn_existing_world.py',
name='spawn_existing_world',
output='screen',
parameters=[{'use_sim_time': True}],
arguments=[
'-file', LaunchConfiguration('expanded_model'),
'-entity', LaunchConfiguration('entity'),
'-x', LaunchConfiguration('x'),
'-y', LaunchConfiguration('y'),
'-z', LaunchConfiguration('z'),
'-Y', LaunchConfiguration('yaw'),
'-timeout', '120',
LaunchConfiguration('expanded_model'), LaunchConfiguration('entity'),
LaunchConfiguration('x'), LaunchConfiguration('y'),
LaunchConfiguration('z'), LaunchConfiguration('yaw'),
],
)
@@ -247,5 +180,8 @@ def generate_launch_description():
return LaunchDescription(
declared_args + env_actions
+ [OpaqueFunction(function=require_free_master), OpaqueFunction(function=expand_model), gzserver, gzclient, spawn,
+ [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])
@@ -18,6 +18,7 @@
<depend>livox_ros_driver2</depend>
<build_depend>sensor_msgs</build_depend>
<depend>std_msgs</depend>
<depend>std_srvs</depend>
<exec_depend>gazebo_ros</exec_depend>
<exec_depend>gazebo_plugins</exec_depend>
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Configure and lease the dormant Gazebo MID360 and IMU plugins."""
import sys
import time
import rclpy
from rclpy.signals import SignalHandlerOptions
from std_msgs.msg import Empty
from std_srvs.srv import Trigger
def invoke(node, name, wait=120.0):
client = node.create_client(Trigger, name)
if not client.wait_for_service(timeout_sec=wait):
raise RuntimeError(f'传感器服务未就绪:{name};先启动带 MID360 的机器人')
future = client.call_async(Trigger.Request())
rclpy.spin_until_future_complete(node, future, timeout_sec=5.0)
if not future.done() or future.exception() or not future.result().success:
raise RuntimeError(f'传感器服务调用失败:{name}')
def main():
profile = sys.argv[1] if len(sys.argv) > 1 else 'ideal'
if profile not in ('ideal', 'mild', 'stress'):
print('sensor_profile must be ideal, mild or stress', file=sys.stderr)
return 2
rclpy.init(signal_handler_options=SignalHandlerOptions.NO)
node = rclpy.create_node('mid360_control')
publisher = node.create_publisher(Empty, '/sim/mid360/heartbeat', 10)
try:
for component in ('lidar', 'imu'):
invoke(node, f'/sim/mid360/{component}/profile/{profile}')
node.get_logger().info(f'MID360 与 IMU 已配置为 {profile}')
while rclpy.ok():
publisher.publish(Empty())
rclpy.spin_once(node, timeout_sec=0.2)
except KeyboardInterrupt:
pass
except Exception as exc:
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
node.destroy_node()
if rclpy.ok():
rclpy.shutdown()
return 0
if __name__ == '__main__':
sys.exit(main())
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Spawn one robot into an already running Gazebo Classic world."""
import math
import sys
import time
import rclpy
from gazebo_msgs.srv import GetEntityState, SpawnEntity
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')
return future.result()
def main():
path, entity, x, y, z, yaw = sys.argv[1:7]
rclpy.init()
node = rclpy.create_node('spawn_existing_world_client')
try:
spawn = node.create_client(SpawnEntity, '/spawn_entity')
state = node.create_client(GetEntityState, '/gazebo/get_entity_state')
if not spawn.wait_for_service(timeout_sec=120.0) or not state.wait_for_service(timeout_sec=30.0):
raise RuntimeError('场地服务未就绪;先启动 robocon_gazebo.launch.py(robocon_robot.world)')
query = GetEntityState.Request()
query.name = entity
if call(node, state, query).success:
raise RuntimeError(f'机器人实体 {entity} 已存在;请勿重复启动机器人入口')
request = SpawnEntity.Request()
request.name = entity
with open(path, encoding='utf-8') as stream:
request.xml = stream.read()
pose = Pose()
pose.position.x, pose.position.y, pose.position.z = map(float, (x, y, z))
half = float(yaw) / 2.0
pose.orientation.z, pose.orientation.w = math.sin(half), math.cos(half)
request.initial_pose = pose
request.reference_frame = 'world'
result = call(node, spawn, request, 120.0)
if not result.success:
raise RuntimeError(f'生成机器人失败:{result.status_message}')
node.get_logger().info(f'已生成机器人 {entity}')
except Exception as exc:
node.get_logger().error(str(exc))
return 1
finally:
node.destroy_node()
rclpy.shutdown()
return 0
if __name__ == '__main__':
sys.exit(main())
@@ -9,6 +9,10 @@
#include <gazebo_ros/node.hpp>
#include <gazebo_ros/conversions/builtin_interfaces.hpp>
#include <sensor_msgs/msg/imu.hpp>
#include <std_msgs/msg/empty.hpp>
#include <std_srvs/srv/trigger.hpp>
#include <atomic>
#include <chrono>
namespace br_sim {
class Mid360Imu : public gazebo::SensorPlugin {
@@ -22,13 +26,40 @@ class Mid360Imu : public gazebo::SensorPlugin {
gyro_bias_=sdf->Get<ignition::math::Vector3d>("gyro_bias",{}).first;
if(!std::isfinite(accel_stddev_) || accel_stddev_<0 || !std::isfinite(gyro_stddev_) || gyro_stddev_<0 ||
!accel_bias_.IsFinite() || !gyro_bias_.IsFinite()) throw std::invalid_argument("Invalid IMU noise/bias");
rng_.seed(sdf->Get<unsigned>("noise_seed",2027u).first+1u);
seed_=sdf->Get<unsigned>("noise_seed",2027u).first;
rng_.seed(seed_+1u);
node_=gazebo_ros::Node::Get(sdf);
for (int i=0;i<3;++i) {
const std::string name=std::string("/sim/mid360/imu/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]; });
}
disable_service_=node_->create_service<std_srvs::srv::Trigger>("/sim/mid360/imu/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,
[this](const std_msgs::msg::Empty::SharedPtr) { last_heartbeat_.store(NowSteady()); });
pub_=node_->create_publisher<sensor_msgs::msg::Imu>("/sim/mid360/imu",rclcpp::SensorDataQoS().reliable());
update_=sensor_->ConnectUpdated(std::bind(&Mid360Imu::Publish,this));
}
private:
static int64_t NowSteady() { return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count(); }
void Publish() {
if (NowSteady()-last_heartbeat_.load()>1000000000LL) return;
const int selected=profile_.load();
if (selected!=applied_profile_) {
constexpr double accel_noise[]={0.,.01,.04},gyro_noise[]={0.,.0005,.0015};
accel_stddev_=accel_noise[selected];gyro_stddev_=gyro_noise[selected];
const double accel_bias[][3]={{0,0,0},{.005,-.005,.01},{.02,.01,.03}};
const double gyro_bias[][3]={{0,0,0},{.0001,-.0001,.0002},{.0005,-.0005,.001}};
accel_bias_.Set(accel_bias[selected][0],accel_bias[selected][1],accel_bias[selected][2]);
gyro_bias_.Set(gyro_bias[selected][0],gyro_bias[selected][1],gyro_bias[selected][2]);
rng_.seed(seed_+1u);applied_profile_=selected;
}
// One synchronized sensor reading, including its actual link-data timestamp.
const auto reading=sensor_->ImuMessage();
sensor_msgs::msg::Imu msg;
@@ -60,6 +91,12 @@ class Mid360Imu : public gazebo::SensorPlugin {
gazebo_ros::Node::SharedPtr node_;
rclcpp::Publisher<sensor_msgs::msg::Imu>::SharedPtr pub_;
gazebo::event::ConnectionPtr update_;
const char *profiles_[3]={"ideal","mild","stress"};
unsigned seed_{2027};
std::atomic<int> profile_{0}; int applied_profile_{-1};
std::atomic<int64_t> last_heartbeat_{0};
rclcpp::Subscription<std_msgs::msg::Empty>::SharedPtr heartbeat_;
rclcpp::Service<std_srvs::srv::Trigger>::SharedPtr profile_services_[3],disable_service_;
};
GZ_REGISTER_SENSOR_PLUGIN(Mid360Imu)
} // namespace br_sim
@@ -15,6 +15,10 @@
#include <sensor_msgs/msg/point_cloud2.hpp>
#include <sensor_msgs/point_cloud2_iterator.hpp>
#include <std_msgs/msg/string.hpp>
#include <std_msgs/msg/empty.hpp>
#include <std_srvs/srv/trigger.hpp>
#include <atomic>
#include <chrono>
namespace br_sim {
class Mid360Sensor : public gazebo::ModelPlugin {
@@ -33,6 +37,19 @@ class Mid360Sensor : public gazebo::ModelPlugin {
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];
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]; });
}
disable_service_=node_->create_service<std_srvs::srv::Trigger>("/sim/mid360/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,
[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; }
@@ -46,6 +63,8 @@ class Mid360Sensor : public gazebo::ModelPlugin {
private:
static double Fraction(double x) { return x-std::floor(x); }
static int64_t NowSteady() { return std::chrono::duration_cast<std::chrono::nanoseconds>(
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";
@@ -54,6 +73,13 @@ class Mid360Sensor : public gazebo::ModelPlugin {
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; }
const int selected=profile_.load();
if (selected!=applied_profile_) {
constexpr double range_noise[]={0.,.005,.015},dropout[]={0.,.01,.05};
range_stddev_=range_noise[selected];dropout_=dropout[selected];rng_.seed(seed_);
applied_profile_=selected;first_=-1;last_=-1;
}
const int64_t now=world_->SimTime().sec*int64_t(1000000000)+world_->SimTime().nsec;
if(first_<0) Begin(now);
if(last_>=0 && now-last_!=step_ns_) {
@@ -132,6 +158,11 @@ class Mid360Sensor : public gazebo::ModelPlugin {
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<int> profile_{0}; int applied_profile_{-1};
std::atomic<int64_t> last_heartbeat_{0};
rclcpp::Subscription<std_msgs::msg::Empty>::SharedPtr heartbeat_;
rclcpp::Service<std_srvs::srv::Trigger>::SharedPtr profile_services_[3],disable_service_;
};
GZ_REGISTER_MODEL_PLUGIN(Mid360Sensor)
} // namespace br_sim
+1 -1
View File
@@ -13,7 +13,7 @@ find_package(ament_cmake REQUIRED)
# worlds/ robocon_track_full.world(仅移除两个错位的 ROS 系统插件声明)
# models/ robocon_ground_full(model.config + model.sdf + meshes/)
install(DIRECTORY launch worlds models
install(DIRECTORY launch worlds models config
DESTINATION share/${PROJECT_NAME}
PATTERN "__pycache__" EXCLUDE
PATTERN "*.pyc" EXCLUDE)
@@ -0,0 +1,3 @@
gazebo:
ros__parameters:
publish_rate: 100.0
@@ -1,4 +1,4 @@
"""启动 ROBOCON 2027 完整场地(Gazebo Classic 11 + ROS 2 Humble)。
"""启动 ROBOCON 2027 完整场地与机器人生成服务(Gazebo Classic 11)。
入口统一为:
ros2 launch robocon_gazebo robocon_gazebo.launch.py
@@ -8,7 +8,7 @@
gui 是否启动一个 gzclient(默认 true)
paused 是否以暂停状态启动 gzserver(默认 false)
verbose gzserver 是否输出详细日志(默认 false)
world 可覆盖 world 路径(默认包内 worlds/robocon_track_full.world)
world 可覆盖 world 路径(默认包内 worlds/robocon_robot.world)
设计要点(SIM-P1-004-C):
1. 只通过**官方 gazebo_ros 的 gzserver.launch.py** 加载 libgazebo_ros_init.so 与
@@ -19,13 +19,13 @@
3. 不启动 ros_gz_bridge,不加载 Fortress(ignition)任何组件。
4. GAZEBO_MASTER_URI 固定到 127.0.0.1:11355(与默认 11345 隔离),
server / client / 采集工具共用同一 master;ROS_DOMAIN_ID=77、ROS_LOCALHOST_ONLY=1。
5. 不接入机器人、TF、里程计、点云或 /cmd_vel。
5. 不生成机器人、TF、里程计、点云或 /cmd_vel;world 插件提供实体状态服务。
"""
import os
import socket
from ament_index_python.packages import get_package_share_directory
from ament_index_python.packages import get_package_share_directory, get_package_prefix
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
@@ -35,27 +35,30 @@ from launch.actions import (
)
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch.substitutions import LaunchConfiguration, EnvironmentVariable
# 与采集工具、手动 gzclient 保持一致(改这里就要同步改 tools/check_classic_baseline.py)
GAZEBO_MASTER_URI = 'http://127.0.0.1:11355'
# 端口可用环境变量 BR_SIM_MASTER_PORT 覆盖(默认 11355):端口被其他程序占用时换一个即可。
MASTER_PORT = int(os.environ.get('BR_SIM_MASTER_PORT', '11355'))
GAZEBO_MASTER_URI = f'http://127.0.0.1:{MASTER_PORT}'
ROS_DOMAIN_ID = '77'
def require_free_master(context):
with socket.socket() as connection:
connection.settimeout(0.3)
if connection.connect_ex(('127.0.0.1', 11355)) == 0:
if connection.connect_ex(('127.0.0.1', MASTER_PORT)) == 0:
raise RuntimeError(
'Gazebo 端口 11355 已被占用:请先在原仿真或自动测试终端按 Ctrl+C,'
'等待退出后重试。本入口不会终止已有进程。')
f'Gazebo 端口 {MASTER_PORT} 已被占用:请先在原仿真或自动测试终端按 Ctrl+C,'
'等待退出后重试;或设置 BR_SIM_MASTER_PORT 换端口。'
'本入口不会终止已有进程。')
return []
def generate_launch_description():
share = get_package_share_directory('robocon_gazebo')
models_dir = os.path.join(share, 'models')
default_world = os.path.join(share, 'worlds', 'robocon_track_full.world')
default_world = os.path.join(share, 'worlds', 'robocon_robot.world')
gazebo_ros_share = get_package_share_directory('gazebo_ros')
# 模型查找路径:本包安装的模型在前,其余沿用环境与 ~/.gazebo/models
@@ -78,9 +81,12 @@ def generate_launch_description():
# 环境隔离:master 端口、ROS 域、仅本机通信、模型路径
env_actions = [
SetEnvironmentVariable('GAZEBO_MASTER_URI', GAZEBO_MASTER_URI),
SetEnvironmentVariable('ROS_DOMAIN_ID', ROS_DOMAIN_ID),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', '1'),
SetEnvironmentVariable('ROS_DOMAIN_ID', EnvironmentVariable('ROS_DOMAIN_ID', default_value=ROS_DOMAIN_ID)),
SetEnvironmentVariable('ROS_LOCALHOST_ONLY', EnvironmentVariable('ROS_LOCALHOST_ONLY', default_value='1')),
SetEnvironmentVariable('GAZEBO_MODEL_PATH', model_path),
SetEnvironmentVariable('GAZEBO_PLUGIN_PATH', os.pathsep.join([
os.path.join(get_package_prefix('r2027_robot_description'), 'lib'),
os.environ.get('GAZEBO_PLUGIN_PATH', '')])),
]
gzserver = IncludeLaunchDescription(
@@ -93,6 +99,7 @@ def generate_launch_description():
'init': 'true', # -s libgazebo_ros_init.so
'factory': 'true', # -s libgazebo_ros_factory.so
'force_system': 'false', # 不再多加载一个系统插件
'params_file': os.path.join(share, 'config', 'gazebo.yaml'),
'server_required': 'true', # 关掉 launch 时一起收掉 gzserver
}.items(),
)