From a16067c2fdbf607d05cb7a7e6c247d2d50582974 Mon Sep 17 00:00:00 2001 From: Cutshion Date: Thu, 19 Nov 2026 16:33:17 +0900 Subject: [PATCH] Added arm speed and saved poses Co-Authored-By: Claude Opus 5.5 --- api/server.py | 66 ++++++++++++++++++++++++++++++++---- manipulation/arm_route.py | 16 +++++++++ robot/motion.py | 71 +++++++++++++++++++++++++++++++++++++-- 3 files changed, 143 insertions(+), 10 deletions(-) diff --git a/api/server.py b/api/server.py index c4c0b97..c0401e6 100644 --- a/api/server.py +++ b/api/server.py @@ -882,7 +882,8 @@ AGV_WEB = "http://192.168.10.10:9001" class JogBody(BaseModel): - axis: str = Field(examples=["head_yaw"], description="base_drive, base_turn, lift, waist, head_yaw, head_pitch, j1..j6") + axis: str = Field(examples=["head_yaw"], description="base_drive, base_turn, lift, waist, head_yaw, head_pitch, j1..j6, " + "tcp_x, tcp_y, tcp_z (the hand in a straight line, arm base frame)") direction: int = Field(1, description="+1 or -1") speed: float = Field(0.5, ge=0.05, le=1.0, description="0..1 of the axis' top speed") @@ -1457,9 +1458,48 @@ def _motion(fn, *args, **kw): raise HTTPException(409, str(e)) -@app.get("/arm/poses", tags=["arm"], summary="The taught poses of the pose graph (deg)") +class SpeedBody(BaseModel): + percent: float = Field(examples=[80], description="% of every arm speed as tuned (100)") + + +def _speed_reply(): + lo, hi = motion.SPEED_RANGE + return {"percent": motion.speed_percent(), "min": lo, "max": hi} + + +@app.get("/arm/speed", tags=["arm"], summary="The arm speed %: every arm move (poses, wave, picks, jog) runs at it") +def arm_speed(): + return _speed_reply() + + +@app.post("/arm/speed", tags=["arm"], summary="Set the arm speed % (kept over restarts)") +def arm_speed_set(body: SpeedBody): + try: + motion.set_speed_percent(body.percent) + except ValueError as e: + raise HTTPException(400, str(e)) + return _speed_reply() + + +@app.get("/arm/poses", tags=["arm"], summary="The poses the arm can go to (deg): the pose graph's and the saved ones") def arm_poses(): - return arm_route.graph() + return {**arm_route.graph(), **motion.saved_poses()} + + +@app.get("/arm/poses/saved", tags=["arm"], summary="Only the poses saved from the app (deg)") +def arm_poses_saved(): + return motion.saved_poses() + + +@app.delete("/arm/poses/{name}", tags=["arm"], summary="Delete a pose saved from the app") +def arm_pose_delete(name: str): + if name in motion.poses(): + raise HTTPException(409, f"{name} is one of Lumi's own poses") + try: + motion.delete_pose(name) + except KeyError: + raise HTTPException(404, f"no saved pose {name}") + return {"ok": True} @app.post("/arm/pose", tags=["arm"], summary="Go to a named pose along the pose graph (every joint move checked first; " @@ -1467,12 +1507,16 @@ def arm_poses(): def arm_pose(body: PoseBody): if body.speed not in motion.JOINT_SPEED: raise HTTPException(400, f"speed: {', '.join(motion.JOINT_SPEED)}") - if body.name not in arm_route.graph(): + saved = body.name in motion.saved_poses() + if body.name not in arm_route.graph() and not saved: raise HTTPException(404, f"no pose {body.name}") robot_free(manual=True) _posing.set() try: - return {"ok": True, "route": arm_route.goto(body.name, gripper.state()["holding"], speed=body.speed), + holding = gripper.state()["holding"] + route = (arm_route.goto_saved(body.name, holding) if saved + else arm_route.goto(body.name, holding, speed=body.speed)) + return {"ok": True, "route": route, "joints": motion.joints()} except arm_route.RouteError as e: raise HTTPException(409, e.args[0]) @@ -1489,9 +1533,17 @@ def arm_line(body: LineBody): return _motion(motion.move_linear, delta=[body.dx, body.dy, body.dz], speed=body.speed) -@app.post("/arm/teach", tags=["arm"], summary="Save the arm's current joints as a named pose") +@app.post("/arm/teach", tags=["arm"], summary="Save the arm's current joints as a new pose (not one of Lumi's own)") def arm_teach(body: NameBody): - return _motion(motion.teach, body.name) + name = body.name.strip() + if not re.fullmatch(rf"[A-Za-z0-9_-]{{1,{motion.SAVED_NAME_MAX}}}", name): + raise HTTPException(400, f"name: 1 to {motion.SAVED_NAME_MAX} letters, digits, _ or -") + if name in motion.poses(): + raise HTTPException(409, f"{name} is one of Lumi's own poses. Choose another name.") + try: + return {"ok": True, "name": name, "joints": motion.save_pose(name)} + except motion.MotionError as e: + raise HTTPException(409, str(e)) @app.get("/objects", tags=["objects"], diff --git a/manipulation/arm_route.py b/manipulation/arm_route.py index ba8cff9..e6d63ab 100644 --- a/manipulation/arm_route.py +++ b/manipulation/arm_route.py @@ -448,6 +448,22 @@ def goto(target, holding=False, leaf=False, speed=None): return [n for n, _ in seq] +def goto_saved(name, holding=False): + """To a pose saved from the app (motion.saved_poses): along the graph to the graph pose nearest it, then one + checked joint move into it (an arm away from the graph joins it first, as goto). Returns the poses passed.""" + target = motion.saved_poses()[name] + now = skills._joints() + if _deg(now, target) <= EXACT_DEG: + return [] + nodes = graph(holding) + anchor = min(nodes, key=lambda n: _deg(target, nodes[n])) + seq = plan(anchor, holding, now=now) + seq = seq + [(name, check_moves(seq[-1][1] if seq else now, [target], holding)[0])] + log(f"arm route to {name} (saved, from {anchor}): {' -> '.join(n for n, _ in seq)}, checked") + move(seq, None, holding) + return [n for n, _ in seq] + + def start_program(name): """Start a Cobo π program, only from `look`. It ends wherever it was taught to end: the next move joins the graph from there (or is refused). RouteError to refuse.""" diff --git a/robot/motion.py b/robot/motion.py index 0b63ffa..0c749e2 100644 --- a/robot/motion.py +++ b/robot/motion.py @@ -50,7 +50,46 @@ BLIND_S = 3.0 # s without a valid state r SETTLE_S = 0.3 # s the arm stands at a pose before the next move (estimate; # going straight on shook the whole robot, 2026-10-21) +SPEED_FILE = ROOT / "data" / "arm_speed.json" # the owner's arm speed % (the app's slider), kept over restarts +SAVED_FILE = ROOT / "data" / "arm_saved_poses.json" # poses saved from the app; never part of the pose graph +SPEED_RANGE = (10, 150) # % of every speed above +JOINT_MAX_DEG_S = 60.0 # deg/s: the Cobo π joint speed limit; route and swing run at it +LINEAR_MAX_MM_S = 150.0 # mm/s: the most a straight move runs at any % +SAVED_NAME_MAX = 24 + _stopped = threading.Event() # set by stop(): a waiting move gives up +_speed = None # cached SPEED_FILE + + +def speed_percent(): + """The owner's arm speed, % of JOINT_SPEED / LINEAR_SPEED (100: as tuned).""" + global _speed + if _speed is None: + try: + _speed = float(json.loads(SPEED_FILE.read_text())["percent"]) + except (OSError, ValueError, KeyError, TypeError): + _speed = 100.0 + return _speed + + +def set_speed_percent(percent): + """Set and keep the arm speed %; ValueError outside SPEED_RANGE.""" + global _speed + lo, hi = SPEED_RANGE + if not lo <= percent <= hi: + raise ValueError(f"speed: {lo} to {hi} %") + _speed = float(round(percent)) + SPEED_FILE.write_text(json.dumps({"percent": _speed})) + return _speed + + +def joint_deg_s(speed): + """deg/s of a named joint speed at the owner's %, never past the controller's limit.""" + return min(JOINT_MAX_DEG_S, JOINT_SPEED[speed] * speed_percent() / 100) + + +def linear_mm_s(speed): + return min(LINEAR_MAX_MM_S, LINEAR_SPEED[speed] * speed_percent() / 100) class MotionError(RuntimeError): @@ -93,6 +132,32 @@ def teach(name): return j +def saved_poses(): + """{name: joints} of the poses saved from the app.""" + try: + return json.loads(SAVED_FILE.read_text()) + except (OSError, ValueError): + return {} + + +def save_pose(name): + """Save the current joints as the app pose `name` (never a taught pose's name).""" + if name in poses(): + raise MotionError(f"{name} is one of Lumi's own poses. Choose another name.") + check(j := [round(v, 2) for v in joints()]) + saved = saved_poses() + saved[name] = j + SAVED_FILE.write_text(json.dumps(saved, indent=1)) + return j + + +def delete_pose(name): + """Delete the app pose `name`; KeyError when there is none.""" + saved = saved_poses() + del saved[name] + SAVED_FILE.write_text(json.dumps(saved, indent=1)) + + def check(target): """Raise MotionError if a joint target is out of range (with LIMIT_MARGIN).""" if len(target) != 6: @@ -192,7 +257,7 @@ def move_path(moves, wait=True, queued=False): for k, (t, speed, deg) in enumerate(seq): if k and not queued and _stopped.wait(SETTLE_S): raise MotionError("stopped") - deg_s = JOINT_SPEED[speed] + deg_s = joint_deg_s(speed) r = arm.cmd("joint_move", relFlag=0, jointPosition=list(t), speed=deg_s, accel=deg_s * SPEED_ACCEL_FACTOR.get(speed, JOINT_ACCEL_FACTOR)) if _stopped.is_set(): # STOP pressed while sending: stop again, after this move stop() @@ -220,7 +285,7 @@ def go(name, speed="slow", wait=True): return move_joints(p[name], speed, wait) -def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=False): +def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=False, mm_s=None): """Straight TCP move to `target` [x, y, z mm, rx, ry, rz deg] or by `delta` (dx, dy, dz mm), base frame. The end pose is checked with the controller's IK first. `path_checked`: the caller checked the whole line in small steps (fetch._line_rows), so a big J1 / J4 / J6 turn over it is a real one, not another IK branch.""" @@ -240,7 +305,7 @@ def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=F if abs(end_j[i] - now_j[i]) > MAX_FLIP: raise MotionError(f"J{i + 1} would turn {end_j[i] - now_j[i]:+.0f} deg - refused") _ready() - mm_s = LINEAR_SPEED[speed] + mm_s = linear_mm_s(speed) if mm_s is None else mm_s dist = sum((a - b) ** 2 for a, b in zip(target[:3], now_p[:3])) ** 0.5 _stopped.clear() r = arm.cmd("moveL", relFlag=0, cartPosition=list(target), speed=mm_s, accel=mm_s * ACCEL_FACTOR)