实现了yaw轴的转动,mid360参数更加接近实际的参数

This commit is contained in:
mzx committed 2026-11-25 21:22:13 +08:00
1 parent 72f407c110
commit 96445bd5f1
61 files changed
+2460 -235

No files matched your search

+3 -2
View File
@@ -75,8 +75,9 @@ class ArenaGrid:
return mask
def coverage(self):
# Largest radius of the existing 0.65 x 0.54 m rectangular footprint.
travel = self.clear(math.hypot(0.325, 0.270))
# 外接半径:footprint 现在是 0.61 x 0.61 的正方形(要覆盖云台 yaw 扫掠圆,
# 半径 0.3021 m),外接半径 = 0.305 * sqrt(2)。
travel = self.clear(math.hypot(0.305, 0.305))
start = self.cell(START)
if not travel[start]:
raise ValueError('spawn pose fails the footprint clearance check')
+12 -4
View File
@@ -64,6 +64,12 @@ def build_map(directory, selected, output):
extrinsics = [np.array(list(map(float, row.split()[1:]))) for row in config[2:4]]
if [line.split()[0] for line in config[2:4]] != ['base_from_imu', 'imu_from_lidar']:
raise ValueError('survey recorder configuration is missing LiDAR extrinsics')
bounds_rows = [row.split()[1:] for row in config if row.startswith('map_bounds ')]
if len(bounds_rows) != 1 or len(bounds_rows[0]) != 6:
raise ValueError('survey recorder configuration is missing map bounds')
low, high = np.array(bounds_rows[0], dtype=float).reshape(2, 3)
if not np.isfinite([low, high]).all() or not (low < high).all():
raise ValueError('survey recorder configuration has invalid map bounds')
clouds = []
for (x, y), (stamp, filename) in selected:
raw = (directory / filename).read_bytes()
@@ -72,11 +78,13 @@ def build_map(directory, selected, output):
raise ValueError(f'invalid recorded scan {filename}')
rows = np.frombuffer(raw, dtype=[('time', '<f8'), ('point', '<f4', (4,))], offset=24)
points = rows['point'][:, :3].astype(np.float64)
points = points[np.isfinite(points).all(axis=1)]
if not len(points):
raise RuntimeError(f'no finite returns at station {(x, y)}')
base_from_imu, imu_from_lidar = extrinsics
clouds.append(transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0])
points = points[np.isfinite(points).all(axis=1)]
world = transform(transform(points, imu_from_lidar), base_from_imu) + [x, y, 0]
selected_points = world[((world >= low) & (world <= high)).all(axis=1)]
if not len(selected_points):
raise RuntimeError(f'no in-field returns at station {(x, y)}')
clouds.append(selected_points)
points = np.concatenate(clouds)
# Average measured returns that occupy the same voxel across overlapping views.
grid = np.floor(points / MAP_RESOLUTION).astype(np.int64)
+82 -11
View File
@@ -37,6 +37,34 @@ GIMBAL_KEYS = (
'24哨兵-拨盘', 'Mirror零件8', 'GUDING', 'F6703ZZ',
'电机带轮', '拨盘带轮', 'z21胀紧', 'Z21胀紧',
)
# 底盘固定件:名字里虽然带 '基座装配',但**不跟着 yaw 转**。
# 先判这张表、再判 GIMBAL_KEYS —— 否则电机会跟着云台绕圈。
# GM6020 / 35齿小带轮 电机与电机轴
# 涨紧轮 / 上供皮带 皮带传动件
# 基座铝件 / 支座碳板 / 打印件补强板 / 轴承压板 基座结构件
# thrust ball bearings / 内70外86 内60外76 轴承(外圈固定)
# 15.5直径滑环 滑环定子侧
# 大yaw6020底板 电机安装底板
# F6703ZZ 法兰轴承 实测在 ROS (-0.071, 0),不在 yaw 轴上
CHASSIS_KEYS = (
'GM6020', '35齿小带轮', '涨紧轮', '上供皮带', '基座铝件', '支座碳板',
'打印件补强板', '轴承压板', 'thrust ball bearings', '内70外86',
'滑环', '大yaw6020底板', 'F6703ZZ',
# '轮系-N 装配体1-1' 之外的轮系零件(如轮上的 Z21 胀紧套):
# 它们跟着轮子转,不属于云台。WHEEL_MARK 已先匹配掉轮子本体。
'轮系-',
)
# 与 yaw 轴同轴的零件:用它们的中心算 yaw 轴位置(不是电机中心)。
# 电机经 35齿小带轮 → 皮带 → 70齿大带轮 减速,电机轴与 yaw 轴相距一个
# 皮带中心距(本装配体实测 89.9 mm),拿电机中心当转轴会整圈偏移。
# ⚠️ 只放**确认在转轴上**的零件。'胀紧联结套' 不行:全车有 5 个
# (电机轴 1 个 + 四个轮子各 1 个),会污染平均值。
YAW_AXIS_KEYS = ('70齿大带轮', '云台内圈', '滑环', '内70外86')
# 这些同轴件的中心必须一致;离散超过该值就说明关键字选错了,直接报警
YAW_AXIS_SPREAD_MM = 5.0
# 轮子本体(会绕自身轴转)
WHEEL_MARK = '轮系-{} 装配体1-1'
@@ -45,6 +73,9 @@ def read_stl(path):
size = os.path.getsize(path)
with open(path, 'rb') as f:
head = f.read(84)
if len(head) < 84:
# 连 84 字节的头都不完整 —— 损坏/截断的文件,当读不出处理
return None
n = struct.unpack('<I', head[80:84])[0]
if 84 + n * 50 != size:
return None
@@ -77,12 +108,53 @@ def classify(name):
for i in (1, 2, 3, 4):
if WHEEL_MARK.format(i) in name:
return f'wheel{i}'
# 固定件优先:'基座装配' 这个关键字太宽,会把电机和基座板一起划进来
for key in CHASSIS_KEYS:
if key in name:
return 'base'
for key in GIMBAL_KEYS:
if key in name:
return 'gimbal'
return 'base'
class YawAxisError(RuntimeError):
"""yaw 轴候选零件不共轴 —— 说明 YAW_AXIS_KEYS 选错了。"""
def find_yaw_axis(files):
"""按 YAW_AXIS_KEYS 定位 yaw 轴,返回 ``(yaw_xz, 候选数, (离散x, 离散z))``。
``yaw_xz`` 是 SW 装配体坐标下的 ``(x, z)``;没有候选时返回 ``None``。
候选零件的包围盒中心必须共轴(离散 <= ``YAW_AXIS_SPREAD_MM``),否则抛
``YawAxisError`` —— 宁可停下,也不要带着偏移的转轴去生成 URDF。
"""
centers = []
for path in files:
if not any(k in os.path.basename(path) for k in YAW_AXIS_KEYS):
continue
tris = read_stl(path)
if tris is None:
continue
v = tris.reshape(-1, 3)
centers.append((v.min(axis=0) + v.max(axis=0)) / 2)
if not centers:
return None, 0, (0.0, 0.0)
arr = np.array(centers)
mean = arr.mean(axis=0)
spread = np.ptp(arr, axis=0) * SCALE * 1000.0 # mm
if max(spread[0], spread[2]) > YAW_AXIS_SPREAD_MM:
lines = '\n'.join(
f' dx={c[0] - mean[0]:+9.1f} dz={c[2] - mean[2]:+9.1f} mm'
for c in centers)
raise YawAxisError(
f'yaw 轴候选不共轴:{len(centers)} 个同轴件的中心离散 '
f'{spread[0]:.1f}/{spread[2]:.1f} mm(阈值 {YAW_AXIS_SPREAD_MM} mm)。\n'
f' 各候选相对均值:\n{lines}\n'
f' 检查 YAW_AXIS_KEYS = {YAW_AXIS_KEYS}')
return (mean[0], mean[2]), len(centers), (spread[0], spread[2])
def to_ros(tris, center_sw):
"""SW 装配体坐标 -> ROS 坐标(米)。
@@ -171,17 +243,16 @@ def main():
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
# yaw 轴:取与大带轮 / 滑环 / 云台内圈这些**同轴件**的中心,见 find_yaw_axis()。
# 不能用 GM6020 电机中心 —— 电机经 35齿小带轮 + 皮带 + 70齿大带轮 减速驱动,
# 电机轴与 yaw 轴相差一个皮带中心距(本装配体 89.9 mm),拿电机当转轴会整圈偏移。
try:
yaw_xz, axis_count, axis_spread = find_yaw_axis(files)
except YawAxisError as error:
raise SystemExit(str(error)) from error
if yaw_xz:
print(f' yaw 轴由 {axis_count} 个同轴件求得'
f'(离散 {axis_spread[0]:.2f}/{axis_spread[1]:.2f} mm)')
wheels_ros = {}
for k, c_sw in wc.items():
+4 -1
View File
@@ -156,7 +156,10 @@ def main():
stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace))
log = open(args.output/'record.log', 'w', encoding='utf8')
log_handles.append(log)
recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true',
sim_share = Path(os.environ.get('SENTRY_SIM_SHARE') or workspace/'src/sentry_sim')
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
'--params-file', str(sim_share/'config/field_cloud.yaml'),
'-p', 'use_sim_time:=true',
'-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}',
'-p', f'point_cloud_topic:={cloud_topic}'],
stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+166
View File
@@ -0,0 +1,166 @@
#!/usr/bin/env python3
"""Lock the two decisions that are easy to get silently wrong in build_vehicle:
1. which parts rotate with the gimbal yaw (`classify`)
2. where the yaw axis actually is (`find_yaw_axis`)
Both used to be wrong: the motor centre was taken as the yaw axis even though a
belt drives it (89.9 mm offset), and the broad `基座装配` keyword pulled the
motor and base plates into the rotating mesh.
"""
import os
from pathlib import Path
import struct
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
import build_vehicle
PREFIX = '完全车2 - 装配体-3 '
def write_box_stl(path, lo, hi):
"""Write a one-triangle binary STL whose bounding box is exactly [lo, hi]."""
vertices = [(lo[0], lo[1], lo[2]),
(hi[0], lo[1], lo[2]),
(lo[0], hi[1], hi[2])]
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, 'wb') as handle:
handle.write(b'\0' * 80)
handle.write(struct.pack('<I', 1))
handle.write(struct.pack('<3f', 0.0, 0.0, 1.0))
for vertex in vertices:
handle.write(struct.pack('<3f', *vertex))
handle.write(struct.pack('<H', 0))
return path
class ClassifyTest(unittest.TestCase):
"""`classify` decides what spins with the yaw; getting it wrong is visible."""
def test_chassis_parts_stay_with_the_base(self):
# '基座装配' alone would match all of these; the explicit chassis list wins.
for name in (
PREFIX + '基座装配-1 RoboMaster GM6020 直流无刷电机-1.STL',
PREFIX + '基座装配-1 35齿小带轮-1.STL',
PREFIX + '基座装配-1 涨紧轮-1.STL',
PREFIX + '基座装配-1 涨紧轮-2.STL',
PREFIX + '基座装配-1 上供皮带2-1.STL',
PREFIX + '基座装配-1 基座铝件-1.STL',
PREFIX + '基座装配-1 支座碳板-1.STL',
PREFIX + '基座装配-1 打印件补强板-1.STL',
PREFIX + '基座装配-1 轴承压板-1.STL',
PREFIX + '基座装配-1 15.5直径滑环-1.STL',
PREFIX + '基座装配-1 thrust ball bearings gb-1.STL',
PREFIX + '基座装配-1 内70外86外圈-1 内60外76内圈-1.STL',
PREFIX + 'F6703ZZ法兰轴承-1.STL',
PREFIX + '大yaw6020底板-1.STL',
):
with self.subTest(name=name):
self.assertEqual(build_vehicle.classify(name), 'base')
def test_rotating_parts_follow_the_gimbal(self):
for name in (
PREFIX + '基座装配-1 70齿大带轮-1.STL',
PREFIX + '基座装配-1 云台内圈-1.STL',
PREFIX + '八爪拨盘平面盘体-1.STL',
PREFIX + '八爪拨盘柱体-1.STL',
PREFIX + 'yaw板^装配体-1.STL',
PREFIX + '小云台装配体-1 鹅颈云台-相机架-顶部保护板-v1.0-1.STL',
PREFIX + '小云台装配体-1 相机支架-v1.0-2.STL',
PREFIX + '24哨兵-拨盘-电机带轮垫片-1.STL',
):
with self.subTest(name=name):
self.assertEqual(build_vehicle.classify(name), 'gimbal')
def test_wheels_win_over_every_other_keyword(self):
self.assertEqual(
build_vehicle.classify(PREFIX + '轮系-1 装配体1-1.STL'), 'wheel1')
self.assertEqual(
build_vehicle.classify(PREFIX + '轮系-4 装配体1-1.STL'), 'wheel4')
def test_wheel_side_parts_do_not_join_the_gimbal(self):
# The four wheel hubs carry their own Z21 sleeves; 'Z21胀紧' must not
# drag them into the gimbal because they spin with the wheels.
for index in (1, 2, 3, 4):
name = PREFIX + f'轮系-{index} Z21胀紧联结套[Z21-10].step-2.STL'
with self.subTest(name=name):
self.assertEqual(build_vehicle.classify(name), 'base')
class YawAxisTest(unittest.TestCase):
"""`find_yaw_axis` must refuse an off-axis candidate set instead of drifting."""
def setUp(self):
temp = tempfile.TemporaryDirectory(prefix='sentry yaw ')
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
def place(self, name, centre_x, centre_z):
"""A part centred at (centre_x, centre_z) mm in SW x/z, 10 mm across."""
return write_box_stl(
self.root / name,
(centre_x - 5.0, 0.0, centre_z - 5.0),
(centre_x + 5.0, 100.0, centre_z + 5.0))
def test_coaxial_parts_give_their_shared_centre(self):
files = [self.place('a 70齿大带轮-1.STL', 31386.4, 10455.2),
self.place('b 云台内圈-1.STL', 31386.4, 10455.2),
self.place('c 15.5直径滑环-1.STL', 31386.5, 10455.3)]
axis, count, spread = build_vehicle.find_yaw_axis(files)
self.assertEqual(count, 3)
self.assertAlmostEqual(axis[0], 31386.43, places=1)
self.assertAlmostEqual(axis[1], 10455.23, places=1)
self.assertLess(max(spread), build_vehicle.YAW_AXIS_SPREAD_MM)
def test_motor_style_offset_is_rejected(self):
# e.g. accidentally including a belt-driven motor beside the pulley.
files = [self.place('a 70齿大带轮-1.STL', 31386.4, 10455.2),
self.place('b 云台内圈-1.STL', 31386.4, 10455.2),
self.place('c 35齿小带轮-1.STL', 31476.3, 10455.0)]
# 35齿小带轮 is not a YAW_AXIS_KEY, so it is ignored entirely.
axis, count, _ = build_vehicle.find_yaw_axis(files)
self.assertEqual(count, 2)
self.assertAlmostEqual(axis[0], 31386.4, places=1)
# But a *keyword* part that sits off-axis must raise, not average.
files.append(self.place('d 70齿大带轮-2.STL', 31476.3, 10455.0))
with self.assertRaisesRegex(build_vehicle.YawAxisError, '不共轴'):
build_vehicle.find_yaw_axis(files)
def test_no_candidates_returns_none(self):
files = [self.place('wheel 轮系-1 装配体1-1.STL', 31599.0, 10621.0)]
self.assertEqual(build_vehicle.find_yaw_axis(files), (None, 0, (0.0, 0.0)))
def test_unreadable_candidate_is_skipped(self):
good = self.place('a 70齿大带轮-1.STL', 1000.0, 2000.0)
bad = self.root / 'b 云台内圈-1.STL'
bad.write_bytes(b'not an stl')
axis, count, _ = build_vehicle.find_yaw_axis([good, bad])
self.assertEqual(count, 1)
self.assertAlmostEqual(axis[0], 1000.0, places=1)
self.assertAlmostEqual(axis[1], 2000.0, places=1)
class KeywordTest(unittest.TestCase):
"""The keyword lists themselves are part of the contract."""
def test_axis_keys_exclude_generic_fasteners(self):
# '胀紧联结套' appears on the motor shaft and all four wheel hubs.
self.assertNotIn('胀紧联结套', build_vehicle.YAW_AXIS_KEYS)
for key in ('70齿大带轮', '云台内圈', '滑环'):
self.assertIn(key, build_vehicle.YAW_AXIS_KEYS)
def test_motor_is_not_an_axis_key(self):
self.assertNotIn('GM6020', build_vehicle.YAW_AXIS_KEYS)
self.assertIn('GM6020', build_vehicle.CHASSIS_KEYS)
if __name__ == '__main__':
unittest.main(verbosity=2)
+2 -2
View File
@@ -59,7 +59,7 @@ def cylinder_clearance(row,x,y,radius):
q=row[4:];yaw=math.atan2(2*(q[3]*q[2]+q[0]*q[1]),1-2*(q[1]*q[1]+q[2]*q[2]))
dx,dy=x-row[1],y-row[2]
bx=math.cos(yaw)*dx+math.sin(yaw)*dy;by=-math.sin(yaw)*dx+math.cos(yaw)*dy
# Union of the actual SDF chassis and gimbal collision boxes.
# Chassis box and the yaw sweep of the SDF gimbal collision box.
chassis=math.hypot(max(0,abs(bx)-0.289),max(0,abs(by)-0.2605))
gimbal=math.hypot(max(0,abs(bx-0.12)-0.20),max(0,abs(by)-0.15))
gimbal=math.hypot(bx,by)-math.hypot(0.2656,0.1439)
return min(chassis,gimbal)-radius
+8 -1
View File
@@ -111,6 +111,8 @@ def main():
help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests')
parser.add_argument('--timeout', type=float, default=420.0,
help='whole-stack validation deadline, including up to three startup attempts')
parser.add_argument('--continue-on-failure', action='store_true',
help='try later full-field goals after recording a failed leg and waiting for recovery')
parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear')
parser.add_argument('--obstacle-x',type=float,default=-4.0)
parser.add_argument('--obstacle-y',type=float,default=-1.5)
@@ -121,6 +123,8 @@ def main():
parser.error('--round-trip-regression requires clear or cylinder')
if args.full_field and args.scenario != 'clear':
parser.error('--full-field starts the clear-field coverage route')
if args.continue_on_failure and not args.full_field:
parser.error('--continue-on-failure requires --full-field')
multileg = args.round_trip_regression or args.full_field or args.southeast_round_trip
if args.full_field:
route = ARENA_GOALS
@@ -174,6 +178,7 @@ def main():
record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0
record_log = open(args.output/'record.log', 'w', encoding='utf8')
recorder = subprocess.Popen([str(recorder_exe), '--ros-args',
'--params-file', str(params_file.with_name('field_cloud.yaml')),
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
'-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'],
stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True)
@@ -404,6 +409,7 @@ def main():
'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out,
'trajectory_metrics': metrics(estimate_goal, truth_goal),
'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None,
'truth_end_xy_m': truth_goal[-1][1:3] if truth_goal else None,
'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal)
if truth_goal and args.scenario == 'cylinder' else None,
'health_failures_during_goal': sum(not value for stamp, value in health_events
@@ -461,7 +467,8 @@ def main():
f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True)
if multileg and not leg['goal_succeeded']:
spin_for(8)
break
if not args.continue_on_failure:
break
result.update(counts)
result['map_to_odom_publishers'] = len(publishers)
result['amcl_present'] = 'amcl' in node.get_node_names()