From a50fdc9c0d9176aefa015d687edd51b4a3f4d70c Mon Sep 17 00:00:00 2001 From: Cutshion Date: Wed, 21 Oct 2026 16:54:22 +0900 Subject: [PATCH] Arm moves only along checked poses; any marker name of the active map Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- api/dashboard.html | 2 +- api/server.py | 54 ++++---- assistant/brain.py | 63 +++++++-- assistant/lumi.py | 58 ++++++--- assistant/steps.py | 28 ++-- assistant/wording.py | 63 ++++++++- manipulation/arm_route.py | 264 ++++++++++++++++++++++++++++++++++++++ manipulation/skills.py | 13 +- manipulation/wave.py | 109 ++++------------ robot/agv.py | 14 ++ robot/arm.py | 17 +-- robot/motion.py | 4 +- tasks/fetch.py | 103 +++++++-------- tests/test_arm_route.py | 140 ++++++++++++++++++++ tests/test_fetch.py | 54 ++++---- tests/test_map_names.py | 118 +++++++++++++++++ tests/test_wave.py | 26 ++-- tools/arm_program.py | 22 +++- 19 files changed, 880 insertions(+), 277 deletions(-) create mode 100644 manipulation/arm_route.py create mode 100644 tests/test_arm_route.py create mode 100644 tests/test_map_names.py diff --git a/README.md b/README.md index 6f3709a..afc0538 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Each part has its own controller on the robot's network; this software talks to - **Talk in English and Korean.** Wake it by name ("Lumi", "Hi Lumi", "루미야") from anywhere; it finds who called by voice direction and camera and answers in English or Korean. Follow-up questions keep the topic, and it can be interrupted while it speaks. - **Answer questions**, from its own knowledge and from the internet: date and time, weather, Wikipedia, news. - **Greet people.** In Greeter mode it greets a person who stops in front of it and asks how it can help. -- **Go to places.** "Come here" brings it to about 1 m in front of the caller; "go to p2", "go home" to a marker on the office map. In Patrol mode it drives its round and stops only for a person in its path. It goes to the charger on low battery. +- **Go to places.** "Come here" brings it to about 1 m in front of the caller; "go to p2", "go home", "go to table front" to any marker on the active map, its names said in English, Korean or mixed. In Patrol mode it drives its round and stops only for a person in its path. It goes to the charger on low battery. - **Pick up a cup and put it back.** It finds the cup with the torso camera, plans the grasp, picks it, can drive holding it, and puts it back where it was. - **Stop on "stop" / "멈춰"**: the base, the arm and its own speech. @@ -132,7 +132,7 @@ lumi-wave/ run with the venv: .venv/bin/python /Speed40 %

Programs

-
+

Gripper

–sensor –
diff --git a/api/server.py b/api/server.py index d3b34c4..ce81f11 100644 --- a/api/server.py +++ b/api/server.py @@ -37,6 +37,7 @@ from robot import gripper from robot import motion from vision import objects from robot import head +from manipulation import arm_route from manipulation import skills from manipulation import wave from api.control import jogger @@ -99,6 +100,7 @@ def start_assistant(no_arm=False, no_drive=False): BUSY_FILE = Path("/dev/shm/lumi_busy.json") # written by lumi.py: {"busy": skill | follow | drive | wave | null} BUSY_MSG = "Busy with a task. Pause or stop it first." _waving = threading.Event() # /arm/wave runs here +_posing = threading.Event() # /arm/pose, /arm/tuck run here def running_now(): @@ -115,6 +117,8 @@ def running_now(): return "route" if _waving.is_set(): return "wave" + if _posing.is_set(): + return "arm" if lumi: try: what = json.loads(BUSY_FILE.read_text()).get("busy") @@ -648,7 +652,7 @@ class OnBody(BaseModel): class ProgramBody(BaseModel): - program: str = Field(examples=["hand_shaking.jks"]) + program: str = Field(examples=["arm_reach.jks"]) @app.post("/jog", tags=["control"], summary="Hold-to-move: call every ~150 ms while a button is held") @@ -738,27 +742,28 @@ def arm_enable(body: OnBody): return arm.cmd("enable_robot" if body.on else "disable_robot") -@app.post("/arm/run", tags=["arm"], summary="Run a Cobo π program (.jks) once; returns at once") +@app.post("/arm/run", tags=["arm"], summary="Run a Cobo π program (.jks) once, only from look; returns at once") def arm_run(body: ProgramBody): robot_free(manual=True) if not arm.ready(): raise HTTPException(409, "arm not ready: power/enable off, or a program is running") try: - arm.start(body.program) + arm_route.start_program(body.program) + except arm_route.RouteError as e: + raise HTTPException(409, e.args[0]) except RuntimeError as e: raise HTTPException(400, str(e)) return {"ok": True, "program": body.program} -@app.post("/arm/tuck", tags=["arm"], summary="Fold the arm beside the column (slow), e.g. before driving") +@app.post("/arm/tuck", tags=["arm"], summary="Fold the arm beside the column along the pose graph (slow)") def arm_tuck(): - return arm_pose(PoseBody(name="tuck", wait=False)) + return arm_pose(PoseBody(name="tuck")) class PoseBody(BaseModel): - name: str = Field(examples=["ready"], description="tuck or a pose taught with /arm/teach") - speed: str = Field("slow", description="slow / normal") - wait: bool = Field(True, description="return when the arm is there (STOP ends the wait)") + name: str = Field(examples=["look"], description="a pose of the pose graph (manipulation/arm_route.py)") + speed: str = Field(arm_route.SPEED, description="slow / normal") class LineBody(BaseModel): @@ -785,20 +790,24 @@ def arm_poses(): return motion.poses() -@app.post("/arm/pose", tags=["arm"], summary="Move to a named pose (checked joint move, slow by default)") +@app.post("/arm/pose", tags=["arm"], summary="Go to a named pose along the pose graph (every joint move checked first; " + "returns when there)") 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 motion.poses(): raise HTTPException(404, f"no pose {body.name}") - from tasks import fetch - j = motion.joints() - if not skills.joint_move_ok(j, motion.poses()[body.name]): - raise HTTPException(409, f"On the way to {body.name} the gripper would go lower than where it starts and ends: " - "move it up first.") - if gripper.state()["holding"] and (tilt := fetch.tilt_along(body.name)) > fetch.MAX_TILT_DEG: - raise HTTPException(409, f"Holding something: on the way to {body.name} it would tilt {tilt:.0f}°.") - return _motion(motion.go, body.name, body.speed, body.wait) + robot_free(manual=True) + _posing.set() + try: + return {"ok": True, "route": arm_route.goto(body.name, gripper.state()["holding"], speed=body.speed), + "joints": motion.joints()} + except arm_route.RouteError as e: + raise HTTPException(409, e.args[0]) + except motion.MotionError as e: + raise HTTPException(409, str(e)) + finally: + _posing.clear() @app.post("/arm/line", tags=["arm"], summary="Straight TCP move by dx / dy / dz mm (IK-checked first)") @@ -868,7 +877,7 @@ def _run_skill(name, fn, *args, **kw): try: st.update(status="done", result=fn(*args, **kw)) except skills.SkillError as e: - st.update(status="refused", reason=str(e)) + st.update(status="refused", reason=e.args[0]) except motion.MotionError as e: st.update(status="stopped", reason=str(e)) except Exception as e: @@ -977,18 +986,19 @@ def task_parse(body: ParseBody): got, unread, by = steps.read(body.text, markers, llm=False) if unread and got and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)): got, unread, by = steps.read(body.text, markers) # clearly several steps: the LLM may read it - if got and unread and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)): + problem = unread and brain.place_problem(" ".join(unread), markers) # "go to p12", "go to booth" (two) + if problem or got and unread and ({s["do"] for s in got} & steps.MISSION_ONLY or steps.is_mission(got)): return {"action": None, "task": None, "sentence": "–", "read_by": by, - "problems": [f"I didn't understand: {', '.join(unread)}"]} + "problems": [problem[0] if problem else f"I didn't understand: {', '.join(unread)}"]} if got and steps.is_mission(got): return {"action": "steps", "steps": got, "lang": "ko" if brain.HANGUL.search(body.text) else "en", "sender": steps.sender(body.text), "read_by": by, **_steps_said(got, markers)} if fetch.check_hand(): # the camera sees the hand; a stale "holding" is forgotten return _held_parse(body, markers) - if body.text.strip() and got and not unread and {s["do"] for s in got} <= {"receive", "arm"}: + if body.text.strip() and got and not unread and {s["do"] for s in got} <= {"receive", "arm", "go"}: return {"action": "steps", "steps": got, "lang": "ko" if brain.HANGUL.search(body.text) else "en", # "take this - "sender": steps.sender(body.text), "read_by": by, **_steps_said(got, markers)} # from my hand", "open your hand" + "sender": steps.sender(body.text), "read_by": by, **_steps_said(got, markers)} # from my hand", "open your hand", "go to stage" if brain.place_on(body.text) and not brain._mentions(body.text, markers).get("object"): # "put it on the table" return {"action": None, "task": None, "sentence": "–", "problems": ["My hand is empty, I'm not holding anything."]} fields, read_by = brain.fetch_from_text(body.text, markers) if body.text.strip() else ({}, "rules") diff --git a/assistant/brain.py b/assistant/brain.py index 7c5b28d..44e3075 100644 --- a/assistant/brain.py +++ b/assistant/brain.py @@ -473,8 +473,8 @@ INTENTS = [ # (action, pattern) checked in order on what the visitor said ("come", r"\bcome (?:back )?(here|to me|closer|over here|over)\b|\bcome\b.*\bme\b|이리 ?(?:돌아 ?)?와|여기로 ?(?:돌아 ?)?와|가까이 ?와|" r"나한테 ?(?:돌아 ?)?와"), ("go_home", r"\bgo (back )?(home|to (the |your )?(dock(?!2)|charger|charging))|\bgo charge|충전하러|집(?:에|으로) ?가|충전기로"), - ("go_point", r"\b(?:go|drive|move|head|come|return)(?: back)? to (?:the )?(?:point |marker )?([a-z]+\d*)\b|(\d+)\s*번\s*(?:으로|포인트)" # after _norm: - r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z]+\d*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘": + ("go_point", r"\b(?:go|drive|move|head|come|return)(?: back)? to (?:the )?(?:point |marker )?([a-z][a-z0-9_]*)\b|(\d+)\s*번\s*(?:으로|포인트)" # after _norm: + r"|^\W*(?:(?:루미야?|lumi|hey lumi)\W*)?(?:좀\s*)?(?:point\s+)?([a-z][a-z0-9_]*)\s*(?:으로|로|에)\s*(?:좀\s*)?" # "p3로 가 줘": r"(?:가|와|이동해|돌아가|돌아 ?와)" # all of it r"(?:\s*줘요?|\s*주세요|요|자|줄래)?\s*[.!?]*$"), ("sing", r"\bsing\b|\ba song\b|노래"), @@ -532,7 +532,7 @@ CALLING = re.compile(r"^\W*(?:(?:hey|hi|okay|ok|so|um+|uh+|alright|please|well|n def intent(text, markers=()): """(action, target) for clear requests, or None. Backs up the LLM's ACTION line.""" - t = _norm(text) # "point five" -> "point 5" + t = _norm(text, markers) # "point five" -> "point 5" asks = re.search(r"^\s*(how(?! about (?:you|we) (?!\w+ing\b)\w)|why(?! don'?t you\b)|what if)\b|\b(how do you|how can you|can you carry|are you able)\b|" r"\b(can|could) you (pick( up)?|lift|hold|grab|take) (a|an|any)\b|" # "can you pick up a bottle?" r"^\s*(what|when|which|at what|do you|does|is it|are you)\b|몇|언제|얼마|" # "at what level do you go back?" @@ -633,9 +633,10 @@ _PLACE_WORD = rf"(?:point|marker|포인트)\s*(\d+)|(? "p3", "point one" -> "p1").""" - t = wording.norm(text) +def _norm(text, markers=()): + """Lower case, marker names and numbers as written (wording.py: "피쓰리" -> "p3", "point one" -> "p1", with the + map's markers "table front" -> "table_front").""" + t = wording.norm(text, markers) for word, digit in NUMBER_WORDS.items(): # "one of them" -> "1 of them" t = re.sub(rf"\b{word}\b", digit, t) return t @@ -664,7 +665,7 @@ def _as_place(name): def _mentions(text, markers): """What the words name: {"object", "colour", "prefer", "source", "dest", "finish"}, only the fields mentioned. "object" / "source" / "dest" is None when the word is there but unknown.""" - t, out = _norm(text), {} + t, out = _norm(text, markers), {} objs = [m for m in re.finditer(rf"(?:({_COL})\s*)?(? "table front").""" + return re.sub(r"[_-]+", " ", name) + + +def no_place_say(word, markers): + """(en, ko): this map has no place called `word`, and the places it has.""" + known = ", ".join(place_said(m) for m in markers) or "none" + return (f"I don't have a place called {place_said(word)} on this map. I know: {known}.", + f"이 지도에는 {place_said(word)}라는 곳이 없어요. 제가 아는 곳은 {known}이에요.") + + +_GO_WORD = re.compile(r"\b(?:go|drive|move|head|come|return|bring it|take it)(?: back)? to (?:the )?(?:point |marker )?" + r"([a-z][a-z0-9_]*)\b|(? 1: + names = [place_said(n) for n in close] + return (f"Did you mean {', '.join(names[:-1])} or {names[-1]}?", + f"{', '.join(names[:-1])} 아니면 {names[-1]} 중 어디 말씀이세요?") + if re.fullmatch(r"p\d+", word) and not close: + return no_place_say(word, markers) + return None + + def fetch_problems(task): """'object' / 'place' (source) / 'dest': what is still missing or unknown in a task.""" return [p for p, f in (("object", "object"), ("place", "source"), ("dest", "dest")) if task.get(f) is None] @@ -963,7 +999,7 @@ def hand_request(text, holding, b=None, markers=(), whole=True): hand while holding; None for anything else (a pick from the table, a mission of several steps, a question). holding: something is in the hand now. "give me the cup" with the hand empty is a pick and give (a mission). whole: the words are a whole command (not one clause of a mission): several steps in it are the mission reader's.""" - t = CALLING.sub("", _norm(text).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down" + t = CALLING.sub("", _norm(text, markers).strip()) # "루미야, 이리 줘", "혹시 저 줘요", "um, put it down" if HAND_Q.search(t) or re.search(r"\b(?:don'?t|do not|never) (?:\w+ )?(?:give|hand|pass|put|place|take|hold|drop|set|" r"leave|let)\b|지 ?마", t) or MULTI.search(t): return None # "can you give things to people?", "don't give it to him" @@ -1032,7 +1068,7 @@ def parse_correction(text, task, markers=(), field=None): field: the field a bare answer is about ("source" / "dest"), when Lumi just asked for it ("p2" -> that field).""" m, task = _mentions(text, markers), dict(task) if field in ("source", "dest") and not {"source", "dest"} & set(m): - p = re.search(_place_re(markers), _norm(text)) + p = re.search(_place_re(markers), _norm(text, markers)) if p: m[field] = _as_place(_resolve(p, markers)) changed = [k for k, v in m.items() if task.get(k) != v and not (k == "colour" and "object" not in m)] @@ -1526,11 +1562,12 @@ class Brain: action = "none" say = None if action == "go_to": - target = next((mk for mk in markers if mk.lower() == target.lower()), None) + said, target = target, next((mk for mk in markers if mk.lower() == target.lower()), None) + if not target and said.lower() not in ("", "none"): + say = place_problem(f"go to {said}", markers) or no_place_say(said, markers) # "go_to kitchen" if target and not named_place(text, target, markers): target = None # "take me to the meeting room" -> p1: a guess, not driven - say = ("I don't know that place. I can go to: " + ", ".join(markers) + ".", - "그 장소는 제가 몰라요. 제가 갈 수 있는 곳은 " + ", ".join(markers) + "이에요.") + say = no_place_say("that", markers) action = "go_to" if target else "none" bare = CALLING.sub("", text) if action in MOTIONS and (QUESTION_START.search(bare) and not (action in ("give", "receive") and diff --git a/assistant/lumi.py b/assistant/lumi.py index a807c8d..d9b352a 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -86,6 +86,7 @@ from robot import motion from audio import mouth from audio import sing from robot import nav +from manipulation import arm_route from manipulation import skills from manipulation import wave as wave_mod from assistant import web @@ -662,7 +663,6 @@ class Lumi: def __init__(self, args): self.a = args self.brain = Brain() - self.markers = agv.markers() self.current = None # the track we are talking with self.mission_hold = None # "talk" / "safety": a mission is halted for someone (mission_talk) self.asked_go_on = False # "Can I go on with my task?" was asked @@ -691,6 +691,15 @@ class Lumi: self.vision = None if args.no_camera else Vision(args.camera) log(f"markers: {self.markers}") + @property + def markers(self): + """The active map's marker names (agv.known_markers: a new map is seen within seconds).""" + return self._markers if getattr(self, "_markers", None) is not None else agv.known_markers() + + @markers.setter + def markers(self, names): # a fixed list (self-checks) + self._markers = names + # ---------- actions ---------- def turn_head(self, yaw=None, pitch=None): def run(): @@ -1318,8 +1327,9 @@ class Lumi: got, unread, by = read if unread: log(f" mission: unread {unread} ({by})") - self.fetch_say(f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.", - "죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요.") + problem = brain_mod.place_problem(" ".join(unread), self.markers) # "go to booth" with two booths + self.fetch_say(*(problem or (f"Sorry, I didn't understand: {', '.join(unread)}. Please say it again.", + "죄송해요, 일부를 이해하지 못했어요. 다시 말씀해 주세요."))) self.keep_listening() return True log(f" mission ({by}): {got}") @@ -1501,7 +1511,7 @@ class Lumi: mouth.say(done[0] if en else done[1]) except skills.SkillError as e: log(f" {action} {target}: {e}") - mouth.say(str(e) if en else "죄송해요, 지금은 할 수 없어요.") + mouth.say(e.args[0] if en else e.args[1] if len(e.args) > 1 else "죄송해요, 지금은 할 수 없어요.") except (motion.MotionError, ConnectionError, OSError) as e: log(f" {action} {target} stopped: {e}") mouth.say("I stopped my arm." if en else "팔을 멈췄어요.") @@ -1510,19 +1520,26 @@ class Lumi: self.keep_listening() def arm_pose(self, target): - """'reach': the Cobo π program ARM_REACH_PROGRAM (record it once); 'fold': the folded drive pose; - 'open' / 'close': the gripper.""" + """'reach': the Cobo π program ARM_REACH_PROGRAM (record it once), only from look; 'fold': tuck along the + pose graph (arm_route, checked first, moved in the background); 'open' / 'close': the gripper. True when + started, False when not learned, None when refused (the reason is said).""" if target in ("open", "close"): st = safe(gripper.open_ if target == "open" else gripper.close) log(f" gripper {target}: {st}") return st is not None - if target == "fold": - return safe(lambda: motion.go("tuck", wait=False)) is not None try: - arm.start(ARM_REACH_PROGRAM) + if target == "fold": + seq = arm_route.plan("tuck", holding=self.fetch_status() == "holding") + threading.Thread(target=safe, args=(arm_route.move, seq), daemon=True).start() + else: + arm_route.start_program(ARM_REACH_PROGRAM) return True + except arm_route.RouteError as e: + log(f" arm {target} refused: {e.args[0]}") + self.fetch_say(*e.args) + return None except Exception as e: - log(f" arm reach: {e} (record {ARM_REACH_PROGRAM} in Cobo pi)") + log(f" arm {target}: {e}" + (f" (record {ARM_REACH_PROGRAM} in Cobo pi)" if target == "reach" else "")) return False # ---------- dashboard commands, trips ---------- @@ -1893,12 +1910,22 @@ class Lumi: mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.") return self.start_trip(place) - mouth.say(f"Okay, I'm going to {place}." if en else f"네, {place}로 갈게요.") + name = brain_mod.place_said(place) + mouth.say(f"Okay, I'm going to {name}." if en else f"네, {name}로 갈게요.") self.keep_listening() def quick_command(self, text): """A command the keyword rules recognise for sure: confirm with a ready phrase and act, no LLM wait.""" rule = brain_mod.intent(text, self.markers) + if not rule and brain_mod.place_problem(text, self.markers): + agv.known_markers(fresh=True) # not on the list: the map may have just changed + rule = brain_mod.intent(text, self.markers) + problem = not rule and brain_mod.place_problem(text, self.markers) + if problem: + log(f" place: {problem[0]}") + mouth.say(problem[0] if self.lang == "en" else problem[1]) + self.keep_listening() + return True if rule and rule[0] in MOVING_ACTIONS and self.mission_running(): self.fetch_say("Sorry, I'm on a task right now. I can help you when I've finished.", "죄송해요, 지금 다른 일을 하고 있어요. 끝나면 도와드릴게요.") @@ -1969,15 +1996,16 @@ class Lumi: done = {"open": ("Okay, opening my hand.", "네, 손을 펼게요."), "close": ("Okay, closing my hand.", "네, 손을 쥘게요.")} if target in done: mouth.say(done[target][0] if en else done[target][1]) - if self.arm_pose(target): + ok = self.arm_pose(target) + if ok: if target not in done: mouth.say("Here you go." if en else "여기요.") - else: + elif ok is False: mouth.say("Sorry, I haven't learned that arm movement yet." if en else "죄송해요, 그 팔 동작은 아직 못 배웠어요.") return True self.start_trip(target) # go_to: start driving, then say so - name = "my charging dock" if target == "home" else target - mouth.say(f"Okay, I'm going to {name}." if en else ("네, 충전소로 갈게요." if target == "home" else f"네, {target}로 갈게요.")) + name = "my charging dock" if target == "home" else brain_mod.place_said(target) + mouth.say(f"Okay, I'm going to {name}." if en else ("네, 충전소로 갈게요." if target == "home" else f"네, {name}로 갈게요.")) self.current, self.voice_until = None, 0.0 return True diff --git a/assistant/steps.py b/assistant/steps.py index b05d0f0..67cfcac 100644 --- a/assistant/steps.py +++ b/assistant/steps.py @@ -44,10 +44,10 @@ _SPLIT = re.compile(r"\s*(?:,|;|\.(?=\s|$)|\band then\b|\bthen\b|\band\b|\bafter _SPLIT_KO = re.compile(r"(?<=[가-힣](?:고|서))(? "p3로", "half a meter" -> - "0.5 m", "오십 센치" -> "0.5 m"), titles without their dot ("Mr. Park").""" - t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text)) + " ") + "0.5 m", "오십 센치" -> "0.5 m", "table front" -> "table_front" on a map with it), titles without their dot.""" + t = re.sub(r"\b(mr|mrs|ms|dr|prof)\. ", r"\1 ", wording.durations(wording.norm(text, markers)) + " ") return re.sub(r"\b(?:take|pick up|pick|grab)\s?(?:해서|하고)", "집어서", t).strip() # "컵 take해서": mixed @@ -59,6 +59,9 @@ def _place(word, markers): exact = next((mk for mk in markers if mk.lower() == w or mk.lower() == w.replace(" ", "")), None) if exact: return exact + close = wording.close_names(w, markers) if re.fullmatch(r"[a-z][a-z0-9_ ]*", w) else [] + if len(close) == 1: + return close[0] # a whisper slip of one name ("stagee로 가") m = re.fullmatch(brain._place_re(markers), word.strip()) if m: return brain._resolve(m, markers) @@ -97,10 +100,9 @@ def _go(c, markers): if m: to = _places(m.group(1), markers) return to and {"do": "go", "to": to if len(to) > 1 else to[0]} - m = re.fullmatch(r"(?:go|drive|head) (?:the )?(p\d+|final|dock2|exit)", c) # whisper drops the "to" - if m: - to = _places(m.group(1), markers) - return to and {"do": "go", "to": to[0]} + m = re.fullmatch(r"(?:go|drive|head) (?:the )?([a-z][a-z0-9_]*)", c) # whisper drops the "to" + if m and m.group(1) not in ("home", "here") and (to := _places(m.group(1), markers)): + return {"do": "go", "to": to[0]} if re.fullmatch(r"go (?:home )?(?:to )?charge(?: yourself)?|충전하러 (?:집으로 )?가", c): return {"do": "go", "to": "home"} if "home" in markers else None m = re.fullmatch(r"(?:go|drive|head|come|return)(?: back)? (home|here)|come back", c) @@ -532,9 +534,9 @@ def _person(c, markers): if m and _places(m.group(1), markers) and len(_places(m.group(1), markers)) == 1: return [{"do": "go", "to": _places(m.group(1), markers)[0]}, {"do": "place", "on": { "name": brain.SUPPORTS[m.group(3)], "colour": brain.COLOURS.get(m.group(2)), "side": None}}] - m = re.fullmatch(r"(p\d+|final|dock2|exit|home) (?:테이블|책상|식탁)(?: 위)?에 (?:놔|놓아|올려놔)", c) - if m: - return [{"do": "go", "to": m.group(1)}, {"do": "place", "on": {"name": "dining table", "colour": None, + m = re.fullmatch(r"([a-z][a-z0-9_]*) (?:테이블|책상|식탁)(?: 위)?에 (?:놔|놓아|올려놔)", c) + if m and (to := _places(m.group(1), markers)) and to != ["here"]: + return [{"do": "go", "to": to[0]}, {"do": "place", "on": {"name": "dining table", "colour": None, "side": None}}] if re.fullmatch(r"\S+ (?:없으니까|없어서|없대|없네)|거기로 갈게|내가 거기로 갈게|거기 있을게", c): return [] @@ -727,7 +729,7 @@ _INTERJECTION = re.compile(r"^(?:(?:(?:oh|ah|um|uh) )?(?:wait(?: wait)*|hold on| def rules(text, markers=()): """(steps, unread clauses). Steps are merged where two clauses mean one ("look for the table" + "put it there").""" cut, says = _cut_says(text) - t = _protect_lists(_norm(cut), markers) + t = _protect_lists(_norm(cut, markers), markers) t = _INTERJECTION.sub("", t) steps, unread = [], [] for c in _split(t): @@ -805,7 +807,7 @@ def read(text, markers=(), llm=True): clauses unread, the LLM reads the whole command and its answer is kept only if every value in it is written in the command (_checked). "other": the LLM says it is not English or Korean, nothing is taken.""" s, u = rules(text, markers) - if not u or not llm or len(_split(_norm(_cut_says(text)[0]))) < 2: + if not u or not llm or len(_split(_norm(_cut_says(text)[0], markers))) < 2: return s, u, "rules" got = _llm(text, markers) if got == "other": @@ -907,7 +909,7 @@ def _said(word_map, value, t): def _checked(raw, text, markers): """One LLM step in the reader's form, only when every value in it is written in the command; else None.""" - t, flat = _norm(text), re.sub(r"\s+", " ", text.lower()) + t, flat = _norm(text, markers), re.sub(r"\s+", " ", text.lower()) num = lambda x: re.search(rf"(? "final로" "도크 투", "dock two" -> "dock2" "엑시트" -> "exit" "홈으로" -> "home으로" "일 미터 반", "1미터 50센치", "one and a half meters" -> "1.5 m" "오십 센치", "half a meter" -> "0.5 m" Only clear forms are changed: "피로 가" (no number), "PE로", "피자", "이번에" stay as they are, and Lumi asks. +With the map's marker names (norm(text, names)) any name is read as said: "table front" / "테이블 프론트" -> +"table_front", "booth two" / "부스 투" -> "booth_2", "스타트로" -> "start로", and a word after "to" / "from" one +letter off one name only ("go to the stagee") -> that name. python assistant/wording.py "피쓰리로 가서 일 미터 앞으로 가" """ +import difflib import re import sys @@ -45,6 +49,14 @@ NAMED = [ # other markers on the map, as said / as whisper writes them -> the (r"(? stage) + def sino(word): """'사십오' -> 45, '백팔십' -> 180, '십' -> 10.""" @@ -169,10 +181,55 @@ def durations(t): return t -def norm(text): - """Lower case, numbers first ("point five meters" is a distance), then marker names.""" +def _key(name): + return re.sub(r"[\s_.-]", "", name.lower()) + + +def close_names(word, names): + """Marker names a spoken word may be when it is none of them exactly (a whisper slip): one letter or so off, the + same digits ("booth3" is not booth_2, "p12" not p1). Several back: ask which one.""" + if len(_key(word)) < 3 or word in NOT_SLIPS: + return [] + by = {_key(n): n for n in names if re.findall(r"\d+", n) == re.findall(r"\d+", word)} + return [by[k] for k in difflib.get_close_matches(_key(word), by, n=3, cutoff=CLOSE)] + + +def _spoken(name): + """A regex for a marker name as said: its words / numbers with spaces, "_", "-" or nothing between them, a number + also as a word ("two", "투"), an English word also in Hangul (KO_SPOKEN).""" + toks = re.findall(r"[a-z]+|\d+|[가-힣]+", name.lower()) + parts = [] + for tok in toks: + alts = [tok] + (KO_SPOKEN.get(tok, []) if len(toks) > 1 or tok not in KO_NOT_ALONE else []) + if tok.isdigit(): + alts += [w for w, n in {**EN_NUM, **KO_EN_NUM}.items() if n == int(tok)] + parts.append("(?:" + "|".join(sorted(map(re.escape, alts), key=len, reverse=True)) + ")") + return rf"(? grasp point -> finger tips) at least HEAD_CLEAR_MM from the head's turning +centre (vision/head_cam.py), never more than skills.PATH_SAG_MM below both ends, and with something in the hand the +cup's lean at most skills.MAX_TILT_DEG. Refusals are RouteError with the reason in English and Korean. + +Cobo π programs start only from `look` (start_program); hand_shaking.jks never (it hit the head, 2026-10-21). + + python manipulation/arm_route.py check [pose] # the route from here to pose (default look), checked; moves nothing + python manipulation/arm_route.py goto # go there along the route (SPEED; the owner at the STOP) +""" +import collections +import sys + +import numpy as np + +from manipulation import skills +from robot import arm, gripper, motion +from vision import calib, head_cam + +HOME = "look" # every arm action starts here +EDGES = (("give", "carry"), ("carry", "look"), ("look", "wave_start"), ("wave_start", "wave"), + ("look", "ready"), ("look", "tuck")) # the only joint moves between named poses (both ways) +SPEED = "slow" # motion.JOINT_SPEED of every move along the graph +AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close (where, programs) +EXACT_DEG = 1.0 # deg; further than this from the nearest pose a route first goes to it +JOIN_DEG = 20.0 # deg; an arm at no pose joins the graph only this close to one (every joint) +PATH_POINTS = 21 # points checked (kine_forward) on every joint move +HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turning centre. Estimate: the head camera + # is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266 +NEVER_RUN = ("hand_shaking.jks",) # Cobo π programs not started any more + +# Why the arm does not move, (English, Korean) +UNKNOWN = ("My arm is in a position I don't know, so I won't move it. Please bring it near its look pose by hand.", + "팔이 모르는 자세라서 움직이지 않을게요. 손으로 팔을 기본 자세 가까이 옮겨 주세요.") +NOT_TAUGHT = ("I haven't learned that arm pose yet.", "그 팔 자세는 아직 배우지 못했어요.") +BLOCKED = ("I can't move my arm there safely.", "팔을 거기로 안전하게 움직일 수 없어요.") +NEAR_HEAD = ("That would bring my hand too close to my head, so I won't move my arm.", + "손이 머리에 너무 가까워져서 팔을 움직이지 않을게요.") +SPILL = ("I can't move my arm there without spilling it.", "쏟지 않고는 팔을 거기로 움직일 수 없어요.") +UNSURE = ("I can't check my arm right now, so I won't move it.", "지금 팔 상태를 확인할 수 없어서 움직이지 않을게요.") +NOT_AT_LOOK = ("My arm has to be in its look pose first.", "먼저 팔이 기본 자세에 있어야 해요.") +RETIRED = ("I don't use that arm program any more.", "그 팔 프로그램은 이제 쓰지 않아요.") + + +class RouteError(skills.SkillError): + """args: (English, Korean) reason. Nothing was sent to the arm.""" + + +def log(*a): + skills.log(*a) + + +def _r(j): + return [round(v, 1) for v in j] + + +def _deg(now, pose): + """Largest joint difference (deg) between `now` and `pose` as move_joints would reach it.""" + return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) + + +def graph(): + """{pose: joints} of the graph's taught poses.""" + p = motion.poses() + return {n: p[n] for e in EDGES for n in e if n in p} + + +def where(now=None): + """The graph pose the arm is at (every joint within AT_POSE_DEG), else None.""" + now = skills._joints() if now is None else now + d = {n: _deg(now, j) for n, j in graph().items()} + best = min(d, key=lambda n: (d[n], n != HOME), default=None) + return best if best is not None and d[best] <= AT_POSE_DEG else None + + +def _path(a, b, nodes): + """Shortest list of poses a .. b along EDGES between `nodes`, None when there is none.""" + back, todo = {a: None}, collections.deque([a]) + while todo: + n = todo.popleft() + if n == b: + out = [] + while n is not None: + out.append(n) + n = back[n] + return out[::-1] + for e in EDGES: + for x, y in (e, e[::-1]): + if x == n and y in nodes and y not in back: + back[y] = n + todo.append(y) + return None + + +def hops(now, target, leaf=False): + """The poses the arm goes through from the joints `now` to `target`, in order (not the one it is at). `leaf`: the + arm is out on the task's own checked way from look (above a table): when it is at no pose, straight to target.""" + nodes = graph() + if target not in nodes: + log(f"arm route: {target} is not taught (robot/motion.py teach {target})") + raise RouteError(*NOT_TAUGHT) + d = {n: _deg(now, j) for n, j in nodes.items()} + start = min(d, key=lambda n: (d[n], n != HOME)) + if d[start] > JOIN_DEG: + if leaf: + return [target] + log(f"arm route: arm at {_r(now)}, {d[start]:.0f} deg from {start}, the nearest pose (joins within " + f"{JOIN_DEG:.0f})") + raise RouteError(*UNKNOWN) + path = _path(start, target, nodes) + if path is None: + log(f"arm route: no way from {start} to {target} among {', '.join(nodes)}") + raise RouteError(*NOT_TAUGHT) + return path if d[start] > EXACT_DEG else path[1:] + + +def _seg_dist(c, a, b): + """mm from point c to the segment a-b.""" + ab = b - a + t = min(1.0, max(0.0, float((c - a) @ ab) / float(ab @ ab))) if ab @ ab else 0.0 + return float(np.linalg.norm(c - (a + t * ab))) + + +def _gripper(c): + """Flange, grasp point, finger tips (mm) and the flange rotation of the flange pose c [x, y, z, rx, ry, rz].""" + R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3], float) + g = f + R @ skills.GRASP_OFFSET + return f, g, g + R @ (skills.TIP_MM * skills.FINGER_DIR), R + + +def flange_clearance(c, centre): + """Smallest distance (mm) from `centre` to the gripper at the flange pose c.""" + f, g, tip, _ = _gripper(c) + return min(_seg_dist(centre, f, g), _seg_dist(centre, g, tip)) + + +def profile(j0, j1, centre): + """(least gripper distance to `centre` mm, lowest z mm of the gripper at the ends, lowest z on the way, largest + lean deg of a held cup's axis) at PATH_POINTS points of the joint move j0 -> j1 (all joints together, a straight + line in joint space).""" + j0, j1 = np.array(j0, float), np.array(j1, float) + axis = calib.rpy_matrix(*skills.GRASP_RPY).T @ [0.0, 0.0, 1.0] # a held cup's axis in the flange frame + clear, low, tilt = [], [], 0.0 + for k in range(PATH_POINTS): + c = skills._ask("kine_forward", jointPosition=[float(v) for v in j0 + (j1 - j0) * k / (PATH_POINTS - 1)]) + f, g, tip, R = _gripper(c["cartPosition"]) + clear.append(flange_clearance(c["cartPosition"], centre)) + low.append(float(min(f[2], g[2], tip[2]))) + tilt = max(tilt, float(np.degrees(np.arccos(np.clip((R @ axis)[2], -1.0, 1.0))))) + return min(clear), min(low[0], low[-1]), min(low), tilt + + +def move_problem(j0, j1, centre, holding=False): + """Why the joint move j0 -> j1 must not run as (reason, log text), None if it may.""" + clear, ends, low, tilt = profile(j0, j1, centre) + if clear < HEAD_CLEAR_MM: + return NEAR_HEAD, f"the gripper comes {clear:.0f} mm from the head (needs {HEAD_CLEAR_MM:.0f})" + if low < ends - skills.PATH_SAG_MM: + return BLOCKED, f"the gripper dips to z {low:.0f} mm" + if holding and tilt > skills.MAX_TILT_DEG: + return SPILL, f"the held cup would lean {tilt:.0f} deg" + return None + + +def check_moves(now, targets, holding=False): + """Joint targets of the moves now -> targets[0] -> ..., as move_joints will turn them (J1 / J4 / J6 nearest), + each checked. RouteError when one must not run.""" + centre = head_cam.head_centre() + if centre is None: + log("arm route: the head's place is not measured (vision/head_cam.py fit)") + raise RouteError(*UNSURE) + seq, prev, done = [], list(now), {} + for t in targets: + try: + motion.check(t) + except motion.MotionError as e: + log(f"arm route: {e}") + raise RouteError(*BLOCKED) from e + t = motion.nearest(t, prev) + if max(abs(a - b) for a, b in zip(t, prev)) > motion.MAX_TRAVEL: + log(f"arm route: {_r(prev)} -> {_r(t)} turns a joint further than {motion.MAX_TRAVEL:.0f} deg") + raise RouteError(*BLOCKED) + key = frozenset((tuple(np.round(prev, 1)), tuple(np.round(t, 1)))) + if key not in done: # a move there and back (a wave's swings): checked once + done[key] = move_problem(prev, t, centre, holding) + if done[key]: + log(f"arm route: {_r(prev)} -> {_r(t)} refused: {done[key][1]}") + raise RouteError(*done[key][0]) + seq.append(t) + prev = t + return seq + + +def plan(target, holding=False, leaf=False, now=None): + """[(pose, joints)] of the checked way from here to `target` ([] when it is there). RouteError to refuse.""" + now = skills._joints() if now is None else now + names = hops(now, target, leaf) + p = motion.poses() + return list(zip(names, check_moves(now, [p[n] for n in names], holding))) + + +def move(seq, speed=SPEED): + """Run a plan() along its poses. motion.MotionError when stopped or failed on the way (the arm stays there).""" + for name, _ in seq: + log(f"arm to {name}") + motion.go(name, speed) + + +def goto(target, holding=False, leaf=False, speed=SPEED): + """Plan, check and go to pose `target` along the graph. Returns the poses passed.""" + seq = plan(target, holding, leaf) + if seq: + log(f"arm route to {target}: {' -> '.join(n for n, _ in seq)}, checked") + move(seq, speed) + 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.""" + if name.lower() in NEVER_RUN: + raise RouteError(*RETIRED) + if where() != HOME: + log(f"program {name} refused: the arm is not at {HOME}") + raise RouteError(*NOT_AT_LOOK) + arm.start(name) + + +if __name__ == "__main__": + a = sys.argv[1:] + try: + if a[:1] == ["check"]: + now = skills._joints() + centre = head_cam.head_centre() + print(f"at {where(now) or 'no pose'}: {_r(now)}") + prev = now + for n, j in plan(a[1] if len(a) > 1 else HOME, gripper.state()["holding"], now=now): + clear, _, low, tilt = profile(prev, j, centre) + print(f" -> {n:10s} {_r(j)} head {clear:.0f} mm, lowest z {low:.0f} mm, cup lean {tilt:.0f} deg") + prev = j + print("checked, nothing moved") + elif a[:1] == ["goto"] and len(a) == 2: + print(goto(a[1], gripper.state()["holding"])) + else: + sys.exit(__doc__) + except RouteError as e: + sys.exit(f"refused: {e.args[0]}") + except motion.MotionError as e: + sys.exit(f"stopped: {e}") + except KeyboardInterrupt: + print(motion.stop()) diff --git a/manipulation/skills.py b/manipulation/skills.py index 25a2e0b..d52fba9 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -709,17 +709,16 @@ def _prepare(): log("opening the gripper") gripper.open_() if max(abs(a - b) for a, b in zip(_joints(), home_joints())) > 1.0: - log(f"going to {home()}") - motion.go(home(), EMPTY_SPEED) + from manipulation import arm_route + arm_route.goto(home()) def _back_home(): - """Joint move to the home pose; refused when it would take the gripper lower than where it is now.""" + """From the table (out from home along the checked plan) straight back to the home pose: one joint move, checked + (arm_route: never lower than where it is now, clear of the head).""" _go_on() - if not joint_move_ok(_joints(), home_joints()): - raise SkillError("I can't get my arm back up safely from here.") - log(f"going to {home()}") - motion.go(home(), EMPTY_SPEED) + from manipulation import arm_route + arm_route.goto(home(), leaf=True) def _line(name, pose): diff --git a/manipulation/wave.py b/manipulation/wave.py index c2ac3b1..588db20 100644 --- a/manipulation/wave.py +++ b/manipulation/wave.py @@ -1,15 +1,11 @@ -"""Wave the hand when someone asks for it. A greeting never moves the arm. +"""Wave the hand when someone asked for it. A greeting never moves the arm. -The arm waves only from a known start pose (START_POSES: `look`, where the robot stands). It goes through the taught -poses ROUTE (first the hand away from the head, then up), swings one wrist joint about the last of them and comes back -the same way. Before anything moves, every joint move of that sequence is checked: joint limits, no joint turning -further than motion.MAX_TRAVEL, and at PATH_POINTS points along it (kine_forward) the gripper (flange -> grasp point -> -finger tips) stays HEAD_CLEAR_MM from the head's turning centre (vision/head_cam.py). 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 anywhere -else (after free drive, in carry or give), a pose not taught, a move too near the head. - -The Cobo π program hand_shaking.jks is not used: it ran from wherever the arm was and hit the head from `look` -(2026-10-21). +The arm goes up along the pose graph (manipulation/arm_route.py: from `look` to `wave_start`, the hand away from the +head, then `wave`, raised), swings one wrist joint there and STAYS at `wave`: the next arm task takes it back down +the same way (wave -> wave_start -> look). 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. python manipulation/wave.py check # plan and check from where the arm is now; moves nothing python manipulation/wave.py run # wave (slow; the owner at the STOP) @@ -18,30 +14,21 @@ Teach the route first, arm moved by hand in Cobo π: python robot/motion.py teac """ import sys -import numpy as np - -from manipulation import skills +from manipulation import arm_route, skills from robot import agv, arm, gripper, motion -from vision import calib, head_cam -START_POSES = ("look",) # the wave starts and ends only at one of these (motion.poses()) -ROUTE = ("wave_start", "wave") # taught poses from the start: the hand away from the head, then raised -AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close +TOP = "wave" # the raised pose (arm_route.EDGES: look - wave_start - wave) WAVE_JOINT = 4 # joint index swung at the raised pose (4 = J5); check on the first slow run WAVE_DEG = 15.0 # deg each way from the raised pose WAVE_SWINGS = 2 # times there and back -WAVE_SPEED = "slow" # motion.JOINT_SPEED; the route and the swings -PATH_POINTS = 21 # points checked (kine_forward) on every joint move -HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turning centre. Estimate: the head camera - # is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266 +WAVE_SPEED = arm_route.SPEED # motion.JOINT_SPEED; the route and the swings # Why Lumi does not wave, (English, Korean) OFF = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") BUSY = ("I'm busy with my arm right now.", "지금 팔로 하는 일이 있어요.") DRIVING = ("I can't wave while I'm moving.", "움직이는 동안에는 손을 흔들 수 없어요.") HOLDING = ("I'm holding something, so I won't wave.", "손에 물건을 들고 있어서 손을 흔들지 않을게요.") -UNKNOWN_POSE = ("My arm isn't in its usual place, so I won't wave. Please put it back first.", - "팔이 평소 자세가 아니어서 손을 흔들지 않을게요. 먼저 팔을 제자리로 해 주세요.") +UNKNOWN_POSE = arm_route.UNKNOWN NOT_TAUGHT = ("I haven't learned how to wave safely yet.", "아직 안전하게 손 흔드는 법을 배우지 못했어요.") NEAR_HEAD = ("Waving would bring my hand too close to my head, so I won't.", "손이 머리에 너무 가까워져서 손을 흔들지 않을게요.") @@ -70,33 +57,6 @@ def _holding(): return seen == "object" if seen != "unknown" else bool(gripper.state()["holding"]) -def _seg_dist(c, a, b): - """mm from point c to the segment a-b.""" - ab = b - a - t = min(1.0, max(0.0, float((c - a) @ ab) / float(ab @ ab))) if ab @ ab else 0.0 - return float(np.linalg.norm(c - (a + t * ab))) - - -def gripper_clearance(j, centre): - """Smallest distance (mm) from `centre` to the gripper (flange -> grasp point -> finger tips) at joints j.""" - c = skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"] - R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3], float) - g = f + R @ skills.GRASP_OFFSET - tip = g + R @ (skills.TIP_MM * skills.FINGER_DIR) - return min(_seg_dist(centre, f, g), _seg_dist(centre, g, tip)) - - -def move_clearance(j0, j1, centre): - """Smallest gripper distance (mm) to `centre` at PATH_POINTS points of the joint move j0 -> j1 (the controller - moves all joints together, in a straight line in joint space).""" - j0, j1 = np.array(j0, float), np.array(j1, float) - return min(gripper_clearance(j0 + (j1 - j0) * k / (PATH_POINTS - 1), centre) for k in range(PATH_POINTS)) - - -def _at(now, pose): - return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) <= AT_POSE_DEG - - def plan(): """Joint targets of the whole wave from here, each move checked. Raises WaveError to refuse.""" from tasks import fetch @@ -109,45 +69,22 @@ def plan(): raise WaveError(*DRIVING) if _holding(): raise WaveError(*HOLDING) - now, poses = motion.joints(), motion.poses() - start = next((n for n in START_POSES if n in poses and _at(now, poses[n])), None) - if start is None: - log(f"wave refused: arm at {[round(v, 1) for v in now]}, not at {', '.join(START_POSES)}") - raise WaveError(*UNKNOWN_POSE) - if any(n not in poses for n in ROUTE): - log(f"wave refused: teach {', '.join(n for n in ROUTE if n not in poses)} first (robot/motion.py teach)") - raise WaveError(*NOT_TAUGHT) - route = [list(poses[n]) for n in ROUTE] - top, i = route[-1], WAVE_JOINT - swings = [top[:i] + [top[i] + s * WAVE_DEG] + top[i + 1:] for _ in range(WAVE_SWINGS) for s in (1, -1)] - seq, prev = [], now - for t in route + swings + [top] + route[-2::-1] + [poses[start]]: - motion.check(t) - t = motion.nearest(t, prev) # as move_joints will turn it - if max(abs(a - b) for a, b in zip(t, prev)) > motion.MAX_TRAVEL: - log(f"wave refused: {[round(v, 1) for v in prev]} -> {[round(v, 1) for v in t]} turns a joint too far") - raise WaveError(*NOT_TAUGHT) - seq.append(t) - prev = t - centre = head_cam.head_centre() - if centre is None: - raise WaveError(*UNSURE) - done = set() - for a, b in zip([now] + seq, seq): - key = frozenset((tuple(np.round(a, 1)), tuple(np.round(b, 1)))) - if key in done: # the way back and the repeated swings: checked once - continue - done.add(key) - d = move_clearance(a, b, centre) - if d < HEAD_CLEAR_MM: - log(f"wave refused: {[round(v, 1) for v in a]} -> {[round(v, 1) for v in b]} brings the gripper " - f"{d:.0f} mm from the head (needs {HEAD_CLEAR_MM:.0f})") - raise WaveError(*NEAR_HEAD) + now = motion.joints() + try: + route = arm_route.plan(TOP, now=now) # up along the graph ([] when it is up already) + start = route[-1][1] if route else now + top = motion.nearest(motion.poses()[TOP], start) + i = WAVE_JOINT + swings = [top[:i] + [top[i] + s * WAVE_DEG] + top[i + 1:] for _ in range(WAVE_SWINGS) for s in (1, -1)] + seq = [j for _, j in route] + arm_route.check_moves(start, ([] if route else [top]) + swings + [top]) + 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 def wave(on_start=None): - """Plan, check and wave; back at the start pose at the end. `on_start()` is called once the plan is checked. + """Plan, check and wave; the arm stays at TOP. `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() diff --git a/robot/agv.py b/robot/agv.py index a5783cb..ec17f65 100644 --- a/robot/agv.py +++ b/robot/agv.py @@ -7,10 +7,13 @@ import json import socket import sys +import time import uuid AGV = ("192.168.10.10", 31001) DOCK_FALLBACK = "충전위치로" # dock marker name on the old map; on any map the type-11 marker is used +MARKERS_FRESH_S = 5.0 # known_markers() reads the list again after this long: a new map is seen within it +_known = {"t": 0.0, "names": []} def request(command, timeout=3.0): @@ -53,6 +56,17 @@ def markers(): return ["home" if n == dock else n for n in names] +def known_markers(fresh=False): + """markers(), read again when older than MARKERS_FRESH_S or when fresh (a name was not on the list); the last + list while the base does not answer.""" + if fresh or time.time() - _known["t"] > MARKERS_FRESH_S: + try: + _known.update(names=markers(), t=time.time()) + except OSError: # ConnectionError and socket.timeout are OSErrors + pass + return _known["names"] + + def go(marker): """Start driving to a marker. Returns (ok, message).""" marker = (dock_marker() or DOCK_FALLBACK) if marker == "home" else marker diff --git a/robot/arm.py b/robot/arm.py index 819f6cb..058a8d4 100644 --- a/robot/arm.py +++ b/robot/arm.py @@ -1,7 +1,7 @@ -"""Run a Cobo π program on the arm over the controller's TCP command port 10001 (no SDK). +"""The arm controller's TCP command port 10001 (JSON, no SDK): commands, Cobo π programs. +Programs are started through manipulation/arm_route.py (only from `look`). python robot/arm.py # state - python robot/arm.py run # play hand_shaking.jks once and wait python robot/arm.py stop """ import json @@ -10,7 +10,6 @@ import sys import time CONTROLLER = ("192.168.10.90", 10001) -WAVE = "hand_shaking.jks" # The controller now and then closes the connection without a reply (seen on get_data, get_program_state, # kine_inverse, stop_program, moveL, set_digital_output). Commands that only read are asked again, and so are those # that set an absolute value: moves to an absolute target (relFlag 0) and setting an output; sent twice they do the @@ -59,7 +58,7 @@ def program_state(): return cmd("get_program_state").get("programState") -def start(program=WAVE): +def start(program): """Load (if needed) and start a program; returns at once.""" if (cmd("get_loaded_program").get("programName") or "").lower() != program.lower(): if cmd("load_program", programName=program).get("errorCode") != "0": @@ -74,15 +73,7 @@ def stop(): if __name__ == "__main__": what = sys.argv[1] if len(sys.argv) > 1 else "state" - if what == "run": - if not ready(): - sys.exit("arm not ready (power/enable off, or a program is running)") - start() - time.sleep(0.5) - while program_state() != "idle": - time.sleep(0.3) - print("done") - elif what == "stop": + if what == "stop": print(stop()) else: print(cmd("get_robot_state"), program_state(), cmd("get_loaded_program").get("programName")) diff --git a/robot/motion.py b/robot/motion.py index e188b4a..9ee1dc9 100644 --- a/robot/motion.py +++ b/robot/motion.py @@ -6,7 +6,7 @@ Every move is checked before it is sent: joint limits with a margin, and for lin and return early with an error when STOP was pressed or the controller stopped the arm. python robot/motion.py # joints, TCP, named poses - python robot/motion.py go tuck [normal] # move to a named pose (slow by default) + python manipulation/arm_route.py goto look # to a named pose: only along the pose graph, checked python robot/motion.py teach ready # save the arm's current joints as a named pose (move it in Cobo π first) python robot/motion.py line 0 0 30 # straight TCP move by dx dy dz mm (base frame), slow python robot/motion.py stop @@ -229,8 +229,6 @@ if __name__ == "__main__": print("tcp ", [round(v, 1) for v in tcp()]) for k, v in poses().items(): print(f"pose {k:8s}", v) - elif a[0] == "go": - print(go(a[1], a[2] if len(a) > 2 else "slow")) elif a[0] == "teach": print(a[1], teach(a[1])) elif a[0] == "line": diff --git a/tasks/fetch.py b/tasks/fetch.py index 04e4fe3..2cf0b3b 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -21,6 +21,7 @@ from pathlib import Path import numpy as np +from manipulation import arm_route from manipulation import skills from robot import agv from robot import gripper @@ -49,14 +50,10 @@ LOOK_POSE = "look" # drives, turns, looks and waits here, also with an # the torso view, too near for depth (ready if not taught). carry is only passed through after a # pick: in carry the hand is ~0.3 m before the base's front, where its 3D camera seems to see # it as an obstacle (every drive in carry stalled; the same drives in look went, 2026-10-16) -MAX_TILT_DEG = skills.MAX_TILT_DEG # deg; the held cup's axis may lean this far from vertical on ready <-> carry -TILT_POINTS = 11 # points checked along a joint move (kine_forward) +MAX_TILT_DEG = skills.MAX_TILT_DEG # deg; the held cup's axis may lean this far from vertical on a straight move LINE_POINTS = 20 # points IK- and tilt-checked on a straight move with an object in the hand ... LINE_STEP_DEG = 25.0 # ... no joint may turn more than this between two of them (one IK branch all the way; # near J5 = 0 J4 and J6 turn ~15 deg a step against each other, the cup hardly turns) -# ponytail: fixed table height (top ~ -400 mm in the arm base frame, the 142 mm tumbler's top ~ -258); -# use the measured table top instead when tables of other heights come in. -MIN_POSE_Z = -220.0 # mm; a move between named poses must keep the grasp point above this (or above its start) PICK_ZONE_CENTRE = (-100.0, 580.0) # mm, arm base frame: where the base brings an object out of reach. Next to the # successful picks (x -126..-178, y 579..613) and inside the reach at table height # (IK map 2026-10-16, top -330: grasps for x -200..100 at y <= 650, none further) @@ -330,47 +327,23 @@ def _at_pose(name): return max(abs(a - b) for a, b in zip(j, motion.nearest(motion.poses()[name], j))) <= 1.0 -def _pose(name, speed=skills.EMPTY_SPEED): - """Joint move to pose `name`, refused when it would take the gripper down to the table. Empty hand: faster. - Nothing when it is there already.""" +def _pose(name, holding=False, leaf=False): + """Joint moves to pose `name` along the pose graph (manipulation/arm_route.py, slow), all checked before the first + one starts. `leaf`: the arm is on this task's own way out from look (arm_route.hops). Nothing when it is there.""" _go_on() if _at_pose(name): return - start, low = lowest_along(name) - if low < min(MIN_POSE_Z, start - 10.0): - log(f"refused: on the way to {name} the gripper would go down to z {low:.0f} mm") - raise FetchError("My arm would go too close to the table, I stopped.", "팔이 테이블에 너무 가까워져서 멈췄어요.") - log(f"arm to {name}") - motion.go(name, speed) + try: + seq = arm_route.plan(name, holding, leaf) + except arm_route.RouteError as e: + raise FetchError(*e.args) from e + log(f"arm to {name}: {' -> '.join(n for n, _ in seq)}") + for n, _ in seq: + _go_on() + motion.go(n, arm_route.SPEED) _go_on() -def _path(name): - """Flange poses (rotation, position) at TILT_POINTS points on the joint move from here to pose `name`.""" - j0 = np.array(skills._joints()) - j1 = np.array(motion.nearest(motion.poses()[name], list(j0))) - for k in range(TILT_POINTS): - c = skills._ask("kine_forward", jointPosition=[float(v) for v in j0 + (j1 - j0) * k / (TILT_POINTS - 1)]) - c = c["cartPosition"] - yield calib.rpy_matrix(*c[3:]), np.array(c[:3]) - - -def lowest_along(name): - """(start z, lowest z) in mm of the grasp point on the joint move from here to pose `name`.""" - z = [float((t + R @ skills.GRASP_OFFSET)[2]) for R, t in _path(name)] - return z[0], min(z) - - -def tilt_along(name): - """Largest lean (deg) of the held cup's axis from vertical on the joint move from here to pose `name`.""" - axis = calib.rpy_matrix(*skills.GRASP_RPY).T @ [0.0, 0.0, 1.0] # cup axis in the flange frame - worst = 0.0 - for R, _ in _path(name): - v = R @ axis - worst = max(worst, math.degrees(math.acos(float(np.clip(v[2], -1.0, 1.0))))) - return worst - - def _line_rows(target, label, start=None): """IK rows of the straight move from here (or `start`: (flange pose, joints)) to the flange pose `target`. FetchError when IK fails on the way or the held cup would lean more than MAX_TILT_DEG (the arm stays where it is).""" @@ -393,38 +366,48 @@ def _line_rows(target, label, start=None): if tilt > MAX_TILT_DEG: log(f"straight move {label}: the cup would lean {tilt:.1f} deg") raise FetchError("I can't move my arm there without spilling it.") + centre = head_cam.head_centre() + clear = min(arm_route.flange_clearance(r[1], centre) for r in rows) if centre is not None else 0.0 + if clear < arm_route.HEAD_CLEAR_MM: + log(f"straight move {label}: the gripper would come {clear:.0f} mm from the head") + raise FetchError(*arm_route.NEAR_HEAD) return rows def _line_holding(name): - """With the object in the hand: straight to pose `name` (IK and tilt checked), then its exact joints. Nothing - when it is there already.""" + """With the object in the hand: along the pose graph to pose `name` (arm_route.hops), a straight line to each + pose, all lines IK-, tilt- and head-checked before the first one starts; after each line the pose's exact joints. + Nothing when it is there already.""" _go_on() if _at_pose(name): return - target =skills._ask("kine_forward", jointPosition=[float(v) for v in motion.poses()[name]])["cartPosition"] - _line_rows(target, f"to {name}") - log(f"arm to {name} (straight)") - motion.move_linear(target=target, speed=skills.HOLDING_SPEED, path_checked=True) - _go_on() - j = skills._joints() - if max(abs(a - b) for a, b in zip(j, motion.nearest(motion.poses()[name], j))) > 1.0: - _pose_holding(name) + try: + names = arm_route.hops(skills._joints(), name, leaf=True) + except arm_route.RouteError as e: + raise FetchError(*e.args) from e + lines, start = [], None + for n in names: + j = motion.poses()[n] + target = skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"] + _line_rows(target, f"to {n}", start) + lines.append((n, target)) + start = (target, j) + for n, target in lines: + log(f"arm to {n} (straight)") + motion.move_linear(target=target, speed=skills.HOLDING_SPEED, path_checked=True) + _go_on() + if not _at_pose(n): # the pose's own joints (the line may end on another IK branch) + try: + arm_route.check_moves(skills._joints(), [motion.poses()[n]], holding=True) + except arm_route.RouteError as e: + raise FetchError(*e.args) from e + motion.go(n, skills.HOLDING_SPEED) def _look(): return LOOK_POSE if LOOK_POSE in motion.poses() else "ready" -def _pose_holding(name): - """Joint move with an object in the hand: refused when the cup would lean more than MAX_TILT_DEG.""" - tilt = tilt_along(name) - log(f"tilt on the way to {name}: {tilt:.1f} deg") - if tilt > MAX_TILT_DEG: - raise FetchError("I can't move my arm there without spilling it.") - _pose(name, skills.HOLDING_SPEED) - - def _at(pose, goal): """The base pose {"x", "y", "theta"} is at `goal` (x, y, theta) within SAME_PLACE_M and SAME_ANGLE_RAD.""" return math.hypot(pose["x"] - goal[0], pose["y"] - goal[1]) < SAME_PLACE_M and \ @@ -2396,7 +2379,7 @@ def measure_axis(name=None): _stop.clear() j = skills._joints() if all(max(abs(a - b) for a, b in zip(j, motion.nearest(motion.poses()[n], j))) > 1.0 for n in {_look(), "ready"}): - sys.exit(f"put the arm in {_look()} first: python robot/motion.py go {_look()}") + sys.exit(f"put the arm in {_look()} first: python manipulation/arm_route.py goto {_look()}") steady = lambda seen: [o for o in seen if o["seen"] >= skills.MIN_SEEN and o["spread"] <= skills.SPREAD_MM and (name is None or o["name"] == name)] before = steady(skills.look()) diff --git a/tests/test_arm_route.py b/tests/test_arm_route.py new file mode 100644 index 0000000..eef2c17 --- /dev/null +++ b/tests/test_arm_route.py @@ -0,0 +1,140 @@ +"""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 +from pathlib import Path + +import numpy as np + +from manipulation import arm_route, skills +from robot import arm, gripper, motion +from tasks import fetch +from vision import head_cam + +fetch.STATE_FILE = Path(tempfile.mkdtemp()) / "lumi_task.json" # never the real /dev/shm file +POSES = {"look": [0.0] * 6, "carry": [20.0, 0, 0, 0, 0, 0], "give": [40.0, 0, 0, 0, 0, 0], + "wave_start": [0.0, -20, 0, 0, 0, 0], "wave": [0.0, -20, 20, 0, 0, 0], "ready": [0.0, 0, -20, 0, 0, 0], + "tuck": [-20.0, 0, 0, 0, 0, 0]} +FAR = np.array([0.0, 0.0, 5000.0]) # the head far away: nothing near it +head = {"centre": FAR} +motion.poses = lambda: dict(POSES) +head_cam.head_centre = lambda: head["centre"] +gripper.state = lambda: {"holding": False, "ai": [160]} +arm_route.log = fetch.log = lambda *a: None + + +class FakeArm: + """Joints in deg; toy forward kinematics: flange at 30 mm per degree of J1 / J2 / J3, never turned.""" + + def __init__(self, joints): + self.j, self.sent, self.programs = list(joints), [], [] + + def __call__(self, name, **a): + if name == "get_robot_state": + return {"power": 1, "enable": 1, "errorCode": "0"} + if name == "get_program_state": + return {"programState": "idle", "errorCode": "0"} + if name == "get_joint_pos": + return {"joint_pos": list(self.j), "errorCode": "0"} + if name == "kine_forward": + j = a["jointPosition"] + 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 == "joint_move": + self.sent.append(list(a["jointPosition"])) + self.j = list(a["jointPosition"]) + return {"errorCode": "0"} + if name in ("get_loaded_program", "load_program", "play_program"): + self.programs.append(name) + return {"errorCode": "0", "programName": ""} + raise AssertionError(f"unexpected arm command {name}") + + +def use(j): + arm.cmd = FakeArm(j) + return arm.cmd + + +def refused(reason, fn, *a, **k): + try: + fn(*a, **k) + except arm_route.RouteError as e: + assert e.args == reason, e.args + return + raise AssertionError(f"moved, expected {reason}") + + +edges = {frozenset(e) for e in arm_route.EDGES} + +# ---------- every pair of poses: along the graph's edges, one joint move each ---------- +for a in POSES: + for b in POSES: + fake = use(POSES[a]) + route = arm_route.goto(b) + assert [a] + route == arm_route._path(a, b, POSES) and fake.sent == [POSES[n] for n in route], (a, b, route) + assert all(frozenset(p) in edges for p in zip([a] + route, route)), (a, b, route) + assert arm_route.where(fake.j) == b +use(POSES["give"]) +assert arm_route.goto("look") == ["carry", "look"] # after giving: give -> carry -> look +assert arm_route.goto("give") == ["carry", "give"] # to give: look -> carry -> give +use(POSES["wave"]) +assert arm_route.goto("tuck") == ["wave_start", "look", "tuck"] # fold: through look + +# ---------- after a wave the arm stays up; the next pick goes wave -> wave_start -> look first ---------- +fake = use(POSES["wave"]) +skills._prepare() +assert fake.sent == [POSES["wave_start"], POSES["look"]], fake.sent +fake = use(POSES["wave"]) +fetch._pose("look") +assert fake.sent == [POSES["wave_start"], POSES["look"]], fake.sent + +# ---------- an unknown pose near a known one: a checked joint move to it, then on ---------- +near = [3.0, 2.0, -4.0, 5.0, 0.0, 0.0] # 5 deg from look (free drive) +assert arm_route.where(near) is None +fake = use(near) +assert arm_route.goto("carry") == ["look", "carry"] and fake.sent == [POSES["look"], POSES["carry"]], fake.sent +fake = use([20.5, 0, 0, 0, 0, 0]) # within EXACT_DEG of carry: straight on +assert arm_route.goto("give") == ["give"] + +# ---------- far from every pose, or a move that passes the head: refused, nothing sent ---------- +fake = use([60.0, 60.0, 0, 0, 0, 0]) +refused(arm_route.UNKNOWN, arm_route.goto, "look") +try: + fetch._pose("look") + raise AssertionError("fetch moved from an unknown pose") +except fetch.FetchError as e: + assert e.args == arm_route.UNKNOWN +assert fake.sent == [] +fake = use([60.0, 60.0, 0, 0, 0, 0]) # a task's own way back from the table: straight +assert arm_route.goto("look", leaf=True) == ["look"] +head["centre"] = np.array([300.0, 0.0, 0.0]) # on the way look -> carry (flange x 0 -> 600) +for start in (POSES["look"], near, POSES["give"]): + fake = use(start) + refused(arm_route.NEAR_HEAD, arm_route.goto, "give" if start != POSES["give"] else "look") + assert fake.sent == [], fake.sent +fake = use(POSES["look"]) +assert arm_route.goto("wave") == ["wave_start", "wave"] # another edge: clear of it +head["centre"] = None # the head not measured: nothing moves +refused(arm_route.UNSURE, arm_route.goto, "look") +head["centre"] = FAR +POSES["give"] = [40.0, 0, 0, 0, 125.0, 0] # beyond J5's limit +fake = use(POSES["look"]) +refused(arm_route.BLOCKED, arm_route.goto, "give") +assert fake.sent == [] +POSES["give"] = [40.0, 0, 0, 0, 0, 0] +del POSES["wave_start"] +refused(arm_route.NOT_TAUGHT, arm_route.goto, "wave") # no way to wave without wave_start +refused(arm_route.NOT_TAUGHT, arm_route.goto, "nowhere") +POSES["wave_start"] = [0.0, -20, 0, 0, 0, 0] + +# ---------- Cobo π programs only from look; hand_shaking never ---------- +fake = use(POSES["carry"]) +refused(arm_route.NOT_AT_LOOK, arm_route.start_program, "arm_reach.jks") +fake = use(near) +refused(arm_route.NOT_AT_LOOK, arm_route.start_program, "arm_reach.jks") +fake = use(POSES["look"]) +refused(arm_route.RETIRED, arm_route.start_program, "hand_shaking.jks") +assert fake.programs == [] +arm_route.start_program("arm_reach.jks") +assert "play_program" in fake.programs +print("arm route ok") diff --git a/tests/test_fetch.py b/tests/test_fetch.py index ccf7ff3..d9a221e 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -233,17 +233,15 @@ except fetch.FetchError: st = run(fetch.place) assert st["status"] == "done" and not st["holding"] and ("place",) in calls and poses()[-1] == "look", (st, calls) -# ---------- arm speed: empty hand faster, with the object slow ---------- +# ---------- arm speed: every move along the pose graph at arm_route.SPEED, empty hand or holding ---------- speeds = [] real_go = fetch.motion.go fetch.motion.go = lambda name, speed="slow", *a, **k: (speeds.append((name, speed)), calls.append(("pose", name))) -arm.update(j=[5.0] * 6) -fetch._pose("look") -fetch.motion.poses = lambda: {"tuck": [0] * 6, "ready": [0] * 6, "carry": [3] * 6, "look": [0] * 6} +arm.update(j=[0.5] * 6) +fetch._pose("carry") tilt["rpy"] = up_rpy -fetch._pose_holding("carry") -assert speeds == [("look", skills.EMPTY_SPEED), ("carry", skills.HOLDING_SPEED)], speeds -assert skills.EMPTY_SPEED != skills.HOLDING_SPEED +fetch._pose("carry", holding=True) +assert speeds == [("carry", fetch.arm_route.SPEED)] * 2 and fetch.arm_route.SPEED == "slow", speeds fetch.motion.go = real_go # ---------- a drive that turns on the spot without getting anywhere is cancelled ---------- @@ -753,9 +751,11 @@ fetch.GIVE_WAIT_S = 0.3 reset() st = run(fetch.start, ok) assert st["status"] == "holding", st +calls.clear() st = run(fetch.give) # nobody says thank you: kept assert st["status"] == "holding" and st["holding"] and ("open",) not in calls, (st, calls) -assert calls.count(("line", "straight")) == 2 and "ready" not in poses() # carry -> give -> carry, straight +assert calls.count(("line", "straight")) == 4 and poses() == ["carry", "give", "carry", "look"], calls # look -> + # carry -> give -> carry -> look, straight fetch.GIVE_WAIT_S = 5.0 threading.Timer(0.2, fetch.release_now).start() # "thank you" / Release st = run(fetch.give) @@ -792,32 +792,34 @@ assert ("cancel",) in calls tilted = calib.rpy_matrix(30, 0, 0) @ calib.rpy_matrix(*up_rpy) # turned 30 deg about base x ry = math.degrees(math.asin(-tilted[2, 0])) tilt["rpy"] = [math.degrees(math.atan2(tilted[2, 1], tilted[2, 2])), ry, math.degrees(math.atan2(tilted[1, 0], tilted[0, 0]))] -assert abs(fetch.tilt_along("carry") - 30) < 0.5, fetch.tilt_along("carry") +arm.update(j=[0.5] * 6) # at look: the route is look -> carry calls.clear() try: - fetch._pose_holding("carry") + fetch._pose("carry", holding=True) raise AssertionError("tilted move accepted") -except fetch.FetchError: - assert not calls +except fetch.FetchError as e: + assert not calls and e.args == fetch.arm_route.SPILL, (calls, e.args) tilt["rpy"] = up_rpy -assert fetch.tilt_along("carry") < 1e-6 +fetch._pose("carry", holding=True) +assert calls == [("pose", "carry")], calls -# ---------- height check: a pose move must not take the gripper down to the table ---------- -z_along = {"look": -500.0} # flange z at the end of the move; it starts at 0 -skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, z_along.get(name_of(a), 0.0)] + up_rpy} -name_of = lambda a: "look" if a["jointPosition"][0] > 0 else None -fetch.motion.poses = lambda: {"tuck": [0] * 6, "ready": [0] * 6, "carry": [3] * 6, "look": [10.0] + [0] * 5} +# ---------- height check: a pose move must not take the gripper down to the table on the way ---------- +skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, -500.0 if 0 < a["jointPosition"][0] < 10 else 0.0] + + up_rpy} +fetch.motion.poses = lambda: {"look": [0] * 6, "carry": [10.0] + [0] * 5} +arm.update(j=[0.0] * 6) calls.clear() try: - fetch._pose("look") + fetch._pose("carry") raise AssertionError("move down to the table accepted") -except fetch.FetchError: - assert not calls -arm.update(j=[-5.0] * 6) -fetch._pose("ready") -assert calls == [("pose", "ready")], calls -fetch._pose("ready") # there already: no move -assert calls == [("pose", "ready")], calls +except fetch.FetchError as e: + assert not calls and e.args == fetch.arm_route.BLOCKED, (calls, e.args) +skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, 0] + up_rpy} +fetch._pose("carry") +assert calls == [("pose", "carry")], calls +fetch._pose("carry") # there already: no move +assert calls == [("pose", "carry")], calls +fetch.motion.poses = lambda: {"tuck": [0] * 6, "ready": [0] * 6, "carry": [3] * 6, "look": [0] * 6} # ---------- place spots: the pick spot only while the base stands where it picked ---------- seen_table = {"spots": None} skills.on_table = lambda spots, table: (seen_table.update(spots=list(spots), table=table), [s for s in spots if s[1] >= 680])[1] diff --git a/tests/test_map_names.py b/tests/test_map_names.py new file mode 100644 index 0000000..3a66361 --- /dev/null +++ b/tests/test_map_names.py @@ -0,0 +1,118 @@ +"""Self-check of marker names as people say them on any map (assistant/wording.py map_names, brain, steps, the +assistant's live list), with fake marker lists for the office and a conference map, no robot, no LLM: +python tests/test_map_names.py""" +import types + +from assistant import brain, lumi, steps, wording +from robot import agv + +lumi.LOG_FILE = "/dev/null" +OFFICE = ["home", "dock2", "exit", "final"] + [f"p{i}" for i in range(1, 13)] +CONF = ["home", "start", "end", "init", "final", "middle", "table_front", "stage", "booth_2"] + +# ---------- said -> written, with the conference map's names ---------- +NORM = { + "go to table front": "go to table_front", "go to the Table-Front": "go to the table_front", + "go to tablefront": "go to table_front", "테이블 프론트로 가": "table_front로 가", "테이블 프런트로": "table_front로", + "go to booth two": "go to booth_2", "go to Booth 2": "go to booth_2", "go to booth-2": "go to booth_2", + "부스 투로 가": "booth_2로 가", "스타트로 가": "start로 가", "엔드에서 컵 가져와": "end에서 컵 가져와", + "미들로 가": "middle로 가", "스테이지로 가": "stage로 가", "이닛으로 가": "init으로 가", "홈으로 가": "home으로 가", + "go to the stagee": "go to the stage", "go to the middel": "go to the middle", # whisper slips, one name + "go to the table fronts": "go to the table_front", "from the stagee to end": "from the stage to end", + # not a marker: unchanged + "테이블에 놔": "테이블에 놔", "restart the song": "restart the song", "스타트업": "스타트업", "go to point": "go to point", + "go to booth 3": "go to booth 3", "go to the left": "go to the left", +} +bad = {t: (wording.norm(t, CONF), w) for t, w in NORM.items() if wording.norm(t, CONF) != w} +assert not bad, bad + +# ---------- go to / come back to: the quick rules ---------- +GO = {"go to table front": "table_front", "테이블 프론트로 가": "table_front", "go to booth two": "booth_2", + "부스 투로 가 줘": "booth_2", "루미야 스타트로 가": "start", "go to the end": "end", "엔드로 가": "end", + "go back to start": "start", "come back to the stage": "stage", "drive to Middle": "middle", "이닛으로 가": "init", + "파이널로 가": "final", "go to the stagee": "stage", "go home": "home"} +wrong = {t: brain.intent(t, CONF) for t, w in GO.items() if brain.intent(t, CONF) != ("go_to", w)} +assert not wrong, wrong +for t, w in {"go to p3": "p3", "피쓰리로 가": "p3", "go to final": "final", "도크 투로 가": "dock2", "go to 10p point": "p10", + "엑시트로 가": "exit"}.items(): # the office map's names keep working + assert brain.intent(t, OFFICE) == ("go_to", w), (t, brain.intent(t, OFFICE)) +for t in ("go to p3", "go to the kitchen", "go to start"): # not on that map: never driven + assert brain.intent(t, OFFICE if t == "go to start" else CONF) is None, t + +# ---------- unknown, ambiguous: what Lumi says ---------- +en, ko = brain.place_problem("go to p12", CONF) +assert en.startswith("I don't have a place called p12 on this map. I know: ") and "table front" in en, en +assert "p12라는 곳이 없어요" in ko, ko +TWO = CONF + ["booth_1"] +en, ko = brain.place_problem("go to booth", TWO) +assert en.startswith("Did you mean booth ") and "booth 1" in en and "booth 2" in en, en +assert brain.intent("go to booth", TWO) is None and brain.intent("go to booth two", TWO) == ("go_to", "booth_2") +for t in ("go to stage", "go to sleep", "go to the left", "go to the kitchen"): # the LLM answers the others + assert brain.place_problem(t, CONF) is None, t +said = brain.Brain._action("ACTION: go_to kitchen", "go to the kitchen", CONF) +assert said["action"] == "none" and said["say"].startswith("I don't have a place called kitchen"), said +assert brain.Brain._action("ACTION: go_to table_front", "go to the table front", CONF)["target"] == "table_front" + +# ---------- missions, fetch to / from, place at a marker ---------- +STEPS = { + "go to start, then come back": [{"do": "go", "to": "start"}, {"do": "go", "to": "here"}], + "스타트로 갔다가 돌아와": [{"do": "go", "to": "start"}, {"do": "go", "to": "here"}], + "go to middle and wait 10 seconds then go to end": + [{"do": "go", "to": "middle"}, {"do": "wait", "s": 10.0}, {"do": "go", "to": "end"}], + "미들로 가서 10초 기다렸다가 엔드로 가": [{"do": "go", "to": "middle"}, {"do": "wait", "s": 10.0}, {"do": "go", "to": "end"}], + "go to Table-Front then 홈으로 가": [{"do": "go", "to": "table_front"}, {"do": "go", "to": "home"}], + "go to the stagee and come back": [{"do": "go", "to": "stage"}, {"do": "go", "to": "here"}], + "go stage": [{"do": "go", "to": "stage"}], + "take the white cup to booth two and put it on the table": [ + {"do": "pick", "object": "cup", "colour": "white"}, {"do": "go", "to": "booth_2"}, + {"do": "place", "on": {"name": "dining table", "colour": None, "side": None}}], + "부스 투 테이블에 놔": [{"do": "go", "to": "booth_2"}, + {"do": "place", "on": {"name": "dining table", "colour": None, "side": None}}], + "컵 들고 테이블 프론트로 가서 놔": [{"do": "pick", "object": "cup", "colour": None}, {"do": "go", "to": "table_front"}, + {"do": "place", "on": None}], +} +for t, want in STEPS.items(): + got, unread, _ = steps.read(t, CONF, llm=False) + assert got == want and not unread, (t, got, unread) +assert steps.read("go to booth and come back", TWO, llm=False)[1] == ["go to booth"] # ambiguous: not guessed +assert lumi.read_mission("go to start, then come back", CONF)[0][0] == {"do": "go", "to": "start"} +FETCH = {"bring the cup from start to table front": ({"marker": "start"}, {"marker": "table_front"}), + "스타트에서 컵 가져와서 부스 투에 놔": ({"marker": "start"}, {"marker": "booth_2"}), + "bring me the cup from the stagee": ({"marker": "stage"}, "here")} +for t, (src, dest) in FETCH.items(): + task, _ = brain.parse_fetch(t, CONF) + assert (task["source"], task["dest"]) == (src, dest), (t, task) +assert brain.parse_fetch("bring the cup from the kitchen", CONF)[0]["source"] is None + +# ---------- the assistant's list follows the map ---------- +maps = {"now": OFFICE} +agv.markers = lambda: list(maps["now"]) +assert agv.known_markers(fresh=True) == OFFICE +maps["now"] = CONF # the owner switched the map +assert agv.known_markers() == OFFICE # read again only after MARKERS_FRESH_S ... +agv._known["t"] -= agv.MARKERS_FRESH_S + 1 +assert agv.known_markers() == CONF # ... or on a miss (fresh=True) + + +def offline(): + raise ConnectionError("AGV closed the connection") + + +agv.markers = offline +assert agv.known_markers(fresh=True) == CONF # the base not answering: the last list +agv.markers = lambda: list(maps["now"]) + +L = lumi.Lumi.__new__(lumi.Lumi) +assert L.markers == CONF +spoken, trips = [], [] +lumi.mouth.say = lambda text, **k: spoken.append(text) +L.lang, L.keep_listening, L.mission_running = "en", lambda: None, lambda: False +L.base_off, L.arm_off, L.start_trip = lambda *a: False, lambda: False, trips.append +L.modes, L.brain, L.current, L.voice_until = types.SimpleNamespace(drive=True), types.SimpleNamespace(history=[]), None, 0 +assert L.quick_command("go to p12") and spoken[-1].startswith("I don't have a place called p12") and not trips +maps["now"] = OFFICE # a miss reads the list again: p12 is on this map +assert L.quick_command("go to p12") and trips == ["p12"] +maps["now"] = CONF +agv.known_markers(fresh=True) +assert L.quick_command("go to table front") and trips[-1] == "table_front" and spoken[-1] == "Okay, I'm going to table front." +print("map names ok") diff --git a/tests/test_wave.py b/tests/test_wave.py index 7b10225..503d06c 100644 --- a/tests/test_wave.py +++ b/tests/test_wave.py @@ -8,7 +8,7 @@ from pathlib import Path import numpy as np from assistant import lumi -from manipulation import skills, wave +from manipulation import arm_route, skills, wave from robot import agv, arm, gripper, motion from tasks import fetch from vision import head_cam @@ -25,7 +25,7 @@ hand = {"holding": False} gripper.state = lambda: {"holding": hand["holding"]} base = {"move_status": "idle"} agv.status = lambda: dict(base) -wave.log = lambda *a: None +wave.log = arm_route.log = lambda *a: None class FakeArm: @@ -67,17 +67,20 @@ def refused(reason): raise AssertionError(f"waved, expected {reason}") -# ---------- from look: along the route, wave, back the same way; every move clear of the head ---------- +# ---------- from look: up along the graph, wave, and the arm stays up; every move clear of the head ---------- a = use(FakeArm(LOOK)) started = [] wave.wave(on_start=lambda: started.append(len(a.sent))) assert started == [0] # said before the first move top = POSES["wave"] up, down = top[:4] + [top[4] + wave.WAVE_DEG] + top[5:], top[:4] + [top[4] - wave.WAVE_DEG] + top[5:] -assert a.sent == [POSES["wave_start"], top] + [up, down] * wave.WAVE_SWINGS + [top, POSES["wave_start"], LOOK], a.sent +assert a.sent == [POSES["wave_start"], top] + [up, down] * wave.WAVE_SWINGS + [top], a.sent for j0, j1 in zip([LOOK] + a.sent, a.sent): - assert wave.move_clearance(j0, j1, HEAD) >= wave.HEAD_CLEAR_MM, (j0, j1) -assert wave.move_clearance(LOOK, top, HEAD) < wave.HEAD_CLEAR_MM # straight up from look would pass the head + assert arm_route.profile(j0, j1, HEAD)[0] >= arm_route.HEAD_CLEAR_MM, (j0, j1) +assert arm_route.profile(LOOK, top, HEAD)[0] < arm_route.HEAD_CLEAR_MM # straight up from look would pass the head +a.sent.clear() +wave.wave() # asked again while up: only the swings +assert a.sent == [top] + [up, down] * wave.WAVE_SWINGS + [top], a.sent # ---------- a taught pose whose way passes the head: refused before anything moves ---------- POSES["wave_start"] = [-15.0, 0.0, 40.0, 0.0, 0.0, 0.0] @@ -99,11 +102,16 @@ refused(wave.HOLDING) skills.hand_sees = lambda: "unknown" assert a.sent == [] -# ---------- an unknown start (after free drive: the wrist the other way round), carry, give, base, power ---------- +# ---------- from carry (empty hand): down to look first, then up ---------- +POSES["carry"] = [30.0, 0.0, 0.0, 0.0, 0.0, 0.0] +a = use(FakeArm(POSES["carry"])) +wave.wave() +assert a.sent[:3] == [LOOK, POSES["wave_start"], top], a.sent +del POSES["carry"] + +# ---------- an unknown start (after free drive: the wrist the other way round), base, power ---------- a = use(FakeArm([-249.1, -90.9, -29.1, 14.6, -83.8, -33.0])) refused(wave.UNKNOWN_POSE) -use(FakeArm([-280.6, -86.13, -2.58, -173.3, 85.86, 119.9])) # carry -refused(wave.UNKNOWN_POSE) use(FakeArm(LOOK, enable=False)) refused(wave.OFF) base["move_status"] = "running" diff --git a/tools/arm_program.py b/tools/arm_program.py index 528c643..ca83eea 100644 --- a/tools/arm_program.py +++ b/tools/arm_program.py @@ -1,9 +1,11 @@ """Run a Cobo π program on the Lumi arm over the controller's TCP command port (10001). -No JAKA SDK needed; works from any computer on the robot network. +No JAKA SDK needed; works from any computer on the robot network. A program starts only with the arm at `look` +(data/arm_poses.json, every joint within AT_LOOK_DEG), as on the robot (manipulation/arm_route.py); hand_shaking +never (it hit the head, 2026-10-21). python3 tools/arm_program.py state # power/enable, loaded program, program state - python3 tools/arm_program.py run hand_shaking # load the program and play it once, wait until done + python3 tools/arm_program.py run arm_reach # load the program and play it once, wait until done python3 tools/arm_program.py stop # stop the running program Ctrl+C while a program runs stops it. @@ -12,8 +14,12 @@ import json import socket import sys import time +from pathlib import Path CONTROLLER = ("192.168.10.90", 10001) +POSES_FILE = Path(__file__).resolve().parents[1] / "data" / "arm_poses.json" +AT_LOOK_DEG = 3.0 # deg; every joint this close to `look` (J1 / J4 / J6 also ± 360) +NEVER_RUN = ("hand_shaking.jks",) def cmd(name, **args): @@ -44,6 +50,14 @@ def run(program): sys.exit(f"A program is {st['program']}; stop it first (python3 tools/arm_program.py stop).") name = program if program.endswith(".jks") else program + ".jks" + if name.lower() in NEVER_RUN: + sys.exit(f"{name} is not used any more (it hit the head); the wave is manipulation/wave.py.") + look = json.loads(POSES_FILE.read_text())["look"] + now = cmd("get_joint_pos")["joint_pos"] + off = max(min(abs(n - l - k) for k in ((-360, 0, 360) if i in (0, 3, 5) else (0,))) + for i, (n, l) in enumerate(zip(now, look))) + if off > AT_LOOK_DEG: + sys.exit(f"The arm is {off:.0f} deg from look: programs start only from look.") if (st["loaded"] or "").lower() != name.lower(): r = cmd("load_program", programName=name) print("load_program:", r.get("errorCode"), r.get("errorMsg")) @@ -65,14 +79,14 @@ def run(program): def main(): - if len(sys.argv) < 2 or sys.argv[1] not in ("state", "run", "stop"): + if len(sys.argv) < 2 or sys.argv[1] not in ("state", "run", "stop") or sys.argv[1] == "run" and len(sys.argv) < 3: sys.exit(__doc__) if sys.argv[1] == "state": print(state()) elif sys.argv[1] == "stop": print("stop_program:", cmd("stop_program")) else: - run(sys.argv[2] if len(sys.argv) > 2 else "hand_shaking") + run(sys.argv[2]) if __name__ == "__main__":