对tools进行了整理,Xmake也改为相对路径,在线 LiDAR-IMU 定位器实现
This commit is contained in:
1 parent
0602144ac5
commit
4502296915
70 files changed
+2652
-1298
No files matched your search
+163
-63
@@ -1,76 +1,176 @@
|
||||
# tools/
|
||||
|
||||
模型转换、调试、演示用的小工具(都是独立脚本,不参与构建)。
|
||||
最后更新:2026-11-22
|
||||
|
||||
## 模型相关
|
||||
构建脚本、启动链内部件、验收脚本和回归测试。
|
||||
**除 `check_stack.py` 需要仿真在运行中外,其余命令都可以在仿真没启动时执行。**
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(唯一的建模入口) |
|
||||
| `decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab/Blender) |
|
||||
| `gen_sdf.sh` | URDF(xacro) → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
> 以下命令**全部从仓库根目录**运行。看到 `AttributeError` / `ModuleNotFoundError` 时
|
||||
> 先确认是不是在 `tools/` 里面敲的。
|
||||
|
||||
## 体检
|
||||
## 目录结构
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `check_dds.sh` | ★ Fast DDS 体检:`/dev/shm` 残留段、进程、DDS 环境变量。加 `--clean` 清理残留 |
|
||||
| `check_stack.py` | ★ **只读体检**:10 个 lifecycle 节点状态 + 节点总览(含 `amcl`、`lifecycle_manager`)+ 话题 + TF + 真值对照,一条命令问清"现在这套栈健康吗" |
|
||||
| `project_env.py` | ★ 路径/版本探测。**排查"路径不对"先跑它**。支持直接取单个值供脚本/文档拼接:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup`,例:`NAV=$(python3 tools/project_env.py --bin-dir)/nav_client`。它同时被 `launch/` 和 `check_stack.py` import,**是依赖库不只是工具** |
|
||||
|
||||
## 静态审计
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `audit_absolute_paths.py` | 扫全仓的写死绝对路径(`/opt/ros/…`、`/home/…`、`/usr/…`)。`--all` 出完整报告 |
|
||||
|
||||
> ⚠️ **这个工具目前噪音很大**:它把 ROS 话题名也当成绝对路径,全仓会产生
|
||||
> **4700+ 条**命中(`/wait`、`/odom`、`/dev/shm` …),真正要看的只有
|
||||
> `ROS 安装路径` / `用户目录路径` 这两类。查的时候这样过滤:
|
||||
> `python3 tools/audit_absolute_paths.py --all | grep -A1 'ROS 安装路径\|用户目录路径'`
|
||||
|
||||
> **本目录里没有 `nav_client`。** 发 Nav2 目标用的是 **xmake 编译出的二进制**,
|
||||
> 源码在 `src/sentry_nav/src/nav_client.cpp`,产物**固定落在 `build/bin/nav_client`**
|
||||
> (xmake 里每个 target 都 `set_targetdir("$(builddir)/bin")`,故意不用带平台三元组的默认目录)。
|
||||
> 它带地图预检(占据值 ≥65 / 未知格 / 净空 <0.5 m 直接拦下),用法见
|
||||
> [`../docs/操作手册.md`](../docs/操作手册.md) §3。
|
||||
|
||||
## 构建 / 编辑器
|
||||
|
||||
**这里已经没有构建相关的脚本了。**
|
||||
|
||||
`compile_commands.json` 由 xmake 在**每次构建后自动重写**
|
||||
(根 `xmake.lua` 里的 `plugin.compile_commands.autoupdate` 规则),
|
||||
以前那个 `gen_compdb.sh`(合并 colcon 分包产物)已随去 colcon 一起删除。
|
||||
|
||||
改了源码结构后只要跑一次 `xmake`,再在 VS Code 里
|
||||
`Ctrl+Shift+P → clangd: Restart language server`。详见 `../.vscode/README.md`。
|
||||
|
||||
## 典型用法
|
||||
|
||||
```bash
|
||||
# 机械给了新装配体
|
||||
python3 tools/build_vehicle.py --src "/run/media/mzxiang/CPBA_X64FRE/装配车" --out src/sentry_sim/meshes/full
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025
|
||||
```text
|
||||
tools/
|
||||
├── project_env.py 环境探测(库和 CLI),供 Shell、Python launch 和工具共用
|
||||
├── check_stack.py 整套栈体检(⚠️ 需要仿真在跑)
|
||||
├── check_dds.sh DDS 环境 / 残留进程检查
|
||||
├── capture_lio.py 录制 LIO 建图 / 评估数据
|
||||
├── build_vehicle.py 整车 STL → 仿真网格 + 布局 JSON
|
||||
├── decimate.py 网格降面
|
||||
├── gen_sdf.sh xacro → SDF / URDF
|
||||
├── _internal/ 启动链内部件;被 sentry_up.sh / launch / 测试 import
|
||||
├── validation/ 验收脚本(会真的拉起 Gazebo,跑完整流程)
|
||||
└── tests/ 回归测试(不碰 Gazebo 运动,最快的检查)
|
||||
```
|
||||
|
||||
> 建模类脚本是**离线**的,不需要起仿真。体检类脚本要先按根目录 README 把仿真跑起来,
|
||||
> 再在另一个终端执行。
|
||||
## 一、会被自动调用的(不用手动跑)
|
||||
|
||||
## 2026-11-21 精简掉了什么
|
||||
| 工具 | 谁调它 | 干什么 |
|
||||
|---|---|---|
|
||||
| `project_env.py` | Shell 环境库、Python launch、体检、录包、验收和测试 | 探测 ROS setup / `build/bin` / 场地包 / 地图 / gz 版本,**一个都不写死** |
|
||||
| `_internal/dds_environment.py` | `sentry_up.sh`(`--shell`)、`sentry_arena.launch.py`、`nav2_startup.py`、`validate_lio_navigation.py`、`tests/test_nav2_startup.py` | DDS 默认值统一出口(`rmw_implementation`、`ROS_DOMAIN_ID`、共享内存传输) |
|
||||
| `_internal/resolve_ros_includes.py` | `src/sentry_nav/xmake.lua`、`src/field_localization/xmake.lua` | 经 ament index 解析 ROS 包的头文件目录,喂给 xmake |
|
||||
| `_internal/nav2_startup.py` | `sentry_up.sh`、`sentry_arena.launch.py` | Nav2 域预检(`--preflight`)+ 发现门控 + 有界就绪检查 |
|
||||
| `_internal/run_nav2.py` | `sentry_up.sh`、`sentry_arena.launch.py`、`tests/test_nav2_supervisor.py` | **只监管自己那组 Nav2 进程**;有界重试后才放行导航 |
|
||||
| `_internal/wait_navigation_ready.py` | `sentry_up.sh`、`sentry_arena.launch.py` | 等到仿真时钟 + 基础机器人 TF 就绪才返回 |
|
||||
|
||||
一次性排查脚本已全部删除(都在 git 历史里,需要时 `git show <commit>:tools/<名字>` 能捞回来):
|
||||
**这六个是被 `sentry_up.sh` 和 launch 拉起来的。改它们等于改启动行为,改完必须重跑一次启动验证。**
|
||||
|
||||
| 删掉的 | 原因 |
|
||||
## 二、手动入口(日常用)
|
||||
|
||||
| 命令 | 用途 |
|
||||
|---|---|
|
||||
| `probe_all.py` / `probe_sub.py` | 已被 `check_stack.py` 完全覆盖 |
|
||||
| `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 同一次排查的三代尸体 |
|
||||
| `smoke_probe.py` | 等激活+收点云+发目标 → `check_stack.py` + `nav_client` |
|
||||
| `nav_diag.py` | 同 `check_stack.py` §2/§3,且还用旧坐标系 |
|
||||
| `cloud_compare.py` | 0 引用 |
|
||||
| `send_goal.py` | **空炮**:往 `/goal_pose` 发,Nav2 没有任何节点订阅它 |
|
||||
| `tf_watch.py` / `scan_probe.py` / `cloud_probe.py` / `free_goals.py` / `mark_field_center.py` / `amcl_drift_demo.py` / `demo.py` / `drive_demo.py` | 精简(替代做法见各文档:用 `ros2 topic echo`、`tf2_echo`、RViz 的 costmap 显示、`ros2 topic pub /cmd_vel`) |
|
||||
| `build_meshes.py` / `build_gimbal.py` | 旧版分件建模(只处理「底盘」或「云台」单独导出),已被 `build_vehicle.py` 的整车装配体方案取代 |
|
||||
| `python3 tools/check_stack.py` | **整套栈体检**:生命周期、话题、TF、Gazebo 真值对照。⚠️ 仿真必须在跑,否则会卡在等服务上 |
|
||||
| `tools/check_dds.sh` | DDS 环境、`/dev/shm`、残留进程。`--clean` 清理残留(**确认所有 ROS 进程已停**再用) |
|
||||
| `python3 tools/project_env.py` | 打印全部探测结果。单项取值:`--bin-dir` / `--field` / `--map` / `--gz` / `--gz-version-args` / `--ros-setup` |
|
||||
| `python3 tools/capture_lio.py --help` | 录制建图(`--profile mapping`)或评估(`--profile evaluation`)数据 |
|
||||
| `python3 tools/build_vehicle.py --help` | 整车装配体 STL → 仿真网格 + 布局 JSON。`--dry-run` 只打印分类结果 |
|
||||
| `python3 tools/decimate.py --help` | 顶点聚类降面:`decimate.py --grid 0.01 src.stl dst.stl` |
|
||||
| `tools/gen_sdf.sh` | xacro → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
|
||||
> **删脚本不影响已有产物**:`src/sentry_sim/meshes/base.stl`、`wheel.stl` 是已经生成好的,
|
||||
> URDF 引用的是这些文件。重跑建模用 `build_vehicle.py` 即可。
|
||||
**发导航目标不用工具脚本**,用 xmake 产物 `build/bin/nav_client`。
|
||||
`xmake` 构建会自动刷新 `compile_commands.json`(clangd 靠它跳转)。
|
||||
|
||||
## 三、库模块(有 `--help` 不代表要单独跑)
|
||||
|
||||
| 模块 | 被谁 import | 说明 |
|
||||
|---|---|---|
|
||||
| `_internal/arena_grid.py`、`_internal/arena_survey.py` | `capture_lio.py`、`validate_lio_navigation.py` | 栅格可达性、隔离仿真测站和雷达地图生成 |
|
||||
| `validation/lio_metrics.py` | `validate_lio_navigation.py` | ATE / RPE / 圆柱间隙计算。**没有 CLI**,直接跑只会静默退出 |
|
||||
| `project_env.py` | 见上 | 既当库又当命令 |
|
||||
| `_internal/dds_environment.py` | 见上 | 既当库又当命令 |
|
||||
|
||||
## 四、验收脚本(会真的拉起 Gazebo)
|
||||
|
||||
| 命令 | 用途 | 耗时 |
|
||||
|---|---|---|
|
||||
| `python3 tools/validation/verify_lio_stack.py --map <flmap> --output <dir>` | **只验栈、不发运动指令**:Gazebo + LIO + Nav2 能不能一起起来。`--launcher {shell,python}` 选启动入口,`--rviz` 加上离屏 RViz 负载 | 分钟级 |
|
||||
| `python3 tools/validation/validate_lio_navigation.py --map <flmap> --output <dir>` | **真跑导航并用仿真真值打分**。`--scenario {clear,cylinder,blocked,lidar_loss}` 选场景,`--full-field` 检查每个 1 m 瓦片的代表目标并跑全场路线,圆柱场景可调 `--obstacle-x/y/radius`,`--domain` 指定 ROS 域 | 分钟级 |
|
||||
| `python3 tools/validation/run_lio_matrix.py --launcher {shell,python} --map <flmap> --output <dir>` | 每条路线/每个启动器跑 3 次冷启动,外加一次"目标不可达"检查。`--domain` 同上 | **十几分钟** |
|
||||
|
||||
三个都要给 `--map`(例如 `src/sentry_sim/maps/field_full.flmap`)和 `--output`,但**输出目录的要求不同**:
|
||||
|
||||
| 脚本 | 对 `--output` 的要求 |
|
||||
|---|---|
|
||||
| `validate_lio_navigation.py` | **必须不存在**(已存在直接报错) |
|
||||
| `run_lio_matrix.py` | **必须不存在**(`output must be new`) |
|
||||
| `verify_lio_stack.py` | **允许已存在**(会自动 `mkdir -p`) |
|
||||
|
||||
脚本自行分配隔离的 `ROS_DOMAIN_ID`,**不会和你正在跑的仿真撞车**。
|
||||
|
||||
隔离 Gazebo 空场的全场建图与东南回放:
|
||||
|
||||
```bash
|
||||
python3 tools/capture_lio.py --profile mapping --full-field \
|
||||
--output generated/full_survey --map generated/field_full.flmap
|
||||
python3 tools/validation/validate_lio_navigation.py --full-field --launcher shell \
|
||||
--lio-cloud-topic /scan/points_lio \
|
||||
--map generated/field_full.flmap --output generated/full_shell
|
||||
python3 tools/validation/compare_lio_maps.py --dataset generated/full_shell/dataset \
|
||||
--baseline generated/field.flmap --candidate generated/field_full.flmap \
|
||||
--output generated/southeast_comparison
|
||||
```
|
||||
|
||||
全场建图按已知坐标在隔离实例布置测站,使用与在线 LIO 相同的自滤点云。测站位置由命令指定,Gazebo 真值核对实际到位。在线验收使用另一实例,机器人连续行驶。回放需要至少 10 帧独立录制的东南扫描(`x >= 4`、`y <= -1.5`)。
|
||||
|
||||
## 五、回归测试
|
||||
|
||||
按跑得快 → 慢排:
|
||||
|
||||
| 命令 | 需要什么 | 实测 |
|
||||
|---|---|---|
|
||||
| `python3 tools/tests/test_project_env.py` | Python 3 和 Bash | 临时文件和假 Gazebo 覆盖路径、退出码、版本超时与桥等待 |
|
||||
| `python3 tools/tests/test_nav2_supervisor.py` | **什么都不需要**(不碰 ROS、不碰 Gazebo) | ✅ 5 项检查,约 1 秒 |
|
||||
| `python3 tools/tests/test_nav2_startup.py` | ROS 环境(起隔离 domain 的服务) | ✅ 15 项检查 |
|
||||
| `python3 tools/tests/test_motion_interlock.py` | ROS 环境 + `build/bin/cmd_vel_relay`(`--binary` 可指定) | 需已构建 |
|
||||
|
||||
**`test_nav2_supervisor.py` 是最便宜的冒烟测试**:改完 `run_nav2.py` 先跑它。
|
||||
|
||||
### 和 C++ 单测的关系
|
||||
|
||||
C++ 侧的单测走 xmake:
|
||||
|
||||
```bash
|
||||
xmake test # 全部
|
||||
xmake test test_waypoint_sequencer/default # 单个(必须带 /default)
|
||||
```
|
||||
|
||||
三个带 `add_tests` 的 target:`test_self_filter_core`、`test_waypoint_sequencer`、`test_geometry`。
|
||||
|
||||
Python 回归测试用上表中的命令单独运行。
|
||||
|
||||
## 六、加新工具时的规矩
|
||||
|
||||
1. **放哪个目录**
|
||||
- 只给启动链用、且会被 import → `_internal/`
|
||||
- 手动跑、会拉起 Gazebo → `validation/`
|
||||
- 手动跑、不碰 Gazebo → `tests/`
|
||||
- 构建期用的 → 本目录顶层
|
||||
|
||||
2. **跨目录 import 必须自己铺 `sys.path`**,仓库里没有安装成包:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal'))
|
||||
```
|
||||
|
||||
3. **别复制公共逻辑**。要读环境变量 / 找产物目录,一律走 `project_env`;
|
||||
要设 DDS 参数,一律走 `_internal/dds_environment.py`。这两处各只有一份实现。
|
||||
|
||||
4. **本文件是唯一索引**。加了工具就在上面的表里补一行,删了工具就把那行删掉
|
||||
—— 否则会出现「文档里有一堆打不开的文件」。
|
||||
|
||||
## 七、这个目录的历史
|
||||
|
||||
`git log --oneline -- tools/` 能看到两次大整理:
|
||||
|
||||
**第一次:删掉 21 个文件**(`git log --diff-filter=D --name-only -- 'tools/*.py' 'tools/*.sh'` 可复现)
|
||||
|
||||
| 类别 | 文件 | 为什么删 |
|
||||
|---|---|---|
|
||||
| 一次性诊断(14) | `probe_all` `probe_sub` `probe_cmd` `probe_cmd2` `cmd_probe_all` `smoke_probe` `nav_diag` `cloud_compare` `cloud_probe` `scan_probe` `tf_watch` `send_goal` `free_goals` `mark_field_center` | 功能被 `check_stack.py` 和 `validation/` 取代 |
|
||||
| 演示(3) | `demo` `drive_demo` `amcl_drift_demo` | 一次性演示,舞台已拆 |
|
||||
| 构建辅助(3) | `build_meshes` `build_gimbal` `gen_compdb.sh` | 前两个并入 `build_vehicle.py`;`compile_commands.json` 改由 xmake 自动刷新 |
|
||||
| 节点迁移(1) | `nav_client.py` | 重写成 C++,在 `src/sentry_nav/src/` |
|
||||
|
||||
**第二次:扁平布局收成三组**
|
||||
|
||||
```
|
||||
_internal/ 启动链内部件(被 shell / launch / 测试 import,一般不当命令用)
|
||||
validation/ 会拉起 Gazebo 的验收脚本
|
||||
tests/ 不碰 Gazebo 的回归测试
|
||||
```
|
||||
|
||||
顺带删了已跑完使命的 `audit_absolute_paths.py`(可移植性重构的一次性审计工具)。
|
||||
|
||||
如果发现 `tools/` 里还残留着已删工具的 `.pyc`,可以安全清掉:
|
||||
|
||||
```bash
|
||||
find . -name __pycache__ -type d -not -path './build/*' -exec rm -rf {} +
|
||||
```
|
||||
|
||||
(`.gitignore` 已经排除 `__pycache__/` 和 `*.pyc`,git 从来不收它们。
|
||||
无源码的 `.pyc` 放在 `__pycache__/` 里也**不会被 import** —— Python 3 的无源码导入要求
|
||||
`.pyc` 直接放在目录里,所以这些是纯死数据。)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Static arena clearance and deterministic routes for isolated simulation tests."""
|
||||
|
||||
from collections import deque
|
||||
from functools import cache
|
||||
import heapq
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import yaml
|
||||
|
||||
|
||||
START = (-5.0, 3.0)
|
||||
SURVEY_GOALS = ((-5., 0.), (-5., -3.), (0., -3.), (5., -3.), (5., 0.), (5., 3.),
|
||||
(0., 3.), (0., 0.), (0., -3.), (-5., -3.), START)
|
||||
# Revisit the reported east route in both directions before covering the perimeter.
|
||||
ARENA_GOALS = ((0., 0.), (5., -3.), (0., 0.), (5., -3.), (5., 0.), (5., 3.),
|
||||
(0., 3.), START, (-5., 0.), (-5., -3.), (0., -3.), (0., 0.), START)
|
||||
|
||||
|
||||
class ArenaGrid:
|
||||
def __init__(self, map_yaml):
|
||||
path = Path(map_yaml)
|
||||
config = yaml.safe_load(path.read_text())
|
||||
self.resolution = float(config['resolution'])
|
||||
self.origin = tuple(config['origin'][:2])
|
||||
if config.get('mode', 'trinary') != 'trinary' or config['origin'][2] != 0:
|
||||
raise ValueError('arena coverage expects an unrotated trinary occupancy map')
|
||||
with (path.parent / config['image']).open('rb') as image:
|
||||
def header():
|
||||
line = image.readline().split(b'#', 1)[0].strip()
|
||||
while not line:
|
||||
raw = image.readline()
|
||||
if not raw:
|
||||
raise ValueError('truncated PGM header')
|
||||
line = raw.split(b'#', 1)[0].strip()
|
||||
return line
|
||||
if header() != b'P5':
|
||||
raise ValueError('expected binary PGM occupancy map')
|
||||
width, height = map(int, header().split())
|
||||
if header() != b'255':
|
||||
raise ValueError('expected 8-bit PGM occupancy map')
|
||||
pixels = np.frombuffer(image.read(), dtype=np.uint8).reshape(height, width)
|
||||
self.size = (height, width)
|
||||
probability = pixels / 255 if config.get('negate', 0) else 1 - pixels / 255
|
||||
self.free = (probability < config['free_thresh'])[::-1]
|
||||
|
||||
def cell(self, point):
|
||||
x, y = point
|
||||
return (math.floor((y-self.origin[1])/self.resolution),
|
||||
math.floor((x-self.origin[0])/self.resolution))
|
||||
|
||||
def point(self, cell):
|
||||
y, x = cell
|
||||
return (self.origin[0]+(x+0.5)*self.resolution,
|
||||
self.origin[1]+(y+0.5)*self.resolution)
|
||||
|
||||
def neighbors(self, cell):
|
||||
y, x = cell
|
||||
h, w = self.size
|
||||
for i, j in ((y-1,x),(y+1,x),(y,x-1),(y,x+1)):
|
||||
if 0 <= i < h and 0 <= j < w:
|
||||
yield i, j
|
||||
|
||||
@cache
|
||||
def clear(self, clearance):
|
||||
radius = math.ceil(clearance/self.resolution)
|
||||
padded = np.pad(self.free, radius)
|
||||
h, w = self.size
|
||||
mask = self.free.copy()
|
||||
for y in range(-radius, radius+1):
|
||||
for x in range(-radius, radius+1):
|
||||
if math.hypot(x, y)*self.resolution <= clearance + 1e-10:
|
||||
mask &= padded[radius+y:radius+y+h, radius+x:radius+x+w]
|
||||
return mask
|
||||
|
||||
def coverage(self):
|
||||
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint.
|
||||
travel = self.clear(math.hypot(0.325, 0.270))
|
||||
start = self.cell(START)
|
||||
if not travel[start]:
|
||||
raise ValueError('spawn pose fails the footprint clearance check')
|
||||
connected = np.zeros(self.size, dtype=bool)
|
||||
connected[start] = True
|
||||
queue = deque([start])
|
||||
while queue:
|
||||
for cell in self.neighbors(queue.popleft()):
|
||||
if travel[cell] and not connected[cell]:
|
||||
connected[cell] = True
|
||||
queue.append(cell)
|
||||
targets = connected & self.clear(0.50)
|
||||
wide = self.clear(0.65)
|
||||
tiles = {}
|
||||
for cell in zip(*np.nonzero(targets)):
|
||||
point = self.point(cell)
|
||||
grid = tuple(map(math.floor, point))
|
||||
score = (not wide[cell], math.dist(point, (grid[0]+0.5, grid[1]+0.5)), point)
|
||||
if grid not in tiles or score < tiles[grid]:
|
||||
tiles[grid] = score
|
||||
ys, xs = np.nonzero(connected)
|
||||
return {'reachable_cells': int(connected.sum()), 'eligible_goal_cells': int(targets.sum()),
|
||||
'reachable_area_m2': float(connected.sum() * self.resolution**2),
|
||||
'center_coordinate_bounds_m': [self.point((min(ys), min(xs))),
|
||||
self.point((max(ys), max(xs)))],
|
||||
'disconnected_goal_cells': int((self.clear(0.50)&~connected).sum()),
|
||||
'resolution_m': self.resolution,
|
||||
'samples': [tiles[tile][2] for tile in sorted(tiles)]}
|
||||
|
||||
def route(self, anchors, clearance=0.55):
|
||||
safe = self.clear(clearance)
|
||||
points = [START]
|
||||
for target in anchors:
|
||||
start, end = self.cell(points[-1]), self.cell(target)
|
||||
if not safe[start] or not safe[end]:
|
||||
raise ValueError(f'unsafe survey anchor {points[-1]} -> {target}')
|
||||
frontier = [(0, 0, start)]
|
||||
distance = {start: 0}
|
||||
previous = {}
|
||||
while frontier:
|
||||
_, cost, node = heapq.heappop(frontier)
|
||||
if node == end:
|
||||
break
|
||||
if cost != distance[node]:
|
||||
continue
|
||||
for cell in self.neighbors(node):
|
||||
if safe[cell] and cost+1 < distance.get(cell, math.inf):
|
||||
distance[cell] = cost+1
|
||||
previous[cell] = node
|
||||
estimate = abs(cell[0]-end[0])+abs(cell[1]-end[1])
|
||||
heapq.heappush(frontier, (cost+1+estimate, cost+1, cell))
|
||||
else:
|
||||
raise ValueError(f'no survey route from {points[-1]} to {target}')
|
||||
cells = [end]
|
||||
while cells[-1] != start:
|
||||
cells.append(previous[cells[-1]])
|
||||
candidates = [self.point(c) for c in reversed(cells[1:-1])] + [target]
|
||||
index = 0
|
||||
while index < len(candidates):
|
||||
a = points[-1]
|
||||
# Advance to the furthest visible waypoint along the grid path.
|
||||
for last in range(len(candidates)-1, index-1, -1):
|
||||
b = candidates[last]
|
||||
count = max(1, math.ceil(2*math.dist(a,b)/self.resolution))
|
||||
if all(safe[self.cell(tuple(x+(y-x)*i/count for x,y in zip(a,b)))]
|
||||
for i in range(count+1)):
|
||||
break
|
||||
else:
|
||||
raise ValueError(f'unable to simplify survey route near {a}')
|
||||
points.append(b)
|
||||
index = last+1
|
||||
return points[1:]
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Make a Gazebo-only map from stationary LiDAR scans at commanded survey stations."""
|
||||
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
|
||||
import project_env
|
||||
from _internal.arena_grid import START, SURVEY_GOALS
|
||||
|
||||
SETTLE_SECONDS = 0.8
|
||||
STATION_SECONDS = 1.5
|
||||
MAP_RESOLUTION = 0.10
|
||||
|
||||
|
||||
def stations(grid):
|
||||
result = [START]
|
||||
route = grid.route(SURVEY_GOALS)
|
||||
for a, b in zip([START] + route, route):
|
||||
steps = max(1, math.ceil(math.dist(a, b) / 1.5))
|
||||
for i in range(1, steps + 1):
|
||||
point = tuple(round(x + (y - x) * i / steps, 4) for x, y in zip(a, b))
|
||||
if point not in result:
|
||||
result.append(point)
|
||||
return result
|
||||
|
||||
|
||||
def set_station(gz, point, partition):
|
||||
x, y = point
|
||||
request = f'name: "sentry" position: {{ x: {x} y: {y} z: 0 }} orientation: {{ w: 1 }}'
|
||||
response = project_env.run_gz(
|
||||
gz, 'service', '-s', '/world/rmul_arena/set_pose', '--reqtype', 'gz.msgs.Pose',
|
||||
'--reptype', 'gz.msgs.Boolean', '--timeout', '2000', '--req', request,
|
||||
timeout=3, partition=partition,
|
||||
)
|
||||
if response.returncode or not re.search(r'^data:\s*true\s*$', response.stdout, re.M):
|
||||
raise RuntimeError(f'Gazebo did not acknowledge station {point}: {response.stdout} {response.stderr}')
|
||||
|
||||
|
||||
def transform(points, pose):
|
||||
translation, xyz, w = pose[:3], pose[3:6], pose[6]
|
||||
twice = 2 * np.cross(xyz, points)
|
||||
return points + w * twice + np.cross(xyz, twice) + translation
|
||||
|
||||
|
||||
def selected_clouds(directory, survey):
|
||||
with (directory / 'scans.csv').open() as stream:
|
||||
scans = [(float(row['timestamp']), row['file']) for row in csv.DictReader(stream)]
|
||||
for station in survey:
|
||||
stamp = station['command_time']
|
||||
candidates = [scan for scan in scans if stamp + SETTLE_SECONDS <= scan[0] < stamp + STATION_SECONDS]
|
||||
if len(candidates) < 3:
|
||||
raise RuntimeError(f'insufficient settled scans at {station["goal"]}')
|
||||
yield station['goal'], candidates[len(candidates) // 2]
|
||||
|
||||
|
||||
def build_map(directory, selected, output):
|
||||
config = (directory / 'config.txt').read_text().splitlines()
|
||||
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
|
||||
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
|
||||
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
|
||||
clouds = []
|
||||
for (x, y), (stamp, filename) in selected:
|
||||
raw = (directory / filename).read_bytes()
|
||||
magic, version, time, count = struct.unpack_from('<8sIdI', raw)
|
||||
if magic != b'FLPC0001' or version != 1 or time != stamp or len(raw) != 24 + count * 24:
|
||||
raise ValueError(f'invalid recorded scan {filename}')
|
||||
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
|
||||
points = rows['point'][:, :3].astype(np.float64)
|
||||
points = points[np.isfinite(points).all(axis=1)]
|
||||
if not len(points):
|
||||
raise RuntimeError(f'no finite returns at station {(x, y)}')
|
||||
base_from_imu, imu_from_lidar = extrinsics
|
||||
clouds.append(transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0])
|
||||
points = np.concatenate(clouds)
|
||||
# Average measured returns that occupy the same voxel across overlapping views.
|
||||
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
|
||||
_, bins, counts = np.unique(grid, axis=0, return_inverse=True, return_counts=True)
|
||||
centers = np.column_stack([np.bincount(bins, weights=axis) / counts for axis in points.T])
|
||||
with tempfile.NamedTemporaryFile(dir=output.parent) as stream:
|
||||
stream.write(struct.pack('<8sIdQ', b'FLMAP001', 1, MAP_RESOLUTION, len(centers)))
|
||||
stream.write(centers.astype('<f8').tobytes())
|
||||
stream.flush()
|
||||
os.link(stream.name, output)
|
||||
return len(centers)
|
||||
|
||||
|
||||
def evaluate_stations(directory, selected):
|
||||
# Independent truth is read only after all scan selections have been made.
|
||||
truth = np.loadtxt(directory / 'truth.tum', ndmin=2)
|
||||
report = []
|
||||
for (x, y), (stamp, filename) in selected:
|
||||
index = int(np.argmin(np.abs(truth[:, 0] - stamp)))
|
||||
time, *pose = truth[index]
|
||||
if abs(time - stamp) > 0.025:
|
||||
raise RuntimeError(f'no independent truth for {filename} at {stamp:.3f}s')
|
||||
error = math.dist(pose[:3], (x, y, 0))
|
||||
rotation = math.degrees(2 * math.acos(min(1.0, abs(pose[6]))))
|
||||
report.append({'station': [x, y], 'timestamp': stamp, 'scan': filename,
|
||||
'position_error_m': error, 'rotation_error_deg': rotation})
|
||||
(directory / 'survey_truth.json').write_text(json.dumps(report, indent=2))
|
||||
if any(row['position_error_m'] > 0.02 or row['rotation_error_deg'] > 1 for row in report):
|
||||
raise RuntimeError('commanded poses failed independent survey verification; see survey_truth.json')
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,151 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
import argparse
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
EXCLUDED_DIRS = {
|
||||
".git",
|
||||
".xmake",
|
||||
"build",
|
||||
"install",
|
||||
"log",
|
||||
"__pycache__",
|
||||
".cache",
|
||||
}
|
||||
|
||||
EXCLUDED_FILES = {
|
||||
"compile_commands.json",
|
||||
"CMakeCache.txt",
|
||||
}
|
||||
|
||||
# 匹配 Linux 绝对路径,避免匹配 URL 中的 //
|
||||
PATH_PATTERN = re.compile(
|
||||
r'(?<![A-Za-z0-9_./-])'
|
||||
r'/(?:[A-Za-z0-9._~+-]+(?:/[A-Za-z0-9._~+-]*)*)'
|
||||
)
|
||||
|
||||
def classify(path):
|
||||
if path.startswith("/opt/ros/"):
|
||||
return "ROS 安装路径"
|
||||
if path.startswith(("/home/", "/root/")):
|
||||
return "用户目录路径"
|
||||
if path.startswith(("/usr/", "/bin/", "/sbin/", "/lib/")):
|
||||
return "系统路径"
|
||||
if path.startswith(("/tmp/", "/var/tmp/")):
|
||||
return "临时目录路径"
|
||||
if path.startswith("/"):
|
||||
return "其他绝对路径"
|
||||
return "其他"
|
||||
|
||||
def should_skip(path):
|
||||
if any(part in EXCLUDED_DIRS for part in path.parts):
|
||||
return True
|
||||
|
||||
if path.name in EXCLUDED_FILES:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Scan repository for hardcoded absolute paths."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--max-lines",
|
||||
type=int,
|
||||
default=100,
|
||||
help="Maximum findings to display (default: 100)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--all",
|
||||
action="store_true",
|
||||
help="Show all findings without the display limit"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
findings = []
|
||||
category_counts = defaultdict(int)
|
||||
file_count = 0
|
||||
|
||||
for file in sorted(ROOT.rglob("*")):
|
||||
if not file.is_file() or should_skip(file.relative_to(ROOT)):
|
||||
continue
|
||||
|
||||
try:
|
||||
content = file.read_text(encoding="utf-8")
|
||||
except (UnicodeDecodeError, OSError):
|
||||
continue
|
||||
|
||||
# 跳过二进制文件
|
||||
if "\0" in content:
|
||||
continue
|
||||
|
||||
file_count += 1
|
||||
relative = file.relative_to(ROOT)
|
||||
|
||||
for line_no, line in enumerate(content.splitlines(), 1):
|
||||
paths = list(dict.fromkeys(PATH_PATTERN.findall(line)))
|
||||
|
||||
for path in paths:
|
||||
category = classify(path)
|
||||
category_counts[category] += 1
|
||||
|
||||
excerpt = " ".join(line.strip().split())
|
||||
if len(excerpt) > 140:
|
||||
excerpt = excerpt[:137] + "..."
|
||||
|
||||
findings.append({
|
||||
"file": str(relative),
|
||||
"line": line_no,
|
||||
"path": path,
|
||||
"category": category,
|
||||
"excerpt": excerpt,
|
||||
})
|
||||
|
||||
print("=" * 72)
|
||||
print("仓库绝对路径审计报告")
|
||||
print("=" * 72)
|
||||
print(f"仓库:{ROOT}")
|
||||
print(f"扫描文件数:{file_count}")
|
||||
print(f"发现路径数:{len(findings)}")
|
||||
print()
|
||||
|
||||
print("[分类统计]")
|
||||
for category, count in sorted(category_counts.items()):
|
||||
print(f" {category:<18} {count:>5}")
|
||||
print()
|
||||
|
||||
limit = len(findings) if args.all else max(0, args.max_lines)
|
||||
shown = findings[:limit]
|
||||
|
||||
current_file = None
|
||||
|
||||
for item in shown:
|
||||
if item["file"] != current_file:
|
||||
current_file = item["file"]
|
||||
print(f"\n[{current_file}]")
|
||||
|
||||
print(
|
||||
f" L{item['line']:<5} "
|
||||
f"[{item['category']}] {item['path']}"
|
||||
)
|
||||
print(f" {item['excerpt']}")
|
||||
|
||||
remaining = len(findings) - len(shown)
|
||||
|
||||
print("\n" + "=" * 72)
|
||||
print(f"已显示:{len(shown)} / {len(findings)}")
|
||||
|
||||
if remaining:
|
||||
print(f"其余隐藏:{remaining} 条")
|
||||
print("需要完整报告时执行:python3 tools/audit_absolute_paths.py --all")
|
||||
|
||||
print("=" * 72)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+79
-14
@@ -2,8 +2,8 @@
|
||||
"""Record an isolated Gazebo mapping/evaluation run; truth is recorder-only.
|
||||
|
||||
Source ROS first. Example:
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap
|
||||
python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field_mapping.flmap
|
||||
python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map src/sentry_sim/maps/field_full.flmap
|
||||
"""
|
||||
import argparse
|
||||
import math
|
||||
@@ -25,6 +25,8 @@ from std_srvs.srv import Trigger
|
||||
from tf2_msgs.msg import TFMessage
|
||||
|
||||
import project_env
|
||||
from _internal.arena_grid import ArenaGrid
|
||||
from _internal import arena_survey
|
||||
|
||||
|
||||
def yaw(q):
|
||||
@@ -88,36 +90,75 @@ def main():
|
||||
parser.add_argument('--profile', choices=['mapping', 'evaluation'], required=True)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--duration', type=float, default=120)
|
||||
parser.add_argument('--duration', type=float)
|
||||
parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC'),
|
||||
help='override the recorded LiDAR topic')
|
||||
parser.add_argument('--full-field', action='store_true',
|
||||
help='capture stationary scans at overlapping Gazebo survey stations (mapping only)')
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]')
|
||||
args = parser.parse_args()
|
||||
if args.full_field and args.profile != 'mapping':
|
||||
parser.error('--full-field requires --profile mapping')
|
||||
if args.duration is not None and (not math.isfinite(args.duration) or args.duration <= 0):
|
||||
parser.error('--duration must be positive and finite')
|
||||
if args.full_field and args.map.exists():
|
||||
parser.error('full-field mapping requires a new output map path')
|
||||
if args.output.exists():
|
||||
parser.error('output directory must not already exist')
|
||||
if args.profile == 'evaluation' and not args.map.is_file():
|
||||
parser.error('evaluation requires an existing map')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
recorder_exe = project_env.require_executable(bin_dir/'field_localization_record',
|
||||
'field_localization_record')
|
||||
survey = None
|
||||
default_duration = 120.0
|
||||
if args.full_field:
|
||||
survey = arena_survey.stations(ArenaGrid(project_env.find_map_yaml()))
|
||||
default_duration = float(math.ceil(3 + len(survey) * (arena_survey.STATION_SECONDS + 0.7)))
|
||||
if args.duration is not None and args.duration < default_duration:
|
||||
parser.error(f'--duration must be at least {default_duration:.1f} simulated seconds for the survey')
|
||||
print(f'mapping survey: {len(survey)} stationary LiDAR stations', flush=True)
|
||||
if args.duration is None:
|
||||
args.duration = default_duration
|
||||
except (project_env.ProbeError, ValueError, OSError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
cloud_topic = args.lio_cloud_topic or '/scan/points_lio'
|
||||
args.output.mkdir(parents=True)
|
||||
args.map.parent.mkdir(parents=True, exist_ok=True)
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
binary = project_env.find_bin_dir(workspace)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1',
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=cloud_topic)
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1',
|
||||
FASTDDS_BUILTIN_TRANSPORTS='UDPv4', HEADLESS='1', NAV2='0', RVIZ='0',
|
||||
LOCALIZATION='lio', LIO_MODE='mapping' if args.profile == 'mapping' else 'localization',
|
||||
LIO_MAP=str(args.map.resolve()), LIO_EXPORT_MAP=str(args.map.resolve()),
|
||||
SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
(args.output/'runtime.json').write_text(json.dumps({'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'],
|
||||
'GZ_PARTITION': os.environ['GZ_PARTITION'], 'duration_sec': args.duration,
|
||||
'profile': args.profile, 'IMU_sensor_noise': 'zero', 'control_input': 'wheel odometry only'}, indent=2))
|
||||
SENTRY_LOG=str((args.output/'stack.log').resolve()),
|
||||
SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()))
|
||||
if survey is not None:
|
||||
# NAV2=0 and this branch starts neither AMCL nor LIO. The survey is offline.
|
||||
os.environ['LOCALIZATION'] = 'amcl'
|
||||
os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve()))
|
||||
os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve()))
|
||||
(args.output/'runtime.json').write_text(json.dumps({
|
||||
'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], 'GZ_PARTITION': os.environ['GZ_PARTITION'],
|
||||
'duration_sec': args.duration, 'profile': args.profile, 'survey': survey, 'IMU_sensor_noise': 'zero',
|
||||
'control_input': 'known stationary survey coordinates' if survey else 'wheel odometry',
|
||||
}, indent=2))
|
||||
processes = []
|
||||
log_handles = []
|
||||
rclpy.init()
|
||||
driver = Driver(args.profile)
|
||||
surveyed = []
|
||||
try:
|
||||
processes.append(subprocess.Popen(['bash', str(workspace/'scripts/sentry_up.sh')], start_new_session=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace))
|
||||
log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
log_handles.append(log)
|
||||
recorder = subprocess.Popen([str(binary/'field_localization_record'), '--ros-args', '-p', 'use_sim_time:=true',
|
||||
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}'],
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true',
|
||||
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}',
|
||||
'-p', f'point_cloud_topic:={cloud_topic}'],
|
||||
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
processes.append(recorder)
|
||||
deadline = time.monotonic() + max(600, args.duration*10)
|
||||
@@ -133,8 +174,22 @@ def main():
|
||||
now = driver.get_clock().now().nanoseconds*1e-9
|
||||
if start is None:
|
||||
start = now
|
||||
driver.drive(now-start)
|
||||
if now-start > last_print+10:
|
||||
if survey is None:
|
||||
driver.drive(now-start)
|
||||
elif len(surveyed) < len(survey) and (not surveyed or
|
||||
now >= surveyed[-1]['command_time'] + arena_survey.STATION_SECONDS + 0.1):
|
||||
if not surveyed and (args.output/'scans.csv').stat().st_size == 0:
|
||||
if now-start > 5:
|
||||
raise RuntimeError(f'no LiDAR scans received on {cloud_topic}')
|
||||
continue
|
||||
point = survey[len(surveyed)]
|
||||
arena_survey.set_station(gz_exe, point, os.environ['GZ_PARTITION'])
|
||||
# Sample the newest received /clock after the synchronous service.
|
||||
for _ in range(10):
|
||||
rclpy.spin_once(driver, timeout_sec=0)
|
||||
surveyed.append({'goal': point, 'command_time': driver.get_clock().now().nanoseconds*1e-9})
|
||||
print(f'survey station {len(surveyed)}/{len(survey)} {point}', flush=True)
|
||||
if survey is None and now-start > last_print+10:
|
||||
last_print = now-start
|
||||
print(f'{args.profile}: {last_print:.1f}/{args.duration:.1f} simulated seconds; odom pose={driver.pose}', flush=True)
|
||||
driver.publisher.publish(Twist())
|
||||
@@ -142,6 +197,14 @@ def main():
|
||||
raise RuntimeError('capture deadline exceeded')
|
||||
if recorder.returncode or not (args.output/'complete.txt').exists():
|
||||
raise RuntimeError('recorder failed; inspect record.log')
|
||||
if survey is not None:
|
||||
if len(surveyed) != len(survey):
|
||||
raise RuntimeError(f'survey reached only {len(surveyed)}/{len(survey)} stations')
|
||||
selection = list(arena_survey.selected_clouds(args.output, surveyed))
|
||||
arena_survey.evaluate_stations(args.output, selection)
|
||||
point_count = arena_survey.build_map(args.output, selection, args.map)
|
||||
print(f'survey complete: {len(selection)} stations, {point_count} voxels; {args.map}', flush=True)
|
||||
return
|
||||
if args.profile == 'mapping':
|
||||
client = driver.create_client(Trigger, '/field_localization/save_map')
|
||||
if not client.wait_for_service(timeout_sec=5):
|
||||
@@ -158,6 +221,8 @@ def main():
|
||||
raise RuntimeError(f'TF validation failed: {tf_summary}')
|
||||
print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True)
|
||||
finally:
|
||||
if survey is not None:
|
||||
(args.output/'survey_progress.json').write_text(json.dumps(surveyed, indent=2))
|
||||
driver.publisher.publish(Twist())
|
||||
for process in reversed(processes):
|
||||
if process.poll() is None:
|
||||
|
||||
+19
-47
@@ -11,7 +11,6 @@
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -29,6 +28,8 @@ from sensor_msgs.msg import PointCloud2, LaserScan
|
||||
from nav_msgs.msg import Odometry, OccupancyGrid
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
import project_env
|
||||
|
||||
|
||||
# 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力)
|
||||
#
|
||||
@@ -96,53 +97,17 @@ def parse_gz_pose(out):
|
||||
return None
|
||||
|
||||
|
||||
def _gz_bin():
|
||||
"""返回 gz 可执行文件路径(系统安装的那个),找不到返回 None。
|
||||
|
||||
不写死 `/usr/bin/gz`:换台机器 gz 可能装在别处。
|
||||
优先用 tools/project_env.py 的统一探测逻辑(同样支持 GZ_BIN 覆盖)。
|
||||
"""
|
||||
try:
|
||||
import project_env # noqa: PLC0415 (同目录模块,按需导入)
|
||||
gz = project_env.find_gz_bin()
|
||||
if gz is not None:
|
||||
return gz
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
for cand in ('/usr/bin/gz', '/usr/local/bin/gz'):
|
||||
if os.access(cand, os.X_OK):
|
||||
return cand
|
||||
return shutil.which('gz')
|
||||
|
||||
|
||||
def gz_model_pose(model_name):
|
||||
"""从 Gazebo 读模型的世界位姿,返回 (x, y, z, roll, pitch, yaw) 或 None。
|
||||
|
||||
为什么要绕道 gz:ROS 里没有独立的真值来源 ——
|
||||
`map -> base_link` 是由「静态 map->odom + 轮速里程计」拼出来的,
|
||||
它无法证明车真的在哪。Gazebo 的服务端才是真值。
|
||||
|
||||
坑:sentry_up.sh 把仿真跑在 `GZ_PARTITION`(默认 sentry)分区里,
|
||||
新开的终端如果不带这个变量,`gz model` 会报
|
||||
「Service call to [/gazebo/worlds] timed out」,看起来像仿真没跑。
|
||||
"""
|
||||
partition = os.environ.get('GZ_PARTITION', 'sentry')
|
||||
env = dict(os.environ)
|
||||
env['GZ_PARTITION'] = partition
|
||||
# 必须用系统版 gz 并清掉 LD_LIBRARY_PATH,否则会加载 ROS vendor 的库,
|
||||
# 和服务端不是同一套。
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
gz_bin = _gz_bin()
|
||||
if gz_bin is None:
|
||||
return None
|
||||
cmd = [str(gz_bin), 'model', '-m', model_name, '-p']
|
||||
"""Read the model pose from Gazebo in the simulation partition."""
|
||||
gz = project_env.find_gz_bin()
|
||||
env_partition = os.environ.get('GZ_PARTITION') or 'sentry'
|
||||
try:
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True,
|
||||
timeout=10).stdout
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
result = project_env.run_gz(
|
||||
gz, 'model', '-m', model_name, '-p', timeout=10,
|
||||
partition=env_partition)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
return parse_gz_pose(out)
|
||||
return parse_gz_pose(result.stdout) if result.returncode == 0 else None
|
||||
|
||||
|
||||
def main():
|
||||
@@ -280,7 +245,14 @@ def main():
|
||||
|
||||
# ---------- 4. 定位真值对照 ----------
|
||||
print('\n=== 4. 定位真值对照 ===')
|
||||
truth = gz_model_pose('sentry')
|
||||
try:
|
||||
truth = gz_model_pose('sentry')
|
||||
except project_env.ProbeError as error:
|
||||
truth = None
|
||||
if os.environ.get('GZ_BIN'):
|
||||
problems.append(str(error))
|
||||
else:
|
||||
print(f' ⚠️ {error}')
|
||||
tf_pos = None
|
||||
try:
|
||||
got = buf.lookup_transform('map', 'base_link', rclpy.time.Time(),
|
||||
@@ -292,7 +264,7 @@ def main():
|
||||
if truth is None:
|
||||
print(' ⚠️ 拿不到 Gazebo 真值(仿真没在跑,或 GZ_PARTITION 对不上)')
|
||||
print(' 手动试:GZ_PARTITION=%s gz model -m sentry -p'
|
||||
% os.environ.get('GZ_PARTITION', 'sentry'))
|
||||
% (os.environ.get('GZ_PARTITION') or 'sentry'))
|
||||
else:
|
||||
gx, gy = truth[0], truth[1]
|
||||
print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy))
|
||||
|
||||
+241
-196
@@ -1,252 +1,297 @@
|
||||
#!/usr/bin/env python3
|
||||
"""可移植的环境探测(Python 版),和 `scripts/env_common.sh` 保持同一套规则。
|
||||
|
||||
规则(两边一致):
|
||||
|
||||
1. **一切都能被环境变量覆盖** —— 探测只提供合理默认值,不是唯一真相。
|
||||
2. **探测失败要吵** —— 宁可启动时报错,也别带着错路径跑到一半。
|
||||
3. **不写死发行版 / 版本 / 平台三元组** —— 换机器、换 ROS 版本、
|
||||
换 Gazebo 大版本、换迁移包日期,都不该需要改代码。
|
||||
|
||||
覆盖用的环境变量:
|
||||
|
||||
=============== ==========================================
|
||||
变量 作用
|
||||
=============== ==========================================
|
||||
ROS_SETUP 直接指定 setup.bash 全路径
|
||||
ROS_DISTRO ROS 发行版名(配合 /opt/ros/<名>/setup.bash)
|
||||
SENTRY_BIN_DIR xmake 产物目录
|
||||
GZ_BIN Gazebo 可执行文件
|
||||
GZ_FORCE_VERSION gz --force-version 的值
|
||||
SENTRY_FIELD_ROOT 场地迁移包根目录
|
||||
SENTRY_MAP_YAML 栅格图 yaml 全路径
|
||||
=============== ==========================================
|
||||
|
||||
用法::
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(WS / 'tools'))
|
||||
import project_env
|
||||
bin_dir = project_env.find_bin_dir(WS)
|
||||
"""
|
||||
"""Shared environment discovery for the simulation launchers and tools."""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
# xmake 会产出的可执行文件,用来反推产物目录。
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'field_localization_node')
|
||||
|
||||
# 系统 gz 的常见安装位置(按优先级)。
|
||||
WORKSPACE = Path(__file__).resolve().parents[1]
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf', 'cmd_vel_relay',
|
||||
'field_localization_node', 'field_localization_record', 'field_localization_replay')
|
||||
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
|
||||
_GZ_VERSION_TIMEOUT = 5
|
||||
_FIELD_PACKAGE = Path('src/guodong_sentry_sim')
|
||||
|
||||
|
||||
class ProbeError(RuntimeError):
|
||||
"""A required setting is missing or points to an unusable path."""
|
||||
|
||||
|
||||
def require_file(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not path.is_file():
|
||||
raise ProbeError(f'{name} 必须指向普通文件: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def require_directory(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not path.is_dir():
|
||||
raise ProbeError(f'{name} 必须指向目录: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def is_executable(path):
|
||||
return Path(path).is_file() and os.access(path, os.X_OK)
|
||||
|
||||
|
||||
def require_executable(path, name):
|
||||
path = Path(path).absolute()
|
||||
if not is_executable(path):
|
||||
raise ProbeError(f'{name} 必须指向可执行的普通文件: {path}')
|
||||
return path
|
||||
|
||||
|
||||
def find_ros_setup():
|
||||
"""返回要 source 的 ROS `setup.bash` 路径;找不到返回 None。
|
||||
|
||||
优先级:`ROS_SETUP` → `ROS_INSTALL_ROOT/setup.bash` →
|
||||
`/opt/ros/<ROS_DISTRO>/setup.bash` → `/opt/ros/*/setup.bash` 里版本号最大的一个。
|
||||
|
||||
已经 source 过(`AMENT_PREFIX_PATH` 非空)时返回 None —— 调用方不该重复 source,
|
||||
否则 PATH 会越叠越长。
|
||||
"""
|
||||
"""Return the ROS setup path, or None when ROS is already sourced."""
|
||||
explicit = os.environ.get('ROS_SETUP')
|
||||
setup = require_file(explicit, 'ROS_SETUP') if explicit else None
|
||||
if os.environ.get('AMENT_PREFIX_PATH') and shutil.which('ros2'):
|
||||
return None
|
||||
|
||||
explicit = os.environ.get('ROS_SETUP')
|
||||
if explicit:
|
||||
p = Path(explicit)
|
||||
return p if p.is_file() else None
|
||||
if setup is not None:
|
||||
return setup
|
||||
|
||||
root = os.environ.get('ROS_INSTALL_ROOT')
|
||||
if root and (Path(root) / 'setup.bash').is_file():
|
||||
return Path(root) / 'setup.bash'
|
||||
if root:
|
||||
setup = Path(root) / 'setup.bash'
|
||||
if setup.is_file():
|
||||
return setup.absolute()
|
||||
|
||||
distro = os.environ.get('ROS_DISTRO')
|
||||
if distro:
|
||||
p = Path('/opt/ros') / distro / 'setup.bash'
|
||||
if p.is_file():
|
||||
return p
|
||||
setup = Path('/opt/ros') / distro / 'setup.bash'
|
||||
if setup.is_file():
|
||||
return setup
|
||||
|
||||
found = sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
if not found:
|
||||
return None
|
||||
# 版本号最大 —— `lyrical` > `kilted` > `jazzy` > `iron` > `humble` 这种名字
|
||||
# 排不出来,所以退化成"取最后一个",并在多于一个时提醒调用方。
|
||||
return found[-1]
|
||||
candidates = sorted(
|
||||
(p for p in Path('/opt/ros').glob('*/setup.bash') if p.is_file()),
|
||||
key=lambda p: ([int(part) if i % 2 else part for i, part in
|
||||
enumerate(re.split(r'([0-9]+)', p.parent.name))], p.parent.name),
|
||||
)
|
||||
if not candidates:
|
||||
raise ProbeError('找不到 ROS 2 setup.bash。请加载 ROS 环境或设置 ROS_SETUP。')
|
||||
if len(candidates) > 1:
|
||||
print(f'[env] 警告: 发现多个 ROS 安装,按目录名排序选择 {candidates[-1]}', file=sys.stderr)
|
||||
return candidates[-1]
|
||||
|
||||
|
||||
def ros_setup_candidates():
|
||||
"""列出机器上所有 ROS `setup.bash`,用于在多版本时给出提示。"""
|
||||
return sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
def find_bin_dir(ws=WORKSPACE):
|
||||
"""Choose a single build directory without mixing targets from different builds."""
|
||||
for name in ('SENTRY_BIN_DIR', 'NAV_BIN_DIR'):
|
||||
if override := os.environ.get(name):
|
||||
return require_directory(override, name)
|
||||
|
||||
|
||||
def find_bin_dir(ws):
|
||||
"""返回 xmake 产物目录(含 `self_filter` / `nav_client` 等的那个)。
|
||||
|
||||
**现行布局是 `build/bin/`** —— `src/sentry_nav/xmake.lua` 里每个 target 都
|
||||
`set_targetdir("$(builddir)/bin")`,故意不用 xmake 默认的平台三元组,
|
||||
免得 `build/<平台>/<架构>/<模式>` 这种串被抄进文档后换机器就失效。
|
||||
|
||||
仍然兼容老布局(`build/*/*/{release,debug}`),因为别的 checkout 可能还没重建。
|
||||
"""
|
||||
env = os.environ.get('SENTRY_BIN_DIR') or os.environ.get('NAV_BIN_DIR')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
build = Path(ws) / 'build'
|
||||
|
||||
# ① 现行布局:build/bin/
|
||||
build = Path(ws).absolute() / 'build'
|
||||
unified = build / 'bin'
|
||||
if unified.is_dir() and any((unified / n).is_file() for n in _KNOWN_BINARIES):
|
||||
if any(is_executable(unified / name) for name in _KNOWN_BINARIES):
|
||||
return unified
|
||||
|
||||
# ② 老布局:build/<平台>/<架构>/<模式>/
|
||||
for mode in ('release', 'debug'):
|
||||
for d in sorted(build.glob(f'*/*/{mode}')):
|
||||
if any((d / n).is_file() for n in _KNOWN_BINARIES):
|
||||
return d
|
||||
|
||||
# ③ 还没编译过:返回现行布局的位置
|
||||
for candidate in sorted(build.glob(f'*/*/{mode}')):
|
||||
if any(is_executable(candidate / name) for name in _KNOWN_BINARIES):
|
||||
return candidate
|
||||
return unified
|
||||
|
||||
|
||||
def find_gz_bin():
|
||||
"""返回 gz 可执行文件路径;找不到返回 None。
|
||||
|
||||
为什么要挑:`source` 过 ROS 之后,`$PATH` 上的 `gz` 是 `gz_tools_vendor`
|
||||
里那个,带着 vendor 的 RUNPATH,会加载缺 cpu-lidar 插件的 vendor 版 gz-sim。
|
||||
所以系统安装的位置优先。
|
||||
"""
|
||||
env = os.environ.get('GZ_BIN')
|
||||
if env:
|
||||
p = Path(env)
|
||||
return p if os.access(p, os.X_OK) else None
|
||||
|
||||
for cand in _GZ_CANDIDATES:
|
||||
if os.access(cand, os.X_OK):
|
||||
return Path(cand)
|
||||
|
||||
which = shutil.which('gz')
|
||||
return Path(which) if which else None
|
||||
"""Prefer system Gazebo, validating an explicit override before any fallback."""
|
||||
if override := os.environ.get('GZ_BIN'):
|
||||
return require_executable(override, 'GZ_BIN')
|
||||
for path in _GZ_CANDIDATES:
|
||||
if is_executable(path):
|
||||
return Path(path)
|
||||
if path := shutil.which('gz'):
|
||||
return require_executable(path, 'gz')
|
||||
raise ProbeError('找不到 Gazebo 的 gz 可执行文件。请设置 GZ_BIN。')
|
||||
|
||||
|
||||
def gz_version_args():
|
||||
"""返回 `['--force-version', '<主版本>']`,取不到就返回 `[]`。
|
||||
def run_gz(gz, *args, timeout, partition=None):
|
||||
"""Run a Gazebo query in its own process group with a wall-clock deadline."""
|
||||
env = os.environ.copy()
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
if partition is not None:
|
||||
env['GZ_PARTITION'] = partition
|
||||
command = [str(gz), *args]
|
||||
# Files let us read results after a timeout even if a descendant still holds
|
||||
# an output descriptor. Only the process group started here is signalled.
|
||||
with tempfile.TemporaryFile() as stdout, tempfile.TemporaryFile() as stderr:
|
||||
process = subprocess.Popen(command, env=env, start_new_session=True,
|
||||
stdout=stdout, stderr=stderr)
|
||||
try:
|
||||
process.wait(timeout=timeout)
|
||||
except BaseException:
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
process.wait()
|
||||
raise
|
||||
stdout.seek(0)
|
||||
stderr.seek(0)
|
||||
return subprocess.CompletedProcess(command, process.returncode,
|
||||
stdout.read().decode(errors='replace'),
|
||||
stderr.read().decode(errors='replace'))
|
||||
|
||||
写死 10 的话,装了 gz 11 就跑不起来。`GZ_FORCE_VERSION` 可强制指定。
|
||||
"""
|
||||
forced = os.environ.get('GZ_FORCE_VERSION')
|
||||
if forced:
|
||||
return ['--force-version', str(forced)]
|
||||
|
||||
gz = find_gz_bin()
|
||||
def gz_version_args(gz=None):
|
||||
"""Return force-version arguments, or warn and let Gazebo choose its default."""
|
||||
if gz is None:
|
||||
return []
|
||||
gz = find_gz_bin()
|
||||
if forced := os.environ.get('GZ_FORCE_VERSION'):
|
||||
return ['--force-version', forced]
|
||||
|
||||
try:
|
||||
out = subprocess.run([str(gz), 'sim', '--version'],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return []
|
||||
|
||||
lines = (out.stdout or out.stderr or '').strip().splitlines()
|
||||
if not lines:
|
||||
return []
|
||||
m = re.match(r'\s*(\d+)', lines[0])
|
||||
return ['--force-version', m.group(1)] if m else []
|
||||
result = run_gz(gz, 'sim', '--version', timeout=_GZ_VERSION_TIMEOUT)
|
||||
if result.returncode:
|
||||
reason = f'退出码 {result.returncode}'
|
||||
else:
|
||||
version = re.match(r'^\s*([0-9]+)(?=\.|\s|$)', result.stdout.strip() or result.stderr.strip())
|
||||
if version:
|
||||
return ['--force-version', version[1]]
|
||||
reason = '无法解析版本'
|
||||
except subprocess.TimeoutExpired:
|
||||
reason = f'超时({_GZ_VERSION_TIMEOUT:g} 秒)'
|
||||
except OSError as error:
|
||||
reason = str(error)
|
||||
print(f'[env] 警告: {gz} sim --version {reason},使用 Gazebo 默认版本。'
|
||||
'可通过 GZ_FORCE_VERSION 指定主版本。', file=sys.stderr)
|
||||
return []
|
||||
|
||||
|
||||
def find_field_root(ws):
|
||||
"""返回场地迁移包根目录;找不到返回 None。
|
||||
def wait_gz_clock(gz, gazebo_pid=None):
|
||||
"""Wait for the selected Gazebo transport to advertise /clock."""
|
||||
raw_timeout = os.environ.get('BRIDGE_WAIT_TIMEOUT') or '120'
|
||||
try:
|
||||
timeout = float(raw_timeout)
|
||||
except ValueError:
|
||||
timeout = 0
|
||||
if not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ProbeError(f'BRIDGE_WAIT_TIMEOUT 必须为正数: {raw_timeout}')
|
||||
|
||||
不写死 `RMUL2027_map_transfer_20261016_STEP_R1` —— 换一版迁移包日期就变了。
|
||||
找的是「含 `src/guodong_sentry_sim` 的那一层」。
|
||||
"""
|
||||
env = os.environ.get('SENTRY_FIELD_ROOT')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
ws = Path(ws)
|
||||
for p in sorted(ws.glob('field/*/src/guodong_sentry_sim')):
|
||||
if p.is_dir():
|
||||
return p.parent.parent
|
||||
|
||||
for p in sorted((Path.home() / 'Gazebo_projects').glob(
|
||||
'*map_transfer*/src/guodong_sentry_sim')):
|
||||
if p.is_dir():
|
||||
return p.parent.parent
|
||||
|
||||
return None
|
||||
deadline = time.monotonic() + timeout
|
||||
while (remaining := deadline - time.monotonic()) > 0:
|
||||
if gazebo_pid is not None:
|
||||
try:
|
||||
os.kill(gazebo_pid, 0)
|
||||
except ProcessLookupError as error:
|
||||
raise ProbeError('Gazebo 启动失败,进程已退出') from error
|
||||
try:
|
||||
# Listing topics waits for a full discovery cycle (over two seconds on this host).
|
||||
result = run_gz(gz, 'topic', '-e', '-t', '/clock', '-n', '1',
|
||||
timeout=min(2, remaining))
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
return
|
||||
except subprocess.TimeoutExpired:
|
||||
pass
|
||||
time.sleep(max(0, min(1, deadline - time.monotonic())))
|
||||
raise ProbeError(
|
||||
f'等待 Gazebo /clock 超时({timeout:g} 秒),请检查 GZ_PARTITION='
|
||||
f'{os.environ.get("GZ_PARTITION") or "sentry"}')
|
||||
|
||||
|
||||
def find_map_yaml(field_root):
|
||||
"""返回栅格图 yaml 路径;找不到返回 None。优先 `rmul_2027.yaml`。"""
|
||||
env = os.environ.get('SENTRY_MAP_YAML')
|
||||
if env:
|
||||
return Path(env)
|
||||
def find_field_root(ws=WORKSPACE, *, explicit=None):
|
||||
if explicit:
|
||||
return require_directory(explicit, 'field_root')
|
||||
if override := os.environ.get('SENTRY_FIELD_ROOT'):
|
||||
return require_directory(override, 'SENTRY_FIELD_ROOT')
|
||||
for parent, pattern in ((Path(ws).absolute() / 'field', '*'),
|
||||
(Path.home() / 'Gazebo_projects', '*map_transfer*')):
|
||||
for candidate in sorted(parent.glob(pattern)):
|
||||
if (candidate / _FIELD_PACKAGE).is_dir():
|
||||
return candidate
|
||||
raise ProbeError('找不到场地迁移包。请设置 SENTRY_FIELD_ROOT。')
|
||||
|
||||
|
||||
def find_map_yaml(field_root=None, *, explicit=None, ws=WORKSPACE):
|
||||
if explicit:
|
||||
return require_file(explicit, 'map')
|
||||
if override := os.environ.get('SENTRY_MAP_YAML'):
|
||||
return require_file(override, 'SENTRY_MAP_YAML')
|
||||
if field_root is None:
|
||||
return None
|
||||
|
||||
maps = Path(field_root) / 'src' / 'guodong_sentry_sim' / 'maps'
|
||||
field_root = find_field_root(ws)
|
||||
maps = Path(field_root) / _FIELD_PACKAGE / 'maps'
|
||||
preferred = maps / 'rmul_2027' / 'rmul_2027.yaml'
|
||||
if preferred.is_file():
|
||||
return preferred
|
||||
|
||||
cands = sorted(maps.glob('*/*.yaml'))
|
||||
return cands[0] if cands else None
|
||||
candidates = sorted(p for p in maps.glob('*/*.yaml') if p.is_file())
|
||||
for candidate in candidates:
|
||||
if candidate.name == 'rmul_2027.yaml':
|
||||
return candidate
|
||||
if candidates:
|
||||
return candidates[0]
|
||||
raise ProbeError(f'{maps} 下找不到栅格图 YAML。请设置 SENTRY_MAP_YAML。')
|
||||
|
||||
|
||||
def report(ws):
|
||||
"""打印所有探测结果,排查路径问题时用。"""
|
||||
field_root = find_field_root(ws)
|
||||
setup = find_ros_setup()
|
||||
if setup:
|
||||
ros_line = str(setup)
|
||||
elif os.environ.get('AMENT_PREFIX_PATH'):
|
||||
ros_line = f'<已 source: {os.environ["AMENT_PREFIX_PATH"]}>'
|
||||
else:
|
||||
ros_line = '<找不到>'
|
||||
print(f' ROS setup : {ros_line}')
|
||||
print(f' BIN_DIR : {find_bin_dir(ws)}')
|
||||
print(f' GZ_BIN : {find_gz_bin()}')
|
||||
print(f' gz 版本参数 : {" ".join(gz_version_args()) or "<无>"}')
|
||||
bin_dir = find_bin_dir(ws)
|
||||
field_root = find_field_root(ws)
|
||||
map_yaml = find_map_yaml(field_root)
|
||||
gz = find_gz_bin()
|
||||
versions = ' '.join(gz_version_args(gz))
|
||||
print(f'仓库根: {ws}')
|
||||
print(f' ROS setup : {setup or "<已 source>"}')
|
||||
print(f' BIN_DIR : {bin_dir}')
|
||||
print(f' GZ_BIN : {gz}')
|
||||
print(f' gz 版本参数 : {versions or "<无>"}')
|
||||
print(f' FIELD_ROOT : {field_root}')
|
||||
print(f' MAP_YAML : {find_map_yaml(field_root)}')
|
||||
print(f' MAP_YAML : {map_yaml}')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('workspace', type=Path, nargs='?', default=WORKSPACE)
|
||||
queries = parser.add_mutually_exclusive_group()
|
||||
for query in ('bin-dir', 'field', 'map', 'gz', 'gz-version-args', 'ros-setup'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query)
|
||||
for query in ('gz-version-args-lines', 'wait-gz-clock'):
|
||||
queries.add_argument(f'--{query}', dest='query', action='store_const', const=query,
|
||||
help=argparse.SUPPRESS)
|
||||
parser.add_argument('--field-root', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--gazebo-pid', type=int, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
if args.field_root is not None and args.query != 'map':
|
||||
parser.error('--field-root requires --map')
|
||||
if args.gazebo_pid is not None and (args.query != 'wait-gz-clock' or args.gazebo_pid <= 0):
|
||||
parser.error('--gazebo-pid requires --wait-gz-clock and a positive PID')
|
||||
|
||||
try:
|
||||
ws = require_directory(args.workspace, 'workspace')
|
||||
match args.query:
|
||||
case 'bin-dir':
|
||||
print(find_bin_dir(ws))
|
||||
case 'field':
|
||||
print(find_field_root(ws))
|
||||
case 'map':
|
||||
print(find_map_yaml(args.field_root, ws=ws))
|
||||
case 'gz':
|
||||
print(find_gz_bin())
|
||||
case 'gz-version-args' | 'gz-version-args-lines':
|
||||
separator = '\n' if args.query == 'gz-version-args-lines' else ' '
|
||||
versions = gz_version_args()
|
||||
if versions:
|
||||
print(separator.join(versions))
|
||||
elif args.query == 'gz-version-args':
|
||||
print()
|
||||
case 'ros-setup':
|
||||
print(find_ros_setup() or '')
|
||||
case 'wait-gz-clock':
|
||||
wait_gz_clock(find_gz_bin(), args.gazebo_pid)
|
||||
case None:
|
||||
report(ws)
|
||||
except (ProbeError, OSError) as error:
|
||||
print(f'[env] {error}', file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 支持直接从命令行取单个值,方便写进文档当可移植的一行命令:
|
||||
# NAV=$(python3 tools/project_env.py --bin-dir)/nav_client
|
||||
# python3 tools/project_env.py --map / --field / --gz / --bin-dir
|
||||
argv = sys.argv[1:]
|
||||
ws_arg = str(Path(__file__).resolve().parents[1])
|
||||
if argv and Path(argv[0]).is_dir():
|
||||
ws_arg = argv.pop(0)
|
||||
|
||||
if argv:
|
||||
opt = argv[0]
|
||||
if opt == '--bin-dir':
|
||||
print(find_bin_dir(ws_arg))
|
||||
elif opt == '--field':
|
||||
print(find_field_root(ws_arg))
|
||||
elif opt == '--map':
|
||||
print(find_map_yaml(find_field_root(ws_arg)))
|
||||
elif opt == '--gz':
|
||||
print(find_gz_bin())
|
||||
elif opt == '--gz-version-args':
|
||||
print(' '.join(gz_version_args()))
|
||||
elif opt == '--ros-setup':
|
||||
print(find_ros_setup() or '')
|
||||
else:
|
||||
print(f'未知选项 {opt},可用:--bin-dir --field --map --gz '
|
||||
'--gz-version-args --ros-setup', file=sys.stderr)
|
||||
sys.exit(2)
|
||||
sys.exit(0)
|
||||
|
||||
print(f'仓库根: {ws_arg}')
|
||||
report(ws_arg)
|
||||
sys.exit(main())
|
||||
@@ -5,14 +5,23 @@ import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import project_env
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--binary',type=Path,default=Path(__file__).resolve().parents[1]/'build/bin/cmd_vel_relay')
|
||||
parser.add_argument('--binary', type=Path)
|
||||
args=parser.parse_args()
|
||||
try:
|
||||
binary = args.binary or project_env.find_bin_dir()/'cmd_vel_relay'
|
||||
binary = project_env.require_executable(binary, 'cmd_vel_relay')
|
||||
except project_env.ProbeError as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
os.environ.update(ROS_DOMAIN_ID=str(130+int(uuid.uuid4().hex[:4],16)%40),
|
||||
FASTDDS_BUILTIN_TRANSPORTS='UDPv4',ROS2CLI_DISABLE_DAEMON='1')
|
||||
import rclpy
|
||||
@@ -31,7 +40,7 @@ def main():
|
||||
return response
|
||||
services=[node.create_service(CancelGoal,name+'/_action/cancel_goal',cancel)
|
||||
for name in ['/navigate_to_pose','/navigate_through_poses']]
|
||||
process=subprocess.Popen([str(args.binary),'--ros-args','-p','navigation_mode:=true'],
|
||||
process=subprocess.Popen([str(binary),'--ros-args','-p','navigation_mode:=true'],
|
||||
start_new_session=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,text=True)
|
||||
checks=0
|
||||
def check(ok,message):
|
||||
@@ -9,6 +9,8 @@ import time
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
INTERNAL_TOOLS = Path(__file__).resolve().parents[1] / '_internal'
|
||||
sys.path.insert(0, str(INTERNAL_TOOLS))
|
||||
from dds_environment import defaults
|
||||
|
||||
|
||||
@@ -73,7 +75,7 @@ def main():
|
||||
services = [node.create_service(GetParameters, '/lifecycle_manager_nav2/get_parameters', parameters),
|
||||
node.create_service(Trigger, '/lifecycle_manager_nav2/is_active', active)]
|
||||
services += [node.create_service(GetState, f'/{name}/get_state', state) for name in managed]
|
||||
command = [sys.executable, str(Path(__file__).with_name('nav2_startup.py'))]
|
||||
command = [sys.executable, str(INTERNAL_TOOLS / 'nav2_startup.py')]
|
||||
|
||||
def run(arguments):
|
||||
process = subprocess.Popen(command+arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
@@ -5,6 +5,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / '_internal'))
|
||||
from run_nav2 import stop_owned, supervise
|
||||
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the shared environment probes through both CLI entry points."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1]
|
||||
WORKSPACE = TOOLS.parent
|
||||
SCRIPTS = WORKSPACE / 'src/sentry_sim/scripts'
|
||||
sys.path.insert(0, str(TOOLS))
|
||||
import project_env
|
||||
|
||||
|
||||
class EnvironmentTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory(prefix='sentry env ')
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.env = os.environ.copy()
|
||||
self.env['PYTHONDONTWRITEBYTECODE'] = '1'
|
||||
for name in ('ROS_SETUP', 'ROS_INSTALL_ROOT', 'ROS_DISTRO', 'AMENT_PREFIX_PATH',
|
||||
'SENTRY_BIN_DIR', 'NAV_BIN_DIR', 'SENTRY_FIELD_ROOT', 'SENTRY_MAP_YAML',
|
||||
'GZ_BIN', 'GZ_FORCE_VERSION', 'BRIDGE_WAIT_TIMEOUT', 'GZ_PARTITION'):
|
||||
self.env.pop(name, None)
|
||||
|
||||
def run_command(self, command, **overrides):
|
||||
return subprocess.run(command, cwd=self.root, env={**self.env, **overrides},
|
||||
capture_output=True, text=True, timeout=12)
|
||||
|
||||
def cli(self, *args, **overrides):
|
||||
return self.run_command([sys.executable, str(TOOLS/'project_env.py'), *map(str, args)],
|
||||
**overrides)
|
||||
|
||||
def shell(self, *args, **overrides):
|
||||
return self.run_command(['bash', '-c', 'source "$1"; shift; "$@"',
|
||||
'env-test', str(SCRIPTS/'env_common.sh'), *map(str, args)],
|
||||
**overrides)
|
||||
|
||||
def executable(self, path, script='exit 0'):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text('#!/bin/bash\n' + script + '\n')
|
||||
path.chmod(0o755)
|
||||
return path
|
||||
|
||||
def expect_value(self, result, value):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, f'{value}\n')
|
||||
|
||||
def expect_error(self, result, text, code=1):
|
||||
self.assertEqual(result.returncode, code, result.stderr)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertIn(text, result.stderr)
|
||||
|
||||
def test_map_overrides(self):
|
||||
field = self.root/'field with spaces'
|
||||
field.mkdir()
|
||||
yaml = self.root/'custom map.yaml'
|
||||
yaml.touch()
|
||||
for bad in (self.root/'missing.yaml', field):
|
||||
with self.subTest(path=bad):
|
||||
self.expect_error(self.cli('--map', SENTRY_MAP_YAML=str(bad)), 'SENTRY_MAP_YAML')
|
||||
self.expect_error(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=str(bad)),
|
||||
'SENTRY_MAP_YAML')
|
||||
self.expect_value(self.cli('--map', SENTRY_MAP_YAML=yaml.name), yaml)
|
||||
self.expect_value(self.shell('env_map_yaml', field, SENTRY_MAP_YAML=yaml.name), yaml)
|
||||
with patch.dict(os.environ, {'SENTRY_MAP_YAML': str(field)}):
|
||||
self.assertEqual(project_env.find_map_yaml(field, explicit=yaml), yaml)
|
||||
|
||||
def test_map_search_order(self):
|
||||
field = self.root/'field'
|
||||
maps = field/'src/guodong_sentry_sim/maps'
|
||||
canonical = maps/'rmul_2027/rmul_2027.yaml'
|
||||
named_first = maps/'a/rmul_2027.yaml'
|
||||
named_last = maps/'z/rmul_2027.yaml'
|
||||
fallback = maps/'a/001.yaml'
|
||||
for path in (canonical, named_first, named_last, fallback):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.touch()
|
||||
(maps/'a/000.yaml').mkdir()
|
||||
|
||||
def expect_map(path):
|
||||
self.expect_value(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), path)
|
||||
self.expect_value(self.shell('env_map_yaml', field), path)
|
||||
|
||||
expect_map(canonical)
|
||||
canonical.unlink()
|
||||
expect_map(named_first)
|
||||
named_first.unlink()
|
||||
expect_map(named_last)
|
||||
named_last.unlink()
|
||||
expect_map(fallback)
|
||||
fallback.unlink()
|
||||
self.expect_error(self.cli('--map', SENTRY_FIELD_ROOT=str(field)), 'SENTRY_MAP_YAML')
|
||||
self.expect_error(self.shell('env_map_yaml', field), 'SENTRY_MAP_YAML')
|
||||
|
||||
def test_field_and_ros_setup_overrides(self):
|
||||
field = self.root/'field'
|
||||
other = self.root/'other field'
|
||||
field.mkdir()
|
||||
other.mkdir()
|
||||
self.expect_error(self.cli('--field', SENTRY_FIELD_ROOT=str(field/'missing')),
|
||||
'SENTRY_FIELD_ROOT')
|
||||
self.expect_error(self.shell('env_field_root', self.root,
|
||||
SENTRY_FIELD_ROOT=str(field/'missing')), 'SENTRY_FIELD_ROOT')
|
||||
self.expect_value(self.cli('--field', SENTRY_FIELD_ROOT=field.name), field)
|
||||
with patch.dict(os.environ, {'SENTRY_FIELD_ROOT': str(field)}):
|
||||
self.assertEqual(project_env.find_field_root(self.root, explicit=other), other)
|
||||
|
||||
setup = self.root/'setup with spaces.bash'
|
||||
setup.write_text('export SENTRY_SETUP_TEST=loaded\n')
|
||||
for invalid in (field, self.root/'missing.bash'):
|
||||
self.expect_error(self.cli('--ros-setup', ROS_SETUP=str(invalid)), 'ROS_SETUP')
|
||||
self.expect_error(self.shell('env_source_ros', ROS_SETUP=str(invalid)), 'ROS_SETUP')
|
||||
self.expect_value(self.cli('--ros-setup', ROS_SETUP=setup.name), setup)
|
||||
result = self.run_command(
|
||||
['bash', '-c', 'source "$1"; env_source_ros && printf "%s\\n" "$SENTRY_SETUP_TEST"',
|
||||
'env-test', str(SCRIPTS/'env_common.sh')], ROS_SETUP=setup.name)
|
||||
self.expect_value(result, 'loaded')
|
||||
ros2 = self.executable(self.root/'ros bin/ros2')
|
||||
self.expect_value(self.cli('--ros-setup', ROS_SETUP=str(setup), AMENT_PREFIX_PATH='/fake',
|
||||
PATH=f'{ros2.parent}:{self.env["PATH"]}'), '')
|
||||
|
||||
def test_cli_status_and_stdout(self):
|
||||
self.expect_error(self.cli('--unknown'), 'unrecognized arguments', code=2)
|
||||
self.expect_error(self.cli('--map', '--gz'), 'not allowed', code=2)
|
||||
self.expect_error(self.cli('--gz', '--field-root', self.root), 'requires --map', code=2)
|
||||
self.expect_error(self.cli('--bin-dir', SENTRY_BIN_DIR=str(self.root/'missing')),
|
||||
'SENTRY_BIN_DIR')
|
||||
with (patch.object(project_env, '_GZ_CANDIDATES', ()),
|
||||
patch.object(project_env.shutil, 'which', return_value=None),
|
||||
patch.dict(os.environ, {'GZ_BIN': ''})):
|
||||
with self.assertRaisesRegex(project_env.ProbeError, '找不到 Gazebo'):
|
||||
project_env.find_gz_bin()
|
||||
|
||||
def test_build_directory_priority_matches_shell(self):
|
||||
build = self.root/'build'
|
||||
unified = build/'bin'
|
||||
|
||||
def expect_bin(path, **overrides):
|
||||
self.expect_value(self.cli(self.root, '--bin-dir', **overrides), path)
|
||||
self.expect_value(self.shell('env_bin_dir', self.root, **overrides), path)
|
||||
|
||||
expect_bin(unified)
|
||||
debug = self.executable(build/'a/first/debug/self_filter')
|
||||
expect_bin(debug.parent)
|
||||
release_last = self.executable(build/'z/last/release/nav_client')
|
||||
release_first = self.executable(build/'a/second/release/odom_tf')
|
||||
(build/'a/first/release').mkdir()
|
||||
(build/'a/first/release/nav_client').touch()
|
||||
expect_bin(release_first.parent)
|
||||
(unified/'self_filter').mkdir(parents=True)
|
||||
(unified/'nav_client').touch()
|
||||
expect_bin(release_first.parent)
|
||||
self.executable(unified/'cmd_vel_relay')
|
||||
expect_bin(unified)
|
||||
expect_bin(release_last.parent, NAV_BIN_DIR=str(release_last.parent))
|
||||
expect_bin(release_first.parent, SENTRY_BIN_DIR=str(release_first.parent),
|
||||
NAV_BIN_DIR=str(release_last.parent))
|
||||
|
||||
def test_gz_executable_validation_matches_shell(self):
|
||||
fake = self.executable(self.root/'fake gazebo')
|
||||
alias = self.root/'link to gz'
|
||||
alias.symlink_to(fake)
|
||||
denied = self.root/'non-executable'
|
||||
denied.touch()
|
||||
for path in (self.root, denied, self.root/'missing'):
|
||||
with self.subTest(path=path):
|
||||
self.expect_error(self.cli('--gz', GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_error(self.shell('env_gz_bin', GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_error(self.cli('--gz-version-args', GZ_FORCE_VERSION='12',
|
||||
GZ_BIN=str(path)), 'GZ_BIN')
|
||||
self.expect_value(self.cli('--gz', GZ_BIN=alias.name), alias)
|
||||
self.expect_value(self.shell('env_gz_bin', GZ_BIN=alias.name), alias)
|
||||
|
||||
def test_version_and_explicit_override_matches_shell(self):
|
||||
fake = self.executable(self.root/'fake gz', '''
|
||||
if [[ "$*" != "sim --version" || -v LD_LIBRARY_PATH ]]; then exit 4; fi
|
||||
touch "$SENTRY_GZ_MARKER"
|
||||
echo ' 10.5.0 '
|
||||
''')
|
||||
marker = self.root/'probe-called'
|
||||
env = dict(GZ_BIN=str(fake), LD_LIBRARY_PATH='/test/vendor', SENTRY_GZ_MARKER=str(marker))
|
||||
self.expect_value(self.cli('--gz-version-args', **env), '--force-version 10')
|
||||
self.assertTrue(marker.is_file())
|
||||
self.expect_value(self.shell('env_gz_version_args', **env), '--force-version\n10')
|
||||
marker.unlink()
|
||||
self.expect_value(self.cli('--gz-version-args', GZ_FORCE_VERSION='12', **env),
|
||||
'--force-version 12')
|
||||
self.expect_value(self.shell('env_gz_version_args', GZ_FORCE_VERSION='12', **env),
|
||||
'--force-version\n12')
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
def test_version_nonzero_and_unparseable_warn_and_continue(self):
|
||||
fake = self.root/'gz'
|
||||
for script, reason in (("echo '10.0'; exit 7", '退出码 7'), ('echo unknown', '无法解析版本')):
|
||||
self.executable(fake, script)
|
||||
cli = self.cli('--gz-version-args', GZ_BIN=str(fake))
|
||||
shell = self.shell('env_gz_version_args', GZ_BIN=str(fake))
|
||||
self.expect_value(cli, '')
|
||||
self.assertIn(reason, cli.stderr)
|
||||
self.assertEqual(shell.returncode, 0, shell.stderr)
|
||||
self.assertEqual(shell.stdout, '')
|
||||
self.assertIn(reason, shell.stderr)
|
||||
|
||||
def test_version_timeout_stops_owned_process_group(self):
|
||||
marker = self.root/'child-pids'
|
||||
fake = self.executable(self.root/'slow gz', '''
|
||||
trap '' TERM
|
||||
sleep 30 &
|
||||
printf '%s %s\\n' "$$" "$!" > "$SENTRY_GZ_MARKER"
|
||||
wait
|
||||
''')
|
||||
start = time.monotonic()
|
||||
result = self.shell('env_gz_version_args', GZ_BIN=str(fake), SENTRY_GZ_MARKER=str(marker))
|
||||
elapsed = time.monotonic() - start
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, '')
|
||||
self.assertIn('超时', result.stderr)
|
||||
self.assertGreaterEqual(elapsed, 5)
|
||||
self.assertLess(elapsed, 8)
|
||||
for pid in marker.read_text().split():
|
||||
try:
|
||||
state = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()[0]
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
self.assertEqual(state, 'Z', f'Gazebo probe process {pid} is still live')
|
||||
|
||||
def test_bridge_does_not_start_without_clock(self):
|
||||
fake_gz = self.executable(self.root/'fake gz', '''
|
||||
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
|
||||
sleep 30
|
||||
''')
|
||||
fake_ros2 = self.executable(self.root/'bin/ros2', 'echo "bridge started"')
|
||||
env = dict(BRIDGE_WAIT_TIMEOUT='0.3', GZ_BIN=str(fake_gz), LD_LIBRARY_PATH='/vendor',
|
||||
PATH=f'{fake_ros2.parent}:{self.env["PATH"]}', GZ_PARTITION='isolated_test')
|
||||
start = time.monotonic()
|
||||
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
|
||||
self.assertLess(time.monotonic() - start, 2)
|
||||
self.expect_error(result, '等待 Gazebo /clock 超时')
|
||||
self.assertIn('isolated_test', result.stderr)
|
||||
self.executable(fake_gz, '''
|
||||
[[ "$*" == 'topic -e -t /clock -n 1' && ! -v LD_LIBRARY_PATH ]] || exit 4
|
||||
echo 'sim { sec: 1 }'
|
||||
''')
|
||||
result = self.run_command(['bash', str(SCRIPTS/'bridge_after_gz.sh')], **env)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('bridge started', result.stdout)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -1,334 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated Gazebo navigation scenario and score it using simulator truth."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from std_msgs.msg import Bool
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
from dds_environment import defaults as dds_defaults
|
||||
from lio_metrics import cylinder_clearance, metrics
|
||||
from verify_lio_stack import NODES, process_environment
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]',
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
parser.add_argument('--obstacle-radius',type=float,default=0.22)
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
if args.output.exists():
|
||||
parser.error('output must be a new directory')
|
||||
args.output.mkdir(parents=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()),
|
||||
LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
os.environ.update(dds_defaults(os.environ))
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
params_file = workspace/'src/sentry_sim/config/nav2_params.yaml'
|
||||
runtime = {
|
||||
'domain': os.environ['ROS_DOMAIN_ID'],
|
||||
'partition': os.environ['GZ_PARTITION'],
|
||||
'scenario': args.scenario,
|
||||
'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius],
|
||||
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
|
||||
}
|
||||
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
|
||||
log = None
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(workspace/'build/bin/field_localization_record'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', 'duration_sec:=600.0'], stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
samples = {'truth': [], 'estimate': []}
|
||||
health_events=[]
|
||||
actuator=[]
|
||||
subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100)
|
||||
subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid',
|
||||
lambda msg:health_events.append((time.monotonic(),msg.data)),10)
|
||||
subscriptions = []
|
||||
def sample(message, name):
|
||||
p = message.pose.pose if name == 'estimate' else message.pose
|
||||
samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec,
|
||||
p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w])
|
||||
subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth',
|
||||
lambda msg: sample(msg, 'truth'), qos_profile_sensor_data))
|
||||
subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry',
|
||||
lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data))
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
goal = None
|
||||
reached_readiness = False
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
reached_readiness = True
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'topic_qos':{topic:[{'node':p.node_name,'reliability':str(p.qos_profile.reliability)} for p in node.get_publishers_info_by_topic(topic)] for topic in ['/scan/points','/scan/points_filtered','/imu']},
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.scenario in ('cylinder','blocked') and result['passed']:
|
||||
# Obstacle lies on the initial straight corridor; a route around the cylinder exists.
|
||||
shape = f'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
|
||||
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
|
||||
if args.scenario == 'blocked':
|
||||
shape = '<box><size>1.6 1.6 0.8</size></box>'
|
||||
pose = '0 0 0.4 0 0 0'
|
||||
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
|
||||
gz = subprocess.run(['/usr/bin/gz', 'service', '-s', '/world/rmul_arena/create',
|
||||
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
|
||||
'--req', 'sdf: '+json.dumps(sdf)], capture_output=True,text=True,timeout=10)
|
||||
(args.output/'obstacle.log').write_text(gz.stdout+gz.stderr)
|
||||
if gz.returncode or 'data: true' not in gz.stdout:
|
||||
raise RuntimeError('obstacle insertion failed')
|
||||
until=time.monotonic()+2
|
||||
while time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if args.goal and result['passed']:
|
||||
goal_start_sim=node.get_clock().now().nanoseconds*1e-9
|
||||
goal_start_wall=time.monotonic()
|
||||
goal = subprocess.Popen([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
|
||||
stdout=open(args.output/'goal.log','w'), stderr=subprocess.STDOUT, text=True, start_new_session=True)
|
||||
until=time.monotonic()+(240 if args.scenario=="blocked" else 120)
|
||||
fault_time=None
|
||||
while goal.poll() is None and time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if args.scenario=='lidar_loss' and fault_time is None and time.monotonic()-goal_start_wall>=5 and actuator and sum(abs(v) for v in actuator[-1][1:])>0.1:
|
||||
owned=process_environment(process.pid)
|
||||
sensors=[p['pid'] for p in owned if p['executable'] and Path(p['executable'][0]).name=='self_filter']
|
||||
if len(sensors)!=1:
|
||||
raise RuntimeError('cannot identify the owned self_filter for fault injection')
|
||||
fault_time=time.monotonic();os.kill(sensors[0],signal.SIGTERM)
|
||||
if goal.poll() is None:
|
||||
os.killpg(goal.pid,signal.SIGINT)
|
||||
goal.wait(timeout=5)
|
||||
goal.stdout_text=(args.output/'goal.log').read_text()
|
||||
if args.scenario == 'blocked':
|
||||
terminal_time = time.monotonic()
|
||||
while time.monotonic() - terminal_time < 0.5:
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
result['blocked_zero_output'] = bool(
|
||||
actuator and actuator[-1][0] > terminal_time and actuator[-1][1:] == (0, 0, 0)
|
||||
)
|
||||
result['passed'] = result['passed'] and result['blocked_zero_output']
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
result['passed'] = (result['passed'] and len(publishers) == 1
|
||||
and counts['map_to_base_link'] == 0
|
||||
and not result['amcl_present'])
|
||||
result['goal_exit_code'] = goal.returncode
|
||||
if args.scenario=='lidar_loss':
|
||||
stops=[t for t,x,y,z in actuator if fault_time is not None and t>=fault_time and x==0 and y==0 and z==0]
|
||||
result['fault_stop_delay_sec']=min(stops)-fault_time if stops else None
|
||||
result['fault_goal_canceled']='结果: ❌ CANCELED' in goal.stdout_text
|
||||
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout_text
|
||||
result['goal_elapsed_wall_sec']=time.monotonic()-goal_start_wall
|
||||
result['trajectory_metrics']=metrics(samples['estimate'],samples['truth'])
|
||||
truth_goal=[row for row in samples['truth'] if row[0]>=goal_start_sim]
|
||||
result['truth_goal_error_m']=math.hypot(truth_goal[-1][1]-args.goal[0],truth_goal[-1][2]-args.goal[1]) if truth_goal else None
|
||||
result['minimum_cylinder_clearance_m']=min(cylinder_clearance(row,args.obstacle_x,args.obstacle_y,args.obstacle_radius) for row in truth_goal) if truth_goal and args.scenario=='cylinder' else None
|
||||
result['health_failures_during_goal']=sum(not value for stamp,value in health_events if stamp>=goal_start_wall)
|
||||
quality=result['trajectory_metrics']
|
||||
result['passed']=result['passed'] and quality['matched']>100 and quality['rpe_pairs']>0 and quality['maximum_position_error_m']<0.25 and quality['ate_translation_m']<0.1
|
||||
if args.scenario not in ('blocked','lidar_loss'):
|
||||
result['passed']=result['passed'] and result['truth_goal_error_m'] is not None and result['truth_goal_error_m']<=0.30
|
||||
if result['minimum_cylinder_clearance_m'] is not None:
|
||||
result['passed']=result['passed'] and result['minimum_cylinder_clearance_m']>=0
|
||||
result['passed'] = result['passed'] and ((args.scenario == 'blocked' and '结果: ❌ ABORTED' in goal.stdout_text) or (args.scenario == 'lidar_loss' and result['fault_goal_canceled'] and result['fault_stop_delay_sec'] is not None and result['fault_stop_delay_sec']<0.5) or (goal.returncode == 0 and result['goal_succeeded']))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription, subscriptions, subscriptions_health, subscription_actuator
|
||||
(args.output/'health_events.json').write_text(json.dumps(health_events))
|
||||
for name, rows in samples.items():
|
||||
with open(args.output/(name+'.tum'),'w') as output:
|
||||
for row in rows:
|
||||
output.write(' '.join(map(str,row))+'\n')
|
||||
if goal is not None and goal.poll() is None:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
try:
|
||||
goal.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(goal.pid, signal.SIGKILL)
|
||||
goal.wait()
|
||||
if recorder.poll() is None:
|
||||
os.killpg(recorder.pid, signal.SIGINT)
|
||||
try:
|
||||
recorder.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(recorder.pid, signal.SIGKILL)
|
||||
recorder.wait()
|
||||
record_log.close()
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Replay the same recorded southeast scans against two maps."""
|
||||
|
||||
import argparse
|
||||
from bisect import bisect_left
|
||||
import csv
|
||||
import json
|
||||
from pathlib import Path
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
import project_env
|
||||
|
||||
|
||||
def rotation(quaternion):
|
||||
x, y, z, w = np.asarray(quaternion)/np.linalg.norm(quaternion)
|
||||
return np.array(((1-2*(y*y+z*z), 2*(x*y-z*w), 2*(x*z+y*w)),
|
||||
(2*(x*y+z*w), 1-2*(x*x+z*z), 2*(y*z-x*w)),
|
||||
(2*(x*z-y*w), 2*(y*z+x*w), 1-2*(x*x+y*y))))
|
||||
|
||||
|
||||
def east_scans(dataset):
|
||||
rows = [list(map(float, l.split())) for l in (dataset/'truth.tum').read_text().splitlines()]
|
||||
if not rows:
|
||||
raise ValueError('southeast evaluation requires recorded ground truth')
|
||||
times = [r[0] for r in rows]
|
||||
mask = set()
|
||||
with (dataset/'scans.csv').open() as scans:
|
||||
for entry in csv.DictReader(scans):
|
||||
stamp = float(entry['timestamp'])
|
||||
index = bisect_left(times, stamp)
|
||||
if index == len(times) or (index > 0 and stamp-times[index-1] < times[index]-stamp):
|
||||
index -= 1
|
||||
time, x, y = rows[index][:3]
|
||||
if abs(time-stamp) <= 0.05 and x >= 4 and y <= -1.5:
|
||||
mask.add(stamp)
|
||||
return mask
|
||||
|
||||
|
||||
def compare_trace(path, stamps, imu_from_base):
|
||||
inliers, horizontal, horizontal_prior = [], [], []
|
||||
degenerate = x_weak = full = 0
|
||||
x, y, z = imu_from_base
|
||||
skew = np.array(((0, -z, y), (z, 0, -x), (-y, x, 0)))
|
||||
with path.open() as trace:
|
||||
for row in csv.DictReader(trace):
|
||||
phase = row['phase']
|
||||
stamp = float(row['scan_time'])
|
||||
if stamp not in stamps or phase == 'candidate':
|
||||
continue
|
||||
p = np.array([[float(row[f'P{i}_{j}']) for j in range(18)] for i in range(18)])
|
||||
j = np.zeros((2, 18))
|
||||
j[0, 0] = j[1, 1] = 1
|
||||
j[:, 6:9] = -(rotation([float(row[k]) for k in ('qx','qy','qz','qw')])@skew)[:2, :]
|
||||
sigma = 3*float(np.sqrt(max(0, np.linalg.eigvalsh(j@p@j.T)[-1])))
|
||||
if phase == 'prediction':
|
||||
if row['registration_stage'] != 'NOT_RUN':
|
||||
horizontal_prior.append(sigma)
|
||||
continue
|
||||
horizontal.append(sigma)
|
||||
inliers.append(int(row['inliers']))
|
||||
full += row['mode'] == 'FULL'
|
||||
dims = int(row['degenerate'])
|
||||
if dims:
|
||||
h = np.array([[float(row[f'H{i}_{j}']) for j in range(6)] for i in range(6)])
|
||||
if np.any(h):
|
||||
vt = np.linalg.svd(h)[2]
|
||||
x_weak += int(np.linalg.norm(vt[-dims:, 0]) >= 0.8)
|
||||
degenerate += 1
|
||||
if not inliers:
|
||||
raise RuntimeError('replay did not include the recorded southeast scans')
|
||||
return {'east_scans': len(inliers), 'accepted': full,
|
||||
'median_inliers': statistics.median(inliers), 'degenerate_scans': degenerate,
|
||||
'x_weak_scans': x_weak, 'maximum_horizontal_3sigma_m': max(horizontal),
|
||||
'maximum_prior_horizontal_3sigma_m': max(horizontal_prior, default=None)}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ('dataset', 'baseline', 'candidate', 'output'):
|
||||
parser.add_argument(f'--{name}', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
stamps = east_scans(args.dataset)
|
||||
if len(stamps) < 10:
|
||||
parser.error('verification dataset must contain at least ten scans in x >= 4, y <= -1.5')
|
||||
transform = next(line for line in (args.dataset/'config.txt').read_text().splitlines()
|
||||
if line.startswith('base_from_imu ')).split()[1:]
|
||||
extrinsic = list(map(float, transform))
|
||||
imu_from_base = -rotation(extrinsic[3:]).T @ extrinsic[:3]
|
||||
exe = project_env.require_executable(project_env.find_bin_dir()/'field_localization_replay',
|
||||
'field_localization_replay')
|
||||
args.output.mkdir(parents=True)
|
||||
reports = {}
|
||||
for name, world_map in (('baseline', args.baseline), ('candidate', args.candidate)):
|
||||
directory = args.output/name
|
||||
subprocess.run([str(exe), '--dataset', str(args.dataset), '--mode', 'localization',
|
||||
'--map', str(world_map), '--output', str(directory)], check=True)
|
||||
reports[name] = compare_trace(directory/'filter_trace.csv', stamps, imu_from_base)
|
||||
content = json.dumps(reports, indent=2)
|
||||
(args.output/'southeast.json').write_text(content+'\n')
|
||||
print(content)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File renamed without changes.
@@ -21,14 +21,15 @@ def main():
|
||||
parser.error('repeats must be positive')
|
||||
if args.output.exists():parser.error('output must be new')
|
||||
args.output.mkdir(parents=True)
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
root = script_dir.parents[1]
|
||||
results=[]
|
||||
for scenario in args.scenario or ['clear', 'cylinder', 'blocked']:
|
||||
count = args.repeats if args.repeats is not None else (3 if scenario in ('clear', 'cylinder') else 1)
|
||||
for index in range(1, count+1):
|
||||
name=f'{scenario}_{index}';folder=args.output/name
|
||||
with open(args.output/(name+'.log'),'w') as log:
|
||||
command=[sys.executable,str(root/'tools/validate_lio_navigation.py'),
|
||||
command=[sys.executable,str(script_dir/'validate_lio_navigation.py'),
|
||||
'--launcher',args.launcher,'--map',str(args.map.resolve()),'--output',str(folder.resolve()),
|
||||
'--scenario',scenario,'--goal','0','0']
|
||||
if args.domain is not None:
|
||||
@@ -0,0 +1,532 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run an isolated Gazebo navigation scenario and score it using simulator truth."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.action import ActionClient
|
||||
from action_msgs.msg import GoalStatus
|
||||
from rclpy.parameter import Parameter
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.srv import IsPathValid
|
||||
from nav2_msgs.action import ComputePathToPose, FollowPath
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from std_msgs.msg import Bool
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from arena_grid import ARENA_GOALS, START, ArenaGrid
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
from dds_environment import defaults as dds_defaults
|
||||
from lio_metrics import cylinder_clearance, metrics
|
||||
from verify_lio_stack import NODES, process_environment
|
||||
|
||||
|
||||
ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0))
|
||||
ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16)
|
||||
|
||||
|
||||
def check_field_coverage(node, grid):
|
||||
coverage = grid.coverage()
|
||||
client = ActionClient(node, ComputePathToPose, '/compute_path_to_pose')
|
||||
try:
|
||||
if not client.wait_for_server(timeout_sec=8):
|
||||
raise RuntimeError('compute_path_to_pose unavailable for field coverage')
|
||||
|
||||
def pose(point):
|
||||
message = PoseStamped()
|
||||
message.header.frame_id = 'map'
|
||||
message.pose.position.x, message.pose.position.y = point
|
||||
message.pose.orientation.w = 1.0
|
||||
return message
|
||||
|
||||
checks = []
|
||||
for point in coverage.pop('samples'):
|
||||
request = ComputePathToPose.Goal()
|
||||
request.start = pose(START)
|
||||
request.goal = pose(point)
|
||||
request.use_start = True
|
||||
future = client.send_goal_async(request)
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
handle = future.result() if future.done() else None
|
||||
check = {'target': point, 'passed': False}
|
||||
if handle is None or not handle.accepted:
|
||||
check['error'] = 'goal rejected or acceptance timed out'
|
||||
else:
|
||||
future = handle.get_result_async()
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=5)
|
||||
wrapped = future.result() if future.done() else None
|
||||
if wrapped is None:
|
||||
cancel = handle.cancel_goal_async()
|
||||
rclpy.spin_until_future_complete(node, cancel, timeout_sec=1)
|
||||
check['error'] = 'planner response timed out'
|
||||
else:
|
||||
outcome = wrapped.result
|
||||
check.update(error_code=outcome.error_code, error=outcome.error_msg)
|
||||
if wrapped.status == GoalStatus.STATUS_SUCCEEDED and outcome.path.poses:
|
||||
endpoint = outcome.path.poses[-1].pose.position
|
||||
check['endpoint_error_m'] = math.hypot(endpoint.x-point[0], endpoint.y-point[1])
|
||||
check['passed'] = outcome.error_code == 0 and check['endpoint_error_m'] <= 0.30
|
||||
checks.append(check)
|
||||
finally:
|
||||
client.destroy()
|
||||
coverage.update(planned=sum(c['passed'] for c in checks), sample_count=len(checks), checks=checks)
|
||||
return coverage
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--map', type=Path, required=True)
|
||||
parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio')
|
||||
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
goals = parser.add_mutually_exclusive_group()
|
||||
goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
|
||||
goals.add_argument('--full-field', action='store_true',
|
||||
help='check reachability in 1 m tiles and navigate the whole-field route')
|
||||
goals.add_argument('--round-trip-regression', action='store_true',
|
||||
help='run the five recorded goals without restarting the stack')
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]',
|
||||
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
|
||||
parser.add_argument('--timeout', type=float, default=420.0,
|
||||
help='whole-stack validation deadline, including up to three startup attempts')
|
||||
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
|
||||
parser.add_argument('--obstacle-x',type=float,default=-4.0)
|
||||
parser.add_argument('--obstacle-y',type=float,default=-1.5)
|
||||
parser.add_argument('--obstacle-radius',type=float,default=0.22)
|
||||
parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load')
|
||||
args = parser.parse_args()
|
||||
if args.round_trip_regression and args.scenario not in ('clear', 'cylinder'):
|
||||
parser.error('--round-trip-regression requires clear or cylinder')
|
||||
if args.full_field and args.scenario != 'clear':
|
||||
parser.error('--full-field starts the clear-field coverage route')
|
||||
multileg = args.round_trip_regression or args.full_field
|
||||
route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ())
|
||||
pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route)
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
if args.output.exists():
|
||||
parser.error('output must be a new directory')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
recorder_exe = project_env.require_executable(bin_dir/'field_localization_record',
|
||||
'field_localization_record')
|
||||
grid = ArenaGrid(project_env.find_map_yaml()) if args.full_field else None
|
||||
if route:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except (project_env.ProbeError, ValueError, OSError) as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()),
|
||||
LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=args.lio_cloud_topic)
|
||||
os.environ.update(dds_defaults(os.environ))
|
||||
os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve()))
|
||||
os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve()))
|
||||
params_file = workspace/'src/sentry_sim/config/nav2_params.yaml'
|
||||
runtime = {
|
||||
'domain': os.environ['ROS_DOMAIN_ID'],
|
||||
'partition': os.environ['GZ_PARTITION'],
|
||||
'scenario': args.scenario,
|
||||
'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius],
|
||||
'goals': route,
|
||||
'pauses_wall_sec': pauses,
|
||||
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
|
||||
'lio_map_sha256': hashlib.sha256(args.map.read_bytes()).hexdigest(),
|
||||
'point_cloud_topic': args.lio_cloud_topic,
|
||||
}
|
||||
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
|
||||
log = None
|
||||
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0
|
||||
record_log = open(args.output/'record.log', 'w', encoding='utf8')
|
||||
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
|
||||
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
|
||||
'-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'],
|
||||
stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
else:
|
||||
command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'),
|
||||
'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}']
|
||||
log = open(args.output/'stack.log', 'w', encoding='utf8')
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(command, cwd=workspace, start_new_session=True,
|
||||
stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
rclpy.init()
|
||||
node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)])
|
||||
publishers = set()
|
||||
samples = {'truth': [], 'estimate': []}
|
||||
health_events = []
|
||||
health_transitions = []
|
||||
actuator = []
|
||||
last_map_tf_wall = None
|
||||
|
||||
def on_health(msg):
|
||||
stamp = time.monotonic()
|
||||
if not health_events or msg.data != health_events[-1][1]:
|
||||
health_transitions.append({'wall': stamp, 'sim': sim_now(), 'valid': msg.data})
|
||||
health_events.append((stamp, msg.data))
|
||||
|
||||
def sim_now():
|
||||
return node.get_clock().now().nanoseconds * 1e-9
|
||||
|
||||
def spin_for(seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100)
|
||||
subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid',
|
||||
on_health, 10)
|
||||
subscriptions = []
|
||||
def sample(message, name):
|
||||
p = message.pose.pose if name == 'estimate' else message.pose
|
||||
samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec,
|
||||
p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w])
|
||||
subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth',
|
||||
lambda msg: sample(msg, 'truth'), qos_profile_sensor_data))
|
||||
subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry',
|
||||
lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data))
|
||||
counts = {'map_to_odom': 0, 'map_to_base_link': 0}
|
||||
|
||||
def on_tf(msg, info):
|
||||
nonlocal last_map_tf_wall
|
||||
for transform in msg.transforms:
|
||||
if transform.header.frame_id != 'map':
|
||||
continue
|
||||
if transform.child_frame_id == 'odom':
|
||||
gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid
|
||||
publishers.add(json.dumps(gid, sort_keys=True, default=str))
|
||||
counts['map_to_odom'] += 1
|
||||
last_map_tf_wall = time.monotonic()
|
||||
if transform.child_frame_id == 'base_link':
|
||||
counts['map_to_base_link'] += 1
|
||||
|
||||
subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500)
|
||||
clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES}
|
||||
path_client = node.create_client(IsPathValid, '/is_path_valid')
|
||||
active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active')
|
||||
parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters')
|
||||
states = {}
|
||||
processes = []
|
||||
rviz = None
|
||||
goal = None
|
||||
reached_readiness = False
|
||||
result = {}
|
||||
try:
|
||||
if args.rviz:
|
||||
rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d',
|
||||
str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args',
|
||||
'-p', 'use_sim_time:=true'],
|
||||
env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'},
|
||||
start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
|
||||
deadline = time.monotonic()+args.timeout
|
||||
last_check = 0.0
|
||||
stable_since = None
|
||||
manager_completed = False
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited')
|
||||
if time.monotonic()-last_check < 0.5:
|
||||
continue
|
||||
last_check = time.monotonic()
|
||||
if not processes and time.monotonic()-started > 8:
|
||||
processes = process_environment(process.pid)
|
||||
states = {}
|
||||
pending = {}
|
||||
for name, client in clients.items():
|
||||
if not client.service_is_ready():
|
||||
continue
|
||||
pending[name] = client.call_async(GetState.Request())
|
||||
poll_end = time.monotonic()+1
|
||||
while time.monotonic() < poll_end and any(not f.done() for f in pending.values()):
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
for name, future in pending.items():
|
||||
if future.done() and future.result():
|
||||
states[name] = future.result().current_state.id
|
||||
else:
|
||||
clients[name].remove_pending_request(future)
|
||||
log_path = args.output/'stack.log'
|
||||
text = log_path.read_text(errors='replace') if log_path.exists() else ''
|
||||
manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line
|
||||
for line in text.splitlines())
|
||||
if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]:
|
||||
if stable_since is None:
|
||||
stable_since = time.monotonic()
|
||||
if time.monotonic()-stable_since >= 2:
|
||||
reached_readiness = True
|
||||
break
|
||||
else:
|
||||
stable_since = None
|
||||
processes = process_environment(process.pid)
|
||||
names = sorted(set(node.get_node_names()))
|
||||
path_ready = path_client.wait_for_service(timeout_sec=2)
|
||||
path_response = None
|
||||
if path_ready:
|
||||
future = path_client.call_async(path_probe_request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=3)
|
||||
if future.done() and future.result() is not None:
|
||||
path_response = str(future.result())
|
||||
manager_active = False
|
||||
if active_client.wait_for_service(timeout_sec=1):
|
||||
future = active_client.call_async(Trigger.Request())
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
manager_active = bool(future.done() and future.result() and future.result().success)
|
||||
managed_nodes = []
|
||||
if parameter_client.wait_for_service(timeout_sec=1):
|
||||
future = parameter_client.call_async(GetParameters.Request(names=['node_names']))
|
||||
rclpy.spin_until_future_complete(node, future, timeout_sec=2)
|
||||
if future.done() and future.result() and future.result().values:
|
||||
managed_nodes = list(future.result().values[0].string_array_value)
|
||||
result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started,
|
||||
'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()),
|
||||
'rmw': get_rmw_implementation_identifier(), 'processes': processes,
|
||||
'node_counts': dict(Counter(node.get_node_names())),
|
||||
'services': dict(node.get_service_names_and_types()),
|
||||
'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))),
|
||||
'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))},
|
||||
'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response,
|
||||
'topic_qos': {
|
||||
topic: [{'node': p.node_name, 'reliability': str(p.qos_profile.reliability)}
|
||||
for p in node.get_publishers_info_by_topic(topic)]
|
||||
for topic in dict.fromkeys(('/scan/points', '/scan/points_filtered', args.lio_cloud_topic, '/imu'))
|
||||
},
|
||||
'manager_active': manager_active, 'managed_nodes': managed_nodes,
|
||||
'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names,
|
||||
'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts}
|
||||
result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None
|
||||
and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes)
|
||||
and all(states.get(name) == 3 for name in NODES) and not result['amcl_present']
|
||||
and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0
|
||||
and counts['map_to_base_link'] == 0)
|
||||
if grid is not None and result['passed']:
|
||||
coverage = check_field_coverage(node, grid)
|
||||
result['field_coverage'] = coverage
|
||||
print(f'field coverage: {coverage["planned"]}/{coverage["sample_count"]} representative goals planned', flush=True)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.scenario in ('cylinder','blocked') and result['passed']:
|
||||
# Obstacle lies on the initial straight corridor; a route around the cylinder exists.
|
||||
shape = f'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
|
||||
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
|
||||
if args.scenario == 'blocked':
|
||||
shape = '<box><size>1.6 1.6 0.8</size></box>'
|
||||
pose = '0 0 0.4 0 0 0'
|
||||
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
|
||||
gz = project_env.run_gz(gz_exe, 'service', '-s', '/world/rmul_arena/create',
|
||||
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
|
||||
'--req', 'sdf: '+json.dumps(sdf), timeout=10)
|
||||
(args.output/'obstacle.log').write_text(gz.stdout+gz.stderr)
|
||||
if gz.returncode or 'data: true' not in gz.stdout:
|
||||
raise RuntimeError('obstacle insertion failed')
|
||||
until=time.monotonic()+2
|
||||
while time.monotonic()<until:
|
||||
rclpy.spin_once(node,timeout_sec=0.02)
|
||||
if route and result['passed']:
|
||||
legs = []
|
||||
start_sim = None
|
||||
start_wall = None
|
||||
for index, target in enumerate(route):
|
||||
spin_for(pauses[index])
|
||||
goal_start_sim, goal_start_wall = sim_now(), time.monotonic()
|
||||
if start_sim is None:
|
||||
start_sim, start_wall = goal_start_sim, goal_start_wall
|
||||
goal_log = args.output/(f'goal_{index+1}.log' if multileg else 'goal.log')
|
||||
command = [str(nav_client), *map(str, target), '0']
|
||||
with goal_log.open('w') as stream:
|
||||
goal = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT,
|
||||
text=True, start_new_session=True)
|
||||
until = time.monotonic() + (240 if args.scenario == 'blocked' else 180)
|
||||
fault_time = None
|
||||
while goal.poll() is None and time.monotonic() < until:
|
||||
if process.poll() is not None:
|
||||
raise RuntimeError('stack exited during navigation')
|
||||
rclpy.spin_once(node, timeout_sec=0.02)
|
||||
if (args.scenario == 'lidar_loss' and fault_time is None
|
||||
and time.monotonic()-goal_start_wall >= 5 and actuator
|
||||
and sum(abs(v) for v in actuator[-1][1:]) > 0.1):
|
||||
owned = process_environment(process.pid)
|
||||
sensors = [p['pid'] for p in owned if p['executable']
|
||||
and Path(p['executable'][0]).name == 'self_filter']
|
||||
if len(sensors) != 1:
|
||||
raise RuntimeError('cannot identify the owned self_filter for fault injection')
|
||||
fault_time = time.monotonic()
|
||||
os.kill(sensors[0], signal.SIGTERM)
|
||||
timed_out = goal.poll() is None
|
||||
if timed_out:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
goal.wait(timeout=5)
|
||||
goal_end_wall = time.monotonic()
|
||||
spin_for(0.3)
|
||||
goal_end_sim = sim_now()
|
||||
output = goal_log.read_text()
|
||||
truth_goal = [row for row in samples['truth'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
estimate_goal = [row for row in samples['estimate'] if goal_start_sim <= row[0] <= goal_end_sim]
|
||||
leg = {
|
||||
'goal': target, 'goal_exit_code': goal.returncode,
|
||||
'goal_succeeded': not timed_out and goal.returncode == 0 and '结果: ✅ SUCCEEDED' in output,
|
||||
'goal_elapsed_wall_sec': goal_end_wall-goal_start_wall,
|
||||
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
|
||||
'trajectory_metrics': metrics(estimate_goal, truth_goal),
|
||||
'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None,
|
||||
'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal)
|
||||
if truth_goal and args.scenario == 'cylinder' else None,
|
||||
'health_failures_during_goal': sum(not value for stamp, value in health_events
|
||||
if goal_start_wall <= stamp <= goal_end_wall),
|
||||
}
|
||||
if args.scenario == 'blocked':
|
||||
stopped = bool(actuator and actuator[-1][0] > goal_end_wall and actuator[-1][1:] == (0, 0, 0))
|
||||
result['blocked_zero_output'] = stopped
|
||||
leg['passed'] = (not timed_out and '结果: ❌ ABORTED' in output and stopped
|
||||
and leg['health_failures_during_goal'] == 0
|
||||
and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] > 0.30)
|
||||
elif args.scenario == 'lidar_loss':
|
||||
spin_for(0.7)
|
||||
stops = [t for t, x, y, z in actuator if fault_time is not None and t >= fault_time and x == y == z == 0]
|
||||
delay = min(stops)-fault_time if stops else None
|
||||
lost = next((event for event in health_transitions if fault_time is not None
|
||||
and event['wall'] >= fault_time and not event['valid']), None)
|
||||
canceled = '结果: ❌ CANCELED' in output
|
||||
# Once TF stops, FollowPath can complete with TF_ERROR before the relay's
|
||||
# cancel request returns. Both outcomes terminate the in-flight goal.
|
||||
tf_abort = ('结果: ❌ ABORTED' in output
|
||||
and f'Nav2 error_code={FollowPath.Result.TF_ERROR} ' in output)
|
||||
terminated = bool(lost and lost['wall'] <= goal_end_wall and (canceled or tf_abort))
|
||||
result.update(fault_goal_canceled=canceled,
|
||||
fault_goal_tf_aborted=tf_abort,
|
||||
fault_goal_terminated=terminated,
|
||||
fault_stop_delay_sec=delay,
|
||||
fault_tf_halted=bool(lost and last_map_tf_wall is not None
|
||||
and last_map_tf_wall <= lost['wall']+0.1))
|
||||
if lost:
|
||||
retry_log = args.output/'retry_invalid_localization.log'
|
||||
with retry_log.open('w') as stream:
|
||||
retry = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=20)
|
||||
retry_text = retry_log.read_text()
|
||||
result['invalid_retry_blocked'] = (retry.returncode != 0 and '定位不可用' in retry_text
|
||||
and '目标已接受' not in retry_text)
|
||||
else:
|
||||
result['invalid_retry_blocked'] = False
|
||||
leg['passed'] = (terminated and not timed_out and delay is not None and delay < 0.5
|
||||
and result['fault_tf_halted'] and result['invalid_retry_blocked'])
|
||||
else:
|
||||
leg['passed'] = (leg['goal_succeeded'] and leg['truth_goal_error_m'] is not None
|
||||
and leg['truth_goal_error_m'] <= 0.30
|
||||
and (leg['minimum_cylinder_clearance_m'] is None
|
||||
or leg['minimum_cylinder_clearance_m'] > 0))
|
||||
quality = leg['trajectory_metrics']
|
||||
leg['passed'] = (leg['passed'] and quality['matched'] > 100 and quality['rpe_pairs'] > 0
|
||||
and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1)
|
||||
legs.append(leg)
|
||||
result.update(leg)
|
||||
result['legs'] = legs
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(f'leg {index+1}/{len(route)} {tuple(target)}: passed={leg["passed"]} '
|
||||
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
|
||||
if multileg and not leg['goal_succeeded']:
|
||||
spin_for(8)
|
||||
break
|
||||
result.update(counts)
|
||||
result['map_to_odom_publishers'] = len(publishers)
|
||||
result['amcl_present'] = 'amcl' in node.get_node_names()
|
||||
# Include drift during the pauses, but keep each goal's outcome independent.
|
||||
if multileg:
|
||||
end_sim = legs[-1]['end_sim']
|
||||
quality = metrics(*([row for row in samples[name] if start_sim <= row[0] <= end_sim]
|
||||
for name in ('estimate', 'truth')))
|
||||
result['trajectory_metrics'] = quality
|
||||
result['first_localization_loss'] = next(
|
||||
(event for event in health_transitions if event['wall'] >= start_wall and not event['valid']), None)
|
||||
clearances = [leg['minimum_cylinder_clearance_m'] for leg in legs
|
||||
if leg['minimum_cylinder_clearance_m'] is not None]
|
||||
result['minimum_cylinder_clearance_m'] = min(clearances) if clearances else None
|
||||
result['passed'] = (quality['maximum_position_error_m'] is not None
|
||||
and quality['maximum_position_error_m'] < 0.25
|
||||
and quality['ate_translation_m'] < 0.1
|
||||
and result['first_localization_loss'] is None)
|
||||
if grid is not None:
|
||||
result['passed'] = (result['passed'] and coverage['sample_count'] > 0
|
||||
and coverage['planned'] == coverage['sample_count'])
|
||||
result['passed'] = (result['passed'] and len(legs) == len(route) and all(leg['passed'] for leg in legs)
|
||||
and len(publishers) == 1 and counts['map_to_base_link'] == 0
|
||||
and not result['amcl_present'])
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps({k: v for k, v in result.items() if k not in
|
||||
('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True)
|
||||
if not result['passed']:
|
||||
raise RuntimeError('stack integration validation failed')
|
||||
except Exception as error:
|
||||
result.update(passed=False, error=str(error))
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
raise
|
||||
finally:
|
||||
_ = subscription, subscriptions, subscriptions_health, subscription_actuator
|
||||
(args.output/'health_events.json').write_text(json.dumps(health_events))
|
||||
(args.output/'health_transitions.json').write_text(json.dumps(health_transitions, indent=2))
|
||||
for name, rows in samples.items():
|
||||
with open(args.output/(name+'.tum'),'w') as output:
|
||||
for row in rows:
|
||||
output.write(' '.join(map(str,row))+'\n')
|
||||
if goal is not None and goal.poll() is None:
|
||||
os.killpg(goal.pid, signal.SIGINT)
|
||||
try:
|
||||
goal.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(goal.pid, signal.SIGKILL)
|
||||
goal.wait()
|
||||
if recorder.poll() is None:
|
||||
os.killpg(recorder.pid, signal.SIGINT)
|
||||
try:
|
||||
recorder.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(recorder.pid, signal.SIGKILL)
|
||||
recorder.wait()
|
||||
record_log.close()
|
||||
if process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=20)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
if rviz is not None:
|
||||
os.killpg(rviz.pid, signal.SIGINT)
|
||||
try:
|
||||
rviz.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(rviz.pid, signal.SIGKILL)
|
||||
rviz.wait()
|
||||
if log:
|
||||
log.close()
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -6,6 +6,7 @@ import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter
|
||||
@@ -19,6 +20,9 @@ from nav2_msgs.srv import IsPathValid
|
||||
from rcl_interfaces.srv import GetParameters
|
||||
from std_srvs.srv import Trigger
|
||||
from rclpy.utilities import get_rmw_implementation_identifier
|
||||
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'),
|
||||
str(Path(__file__).resolve().parents[1])]
|
||||
import project_env
|
||||
from nav2_startup import path_probe_request
|
||||
|
||||
NODES = ['map_server', 'controller_server', 'planner_server', 'smoother_server',
|
||||
@@ -77,13 +81,21 @@ def main():
|
||||
args = parser.parse_args()
|
||||
if not args.map.is_file():
|
||||
parser.error('map missing')
|
||||
workspace = project_env.WORKSPACE
|
||||
try:
|
||||
gz_exe = project_env.find_gz_bin()
|
||||
bin_dir = project_env.find_bin_dir(workspace)
|
||||
if args.goal is not None:
|
||||
nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client')
|
||||
except project_env.ProbeError as error:
|
||||
parser.exit(1, f'{parser.prog}: {error}\n')
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
session = uuid.uuid4().hex[:12]
|
||||
os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir))
|
||||
os.environ.update(ROS_DOMAIN_ID=str(50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}',
|
||||
ROS2CLI_DISABLE_DAEMON='1',
|
||||
HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization',
|
||||
LIO_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve()))
|
||||
workspace = Path(__file__).resolve().parents[1]
|
||||
log = None
|
||||
if args.launcher == 'shell':
|
||||
command = ['bash', str(workspace/'scripts/sentry_up.sh')]
|
||||
@@ -202,7 +214,7 @@ def main():
|
||||
and counts['map_to_base_link'] == 0)
|
||||
(args.output/'result.json').write_text(json.dumps(result, indent=2))
|
||||
if args.goal and result['passed']:
|
||||
goal = subprocess.run([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
|
||||
goal = subprocess.run([str(nav_client), *map(str, args.goal), '0'],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=200)
|
||||
(args.output/'goal.log').write_text(goal.stdout)
|
||||
result['goal_exit_code'] = goal.returncode
|
||||
Reference in new issue
Block a user