docs: 对齐 build/bin 布局、日志自动落盘、env_common 探测库与 tools 精简
This commit is contained in:
1 parent
0843c6ade0
commit
3c58a08dad
47 files changed
+1063
-2009
No files matched your search
+41
-24
@@ -6,31 +6,34 @@
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(主力工具) |
|
||||
| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(唯一的建模入口) |
|
||||
| `decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab/Blender) |
|
||||
| `gen_sdf.sh` | URDF(xacro) → `models/sentry/model.sdf` + `generated/sentry.urdf` |
|
||||
| `build_meshes.py` | 旧版:只处理「底盘」导出(已被 `build_vehicle.py` 取代) |
|
||||
| `build_gimbal.py` | 旧版:只处理「云台」导出(已被取代) |
|
||||
|
||||
## 演示 / 测试
|
||||
## 体检
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `demo.py` | 前进 → 转向 → 再前进,并打印雷达和里程计 |
|
||||
| `drive_demo.py` | 走正方形并生成 SVG 轨迹图(`generated/drive_trajectory.svg`) |
|
||||
| `build/linux/x86_64/release/nav_client` | ★ 发 Nav2 目标点。**发之前先读 `/map` 预检**:占据值 ≥65、未知格、净空 <0.5 m(车体半对角 0.422 m)都直接拦下并说明原因,不合格不发。通过后打印位置/重试次数/结果/离目标误差/field 坐标 |
|
||||
| `free_goals.py` | ★ 从 `rmul_2027.yaml` + `.pgm` 算出「从起点连通的安全区」并列出可去目标点(附净空、距离、可直接复制的 `build/linux/x86_64/release/nav_client` 命令)。**不需要起 ROS** |
|
||||
| `tf_watch.py` | ★ 实时盯 `map→odom` / `odom→base_link` / `map→base_link` 三条 TF 边 + Gazebo 真值 + `/scan2d` 有效率,超过 0.25 m 的跳变会打 ⚠️。**抓定位瞬移专用**:一个窗口开着,另一个窗口发目标 |
|
||||
| ~~`send_goal.py`~~ | ⚠️ **已废弃(空炮)**:往 `/goal_pose` 话题发 PoseStamped,但 Nav2 **没有任何节点订阅它**(`lib/nav2_bt_navigator/bt_navigator` 里根本没有 `goal_pose` 这个字符串)。要发目标请用 `build/linux/x86_64/release/nav_client` |
|
||||
| `scan_probe.py` | 雷达质量体检:有效束、距离分布、**有没有被车体糊住**。`scan_probe.py [话题]`,默认 `/scan2d` |
|
||||
| `probe_all.py` | 检查 `/clock /odom /scan /tf` 有没有数据 |
|
||||
| `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 统计各级 `/cmd_vel` 消息数 |
|
||||
| `probe_sub.py` | 最小订阅示例 |
|
||||
| `smoke_probe.py` | 全栈冒烟:等 Nav2 激活 → 收点云 → 发目标点验结果 |
|
||||
| `amcl_drift_demo.py` | ★ AMCL 效果演示:让里程计说谎(`SENTRY_ODOM_SCALE`),对比真值/原始里程计/AMCL 三列 |
|
||||
| `mark_field_center.py` | 把「场地中心 = 零点」画成 RViz Marker(红圆柱=map 帧、绿球=field 帧,重合即正确) |
|
||||
| `check_dds.sh` | ★ Fast DDS 体检:`/dev/shm` 残留段、进程、DDS 环境变量。加 `--clean` 清理残留 |
|
||||
| `check_stack.py` | ★ **只读体检**:生命周期状态 + 5 个话题有没有数据 + TF,一条命令问清"现在这套栈健康吗" |
|
||||
| `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。
|
||||
|
||||
## 构建 / 编辑器
|
||||
|
||||
@@ -49,11 +52,25 @@
|
||||
# 机械给了新装配体
|
||||
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
|
||||
|
||||
# 演示
|
||||
python3 tools/drive_demo.py 1.0
|
||||
python3 tools/scan_probe.py # 默认查 /scan2d(给 AMCL 用的)
|
||||
python3 tools/scan_probe.py /scan # 查 3D 雷达中间层(+22.5°,不可用)
|
||||
```
|
||||
|
||||
> 这些脚本按「单次运行」写的:需要先按根目录 README 把仿真跑起来,再在另一个终端执行。
|
||||
> 建模类脚本是**离线**的,不需要起仿真。体检类脚本要先按根目录 README 把仿真跑起来,
|
||||
> 再在另一个终端执行。
|
||||
|
||||
## 2026-11-21 精简掉了什么
|
||||
|
||||
一次性排查脚本已全部删除(都在 git 历史里,需要时 `git show <commit>:tools/<名字>` 能捞回来):
|
||||
|
||||
| 删掉的 | 原因 |
|
||||
|---|---|
|
||||
| `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` 的整车装配体方案取代 |
|
||||
|
||||
> **删脚本不影响已有产物**:`src/sentry_sim/meshes/base.stl`、`wheel.stl` 是已经生成好的,
|
||||
> URDF 引用的是这些文件。重跑建模用 `build_vehicle.py` 即可。
|
||||
@@ -1,165 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""AMCL 效果演示:让里程计「说谎」,看 AMCL 是不是在纠正它。
|
||||
|
||||
对比三列:
|
||||
|
||||
真值 Gazebo 世界坐标(物理真相)
|
||||
原始里程计 odom -> base_link(被 odom_scale 打了比例误差,会越走越偏)
|
||||
AMCL 定位 map -> base_link(AMCL 用扫描 + 地图纠正后的结果)
|
||||
|
||||
期望:原始里程计的偏差随行进距离增长,而 AMCL 一直贴在真值附近。
|
||||
|
||||
用法:
|
||||
|
||||
# 终端 1:启动仿真,并给里程计加 15% 比例误差
|
||||
SENTRY_ODOM_SCALE=1.15 HEADLESS=1 scripts/sentry_up.sh
|
||||
|
||||
# 终端 2:等 AMCL 激活后
|
||||
python3 tools/amcl_drift_demo.py
|
||||
|
||||
不设 `SENTRY_ODOM_SCALE` 也能跑(等于 1.0 真实里程计),但那样看不出 AMCL 的价值
|
||||
—— 因为仿真里 odom 本来就是真值。
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
import rclpy.time
|
||||
from geometry_msgs.msg import Twist
|
||||
from rclpy.duration import Duration
|
||||
from rclpy.node import Node
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
# 复用 tools/check_stack.py 的 gz_model_pose():它已经处理好了
|
||||
# · GZ_PARTITION(默认 sentry,和 sentry_up.sh 一致)
|
||||
# · 清掉 LD_LIBRARY_PATH 用系统版 gz
|
||||
# 自己再写一遍就会踩「分区写死」的坑(本脚本第一版就是这个 bug)。
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import check_stack as cs # noqa: E402
|
||||
|
||||
SCALE = float(os.environ.get('SENTRY_ODOM_SCALE', '1.0'))
|
||||
|
||||
|
||||
def gz_truth():
|
||||
"""Gazebo 里的真实位姿(世界坐标 == 场地坐标)。"""
|
||||
pose = cs.gz_model_pose('sentry')
|
||||
return (pose[0], pose[1]) if pose else None
|
||||
|
||||
|
||||
rclpy.init()
|
||||
node = Node('amcl_drift_demo')
|
||||
node.set_parameters([rclpy.parameter.Parameter(
|
||||
'use_sim_time', rclpy.Parameter.Type.BOOL, True)])
|
||||
buf = Buffer()
|
||||
TransformListener(buf, node)
|
||||
pub = node.create_publisher(Twist, '/cmd_vel', 10)
|
||||
|
||||
end = time.time() + 20
|
||||
while time.time() < end:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
try:
|
||||
buf.lookup_transform('map', 'base_link', rclpy.time.Time(),
|
||||
Duration(seconds=0.5))
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def tf_xy(target, source):
|
||||
try:
|
||||
t = buf.lookup_transform(target, source, rclpy.time.Time(),
|
||||
Duration(seconds=0.5)).transform.translation
|
||||
return t.x, t.y
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
# ---------- 启动自检:读不到就别往下跑 ----------
|
||||
origin = gz_truth()
|
||||
if origin is None:
|
||||
print('❌ 读不到 Gazebo 真值,无法做对照。可能原因:')
|
||||
print(' ① 仿真没在跑')
|
||||
print(' ② GZ_PARTITION 对不上(sentry_up.sh 默认用 sentry)')
|
||||
print(' 先确认:GZ_PARTITION=%s gz model -m sentry -p'
|
||||
% os.environ.get('GZ_PARTITION', 'sentry'))
|
||||
print(' 或者直接跑:python3 tools/check_stack.py')
|
||||
rclpy.try_shutdown()
|
||||
sys.exit(1)
|
||||
|
||||
if tf_xy('map', 'base_link') is None:
|
||||
print('❌ 读不到 TF map -> base_link(AMCL 可能还没激活)')
|
||||
print(' 等 30~60 秒再试,或先跑 python3 tools/check_stack.py')
|
||||
rclpy.try_shutdown()
|
||||
sys.exit(1)
|
||||
|
||||
print('\n⚠️ 本演示**直接发 /cmd_vel,绕过了整个 Nav2** —— 所以没有避障。')
|
||||
print(' 车撞到东西是预期的:这里要的是「里程计和真实位置不一致」,')
|
||||
print(' 走 Nav2 的话代价地图会把它绕开,就制造不出漂移了。')
|
||||
print(' Nav2 自己的避障要另外验证(用 build/linux/x86_64/release/nav_client 发目标)。')
|
||||
print()
|
||||
print('odom_scale = %.2f (1.00 = 真实里程计;>1 = 报告的距离偏大)' % SCALE)
|
||||
if abs(SCALE - 1.0) < 1e-6:
|
||||
print('⚠️ 现在是 1.00 —— 仿真里 odom 本来就是真值,看不出 AMCL 的价值。')
|
||||
print(' 想看效果:SENTRY_ODOM_SCALE=1.15 HEADLESS=1 scripts/sentry_up.sh')
|
||||
print('出发点 = (%.3f, %.3f)\n' % origin)
|
||||
|
||||
|
||||
def sample(tag):
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
tr = gz_truth()
|
||||
amcl = tf_xy('map', 'base_link')
|
||||
raw = tf_xy('odom', 'base_link') # 原始里程计(含比例误差)
|
||||
if tr is None or amcl is None or raw is None:
|
||||
print(' %-8s 读不到' % tag)
|
||||
return None, None
|
||||
d_amcl = math.hypot(amcl[0] - origin[0], amcl[1] - origin[1])
|
||||
d_raw = math.hypot(raw[0], raw[1])
|
||||
d_true = math.hypot(tr[0] - origin[0], tr[1] - origin[1])
|
||||
print(' %-8s 真值走了%5.2fm 原始里程计说%5.2fm AMCL 说%5.2fm '
|
||||
'里程计误差%+5.2fm AMCL 误差%+5.2fm'
|
||||
% (tag, d_true, d_raw, d_amcl, d_raw - d_true, d_amcl - d_true))
|
||||
return d_raw - d_true, d_amcl - d_true
|
||||
|
||||
|
||||
print('【静止】三列应该一致:')
|
||||
for i in range(2):
|
||||
sample('t=%ds' % i)
|
||||
time.sleep(1)
|
||||
|
||||
print('\n【直线前进】(0.25 m/s × 12 s)')
|
||||
rows = []
|
||||
tw = Twist()
|
||||
tw.linear.x = 0.25
|
||||
t0 = time.time()
|
||||
next_sample = 0.0
|
||||
while time.time() - t0 < 12.0:
|
||||
pub.publish(tw)
|
||||
rclpy.spin_once(node, timeout_sec=0.05)
|
||||
if time.time() - t0 >= next_sample:
|
||||
r = sample('%4.1fs' % (time.time() - t0))
|
||||
if r[0] is not None:
|
||||
rows.append(r)
|
||||
next_sample += 2.0
|
||||
time.sleep(0.05)
|
||||
pub.publish(Twist())
|
||||
time.sleep(1.0)
|
||||
sample('停')
|
||||
|
||||
print('\n【结论】')
|
||||
if rows:
|
||||
raw_err = rows[-1][0]
|
||||
amcl_err = rows[-1][1]
|
||||
print(' 里程计累计误差:%+.2f m' % raw_err)
|
||||
print(' AMCL 累计误差:%+.2f m' % amcl_err)
|
||||
if abs(raw_err) <= 0.15:
|
||||
print(' ~ 里程计误差太小,看不出差别'
|
||||
'(odom_scale 接近 1.0?或者车没怎么动?)')
|
||||
elif abs(amcl_err) < abs(raw_err) * 0.8:
|
||||
print(' ✅ AMCL 把漂移压住了 —— 这正是它的作用')
|
||||
else:
|
||||
print(' ❌ AMCL 没能纠正')
|
||||
|
||||
rclpy.try_shutdown()
|
||||
@@ -1,134 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 SolidWorks 导出的「云台」STL 转成仿真用网格。
|
||||
|
||||
与底盘的关键差异:
|
||||
* 底盘导出:Y 轴向上(地面在 Y 最小端)
|
||||
* 云台导出:Y 轴向下(安装板 yaw板/底部固定板 在 Y 最大端,相机/枪管在 Y 最小端)
|
||||
所以这里用 ros_z = -(sw_y - mount_y) 把模型翻正,并翻转一个水平轴保持右手系
|
||||
(det=+1,避免镜像)。
|
||||
|
||||
输出 meshes/gimbal.stl:原点在「安装面 + yaw 轴」上,模型向 +Z 生长。
|
||||
|
||||
用法:
|
||||
python3 tools/build_gimbal.py --src "/run/media/.../云台" --out src/sentry_sim/meshes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALE = 0.001
|
||||
|
||||
# 需要剔除的异常件:一个在别处(X≈388),一个是 30 米量级的坏面片
|
||||
EXCLUDE = ('弹仓底B', '弹仓前1')
|
||||
|
||||
# 云台自身的关键点(SW 坐标,毫米):yaw 轴 + 安装面高度
|
||||
YAW_AXIS_X = 30900.0
|
||||
YAW_AXIS_Z = 6500.0
|
||||
MOUNT_Y = 5769.4 # 安装面(yaw板 顶面)
|
||||
|
||||
# SW(mm, Y 向下) -> ROS(m, Z 向上),右手系(det=+1)
|
||||
# ros_x = -(sw_z - YAW_AXIS_Z)
|
||||
# ros_y = (sw_x - YAW_AXIS_X)
|
||||
# ros_z = -(sw_y - MOUNT_Y)
|
||||
ROT = np.array([[0.0, 0.0, -1.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, -1.0, 0.0]])
|
||||
ORIGIN_SW = np.array([YAW_AXIS_X, MOUNT_Y, YAW_AXIS_Z])
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 != size:
|
||||
return None
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
return rec['v'].reshape(-1, 3, 3).astype(np.float64)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim gimbal'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--src', required=True)
|
||||
ap.add_argument('--out', required=True)
|
||||
args = ap.parse_args()
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
|
||||
glob.glob(os.path.join(args.src, '*.stl')))
|
||||
if not files:
|
||||
sys.exit(f'没找到 STL:{args.src}')
|
||||
|
||||
used, skipped, parts = [], [], []
|
||||
for p in files:
|
||||
base = os.path.basename(p)
|
||||
if any(x in base for x in EXCLUDE):
|
||||
skipped.append(base)
|
||||
continue
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
skipped.append(base + '(无法解析)')
|
||||
continue
|
||||
used.append(t)
|
||||
parts.append(base)
|
||||
|
||||
tris = np.concatenate(used)
|
||||
# 变换到 ROS 系(米),原点在安装面 + yaw 轴
|
||||
tris = ((tris.reshape(-1, 3) - ORIGIN_SW) @ ROT.T) * SCALE
|
||||
tris = tris.reshape(-1, 3, 3)
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
out = os.path.join(args.out, 'gimbal.stl')
|
||||
write_stl(out, tris)
|
||||
|
||||
v = tris.reshape(-1, 3)
|
||||
mn, mx = v.min(axis=0), v.max(axis=0)
|
||||
meta = {
|
||||
'source_dir': os.path.abspath(args.src),
|
||||
'parts_used': len(parts),
|
||||
'parts_skipped': skipped,
|
||||
'triangles': int(len(tris)),
|
||||
'ros_bbox_min_m': [round(float(x), 4) for x in mn],
|
||||
'ros_bbox_max_m': [round(float(x), 4) for x in mx],
|
||||
'ros_bbox_size_m': [round(float(mx[i] - mn[i]), 4) for i in range(3)
|
||||
],
|
||||
'origin_sw_mm': [float(x) for x in ORIGIN_SW],
|
||||
'note': '云台导出 Y 轴朝下,已翻正(det=+1,无镜像);原点=安装面+yaw轴',
|
||||
}
|
||||
with open(os.path.join(args.out, 'gimbal_transform.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f'使用 {len(parts)} 个零件,跳过 {len(skipped)} 个:')
|
||||
for s in skipped:
|
||||
print(f' 跳过: {s}')
|
||||
print(f'\ngimbal.stl: {len(tris):,} 面')
|
||||
print(f'ROS 包围盒 min={np.round(mn, 3)} max={np.round(mx, 3)}')
|
||||
print(f'尺寸 (m) = {np.round(mx - mn, 3)}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,179 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 SolidWorks 导出的底盘 STL 装配体转成仿真可用的网格。
|
||||
|
||||
输入:SW 按零件导出的二进制 STL(装配体坐标系,单位 mm,Y 轴向上)
|
||||
输出:
|
||||
meshes/base.stl 底盘(除轮子本体外的全部零件),已转到 ROS 坐标系并居中
|
||||
meshes/wheel.stl 单个麦轮,已转到 ROS 坐标系并把原点放在轮子中心
|
||||
meshes/transform.json 坐标变换与四个轮子的关节位置(供 URDF 与人工核对)
|
||||
|
||||
坐标约定(REP-103:X 前、Y 左、Z 上):
|
||||
p_ros = R @ (p_sw - C) / 1000 R = [[0,0,1],[1,0,0],[0,1,0]]
|
||||
即 ROS_x = SW_z、ROS_y = SW_x、ROS_z = SW_y(把 SW 的 Z 前 / X 左 / Y 上 换成 ROS 约定)
|
||||
|
||||
用法:
|
||||
python3 tools/build_meshes.py --src "/run/media/.../底盘" --out src/sentry_sim/meshes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
# SW 装配体坐标 -> ROS(REP-103)
|
||||
ROT = np.array([[0.0, 0.0, 1.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0]])
|
||||
SCALE = 0.001 # mm -> m
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
"""读二进制/ASCII STL,返回 (N,3,3) 的三角面片数组(float32,SW 原始单位)。"""
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
if len(head) < 84:
|
||||
return None
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 == size: # 二进制
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
|
||||
('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
tris = rec['v'].reshape(-1, 3, 3).astype(np.float64)
|
||||
return tris
|
||||
# ASCII 兜底
|
||||
verts = []
|
||||
with open(path, 'r', errors='ignore') as f:
|
||||
for line in f:
|
||||
s = line.strip()
|
||||
if s.startswith('vertex'):
|
||||
verts.append([float(x) for x in s.split()[1:4]])
|
||||
if not verts or len(verts) % 3:
|
||||
return None
|
||||
return np.asarray(verts, dtype=np.float64).reshape(-1, 3, 3)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
"""写二进制 STL。"""
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim converted'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def to_ros(tris, center):
|
||||
"""SW 装配体坐标 -> ROS 坐标(米),并平移到 center 为原点。"""
|
||||
return ((tris - center) @ ROT.T) * SCALE
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--src', required=True, help='SW 导出的 STL 目录')
|
||||
ap.add_argument('--out', required=True, help='输出 meshes 目录')
|
||||
args = ap.parse_args()
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
|
||||
glob.glob(os.path.join(args.src, '*.stl')))
|
||||
if not files:
|
||||
sys.exit(f'没找到 STL:{args.src}')
|
||||
print(f'共 {len(files)} 个 STL')
|
||||
|
||||
# ---- 第 1 遍:整体包围盒,确定原点 C ----
|
||||
gmin = np.full(3, np.inf)
|
||||
gmax = np.full(3, -np.inf)
|
||||
for p in files:
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
print(f' 跳过(无法解析): {os.path.basename(p)}')
|
||||
continue
|
||||
v = t.reshape(-1, 3)
|
||||
gmin = np.minimum(gmin, v.min(axis=0))
|
||||
gmax = np.maximum(gmax, v.max(axis=0))
|
||||
|
||||
# 原点:X/Z 取包围盒中心,Y 取“地面”(最低点)
|
||||
center_sw = np.array([(gmin[0] + gmax[0]) / 2.0,
|
||||
gmin[1],
|
||||
(gmin[2] + gmax[2]) / 2.0])
|
||||
print(f'SW 包围盒 min={np.round(gmin, 1)} max={np.round(gmax, 1)}')
|
||||
print(f'原点 C (mm) = {np.round(center_sw, 2)}')
|
||||
|
||||
# ---- 第 2 遍:合并 ----
|
||||
# 只认「轮系-N 装配体1-1」,排除悬挂摇臂(文件名里也含“装配体1-1”)
|
||||
wheel_files = [p for p in files
|
||||
if '装配体1-1' in os.path.basename(p)
|
||||
and '轮系-' in os.path.basename(p)]
|
||||
base_files = [p for p in files if p not in wheel_files]
|
||||
print(f'轮子本体 {len(wheel_files)} 个;底盘 {len(base_files)} 个')
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
base_tris = []
|
||||
for p in base_files:
|
||||
t = read_stl(p)
|
||||
if t is not None:
|
||||
base_tris.append(to_ros(t, center_sw))
|
||||
base = np.concatenate(base_tris)
|
||||
write_stl(os.path.join(args.out, 'base.stl'), base)
|
||||
print(f'base.stl: {len(base):,} 面')
|
||||
|
||||
wheels = {}
|
||||
for p in wheel_files:
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
continue
|
||||
v = t.reshape(-1, 3)
|
||||
wheel_center_sw = (v.min(axis=0) + v.max(axis=0)) / 2.0
|
||||
wheels[os.path.basename(p)] = wheel_center_sw
|
||||
if 'wheel_raw' not in wheels:
|
||||
# 以第一个轮子为模板,把原点放在轮子中心
|
||||
ros = to_ros(t, center_sw) # 先到 ROS 系、底盘中心为原点
|
||||
wc = (to_ros(t, wheel_center_sw)).reshape(-1, 3).mean(axis=0) * 0 # 占位
|
||||
# 轮子中心在 ROS 系下的位置
|
||||
wc_ros = ((wheel_center_sw - center_sw) @ ROT.T) * SCALE
|
||||
ros_centered = ros - wc_ros
|
||||
write_stl(os.path.join(args.out, 'wheel.stl'), ros_centered)
|
||||
print(f'wheel.stl: {len(ros_centered):,} 面(模板:{os.path.basename(p)})')
|
||||
|
||||
# ---- 轮子关节位置(ROS,米)----
|
||||
joints = {}
|
||||
for name, c_sw in wheels.items():
|
||||
# 轮系-N 装配体1-1.STL -> N
|
||||
idx = name.split('轮系-')[-1].split()[0]
|
||||
c_ros = ((c_sw - center_sw) @ ROT.T) * SCALE
|
||||
joints[f'wheel_{idx}'] = [round(float(x), 6) for x in c_ros]
|
||||
|
||||
meta = {
|
||||
'source_dir': os.path.abspath(args.src),
|
||||
'sw_bbox_min_mm': [round(float(x), 2) for x in gmin],
|
||||
'sw_bbox_max_mm': [round(float(x), 2) for x in gmax],
|
||||
'origin_sw_mm': [round(float(x), 2) for x in center_sw],
|
||||
'ros_bbox_size_m': [round(float(x) * SCALE, 4) for x in (gmax - gmin)],
|
||||
'wheels_ros_m': joints,
|
||||
'wheel_radius_m': 0.0762,
|
||||
'note': 'ROS_x=SW_z, ROS_y=SW_x, ROS_z=SW_y;单位 mm->m',
|
||||
}
|
||||
with open(os.path.join(args.out, 'transform.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
print('\n轮子中心(ROS,米):')
|
||||
for k, v in joints.items():
|
||||
print(f' {k}: {v}')
|
||||
print(f'\n车体尺寸(ROS,米): {meta["ros_bbox_size_m"]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+63
-3
@@ -11,6 +11,7 @@
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -30,12 +31,19 @@ from tf2_ros import Buffer, TransformListener
|
||||
|
||||
|
||||
# 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力)
|
||||
#
|
||||
# ⚠️ amcl 必须在这个列表里:它不发 /map,但 **map_server 的激活与否看不出定位好坏**。
|
||||
# 曾经漏掉它,结果 map_server 卡在 inactive、amcl 压根没配起来,而这个脚本
|
||||
# 只报了 7 个节点的状态 —— 一眼看不出问题其实出在定位那一组。
|
||||
EXPECTED_ACTIVE = [
|
||||
'map_server',
|
||||
'amcl',
|
||||
'controller_server',
|
||||
'planner_server',
|
||||
'smoother_server',
|
||||
'bt_navigator',
|
||||
'behavior_server',
|
||||
'waypoint_follower',
|
||||
'velocity_smoother',
|
||||
'collision_monitor',
|
||||
]
|
||||
@@ -60,7 +68,7 @@ def parse_gz_pose(out):
|
||||
Model: [52]
|
||||
- Name: sentry
|
||||
- Pose [ XYZ (m) ] [ RPY (rad) ]:
|
||||
[0.900000 4.000000 0.000000]
|
||||
[-5.000000 3.000000 0.000000]
|
||||
[0.000000 -0.000000 0.000000]
|
||||
|
||||
注意标签本身就带两个方括号(`[ XYZ (m) ]` `[ RPY (rad) ]`),
|
||||
@@ -89,6 +97,26 @@ 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。
|
||||
|
||||
@@ -104,9 +132,12 @@ def gz_model_pose(model_name):
|
||||
env = dict(os.environ)
|
||||
env['GZ_PARTITION'] = partition
|
||||
# 必须用系统版 gz 并清掉 LD_LIBRARY_PATH,否则会加载 ROS vendor 的库,
|
||||
# 和服务端(系统版 10.6)不是同一套
|
||||
# 和服务端不是同一套。
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
cmd = ['/usr/bin/gz', 'model', '-m', model_name, '-p']
|
||||
gz_bin = _gz_bin()
|
||||
if gz_bin is None:
|
||||
return None
|
||||
cmd = [str(gz_bin), 'model', '-m', model_name, '-p']
|
||||
try:
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True,
|
||||
timeout=10).stdout
|
||||
@@ -146,6 +177,35 @@ def main():
|
||||
print(' %-20s ⚠️ %s' % (name, st.label))
|
||||
problems.append(f'{name} 是 {st.label},不是 ACTIVE')
|
||||
|
||||
# ---------- 1.5 节点总览:定位"卡在谁身上" ----------
|
||||
# 光看生命周期状态不够 —— 如果某个节点**压根没起来**,
|
||||
# 上面只会说"服务不存在",看不出是谁没被编排。这里把家底列出来。
|
||||
print('\n=== 1.5 节点总览(生命周期管理器在不在)===')
|
||||
try:
|
||||
names = sorted(set(node.get_node_names()))
|
||||
except Exception: # noqa: BLE001
|
||||
names = []
|
||||
if names:
|
||||
lms = [n for n in names if 'lifecycle_manager' in n]
|
||||
print(f' 节点总数: {len(names)}')
|
||||
if lms:
|
||||
print(f' 生命周期管理器: {", ".join(lms)}')
|
||||
else:
|
||||
print(' 生命周期管理器: ❌ 一个都没有(Nav2 不会自己配置)')
|
||||
problems.append('没有 lifecycle_manager 在跑')
|
||||
missing = [n for n in EXPECTED_ACTIVE if n not in names]
|
||||
if missing:
|
||||
print(f' ⚠️ 期望存在但没起: {", ".join(missing)}')
|
||||
for n in missing:
|
||||
problems.append(f'{n} 没在跑')
|
||||
extra = [n for n in names
|
||||
if any(k in n for k in ('amcl', 'server', 'navigator', 'manager'))
|
||||
and n not in EXPECTED_ACTIVE and 'lifecycle_manager' not in n]
|
||||
if extra:
|
||||
print(f' 其他相关节点: {", ".join(extra)}')
|
||||
else:
|
||||
print(' ⚠️ 一个节点都没发现 —— DDS 发现可能有问题')
|
||||
|
||||
# ---------- 2. 话题有没有数据 ----------
|
||||
print('\n=== 2. 话题数据(各收 1 条,最多 8 秒)===')
|
||||
seen = {}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""对比自滤前后的点云:有没有把车身自身回波滤掉。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
from rclpy.qos import QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
QOS = QoSProfile(depth=5, reliability=QoSReliabilityPolicy.BEST_EFFORT)
|
||||
rclpy.init()
|
||||
node = Node('cloud_compare')
|
||||
got = {}
|
||||
node.create_subscription(PointCloud2, '/scan/points',
|
||||
lambda m: got.setdefault('raw', m), QOS)
|
||||
node.create_subscription(PointCloud2, '/scan/points_filtered',
|
||||
lambda m: got.setdefault('filtered', m), QOS)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 2:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
|
||||
def stats(msg):
|
||||
if msg is None:
|
||||
return None
|
||||
pts = [p for p in pc2.read_points(msg, field_names=('x', 'y', 'z'), skip_nans=True)]
|
||||
fin = [p for p in pts if all(abs(v) != float('inf') for v in p)]
|
||||
if not fin:
|
||||
return (0, 0.0, 0.0)
|
||||
d = [((p[0] ** 2 + p[1] ** 2) ** 0.5) for p in fin]
|
||||
return (len(fin), min(d), max(d))
|
||||
|
||||
|
||||
raw = stats(got.get('raw'))
|
||||
flt = stats(got.get('filtered'))
|
||||
print(f'原始 /scan/points : {raw[0]} 点, 距离 {raw[1]:.2f} ~ {raw[2]:.2f} m' if raw else '没收到原始点云')
|
||||
print(f'自滤 /scan/points_filtered : {flt[0]} 点, 距离 {flt[1]:.2f} ~ {flt[2]:.2f} m' if flt else '没收到自滤点云')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查 MID-360 3D 点云质量:点数、有效点、距离分布、可见的地面/围挡。"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
|
||||
try:
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
except ImportError:
|
||||
pc2 = None
|
||||
|
||||
rclpy.init()
|
||||
node = Node('cloud_probe')
|
||||
got = {}
|
||||
node.create_subscription(PointCloud2, '/scan/points', lambda m: got.setdefault('c', m), 10)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and 'c' not in got:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
m = got.get('c')
|
||||
if m is None:
|
||||
print('没收到 /scan/points')
|
||||
else:
|
||||
print(f'frame={m.header.frame_id} 尺寸={m.width}x{m.height} point_step={m.point_step}')
|
||||
if pc2 is None:
|
||||
print('(没有 sensor_msgs_py,跳过解析)')
|
||||
else:
|
||||
pts = [p for p in pc2.read_points(m, field_names=('x', 'y', 'z'), skip_nans=True)]
|
||||
fin = [p for p in pts if all(math.isfinite(v) for v in p)]
|
||||
print(f'点总数={len(pts)} 有限点={len(fin)}')
|
||||
if fin:
|
||||
rng = [math.hypot(p[0], p[1]) for p in fin]
|
||||
zs = [p[2] for p in fin]
|
||||
print(f'水平距离: {min(rng):.2f} ~ {max(rng):.2f} m')
|
||||
print(f'高度范围: {min(zs):+.2f} ~ {max(zs):+.2f} m(传感器在 0.405,地面应在 -0.405 附近)')
|
||||
import collections
|
||||
h = collections.Counter(int(r / 2) * 2 for r in rng)
|
||||
print('距离直方图(每 2m):', dict(sorted(h.items())))
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""统计导航链路上各级速度话题的消息数。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist, TwistStamped
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
qos = QoSProfile(depth=10, reliability=QoSReliabilityPolicy.BEST_EFFORT)
|
||||
rclpy.init()
|
||||
node = Node('cmd_probe_all')
|
||||
counts = {}
|
||||
|
||||
|
||||
def make_cb(name):
|
||||
def cb(_msg):
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
return cb
|
||||
|
||||
|
||||
for t in ('/cmd_vel_nav', '/cmd_vel_smoothed', '/cmd_vel', '/model/sentry/cmd_vel'):
|
||||
node.create_subscription(Twist, t, make_cb(t), qos)
|
||||
node.create_subscription(TwistStamped, '/cmd_vel_nav', make_cb('/cmd_vel_nav[stamped]'), qos)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
for t in ('/cmd_vel_nav', '/cmd_vel_nav[stamped]', '/cmd_vel_smoothed', '/cmd_vel',
|
||||
'/model/sentry/cmd_vel'):
|
||||
print(f' {t:26} {counts.get(t, 0)}')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,69 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""演示脚本:驱动哨兵前进+转向,并打印雷达/里程计/AMCL 的真实数据。"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import LaserScan
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
rclpy.init()
|
||||
node = Node('demo_driver')
|
||||
pub = node.create_publisher(Twist, '/cmd_vel', 10)
|
||||
data = {'odom': None, 'scan': None}
|
||||
node.create_subscription(Odometry, '/odom', lambda m: data.__setitem__('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: data.__setitem__('scan', m), 10)
|
||||
tf = Buffer()
|
||||
TransformListener(tf, node)
|
||||
|
||||
|
||||
def spin(sec):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < sec:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
|
||||
|
||||
def drive(lin, ang, sec, label):
|
||||
msg = Twist()
|
||||
msg.linear.x = lin
|
||||
msg.angular.z = ang
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < sec:
|
||||
pub.publish(msg)
|
||||
rclpy.spin_once(node, timeout_sec=0.05)
|
||||
pub.publish(Twist())
|
||||
p = data['odom'].pose.pose.position if data['odom'] else None
|
||||
yaw = 0.0
|
||||
if data['odom']:
|
||||
q = data['odom'].pose.pose.orientation
|
||||
yaw = math.degrees(2 * math.atan2(q.z, q.w))
|
||||
print(f' {label}: odom=({p.x:+.3f}, {p.y:+.3f}) 航向={yaw:+.1f}°' if p else f' {label}: 无 odom')
|
||||
|
||||
|
||||
spin(3)
|
||||
if data['scan']:
|
||||
finite = [r for r in data['scan'].ranges if r == r and r != float('inf')]
|
||||
print(f'[雷达] frame={data["scan"].header.frame_id} 线数={len(data["scan"].ranges)} '
|
||||
f'有效点={len(finite)} 最近={min(finite):.2f}m 最远={max(finite):.2f}m')
|
||||
else:
|
||||
print('[雷达] 无数据')
|
||||
|
||||
print('[驱动]')
|
||||
drive(0.5, 0.0, 3.0, '前进 0.5 m/s × 3s')
|
||||
drive(0.0, 0.8, 1.5, '原地转 0.8 rad/s × 1.5s')
|
||||
drive(0.3, 0.0, 2.0, '再前进 0.3 m/s × 2s')
|
||||
|
||||
for i in range(20):
|
||||
spin(0.2)
|
||||
try:
|
||||
tr = tf.lookup_transform('map', 'base_link', rclpy.time.Time())
|
||||
p = tr.transform.translation
|
||||
print(f'[AMCL] TF map->base_link: x={p.x:.3f} y={p.y:.3f}')
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[AMCL] 查不到 TF: {exc}')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,133 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""驱动哨兵走一个正方形,并输出轨迹数据 + SVG 图。
|
||||
|
||||
用法:python3 tools/drive_demo.py [边长m] [输出svg路径]
|
||||
"""
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
|
||||
SIDE = float(sys.argv[1]) if len(sys.argv) > 1 else 1.0
|
||||
OUT = sys.argv[2] if len(sys.argv) > 2 else 'generated/drive_trajectory.svg'
|
||||
LINEAR = 0.5 # m/s
|
||||
ANGULAR = 0.8 # rad/s
|
||||
|
||||
rclpy.init()
|
||||
node = Node('drive_demo')
|
||||
pub = node.create_publisher(Twist, '/cmd_vel', 10)
|
||||
odom = {}
|
||||
node.create_subscription(Odometry, '/odom', lambda m: odom.__setitem__('v', m), 10)
|
||||
|
||||
track = []
|
||||
|
||||
|
||||
def record():
|
||||
m = odom.get('v')
|
||||
if not m:
|
||||
return
|
||||
p = m.pose.pose.position
|
||||
q = m.pose.pose.orientation
|
||||
yaw = math.degrees(2 * math.atan2(q.z, q.w))
|
||||
track.append((p.x, p.y, yaw))
|
||||
|
||||
|
||||
def spin(sec, cmd=None, hz=20):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < sec:
|
||||
if cmd is not None:
|
||||
pub.publish(cmd)
|
||||
rclpy.spin_once(node, timeout_sec=1.0 / hz)
|
||||
record()
|
||||
|
||||
|
||||
# 等 odom
|
||||
t0 = time.time()
|
||||
while 'v' not in odom and time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
print(f'起始位姿: x=0.000 y=0.000 yaw=0.0')
|
||||
|
||||
fw = Twist()
|
||||
fw.linear.x = LINEAR
|
||||
turn = Twist()
|
||||
turn.angular.z = ANGULAR
|
||||
|
||||
for i in range(4):
|
||||
spin(SIDE / LINEAR, fw)
|
||||
pub.publish(Twist())
|
||||
spin(0.3)
|
||||
before = track[-1][2] if track else 0
|
||||
spin((math.pi / 2) / ANGULAR, turn)
|
||||
pub.publish(Twist())
|
||||
spin(0.3)
|
||||
print(f' 第 {i+1} 边完成: x={track[-1][0]:+.3f} y={track[-1][1]:+.3f} '
|
||||
f'航向 {before:+.1f}° -> {track[-1][2]:+.1f}°')
|
||||
|
||||
x, y, yaw = track[-1]
|
||||
print(f'\n回到起点偏差: dx={x:+.3f} m dy={y:+.3f} m 最终航向={yaw:+.1f}°(理想 360°)')
|
||||
|
||||
# ---- 写 SVG ----
|
||||
pts = [(t[0], t[1]) for t in track]
|
||||
xs = [p[0] for p in pts]
|
||||
ys = [p[1] for p in pts]
|
||||
pad = 0.3
|
||||
x0, x1 = min(xs + [0]) - pad, max(xs + [0]) + pad
|
||||
y0, y1 = min(ys + [0]) - pad, max(ys + [0]) + pad
|
||||
W = 700
|
||||
scale = W / max(x1 - x0, y1 - y0)
|
||||
H = int((y1 - y0) * scale) + 60
|
||||
|
||||
|
||||
def sx(v):
|
||||
return 40 + (v - x0) * scale
|
||||
|
||||
|
||||
def sy(v):
|
||||
return H - 40 - (v - y0) * scale
|
||||
|
||||
|
||||
path = ' '.join(f'{sx(px):.1f},{sy(py):.1f}' for px, py in pts[::max(1, len(pts)//400)])
|
||||
lines = [
|
||||
f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">',
|
||||
f'<rect width="{W}" height="{H}" fill="#11141a"/>',
|
||||
]
|
||||
# 网格
|
||||
step = 0.5
|
||||
g = math.floor(x0 / step) * step
|
||||
while g <= x1:
|
||||
lines.append(f'<line x1="{sx(g):.1f}" y1="20" x2="{sx(g):.1f}" y2="{H-20}" stroke="#222833" stroke-width="1"/>')
|
||||
lines.append(f'<text x="{sx(g):.1f}" y="{H-6}" fill="#556" font-size="10" text-anchor="middle">{g:.1f}</text>')
|
||||
g += step
|
||||
g = math.floor(y0 / step) * step
|
||||
while g <= y1:
|
||||
lines.append(f'<line x1="20" y1="{sy(g):.1f}" x2="{W-20}" y2="{sy(g):.1f}" stroke="#222833" stroke-width="1"/>')
|
||||
lines.append(f'<text x="4" y="{sy(g)+3:.1f}" fill="#556" font-size="10">{g:.1f}</text>')
|
||||
g += step
|
||||
# 轨迹
|
||||
lines.append(f'<polyline points="{path}" fill="none" stroke="#4da3ff" stroke-width="2.5"/>')
|
||||
# 起点/终点
|
||||
lines.append(f'<circle cx="{sx(0):.1f}" cy="{sy(0):.1f}" r="5" fill="#3ddc84"/>')
|
||||
lines.append(f'<text x="{sx(0)+8:.1f}" y="{sy(0)-6:.1f}" fill="#3ddc84" font-size="12">起点</text>')
|
||||
lines.append(f'<circle cx="{sx(x):.1f}" cy="{sy(y):.1f}" r="5" fill="#ff5c5c"/>')
|
||||
lines.append(f'<text x="{sx(x)+8:.1f}" y="{sy(y)+14:.1f}" fill="#ff5c5c" font-size="12">终点</text>')
|
||||
# 终点朝向箭头
|
||||
rad = math.radians(yaw)
|
||||
ax, ay = sx(x), sy(y)
|
||||
ex, ey = ax + 26 * math.cos(rad), ay - 26 * math.sin(rad)
|
||||
lines.append(f'<line x1="{ax:.1f}" y1="{ay:.1f}" x2="{ex:.1f}" y2="{ey:.1f}" stroke="#ffd166" stroke-width="2"/>')
|
||||
lines.append(f'<text x="20" y="24" fill="#8892a6" font-size="13">'
|
||||
f'哨兵方形行驶轨迹(边长 {SIDE} m,速度 {LINEAR} m/s,转向 {ANGULAR} rad/s)</text>')
|
||||
lines.append('</svg>')
|
||||
|
||||
import os
|
||||
os.makedirs(os.path.dirname(OUT) or '.', exist_ok=True)
|
||||
open(OUT, 'w').write('\n'.join(lines))
|
||||
print(f'\n轨迹图已保存: {OUT}(用浏览器或图片查看器打开)')
|
||||
print(f'采样点 {len(track)} 个')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从栅格图里找出「车能安全通过」的目标点,并检查从起点连不连得过去。
|
||||
|
||||
用法::
|
||||
|
||||
python3 tools/free_goals.py # 起点默认 (-5.0, 3.0) 当前出生点
|
||||
python3 tools/free_goals.py --from 0.0 0.0 # 换个起点(场地中心)
|
||||
python3 tools/free_goals.py --min-clear 0.7 # 要求更大净空
|
||||
python3 tools/free_goals.py --map path/to/x.yaml
|
||||
|
||||
不依赖 ROS,直接读官方迁移包里的 yaml + pgm,可以随时跑。
|
||||
|
||||
为什么需要这个:RMUL 2027 的官方栅格图是 CAD 的「保守障碍投影」,
|
||||
场内有两块 0.4 m 高的障碍把场地切成几条走廊,很多看起来很空的点
|
||||
(比如 (3.0, 4.0))其实压在障碍里,发过去必然规划失败。
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
# 车体 0.65 x 0.54 矩形,半对角 0.422 m。
|
||||
HALF_DIAGONAL = 0.422
|
||||
# 默认要求的净空。
|
||||
DEFAULT_MIN_CLEAR = 0.50
|
||||
# 占据判定阈值,和 yaml 的 occupied_thresh 对齐。
|
||||
OCCUPIED_THRESHOLD = 65
|
||||
|
||||
DEFAULT_YAML = (
|
||||
'field/RMUL2027_map_transfer_20261016_STEP_R1'
|
||||
'/src/guodong_sentry_sim/maps/rmul_2027/rmul_2027.yaml')
|
||||
|
||||
_NEIGHBORS = ((1, 0, 1.0), (-1, 0, 1.0), (0, 1, 1.0), (0, -1, 1.0),
|
||||
(1, 1, math.sqrt(2)), (1, -1, math.sqrt(2)),
|
||||
(-1, 1, math.sqrt(2)), (-1, -1, math.sqrt(2)))
|
||||
|
||||
|
||||
def read_pgm(path):
|
||||
"""读二进制 PGM(P5),返回 (像素数组, 宽, 高, 最大值)。"""
|
||||
raw = path.read_bytes()
|
||||
i, fields = 0, []
|
||||
while len(fields) < 4:
|
||||
while raw[i:i + 1].isspace():
|
||||
i += 1
|
||||
if raw[i:i + 1] == b'#':
|
||||
while raw[i:i + 1] not in (b'\n', b''):
|
||||
i += 1
|
||||
continue
|
||||
start = i
|
||||
while not raw[i:i + 1].isspace():
|
||||
i += 1
|
||||
fields.append(raw[start:i])
|
||||
i += 1
|
||||
width, height, maxval = int(fields[1]), int(fields[2]), int(fields[3])
|
||||
img = np.frombuffer(raw[i:i + width * height], dtype=np.uint8)
|
||||
return img.reshape(height, width), width, height, maxval
|
||||
|
||||
|
||||
def load_map(yaml_path):
|
||||
"""读 yaml + pgm,返回占据布尔表和地图元信息(行 0 = y 最小)。"""
|
||||
yaml_path = pathlib.Path(yaml_path)
|
||||
text = yaml_path.read_text()
|
||||
res = float(re.search(r'resolution:\s*([\d.]+)', text).group(1))
|
||||
ox, oy = [float(v) for v in
|
||||
re.search(r'origin:\s*\[([^\]]+)\]', text).group(1).split(',')[:2]]
|
||||
image = re.search(r'image:\s*(\S+)', text).group(1).strip('"\'')
|
||||
occ_thresh = float(re.search(r'occupied_thresh:\s*([\d.]+)', text).group(1))
|
||||
|
||||
img, width, height, maxval = read_pgm(yaml_path.parent / image)
|
||||
# mode: trinary + negate 0 -> 灰度越黑越占据;pgm 行 0 在顶部,翻转成 y 向上。
|
||||
occupied = (img[::-1, :] <= (1.0 - occ_thresh) * maxval)
|
||||
return {'arr': occupied, 'res': res, 'ox': ox, 'oy': oy,
|
||||
'w': width, 'h': height}
|
||||
|
||||
|
||||
def clearance_map(mp):
|
||||
"""8 邻域 Dijkstra 求每个栅格到最近障碍的距离(米)。"""
|
||||
import heapq
|
||||
|
||||
arr, res = mp['arr'], mp['res']
|
||||
h, w = arr.shape
|
||||
dist = np.full((h, w), np.inf)
|
||||
pq = []
|
||||
for r, c in zip(*np.nonzero(arr)):
|
||||
dist[r, c] = 0.0
|
||||
pq.append((0.0, int(r), int(c)))
|
||||
heapq.heapify(pq)
|
||||
while pq:
|
||||
d, r, c = heapq.heappop(pq)
|
||||
if d > dist[r, c]:
|
||||
continue
|
||||
for dr, dc, weight in _NEIGHBORS:
|
||||
nr, nc = r + dr, c + dc
|
||||
if 0 <= nr < h and 0 <= nc < w:
|
||||
nd = d + weight
|
||||
if nd < dist[nr, nc]:
|
||||
dist[nr, nc] = nd
|
||||
heapq.heappush(pq, (nd, nr, nc))
|
||||
return dist * res
|
||||
|
||||
|
||||
def reachable(clear, mp, start, min_clear):
|
||||
"""从 start 出发,在「净空 >= min_clear」的格子里做 4 邻域连通填充。"""
|
||||
arr, res, ox, oy = mp['arr'], mp['res'], mp['ox'], mp['oy']
|
||||
h, w = arr.shape
|
||||
r0 = int(round((start[1] - oy) / res))
|
||||
c0 = int(round((start[0] - ox) / res))
|
||||
# 起点自己不够干净时,就近找一个达标的种子格。
|
||||
if not (0 <= r0 < h and 0 <= c0 < w):
|
||||
raise SystemExit(f'起点 {start} 在地图外')
|
||||
if clear[r0, c0] < min_clear:
|
||||
best = None
|
||||
for dr in range(-40, 41):
|
||||
for dc in range(-40, 41):
|
||||
r, c = r0 + dr, c0 + dc
|
||||
if 0 <= r < h and 0 <= c < w and clear[r, c] >= min_clear:
|
||||
dd = dr * dr + dc * dc
|
||||
if best is None or dd < best[0]:
|
||||
best = (dd, r, c)
|
||||
if best is None:
|
||||
raise SystemExit(f'起点 {start} 周围 1 m 内没有安全格子')
|
||||
r0, c0 = best[1], best[2]
|
||||
|
||||
ok = clear >= min_clear
|
||||
seen = np.zeros_like(ok)
|
||||
seen[r0, c0] = True
|
||||
queue = collections.deque([(r0, c0)])
|
||||
while queue:
|
||||
r, c = queue.popleft()
|
||||
for dr, dc, _ in _NEIGHBORS:
|
||||
nr, nc = r + dr, c + dc
|
||||
if 0 <= nr < h and 0 <= nc < w and ok[nr, nc] and not seen[nr, nc]:
|
||||
seen[nr, nc] = True
|
||||
queue.append((nr, nc))
|
||||
return seen, (r0, c0)
|
||||
|
||||
|
||||
def main():
|
||||
"""打印可达的安全目标点,并画一张安全通行走廊图。"""
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument('--map', default=DEFAULT_YAML, help='栅格图 yaml 路径')
|
||||
ap.add_argument('--from', dest='start', nargs=2, type=float,
|
||||
default=[-5.0, 3.0], metavar=('X', 'Y'), help='起点 map 坐标')
|
||||
ap.add_argument('--min-clear', type=float, default=DEFAULT_MIN_CLEAR,
|
||||
help=f'要求的最小净空(米),默认 {DEFAULT_MIN_CLEAR}')
|
||||
ap.add_argument('--grid', type=float, default=0.5,
|
||||
help='候选点采样间隔(米),默认 0.5')
|
||||
ap.add_argument('--no-map', action='store_true', help='不画 ASCII 图')
|
||||
args = ap.parse_args()
|
||||
|
||||
mp = load_map(args.map)
|
||||
clear = clearance_map(mp)
|
||||
res, ox, oy = mp['res'], mp['ox'], mp['oy']
|
||||
|
||||
print(f'地图 {mp["w"]}x{mp["h"]} @ {res} m/px origin=({ox}, {oy})')
|
||||
print(f'车体半对角 {HALF_DIAGONAL:.3f} m,要求净空 >= {args.min_clear:.2f} m')
|
||||
print(f'起点 ({args.start[0]:.2f}, {args.start[1]:.2f})')
|
||||
|
||||
seen, seed = reachable(clear, mp, args.start, args.min_clear)
|
||||
sx, sy = ox + seed[1] * res, oy + seed[0] * res
|
||||
area = seen.sum() * res * res
|
||||
print(f'从起点连通的安全区面积: {area:.1f} m²\n')
|
||||
|
||||
step = max(1, int(round(args.grid / res)))
|
||||
cands = []
|
||||
h, w = clear.shape
|
||||
for r in range(0, h, step):
|
||||
for c in range(0, w, step):
|
||||
if seen[r, c]:
|
||||
x, y = ox + (c + 0.5) * res, oy + (r + 0.5) * res
|
||||
if 0.0 <= x <= 12.0 and 0.0 <= y <= 8.0:
|
||||
cands.append((x, y, clear[r, c]))
|
||||
|
||||
# 贪心去重:任意两点至少隔开 1.2 m,避免刷一屏相邻点。
|
||||
picked = []
|
||||
for x, y, cl in sorted(cands, key=lambda t: -t[2]):
|
||||
if all(math.hypot(x - px, y - py) > 1.2 for px, py, _ in picked):
|
||||
picked.append((x, y, cl))
|
||||
picked.sort(key=lambda t: math.hypot(t[0] - sx, t[1] - sy))
|
||||
|
||||
print(f'{"目标点 (map)":>20} {"净空":>6} {"离起点":>7} field 坐标')
|
||||
print(' ' + '-' * 62)
|
||||
for x, y, cl in picked:
|
||||
d = math.hypot(x - sx, y - sy)
|
||||
print(f' ({x:5.2f}, {y:4.2f}) {cl:5.2f} m {d:6.2f} m '
|
||||
f'({x - 6.0:5.2f}, {y - 4.0:5.2f})')
|
||||
|
||||
print('\n直接复制就能跑:')
|
||||
for x, y, cl in picked[:6]:
|
||||
print(f' build/linux/x86_64/release/nav_client {x:.2f} {y:.2f}')
|
||||
|
||||
if args.no_map:
|
||||
return 0
|
||||
|
||||
print('\n=== 安全通行走廊(+ 能过 / . 空但太窄 / # 障碍 / o 起点)===')
|
||||
stride = 6
|
||||
print(' ' + ''.join(str(int(ox + c * res) % 10)
|
||||
for c in range(0, w, stride)))
|
||||
for r in range(h - 1, -1, -stride):
|
||||
line = ''
|
||||
for c in range(0, w, stride):
|
||||
if (r, c) == seed:
|
||||
line += 'o'
|
||||
elif seen[r, c]:
|
||||
line += '+'
|
||||
elif mp['arr'][r, c]:
|
||||
line += '#'
|
||||
else:
|
||||
line += '.'
|
||||
print(f' {oy + r * res:5.2f} {line}')
|
||||
print(f'\n 每格 {stride * res:.2f} m')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
+10
-2
@@ -13,8 +13,16 @@ WS="$PWD"
|
||||
# 所以 URDF 里写的是 `$(env SENTRY_SIM_SHARE)`,这里必须先把变量设好。
|
||||
export SENTRY_SIM_SHARE="${SENTRY_SIM_SHARE:-$WS/src/sentry_sim}"
|
||||
|
||||
# 可移植探测:ROS 发行版和 gz 可执行文件都不写死。
|
||||
# shellcheck source=../src/sentry_sim/scripts/env_common.sh
|
||||
. "$WS/src/sentry_sim/scripts/env_common.sh"
|
||||
|
||||
# xacro 只需要 ROS 的基础环境,不需要工作空间的 install/setup.bash(也没有了)。
|
||||
source /opt/ros/lyrical/setup.bash 2>/dev/null || true
|
||||
# 探测不到就继续 —— 后面 xacro 找不到时它自己会报错,报错信息更准确。
|
||||
env_source_ros 2>/dev/null || true
|
||||
|
||||
# `gz sdf -p` 只是 URDF → SDF 转换,用系统 gz(避免 vendor 库路径干扰)。
|
||||
GZ=$(env_gz_bin)
|
||||
|
||||
mkdir -p generated
|
||||
TMP="$(mktemp -d)"
|
||||
@@ -22,7 +30,7 @@ trap 'rm -rf "$TMP"' EXIT
|
||||
|
||||
xacro src/sentry_sim/urdf/sentry.urdf.xacro > "$TMP/sentry.urdf"
|
||||
cp "$TMP/sentry.urdf" generated/sentry.urdf
|
||||
gz sdf -p "$TMP/sentry.urdf" > src/sentry_sim/models/sentry/model.sdf
|
||||
env -u LD_LIBRARY_PATH "$GZ" sdf -p "$TMP/sentry.urdf" > src/sentry_sim/models/sentry/model.sdf
|
||||
|
||||
echo "已生成:"
|
||||
echo " src/sentry_sim/models/sentry/model.sdf ($(wc -l < src/sentry_sim/models/sentry/model.sdf) 行)"
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把「场地中心 = 零点」画出来,方便肉眼核对位置对不对。
|
||||
|
||||
发布可视化 Marker(不改仿真里的任何东西,纯叠加显示):
|
||||
|
||||
① 红色圆柱 —— 用 `map` 帧表达场地中心 (0, 0)
|
||||
② 绿色球 —— 用 `field` 帧表达同一个点 (0.0, 0.0)
|
||||
两者如果**完全重合**,说明 map→field 这条变换是对的
|
||||
③ 黄色线框 —— 场地内圈 12×8 的边界(`map` 帧 x[-6,6] y[-4,4])
|
||||
④ 蓝色细线 —— 场地中线(crosshair),交点在场地中心
|
||||
⑤ 文字标签 —— "field(0,0) = map(0,0)"
|
||||
|
||||
用法:
|
||||
|
||||
# 仿真跑着的时候,另开一个终端
|
||||
python3 tools/mark_field_center.py
|
||||
|
||||
# 然后在 RViz 里加一个 Marker 显示项,topic 选 /field_center_marker
|
||||
# (或者直接开 scripts/sentry_up.sh 起的那个 RViz,手动 Add → By topic)
|
||||
|
||||
如果 RViz 里 marker 跑到了场地外面,或者红绿不重合,说明坐标系有问题。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Point
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import DurabilityPolicy, HistoryPolicy, QoSProfile
|
||||
from visualization_msgs.msg import Marker
|
||||
|
||||
# 场地几何(内圈 12×8)。世界/地图已整体平移:场地中心 = (0,0),
|
||||
# 内圈范围 x ∈ [-6,6],y ∈ [-4,4]。
|
||||
FIELD_W = 12.0
|
||||
FIELD_H = 8.0
|
||||
CENTER_X = 0.0 # 场地中心 x
|
||||
CENTER_Y = 0.0 # 场地中心 y
|
||||
X0 = -FIELD_W / 2.0 # -6.0
|
||||
Y0 = -FIELD_H / 2.0 # -4.0
|
||||
|
||||
|
||||
class FieldCenterMarker(Node):
|
||||
def __init__(self):
|
||||
super().__init__('field_center_marker')
|
||||
self.declare_parameter('frame', 'map')
|
||||
self.declare_parameter('z', 0.03) # 略高于地面,免得被地面挡住
|
||||
self.frame = self.get_parameter('frame').value
|
||||
self.z = self.get_parameter('z').value
|
||||
|
||||
# latched:RViz 晚加显示项也能立刻收到
|
||||
qos = QoSProfile(depth=1,
|
||||
history=HistoryPolicy.KEEP_LAST,
|
||||
durability=DurabilityPolicy.TRANSIENT_LOCAL)
|
||||
self.pub = self.create_publisher(Marker, '/field_center_marker', qos)
|
||||
self.timer = self.create_timer(1.0, self.publish_all)
|
||||
|
||||
self.get_logger().info(
|
||||
'field_center_marker: 发布 /field_center_marker(frame=%s)\n'
|
||||
' RViz 里 Add → By topic → /field_center_marker → Marker' % self.frame)
|
||||
|
||||
# ---------------- 工具 ----------------
|
||||
def _base(self, mid, mtype):
|
||||
m = Marker()
|
||||
m.header.frame_id = self.frame
|
||||
m.header.stamp = self.get_clock().now().to_msg()
|
||||
m.ns = 'field_center'
|
||||
m.id = mid
|
||||
m.type = mtype
|
||||
m.action = Marker.ADD
|
||||
m.pose.orientation.w = 1.0
|
||||
m.lifetime = rclpy.duration.Duration(seconds=0).to_msg() # 永不过期
|
||||
return m
|
||||
|
||||
def _point(self, x, y, z=None):
|
||||
p = Point()
|
||||
p.x = float(x)
|
||||
p.y = float(y)
|
||||
p.z = float(self.z if z is None else z)
|
||||
return p
|
||||
|
||||
# ---------------- 三类 marker ----------------
|
||||
def publish_all(self):
|
||||
now = self.get_clock().now().to_msg()
|
||||
ms = []
|
||||
|
||||
# ① 场地内圈边界(黄色线框,闭合)
|
||||
line = self._base(1, Marker.LINE_STRIP)
|
||||
line.header.stamp = now
|
||||
line.scale.x = 0.04
|
||||
line.color.r, line.color.g, line.color.b, line.color.a = 1.0, 0.85, 0.1, 1.0
|
||||
for x, y in ((X0, Y0), (X0 + FIELD_W, Y0), (X0 + FIELD_W, Y0 + FIELD_H),
|
||||
(X0, Y0 + FIELD_H), (X0, Y0)):
|
||||
line.points.append(self._point(x, y))
|
||||
ms.append(line)
|
||||
|
||||
# ② 中线(蓝色十字,交点在场地中心)
|
||||
cross = self._base(2, Marker.LINE_LIST)
|
||||
cross.header.stamp = now
|
||||
cross.scale.x = 0.03
|
||||
cross.color.r, cross.color.g, cross.color.b, cross.color.a = 0.2, 0.5, 1.0, 1.0
|
||||
cross.points.append(self._point(CENTER_X, Y0))
|
||||
cross.points.append(self._point(CENTER_X, Y0 + FIELD_H))
|
||||
cross.points.append(self._point(X0, CENTER_Y))
|
||||
cross.points.append(self._point(X0 + FIELD_W, CENTER_Y))
|
||||
ms.append(cross)
|
||||
|
||||
# ③ 红色圆柱:用 map 帧表达场地中心
|
||||
cyl = self._base(3, Marker.CYLINDER)
|
||||
cyl.header.stamp = now
|
||||
cyl.pose.position = self._point(CENTER_X, CENTER_Y, self.z + 0.25)
|
||||
cyl.scale.x = cyl.scale.y = 0.30
|
||||
cyl.scale.z = 0.50
|
||||
cyl.color.r, cyl.color.g, cyl.color.b, cyl.color.a = 1.0, 0.1, 0.1, 0.75
|
||||
ms.append(cyl)
|
||||
|
||||
# ④ 绿色球:用 field 帧表达同一个点。和红色圆柱重合 = 变换正确
|
||||
sph = self._base(4, Marker.SPHERE)
|
||||
sph.header.stamp = now
|
||||
sph.header.frame_id = 'field' # ← 注意这里换成 field 帧
|
||||
sph.pose.position = self._point(0.0, 0.0, self.z + 0.25)
|
||||
sph.scale.x = sph.scale.y = sph.scale.z = 0.22
|
||||
sph.color.r, sph.color.g, sph.color.b, sph.color.a = 0.1, 1.0, 0.2, 0.85
|
||||
ms.append(sph)
|
||||
|
||||
# ⑤ 文字标签
|
||||
text = self._base(5, Marker.TEXT_VIEW_FACING)
|
||||
text.header.stamp = now
|
||||
text.pose.position = self._point(CENTER_X, CENTER_Y, self.z + 0.75)
|
||||
text.scale.z = 0.35
|
||||
text.color.r = text.color.g = text.color.b = text.color.a = 1.0
|
||||
text.text = 'field(0,0) = map(0,0)'
|
||||
ms.append(text)
|
||||
|
||||
for m in ms:
|
||||
self.pub.publish(m)
|
||||
|
||||
|
||||
def main():
|
||||
rclpy.init()
|
||||
node = FieldCenterMarker()
|
||||
try:
|
||||
rclpy.spin(node)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except Exception: # noqa: BLE001
|
||||
# 退出竞态(跟 odom_tf 同样的问题):context 已经关了就不用报
|
||||
if rclpy.ok():
|
||||
raise
|
||||
finally:
|
||||
node.destroy_node()
|
||||
rclpy.try_shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""诊断 Nav2:代价地图是否在更新、TF 是否完整、能否规划。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import OccupancyGrid
|
||||
from rclpy.node import Node
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
rclpy.init()
|
||||
node = Node('nav_diag')
|
||||
buf = Buffer()
|
||||
TransformListener(buf, node)
|
||||
grids = {}
|
||||
node.create_subscription(OccupancyGrid, '/global_costmap/costmap',
|
||||
lambda m: grids.__setitem__('g', (time.time(), m)), 10)
|
||||
node.create_subscription(OccupancyGrid, '/local_costmap/costmap',
|
||||
lambda m: grids.__setitem__('l', (time.time(), m)), 10)
|
||||
node.create_subscription(OccupancyGrid, '/map',
|
||||
lambda m: grids.__setitem__('m', (time.time(), m)), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 12:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key, name in (('m', '/map'), ('g', 'global_costmap'), ('l', 'local_costmap')):
|
||||
if key in grids:
|
||||
ts, g = grids[key]
|
||||
print(f'{name:16} ✅ 收到 尺寸={g.info.width}x{g.info.height} 分辨率={g.info.resolution} 龄期={time.time()-ts:.1f}s')
|
||||
else:
|
||||
print(f'{name:16} ❌ 没收到(说明这一环没在发布/更新)')
|
||||
|
||||
for parent, child in (('map', 'odom'), ('odom', 'base_link'), ('base_link', 'lidar_link')):
|
||||
try:
|
||||
tr = buf.lookup_transform(parent, child, rclpy.time.Time())
|
||||
p = tr.transform.translation
|
||||
print(f'TF {parent:9} -> {child:10} ✅ ({p.x:+.2f}, {p.y:+.2f}, {p.z:+.2f})')
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'TF {parent:9} -> {child:10} ❌ {str(exc)[:60]}')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""同时探测多个关键话题是否真的有数据。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from rosgraph_msgs.msg import Clock
|
||||
from sensor_msgs.msg import LaserScan
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.msg import ParticleCloud
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_all')
|
||||
got = {}
|
||||
node.create_subscription(Clock, '/clock', lambda m: got.setdefault('clock', m), 10)
|
||||
node.create_subscription(Odometry, '/odom', lambda m: got.setdefault('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('scan', m), 10)
|
||||
node.create_subscription(TFMessage, '/tf', lambda m: got.setdefault('tf', m), 50)
|
||||
node.create_subscription(ParticleCloud, '/particle_cloud', lambda m: got.setdefault('particles', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 5:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key in ('clock', 'odom', 'scan', 'tf', 'particles'):
|
||||
m = got.get(key)
|
||||
if m is None:
|
||||
print(f'{key:10} ✗ 无数据')
|
||||
elif key == 'clock':
|
||||
print(f'clock ✓ sim={m.clock.sec}.{m.clock.nanosec:09d}')
|
||||
elif key == 'odom':
|
||||
print(f'odom ✓ x={m.pose.pose.position.x:.3f}')
|
||||
elif key == 'scan':
|
||||
print(f'scan ✓ frame={m.header.frame_id} rays={len(m.ranges)}')
|
||||
elif key == 'tf':
|
||||
print(f'tf ✓ 本帧变换数={len(m.transforms)}')
|
||||
else:
|
||||
print(f'particles ✓ {len(m.particles) if hasattr(m,"particles") else "?"} 个粒子')
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""统计 /cmd_vel、/model/sentry/cmd_vel 的消息数,并观察 odom 位移。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_cmd')
|
||||
cnt = {'a': 0, 'b': 0}
|
||||
last = {'odom': None}
|
||||
node.create_subscription(Twist, '/cmd_vel', lambda m: cnt.__setitem__('a', cnt['a'] + 1), 10)
|
||||
node.create_subscription(Twist, '/model/sentry/cmd_vel',
|
||||
lambda m: cnt.__setitem__('b', cnt['b'] + 1), 10)
|
||||
node.create_subscription(Odometry, '/odom', lambda m: last.__setitem__('odom', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
print(f'/cmd_vel 消息数={cnt["a"]} /model/sentry/cmd_vel 消息数={cnt["b"]}')
|
||||
if last['odom']:
|
||||
p = last['odom'].pose.pose.position
|
||||
print(f'odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""用 Best Effort QoS 统计 cmd_vel 消息数(Nav2 可能用 best-effort 发布)。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import QoSHistoryPolicy, QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
qos = QoSProfile(depth=10,
|
||||
reliability=QoSReliabilityPolicy.BEST_EFFORT,
|
||||
history=QoSHistoryPolicy.KEEP_LAST)
|
||||
rclpy.init()
|
||||
n = Node('probe_cmd2')
|
||||
cnt = {'a': 0, 'b': 0}
|
||||
n.create_subscription(Twist, '/cmd_vel', lambda m: cnt.__setitem__('a', cnt['a'] + 1), qos)
|
||||
n.create_subscription(Twist, '/model/sentry/cmd_vel',
|
||||
lambda m: cnt.__setitem__('b', cnt['b'] + 1), qos)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(n, timeout_sec=0.2)
|
||||
print(f'/cmd_vel={cnt["a"]} /model/sentry/cmd_vel={cnt["b"]}')
|
||||
n.destroy_node(); rclpy.shutdown()
|
||||
@@ -1,34 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""一次性检查:/odom 和 /scan 有没有数据流进来。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import LaserScan
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_sub')
|
||||
got = {}
|
||||
|
||||
node.create_subscription(Odometry, '/odom', lambda m: got.setdefault('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('scan', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 2:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key in ('odom', 'scan'):
|
||||
msg = got.get(key)
|
||||
if msg is None:
|
||||
print(f'{key} 没收到')
|
||||
elif key == 'odom':
|
||||
p = msg.pose.pose.position
|
||||
print(f'odom OK: x={p.x:.3f} y={p.y:.3f} frame={msg.header.frame_id}')
|
||||
else:
|
||||
finite = [r for r in msg.ranges if r == r and r != float('inf')]
|
||||
print(f'scan OK: frame={msg.header.frame_id} rays={len(msg.ranges)} '
|
||||
f'有效点={len(finite)} 最近={min(finite):.2f}m' if finite else 'scan 全无效')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/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)
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# xmake 会产出的可执行文件,用来反推产物目录。
|
||||
_KNOWN_BINARIES = ('self_filter', 'nav_client', 'patrol', 'odom_tf')
|
||||
|
||||
# 系统 gz 的常见安装位置(按优先级)。
|
||||
_GZ_CANDIDATES = ('/usr/bin/gz', '/usr/local/bin/gz', '/opt/gz/bin/gz')
|
||||
|
||||
|
||||
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 会越叠越长。
|
||||
"""
|
||||
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
|
||||
|
||||
root = os.environ.get('ROS_INSTALL_ROOT')
|
||||
if root and (Path(root) / 'setup.bash').is_file():
|
||||
return Path(root) / 'setup.bash'
|
||||
|
||||
distro = os.environ.get('ROS_DISTRO')
|
||||
if distro:
|
||||
p = Path('/opt/ros') / distro / 'setup.bash'
|
||||
if p.is_file():
|
||||
return p
|
||||
|
||||
found = sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
if not found:
|
||||
return None
|
||||
# 版本号最大 —— `lyrical` > `kilted` > `jazzy` > `iron` > `humble` 这种名字
|
||||
# 排不出来,所以退化成"取最后一个",并在多于一个时提醒调用方。
|
||||
return found[-1]
|
||||
|
||||
|
||||
def ros_setup_candidates():
|
||||
"""列出机器上所有 ROS `setup.bash`,用于在多版本时给出提示。"""
|
||||
return sorted(Path('/opt/ros').glob('*/setup.bash'))
|
||||
|
||||
|
||||
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/
|
||||
unified = build / 'bin'
|
||||
if unified.is_dir() and any((unified / n).is_file() for n 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
|
||||
|
||||
# ③ 还没编译过:返回现行布局的位置
|
||||
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
|
||||
|
||||
|
||||
def gz_version_args():
|
||||
"""返回 `['--force-version', '<主版本>']`,取不到就返回 `[]`。
|
||||
|
||||
写死 10 的话,装了 gz 11 就跑不起来。`GZ_FORCE_VERSION` 可强制指定。
|
||||
"""
|
||||
forced = os.environ.get('GZ_FORCE_VERSION')
|
||||
if forced:
|
||||
return ['--force-version', str(forced)]
|
||||
|
||||
gz = find_gz_bin()
|
||||
if gz is None:
|
||||
return []
|
||||
|
||||
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 []
|
||||
|
||||
|
||||
def find_field_root(ws):
|
||||
"""返回场地迁移包根目录;找不到返回 None。
|
||||
|
||||
不写死 `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
|
||||
|
||||
|
||||
def find_map_yaml(field_root):
|
||||
"""返回栅格图 yaml 路径;找不到返回 None。优先 `rmul_2027.yaml`。"""
|
||||
env = os.environ.get('SENTRY_MAP_YAML')
|
||||
if env:
|
||||
return Path(env)
|
||||
|
||||
if field_root is None:
|
||||
return None
|
||||
|
||||
maps = Path(field_root) / 'src' / 'guodong_sentry_sim' / '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
|
||||
|
||||
|
||||
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 "<无>"}')
|
||||
print(f' FIELD_ROOT : {field_root}')
|
||||
print(f' MAP_YAML : {find_map_yaml(field_root)}')
|
||||
|
||||
|
||||
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)
|
||||
@@ -1,85 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查一个 LaserScan 话题的数据质量:有效束、距离分布、有没有被车体糊住。
|
||||
|
||||
用法:
|
||||
|
||||
python3 tools/scan_probe.py # 默认查 /scan2d(给 AMCL 用的那个)
|
||||
python3 tools/scan_probe.py /scan # 查 3D 雷达的中间层(+22.5°,已知不可用)
|
||||
|
||||
判据速查:
|
||||
|
||||
| 现象 | 含义 |
|
||||
|---|---|
|
||||
| 有效束很少(如 86/360) | 射线打不到东西(仰角朝上)或视野被挡 |
|
||||
| 最近距离 < 0.6 m | 打到**车体自己**(雷达装在车体内,车身最远 0.537 m) |
|
||||
| 全部 inf | 传感器高于围挡(0.42 m)或完全被遮死 |
|
||||
"""
|
||||
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import QoSProfile, ReliabilityPolicy
|
||||
from sensor_msgs.msg import LaserScan
|
||||
|
||||
TOPIC = sys.argv[1] if len(sys.argv) > 1 else '/scan2d'
|
||||
BODY_LIMIT = 0.6 # 车身到雷达最远 0.537 m,低于这个基本是自身回波
|
||||
|
||||
rclpy.init()
|
||||
node = Node('scan_probe')
|
||||
got = {}
|
||||
|
||||
# 传感器数据用 BEST_EFFORT:对 reliable 和 best_effort 的发布者都兼容
|
||||
# (反过来用 reliable 订阅 best_effort 发布者会一条都收不到)
|
||||
qos = QoSProfile(depth=1, reliability=ReliabilityPolicy.BEST_EFFORT)
|
||||
node.create_subscription(LaserScan, TOPIC, lambda m: got.setdefault('s', m), qos)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 12 and 's' not in got:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
s = got.get('s')
|
||||
if s is None:
|
||||
print(f'❌ 12 秒内没收到 {TOPIC}')
|
||||
print(' 检查:话题存在吗?桥里有这一条吗?(sentry_up.sh 和 bridge_after_gz.sh 两处)')
|
||||
node.destroy_node()
|
||||
rclpy.try_shutdown()
|
||||
sys.exit(1)
|
||||
|
||||
ranges = list(s.ranges)
|
||||
valid = [v for v in ranges if math.isfinite(v) and v > 0]
|
||||
print(f'话题={TOPIC} frame={s.header.frame_id}')
|
||||
print(f' 线数={len(ranges)} 有效={len(valid)} ({100.0 * len(valid) / len(ranges):.1f}%) '
|
||||
f'无效={len(ranges) - len(valid)}')
|
||||
print(f' 角度范围=[{s.angle_min:.2f}, {s.angle_max:.2f}] rad '
|
||||
f'量程上限={s.range_max:.1f} m')
|
||||
|
||||
if not valid:
|
||||
print(' ⚠️ 全部是 inf —— 传感器可能高于围挡(0.42 m)或完全被遮死')
|
||||
else:
|
||||
print(f' 距离:最近 {min(valid):.2f} m / 最远 {max(valid):.2f} m')
|
||||
|
||||
# 距离分布:一眼看出有没有被车体糊住
|
||||
buckets = [(0.0, 0.3), (0.3, 0.6), (0.6, 1.0), (1.0, 2.0), (2.0, 5.0),
|
||||
(5.0, 12.1), (12.1, float('inf'))]
|
||||
print(' 距离分布:')
|
||||
for lo, hi in buckets:
|
||||
c = sum(1 for v in valid if lo <= v < hi)
|
||||
if c:
|
||||
tail = ' ← 车体自己' if hi <= BODY_LIMIT else ''
|
||||
print(f' {lo:5.1f} ~ {hi:<5.1f} m : {c:4d} '
|
||||
f'({100.0 * c / len(valid):5.1f}%){tail}')
|
||||
|
||||
body = [v for v in valid if v < BODY_LIMIT]
|
||||
if body:
|
||||
print(f' ⚠️ 低于 {BODY_LIMIT} m 的有 {len(body)} 束 '
|
||||
f'({100.0 * len(body) / len(valid):.1f}%) —— 是车身自身回波')
|
||||
print(f' AMCL 里用 laser_min_range: {BODY_LIMIT} 让 AMCL 丢掉它们')
|
||||
print(' (nav2_params.yaml 的 amcl 段)')
|
||||
else:
|
||||
print(f' ✅ 没有低于 {BODY_LIMIT} m 的束 —— 车体回波已被剔除')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.try_shutdown()
|
||||
@@ -1,50 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""发布一个 /goal_pose 目标点,并监视 /odom 是否真的在动。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
|
||||
goal_x = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
|
||||
goal_y = float(sys.argv[2]) if len(sys.argv) > 2 else 2.0
|
||||
watch = float(sys.argv[3]) if len(sys.argv) > 3 else 40.0
|
||||
|
||||
rclpy.init()
|
||||
node = Node('goal_sender')
|
||||
pub = node.create_publisher(PoseStamped, '/goal_pose', 10)
|
||||
last = {'odom': None}
|
||||
node.create_subscription(Odometry, '/odom',
|
||||
lambda m: last.__setitem__('odom', m), 10)
|
||||
|
||||
# 等 /odom 有数据
|
||||
t0 = time.time()
|
||||
while last['odom'] is None and time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
msg = PoseStamped()
|
||||
msg.header.frame_id = 'map'
|
||||
msg.header.stamp = node.get_clock().now().to_msg()
|
||||
msg.pose.position.x = goal_x
|
||||
msg.pose.position.y = goal_y
|
||||
msg.pose.orientation.w = 1.0
|
||||
pub.publish(msg)
|
||||
print(f'已发送目标 ({goal_x}, {goal_y}),观察 {watch:.0f}s ...')
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < watch:
|
||||
rclpy.spin_once(node, timeout_sec=0.3)
|
||||
if int((time.time() - t0)) % 5 == 0:
|
||||
m = last['odom']
|
||||
if m:
|
||||
p = m.pose.pose.position
|
||||
print(f' t={time.time()-t0:4.1f}s odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
time.sleep(1)
|
||||
m = last['odom']
|
||||
if m:
|
||||
p = m.pose.pose.position
|
||||
print(f'最终 odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -1,105 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""冒烟探针:等 Nav2 完全激活 → 收几帧过滤后的点云 → 发导航目标并等结果。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.qos import QoSProfile, ReliabilityPolicy
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav2_msgs.action import NavigateToPose
|
||||
from lifecycle_msgs.srv import GetState
|
||||
from lifecycle_msgs.msg import State
|
||||
|
||||
rclpy.init()
|
||||
node = Node('smoke_probe', parameter_overrides=[])
|
||||
node.set_parameters([rclpy.parameter.Parameter('use_sim_time',
|
||||
rclpy.Parameter.Type.BOOL, True)])
|
||||
|
||||
got = {'cloud': 0, 'pts': 0}
|
||||
|
||||
|
||||
def on_cloud(msg):
|
||||
got['cloud'] += 1
|
||||
got['pts'] = msg.width * msg.height
|
||||
|
||||
|
||||
qos = QoSProfile(depth=3, reliability=ReliabilityPolicy.BEST_EFFORT)
|
||||
node.create_subscription(PointCloud2, '/scan/points_filtered', on_cloud, qos)
|
||||
|
||||
|
||||
def wait_active(name, timeout):
|
||||
"""等某个 lifecycle 节点进入 ACTIVE(id=3)。"""
|
||||
cli = node.create_client(GetState, f'/{name}/get_state')
|
||||
if not cli.wait_for_service(timeout_sec=10.0):
|
||||
return f'服务 /{name}/get_state 不存在'
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
fut = cli.call_async(GetState.Request())
|
||||
rclpy.spin_until_future_complete(node, fut, timeout_sec=5.0)
|
||||
if fut.done() and fut.result() is not None:
|
||||
st = fut.result().current_state
|
||||
if st.id == State.PRIMARY_STATE_ACTIVE:
|
||||
return None
|
||||
print('[probe] %s = %s,继续等…' % (name, st.label))
|
||||
time.sleep(2)
|
||||
return f'{name} {timeout} 秒内没到 ACTIVE'
|
||||
|
||||
|
||||
print('[probe] 等 Nav2 生命周期节点激活…')
|
||||
for name in ('bt_navigator', 'planner_server', 'controller_server'):
|
||||
err = wait_active(name, 180)
|
||||
if err:
|
||||
print('[probe] ❌', err)
|
||||
sys.exit(2)
|
||||
print('[probe] ✅ %s ACTIVE' % name)
|
||||
|
||||
AC = ActionClient(node, NavigateToPose, 'navigate_to_pose')
|
||||
if not AC.wait_for_server(timeout_sec=30.0):
|
||||
print('[probe] ❌ navigate_to_pose 动作服务器不存在')
|
||||
sys.exit(2)
|
||||
print('[probe] ✅ 动作服务器就绪')
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 25 and got['cloud'] < 3:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
print('[probe] /scan/points_filtered: %d 帧, 最后一帧 %d 点 %s'
|
||||
% (got['cloud'], got['pts'], '✅' if got['cloud'] else '❌ 一帧都没收到'))
|
||||
|
||||
goal = NavigateToPose.Goal()
|
||||
goal.pose = PoseStamped()
|
||||
goal.pose.header.frame_id = 'map'
|
||||
goal.pose.header.stamp = node.get_clock().now().to_msg()
|
||||
goal.pose.pose.position.x = 2.0
|
||||
goal.pose.pose.position.y = 2.0
|
||||
goal.pose.pose.orientation.w = 1.0
|
||||
|
||||
print('[probe] 发导航目标 (2.0, 2.0) …')
|
||||
handle = None
|
||||
for attempt in range(1, 13):
|
||||
send = AC.send_goal_async(goal)
|
||||
rclpy.spin_until_future_complete(node, send, timeout_sec=30)
|
||||
handle = send.result()
|
||||
if handle is not None and handle.accepted:
|
||||
print('[probe] 目标已接受(第 %d 次尝试)' % attempt)
|
||||
break
|
||||
print('[probe] 第 %d 次被拒绝,5 秒后重试…' % attempt)
|
||||
time.sleep(5)
|
||||
handle = None
|
||||
|
||||
if handle is None:
|
||||
print('[probe] ❌ 目标始终被拒绝')
|
||||
sys.exit(3)
|
||||
|
||||
res = handle.get_result_async()
|
||||
rclpy.spin_until_future_complete(node, res, timeout_sec=300)
|
||||
if not res.done():
|
||||
print('[probe] ❌ 300 秒内没拿到结果')
|
||||
sys.exit(4)
|
||||
status = res.result().status
|
||||
print('[probe] ★ NavigateToPose status = %d (%s)'
|
||||
% (status, 'SUCCEEDED' if status == 4 else '不是 SUCCEEDED'))
|
||||
rclpy.shutdown()
|
||||
sys.exit(0 if status == 4 else 5)
|
||||
@@ -1,200 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""实时盯 TF 三条边 + Gazebo 真值 + 雷达有效率,专抓「定位瞬移」。
|
||||
|
||||
用法::
|
||||
|
||||
python3 tools/tf_watch.py # 5 Hz,跑 30 秒
|
||||
python3 tools/tf_watch.py --time 90 # 跑久一点
|
||||
python3 tools/tf_watch.py --rate 10 # 采样更密
|
||||
python3 tools/tf_watch.py --gz-off # 不查 Gazebo 真值(更快)
|
||||
|
||||
用法:这个窗口一直开着,**另开一个终端发导航目标**,就能看到到底是哪一段在跳:
|
||||
|
||||
map --(AMCL)--> odom --(gz /odom)--> base_link
|
||||
|
||||
``map->odom`` 跳 = AMCL 粒子滤波崩了(重定位/随机注入/地图对不上)。
|
||||
``map->base_link`` 跳但 ``map->odom`` 稳 = 里程计那边出问题。
|
||||
|
||||
同时统计 ``/scan2d`` 的有效返回率 —— 有效率太低(大量 inf)说明
|
||||
雷达几乎没看到东西,AMCL 没有观测可以纠正,漂移和乱跳都会发生。
|
||||
"""
|
||||
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
import rclpy.time
|
||||
from rclpy.node import Node
|
||||
from rclpy.parameter import Parameter
|
||||
from sensor_msgs.msg import LaserScan
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
# 单帧位移超过这个值就算「瞬移」(米)。
|
||||
JUMP_THRESHOLD = 0.25
|
||||
# Gazebo 真值的查询间隔(秒)—— 起一个子进程,别太频繁。
|
||||
GZ_INTERVAL = 0.4
|
||||
|
||||
|
||||
def parse_args(argv):
|
||||
"""解析 --time / --rate / --gz-off。"""
|
||||
opts = {'time': 30.0, 'rate': 5.0, 'gz': True}
|
||||
i = 0
|
||||
while i < len(argv):
|
||||
a = argv[i]
|
||||
if a == '--gz-off':
|
||||
opts['gz'] = False
|
||||
elif a == '--time':
|
||||
opts['time'] = float(argv[i + 1])
|
||||
i += 1
|
||||
elif a == '--rate':
|
||||
opts['rate'] = float(argv[i + 1])
|
||||
i += 1
|
||||
i += 1
|
||||
return opts
|
||||
|
||||
|
||||
def gz_truth(model='sentry'):
|
||||
"""问 Gazebo 要模型的真值位姿,返回 (x, y, yaw) 或 None。
|
||||
|
||||
注意要清掉 LD_LIBRARY_PATH:本机 apt 版 gz 和 ROS vendor 版并存,
|
||||
带着 ROS 的库路径会去加载另一个版本的 gz,行为诡异。
|
||||
"""
|
||||
env = dict(os.environ)
|
||||
env.pop('LD_LIBRARY_PATH', None)
|
||||
env.setdefault('GZ_PARTITION', 'sentry')
|
||||
try:
|
||||
out = subprocess.run(['gz', 'model', '-m', model, '--pose'],
|
||||
capture_output=True, text=True, timeout=5, env=env)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
text = out.stdout + out.stderr
|
||||
# 兼容单行和多行两种输出:
|
||||
# Pose [ XYZ (m) ] [ RPY (rad) ]: 6 numbers
|
||||
xyz = re.search(r'XYZ \(m\) \]:\s*([-\d.eE+]+)\s+([-\d.eE+]+)', text)
|
||||
if not xyz:
|
||||
xyz = re.search(r'^\s*([-\d.eE+]+)\s+([-\d.eE+]+)\s+[-\d.eE+]+ '
|
||||
r'[-\d.eE+]+ [-\d.eE+]+ ([-\d.eE+]+)', text, re.M)
|
||||
if not xyz:
|
||||
return None
|
||||
return float(xyz.group(1)), float(xyz.group(2))
|
||||
|
||||
|
||||
def fmt(v):
|
||||
"""把 (x, y) 格式化成定长字符串。"""
|
||||
return f'({v[0]:6.2f},{v[1]:6.2f})'
|
||||
|
||||
|
||||
def main():
|
||||
"""采样并打印 TF / 真值 / 雷达统计。"""
|
||||
opts = parse_args(sys.argv[1:])
|
||||
rclpy.init()
|
||||
node = Node('tf_watch',
|
||||
parameter_overrides=[
|
||||
Parameter('use_sim_time', Parameter.Type.BOOL, True)])
|
||||
buf = Buffer()
|
||||
TransformListener(buf, node)
|
||||
|
||||
scan_stats = {'n': 0, 'finite': 0, 'lo': float('inf'), 'hi': 0.0}
|
||||
|
||||
def on_scan(msg):
|
||||
vals = [r for r in msg.ranges if math.isfinite(r)]
|
||||
scan_stats['n'] = len(msg.ranges)
|
||||
scan_stats['finite'] = len(vals)
|
||||
if vals:
|
||||
scan_stats['lo'] = min(vals)
|
||||
scan_stats['hi'] = max(vals)
|
||||
|
||||
node.create_subscription(LaserScan, '/scan2d', on_scan, 10)
|
||||
|
||||
def look(parent, child):
|
||||
"""查一条 TF 边,查不到返回 None。"""
|
||||
try:
|
||||
tr = buf.lookup_transform(parent, child, rclpy.time.Time())
|
||||
p = tr.transform.translation
|
||||
return (p.x, p.y)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
print(f'采样 {opts["rate"]:.0f} Hz,共 {opts["time"]:.0f} s;'
|
||||
f'瞬移阈值 {JUMP_THRESHOLD:.2f} m')
|
||||
print('另开一个终端发导航目标,我这边盯着。\n')
|
||||
print(f'{"t":>6} {"map->odom":>17} {"odom->base":>17} '
|
||||
f'{"map->base":>17} {"GZ 真值":>17} {"偏差":>7}')
|
||||
print(' ' + '-' * 86)
|
||||
|
||||
period = 1.0 / max(1.0, opts['rate'])
|
||||
t_start = time.time()
|
||||
prev = {}
|
||||
jumps = {k: 0 for k in ('map->odom', 'odom->base', 'map->base')}
|
||||
truth = None
|
||||
t_gz = -1e9
|
||||
errs = []
|
||||
|
||||
while time.time() - t_start < opts['time']:
|
||||
rclpy.spin_once(node, timeout_sec=period)
|
||||
now = time.time() - t_start
|
||||
|
||||
mo = look('map', 'odom')
|
||||
ob = look('odom', 'base_link')
|
||||
mb = look('map', 'base_link')
|
||||
|
||||
if opts['gz'] and now - t_gz > GZ_INTERVAL:
|
||||
got = gz_truth()
|
||||
t_gz = now
|
||||
if got:
|
||||
# Gazebo 世界坐标 = map 坐标(场地西南内角 = (0,0))
|
||||
truth = got
|
||||
|
||||
flags = []
|
||||
for key, val in (('map->odom', mo), ('odom->base', ob), ('map->base', mb)):
|
||||
if val is None:
|
||||
continue
|
||||
old = prev.get(key)
|
||||
if old is not None:
|
||||
d = math.hypot(val[0] - old[0], val[1] - old[1])
|
||||
if d > JUMP_THRESHOLD:
|
||||
jumps[key] += 1
|
||||
flags.append(f'{key} 跳 {d:.2f} m')
|
||||
prev[key] = val
|
||||
|
||||
dev = ''
|
||||
if truth and mb:
|
||||
e = math.hypot(mb[0] - truth[0], mb[1] - truth[1])
|
||||
errs.append(e)
|
||||
dev = f'{e:6.2f} m'
|
||||
|
||||
mark = (' ⚠️ ' + ' / '.join(flags)) if flags else ''
|
||||
print(f'{now:6.1f} {fmt(mo) if mo else " (无) ":>17} '
|
||||
f'{fmt(ob) if ob else " (无) ":>17} '
|
||||
f'{fmt(mb) if mb else " (无) ":>17} '
|
||||
f'{fmt(truth) if truth else " (无) ":>17} '
|
||||
f'{dev:>7}{mark}')
|
||||
|
||||
print('\n=== 汇总 ===')
|
||||
for key, n in jumps.items():
|
||||
print(f' {key:10} 瞬移次数: {n}')
|
||||
if errs:
|
||||
print(f' map->base 相对真值: 平均 {sum(errs)/len(errs):.2f} m '
|
||||
f'最大 {max(errs):.2f} m (采样 {len(errs)} 次)')
|
||||
if scan_stats['n']:
|
||||
rate = scan_stats['finite'] / scan_stats['n'] * 100
|
||||
print(f' /scan2d 有效返回: {scan_stats["finite"]}/{scan_stats["n"]} '
|
||||
f'= {rate:.1f}% 距离范围 '
|
||||
f'{scan_stats["lo"]:.2f} ~ {scan_stats["hi"]:.2f} m')
|
||||
if rate < 20.0:
|
||||
print(' ⚠️ 有效率太低:雷达基本没看到东西,AMCL 没有观测可纠正,'
|
||||
'必然漂移/乱跳。')
|
||||
else:
|
||||
print(' /scan2d 没收到任何数据')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user