ros2中引入了一些生命周期的东西,本意是好的,但是在写一些demo的时候总是要ros2 lifecycle set /map_server configure
以及 ros2 lifecycle set /map_server activate
去配置和激活地图,虽然可以写脚本在启动应用程序后再启动配置和激活,但是一般很少这样做,所以在查阅和尝试一些方式后,决定在launch中提那家configure和activate;
首先,地图的服务节点在launch中创建:
map_file = DeclareLaunchArgument(
'map_file',
default_value=os.path.join(
# get_package_share_directory('robot_navigation'),
os.path.expanduser('这里修改为map的目录'),
'maps',
'map.yaml'
),
description='Path to the map file (YAML)'
)
map_server_node = LifecycleNode(
package='nav2_map_server',
executable='map_server',
name='map_server',
namespace='',
output='screen',
parameters=[{
'yaml_filename': LaunchConfiguration('map_file'),
'frame_id': 'map',
'topic_name': LaunchConfiguration('map_topic'),
'use_sim_time': False
}]
)
然后重点就是,如果希望在启动map_server之后立刻启动configure和activate,可以添加下述代码:
configure_map_server = EmitEvent(
event=ChangeState(
lifecycle_node_matcher=lambda node: node == map_server_node,
transition_id=Transition.TRANSITION_CONFIGURE
)
)
activate_map_server = EmitEvent(
event=ChangeState(
lifecycle_node_matcher=lambda node: node == map_server_node,
transition_id=Transition.TRANSITION_ACTIVATE
)
)
需要引用的头文件有:
from launch.actions import EmitEvent
from launch_ros.events.lifecycle import ChangeState
这样就可以在启动server后立即加载图像了
当然别忘了在return的LaunchDescription添加
return LaunchDescription([
map_server_node,
configure_map_server,
activate_map_server
])