feat: AMCL 定位接入、场地定位工具与文档更新
This commit is contained in:
1 parent
0c6b49e276
commit
0e4e4c6e18
45 files changed
+3173
-151
No files matched your search
+210
-48
@@ -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())
|
||||
Reference in new issue
Block a user