关于本文的脱敏处理:模块名、设备型号、配置项名称已做中性化替换,算法结构与参数保持原样。
系列导航
一、任务的形状
一次巡检的输入是一张顶部相机照片,输出是一组「哪个点、什么状态、两张图」的记录。中间要做的事:
拍一张 -> 检测出 N 个目标点
-> 按图像中线分成左右两组
-> 逐臂、逐点:重检测 -> 移动 -> 稳定 -> 拍照 -> 判灯 -> 上传 -> 回待机位这条流水线里有四处需要真正设计的地方:分工、顺序、重定位、兜底。
二、分工:按图像中线切
一台顶部相机同时服务两条臂。检测点按图像中线分组:
@staticmethod
def split_points_by_midline(points, image_width):
midline = float(image_width) / 2.0
left_points = [p for p in points if float(p["u"]) < midline]
right_points = [p for p in points if float(p["u"]) >= midline]
left_points.sort(key=lambda p: (float(p["v"]), float(p["u"])))
right_points.sort(key=lambda p: (float(p["v"]), float(p["u"])))
return left_points, right_points2.1 为什么排序键是 (v, u)
按 (v, u) 排序就是先按行、再按列,也是扫描线的自然顺序:从上到下、从左到右。
对比三种顺序对路径长度的影响:
| 顺序 | 路径特征 | 结果 |
|---|---|---|
(v, u) 扫描线 | 逐行推进,横向单调 | 路径最短,无回头 |
(u, v) 列优先 | 逐列推进,纵向单调 | 若目标呈横向分布则来回横跳 |
| 检测输出顺序 | 取决于模型/后处理 | 可能完全随机,路径翻倍 |
排序的用处不在输出好看,而在机械臂少走路。少走路意味着更少的运动时间、更少的碰撞机会、更少的机械磨损。
2.2 手动点击时的自动切臂
同样的中线逻辑还出现在手动点击路径里:
target_arm = "left" if u < image_width / 2 else "right"
if target_arm != self.arm_side:
self.set_active_arm(target_arm)两个收益:
- 省掉「先选臂、再点图」的两步交互;
- 避免「用左臂去够右半边」这种必然超限的指令。
代价是跨中线目标永远判给对应侧。这是用清晰的空间约束换安全,比让操作员自己判断更可靠。
三、顺序:为什么必须串行
两条臂物理上可以同时动,但系统强制一条臂做完再做另一条。原因有三条:
- 共用一台顶部相机。 两臂同时动,拍到的图中另一条臂可能挡在视野里,检测被污染。
- 外参按臂分文件。 切臂会重新加载变换矩阵、工具偏置、待机位,这些都是进程级的全局状态,并发必然互相覆盖。
- 控制通道是同一条 60 Hz 流。 一个数据包同时携带左右臂位姿与腰部角度(见第五篇),并发修改同一个位姿对象会撕裂数据。
第 2 条最隐蔽:它的表现不是“偶发错误”,而是“某些点总是偏 90° 或相位错乱”,因为另一条臂的矩阵在某一刻被换了进来。
3.1 切臂的固定代价
串行的代价是时间,代码用「切臂 → 回待机位 → 等稳定」来换正确性:
def return_to_waiting_position(self, smooth=False, stop_event=None):
with self.control_lock:
original_arm = self.arm_side
results = {}
for arm_side in ("left", "right"):
wp = (self.waiting_position_left if arm_side == "left"
else self.waiting_position_right)
if wp is None:
wp = self._load_waiting_position(arm_side)
if wp is None:
raise RuntimeError(f"No waiting position saved for {arm_side} arm")
self.set_active_arm(arm_side) # 切换全局外参
move = self._move_to_xyz_locked(
wp["xyz_m"],
smooth=smooth,
stop_event=stop_event,
approach_axis=cfg.APPROACH_AXIS if smooth else None,
retreat=True, # 先退出再横移
)
results[arm_side] = {"move": move, "waiting_position": wp}
self.set_active_arm(original_arm) # 恢复原臂
return results这个函数有个容易漏的设计:它把两条臂都送回待机位,然后恢复原臂。为什么?因为待机位是安全位姿,只有两条臂都在待机位时,它们才不会互相挡视野、也不会互相碰撞。只送一条回去,另一条可能正好挡在视野中央。
3.2 为什么要等 3 秒
self.set_active_arm(arm_side)
self.return_to_waiting_position(smooth=smooth_move, stop_event=stop_event)
if return_waiting_settle_sec > 0.0:
stop_event.wait(return_waiting_settle_sec) # 3.0 s这 3 秒等的是:机械结构的余振、伺服的位置环收敛、控制盒状态机的迁移。
宁可花可预测的时间,也不去赌不可预测的精度。多等几秒是廉价的,一次跑偏的机械臂不是。交付压力下,这个方向的取舍更划算。
四、重定位:每个点移动前都要重新看一眼
4.1 为什么必须重检测
一轮巡检可能几十秒到几分钟。这期间:
- 相机的自动白平衡 / 曝光会调整,颜色分布变了;
- 机械臂自己移动时可能挡住部分视野;
- 场景里的物体可能被碰动。
沿用第一次检测的像素坐标,后面的点会越做越偏。所以每个点移动前都重新拍一张、重新检测。
4.2 核心问题:新框怎么配回原计划点
重新检测会得到一组新的框,但顺序、数量都可能不同。需要一个指派(assignment)来回答「哪个新框对应我原来要去的那个点」。
实现是按距离升序的贪心匹配:
def match_refreshed_detections(self, planned_points, detections):
max_distance = float(cfg.INSPECTION_REDETECT_MAX_MATCH_DISTANCE_PX) # 180
edges = []
for planned_index, planned_point in enumerate(planned_points):
planned_u = float(planned_point["u"])
planned_v = float(planned_point["v"])
for det_index, detection in enumerate(detections):
if not self._same_yolo_class(planned_point, detection):
continue # 约束一:类别相同
distance_px = float(
((float(detection["u"]) - planned_u) ** 2
+ (float(detection["v"]) - planned_v) ** 2) ** 0.5)
if max_distance <= 0 or distance_px <= max_distance: # 约束二:距离上限
edges.append((distance_px, planned_index, det_index))
edges.sort(key=lambda item: item[0]) # 全局按距离升序
used_planned, used_detections, assignment = set(), set(), {}
for distance_px, planned_index, det_index in edges:
if planned_index in used_planned or det_index in used_detections:
continue # 约束三:一对一
used_planned.add(planned_index)
used_detections.add(det_index)
assignment[planned_index] = (detections[det_index], distance_px)
return assignment4.3 这是匈牙利算法的贪心近似
标准的指派问题是最小代价二分图匹配,最优解由 Kuhn–Munkres(匈牙利)算法给出,复杂度 O(n³)。
这里用的是「最近邻按序占位」:
1. 枚举所有合法边 (距离, 计划点, 检测框),只保留类别相同且距离 ≤ 180 px 的
2. 全局按距离升序排序
3. 依次贪心占用:两端都没被占,就配对复杂度 O(n² log n)。之所以不去求最优,是因为在这个数据分布下,最优和贪心的结果几乎总是相同。
前提是目标间距远大于匹配抖动:
| 量 | 典型值 | 说明 |
|---|---|---|
| 目标间距(像素) | 几百 px | 目标物理上相隔几十厘米 |
| 重检测抖动 | < 20 px | 同一目标在两张图里的位置差 |
| 匹配距离上限 | 180 px | 兜底阈值 |
比值约 10:1,贪心不会出错。多花那点复杂度换来的最优性,在这个数据分布下没有实际收益。
但目标密集时会失效。设想一排指示灯,间距 30 px、抖动 20 px:
计划点 A 最近的是 框2(12 px),但 框2 同时也是 计划点 B 的最近邻(8 px)
贪心按全局距离:先给 B-框2 配对
A 只剩 框1 或 框3(距离 25 px),强行配对 -> 配错正确做法是加约束(按置信度加权、或者改用匈牙利),而不是继续调大 max_distance。调大上限只会把“配不上”变成“配错了”,后者更糟,因为它不报错。
4.4 失败时降级,但必须留痕
try:
source_capture = self.capture_head_image("yolo_refresh", run_id=run_id, point_index=index)
detections = self.detect_inspection_points(source_capture, yolo_request)
except Exception as exc:
refreshed = dict(planned_point)
refreshed["redetect_warning"] = str(exc)
return refreshed
assignment = self.match_refreshed_detections(arm_planned_points, detections)
matched = assignment.get(local_index)
if matched is None:
refreshed = dict(planned_point)
refreshed["redetect_warning"] = "no unique refreshed YOLO match for planned point"
refreshed["redetect_capture"] = source_capture
return refreshed三种降级路径都在做同一件事:用旧坐标继续,但把警告写进结果。
- 不抛异常(那样整轮巡检会中断,前面做的点全白费);
- 不静默(那样问题会被埋掉,永远不知道有多少点是靠旧坐标蒙的)。
巡检结果里每条都带 redetect_warning,事后能统计出「这一轮有几个点没配上」。可统计的降级,比不可见的失败好得多。
五、单点状态机
5.1 固定顺序
每个检测点的流程严格按序:
refresh(YOLO 重检测 + 贪心匹配)
-> move(分段移动, 带碰撞检测)
-> settle(10 s, 期间启动力矩保持监视)
-> capture_head + capture_hand
-> detect_red_light_from_hand
-> upload(两张图)
-> return_to_waiting_position
-> if 红灯亮: wait_for_red_clear(每 5 s 复查, 最长 90 s)5.2 用 finally 保证「先回位再抛异常」
try:
move_point = self.refresh_point_before_move(
point, points, request, run_id, global_index, arm_side=arm_side)
move = self.move_to_pixel(u, v, move_mode, smooth=smooth_move, stop_event=stop_event)
move_collision = move.get("collision") if move else None
if move_collision is None and not stop_event.is_set():
self.start_hold_monitor() # 启动力矩保持监视
deadline = time.time() + settle_sec
while time.time() < deadline:
if stop_event.is_set() or self.hold_collision is not None:
break
time.sleep(0.05)
hold_collision = self.stop_hold_monitor()
if not stop_event.is_set():
head_capture = self.capture_head_image("inspection", run_id=run_id, point_index=global_index)
hand_capture = self.capture_hand_image(arm_side, purpose="inspection",
run_id=run_id, point_index=global_index)
red_result = self.detect_red_light_from_hand(hand_capture)
except Exception as exc:
point_error = exc
finally:
# 无论上面怎么失败,都必须先回待机位
if hold_collision is None:
hold_collision = self.stop_hold_monitor()
return_move = self.return_to_waiting_position(
global_index, total_points, smooth_move,
return_waiting_settle_sec, stop_event=stop_event)这段代码里最重要的设计是那个 finally:拍照失败、检测失败、上传失败,机械臂都停在目标位置附近。如果不在 finally 里回位,下一次巡检就从“上一次撞到的东西旁边”出发,位置误差会累积。
回位的优先级高于成功。异常路径里的这个判断总是反直觉,也总是对的。
5.3 等待红灯熄灭:复查循环而非一次性判定
def wait_for_red_clear(self, arm_side, stop_event):
deadline = time.time() + cfg.INSPECTION_RED_LIGHT_WAIT_TIMEOUT_SEC # 90 s
start = time.time()
recheck_count = 0
while time.time() < deadline:
if stop_event.is_set():
break
if stop_event.wait(cfg.INSPECTION_RED_LIGHT_WAIT_INTERVAL_SEC): # 5 s
break
pool = get_hand_camera_pool()
result = pool.capture_jpeg(arm_side)
image = cv2.imdecode(np.frombuffer(result["jpeg"], np.uint8), cv2.IMREAD_COLOR)
red = detect_red_light(image)
recheck_count += 1
if not red["red_detected"]:
return {"cleared": True, "timeout": False,
"wait_sec": round(time.time() - start, 1),
"recheck_count": recheck_count}
return {"cleared": False, "timeout": time.time() >= deadline,
"wait_sec": round(time.time() - start, 1),
"recheck_count": recheck_count}三个细节:
- 必须复查而不是单帧判定:指示灯可能是闪烁的,单帧正好拍到灭的那一瞬就会漏检。
- 返回结构里带
recheck_count和wait_sec,事后能知道「这个点是等了一轮就灭,还是等满了 90 秒」,后者通常意味着判定阈值有问题。 - 用
stop_event.wait(interval)而不是time.sleep,急停才能在 5 秒间隔内立即生效。
5.4 每点落盘
self.append_inspection_result(result)
self.write_inspection_results(run_id)每点结束后立即写文件。中途崩溃时已完成的点不会丢,这比“最后统一写”可靠得多,代价只是多几次磁盘写入。
六、硬件访问:两个必须处理的物理限制
6.1 共享 HUB 的两台相机:互斥单帧池
两台手部相机(左/右)装在夹爪附近,共享一个 USB HUB,vid/pid 完全相同,无法靠静态规则区分。更麻烦的是,它们不能同时保持长连接。
设计是按需单帧加一把全局互斥锁:
class HandCameraPool:
"""互斥的按需单帧 USB 相机池。所有手部相机共享同一把锁,
任意时刻只允许一个设备被 open。"""
def __init__(self):
self._hub_lock = threading.Lock()
self._specs = {}
self.reload_specs()
def capture_jpeg(self, arm_side, timeout_sec=None):
spec = self._spec(arm_side)
# 锁等待要覆盖整个重试预算,避免重试期间被锁等待误杀
lock_timeout = (float(cfg.HAND_CAMERA_HARD_TIMEOUT_SEC) # 6.0
* (int(cfg.HAND_CAMERA_CAPTURE_RETRIES) + 1) # 2 + 1
+ 2.0)
if not self._hub_lock.acquire(timeout=lock_timeout):
raise HandCameraCaptureError(
f"Hand camera hub lock busy for arm_side={spec.arm_side} "
f"within {lock_timeout:.1f}s")
t0 = time.monotonic()
try:
warmup = max(0, int(cfg.HAND_CAMERA_WARMUP_FRAMES)) # 3
jpeg = capture_frame_subprocess(
spec.device,
width=int(cfg.HAND_CAMERA_WIDTH), height=int(cfg.HAND_CAMERA_HEIGHT),
warmup=warmup, quality=int(cfg.HAND_CAMERA_JPEG_QUALITY),
rotation_mode=spec.rotation_mode,
)
return {"arm_side": spec.arm_side, "device": spec.device, "jpeg": jpeg,
"width": ..., "height": ..., "elapsed_sec": ...,
"warmup_frames": warmup, "backend": "local_pool"}
finally:
self._hub_lock.release()三个决策:
① 按需 open、丢 warmup 帧、读一帧、立即 release。 长连接在共享 HUB 上会互相抢带宽/供电;按需单帧把冲突从“偶发不可复现”变成“串行排队可预测”。
② lock_timeout 要覆盖整个重试预算,而不是单次超时。 这是个容易错的细节:如果锁等待只用单次超时(6 s),但内部要重试 3 次(最长 18 s),那么第二个调用方会在 6 s 时就判定锁忙并抛错,而第一个调用方其实正常工作。所以锁的等待时间不能短于被保护操作的最坏总时长。
③ warmup=3。 USB 相机刚 open 时前几帧通常是黑的/未曝光的。丢掉前 3 帧再读,能显著减少“拍到全黑图”的概率。这个数字要靠实测,不同相机会不同。
6.2 cv2 的阻塞读:只能靠子进程硬超时
这是这套系统里最硬核的一个工程妥协。
问题:某些 OpenCV 版本(如 4.6.0)不支持 CAP_PROP_V4L2_TIMEOUT/OPENCV_V4L_TIMEOUT。当相机挂死(USB 复位失败、供电不足)时,单次 cap.read() 会阻塞几分钟,而 Python 无法中断阻塞的 C 调用:signal、threading、timeout 全部无效。
解法:用子进程 + subprocess.run(timeout=)。超时触发 SIGKILL,子进程死亡时操作系统关闭 fd,V4L2 设备被真正释放。
def capture_frame_subprocess(device, width=640, height=480, warmup=3, quality=90,
rotation_mode=0, hard_timeout=None, retries=None):
"""子进程取一帧 + 硬超时 + 重试。返回 JPEG bytes。
每次 fresh 子进程(fresh cv2 import + fresh open)。TimeoutExpired 时
子进程被 SIGKILL,OS 关 fd 释放 V4L2 设备。"""
hard_timeout = float(getattr(cfg, "HAND_CAMERA_HARD_TIMEOUT_SEC", 6.0))
retries = int(getattr(cfg, "HAND_CAMERA_CAPTURE_RETRIES", 2))
attempts = max(1, retries + 1)
last_err = ""
for i in range(attempts):
try:
proc = subprocess.run(
[sys.executable, "-m", "hand_camera_capture",
"--device", device,
"--width", str(width), "--height", str(height),
"--warmup", str(warmup), "--quality", str(quality),
"--rotation-mode", str(rotation_mode)],
capture_output=True,
timeout=hard_timeout,
)
except subprocess.TimeoutExpired:
last_err = f"subprocess timeout after {hard_timeout:.1f}s (killed)"
if i < attempts - 1:
time.sleep(0.3)
continue
if proc.returncode == 0 and proc.stdout:
return bytes(proc.stdout)
last_err = (proc.stderr.decode("utf-8", "replace").strip()
or f"exit code {proc.returncode}")
if i < attempts - 1:
time.sleep(0.3)
raise RuntimeError(
f"{device} 连续 {attempts} 次取帧失败(最后: {last_err}),疑似 USB 挂死")为什么这招真的有效:
| 机制 | 说明 |
|---|---|
subprocess.run(timeout=) | 到点在父进程侧触发,不依赖子进程配合 |
SIGKILL | 不可捕获,子进程无法忽略 |
| 进程死亡 → fd 关闭 | 内核回收 V4L2 句柄,设备重新可用 |
| 每次 fresh 进程 | cv2 重新 import、设备重新 open,不继承任何脏状态 |
代价是每次取帧都要付一次进程启动 + import cv2 的开销(几十到几百毫秒)。在“几秒一次”的巡检节奏里完全可以接受:拿一个固定的小成本,换掉一个不可复现的大风险,这笔账是划算的。
这个模式通用性很强:任何「阻塞在 C 层、无法从 Python 侧中断」的调用,都可以用「子进程 + 硬超时 + SIGKILL」包一层,某些驱动 ioctl 和 native 库的阻塞 read 同样适用。
七、安全判据:两套,因为两种状态
机械臂撞到东西是会坏的。系统里有两套独立的力矩碰撞检测,分别覆盖运动与静止。
力矩数据来自状态回读,取 5 个关节通道。
7.1 运动中:一阶差分 + 自适应基线
def check_collision(self, step_index, is_phase_first_step):
if not cfg.COLLISION_DETECT_ENABLED:
return None
info = self.node.system_info
if info is None:
return None
tau_all = list(info.arm_tau_left if self.arm_side == "left" else info.arm_tau_right)
tau = [float(t) for t in tau_all[1:6]]
if self.last_tau is None:
self.last_tau = tau
return None
d_tau = [abs(tau[i] - self.last_tau[i]) for i in range(5)]
max_d = max(d_tau)
# 前几步(或换相位的第一步)建基线,不判定
if is_phase_first_step or len(self.tau_baseline) < 3:
self.tau_baseline.append(max_d)
self.last_tau = tau
return None
baseline_max = max(self.tau_baseline) if self.tau_baseline else 0.0
multiplier = float(cfg.COLLISION_TORQUE_MULTIPLIER) # 4.0
min_nm = float(cfg.COLLISION_TORQUE_MIN_NM) # 0.5
threshold = max(baseline_max * multiplier, min_nm)
if max_d > threshold:
joint_idx = d_tau.index(max_d) + 1
self.last_tau = tau
return {
"joint": joint_idx,
"d_tau": round(max_d, 4),
"threshold": round(threshold, 4),
"baseline_max": round(baseline_max, 4),
"tau": [round(t, 4) for t in tau_all],
}
self.last_tau = tau
return None判据:
max_i | tau_i(k) - tau_i(k-1) | > max( 4 * baseline_max , 0.5 N·m )三个设计点:
① 用差分而不是绝对值。运动中力矩本来就在大范围变化(加速、重力补偿、摩擦),绝对阈值没法设;而碰撞的特征是力矩突变,一帧之内跳变,差分正好抓这个。
② 基线自适应。 前 3 步的 max_d 取最大值当基线,自动适配不同的运动速度、负载、姿态。换成绝对阈值就得为每个姿态标一个数。
③ 绝对下限兜底。 如果基线很小(微动),4 × baseline 可能只有 0.01 N·m,噪声就够触发。max(..., 0.5) 防止这种误报。
is_phase_first_step 参与建基线也是个细节:分段移动是多相位(见第五篇),换相位时速度方向会突变,那一步的力矩跳变是正常的,必须排除。
7.2 静止保持:双判据 + 连续确认
保持位姿时机械臂几乎不动,力矩差分接近零,上面的判据失效。第二套专门覆盖这个状态:
def hold_monitor_loop(self):
interval = float(cfg.COLLISION_HOLD_SAMPLE_INTERVAL) # 0.05
settle_samples = int(cfg.COLLISION_HOLD_SETTLE_SAMPLES) # 3
tau_threshold = float(cfg.COLLISION_HOLD_TAU_DEV_THRESHOLD) # 0.3
pos_threshold = float(cfg.COLLISION_HOLD_POS_DELTA_THRESHOLD) # 0.002
consecutive_needed = int(cfg.COLLISION_HOLD_CONSECUTIVE_COUNT) # 3
tau_baseline = []
baseline_avg = None
consecutive = 0
while not self.stop_monitor_stop.is_set() and not self.inspection_stop_event.is_set():
info = self.node.system_info
if info is None:
self.stop_monitor_stop.wait(interval)
continue
tau_all = list(info.arm_tau_left if self.arm_side == "left" else info.arm_tau_right)
tau = [float(t) for t in tau_all[1:6]]
cmd_xyz = arm_translation(self.command_pose, self.arm_side)
fb_xyz = arm_translation(pose_from_system_info(info), self.arm_side)
# 静默期:先收 3 个样本建基线,不做判定
if len(tau_baseline) < settle_samples:
tau_baseline.append(tau)
if len(tau_baseline) == settle_samples:
baseline_avg = [sum(tau_baseline[j][i] for j in range(settle_samples))
/ settle_samples for i in range(5)]
self.stop_monitor_stop.wait(interval)
continue
tau_dev = [abs(tau[i] - baseline_avg[i]) for i in range(5)]
tau_dev_max = max(tau_dev)
pos_delta = 0.0
if fb_xyz is not None:
dx = cmd_xyz[0] - fb_xyz[0]
dy = cmd_xyz[1] - fb_xyz[1]
dz = cmd_xyz[2] - fb_xyz[2]
pos_delta = (dx * dx + dy * dy + dz * dz) ** 0.5
if tau_dev_max > tau_threshold or pos_delta > pos_threshold:
consecutive += 1
else:
consecutive = 0
if consecutive >= consecutive_needed:
joint_idx = tau_dev.index(tau_dev_max) + 1
self.hold_collision = {
"joint": joint_idx,
"tau_dev": round(tau_dev_max, 4),
"pos_delta": round(pos_delta, 6),
"consecutive": consecutive,
"baseline_avg": [round(v, 4) for v in baseline_avg],
"tau": [round(t, 4) for t in tau_all],
}
break
if self.stop_monitor_stop.wait(interval):
break判据是两条「或」,且都要连续 3 帧(150 ms):
A: max_i | tau_i - baseline_i | > 0.3 N·m —— 力矩偏离
B: || cmd_xyz - fb_xyz || > 2 mm —— 位置跟随误差① 连续确认是必须的。单帧超阈值可能只是一次网络抖动、一次反馈丢包或一次 PWM 干扰;要求连续 3 帧,误报率降两个数量级,而真实碰撞的持续时间通常远大于 150 ms。代价是 100 ms 的响应延迟,换来的是绝大多数误报被挡掉。
② pos_delta 这个第二判据是最巧的一处。碰撞的物理后果是「指令到位了但实际没到位」:控制盒在推、机械臂被挡住,位置跟随误差会持续存在。
反过来也成立:如果力矩偏离但位置跟得上,那多半是负载变化(比如夹爪抓到了东西、或者手腕被压了一下),不是碰撞。两个判据的物理含义不同,才构成了“或”的关系。
③ 静默期的意义。前 3 个样本(150 ms)只建基线、不做判定,让机械臂从运动状态稳定下来,避免把减速的余振当成碰撞。
7.3 为什么一套判据不够
一句话:运动时看变化,静止时看偏差。
| 运动阶段 | 保持阶段 | |
|---|---|---|
| 力矩特征 | 本身在变,绝对值无意义 | 基本恒定,偏离有意义 |
| 主判据 | d_tau 一阶差分 | tau 绝对偏差 |
| 辅助判据 | 无 | 位置跟随误差 |
| 阈值来源 | 自适应基线 × 4 | 固定 0.3 N·m |
| 时间确认 | 单帧 | 连续 3 帧 |
| 采样节奏 | 每个运动步(80 ms) | 独立线程 50 ms |
一套判据覆盖两种状态是不可能的。这也是「先分类再判断」的通用价值:把问题按状态切分,每个子问题用最简单的判据,比硬找一个万能阈值可靠得多。
同样的思路可以迁移:判断“网络是否异常”时,空闲期看 RTT 抖动、繁忙期看吞吐突变;判断“磁盘是否异常”时,空闲期看 SMART 值、繁忙期看 IO 延迟分布。状态不同,可观测量的统计性质就不同。
7.4 行程限位:抬腕换高度
升降柱有行程上限。指令 Z 超出限位时,控制盒停在原地,而软件以为已经到位,后续拍照位置全错。
def check_z_limit_and_lift_wrist(self):
if not cfg.WRIST_LIFT_ON_Z_LIMIT:
return None
z_limit = self.z_limit
if z_limit is None:
return None
commanded_z_pre = arm_translation(self.command_pose, self.arm_side)[2]
if commanded_z_pre <= z_limit:
return None # 没超限,不处理
with self.control_lock:
time.sleep(float(cfg.WRIST_LIFT_FEEDBACK_WAIT_SEC)) # 1.0 s 等反馈稳定
feedback = self.current_pose()
if feedback is None:
return None
actual_z = arm_translation(feedback, self.arm_side)[2]
commanded_z = arm_translation(self.command_pose, self.arm_side)[2]
z_deficit = float(commanded_z - actual_z)
threshold = float(cfg.WRIST_LIFT_Z_DEFICIT_THRESHOLD_M) # 0.005
if z_deficit <= threshold:
return None # 跟得上,不是限位问题
pitch_deg = float(cfg.WRIST_LIFT_PITCH_DEG) # -10.0
pose = copy_pose(self.command_pose)
if self.arm_side == "left":
pose.left_orientation_deg[1] += pitch_deg
else:
pose.right_orientation_deg[1] += pitch_deg
self.command_pose = copy_pose(pose)
self.hold_pose(pose)
time.sleep(float(cfg.WRIST_LIFT_SETTLE_SEC)) # 1.0 s
return {"z_limit_m": round(z_limit, 4), "z_deficit_m": round(z_deficit, 4),
"commanded_z_m": round(commanded_z, 4), "actual_z_m": round(actual_z, 4),
"pitch_delta_deg": pitch_deg}判据是 z_cmd − z_fb > 5 mm:认为触限,然后把腕部 pitch 加 −10°,用姿态换高度。
这个处理本质上是用冗余自由度绕开约束:升降柱到顶了,但腕关节还有活动空间,抬腕能让末端再往上够一点。
代价是末端姿态变了,所以只在触限时才做,正常情况保持固定的标定姿态,保证外参的适用性。用姿态换位置是有代价的交换,只能在必要时用。
这里先看指令是否超限(便宜的判断),再看反馈是否吻合(贵的判断),两级串联。如果反过来,每次移动都要等 1 秒反馈,代价不可接受。
八、小结
编排与安全这一篇的六条:
- 排序键决定路径长度,
(v, u)扫描序让机械臂少走路; - 串行的收益是正确性而不是效率,共用相机、全局外参、单通道都是并发会撕坏的东西;
- 重检测必须配指派,贪心匹配在「间距远大于抖动」时等价于最优,但目标密集时要用匈牙利;
- 降级要留痕,用旧坐标继续没问题,但必须记录,否则问题永远不可统计;
- 回位的优先级高于成功,异常路径里也要先回安全位姿;
- 阻塞在 C 层的调用只能用子进程加 SIGKILL 硬超时,这是唯一可靠的中断手段。
下一篇讲控制回路:一个 162 字节的数据包如何承载双臂与腰部、为什么未激活的臂必须填常量、为什么只能有一个发送线程,以及「帧数即时间」的时序设计。