对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现

This commit is contained in:
mzx committed 2026-11-23 14:32:42 +08:00
1 parent 0602144ac5
commit 4502296915
70 files changed
+2652 -1298

No files matched your search

+91 -68
View File
@@ -53,12 +53,14 @@ from launch.actions import (
LogInfo,
OpaqueFunction,
SetEnvironmentVariable,
SetLaunchConfiguration,
)
from launch.conditions import IfCondition
from launch.event_handlers import OnProcessExit
from launch.events import Shutdown
from launch.substitutions import (LaunchConfiguration,
PathJoinSubstitution, PythonExpression)
from launch.substitutions import (
EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, PathJoinSubstitution, PythonExpression,
)
from launch_ros.actions import Node
from launch_ros.parameter_descriptions import ParameterValue
@@ -68,29 +70,61 @@ from launch_ros.parameter_descriptions import ParameterValue
PKG_SHARE = Path(__file__).resolve().parents[1] # src/sentry_sim
WS = Path(__file__).resolve().parents[3] # 仓库根
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 覆盖)。
# `tools/` 不是 Python 包(本工程不用 ament),所以直接把目录塞进 sys.path。
if str(WS / 'tools') not in sys.path:
sys.path.insert(0, str(WS / 'tools'))
# 从仓库源码加载工具模块。
if str(TOOLS_DIR) not in sys.path:
sys.path.insert(0, str(TOOLS_DIR))
import project_env # noqa: E402 (必须在 sys.path 调整之后导入)
from dds_environment import defaults as dds_defaults # noqa: E402
from _internal.dds_environment import defaults as dds_defaults # noqa: E402
BIN_DIR = project_env.find_bin_dir(WS)
GZ_VERSION_ARGS = project_env.gz_version_args()
BIN_DIR = LaunchConfiguration('_sentry_bin_dir')
GZ_MAJOR_VERSION = LaunchConfiguration('_sentry_gz_major_version')
_FIELD_ROOT = project_env.find_field_root(WS)
if _FIELD_ROOT is None:
raise RuntimeError(
'找不到场地迁移包。设 SENTRY_FIELD_ROOT=<含 src/guodong_sentry_sim 的目录>。')
DEFAULT_FIELD_ROOT = str(_FIELD_ROOT)
_MAP_YAML = project_env.find_map_yaml(_FIELD_ROOT)
if _MAP_YAML is None:
raise RuntimeError(f'{_FIELD_ROOT} 下找不到任何栅格图 yaml。设 SENTRY_MAP_YAML=<路径>。')
DEFAULT_MAP_YAML = str(_MAP_YAML)
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', '-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 _robot_description():
@@ -126,12 +160,15 @@ def _validate_lio(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(WS / 'tools' / 'nav2_startup.py'), '--preflight'],
subprocess.run(['python3', str(INTERNAL_TOOLS / 'nav2_startup.py'), '--preflight'],
env=dict(context.environment), check=True)
return []
@@ -141,7 +178,7 @@ def _start_velocity_relay(context):
localization = LaunchConfiguration('localization').perform(context)
input_topic = '/cmd_vel' if navigation else context.environment.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel')
return [ExecuteProcess(
cmd=[str(BIN_DIR / 'cmd_vel_relay'),
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()}',
@@ -154,31 +191,37 @@ def generate_launch_description():
headless = LaunchConfiguration('headless')
nav2 = LaunchConfiguration('nav2')
rviz = LaunchConfiguration('rviz')
world = LaunchConfiguration('world')
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" 当真值
is_headless = PythonExpression(["'", headless, "'.lower() in ('true', '1')"])
is_gui = PythonExpression(["'", headless, "'.lower() not in ('true', '1')"])
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 = _robot_description()
bridge = ExecuteProcess(
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
name='ros_gz_bridge', output='screen',
)
navigation_ready = ExecuteProcess(
cmd=['python3', str(WS / 'tools' / 'wait_navigation_ready.py')],
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(WS / 'tools' / 'run_nav2.py'),
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')],
@@ -192,8 +235,13 @@ def generate_launch_description():
actions = [
DeclareLaunchArgument('localization', default_value='lio', choices=['lio', 'amcl']),
DeclareLaunchArgument('lio_mode', default_value='localization', choices=['mapping', 'localization']),
DeclareLaunchArgument('lio_map', default_value=str(WS / 'generated' / 'field.flmap')),
DeclareLaunchArgument('lio_export_map', default_value=lio_map),
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'),
@@ -211,18 +259,19 @@ def generate_launch_description():
'world', default_value='sentry_arena.sdf',
description='worlds/ 下的世界文件名'),
DeclareLaunchArgument(
'map', default_value=DEFAULT_MAP_YAML,
description='Nav2 用的栅格图 yaml'),
'map', default_value='',
description='Nav2 栅格图 YAML,留空则从环境或场地包探测'),
DeclareLaunchArgument(
'field_root', default_value=DEFAULT_FIELD_ROOT,
description='迁移包(guodong_sentry_sim)所在目录'),
'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', 'sentry')),
'GZ_PARTITION', os.environ.get('GZ_PARTITION') or 'sentry'),
SetEnvironmentVariable(
'ROS_DOMAIN_ID', dds_defaults(os.environ)['ROS_DOMAIN_ID']),
# URDF 的网格路径靠它解析;tools/check_stack.py 也读它
@@ -230,41 +279,14 @@ def generate_launch_description():
OpaqueFunction(function=_preflight_nav2),
# ---------------- 1. Gazebo ----------------
# 用 run_gz.sh 包一层:它会清掉 LD_LIBRARY_PATH,
# 否则 source 过 ROS 之后连系统版 gz 也会加载 vendor 库(缺 cpu-lidar 插件)
# ⚠️ cmd 列表里的每个元素是**独立 argv**,不会自动拼接。
# world 是 LaunchConfiguration,所以必须用 PathJoinSubstitution
# 合成成一个参数,否则 gz 会收到三个散参数
# (报 "The following arguments were not expected: xxx.sdf /")。
ExecuteProcess(
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-r',
*GZ_VERSION_ARGS,
PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])],
name='gazebo',
output='screen',
condition=IfCondition(is_gui),
),
# ⚠️ headless 也必须带 -r(启动即运行)。
# 少了 -r 的话 gazebo 以**暂停**状态启动:物理引擎不步进 →
# MecanumDrive 不发 /odom、传感器不出数据,但 /clock 照常发布,
# 表面上一切正常,实际整条数据链是死的。
ExecuteProcess(
cmd=[str(SCRIPTS / 'run_gz.sh'), 'sim', '-s', '-r',
*GZ_VERSION_ARGS,
PathJoinSubstitution([str(PKG_SHARE / 'worlds'), world])],
name='gazebo',
output='screen',
condition=IfCondition(is_headless),
),
OpaqueFunction(function=_start_gazebo),
# ---------------- 2. ros_gz 桥 ----------------
# bridge_after_gz.sh 自己轮询 /clock 再起桥:
# gz-transport 的发现不回补,桥先于话题存在就订阅会一直收不到数据
ExecuteProcess(
cmd=[str(SCRIPTS / 'bridge_after_gz.sh')],
name='ros_gz_bridge',
output='screen',
),
# 等到 /clock 出现再加载桥,否则 gz-transport 可能漏掉话题。
RegisterEventHandler(OnProcessExit(
target_action=bridge, on_exit=_on_bridge_exit,
)),
bridge,
# ---------------- 3. TF 树 ----------------
Node(
@@ -286,7 +308,7 @@ def generate_launch_description():
# 如果写成嵌套列表 ['-p', 'odom_scale:=', v],会被拼成 "-podom_scale:=1.15"(没空格),
# rclpy 的参数解析会直接报错。
ExecuteProcess(
cmd=[str(BIN_DIR / 'odom_tf'), '--ros-args',
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',
@@ -300,15 +322,16 @@ def generate_launch_description():
# ---------------- 6. 点云自滤 ----------------
# 本工程没有 ament 注册,不能 ros2 run,直接跑 xmake 产物
ExecuteProcess(
cmd=[str(BIN_DIR / 'self_filter'),
cmd=[PathJoinSubstitution([BIN_DIR, 'self_filter']),
'--ros-args', '-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true'],
name='self_filter',
output='screen',
),
ExecuteProcess(
cmd=[str(BIN_DIR / 'field_localization_node'), '--ros-args',
'-p', 'use_sim_time:=true', '-p', 'reliable_clouds:=true', '-p', 'point_cloud_topic:=/scan/points_filtered',
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', '') + "'",