382 lines
17 KiB
Python
382 lines
17 KiB
Python
#!/usr/bin/env python3
|
||
"""哨兵导航仿真 —— `ros2 launch` 入口(按文件路径启动,不依赖 ament 包注册)。
|
||
|
||
用法:
|
||
|
||
cd ~/Gazebo_projects/sentry_nav_dev
|
||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py # 全部
|
||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py headless:=true rviz:=false
|
||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py nav2:=false # 只看仿真
|
||
ros2 launch src/sentry_sim/launch/sentry_arena.launch.py --show-args # 看所有参数
|
||
|
||
和 `scripts/sentry_up.sh` 的关系
|
||
------------------------------
|
||
两者**等价**,都是完整启动链:
|
||
|
||
| | `sentry_up.sh` | 本文件 |
|
||
|---|---|---|
|
||
| 入口 | `scripts/sentry_up.sh` | `ros2 launch <路径>` |
|
||
| 排序 | bash 顺序执行 + 轮询 `/clock` | launch 管进程;桥仍用带等待的脚本 |
|
||
| 依赖 | 只有 bash | 需要 `ros2 launch` |
|
||
| 优势 | 少一层、日志直接 | 参数可见(`--show-args`)、进程树可见、退出统一收尾 |
|
||
|
||
⚠️ **桥的话题列表只在 `scripts/bridge_after_gz.sh` 里**,本文件只是调用它。
|
||
(`sentry_up.sh` 把同样的列表内联在自己里面 —— 那是唯一需要手工同步的地方。)
|
||
|
||
为什么没有 `package.xml` 也能 `ros2 launch`
|
||
------------------------------------------
|
||
`ros2 launch` 接受**文件路径**,不需要包注册。所以:
|
||
|
||
* 系统包(`robot_state_publisher` / `nav2_map_server` / `rviz2` …)
|
||
照常写 `Node(package=..., executable=...)`;
|
||
* 本工程自己的节点(`self_filter`)用 `ExecuteProcess` 直接指 xmake 产物;
|
||
* 数据包路径用 `__file__` 往上推,不查 ament。
|
||
|
||
坐标系
|
||
------
|
||
map → odom 由显式选择的 LIO / AMCL 定位器发布,不能同时启动。
|
||
map → field 为恒等变换。map / field 都以场地中心为原点。
|
||
Nav2 等待仿真时钟和 odom/base/lidar TF 就绪后启动。
|
||
"""
|
||
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
from launch import LaunchDescription
|
||
from launch.actions import (
|
||
DeclareLaunchArgument,
|
||
ExecuteProcess,
|
||
EmitEvent,
|
||
RegisterEventHandler,
|
||
LogInfo,
|
||
OpaqueFunction,
|
||
SetEnvironmentVariable,
|
||
SetLaunchConfiguration,
|
||
)
|
||
from launch.conditions import IfCondition
|
||
from launch.event_handlers import OnProcessExit
|
||
from launch.events import Shutdown
|
||
from launch.substitutions import (
|
||
EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, PathJoinSubstitution, PythonExpression,
|
||
)
|
||
from launch_ros.actions import Node
|
||
from launch_ros.parameter_descriptions import ParameterValue
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 路径推算:launch/ 的上一级是 src/sentry_sim,再上三级是仓库根
|
||
# ---------------------------------------------------------------------------
|
||
WS = Path(__file__).resolve().parents[3]
|
||
PKG_SHARE = Path(os.environ.get('SENTRY_SIM_SHARE') or WS / 'src' / 'sentry_sim').resolve()
|
||
SCRIPTS = PKG_SHARE / 'scripts'
|
||
TOOLS_DIR = WS / 'tools'
|
||
INTERNAL_TOOLS = TOOLS_DIR / '_internal'
|
||
|
||
# 可移植探测:xmake 产物目录 / 场地包 / 地图 / gz 版本,一个都不写死。
|
||
# 规则与 `scripts/env_common.sh` 完全一致(同样支持 SENTRY_BIN_DIR、
|
||
# SENTRY_FIELD_ROOT、SENTRY_MAP_YAML、GZ_BIN、GZ_FORCE_VERSION 覆盖)。
|
||
# 从仓库源码加载工具模块。
|
||
if str(TOOLS_DIR) not in sys.path:
|
||
sys.path.insert(0, str(TOOLS_DIR))
|
||
import project_env # noqa: E402 (必须在 sys.path 调整之后导入)
|
||
from _internal.dds_environment import defaults as dds_defaults # noqa: E402
|
||
from _internal.robot_description import runtime_description # noqa: E402
|
||
|
||
BIN_DIR = LaunchConfiguration('_sentry_bin_dir')
|
||
GZ_MAJOR_VERSION = LaunchConfiguration('_sentry_gz_major_version')
|
||
|
||
|
||
def _resolve_environment(context):
|
||
field_root = project_env.find_field_root(
|
||
WS, explicit=LaunchConfiguration('field_root').perform(context))
|
||
map_yaml = project_env.find_map_yaml(
|
||
field_root, explicit=LaunchConfiguration('map').perform(context))
|
||
bin_dir = project_env.find_bin_dir(WS)
|
||
nodes = ['odom_tf', 'cmd_vel_relay', 'self_filter']
|
||
if LaunchConfiguration('localization').perform(context) == 'lio':
|
||
nodes.append('field_localization_node')
|
||
for name in nodes:
|
||
project_env.require_executable(bin_dir / name, name)
|
||
gz = project_env.find_gz_bin()
|
||
versions = project_env.gz_version_args(gz)
|
||
return [
|
||
SetLaunchConfiguration('field_root', str(field_root)),
|
||
SetLaunchConfiguration('map', str(map_yaml)),
|
||
SetLaunchConfiguration('_sentry_bin_dir', str(bin_dir)),
|
||
SetEnvironmentVariable('GZ_BIN', str(gz)),
|
||
SetLaunchConfiguration('_sentry_gz_major_version', versions[1] if versions else ''),
|
||
]
|
||
|
||
|
||
def _start_gazebo(context):
|
||
headless = LaunchConfiguration('headless').perform(context).lower() in ('true', '1')
|
||
# Keep -r in both modes so that the world starts unpaused.
|
||
args = ['-s', '--headless-rendering', '-r'] if headless else ['-r']
|
||
if major := GZ_MAJOR_VERSION.perform(context):
|
||
args.extend(['--force-version', major])
|
||
world_path = PathJoinSubstitution([str(PKG_SHARE / 'worlds'), LaunchConfiguration('world')])
|
||
return [ExecuteProcess(
|
||
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', *args, world_path],
|
||
name='gazebo', output='screen',
|
||
)]
|
||
|
||
|
||
def _on_bridge_exit(event, context):
|
||
if event.returncode != 0 and not context.is_shutdown:
|
||
raise RuntimeError('Gazebo 桥启动或运行失败,请检查 /clock 与 ros_gz_bridge 日志。')
|
||
return []
|
||
|
||
|
||
def _gz_resource_path():
|
||
"""GZ_SIM_RESOURCE_PATH:本包的 models + 迁移包的 models(可带用户追加的)。"""
|
||
# 注意冒号分隔符不能漏 —— 漏了会拼成一条不存在的路径,
|
||
# gazebo 只会报 "Unable to find uri[model://xxx]",不会说路径写错了
|
||
parts = [str(PKG_SHARE / 'models'), ':',
|
||
LaunchConfiguration('field_root'),
|
||
'/src/guodong_sentry_sim/models']
|
||
extra = os.environ.get('GZ_SIM_RESOURCE_PATH')
|
||
if extra:
|
||
parts += [':', extra]
|
||
return parts
|
||
|
||
|
||
def _validate_lio(context):
|
||
if LaunchConfiguration('localization').perform(context) == 'lio':
|
||
mode = LaunchConfiguration('lio_mode').perform(context)
|
||
path = Path(LaunchConfiguration('lio_map').perform(context))
|
||
if mode == 'localization' and not path.is_file():
|
||
raise RuntimeError(f'Missing LIO map: {path}; first select lio_mode:=mapping')
|
||
if mode == 'mapping':
|
||
export = Path(LaunchConfiguration('lio_export_map').perform(context))
|
||
export.parent.mkdir(parents=True, exist_ok=True)
|
||
return []
|
||
|
||
|
||
def _preflight_nav2(context):
|
||
if LaunchConfiguration('nav2').perform(context).lower() in ('true', '1'):
|
||
subprocess.run(['python3', str(INTERNAL_TOOLS / 'nav2_startup.py'), '--preflight'],
|
||
env=dict(context.environment), check=True)
|
||
return []
|
||
|
||
|
||
def _start_velocity_relay(context):
|
||
navigation = LaunchConfiguration('nav2').perform(context).lower() in ('true', '1')
|
||
localization = LaunchConfiguration('localization').perform(context)
|
||
input_topic = '/cmd_vel' if navigation else context.environment.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel')
|
||
return [ExecuteProcess(
|
||
cmd=[PathJoinSubstitution([BIN_DIR, 'cmd_vel_relay']),
|
||
'--ros-args', '-p', 'use_sim_time:=true',
|
||
'-p', f'navigation_mode:={str(navigation).lower()}',
|
||
'-p', f'require_localization_health:={str(localization == "lio").lower()}',
|
||
'-p', f'in_topic:={input_topic}'],
|
||
name='cmd_vel_relay', output='screen',
|
||
)]
|
||
|
||
|
||
def generate_launch_description():
|
||
headless = LaunchConfiguration('headless')
|
||
nav2 = LaunchConfiguration('nav2')
|
||
rviz = LaunchConfiguration('rviz')
|
||
map_yaml = LaunchConfiguration('map')
|
||
localization = LaunchConfiguration('localization')
|
||
lio_mode = LaunchConfiguration('lio_mode')
|
||
lio_map = LaunchConfiguration('lio_map')
|
||
lio_export = LaunchConfiguration('lio_export_map')
|
||
lio_default_map = IfElseSubstitution(
|
||
EqualsSubstitution(lio_mode, 'mapping'),
|
||
if_value=str(WS / 'generated' / 'field_mapping.flmap'),
|
||
else_value=str(PKG_SHARE / 'maps' / 'field_full.flmap'),
|
||
)
|
||
|
||
# 布尔参数统一用 PythonExpression 判,避免 launch 把 "false" 当真值
|
||
nav2_on = PythonExpression(["'", nav2, "'.lower() in ('true', '1')"])
|
||
rviz_on = PythonExpression([
|
||
"'", rviz, "'.lower() in ('true', '1') and '",
|
||
headless, "'.lower() not in ('true', '1')"])
|
||
|
||
robot_description = runtime_description(PKG_SHARE)
|
||
bridge = ExecuteProcess(
|
||
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
|
||
name='ros_gz_bridge', output='screen',
|
||
)
|
||
|
||
navigation_ready = ExecuteProcess(
|
||
cmd=['python3', str(INTERNAL_TOOLS / 'wait_navigation_ready.py')],
|
||
name='wait_navigation_ready', output='screen', condition=IfCondition(nav2_on),
|
||
)
|
||
# Use the same process boundary and options as the shell entry point.
|
||
# The nested include path reproduced a Wait action discovery timeout on this setup.
|
||
navigation = ExecuteProcess(
|
||
cmd=['python3', str(INTERNAL_TOOLS / 'run_nav2.py'),
|
||
'--timeout', os.environ.get('SENTRY_NAV2_TIMEOUT', '120'), '--',
|
||
['map:=', map_yaml], 'use_sim_time:=true', 'autostart:=False',
|
||
['params_file:=', str(PKG_SHARE / 'config' / 'nav2_params.yaml')],
|
||
'use_composition:=False',
|
||
['use_localization:=', PythonExpression(["'", localization, "' == 'amcl'"])],
|
||
'serve_static_map:=True', 'use_keepout_zones:=False',
|
||
'use_speed_zones:=False', 'slam:=False'],
|
||
name='nav2', output='screen', condition=IfCondition(nav2_on), sigterm_timeout='20',
|
||
)
|
||
|
||
actions = [
|
||
DeclareLaunchArgument('localization', default_value='lio', choices=['lio', 'amcl']),
|
||
DeclareLaunchArgument('lio_mode', default_value='localization', choices=['mapping', 'localization']),
|
||
DeclareLaunchArgument(
|
||
'lio_map', default_value=os.environ.get('LIO_MAP') or lio_default_map,
|
||
description='Full-field localization map or generated/field_mapping.flmap in mapping mode',
|
||
),
|
||
DeclareLaunchArgument('lio_export_map', default_value=os.environ.get('LIO_EXPORT_MAP') or lio_map),
|
||
DeclareLaunchArgument('lio_point_cloud_topic',
|
||
default_value=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio'),
|
||
DeclareLaunchArgument('lio_initial_x', default_value='-5.0'),
|
||
DeclareLaunchArgument('lio_initial_y', default_value='3.0'),
|
||
DeclareLaunchArgument('lio_initial_z', default_value='0.0'),
|
||
DeclareLaunchArgument('lio_initial_yaw', default_value='0.0'),
|
||
OpaqueFunction(function=_validate_lio),
|
||
# ---------------- 参数 ----------------
|
||
DeclareLaunchArgument(
|
||
'headless', default_value='false',
|
||
description='true = Gazebo 服务端使用 EGL 渲染,无界面'),
|
||
DeclareLaunchArgument(
|
||
'nav2', default_value='true', description='false = 不起 Nav2'),
|
||
DeclareLaunchArgument(
|
||
'rviz', default_value='true', description='false = 不起 RViz'),
|
||
DeclareLaunchArgument(
|
||
'world', default_value='sentry_arena.sdf',
|
||
description='worlds/ 下的世界文件名'),
|
||
DeclareLaunchArgument(
|
||
'map', default_value='',
|
||
description='Nav2 栅格图 YAML,留空则从环境或场地包探测'),
|
||
DeclareLaunchArgument(
|
||
'field_root', default_value='',
|
||
description='场地包目录,留空则从环境或仓库探测'),
|
||
OpaqueFunction(function=_resolve_environment),
|
||
|
||
# ---------------- 环境变量 ----------------
|
||
SetEnvironmentVariable('FASTDDS_BUILTIN_TRANSPORTS',
|
||
dds_defaults(os.environ)['FASTDDS_BUILTIN_TRANSPORTS']),
|
||
SetEnvironmentVariable('GZ_SIM_RESOURCE_PATH', _gz_resource_path()),
|
||
SetEnvironmentVariable(
|
||
'GZ_PARTITION', os.environ.get('GZ_PARTITION') or 'sentry'),
|
||
SetEnvironmentVariable(
|
||
'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']),
|
||
# 给子进程保留数据包目录
|
||
SetEnvironmentVariable('SENTRY_SIM_SHARE', str(PKG_SHARE)),
|
||
OpaqueFunction(function=_preflight_nav2),
|
||
|
||
# ---------------- 1. Gazebo ----------------
|
||
OpaqueFunction(function=_start_gazebo),
|
||
|
||
# ---------------- 2. ros_gz 桥 ----------------
|
||
# 等到 /clock 出现再加载桥,否则 gz-transport 可能漏掉话题。
|
||
RegisterEventHandler(OnProcessExit(
|
||
target_action=bridge, on_exit=_on_bridge_exit,
|
||
)),
|
||
bridge,
|
||
|
||
# ---------------- 3. TF 树 ----------------
|
||
Node(
|
||
package='robot_state_publisher',
|
||
executable='robot_state_publisher',
|
||
name='robot_state_publisher',
|
||
output='screen',
|
||
parameters=[{
|
||
'robot_description': ParameterValue(
|
||
robot_description, value_type=str),
|
||
'use_sim_time': True,
|
||
}],
|
||
),
|
||
|
||
# ---------------- 4. odom -> base_link ----------------
|
||
# Gazebo 的麦轮插件只发 odometry 消息、不发 TF
|
||
# SENTRY_ODOM_SCALE != 1.0 时给里程计加比例误差(演示 AMCL 纠正漂移用)。
|
||
# 这里是构建期读环境变量、直接拼成普通字符串 ——
|
||
# 如果写成嵌套列表 ['-p', 'odom_scale:=', v],会被拼成 "-podom_scale:=1.15"(没空格),
|
||
# rclpy 的参数解析会直接报错。
|
||
ExecuteProcess(
|
||
cmd=[PathJoinSubstitution([BIN_DIR, 'odom_tf']), '--ros-args',
|
||
'-p', 'use_sim_time:=true',
|
||
'-p', 'odom_scale:=' + os.environ.get('SENTRY_ODOM_SCALE', '1.0')],
|
||
name='odom_tf',
|
||
output='screen',
|
||
),
|
||
|
||
# ---------------- 5. /cmd_vel 改名转发 ----------------
|
||
# 插件订阅 /model/sentry/cmd_vel,而桥只支持两端同名
|
||
OpaqueFunction(function=_start_velocity_relay),
|
||
|
||
# ---------------- 6. 点云自滤 ----------------
|
||
# 本工程没有 ament 注册,不能 ros2 run,直接跑 xmake 产物
|
||
ExecuteProcess(
|
||
cmd=[PathJoinSubstitution([BIN_DIR, 'self_filter']),
|
||
'--ros-args', '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true'],
|
||
name='self_filter',
|
||
output='screen',
|
||
),
|
||
|
||
ExecuteProcess(
|
||
cmd=[PathJoinSubstitution([BIN_DIR, 'field_localization_node']), '--ros-args',
|
||
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true',
|
||
'-p', ['point_cloud_topic:=', LaunchConfiguration('lio_point_cloud_topic')],
|
||
'-p', ['mode:=', lio_mode], '-p', ['map_path:=', lio_map],
|
||
'-p', ['export_map_path:=', lio_export], '-p', 'publish_map_to_odom:=true',
|
||
'-p', "diagnostics_path:='" + os.environ.get('LIO_TRACE_PATH', '') + "'",
|
||
'-p', ['initial_x:=', LaunchConfiguration('lio_initial_x')],
|
||
'-p', ['initial_y:=', LaunchConfiguration('lio_initial_y')],
|
||
'-p', ['initial_z:=', LaunchConfiguration('lio_initial_z')],
|
||
'-p', ['initial_yaw:=', LaunchConfiguration('lio_initial_yaw')]],
|
||
name='field_localization', output='screen',
|
||
condition=IfCondition(PythonExpression(["'", localization, "' == 'lio'"])),
|
||
),
|
||
|
||
# ---------------- 7. map -> field 恒等别名 ----------------
|
||
# map -> field:恒等变换(map 已以场地中心为原点)
|
||
Node(
|
||
package='tf2_ros',
|
||
executable='static_transform_publisher',
|
||
name='map_to_field',
|
||
arguments=['--x', '0.0', '--y', '0.0', '--z', '0.0',
|
||
'--yaw', '0.0', '--pitch', '0.0', '--roll', '0.0',
|
||
'--frame-id', 'map', '--child-frame-id', 'field'],
|
||
parameters=[{'use_sim_time': True}],
|
||
output='screen',
|
||
),
|
||
|
||
# ---------------- 8. 静态地图服务 ----------------
|
||
# 两个分支均由 bringup 提供 map_server,只有 AMCL 分支启动 amcl。
|
||
# 这里再起一份会**同名冲突**(lifecycle_manager 崩在 createLifecycleServiceServers)。
|
||
|
||
# ---------------- 9. Nav2 ----------------
|
||
RegisterEventHandler(OnProcessExit(
|
||
target_action=navigation,
|
||
on_exit=[EmitEvent(event=Shutdown(reason='Nav2 supervisor exited'))],
|
||
)),
|
||
RegisterEventHandler(OnProcessExit(
|
||
target_action=navigation_ready,
|
||
on_exit=lambda event, context: [navigation] if event.returncode == 0 else [
|
||
EmitEvent(event=Shutdown(reason='simulation clock/TF readiness failed'))],
|
||
)),
|
||
navigation_ready,
|
||
|
||
# ---------------- 10. RViz ----------------
|
||
Node(
|
||
package='rviz2',
|
||
executable='rviz2',
|
||
name='rviz2',
|
||
arguments=['-d', str(PKG_SHARE / 'config' / 'sentry.rviz')],
|
||
parameters=[{'use_sim_time': True}],
|
||
output='screen',
|
||
condition=IfCondition(rviz_on),
|
||
),
|
||
|
||
LogInfo(msg=[
|
||
'\n[sentry_arena] 坐标系:',
|
||
'\n map 场地中心 = (0,0),范围 x[-6,6] y[-4,4],出生点在 (-5.0, 3.0)',
|
||
'\n field 与 map 相同(恒等变换,保留给决策代码用)',
|
||
'\n[sentry_arena] 体检:python3 tools/check_stack.py',
|
||
]),
|
||
]
|
||
|
||
return LaunchDescription(actions)
|