初始化:RMUL 2027 哨兵导航仿真工程
- Gazebo Sim (Jetty 10.6) + ROS 2 Lyrical + Nav2 全栈 - 整车模型:URDF/SDF + 减面网格(SolidWorks 装配体实测尺寸) - 场地:RMUL 2027 官方包(2D 栅格地图 + 3D 场地模型),放在 field/ - sentry_nav C++ 包:self_filter 点云自滤 / patrol 航点巡逻 - 文档:README(含本机开发环境实测)、MID-360 接入说明 已排除:build/ install/ log/ 缓存目录,以及 115 MB 的原始高模 (仿真实际用的是 meshes/base.stl 减面版,约 25.7 万面)
This commit is contained in:
1 parent
ed31ccc39f
commit
f7412ec369
142 files changed
+58958
-2
No files matched your search
@@ -0,0 +1,40 @@
|
||||
# tools/
|
||||
|
||||
模型转换、调试、演示用的小工具(都是独立脚本,不参与 colcon 构建)。
|
||||
|
||||
## 模型相关
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `build_vehicle.py` | **整车装配体 STL → 仿真网格 + 布局 json**(主力工具) |
|
||||
| `decimate.py` | 顶点聚类减面(纯 numpy,不依赖 MeshLab/Blender) |
|
||||
| `gen_sdf.sh` | URDF(xacro) → Gazebo 的 `models/sentry/model.sdf` |
|
||||
| `build_meshes.py` | 旧版:只处理「底盘」导出(已被 `build_vehicle.py` 取代) |
|
||||
| `build_gimbal.py` | 旧版:只处理「云台」导出(已被取代) |
|
||||
|
||||
## 演示 / 测试
|
||||
|
||||
| 脚本 | 用途 |
|
||||
|---|---|
|
||||
| `demo.py` | 前进 → 转向 → 再前进,并打印雷达和里程计 |
|
||||
| `drive_demo.py` | 走正方形并生成 SVG 轨迹图(`generated/drive_trajectory.svg`) |
|
||||
| `nav_client.py` | 发 Nav2 目标点,打印反馈/结果/TF |
|
||||
| `send_goal.py` | 用 `/goal_pose` 话题发目标 |
|
||||
| `scan_probe.py` | 检查雷达质量(有效点、最近/最远距离) |
|
||||
| `probe_all.py` | 检查 `/clock /odom /scan /tf` 有没有数据 |
|
||||
| `probe_cmd.py` / `probe_cmd2.py` / `cmd_probe_all.py` | 统计各级 `/cmd_vel` 消息数 |
|
||||
| `probe_sub.py` | 最小订阅示例 |
|
||||
|
||||
## 典型用法
|
||||
|
||||
```bash
|
||||
# 机械给了新装配体
|
||||
python3 tools/build_vehicle.py --src "/run/media/mzxiang/CPBA_X64FRE/装配车" --out src/sentry_sim/meshes/full
|
||||
python3 tools/decimate.py src/sentry_sim/meshes/full/base.stl src/sentry_sim/meshes/base.stl --grid 0.0025
|
||||
|
||||
# 演示
|
||||
python3 tools/drive_demo.py 1.0
|
||||
python3 tools/scan_probe.py
|
||||
```
|
||||
|
||||
> 这些脚本按「单次运行」写的:需要先按根目录 README 把仿真跑起来,再在另一个终端执行。
|
||||
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 SolidWorks 导出的「云台」STL 转成仿真用网格。
|
||||
|
||||
与底盘的关键差异:
|
||||
* 底盘导出:Y 轴向上(地面在 Y 最小端)
|
||||
* 云台导出:Y 轴向下(安装板 yaw板/底部固定板 在 Y 最大端,相机/枪管在 Y 最小端)
|
||||
所以这里用 ros_z = -(sw_y - mount_y) 把模型翻正,并翻转一个水平轴保持右手系
|
||||
(det=+1,避免镜像)。
|
||||
|
||||
输出 meshes/gimbal.stl:原点在「安装面 + yaw 轴」上,模型向 +Z 生长。
|
||||
|
||||
用法:
|
||||
python3 tools/build_gimbal.py --src "/run/media/.../云台" --out src/sentry_sim/meshes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALE = 0.001
|
||||
|
||||
# 需要剔除的异常件:一个在别处(X≈388),一个是 30 米量级的坏面片
|
||||
EXCLUDE = ('弹仓底B', '弹仓前1')
|
||||
|
||||
# 云台自身的关键点(SW 坐标,毫米):yaw 轴 + 安装面高度
|
||||
YAW_AXIS_X = 30900.0
|
||||
YAW_AXIS_Z = 6500.0
|
||||
MOUNT_Y = 5769.4 # 安装面(yaw板 顶面)
|
||||
|
||||
# SW(mm, Y 向下) -> ROS(m, Z 向上),右手系(det=+1)
|
||||
# ros_x = -(sw_z - YAW_AXIS_Z)
|
||||
# ros_y = (sw_x - YAW_AXIS_X)
|
||||
# ros_z = -(sw_y - MOUNT_Y)
|
||||
ROT = np.array([[0.0, 0.0, -1.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, -1.0, 0.0]])
|
||||
ORIGIN_SW = np.array([YAW_AXIS_X, MOUNT_Y, YAW_AXIS_Z])
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 != size:
|
||||
return None
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
return rec['v'].reshape(-1, 3, 3).astype(np.float64)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim gimbal'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--src', required=True)
|
||||
ap.add_argument('--out', required=True)
|
||||
args = ap.parse_args()
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
|
||||
glob.glob(os.path.join(args.src, '*.stl')))
|
||||
if not files:
|
||||
sys.exit(f'没找到 STL:{args.src}')
|
||||
|
||||
used, skipped, parts = [], [], []
|
||||
for p in files:
|
||||
base = os.path.basename(p)
|
||||
if any(x in base for x in EXCLUDE):
|
||||
skipped.append(base)
|
||||
continue
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
skipped.append(base + '(无法解析)')
|
||||
continue
|
||||
used.append(t)
|
||||
parts.append(base)
|
||||
|
||||
tris = np.concatenate(used)
|
||||
# 变换到 ROS 系(米),原点在安装面 + yaw 轴
|
||||
tris = ((tris.reshape(-1, 3) - ORIGIN_SW) @ ROT.T) * SCALE
|
||||
tris = tris.reshape(-1, 3, 3)
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
out = os.path.join(args.out, 'gimbal.stl')
|
||||
write_stl(out, tris)
|
||||
|
||||
v = tris.reshape(-1, 3)
|
||||
mn, mx = v.min(axis=0), v.max(axis=0)
|
||||
meta = {
|
||||
'source_dir': os.path.abspath(args.src),
|
||||
'parts_used': len(parts),
|
||||
'parts_skipped': skipped,
|
||||
'triangles': int(len(tris)),
|
||||
'ros_bbox_min_m': [round(float(x), 4) for x in mn],
|
||||
'ros_bbox_max_m': [round(float(x), 4) for x in mx],
|
||||
'ros_bbox_size_m': [round(float(mx[i] - mn[i]), 4) for i in range(3)
|
||||
],
|
||||
'origin_sw_mm': [float(x) for x in ORIGIN_SW],
|
||||
'note': '云台导出 Y 轴朝下,已翻正(det=+1,无镜像);原点=安装面+yaw轴',
|
||||
}
|
||||
with open(os.path.join(args.out, 'gimbal_transform.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f'使用 {len(parts)} 个零件,跳过 {len(skipped)} 个:')
|
||||
for s in skipped:
|
||||
print(f' 跳过: {s}')
|
||||
print(f'\ngimbal.stl: {len(tris):,} 面')
|
||||
print(f'ROS 包围盒 min={np.round(mn, 3)} max={np.round(mx, 3)}')
|
||||
print(f'尺寸 (m) = {np.round(mx - mn, 3)}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把 SolidWorks 导出的底盘 STL 装配体转成仿真可用的网格。
|
||||
|
||||
输入:SW 按零件导出的二进制 STL(装配体坐标系,单位 mm,Y 轴向上)
|
||||
输出:
|
||||
meshes/base.stl 底盘(除轮子本体外的全部零件),已转到 ROS 坐标系并居中
|
||||
meshes/wheel.stl 单个麦轮,已转到 ROS 坐标系并把原点放在轮子中心
|
||||
meshes/transform.json 坐标变换与四个轮子的关节位置(供 URDF 与人工核对)
|
||||
|
||||
坐标约定(REP-103:X 前、Y 左、Z 上):
|
||||
p_ros = R @ (p_sw - C) / 1000 R = [[0,0,1],[1,0,0],[0,1,0]]
|
||||
即 ROS_x = SW_z、ROS_y = SW_x、ROS_z = SW_y(把 SW 的 Z 前 / X 左 / Y 上 换成 ROS 约定)
|
||||
|
||||
用法:
|
||||
python3 tools/build_meshes.py --src "/run/media/.../底盘" --out src/sentry_sim/meshes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
# SW 装配体坐标 -> ROS(REP-103)
|
||||
ROT = np.array([[0.0, 0.0, 1.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0]])
|
||||
SCALE = 0.001 # mm -> m
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
"""读二进制/ASCII STL,返回 (N,3,3) 的三角面片数组(float32,SW 原始单位)。"""
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
if len(head) < 84:
|
||||
return None
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 == size: # 二进制
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
|
||||
('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
tris = rec['v'].reshape(-1, 3, 3).astype(np.float64)
|
||||
return tris
|
||||
# ASCII 兜底
|
||||
verts = []
|
||||
with open(path, 'r', errors='ignore') as f:
|
||||
for line in f:
|
||||
s = line.strip()
|
||||
if s.startswith('vertex'):
|
||||
verts.append([float(x) for x in s.split()[1:4]])
|
||||
if not verts or len(verts) % 3:
|
||||
return None
|
||||
return np.asarray(verts, dtype=np.float64).reshape(-1, 3, 3)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
"""写二进制 STL。"""
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim converted'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def to_ros(tris, center):
|
||||
"""SW 装配体坐标 -> ROS 坐标(米),并平移到 center 为原点。"""
|
||||
return ((tris - center) @ ROT.T) * SCALE
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--src', required=True, help='SW 导出的 STL 目录')
|
||||
ap.add_argument('--out', required=True, help='输出 meshes 目录')
|
||||
args = ap.parse_args()
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
|
||||
glob.glob(os.path.join(args.src, '*.stl')))
|
||||
if not files:
|
||||
sys.exit(f'没找到 STL:{args.src}')
|
||||
print(f'共 {len(files)} 个 STL')
|
||||
|
||||
# ---- 第 1 遍:整体包围盒,确定原点 C ----
|
||||
gmin = np.full(3, np.inf)
|
||||
gmax = np.full(3, -np.inf)
|
||||
for p in files:
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
print(f' 跳过(无法解析): {os.path.basename(p)}')
|
||||
continue
|
||||
v = t.reshape(-1, 3)
|
||||
gmin = np.minimum(gmin, v.min(axis=0))
|
||||
gmax = np.maximum(gmax, v.max(axis=0))
|
||||
|
||||
# 原点:X/Z 取包围盒中心,Y 取“地面”(最低点)
|
||||
center_sw = np.array([(gmin[0] + gmax[0]) / 2.0,
|
||||
gmin[1],
|
||||
(gmin[2] + gmax[2]) / 2.0])
|
||||
print(f'SW 包围盒 min={np.round(gmin, 1)} max={np.round(gmax, 1)}')
|
||||
print(f'原点 C (mm) = {np.round(center_sw, 2)}')
|
||||
|
||||
# ---- 第 2 遍:合并 ----
|
||||
# 只认「轮系-N 装配体1-1」,排除悬挂摇臂(文件名里也含“装配体1-1”)
|
||||
wheel_files = [p for p in files
|
||||
if '装配体1-1' in os.path.basename(p)
|
||||
and '轮系-' in os.path.basename(p)]
|
||||
base_files = [p for p in files if p not in wheel_files]
|
||||
print(f'轮子本体 {len(wheel_files)} 个;底盘 {len(base_files)} 个')
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
base_tris = []
|
||||
for p in base_files:
|
||||
t = read_stl(p)
|
||||
if t is not None:
|
||||
base_tris.append(to_ros(t, center_sw))
|
||||
base = np.concatenate(base_tris)
|
||||
write_stl(os.path.join(args.out, 'base.stl'), base)
|
||||
print(f'base.stl: {len(base):,} 面')
|
||||
|
||||
wheels = {}
|
||||
for p in wheel_files:
|
||||
t = read_stl(p)
|
||||
if t is None:
|
||||
continue
|
||||
v = t.reshape(-1, 3)
|
||||
wheel_center_sw = (v.min(axis=0) + v.max(axis=0)) / 2.0
|
||||
wheels[os.path.basename(p)] = wheel_center_sw
|
||||
if 'wheel_raw' not in wheels:
|
||||
# 以第一个轮子为模板,把原点放在轮子中心
|
||||
ros = to_ros(t, center_sw) # 先到 ROS 系、底盘中心为原点
|
||||
wc = (to_ros(t, wheel_center_sw)).reshape(-1, 3).mean(axis=0) * 0 # 占位
|
||||
# 轮子中心在 ROS 系下的位置
|
||||
wc_ros = ((wheel_center_sw - center_sw) @ ROT.T) * SCALE
|
||||
ros_centered = ros - wc_ros
|
||||
write_stl(os.path.join(args.out, 'wheel.stl'), ros_centered)
|
||||
print(f'wheel.stl: {len(ros_centered):,} 面(模板:{os.path.basename(p)})')
|
||||
|
||||
# ---- 轮子关节位置(ROS,米)----
|
||||
joints = {}
|
||||
for name, c_sw in wheels.items():
|
||||
# 轮系-N 装配体1-1.STL -> N
|
||||
idx = name.split('轮系-')[-1].split()[0]
|
||||
c_ros = ((c_sw - center_sw) @ ROT.T) * SCALE
|
||||
joints[f'wheel_{idx}'] = [round(float(x), 6) for x in c_ros]
|
||||
|
||||
meta = {
|
||||
'source_dir': os.path.abspath(args.src),
|
||||
'sw_bbox_min_mm': [round(float(x), 2) for x in gmin],
|
||||
'sw_bbox_max_mm': [round(float(x), 2) for x in gmax],
|
||||
'origin_sw_mm': [round(float(x), 2) for x in center_sw],
|
||||
'ros_bbox_size_m': [round(float(x) * SCALE, 4) for x in (gmax - gmin)],
|
||||
'wheels_ros_m': joints,
|
||||
'wheel_radius_m': 0.0762,
|
||||
'note': 'ROS_x=SW_z, ROS_y=SW_x, ROS_z=SW_y;单位 mm->m',
|
||||
}
|
||||
with open(os.path.join(args.out, 'transform.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
print('\n轮子中心(ROS,米):')
|
||||
for k, v in joints.items():
|
||||
print(f' {k}: {v}')
|
||||
print(f'\n车体尺寸(ROS,米): {meta["ros_bbox_size_m"]}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,295 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从「整车装配体」STL 导出构建仿真网格(底盘 / 4 轮 / 云台),并输出布局参数。
|
||||
|
||||
相比之前分别用「底盘」「云台」两套导出,整车装配体的优势:所有零件在同一坐标系里,
|
||||
云台的位置和朝向可以直接量出来,不需要推测。
|
||||
|
||||
坐标约定(本装配体):Y 轴向上(地面 = 轮心Y - 轮半径)、X 横向、Z 前后。
|
||||
输出到 ROS/REP-103:ROS_x=SW_z、ROS_y=SW_x、ROS_z=SW_y(与之前一致)。
|
||||
|
||||
用法:
|
||||
python3 tools/build_vehicle.py --src "/run/media/.../装配车" --out src/sentry_sim/meshes
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
|
||||
SCALE = 0.001
|
||||
|
||||
# 车头方向:装配体里「相机支架/发射核心板」在 SW +Z 侧、「弹仓后」在 -Z 侧,
|
||||
# 因此车头 = +SW_z,映射到 ROS 后即 +X。无需翻转(曾经试过 180°,方向反而反了)。
|
||||
FLIP_180 = False
|
||||
# SW(装配体) -> ROS:ROS_x=SW_z、ROS_y=SW_x、ROS_z=SW_y(Y 向上转成 Z 向上)
|
||||
ROT = np.array([[0.0, 0.0, 1.0],
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0]])
|
||||
|
||||
# 云台(会绕 yaw 轴转)的零件名关键字
|
||||
GIMBAL_KEYS = (
|
||||
'yaw板', 'pitch', '小云台装配体', '基座装配', '八爪拨盘', '拨盘',
|
||||
'云台', '鹅颈', '枪管', '相机', '发射核心', '弹链', '弹仓',
|
||||
'24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ',
|
||||
'电机带轮', '拨盘带轮', 'z21胀紧', 'Z21胀紧',
|
||||
)
|
||||
# 轮子本体(会绕自身轴转)
|
||||
WHEEL_MARK = '轮系-{} 装配体1-1'
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 != size:
|
||||
return None
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
|
||||
('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
return rec['v'].reshape(-1, 3, 3).astype(np.float64)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim vehicle'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def classify(name):
|
||||
"""返回 'wheelN' / 'gimbal' / 'base'。"""
|
||||
for i in (1, 2, 3, 4):
|
||||
if WHEEL_MARK.format(i) in name:
|
||||
return f'wheel{i}'
|
||||
for key in GIMBAL_KEYS:
|
||||
if key in name:
|
||||
return 'gimbal'
|
||||
return 'base'
|
||||
|
||||
|
||||
def to_ros(tris, center_sw):
|
||||
"""SW 装配体坐标 -> ROS 坐标(米)。
|
||||
|
||||
p_ros = ROT @ (p_sw - center) * 0.001
|
||||
FLIP_180 为 True 时再绕 ROS 的 Z 轴转 180°(x、y 同时取反,仍是右手系)。
|
||||
当前为 False:实测车头(相机/枪口侧)本来就朝 +SW_z,即映射后朝 +X。
|
||||
"""
|
||||
out = ((np.asarray(tris, dtype=np.float64).reshape(-1, 3) - center_sw) @ ROT.T) * SCALE
|
||||
if FLIP_180:
|
||||
out[:, 0] *= -1.0
|
||||
out[:, 1] *= -1.0
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--src', required=True)
|
||||
ap.add_argument('--out', required=True)
|
||||
ap.add_argument('--dry-run', action='store_true', help='只打印分类结果,不写文件')
|
||||
ap.add_argument('--split-gimbal', action='store_true',
|
||||
help='把云台拆成独立 link(需要准确零件清单;默认整车刚体)')
|
||||
args = ap.parse_args()
|
||||
|
||||
files = sorted(glob.glob(os.path.join(args.src, '*.STL')) +
|
||||
glob.glob(os.path.join(args.src, '*.stl')))
|
||||
if not files:
|
||||
sys.exit(f'没找到 STL:{args.src}')
|
||||
|
||||
groups = {'base': [], 'gimbal': [], 'wheel1': [], 'wheel2': [],
|
||||
'wheel3': [], 'wheel4': []}
|
||||
skipped = []
|
||||
|
||||
# ---- 第一遍:读所有零件,找出主簇(装配体可能被放在离原点很远的位置)----
|
||||
loaded = []
|
||||
for path in files:
|
||||
name = os.path.basename(path)
|
||||
tris = read_stl(path)
|
||||
if tris is None:
|
||||
skipped.append((name, '无法解析'))
|
||||
continue
|
||||
v = tris.reshape(-1, 3)
|
||||
lo, hi = v.min(axis=0), v.max(axis=0)
|
||||
loaded.append((name, tris, lo, hi))
|
||||
|
||||
ok = [x for x in loaded if max(x[3] - x[2]) <= 2000] # 尺寸异常(30 米量级)的直接剔除
|
||||
for name, _t, _lo, _hi in loaded:
|
||||
if max(_hi - _lo) > 2000:
|
||||
skipped.append((name, f'异常几何 尺寸{np.round(_hi-_lo,0)}'))
|
||||
if not ok:
|
||||
sys.exit('没有可用零件')
|
||||
cen = np.array([(x[2] + x[3]) / 2 for x in ok])
|
||||
med = np.median(cen, axis=0)
|
||||
all_min = np.full(3, np.inf)
|
||||
all_max = np.full(3, -np.inf)
|
||||
for name, tris, lo, hi in ok:
|
||||
c = (lo + hi) / 2
|
||||
# 离主簇太远(>3m)的当作放错了的零件
|
||||
if max(abs(c[0] - med[0]), abs(c[1] - med[1]), abs(c[2] - med[2])) > 3000:
|
||||
skipped.append((name, f'离主簇太远 中心{np.round(c,0)}'))
|
||||
continue
|
||||
all_min = np.minimum(all_min, lo)
|
||||
all_max = np.maximum(all_max, hi)
|
||||
groups[classify(name)].append(tris)
|
||||
|
||||
wc = {}
|
||||
for i in (1, 2, 3, 4):
|
||||
if groups[f'wheel{i}']:
|
||||
v = np.concatenate(groups[f'wheel{i}']).reshape(-1, 3)
|
||||
wc[f'wheel{i}'] = (v.min(axis=0) + v.max(axis=0)) / 2
|
||||
|
||||
print(f'总零件 {len(files)},跳过 {len(skipped)}')
|
||||
for n, why in skipped:
|
||||
print(f' 跳过 {n[:60]} ({why})')
|
||||
for g, arrs in groups.items():
|
||||
if not arrs:
|
||||
continue
|
||||
v = np.concatenate(arrs).reshape(-1, 3)
|
||||
lo, hi = v.min(axis=0), v.max(axis=0)
|
||||
print(f' {g:8} 零件 {len(arrs):3} 件 SW bbox min={np.round(lo,1)} max={np.round(hi,1)} 尺寸={np.round(hi-lo,1)}')
|
||||
|
||||
ground_y = all_min[1]
|
||||
print(f'\n地面 Y={ground_y:.1f} mm;整车 bbox {np.round(all_max-all_min,1)} mm')
|
||||
|
||||
# 原点:横向/前后取整车中心,高度取地面
|
||||
origin_sw = np.array([(all_min[0] + all_max[0]) / 2,
|
||||
ground_y,
|
||||
(all_min[2] + all_max[2]) / 2])
|
||||
|
||||
# yaw 轴:用 GM6020 云台电机的中心(在 gimbal 组内找)
|
||||
yaw_xz = None
|
||||
for path in files:
|
||||
if 'GM6020' in os.path.basename(path):
|
||||
tris = read_stl(path)
|
||||
if tris is None:
|
||||
continue
|
||||
v = tris.reshape(-1, 3)
|
||||
c = (v.min(axis=0) + v.max(axis=0)) / 2
|
||||
yaw_xz = (c[0], c[2])
|
||||
break
|
||||
|
||||
wheels_ros = {}
|
||||
for k, c_sw in wc.items():
|
||||
pts = to_ros(np.array([c_sw]), origin_sw).reshape(-1, 3)[0]
|
||||
rel = pts
|
||||
wheels_ros[k] = [round(float(x), 5) for x in rel]
|
||||
print(f' {k} SW中心={np.round(c_sw,1)} -> ROS {wheels_ros[k]}')
|
||||
|
||||
meta = {
|
||||
'source_dir': os.path.abspath(args.src),
|
||||
'origin_sw_mm': [round(float(x), 2) for x in origin_sw],
|
||||
'ground_sw_y_mm': round(float(ground_y), 2),
|
||||
'size_ros_m': [round(float(x) * SCALE, 4) for x in (all_max - all_min)],
|
||||
'wheels_ros_m': wheels_ros,
|
||||
}
|
||||
# MID-360 雷达位置(如果装配体里放了)
|
||||
mid_pts = []
|
||||
for path in files:
|
||||
if 'MID' in os.path.basename(path).upper() or 'mid-360' in os.path.basename(path):
|
||||
tris = read_stl(path)
|
||||
if tris is not None:
|
||||
mid_pts.append(tris.reshape(-1, 3))
|
||||
if mid_pts:
|
||||
mv = np.concatenate(mid_pts)
|
||||
mid_c = (mv.min(axis=0) + mv.max(axis=0)) / 2
|
||||
mid_ros = to_ros(np.array([mid_c]), origin_sw).reshape(-1, 3)[0]
|
||||
meta['mid360_ros_m'] = [round(float(x), 4) for x in mid_ros]
|
||||
W = mv.max(axis=0) - mv.min(axis=0)
|
||||
meta['mid360_size_m'] = [round(float(x) * SCALE, 4) for x in W]
|
||||
print(f' MID-360 SW中心={np.round(mid_c,1)} -> ROS {meta["mid360_ros_m"]} 尺寸(m)={meta["mid360_size_m"]}')
|
||||
|
||||
if yaw_xz:
|
||||
yaw_rel = np.array([yaw_xz[1], yaw_xz[0], 0.0]) # ROS_x=SW_z, ROS_y=SW_x
|
||||
yaw_rel = yaw_rel - np.array([origin_sw[2], origin_sw[0], 0.0])
|
||||
meta['yaw_axis_ros_xy_m'] = [round(float(yaw_rel[0]) * SCALE, 5),
|
||||
round(float(yaw_rel[1]) * SCALE, 5)]
|
||||
print(f' yaw 轴 ROS(x,y) = {meta["yaw_axis_ros_xy_m"]}')
|
||||
|
||||
if args.dry_run:
|
||||
print('\n[dry-run] 未写文件')
|
||||
return
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
|
||||
# 底盘:原点在整车原点;默认把云台并进来(导航阶段刚体即可,避免拆分错误)
|
||||
base_parts = list(groups['base'])
|
||||
if not args.split_gimbal:
|
||||
base_parts += list(groups['gimbal'])
|
||||
print(' [rigid] 云台零件并入底盘(不再单独出 gimbal.stl)')
|
||||
base = np.concatenate(base_parts)
|
||||
write_stl(os.path.join(args.out, 'base.stl'), to_ros(base, origin_sw).reshape(-1, 3, 3))
|
||||
print(f'\nbase.stl {len(base):,} 面')
|
||||
|
||||
# 轮子:以第一个轮子的中心为原点(四个轮子几何相同,尺寸一致已核对)
|
||||
w1 = np.concatenate(groups['wheel1'])
|
||||
write_stl(os.path.join(args.out, 'wheel.stl'), to_ros(w1, wc['wheel1']).reshape(-1, 3, 3))
|
||||
print(f'wheel.stl {len(w1):,} 面')
|
||||
|
||||
if not args.split_gimbal:
|
||||
with open(os.path.join(args.out, 'vehicle_layout.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
print(f'\n布局写入 {os.path.join(args.out, "vehicle_layout.json")}')
|
||||
return
|
||||
|
||||
# 云台:原点在 yaw 轴 + 安装面(取云台组最低 Y)
|
||||
gim = np.concatenate(groups['gimbal'])
|
||||
gv = gim.reshape(-1, 3)
|
||||
g_min, g_max = gv.min(axis=0), gv.max(axis=0)
|
||||
mount_y = g_min[1]
|
||||
# MID-360 雷达位置(如果装配体里放了)
|
||||
mid_pts = []
|
||||
for path in files:
|
||||
if 'MID' in os.path.basename(path).upper() or 'mid-360' in os.path.basename(path):
|
||||
tris = read_stl(path)
|
||||
if tris is not None:
|
||||
mid_pts.append(tris.reshape(-1, 3))
|
||||
if mid_pts:
|
||||
mv = np.concatenate(mid_pts)
|
||||
mid_c = (mv.min(axis=0) + mv.max(axis=0)) / 2
|
||||
mid_ros = to_ros(np.array([mid_c]), origin_sw).reshape(-1, 3)[0]
|
||||
meta['mid360_ros_m'] = [round(float(x), 4) for x in mid_ros]
|
||||
W = mv.max(axis=0) - mv.min(axis=0)
|
||||
meta['mid360_size_m'] = [round(float(x) * SCALE, 4) for x in W]
|
||||
print(f' MID-360 SW中心={np.round(mid_c,1)} -> ROS {meta["mid360_ros_m"]} 尺寸(m)={meta["mid360_size_m"]}')
|
||||
|
||||
if yaw_xz:
|
||||
g_center_sw = np.array([yaw_xz[0], mount_y, yaw_xz[1]])
|
||||
else:
|
||||
g_center_sw = np.array([(g_min[0] + g_max[0]) / 2, mount_y,
|
||||
(g_min[2] + g_max[2]) / 2])
|
||||
gim_ros = to_ros(gim, g_center_sw).reshape(-1, 3, 3)
|
||||
write_stl(os.path.join(args.out, 'gimbal.stl'), gim_ros)
|
||||
gv_ros = gim_ros.reshape(-1, 3)
|
||||
print(f'gimbal.stl {len(gim):,} 面 ROS bbox min={np.round(gv_ros.min(axis=0),3)} max={np.round(gv_ros.max(axis=0),3)}')
|
||||
meta['gimbal_origin_sw_mm'] = [round(float(x), 2) for x in g_center_sw]
|
||||
meta['gimbal_bbox_ros_m'] = [
|
||||
[round(float(x), 4) for x in gv_ros.min(axis=0)],
|
||||
[round(float(x), 4) for x in gv_ros.max(axis=0)]]
|
||||
meta['gimbal_joint_origin_ros_m'] = [
|
||||
round(float((g_center_sw[2] - origin_sw[2]) * SCALE), 5),
|
||||
round(float((g_center_sw[0] - origin_sw[0]) * SCALE), 5),
|
||||
round(float((g_center_sw[1] - origin_sw[1]) * SCALE), 5)]
|
||||
|
||||
with open(os.path.join(args.out, 'vehicle_layout.json'), 'w') as f:
|
||||
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||
print(f'\n云台关节安装点(ROS 米): {meta["gimbal_joint_origin_ros_m"]}')
|
||||
print(f'布局写入 {os.path.join(args.out, "vehicle_layout.json")}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""对比自滤前后的点云:有没有把车身自身回波滤掉。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
from rclpy.qos import QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
QOS = QoSProfile(depth=5, reliability=QoSReliabilityPolicy.BEST_EFFORT)
|
||||
rclpy.init()
|
||||
node = Node('cloud_compare')
|
||||
got = {}
|
||||
node.create_subscription(PointCloud2, '/scan/points',
|
||||
lambda m: got.setdefault('raw', m), QOS)
|
||||
node.create_subscription(PointCloud2, '/scan/points_filtered',
|
||||
lambda m: got.setdefault('filtered', m), QOS)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 2:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
|
||||
def stats(msg):
|
||||
if msg is None:
|
||||
return None
|
||||
pts = [p for p in pc2.read_points(msg, field_names=('x', 'y', 'z'), skip_nans=True)]
|
||||
fin = [p for p in pts if all(abs(v) != float('inf') for v in p)]
|
||||
if not fin:
|
||||
return (0, 0.0, 0.0)
|
||||
d = [((p[0] ** 2 + p[1] ** 2) ** 0.5) for p in fin]
|
||||
return (len(fin), min(d), max(d))
|
||||
|
||||
|
||||
raw = stats(got.get('raw'))
|
||||
flt = stats(got.get('filtered'))
|
||||
print(f'原始 /scan/points : {raw[0]} 点, 距离 {raw[1]:.2f} ~ {raw[2]:.2f} m' if raw else '没收到原始点云')
|
||||
print(f'自滤 /scan/points_filtered : {flt[0]} 点, 距离 {flt[1]:.2f} ~ {flt[2]:.2f} m' if flt else '没收到自滤点云')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查 MID-360 3D 点云质量:点数、有效点、距离分布、可见的地面/围挡。"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
|
||||
try:
|
||||
import sensor_msgs_py.point_cloud2 as pc2
|
||||
except ImportError:
|
||||
pc2 = None
|
||||
|
||||
rclpy.init()
|
||||
node = Node('cloud_probe')
|
||||
got = {}
|
||||
node.create_subscription(PointCloud2, '/scan/points', lambda m: got.setdefault('c', m), 10)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and 'c' not in got:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
m = got.get('c')
|
||||
if m is None:
|
||||
print('没收到 /scan/points')
|
||||
else:
|
||||
print(f'frame={m.header.frame_id} 尺寸={m.width}x{m.height} point_step={m.point_step}')
|
||||
if pc2 is None:
|
||||
print('(没有 sensor_msgs_py,跳过解析)')
|
||||
else:
|
||||
pts = [p for p in pc2.read_points(m, field_names=('x', 'y', 'z'), skip_nans=True)]
|
||||
fin = [p for p in pts if all(math.isfinite(v) for v in p)]
|
||||
print(f'点总数={len(pts)} 有限点={len(fin)}')
|
||||
if fin:
|
||||
rng = [math.hypot(p[0], p[1]) for p in fin]
|
||||
zs = [p[2] for p in fin]
|
||||
print(f'水平距离: {min(rng):.2f} ~ {max(rng):.2f} m')
|
||||
print(f'高度范围: {min(zs):+.2f} ~ {max(zs):+.2f} m(传感器在 0.405,地面应在 -0.405 附近)')
|
||||
import collections
|
||||
h = collections.Counter(int(r / 2) * 2 for r in rng)
|
||||
print('距离直方图(每 2m):', dict(sorted(h.items())))
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""统计导航链路上各级速度话题的消息数。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist, TwistStamped
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
qos = QoSProfile(depth=10, reliability=QoSReliabilityPolicy.BEST_EFFORT)
|
||||
rclpy.init()
|
||||
node = Node('cmd_probe_all')
|
||||
counts = {}
|
||||
|
||||
|
||||
def make_cb(name):
|
||||
def cb(_msg):
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
return cb
|
||||
|
||||
|
||||
for t in ('/cmd_vel_nav', '/cmd_vel_smoothed', '/cmd_vel', '/model/sentry/cmd_vel'):
|
||||
node.create_subscription(Twist, t, make_cb(t), qos)
|
||||
node.create_subscription(TwistStamped, '/cmd_vel_nav', make_cb('/cmd_vel_nav[stamped]'), qos)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
for t in ('/cmd_vel_nav', '/cmd_vel_nav[stamped]', '/cmd_vel_smoothed', '/cmd_vel',
|
||||
'/model/sentry/cmd_vel'):
|
||||
print(f' {t:26} {counts.get(t, 0)}')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""STL 顶点聚类减面(不依赖 MeshLab/Blender,纯 numpy)。
|
||||
|
||||
原理:把顶点量化到边长 h 的网格,用网格中心代替原顶点,丢弃退化三角形。
|
||||
对「视觉用」网格足够:形状保持,面数可降一个数量级。
|
||||
|
||||
用法:
|
||||
python3 tools/decimate.py 输入.stl 输出.stl --grid 0.002
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import struct
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def read_stl(path):
|
||||
size = os.path.getsize(path)
|
||||
with open(path, 'rb') as f:
|
||||
head = f.read(84)
|
||||
n = struct.unpack('<I', head[80:84])[0]
|
||||
if 84 + n * 50 != size:
|
||||
raise ValueError(f'{path} 不是二进制 STL')
|
||||
f.seek(84)
|
||||
buf = f.read(n * 50)
|
||||
rec = np.frombuffer(buf, dtype=np.dtype([('n', '<3f4'),
|
||||
('v', '<9f4'),
|
||||
('a', '<u2')]))
|
||||
return rec['v'].reshape(-1, 3, 3).astype(np.float32)
|
||||
|
||||
|
||||
def write_stl(path, tris):
|
||||
n = len(tris)
|
||||
v0, v1, v2 = tris[:, 0], tris[:, 1], tris[:, 2]
|
||||
normals = np.cross(v1 - v0, v2 - v0)
|
||||
leng = np.linalg.norm(normals, axis=1)
|
||||
leng[leng == 0] = 1.0
|
||||
normals = normals / leng[:, None]
|
||||
rec = np.zeros(n, dtype=np.dtype([('n', '<3f4'), ('v', '<9f4'), ('a', '<u2')]))
|
||||
rec['n'] = normals
|
||||
rec['v'] = tris.reshape(n, 9)
|
||||
with open(path, 'wb') as f:
|
||||
f.write(b'sentry_sim decimated'.ljust(80, b' '))
|
||||
f.write(struct.pack('<I', n))
|
||||
f.write(rec.tobytes())
|
||||
|
||||
|
||||
def decimate(tris, grid):
|
||||
verts = tris.reshape(-1, 3)
|
||||
cells = np.floor(verts / grid).astype(np.int64)
|
||||
# 每个网格单元 -> 该单元内顶点的平均值
|
||||
_, inverse = np.unique(cells, axis=0, return_inverse=True)
|
||||
inverse = inverse.reshape(-1)
|
||||
ncell = inverse.max() + 1
|
||||
sums = np.zeros((ncell, 3), dtype=np.float64)
|
||||
np.add.at(sums, inverse, verts)
|
||||
counts = np.bincount(inverse, minlength=ncell)[:, None]
|
||||
centers = (sums / counts).astype(np.float32)
|
||||
|
||||
faces = inverse.reshape(-1, 3)
|
||||
# 去掉退化面(三个顶点落在同一/两个单元)
|
||||
keep = ((faces[:, 0] != faces[:, 1]) &
|
||||
(faces[:, 1] != faces[:, 2]) &
|
||||
(faces[:, 0] != faces[:, 2]))
|
||||
faces = faces[keep]
|
||||
return centers[faces]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('src')
|
||||
ap.add_argument('dst')
|
||||
ap.add_argument('--grid', type=float, default=0.002,
|
||||
help='网格边长(米),越大越省面、越粗糙')
|
||||
args = ap.parse_args()
|
||||
|
||||
tris = read_stl(args.src)
|
||||
print(f'输入 {len(tris):,} 面')
|
||||
out = decimate(tris, args.grid)
|
||||
print(f'输出 {len(out):,} 面(网格 {args.grid*1000:.1f} mm,压缩到 {len(out)/len(tris)*100:.1f}%)')
|
||||
write_stl(args.dst, out)
|
||||
print(f'已写入 {args.dst}({os.path.getsize(args.dst)/1e6:.1f} MB)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
"""演示脚本:驱动哨兵前进+转向,并打印雷达/里程计/AMCL 的真实数据。"""
|
||||
import math
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import LaserScan
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
rclpy.init()
|
||||
node = Node('demo_driver')
|
||||
pub = node.create_publisher(Twist, '/cmd_vel', 10)
|
||||
data = {'odom': None, 'scan': None}
|
||||
node.create_subscription(Odometry, '/odom', lambda m: data.__setitem__('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: data.__setitem__('scan', m), 10)
|
||||
tf = Buffer()
|
||||
TransformListener(tf, node)
|
||||
|
||||
|
||||
def spin(sec):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < sec:
|
||||
rclpy.spin_once(node, timeout_sec=0.1)
|
||||
|
||||
|
||||
def drive(lin, ang, sec, label):
|
||||
msg = Twist()
|
||||
msg.linear.x = lin
|
||||
msg.angular.z = ang
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < sec:
|
||||
pub.publish(msg)
|
||||
rclpy.spin_once(node, timeout_sec=0.05)
|
||||
pub.publish(Twist())
|
||||
p = data['odom'].pose.pose.position if data['odom'] else None
|
||||
yaw = 0.0
|
||||
if data['odom']:
|
||||
q = data['odom'].pose.pose.orientation
|
||||
yaw = math.degrees(2 * math.atan2(q.z, q.w))
|
||||
print(f' {label}: odom=({p.x:+.3f}, {p.y:+.3f}) 航向={yaw:+.1f}°' if p else f' {label}: 无 odom')
|
||||
|
||||
|
||||
spin(3)
|
||||
if data['scan']:
|
||||
finite = [r for r in data['scan'].ranges if r == r and r != float('inf')]
|
||||
print(f'[雷达] frame={data["scan"].header.frame_id} 线数={len(data["scan"].ranges)} '
|
||||
f'有效点={len(finite)} 最近={min(finite):.2f}m 最远={max(finite):.2f}m')
|
||||
else:
|
||||
print('[雷达] 无数据')
|
||||
|
||||
print('[驱动]')
|
||||
drive(0.5, 0.0, 3.0, '前进 0.5 m/s × 3s')
|
||||
drive(0.0, 0.8, 1.5, '原地转 0.8 rad/s × 1.5s')
|
||||
drive(0.3, 0.0, 2.0, '再前进 0.3 m/s × 2s')
|
||||
|
||||
for i in range(20):
|
||||
spin(0.2)
|
||||
try:
|
||||
tr = tf.lookup_transform('map', 'base_link', rclpy.time.Time())
|
||||
p = tr.transform.translation
|
||||
print(f'[AMCL] TF map->base_link: x={p.x:.3f} y={p.y:.3f}')
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'[AMCL] 查不到 TF: {exc}')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/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'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">',
|
||||
f'<rect width="{W}" height="{H}" fill="#11141a"/>',
|
||||
]
|
||||
# 网格
|
||||
step = 0.5
|
||||
g = math.floor(x0 / step) * step
|
||||
while g <= x1:
|
||||
lines.append(f'<line x1="{sx(g):.1f}" y1="20" x2="{sx(g):.1f}" y2="{H-20}" stroke="#222833" stroke-width="1"/>')
|
||||
lines.append(f'<text x="{sx(g):.1f}" y="{H-6}" fill="#556" font-size="10" text-anchor="middle">{g:.1f}</text>')
|
||||
g += step
|
||||
g = math.floor(y0 / step) * step
|
||||
while g <= y1:
|
||||
lines.append(f'<line x1="20" y1="{sy(g):.1f}" x2="{W-20}" y2="{sy(g):.1f}" stroke="#222833" stroke-width="1"/>')
|
||||
lines.append(f'<text x="4" y="{sy(g)+3:.1f}" fill="#556" font-size="10">{g:.1f}</text>')
|
||||
g += step
|
||||
# 轨迹
|
||||
lines.append(f'<polyline points="{path}" fill="none" stroke="#4da3ff" stroke-width="2.5"/>')
|
||||
# 起点/终点
|
||||
lines.append(f'<circle cx="{sx(0):.1f}" cy="{sy(0):.1f}" r="5" fill="#3ddc84"/>')
|
||||
lines.append(f'<text x="{sx(0)+8:.1f}" y="{sy(0)-6:.1f}" fill="#3ddc84" font-size="12">起点</text>')
|
||||
lines.append(f'<circle cx="{sx(x):.1f}" cy="{sy(y):.1f}" r="5" fill="#ff5c5c"/>')
|
||||
lines.append(f'<text x="{sx(x)+8:.1f}" y="{sy(y)+14:.1f}" fill="#ff5c5c" font-size="12">终点</text>')
|
||||
# 终点朝向箭头
|
||||
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'<line x1="{ax:.1f}" y1="{ay:.1f}" x2="{ex:.1f}" y2="{ey:.1f}" stroke="#ffd166" stroke-width="2"/>')
|
||||
lines.append(f'<text x="20" y="24" fill="#8892a6" font-size="13">'
|
||||
f'哨兵方形行驶轨迹(边长 {SIDE} m,速度 {LINEAR} m/s,转向 {ANGULAR} rad/s)</text>')
|
||||
lines.append('</svg>')
|
||||
|
||||
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()
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# 重新生成工作区根的 compile_commands.json(VS Code / clangd 的智能感知数据源)。
|
||||
#
|
||||
# 做了两件事:
|
||||
# 1. 用 -DCMAKE_EXPORT_COMPILE_COMMANDS=ON 跑一遍 colcon build(增量,很快)
|
||||
# 2. 把 build/<包>/compile_commands.json 合并到工作区根目录
|
||||
#
|
||||
# 什么时候要重跑:新增/重命名了新 .cpp、新增了 C++ 包、改了 CMakeLists 的
|
||||
# include 目录或依赖、换了 ROS 发行版。
|
||||
#
|
||||
# 用法:
|
||||
# tools/gen_compdb.sh # 全部包
|
||||
# tools/gen_compdb.sh sentry_nav # 只处理某个包
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
ROS_SETUP="${ROS_SETUP:-/opt/ros/lyrical/setup.bash}"
|
||||
# 本脚本在 tools/ 下,工作区根是它的父目录。
|
||||
WS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
|
||||
if [[ ! -f "${ROS_SETUP}" ]]; then
|
||||
echo "找不到 ${ROS_SETUP},请用 ROS_SETUP=/opt/ros/<distro>/setup.bash 指定" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# shellcheck disable=SC1090
|
||||
# ROS 的 setup.bash 里有未定义变量,必须临时关掉 set -u 才能 source。
|
||||
set +u
|
||||
# shellcheck disable=SC1090
|
||||
source "${ROS_SETUP}"
|
||||
set -u
|
||||
cd "${WS_ROOT}"
|
||||
|
||||
# 位置参数 = 包名列表;不给参数就构建整个工作区。
|
||||
if [[ $# -gt 0 ]]; then
|
||||
PACKAGE_ARGS=(--packages-select "$@")
|
||||
else
|
||||
PACKAGE_ARGS=()
|
||||
fi
|
||||
|
||||
colcon build --symlink-install \
|
||||
"${PACKAGE_ARGS[@]}" \
|
||||
--cmake-args -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
|
||||
|
||||
python3 - "${WS_ROOT}" <<'PY'
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
root = sys.argv[1]
|
||||
out = []
|
||||
for path in sorted(glob.glob(os.path.join(root, "build", "*", "compile_commands.json"))):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
entries = json.load(f)
|
||||
print(f"{len(entries):4d} 条 <- {os.path.relpath(path, root)}")
|
||||
out.extend(entries)
|
||||
|
||||
if not out:
|
||||
sys.exit("没有找到任何 compile_commands.json,检查包是否含 C/C++ 源文件")
|
||||
|
||||
with open(os.path.join(root, "compile_commands.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(out, f, indent=2)
|
||||
print(f"合并完成 -> {os.path.join(root, 'compile_commands.json')}({len(out)} 条)")
|
||||
PY
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
!/usr/bin/env bash
|
||||
# 由 URDF(xacro) 生成 Gazebo 用的静态模型 SDF。
|
||||
# 改了 URDF 之后重跑一次本脚本(launch 用 world 里 include 的 model://sentry)。
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
[ -f install/setup.bash ] && source install/setup.bash || source /opt/ros/lyrical/setup.bash 2>/dev/null || true
|
||||
xacro src/sentry_sim/urdf/sentry.urdf.xacro > /tmp/sentry.urdf
|
||||
gz sdf -p /tmp/sentry.urdf > src/sentry_sim/models/sentry/model.sdf
|
||||
echo "已生成 src/sentry_sim/models/sentry/model.sdf ($(wc -l < src/sentry_sim/models/sentry/model.sdf) 行)"
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""用 Nav2 的 NavigateToPose 动作发目标,打印反馈与结果,并检查 TF。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav2_msgs.action import NavigateToPose
|
||||
from rclpy.action import ActionClient
|
||||
from rclpy.node import Node
|
||||
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
|
||||
|
||||
rclpy.init()
|
||||
node = Node('nav_client')
|
||||
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('✅ 动作服务器可用')
|
||||
|
||||
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('✅ 目标已接受,等待结果...')
|
||||
|
||||
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
|
||||
names = {4: '✅ SUCCEEDED', 5: '❌ CANCELED', 6: '❌ ABORTED'}
|
||||
print(f'结果: {names.get(status, status)}')
|
||||
else:
|
||||
print('超时未完成')
|
||||
|
||||
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}')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""诊断 Nav2:代价地图是否在更新、TF 是否完整、能否规划。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import OccupancyGrid
|
||||
from rclpy.node import Node
|
||||
from tf2_ros import Buffer, TransformListener
|
||||
|
||||
rclpy.init()
|
||||
node = Node('nav_diag')
|
||||
buf = Buffer()
|
||||
TransformListener(buf, node)
|
||||
grids = {}
|
||||
node.create_subscription(OccupancyGrid, '/global_costmap/costmap',
|
||||
lambda m: grids.__setitem__('g', (time.time(), m)), 10)
|
||||
node.create_subscription(OccupancyGrid, '/local_costmap/costmap',
|
||||
lambda m: grids.__setitem__('l', (time.time(), m)), 10)
|
||||
node.create_subscription(OccupancyGrid, '/map',
|
||||
lambda m: grids.__setitem__('m', (time.time(), m)), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 12:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key, name in (('m', '/map'), ('g', 'global_costmap'), ('l', 'local_costmap')):
|
||||
if key in grids:
|
||||
ts, g = grids[key]
|
||||
print(f'{name:16} ✅ 收到 尺寸={g.info.width}x{g.info.height} 分辨率={g.info.resolution} 龄期={time.time()-ts:.1f}s')
|
||||
else:
|
||||
print(f'{name:16} ❌ 没收到(说明这一环没在发布/更新)')
|
||||
|
||||
for parent, child in (('map', 'odom'), ('odom', 'base_link'), ('base_link', 'lidar_link')):
|
||||
try:
|
||||
tr = buf.lookup_transform(parent, child, rclpy.time.Time())
|
||||
p = tr.transform.translation
|
||||
print(f'TF {parent:9} -> {child:10} ✅ ({p.x:+.2f}, {p.y:+.2f}, {p.z:+.2f})')
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f'TF {parent:9} -> {child:10} ❌ {str(exc)[:60]}')
|
||||
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""同时探测多个关键话题是否真的有数据。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from rosgraph_msgs.msg import Clock
|
||||
from sensor_msgs.msg import LaserScan
|
||||
from tf2_msgs.msg import TFMessage
|
||||
from nav2_msgs.msg import ParticleCloud
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_all')
|
||||
got = {}
|
||||
node.create_subscription(Clock, '/clock', lambda m: got.setdefault('clock', m), 10)
|
||||
node.create_subscription(Odometry, '/odom', lambda m: got.setdefault('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('scan', m), 10)
|
||||
node.create_subscription(TFMessage, '/tf', lambda m: got.setdefault('tf', m), 50)
|
||||
node.create_subscription(ParticleCloud, '/particle_cloud', lambda m: got.setdefault('particles', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 5:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key in ('clock', 'odom', 'scan', 'tf', 'particles'):
|
||||
m = got.get(key)
|
||||
if m is None:
|
||||
print(f'{key:10} ✗ 无数据')
|
||||
elif key == 'clock':
|
||||
print(f'clock ✓ sim={m.clock.sec}.{m.clock.nanosec:09d}')
|
||||
elif key == 'odom':
|
||||
print(f'odom ✓ x={m.pose.pose.position.x:.3f}')
|
||||
elif key == 'scan':
|
||||
print(f'scan ✓ frame={m.header.frame_id} rays={len(m.ranges)}')
|
||||
elif key == 'tf':
|
||||
print(f'tf ✓ 本帧变换数={len(m.transforms)}')
|
||||
else:
|
||||
print(f'particles ✓ {len(m.particles) if hasattr(m,"particles") else "?"} 个粒子')
|
||||
node.destroy_node(); rclpy.shutdown()
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""统计 /cmd_vel、/model/sentry/cmd_vel 的消息数,并观察 odom 位移。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_cmd')
|
||||
cnt = {'a': 0, 'b': 0}
|
||||
last = {'odom': None}
|
||||
node.create_subscription(Twist, '/cmd_vel', lambda m: cnt.__setitem__('a', cnt['a'] + 1), 10)
|
||||
node.create_subscription(Twist, '/model/sentry/cmd_vel',
|
||||
lambda m: cnt.__setitem__('b', cnt['b'] + 1), 10)
|
||||
node.create_subscription(Odometry, '/odom', lambda m: last.__setitem__('odom', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
print(f'/cmd_vel 消息数={cnt["a"]} /model/sentry/cmd_vel 消息数={cnt["b"]}')
|
||||
if last['odom']:
|
||||
p = last['odom'].pose.pose.position
|
||||
print(f'odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""用 Best Effort QoS 统计 cmd_vel 消息数(Nav2 可能用 best-effort 发布)。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import Twist
|
||||
from rclpy.node import Node
|
||||
from rclpy.qos import QoSHistoryPolicy, QoSProfile, QoSReliabilityPolicy
|
||||
|
||||
qos = QoSProfile(depth=10,
|
||||
reliability=QoSReliabilityPolicy.BEST_EFFORT,
|
||||
history=QoSHistoryPolicy.KEEP_LAST)
|
||||
rclpy.init()
|
||||
n = Node('probe_cmd2')
|
||||
cnt = {'a': 0, 'b': 0}
|
||||
n.create_subscription(Twist, '/cmd_vel', lambda m: cnt.__setitem__('a', cnt['a'] + 1), qos)
|
||||
n.create_subscription(Twist, '/model/sentry/cmd_vel',
|
||||
lambda m: cnt.__setitem__('b', cnt['b'] + 1), qos)
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 10:
|
||||
rclpy.spin_once(n, timeout_sec=0.2)
|
||||
print(f'/cmd_vel={cnt["a"]} /model/sentry/cmd_vel={cnt["b"]}')
|
||||
n.destroy_node(); rclpy.shutdown()
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""一次性检查:/odom 和 /scan 有没有数据流进来。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import LaserScan
|
||||
|
||||
rclpy.init()
|
||||
node = Node('probe_sub')
|
||||
got = {}
|
||||
|
||||
node.create_subscription(Odometry, '/odom', lambda m: got.setdefault('odom', m), 10)
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('scan', m), 10)
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < 15 and len(got) < 2:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
for key in ('odom', 'scan'):
|
||||
msg = got.get(key)
|
||||
if msg is None:
|
||||
print(f'{key} 没收到')
|
||||
elif key == 'odom':
|
||||
p = msg.pose.pose.position
|
||||
print(f'odom OK: x={p.x:.3f} y={p.y:.3f} frame={msg.header.frame_id}')
|
||||
else:
|
||||
finite = [r for r in msg.ranges if r == r and r != float('inf')]
|
||||
print(f'scan OK: frame={msg.header.frame_id} rays={len(msg.ranges)} '
|
||||
f'有效点={len(finite)} 最近={min(finite):.2f}m' if finite else 'scan 全无效')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""检查雷达数据的合理性:有多少有效点、最近/最远距离。"""
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from rclpy.node import Node
|
||||
from sensor_msgs.msg import LaserScan
|
||||
|
||||
rclpy.init()
|
||||
node = Node('scan_probe')
|
||||
got = {}
|
||||
node.create_subscription(LaserScan, '/scan', lambda m: got.setdefault('s', m), 10)
|
||||
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')
|
||||
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')
|
||||
else:
|
||||
print('⚠️ 全部无效(inf):传感器可能高于围挡或被遮死')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""发布一个 /goal_pose 目标点,并监视 /odom 是否真的在动。"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.node import Node
|
||||
|
||||
goal_x = float(sys.argv[1]) if len(sys.argv) > 1 else 2.0
|
||||
goal_y = float(sys.argv[2]) if len(sys.argv) > 2 else 2.0
|
||||
watch = float(sys.argv[3]) if len(sys.argv) > 3 else 40.0
|
||||
|
||||
rclpy.init()
|
||||
node = Node('goal_sender')
|
||||
pub = node.create_publisher(PoseStamped, '/goal_pose', 10)
|
||||
last = {'odom': None}
|
||||
node.create_subscription(Odometry, '/odom',
|
||||
lambda m: last.__setitem__('odom', m), 10)
|
||||
|
||||
# 等 /odom 有数据
|
||||
t0 = time.time()
|
||||
while last['odom'] is None and time.time() - t0 < 10:
|
||||
rclpy.spin_once(node, timeout_sec=0.2)
|
||||
|
||||
msg = PoseStamped()
|
||||
msg.header.frame_id = 'map'
|
||||
msg.header.stamp = node.get_clock().now().to_msg()
|
||||
msg.pose.position.x = goal_x
|
||||
msg.pose.position.y = goal_y
|
||||
msg.pose.orientation.w = 1.0
|
||||
pub.publish(msg)
|
||||
print(f'已发送目标 ({goal_x}, {goal_y}),观察 {watch:.0f}s ...')
|
||||
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < watch:
|
||||
rclpy.spin_once(node, timeout_sec=0.3)
|
||||
if int((time.time() - t0)) % 5 == 0:
|
||||
m = last['odom']
|
||||
if m:
|
||||
p = m.pose.pose.position
|
||||
print(f' t={time.time()-t0:4.1f}s odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
time.sleep(1)
|
||||
m = last['odom']
|
||||
if m:
|
||||
p = m.pose.pose.position
|
||||
print(f'最终 odom=({p.x:+.3f}, {p.y:+.3f})')
|
||||
node.destroy_node()
|
||||
rclpy.shutdown()
|
||||
Reference in new issue
Block a user