Files

299 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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
import project_env
# 期望处于 ACTIVE 的节点(缺了哪个,导航就会缺一块能力)
#
# ⚠️ amcl 必须在这个列表里:它不发 /map,但 **map_server 的激活与否看不出定位好坏**。
# 曾经漏掉它,结果 map_server 卡在 inactive、amcl 压根没配起来,而这个脚本
# 只报了 7 个节点的状态 —— 一眼看不出问题其实出在定位那一组。
EXPECTED_ACTIVE = [
'map_server',
'controller_server',
'planner_server',
'smoother_server',
'bt_navigator',
'behavior_server',
'waypoint_follower',
'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) ]:
[-5.000000 3.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):
"""Read the model pose from Gazebo in the simulation partition."""
gz = project_env.find_gz_bin()
env_partition = os.environ.get('GZ_PARTITION') or 'sentry'
try:
result = project_env.run_gz(
gz, 'model', '-m', model_name, '-p', timeout=10,
partition=env_partition)
except (OSError, subprocess.TimeoutExpired):
return None
return parse_gz_pose(result.stdout) if result.returncode == 0 else None
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
# Give DDS discovery a chance before choosing the expected localization branch.
for _ in range(10):
rclpy.spin_once(node, timeout_sec=0.1)
names_now = set(node.get_node_names())
expected_active = EXPECTED_ACTIVE + (['amcl'] if 'amcl' in names_now else [])
# ---------- 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')
names_now = set(node.get_node_names())
if 'field_localization' in names_now and 'amcl' in names_now:
problems.append('LIO 与 AMCL 同时运行;检查 map->odom 发布者互斥')
elif 'amcl' not in names_now and 'field_localization' not in names_now:
problems.append('LIO / AMCL 定位器均未发现')
# ---------- 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 = {}
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(LaserScan, '/scan2d', waiter('scan2d'), 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) < 6:
rclpy.spin_once(node, timeout_sec=0.2)
for key in ('map', 'odom', 'scan', 'scan/points', 'scan/points_filtered', 'scan2d'):
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. 定位真值对照 ===')
try:
truth = gz_model_pose('sentry')
except project_env.ProbeError as error:
truth = None
if os.environ.get('GZ_BIN'):
problems.append(str(error))
else:
print(f' ⚠️ {error}')
tf_pos = None
try:
got = buf.lookup_transform('map', 'base_link', rclpy.time.Time(),
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') or 'sentry'))
else:
gx, gy = truth[0], truth[1]
print(' [真值] Gazebo 世界坐标 (%.3f, %.3f)' % (gx, gy))
print(' 场地坐标 (map=field) (%.3f, %.3f)' % (gx, gy))
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 = '定位与 Gazebo 独立真值存在偏差;检查定位状态与传感器时间同步'
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())