258 lines
9.8 KiB
Python
258 lines
9.8 KiB
Python
#!/usr/bin/env python3
|
||
"""只读体检:看当前跑着的这套仿真栈处于什么状态。
|
||
|
||
不发布任何指令、不改任何参数,只读话题/服务/TF。
|
||
**这脚本自己不会干扰仿真**,随便在另一个终端跑。
|
||
|
||
python3 tools/check_stack.py
|
||
|
||
退出码 0 = 一切正常;非 0 = 有东西没起来(逐条原因见输出)。
|
||
"""
|
||
import math
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
import rclpy
|
||
import rclpy.time
|
||
from rclpy.duration import Duration
|
||
from rclpy.node import Node
|
||
from rclpy.parameter import Parameter
|
||
from rclpy.qos import (QoSProfile, ReliabilityPolicy, DurabilityPolicy,
|
||
HistoryPolicy)
|
||
from lifecycle_msgs.msg import State
|
||
from lifecycle_msgs.srv import GetState
|
||
from sensor_msgs.msg import PointCloud2, LaserScan
|
||
from nav_msgs.msg import Odometry, OccupancyGrid
|
||
from tf2_ros import Buffer, TransformListener
|
||
|
||
|
||
# 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力)
|
||
EXPECTED_ACTIVE = [
|
||
'map_server',
|
||
'controller_server',
|
||
'planner_server',
|
||
'bt_navigator',
|
||
'behavior_server',
|
||
'velocity_smoother',
|
||
'collision_monitor',
|
||
]
|
||
|
||
# map_server 发的 /map 是 **latched**(TRANSIENT_LOCAL)。
|
||
# 订阅端必须也是 TRANSIENT_LOCAL,否则 QoS 不兼容,一条都收不到 —— 最容易误判的一条。
|
||
MAP_QOS = QoSProfile(
|
||
depth=1,
|
||
history=HistoryPolicy.KEEP_LAST,
|
||
reliability=ReliabilityPolicy.RELIABLE,
|
||
durability=DurabilityPolicy.TRANSIENT_LOCAL,
|
||
)
|
||
# 传感器数据:仿真里都是 BEST_EFFORT
|
||
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,探针也必须一致,否则时间戳比较会出错
|
||
node = Node('check_stack',
|
||
parameter_overrides=[Parameter('use_sim_time',
|
||
Parameter.Type.BOOL, True)])
|
||
problems = []
|
||
|
||
def active(name):
|
||
cli = node.create_client(GetState, f'/{name}/get_state')
|
||
if not cli.wait_for_service(timeout_sec=3.0):
|
||
return None, '服务不存在'
|
||
fut = cli.call_async(GetState.Request())
|
||
rclpy.spin_until_future_complete(node, fut, timeout_sec=5.0)
|
||
if not fut.done() or fut.result() is None:
|
||
return None, '调用超时'
|
||
return fut.result().current_state, None
|
||
|
||
# ---------- 1. 生命周期 ----------
|
||
print('=== 1. 生命周期状态 ===')
|
||
for name in EXPECTED_ACTIVE:
|
||
st, err = active(name)
|
||
if st is None:
|
||
print(' %-20s ❌ %s' % (name, err))
|
||
problems.append(f'{name} 不可达({err})')
|
||
elif st.id == State.PRIMARY_STATE_ACTIVE:
|
||
print(' %-20s ✅ ACTIVE' % name)
|
||
else:
|
||
print(' %-20s ⚠️ %s' % (name, st.label))
|
||
problems.append(f'{name} 是 {st.label},不是 ACTIVE')
|
||
|
||
# ---------- 2. 话题有没有数据 ----------
|
||
print('\n=== 2. 话题数据(各收 1 条,最多 8 秒)===')
|
||
seen = {}
|
||
|
||
def waiter(key):
|
||
def cb(_msg):
|
||
seen[key] = seen.get(key, 0) + 1
|
||
return cb
|
||
|
||
node.create_subscription(PointCloud2, '/scan/points', waiter('scan/points'), SENSOR_QOS)
|
||
node.create_subscription(PointCloud2, '/scan/points_filtered',
|
||
waiter('scan/points_filtered'), SENSOR_QOS)
|
||
node.create_subscription(LaserScan, '/scan', waiter('scan'), SENSOR_QOS)
|
||
node.create_subscription(Odometry, '/odom', waiter('odom'), 10)
|
||
node.create_subscription(OccupancyGrid, '/map', waiter('map'), MAP_QOS)
|
||
|
||
deadline = time.time() + 8.0
|
||
while time.time() < deadline and len(seen) < 5:
|
||
rclpy.spin_once(node, timeout_sec=0.2)
|
||
|
||
for key in ('map', 'odom', 'scan', 'scan/points', 'scan/points_filtered'):
|
||
ok = key in seen
|
||
note = '(latched,订阅端 QoS 必须 TRANSIENT_LOCAL)' if key == 'map' else ''
|
||
print(' /%-22s %s %s' % (key, '✅ 有数据' if ok else '❌ 没收到', note))
|
||
if not ok:
|
||
problems.append(f'话题 /{key} 没有数据')
|
||
|
||
# ---------- 3. TF 链 ----------
|
||
print('\n=== 3. TF 链 ===')
|
||
buf = Buffer()
|
||
TransformListener(buf, node)
|
||
|
||
deadline = time.time() + 8.0
|
||
while time.time() < deadline:
|
||
rclpy.spin_once(node, timeout_sec=0.2)
|
||
|
||
for target, source in (('map', 'odom'), ('odom', 'base_link'),
|
||
('map', 'base_link')):
|
||
got = None
|
||
deadline = time.time() + 5.0
|
||
while time.time() < deadline:
|
||
rclpy.spin_once(node, timeout_sec=0.1)
|
||
try:
|
||
got = buf.lookup_transform(target, source, rclpy.time.Time(),
|
||
Duration(seconds=0.5))
|
||
break
|
||
except Exception:
|
||
pass
|
||
if got is None:
|
||
print(' %-18s ❌ 不存在' % f'{target} -> {source}')
|
||
problems.append(f'TF {target}->{source} 不存在')
|
||
else:
|
||
t = got.transform.translation
|
||
print(' %-18s ✅ (%.3f, %.3f, %.3f)'
|
||
% (f'{target} -> {source}', t.x, t.y, t.z))
|
||
|
||
if hasattr(buf, 'all_frames_as_yaml'):
|
||
print('\n TF 里出现过的 frame:')
|
||
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:
|
||
print(' ❌ 有 %d 个问题:' % len(problems))
|
||
for p in problems:
|
||
print(' · ' + p)
|
||
rclpy.shutdown()
|
||
return 1
|
||
print(' ✅ 全栈正常,可以发导航目标')
|
||
rclpy.shutdown()
|
||
return 0
|
||
|
||
|
||
if __name__ == '__main__':
|
||
sys.exit(main())
|