feat: AMCL 定位接入、场地定位工具与文档更新

This commit is contained in:
mzx committed 2026-11-19 12:54:02 +08:00
1 parent 0c6b49e276
commit 0e4e4c6e18
45 files changed
+3173 -151

No files matched your search

+10 -4
View File
@@ -18,13 +18,18 @@
|---|---|
| `demo.py` | 前进 → 转向 → 再前进,并打印雷达和里程计 |
| `drive_demo.py` | 走正方形并生成 SVG 轨迹图(`generated/drive_trajectory.svg`) |
| `nav_client.py` | 发 Nav2 目标点,打印反馈/结果/TF |
| `send_goal.py` | 用 `/goal_pose` 话题发目标 |
| `scan_probe.py` | 检查雷达质量(有效点、最近/最远距离) |
| `nav_client.py` | ★ 发 Nav2 目标点。**发之前先读 `/map` 预检**:占据值 ≥65、未知格、净空 <0.5 m(车体半对角 0.422 m)都直接拦下并说明原因,不合格不发。通过后打印位置/重试次数/结果/离目标误差/field 坐标 |
| `free_goals.py` | ★ 从 `rmul_2027.yaml` + `.pgm` 算出「从起点连通的安全区」并列出可去目标点(附净空、距离、可直接复制的 `nav_client.py` 命令)。**不需要起 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` 这个字符串)。要发目标请用 `nav_client.py` |
| `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,一条命令问清"现在这套栈健康吗" |
## 构建 / 编辑器
@@ -47,7 +52,8 @@ python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/mes
# 演示
python3 tools/drive_demo.py 1.0
python3 tools/scan_probe.py
python3 tools/scan_probe.py # 默认查 /scan2d(给 AMCL 用的)
python3 tools/scan_probe.py /scan # 查 3D 雷达中间层(+22.5°,不可用)
```
> 这些脚本按「单次运行」写的:需要先按根目录 README 把仿真跑起来,再在另一个终端执行。
+165
View File
@@ -0,0 +1,165 @@
#!/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 自己的避障要另外验证(用 nav_client.py 发目标)。')
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()
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env bash
# Fast DDS 健康状况体检 —— 专门查「ROS 2 节点互相发现不到」这类间歇性故障。
#
# 用法:
# tools/check_dds.sh 只检查,不动任何东西
# tools/check_dds.sh --clean 清理 /dev/shm 里的残留共享内存段
# (会先确认没有 ROS 进程在跑,有就拒绝执行)
#
# 背景:ROS 2 反复启停、尤其是被 kill -9 或崩溃之后,Fast DDS 会在 /dev/shm
# 留下共享内存文件。这些残留会让新起的进程连不上或发现失败,典型症状是:
# · ros2 action list 能看到某个 action,但另一个节点说 "not available"
# · 每次失败的点都不一样(这次是 is_path_valid,下次是 wait)
# · 只有重启机器才"莫名其妙好了"
set -u
SEG_PATTERN='fastrtps|fast_datachannel|fastdds|iceoryx|sem\.fastdds'
RC=0
echo "=============================================="
echo " 1. /dev/shm 占用"
echo "=============================================="
df -h /dev/shm | sed 's/^/ /'
total=$(ls -1 /dev/shm 2>/dev/null | wc -l)
fast=$(ls -1 /dev/shm 2>/dev/null | grep -cE "$SEG_PATTERN")
echo " 文件总数 : $total"
echo " Fast DDS 残留段 : $fast"
if [ "$fast" -gt 0 ]; then
echo " → 前 10 个:"
ls -1 /dev/shm | grep -E "$SEG_PATTERN" | head -10 | sed 's/^/ /'
fi
echo
echo "=============================================="
echo " 2. 有没有 ROS / 仿真进程在跑"
echo "=============================================="
# 两个注意点:
# ① robot_state_publisher 把整段 URDF 当命令行参数传(几千字符),
# 直接打 args 会把屏幕冲掉 → 这里只打前 48 个字符
# ② 用 grep 匹配命令行时,**自己这条命令也会被匹配到**(脚本源码里就有这些词)
# → 排除自身 PID、父进程、以及命令行里含本脚本名的
SELF=$$
SELF_PARENT=$PPID
PAT='sentry_up\.sh|gz sim|gz-sim-main|gz-sim-server|parameter_bridge|robot_state_publisher|self_filter|odom_tf\.py|cmd_vel_relay\.py|rviz2|nav2_|amcl|map_server|bt_navigator|controller_server|planner_server|behavior_server|smoother_server|waypoint_follower|velocity_smoother|collision_monitor|lifecycle_manager|docking_server|route_server|following_server'
PROC_LIST=$(ps -eo pid,ppid,etimes,args \
| grep -E "$PAT" \
| grep -vE "^\s*($SELF|$SELF_PARENT)\s" \
| grep -v 'check_dds\.sh' \
| grep -v 'grep -E')
n_pids=$(printf '%s\n' "$PROC_LIST" | grep -cE '^[[:space:]]*[0-9]' || true)
if [ "$n_pids" -eq 0 ]; then
echo " ✅ 没有相关进程在跑(可以安全清理)"
else
echo " ⚠️ 还有 $n_pids 个相关进程在跑:"
printf " %-8s %8s %s\n" "PID" "运行秒" "命令(截断)"
printf '%s\n' "$PROC_LIST" | awk '
{ printf " %-8s %8s %s\n", $1, $3, substr($0, index($0,$4), 48) }'
echo
echo " 停法(按顺序):"
echo " 1) 先停启动脚本,它自己的 trap 会收掉整棵进程树:"
echo " pgrep -a -f 'scripts/sentry_up.sh' # 找到 PID"
echo " kill <那个 PID> # 只杀父脚本"
echo " 2) 等 5 秒,再回来跑本脚本确认干净"
echo " 3) 上面这些是脱队的孤儿(父进程已经没了),直接按 PID 停:"
echo " 复制下面这几行执行即可:"
printf '%s\n' "$PROC_LIST" | awk '
/^[[:space:]]*[0-9]/ && $1 != "" { printf " kill %s\n", $1 }'
echo " 还赖着的再补一刀:"
printf '%s\n' "$PROC_LIST" | awk '
/^[[:space:]]*[0-9]/ && $1 != "" { printf " kill -9 %s\n", $1 }'
echo
echo " ⚠️ 别用 pkill -f 'nav2_' 之类 —— 会匹配到你自己这条命令。"
fi
echo
echo "=============================================="
echo " 3. DDS 相关环境变量"
echo "=============================================="
for v in RMW_IMPLEMENTATION ROS_DOMAIN_ID ROS_LOCALHOST_ONLY FASTDDS_BUILTIN_TRANSPORTS \
GZ_PARTITION GZ_IP GZ_DISCOVERY; do
val="${!v:-<未设>}"
printf " %-30s = %s\n" "$v" "$val"
done
echo " 提示:sentry_up.sh 里 GZ_PARTITION 默认是 sentry;"
echo " 在别的终端查 gz 状态时要带上同名分区。"
echo
echo "=============================================="
echo " 4. 内核网络缓冲(大消息/点云走 UDP 时会用到)"
echo "=============================================="
printf " net.core.rmem_max = %s\n" "$(cat /proc/sys/net/core/rmem_max 2>/dev/null || echo '?')"
printf " net.core.wmem_max = %s\n" "$(cat /proc/sys/net/core/wmem_max 2>/dev/null || echo '?')"
echo
echo "=============================================="
echo " 结论"
echo "=============================================="
if [ "$fast" -eq 0 ]; then
echo " ✅ /dev/shm 干净,没有 Fast DDS 残留。"
echo " 如果节点仍然发现不到彼此,问题不在这里 —— 换方案 B(自定义 BT 去掉 Wait)。"
else
echo " ⚠️ 发现 $fast 个 Fast DDS 残留段。"
if [ "$n_pids" -eq 0 ]; then
if [ "${1:-}" = "--clean" ]; then
echo " → 开始清理…"
ls -1 /dev/shm | grep -E "$SEG_PATTERN" | while read -r f; do
rm -f "/dev/shm/$f" 2>/dev/null
done
after=$(ls -1 /dev/shm | grep -cE "$SEG_PATTERN")
echo " → 清理完成,剩余 $after 个"
df -h /dev/shm | tail -1 | sed 's/^/ /'
else
echo " → 加 --clean 参数可以清理(会先确认没有进程在跑):"
echo " tools/check_dds.sh --clean"
fi
else
echo " → 先停掉上面列出的进程,再跑:tools/check_dds.sh --clean"
RC=2
fi
fi
exit $RC
+100
View File
@@ -8,6 +8,10 @@
退出码 0 = 一切正常;非 0 = 有东西没起来(逐条原因见输出)。
"""
import math
import os
import re
import subprocess
import sys
import time
@@ -48,6 +52,69 @@ MAP_QOS = QoSProfile(
SENSOR_QOS = QoSProfile(depth=1, reliability=ReliabilityPolicy.BEST_EFFORT)
def parse_gz_pose(out):
"""从 `gz model -m X -p` 的输出里抽出世界位姿,返回 (x,y,z,roll,pitch,yaw)。
真实输出是**多行**的(数值在标签下面两行,各自一个方括号):
Model: [52]
- Name: sentry
- Pose [ XYZ (m) ] [ RPY (rad) ]:
[0.900000 4.000000 0.000000]
[0.000000 -0.000000 0.000000]
注意标签本身就带两个方括号(`[ XYZ (m) ]` `[ RPY (rad) ]`),
所以不能"取第一个 []";要往后几行找真正的数值。
"""
lines = out.splitlines()
for i, line in enumerate(lines):
if 'Pose' not in line or 'XYZ' not in line:
continue
# 数值可能在同一行(冒号后),也可能在随后的两三行里
chunk = ' '.join(lines[i:i + 3])
tail = chunk.split(':', 1)[1] if ':' in chunk else chunk
triples = []
for grp in re.findall(r'\[([^\]]+)\]', tail):
nums = [float(v) for v in re.findall(
r'-?\d+(?:\.\d*)?(?:[eE][-+]?\d+)?', grp)]
if len(nums) == 3:
triples.append(nums)
if len(triples) >= 2:
return tuple(triples[0] + triples[1])
# 兜底:万一某些版本把 6 个数直接裸打在冒号后面,没有方括号
flat = [float(v) for v in re.findall(
r'-?\d+(?:\.\d*)?(?:[eE][-+]?\d+)?', tail)]
if len(flat) >= 6:
return tuple(flat[:6])
return None
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 的库,
# 和服务端(系统版 10.6)不是同一套
env.pop('LD_LIBRARY_PATH', None)
cmd = ['/usr/bin/gz', 'model', '-m', model_name, '-p']
try:
out = subprocess.run(cmd, env=env, capture_output=True, text=True,
timeout=10).stdout
except (OSError, subprocess.SubprocessError):
return None
return parse_gz_pose(out)
def main():
rclpy.init()
# 整套栈都是 use_sim_time:=true,探针也必须一致,否则时间戳比较会出错
@@ -140,6 +207,39 @@ def main():
for line in buf.all_frames_as_yaml().splitlines():
print(' ' + line)
# ---------- 4. 定位真值对照 ----------
print('\n=== 4. 定位真值对照 ===')
truth = gz_model_pose('sentry')
tf_pos = None
try:
got = buf.lookup_transform('map', 'base_link', rclpy.time.Time(),
Duration(seconds=1.0))
tf_pos = (got.transform.translation.x, got.transform.translation.y)
except Exception:
pass
if truth is None:
print(' ⚠️ 拿不到 Gazebo 真值(仿真没在跑,或 GZ_PARTITION 对不上)')
print(' 手动试:GZ_PARTITION=%s gz model -m sentry -p'
% os.environ.get('GZ_PARTITION', 'sentry'))
else:
gx, gy = truth[0], truth[1]
print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy))
print(' 场地坐标 (map) (%.3f, %.3f)' % (gx, gy))
print(' 中心零点 (field) (%.3f, %.3f)' % (gx - 6.0, gy - 4.0))
if tf_pos is None:
print(' [TF] map -> base_link 拿不到,无法比较')
else:
dev = math.hypot(tf_pos[0] - gx, tf_pos[1] - gy)
flag = '✅' if dev < 0.05 else ('⚠️ ' if dev < 0.5 else '❌')
print(' [TF] map -> base_link (%.3f, %.3f)' % tf_pos)
print(' [偏差] %.3f m %s' % (dev, flag))
if dev >= 0.05:
note = ('现在定位是"作弊"的(静态 map->odom + 轮速里程计),'
'偏差会随时间累积且不自愈')
print(' %s' % note)
problems.append('TF 位置与 Gazebo 真值差 %.2f m' % dev)
# ---------- 汇总 ----------
print('\n=== 汇总 ===')
if problems:
+222
View File
@@ -0,0 +1,222 @@
#!/usr/bin/env python3
"""从栅格图里找出「车能安全通过」的目标点,并检查从起点连不连得过去。
用法::
python3 tools/free_goals.py # 起点默认 (0.9, 4.0) 出生点
python3 tools/free_goals.py --from 6.0 4.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=[0.9, 4.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' python3 tools/nav_client.py {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())
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""把「场地中心 = 零点」画出来,方便肉眼核对位置对不对。
发布可视化 Marker(不改仿真里的任何东西,纯叠加显示):
① 红色圆柱 —— 用 `map` 帧表达场地中心 (6.0, 4.0)
② 绿色球 —— 用 `field` 帧表达同一个点 (0.0, 0.0)
两者如果**完全重合**,说明 map→field 这条变换是对的
③ 黄色线框 —— 场地内圈 12×8 的边界(`map` 帧 x[0,12] y[0,8])
④ 蓝色细线 —— 场地中线(crosshair),交点在场地中心
⑤ 文字标签 —— "field(0,0) = map(6.0,4.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
# 场地几何(来自官方 parameters.json:内圈 12×8,西南内角 = (0,0))
FIELD_W = 12.0
FIELD_H = 8.0
CENTER_X = FIELD_W / 2.0 # 6.0
CENTER_Y = 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 ((0, 0), (FIELD_W, 0), (FIELD_W, FIELD_H),
(0, FIELD_H), (0, 0)):
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, 0.0))
cross.points.append(self._point(CENTER_X, FIELD_H))
cross.points.append(self._point(0.0, CENTER_Y))
cross.points.append(self._point(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(6.0,4.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.py 同样的问题):context 已经关了就不用报
if rclpy.ok():
raise
finally:
node.destroy_node()
rclpy.try_shutdown()
if __name__ == '__main__':
sys.exit(main())
+210 -48
View File
@@ -1,68 +1,230 @@
#!/usr/bin/env python3
"""用 Nav2 的 NavigateToPose 动作发目标,打印反馈与结果,并检查 TF。"""
"""用 Nav2 的 NavigateToPose 动作发目标,发之前先用栅格图做可达性预检。
用法::
python3 tools/nav_client.py <x> <y> [yaw度]
python3 tools/nav_client.py 6.0 4.0 # 走到场地中部
python3 tools/nav_client.py 6.0 4.0 90 # 到位置后朝向 +90°
python3 tools/nav_client.py 3.0 4.0 --force # 明知在障碍里也发(调试用)
坐标是 map 帧:x∈[0,12],y∈[0,8],出生点 (0.9, 4.0)。
想换成「场地中心 = 零点」的直觉坐标:field = (map_x - 6, map_y - 4)。
为什么要预检:Nav2 的规划器对「目标点落在障碍格里」只会吐一句
``Failed to create plan with tolerance of: 0.500000``,看不出原因。
这里直接读 /map,把目标点的占据值和净空算出来,不合格就在发之前拦住。
"""
import math
import sys
import time
import numpy as np
import rclpy
from nav2_msgs.action import NavigateToPose
from nav_msgs.msg import OccupancyGrid
from rclpy.action import ActionClient
from rclpy.node import Node
from rclpy.parameter import Parameter
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy
from tf2_ros import Buffer, TransformListener
gx = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
gy = float(sys.argv[2]) if len(sys.argv) > 2 else 2.0
# 车体是 0.65 x 0.54 矩形,半对角 0.422 m;小于这个值必然车身压障碍。
HALF_DIAGONAL = 0.422
# 低于这个净空就不建议去(膨胀层默认 0.45)。
MIN_CLEARANCE = 0.50
# 判定「被占据」的阈值,和 rmul_2027.yaml 的 occupied_thresh 对齐。
OCCUPIED_THRESHOLD = 65
# 净空搜索半径上限(米)。
CLEARANCE_SEARCH = 2.0
rclpy.init()
# 整套栈都是 use_sim_time:=true(Gazebo 时钟),客户端必须一致,
# 否则本节点算出的时间戳跟 TF 里的仿真时间对不上。
node = Node('nav_client',
parameter_overrides=[
Parameter('use_sim_time', Parameter.Type.BOOL, True)])
tf_buffer = Buffer()
TransformListener(tf_buffer, node)
client = ActionClient(node, NavigateToPose, 'navigate_to_pose')
print('等待 navigate_to_pose 动作服务器...')
if not client.wait_for_server(timeout_sec=30):
print('❌ 动作服务器不可用')
raise SystemExit(1)
print('✅ 动作服务器可用')
def parse_args(argv):
"""分出位置参数和 --force。"""
force = '--force' in argv
pos = [a for a in argv if not a.startswith('--')]
gx = float(pos[0]) if len(pos) > 0 else 6.0
gy = float(pos[1]) if len(pos) > 1 else 4.0
yaw_deg = float(pos[2]) if len(pos) > 2 else 0.0
return gx, gy, yaw_deg, force
goal = NavigateToPose.Goal()
goal.pose.header.frame_id = 'map'
goal.pose.header.stamp = node.get_clock().now().to_msg()
goal.pose.pose.position.x = gx
goal.pose.pose.position.y = gy
goal.pose.pose.orientation.w = 1.0
sent = client.send_goal_async(goal, feedback_callback=lambda fb: print(
f' 反馈: 剩余 {fb.feedback.distance_remaining:.2f} m'))
rclpy.spin_until_future_complete(node, sent, timeout_sec=15)
handle = sent.result()
if handle is None or not handle.accepted:
print('❌ 目标被拒绝')
raise SystemExit(1)
print('✅ 目标已接受,等待结果...')
def grid_to_array(grid):
"""把 OccupancyGrid 变成 numpy 数组,行 0 = y 最小(和 origin 对齐)。"""
info = grid.info
arr = np.asarray(grid.data, dtype=np.int8).reshape(info.height, info.width)
return arr, info
res = handle.get_result_async()
t0 = time.time()
while not res.done() and time.time() - t0 < 120:
rclpy.spin_once(node, timeout_sec=0.2)
if res.done():
status = res.result().status
def world_to_cell(info, x, y):
"""世界坐标 -> 栅格下标,越界返回 None。"""
c = int(math.floor((x - info.origin.position.x) / info.resolution))
r = int(math.floor((y - info.origin.position.y) / info.resolution))
if not (0 <= c < info.width and 0 <= r < info.height):
return None
return r, c
def clearance_at(arr, res, r, c, search=CLEARANCE_SEARCH):
"""返回 (r, c) 到最近障碍格的距离(米),超过 search 就返回 search。
未知格(-1)也算障碍 —— 代价地图开了 track_unknown_space,
在未知区里规划同样会失败,按障碍处理更接近实际行为。
"""
n = max(1, int(search / res))
r0, r1 = max(0, r - n), min(arr.shape[0], r + n + 1)
c0, c1 = max(0, c - n), min(arr.shape[1], c + n + 1)
win = arr[r0:r1, c0:c1]
bad = (win >= OCCUPIED_THRESHOLD) | (win < 0)
if not bad.any():
return search
rr, cc = np.nonzero(bad)
dist = np.hypot(rr + r0 - r, cc + c0 - c) * res
return float(dist.min())
def yaw_to_quaternion(yaw):
"""从偏航角(弧度)构造只含 z/w 的四元数。"""
return math.sin(yaw / 2.0), math.cos(yaw / 2.0)
def main():
"""发一个目标并跟踪到结束。"""
gx, gy, yaw_deg, force = parse_args(sys.argv[1:])
rclpy.init()
# 整套栈都是 use_sim_time:=true(Gazebo 时钟),客户端必须一致,
# 否则本节点算出的时间戳跟 TF 里的仿真时间对不上。
node = Node('nav_client',
parameter_overrides=[
Parameter('use_sim_time', Parameter.Type.BOOL, True)])
tf_buffer = Buffer()
TransformListener(tf_buffer, node)
# /map 是 TRANSIENT_LOCAL 发布的,用默认 QoS 会一条都收不到。
map_qos = QoSProfile(depth=1,
reliability=ReliabilityPolicy.RELIABLE,
durability=DurabilityPolicy.TRANSIENT_LOCAL)
holder = {}
node.create_subscription(OccupancyGrid, '/map',
lambda m: holder.setdefault('m', m), map_qos)
t0 = time.time()
while 'm' not in holder and time.time() - t0 < 15.0:
rclpy.spin_once(node, timeout_sec=0.2)
if 'm' not in holder:
print('⚠️ 15 秒内没收到 /map,跳过预检直接发目标')
arr = info = None
else:
arr, info = grid_to_array(holder['m'])
print(f'地图 {info.width}x{info.height} @ {info.resolution} m/px '
f'origin=({info.origin.position.x:.2f}, {info.origin.position.y:.2f})')
cell = world_to_cell(info, gx, gy)
if cell is None:
print(f'❌ 目标 ({gx:.2f}, {gy:.2f}) 在地图范围外,发出去也是 ABORTED')
node.destroy_node()
rclpy.shutdown()
return 1
r, c = cell
value = int(arr[r, c])
clr = clearance_at(arr, info.resolution, r, c)
state = ('障碍' if value >= OCCUPIED_THRESHOLD
else '未知' if value < 0 else '空闲')
print(f'目标 ({gx:.2f}, {gy:.2f}) -> 栅格 ({c}, {r}) '
f'占据值 {value:4d} ({state}) 净空 {clr:.2f} m')
if state != '空闲' or clr < MIN_CLEARANCE:
print()
print(f'❌ 这个点不适合当目标(净空需 >= {MIN_CLEARANCE:.2f} m):')
if state == '障碍':
print(' 点落在障碍格里 —— 规划器必然报 '
'"Failed to create plan with tolerance",换一个点。')
elif state == '未知':
print(' 点落在未知区域 —— 代价地图开了 track_unknown_space,同样规划不出来。')
else:
print(f' 净空只有 {clr:.2f} m,车身半对角就有 {HALF_DIAGONAL:.2f} m,'
'挤进去会卡死。')
print(' 想找安全点:python3 tools/free_goals.py')
if not force:
print(' (确实要发就加 --force)')
node.destroy_node()
rclpy.shutdown()
return 2
print(' --force 已指定,继续发送')
client = ActionClient(node, NavigateToPose, 'navigate_to_pose')
print('等待 navigate_to_pose 动作服务器...')
if not client.wait_for_server(timeout_sec=30):
print('❌ 动作服务器不可用(Nav2 没起来,或 bt_navigator 没 ACTIVE)')
node.destroy_node()
rclpy.shutdown()
return 1
print('✅ 动作服务器可用')
goal = NavigateToPose.Goal()
goal.pose.header.frame_id = 'map'
goal.pose.header.stamp = node.get_clock().now().to_msg()
goal.pose.pose.position.x = gx
goal.pose.pose.position.y = gy
qz, qw = yaw_to_quaternion(math.radians(yaw_deg))
goal.pose.pose.orientation.z = qz
goal.pose.pose.orientation.w = qw
# 注意:不要打印 feedback.distance_remaining。
# Nav2 1.5 的 NavigateToPose 不会填这个字段,永远是 0.00,
# 打了只会刷屏骗人。用 current_pose 和 number_of_recoveries。
state = {'last': 0.0}
def on_feedback(fb):
now = time.time()
if now - state['last'] < 1.0:
return
state['last'] = now
f = fb.feedback
p = f.current_pose.pose.position
print(f' 位置 ({p.x:5.2f}, {p.y:5.2f}) '
f'重试 {int(getattr(f, "number_of_recoveries", 0))}')
sent = client.send_goal_async(goal, feedback_callback=on_feedback)
rclpy.spin_until_future_complete(node, sent, timeout_sec=15)
handle = sent.result()
if handle is None or not handle.accepted:
print('❌ 目标被拒绝')
node.destroy_node()
rclpy.shutdown()
return 1
print('✅ 目标已接受,等待结果...')
res = handle.get_result_async()
t0 = time.time()
while not res.done() and time.time() - t0 < 180:
rclpy.spin_once(node, timeout_sec=0.2)
names = {4: '✅ SUCCEEDED', 5: '❌ CANCELED', 6: '❌ ABORTED'}
print(f'结果: {names.get(status, status)}')
else:
print('超时未完成')
if res.done():
status = res.result().status
print(f'结果: {names.get(status, status)}')
else:
print('超时未完成(180 s)')
try:
tr = tf_buffer.lookup_transform('map', 'base_link', rclpy.time.Time())
p = tr.transform.translation
print(f'TF map->base_link: x={p.x:.2f} y={p.y:.2f}')
except Exception as exc: # noqa: BLE001
print(f'⚠️ 查不到 TF map->base_link: {exc}')
try:
tr = tf_buffer.lookup_transform('map', 'base_link', rclpy.time.Time())
p = tr.transform.translation
err = math.hypot(p.x - gx, p.y - gy)
print(f'TF map->base_link: ({p.x:.2f}, {p.y:.2f}) '
f'离目标 {err:.2f} m '
f'field 坐标 ({p.x - 6.0:.2f}, {p.y - 4.0:.2f})')
except Exception as exc: # noqa: BLE001
print(f'⚠️ 查不到 TF map->base_link: {exc}')
node.destroy_node()
rclpy.shutdown()
node.destroy_node()
rclpy.shutdown()
return 0
if __name__ == '__main__':
sys.exit(main())
+66 -10
View File
@@ -1,29 +1,85 @@
#!/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 = {}
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('s', m), 10)
# 传感器数据用 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('没有收到 /scan')
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:
finite = [x for x in s.ranges if x == x and x != float('inf')]
print(f'frame={s.header.frame_id} 线数={len(s.ranges)} 有效={len(finite)} '
f'无效={len(s.ranges) - len(finite)}')
if finite:
print(f'最近={min(finite):.2f}m 最远={max(finite):.2f}m')
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('⚠️ 全部无效(inf):传感器可能高于围挡或被遮死')
print(f' ✅ 没有低于 {BODY_LIMIT} m 的束 —— 车体回波已被剔除')
node.destroy_node()
rclpy.shutdown()
rclpy.try_shutdown()
+200
View File
@@ -0,0 +1,200 @@
#!/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())