#!/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'', f'', ] # 网格 step = 0.5 g = math.floor(x0 / step) * step while g <= x1: lines.append(f'') lines.append(f'{g:.1f}') g += step g = math.floor(y0 / step) * step while g <= y1: lines.append(f'') lines.append(f'{g:.1f}') g += step # 轨迹 lines.append(f'') # 起点/终点 lines.append(f'') lines.append(f'起点') lines.append(f'') lines.append(f'终点') # 终点朝向箭头 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'') lines.append(f'' f'哨兵方形行驶轨迹(边长 {SIDE} m,速度 {LINEAR} m/s,转向 {ANGULAR} rad/s)') lines.append('') 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()