From a5ae8520977f5621e5b0f196f17cea9d38e01eee Mon Sep 17 00:00:00 2001 From: Cutshion Date: Wed, 21 Oct 2026 17:58:58 +0900 Subject: [PATCH] Queued arm moves wait while the arm moves; wave rise at route speed Co-Authored-By: Claude Opus 5.5 --- manipulation/wave.py | 34 +++++++++++++++-------------- robot/motion.py | 38 ++++++++++++++++++++++---------- tests/test_arm_route.py | 48 +++++++++++++++++++++++++++++++++++++++++ tests/test_wave.py | 12 ++++++++--- 4 files changed, 102 insertions(+), 30 deletions(-) diff --git a/manipulation/wave.py b/manipulation/wave.py index d49f757..38cf1cb 100644 --- a/manipulation/wave.py +++ b/manipulation/wave.py @@ -3,8 +3,9 @@ The arm goes up along the pose graph (manipulation/arm_route.py: from `look` to `wave_out`, the hand away from the head, then `wave_start`, the hand above the head), swings between the taught poses `wave_start` and `wave` (J3 −14.7° deg) SWINGS times and STAYS at `wave_start`: the next arm task takes it back down the same way (wave_start -> wave_out --> look). All moves are sent at once (motion.move_path): no pause between them, blended through wave_out. Before anything moves, every joint move is checked (arm_route.check_moves: limits, travel, the gripper clear -of the head, no dip). Refused, with the reason in English and Korean: the arm off or busy, the base driving, a task +-> look). The way up goes like arm_route.goto (queued, blended through wave_out), then the swings, queued. Before +anything moves, every joint move is checked (arm_route.check_moves: limits, travel, the gripper clear of the head, no +dip). Refused, with the reason in English and Korean: the arm off or busy, the base driving, a task running, something in the hand, the arm at no known pose (after free drive), a pose not taught, a move too near the head. @@ -14,14 +15,15 @@ head. Teach the poses first, arm moved by hand in Cobo π: python robot/motion.py teach wave_out / wave_start / wave """ import sys +import time from manipulation import arm_route, skills from robot import agv, arm, gripper, motion START = "wave_start" # hand above the head; the wave starts and ends here -SWING = "wave" # START with J3 −14.7°) +SWING = "wave" # START with J3 −14.7° SWINGS = 2 # times START -> SWING -> START -SWING_SPEED = "slow" # motion.JOINT_SPEED of the swings; the way up is arm_route.SPEED +SWING_SPEED = "normal" # motion.JOINT_SPEED of the swings; the way up is arm_route.move (as goto) # Why Lumi does not wave, (English, Korean) OFF = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") @@ -58,7 +60,8 @@ def _holding(): def plan(): - """Joint targets of the whole wave from here, each move checked. Raises WaveError to refuse.""" + """(the way up: arm_route.plan to START, the swings' joint targets) from here, each move checked. Raises + WaveError to refuse.""" from tasks import fetch st = arm.cmd("get_robot_state") if not (st.get("power") and st.get("enable")): @@ -75,37 +78,36 @@ def plan(): p = motion.poses() if SWING not in p: raise arm_route.RouteError(*arm_route.NOT_TAUGHT) - seq = [j for _, j in route] + arm_route.check_moves(route[-1][1] if route else now, - [p[SWING], p[START]] * SWINGS) + swings = arm_route.check_moves(route[-1][1] if route else now, [p[SWING], p[START]] * SWINGS) except arm_route.RouteError as e: raise WaveError(*{arm_route.UNKNOWN: UNKNOWN_POSE, arm_route.NOT_TAUGHT: NOT_TAUGHT, arm_route.BLOCKED: NOT_TAUGHT, arm_route.NEAR_HEAD: NEAR_HEAD}.get(e.args, UNSURE)) from e - return seq + return route, swings def wave(on_start=None): """Plan, check and wave; the arm stays at START. `on_start()` is called once the plan is checked. Raises WaveError (refused) or motion.MotionError (stopped / failed while moving: the arm stays where it stopped).""" try: - seq = plan() + route, swings = plan() except (motion.MotionError, skills.SkillError, ConnectionError, OSError, KeyError, ValueError) as e: log(f"wave refused: {e}") raise WaveError(*UNSURE) from e - log(f"wave: {len(seq)} joint moves, checked") + log(f"wave: {len(route) + len(swings)} joint moves, checked") if on_start: on_start() - up = len(seq) - 2 * SWINGS # the moves before are the way up along the graph - way = arm_route.moves(seq[:up]) # blended through wave_out (checked by arm_route.plan) ... - if way: - way[-1] = (way[-1][0], way[-1][1], 0.0) # ... to a full stop at START, where the swings start - motion.move_path(way + [(t, SWING_SPEED, 0.0) for t in seq[up:]]) # all queued: no pause between moves + arm_route.move(route) # up exactly as arm_route.goto: queued, blended at wave_out + t0 = time.time() + motion.move_path([(t, SWING_SPEED, 0.0) for t in swings]) # the swings queued: no pause between them + log(f"wave: {SWINGS} swings after {time.time() - t0:.1f} s") if __name__ == "__main__": what = sys.argv[1] if len(sys.argv) > 1 else "check" try: if what == "check": - print([[round(v, 1) for v in t] for t in plan()]) + route, swings = plan() + print([n for n, _ in route], [[round(v, 1) for v in t] for t in swings]) elif what == "run": wave() print("done") diff --git a/robot/motion.py b/robot/motion.py index 9523bb7..cd5c60b 100644 --- a/robot/motion.py +++ b/robot/motion.py @@ -36,7 +36,9 @@ FULL_TURN = (0, 3, 5) # J1, J4, J6: ±360 joints; AT_JOINT_DEG = 0.3 # arrived when every joint is this close ... AT_TCP_MM = 1.0 # ... or the TCP this close (linear moves) POLL_S = 0.1 -EXTRA_S = 10.0 # s allowed on top of 3x the planned move time +EXTRA_S = 10.0 # s allowed on top of the longest a move may take +SLOW_DEG_S = 5.0 # deg/s; long joint moves ran this slow whatever the speed asked + # (measured: 157 deg of J6 in 37 s, 60 deg of J1 in 8.5 s) STILL_S = 2.0 # s without joint motion (and not there) -> the move ended short STILL_DEG = 0.05 # joint change that counts as motion BLIND_S = 1.0 # s without a valid state reply while moving -> stop the arm @@ -104,13 +106,22 @@ def _ready(): raise MotionError("a Cobo π program is running") -def _wait(arrived, planned_s): - """Wait while the arm moves. Big joint moves run slower than speed / travel suggests (measured: 157 deg - of J6 at 10 deg/s took well over 21 s), so the limit is generous; a move that stops short is caught by - STILL_S instead.""" +def _queue_empty(): + """The controller has no motion command left to run (get_motion_state; an odd reply counts as not empty).""" + try: + r = arm.cmd("get_motion_state") + except (ConnectionError, OSError): + return False + return r.get("queue") == 0 and r.get("active_queue", 0) == 0 + + +def _wait(arrived, limit_s, queued=False): + """Wait while the arm moves, at most limit_s. Big moves run far slower than the speed asked (SLOW_DEG_S), so the + limit is generous; a move that stops short is caught by STILL_S instead. `queued`: several moves were sent, so + arrived also needs the controller's queue empty (a route can pass its last pose before, a wave does).""" t0 = last_move = last_seen = time.time() last = None - while time.time() - t0 < 3 * planned_s + EXTRA_S: + while time.time() - t0 < limit_s: if _stopped.is_set(): raise MotionError("stopped") try: @@ -126,12 +137,14 @@ def _wait(arrived, planned_s): last_seen = time.time() if d.get("protective_stop") or d.get("emergency_stop"): raise MotionError("the controller stopped the arm (protective / emergency stop)") - if d.get("inpos") and arrived(d): + if d.get("inpos") and arrived(d) and (not queued or _queue_empty()): return d j = d["joint_actual_position"] if last is None or max(abs(a - b) for a, b in zip(j, last)) > STILL_DEG: last, last_move = j, time.time() elif time.time() - last_move > STILL_S and time.time() - t0 > STILL_S + 1: + if queued: + stop() # the moves still queued must not run on later raise MotionError("the arm stopped before the target") time.sleep(POLL_S) stop() @@ -163,13 +176,15 @@ def move_path(moves, wait=True): for t, _, _ in moves: check(t) _ready() - prev, planned, seq = joints(), 0.0, [] + prev, planned, travel, seq = joints(), 0.0, 0.0, [] for t, speed, tol in moves: t = nearest(t, prev) for i, (a, b) in enumerate(zip(t, prev)): if abs(a - b) > MAX_TRAVEL: raise MotionError(f"J{i + 1} would turn {a - b:+.0f} deg - refused") - planned += max(abs(a - b) for a, b in zip(t, prev)) / JOINT_SPEED[speed] + deg = max(abs(a - b) for a, b in zip(t, prev)) + planned += deg / JOINT_SPEED[speed] + travel += deg seq.append((t, speed, tol)) prev = t _stopped.clear() @@ -187,7 +202,8 @@ def move_path(moves, wait=True): target = seq[-1][0] if not wait: return list(target) - d = _wait(lambda d: max(abs(a - b) for a, b in zip(d["joint_actual_position"], target)) < AT_JOINT_DEG, planned) + d = _wait(lambda d: max(abs(a - b) for a, b in zip(d["joint_actual_position"], target)) < AT_JOINT_DEG, + max(3 * planned, travel / SLOW_DEG_S) + EXTRA_S, queued=len(seq) > 1) return d["joint_actual_position"] @@ -227,7 +243,7 @@ def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=F if not wait: return list(target) d = _wait(lambda d: sum((a - b) ** 2 for a, b in zip(d["actual_position"][:3], target[:3])) ** 0.5 < AT_TCP_MM, - dist / mm_s) + 3 * dist / mm_s + EXTRA_S) return d["actual_position"] diff --git a/tests/test_arm_route.py b/tests/test_arm_route.py index 681bb17..6140b60 100644 --- a/tests/test_arm_route.py +++ b/tests/test_arm_route.py @@ -1,6 +1,7 @@ """Self-check of the pose graph (manipulation/arm_route.py) with a fake arm and toy kinematics (no robot): python tests/test_arm_route.py""" import tempfile +import time from pathlib import Path import numpy as np @@ -41,6 +42,8 @@ class FakeArm: return {"cartPosition": [30 * j[0], 30 * j[1], 30 * j[2]] + list(skills.GRASP_RPY), "errorCode": "0"} if name == "get_data": return {"joint_actual_position": list(self.j), "inpos": True} + if name == "get_motion_state": + return {"queue": 0, "active_queue": 0, "errorCode": "0"} if name == "joint_move": self.sent.append(list(a["jointPosition"])) self.j = list(a["jointPosition"]) @@ -159,6 +162,8 @@ class QueueArm(FakeArm): if name == "stop_program": self.queue.clear() return {"errorCode": "0"} + if name == "get_motion_state": + return {"queue": len(self.queue), "active_queue": len(self.queue), "errorCode": "0"} return super().__call__(name, **a) def moves(self): @@ -197,6 +202,49 @@ try: except motion.MotionError as e: assert str(e) == "stopped" and fake.queue == [] and fake.j == POSES["look"], (e, fake.j) +# a route through its last pose before the end (a wave): the wait ends only with the queue empty, at the end +a_, b_ = POSES["wave_start"], POSES["wave"] +fake = arm.cmd = QueueArm(a_) +motion.move_path([(b_, "slow", 0.0), (a_, "slow", 0.0), (b_, "slow", 0.0), (a_, "slow", 0.0)]) +assert fake.queue == [] and fake.j == a_ and order(fake).count("get_data") >= 4, order(fake) + + +class SlowArm(QueueArm): + """Runs the queued moves at `deg_s` (wall clock), far below the speed asked; `stall_at`: stops there for good.""" + + def __init__(self, joints, deg_s, stall_at=None): + super().__init__(joints) + self.deg_s, self.stall_at, self.t = deg_s, stall_at, None + + def __call__(self, name, **a): + if name == "get_data": + now = time.time() + step, self.t = self.deg_s * (now - (self.t or now)), now + if self.queue and (self.stall_at is None or max(abs(x - y) for x, y in zip(self.j, self.stall_at)) > 1e-6): + t = self.queue[0] + d = np.clip(np.array(t) - self.j, -step, step) + self.j = [float(v) for v in np.array(self.j) + d] + if self.stall_at is not None and max(abs(x - y) for x, y in zip(self.j, self.stall_at)) < step: + self.j = list(self.stall_at) + if np.allclose(self.j, t): + self.queue.pop(0) + return {"joint_actual_position": list(self.j), "inpos": not self.queue} + return super().__call__(name, **a) + + +extra, still = motion.EXTRA_S, motion.STILL_S +motion.EXTRA_S, motion.STILL_S = 0.0, 0.5 +fake = arm.cmd = SlowArm(POSES["look"], deg_s=8.0) # 40 deg asked at 40 deg/s: planned 1 s, takes 5 s +motion.move_path(arm_route.moves([POSES["wave_out"], POSES["wave_start"]])) +assert fake.j == POSES["wave_start"] and fake.queue == [], fake.j +fake = arm.cmd = SlowArm(POSES["look"], deg_s=8.0, stall_at=[0.0, -20, 5, 0, 0, 0]) # stuck on the way: stopped +try: + motion.move_path(arm_route.moves([POSES["wave_out"], POSES["wave_start"]])) + raise AssertionError("waited on a stalled arm") +except motion.MotionError as e: + assert "stopped before" in str(e) and fake.queue == [] and fake.log[-1][0] == "stop_program", (e, fake.log[-1]) +motion.EXTRA_S, motion.STILL_S = extra, still + # the blend's corner cut is checked: a head inside the corner at wave_out refuses the blended route, not the one by one f, g, tip, _ = arm_route._gripper([0.0, 0.0, 0.0] + list(skills.GRASP_RPY)) head["centre"] = np.array([0.0, -330.0, 330.0]) + g # 270+ mm from both moves, 212 from the cut diff --git a/tests/test_wave.py b/tests/test_wave.py index 8ab195f..42337f6 100644 --- a/tests/test_wave.py +++ b/tests/test_wave.py @@ -47,6 +47,8 @@ class FakeArm: return {"cartPosition": [10 * j[0], 10 * j[1], 10 * j[2], 0.0, 0.0, 0.0], "errorCode": "0"} if name == "get_data": return {"joint_actual_position": list(self.j), "inpos": True} + if name == "get_motion_state": + return {"queue": 0, "active_queue": 0, "errorCode": "0"} if name == "joint_move": self.sent.append(list(a["jointPosition"])) self.j = list(a["jointPosition"]) @@ -87,11 +89,15 @@ a.sent.clear() a.j = list(swing) # stopped at wave: back to wave_start, then swings wave.wave() assert a.sent == [top] + [swing, top] * wave.SWINGS, a.sent -names = [] # all moves sent one after another, no poll -arm.cmd = lambda name, **k: (names.append(name), a(name, **k))[1] # between them +names = [] # the way up as arm_route.goto sends it, then the +arm.cmd = lambda name, **k: (names.append((name, k.get("speed"), k.get("tol"))), a(name, **k))[1] # swings, each queued a.j = list(LOOK) wave.wave() -assert [n for n in names if n in ("joint_move", "get_data")][:3 + 2 * wave.SWINGS] == ["joint_move"] * (2 + 2 * wave.SWINGS) + ["get_data"], names +sent = [(n, v, t) for n, v, t in names if n in ("joint_move", "get_data")] +route, swing_s = motion.JOINT_SPEED[arm_route.SPEED], motion.JOINT_SPEED[wave.SWING_SPEED] +assert sent[:3] == [("joint_move", route, arm_route.TOL), ("joint_move", route, None), ("get_data", None, None)], sent +assert sent[3:4 + 2 * wave.SWINGS] == [("joint_move", swing_s, None)] * 2 * wave.SWINGS + [("get_data", None, None)], sent +assert wave.SWING_SPEED == "normal" arm.cmd = a a.j = list(top) a.sent.clear()