diff --git a/.gitignore b/.gitignore
index c65b1b3..246c951 100644
--- a/.gitignore
+++ b/.gitignore
@@ -66,3 +66,4 @@ tests/blind/r12/
tests/blind/r13/
data/bank_build.lock
data/bank_check_queries.npz
+tests/data/waves/
diff --git a/README.md b/README.md
index 27aa926..756f38a 100644
--- a/README.md
+++ b/README.md
@@ -40,7 +40,7 @@ Jetson AGX Thor inside the robot and turns it into a conversational service robo
| **Go to places** | Drives to any named location on the map or to a spot a person points at, patrols a route, and returns to its dock to charge. |
| **Fetch and deliver** | Picks up a cup or bottle, brings it to a person or a place, puts it down, or hands it over. |
| **Run missions** | Carries out several steps from one spoken request, such as fetching an item, delivering it and passing on a message. |
-| **Sing and gesture** | Sings songs from its repertoire and waves to greet or say goodbye. |
+| **Sing and gesture** | Sings songs from its repertoire, waves when asked, and waves back at people who wave at it from up to 3 m, turning to face them and greeting them. |
---
@@ -228,7 +228,7 @@ Lumi는 쿳션이 개발한 **JAKA Lumi** 모바일 매니퓰레이터용 소프
| **장소 이동** | 지도에 있는 어느 장소나 사람이 가리키는 곳으로 이동하고, 순찰하며, 충전 도크로 돌아갑니다. |
| **가져오기와 전달** | 컵이나 병을 집어 사람이나 장소로 가져가고, 내려놓거나 건네줍니다. |
| **미션 수행** | 물건 가져오기, 전달하기, 메시지 전하기처럼 한 번의 요청으로 여러 단계를 수행합니다. |
-| **노래와 제스처** | 레퍼토리의 노래를 부르고, 인사나 작별할 때 손을 흔듭니다. |
+| **노래와 제스처** | 레퍼토리의 노래를 부르고, 요청하면 손을 흔들며, 3 m 안에서 손을 흔드는 사람에게는 몸을 돌려 마주 보고 인사하며 함께 손을 흔듭니다. |
---
diff --git a/api/dashboard.html b/api/dashboard.html
index e65edab..50558f3 100644
--- a/api/dashboard.html
+++ b/api/dashboard.html
@@ -253,7 +253,7 @@ input[type=color]{width:30px;height:28px;border:1px solid var(--line);border-rad
Standing: greets people who come close, talks, answers "Hi Lumi"
Patrol
Driving: stops for people on the way, talks, then drives on
`;
diff --git a/api/server.py b/api/server.py
index 1be77e6..51f136d 100644
--- a/api/server.py
+++ b/api/server.py
@@ -40,6 +40,7 @@ from robot import head
from manipulation import arm_route
from manipulation import skills
from manipulation import wave
+from tasks import wave_greet
from api.control import jogger
PORT = 8100
@@ -69,7 +70,7 @@ def assistant_pids():
MODES_FILE = Path("/dev/shm/lumi_modes.json")
CMD_FILE = Path("/dev/shm/lumi_cmd.json")
CALIB_FILE = Path("/dev/shm/lumi_calib.json")
-DEFAULT_MODES = {"greeter": False, "patrol": False, "wave": True}
+DEFAULT_MODES = {"greeter": False, "patrol": False, "wave_greet": False}
def read_modes():
@@ -118,6 +119,8 @@ def running_now():
return "route"
if _waving.is_set():
return "wave"
+ if wave_greet.busy():
+ return "wave_greet"
if _posing.is_set():
return "arm"
if lumi:
@@ -1401,10 +1404,10 @@ def task_state():
class ModesBody(BaseModel):
greeter: bool | None = Field(None, description="standing: greet people who come close, talk, wake word")
patrol: bool | None = Field(None, description="driving anywhere: stop for people in the way, talk, drive on")
- wave: bool | None = Field(None, description="wave when asked")
+ wave_greet: bool | None = Field(None, description="wave back at people who wave, Greeter / Patrol not needed")
-@app.get("/assistant/modes", tags=["assistant"], summary="Greeter / patrol / wave switches")
+@app.get("/assistant/modes", tags=["assistant"], summary="Greeter / patrol / wave greeting switches")
def modes_get():
return {**read_modes(), "running": bool(assistant_pids())}
@@ -1539,4 +1542,7 @@ if __name__ == "__main__":
threading.Thread(target=_drive_log, daemon=True).start()
# the supervisor here, not on import: a test importing this module started real lumi.py processes (2026-10-28)
threading.Thread(target=_supervise, daemon=True).start()
+ wave_greet.start(lambda: read_modes()["wave_greet"],
+ lambda: not assistant_pids() and running_now() in (None, "wave_greet"),
+ lambda: modes_set(ModesBody(wave_greet=False)))
uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="warning")
diff --git a/assistant/brain.py b/assistant/brain.py
index 3a8e939..c7ec845 100644
--- a/assistant/brain.py
+++ b/assistant/brain.py
@@ -2410,6 +2410,41 @@ REFUSE_PICK = ("I'm holding something already. Tell me where to put it first.",
REFUSE_OPEN = ("I won't open my hand while I'm holding something: it would fall. Say put it down or hand it over.",
"물건을 들고 있어서 손을 펴면 떨어져요. 내려놓으라고 하시거나 달라고 해 주세요.")
+# ---------- while holding: the person says they hold it themselves, so the hand may open ("I've got it", "I am holding
+# the cuff, so let's open", "내가 잡고 있어", "제가 들고 있어요, 놓아"); whisper's cuff / cop for cup ----------
+_HELD_IT = (rf"(?:it|that|this|one|them|(?:the|your|this|that) (?:\w+ )?(?:{_OBJ}|cuff|cop|thing)s?)"
+ r"(?=\s*(?:[,.!;]|$)|\s+(?:now|already|too|so|and|you|let|open|release|please|thanks?|lumi|firmly|tight|safely|"
+ r"right|here|in my|with my)\b)")
+HOLDS_IT_EN = re.compile(
+ rf"\bi(?:'m| am)\s+(?:now\s+|already\s+|still\s+)?(?:holding|gripping|grabbing|carrying|grasping)(?:\s+on\s*to)?\s+{_HELD_IT}|"
+ rf"\bi(?:'ve| have)\s+(?:now\s+|already\s+|just\s+)?(?:got\s+)?(?:(?:a (?:good |firm )?)?(?:hold|grip) (?:of|on)\s+)?{_HELD_IT}|"
+ rf"\bi(?:'ve| have)?\s+(?:already\s+|just\s+)?(?:took|taken|grabbed|caught|got hold of|got a (?:good |firm )?grip on)\s+{_HELD_IT}|"
+ rf"\bi got (?:the|your) (?:\w+ )?(?:{_OBJ}|cuff|cop)s?\b|\bit(?:'s| is) (?:already |now )?in my hands?\b|"
+ rf"\bmy hands? (?:is|are) on (?:it|the (?:{_OBJ}|cuff))\b", re.I)
+HOLDS_IT_KO = re.compile( # "잡고 있어" / "들고 있어" alone is an order to Lumi (keep holding): a claim needs 내가 / 제가
+ r"(?:내가|제가|나|저|i)\s+(?:\S+\s+){0,2}?(?:잡고|들고|쥐고|붙잡고|받치고|hold\w*\s*하고|holding\s*하고)\s*있|"
+ r"(?:내가|제가|나|저|i)\s+(?:\S+\s+){0,2}?(?:잡았|들었|받았|쥐었|가졌)|(?= 0 else -1.0
for a in (side * head.YAW_LIMIT, -side * head.YAW_LIMIT):
log(f" look me: nobody seen, looking at {a:+.0f} deg")
@@ -1185,10 +1184,19 @@ class Lumi:
time.sleep(LOOK_ME_SETTLE_S) # new head camera frames from there
seen = self.vision.seen(LOOK_ME_MAX_M)
if seen:
- found, why = min(seen, key=lambda s: abs(s[0] - a)), "found looking around"
- break
- if found is None and voice is None: # an unsure voice still gives the side
- voice = getattr(self, "voice_guess", None)
+ return min(seen, key=lambda s: abs(s[0] - a)), "found looking around"
+ return None, ""
+
+ if found is None: # nobody in view: the head camera looks around first
+ if voice is None: # an unsure voice still picks the side
+ voice = getattr(self, "voice_guess", None)
+ found, why = sweep(gaze if voice is None else voice)
+ w = waist_turned()
+ if found is None and abs(w) > LOOK_ME_WAIST_DEG and waist_home("looking for the caller"):
+ voice = None if voice is None else voice + w # the cameras turn with the waist: a caller on the
+ gaze = 0.0 # other side of it was in no view; again from the front
+ log(f" look me: waist from {w:+.0f} deg to the front")
+ found, why = sweep(0.0 if voice is None else voice)
if found is None and voice is not None and abs(voice) <= head.YAW_LIMIT: # nobody where the head looked: the
voice = (180.0 - abs(voice)) * (1.0 if voice >= 0 else -1.0) # array mixes front and back
if found is None and voice is not None:
@@ -2024,6 +2032,10 @@ class Lumi:
elif kind == "refuse":
if not (what == brain_mod.REFUSE_OPEN and self.release_giving()):
self.fetch_say(*what)
+ elif kind == "release": # "I've got it", "내가 잡고 있어": they hold it, open
+ if not self.release_giving():
+ self.fetch_say("Okay, I'm letting go.", "네, 놓을게요.")
+ safe(fetch.let_go)
elif not held:
mouth.say(EMPTY_HAND_SAY[self.lang])
else:
@@ -2086,7 +2098,7 @@ class Lumi:
safe(fetch.stop)
self.act("stop", "")
self.fetch_say("Okay, I stopped.", "네, 멈췄어요.")
- elif (FETCH_THANKS.search(text) and fetch.state().get("step") == "giving") or \
+ elif ((FETCH_THANKS.search(text) or brain_mod.person_holds(text)) and fetch.state().get("step") == "giving") or \
(RECEIVE_OK.search(text) and fetch.state().get("step") == "receiving: waiting for okay"):
safe(fetch.release_now) # the person has taken it
elif status == "holding" and not (brain_mod.direct_order(text) and not brain_mod.not_an_order(text)):
@@ -2217,7 +2229,8 @@ class Lumi:
person (the tracked one, else the one the voice came from, else the voice's direction): further than
REACH_COME_M the base comes to them first (come_to); the head turns to them; the hand further from them than
REACH_FRONT_DEG: the waist turns first, until the hand (not the waist's front) points at them (reach_turn, Greeter only too: the base
- stays); then fetch.reach (give pose along the graph, a short checked move toward their hand). The arm folds back on "thanks" / "okay" or after REACH_HOLD_S (reach_done).
+ stays); then fetch.reach (give pose along the graph, a short checked move toward their hand). The arm folds back on the next words that
+ are no arm order or after REACH_HOLD_S (reach_done).
True when started, None when refused or handed over (said)."""
from tasks import fetch
if held:
@@ -2275,15 +2288,21 @@ class Lumi:
return True, track
def reach_done(self, text=None):
- """The hand is held out (reach_out) and the reach has ended: "thanks" / "okay" / "고마워" / "됐어" (`text`) or
- REACH_HOLD_S without one folds the arm back to look. True when it folded."""
- if not getattr(self, "reached_at", 0.0) or self.fetch_status() == "running":
+ """The empty hand is held out (reach_out): whatever is said next that is no arm order (thanks, a question,
+ another order; the caller leaves arm orders out) or REACH_HOLD_S without a word folds the arm back to look
+ first, also while the reach still goes toward their hand (it is stopped) or after it failed (the hand stayed
+ out in give, 2026-10-30). After a stop word the arm stays where it is. True when it folded."""
+ from tasks import fetch
+ if not getattr(self, "reached_at", 0.0):
return False
- if text is None and time.time() - self.reached_at < REACH_HOLD_S or text is not None and not REACH_DONE.search(text):
+ if text is None and time.time() - self.reached_at < REACH_HOLD_S:
return False
- if self.fetch_status() != "done": # the reach failed or was stopped: the arm stays as it is
- self.reached_at = 0.0
+ status = self.fetch_status()
+ if status == "stopped" or status == "running" and safe(fetch.state, default={}).get("step") != "reaching out":
+ self.reached_at = 0.0 # stopped by a word, or another task has the arm now
return False
+ if status == "running":
+ safe(fetch.stop)
log(f" reach over ({'said ' + repr(text) if text else 'timeout'}): the arm back to look")
return bool(self.arm_pose("fold"))
@@ -2771,9 +2790,18 @@ class Lumi:
def who_spoke(self, u, text=None):
"""Use the sound direction: pick the visible person who spoke; meanwhile collect calibration samples. Someone
else near the voice takes the talk over (and the head) only with a call, a stop word or an order in `text`;
- other words keep the focus on the person talked with."""
+ other words keep the focus on the person talked with. Then the head turns to the one it talks with (else the
+ only one in view), sure voice or not: it answered people a little to the side looking ahead (2026-10-30). A
+ held look ("look left") and a task's aim keep the head (turn_head)."""
if not self.vision or u is None:
return
+ if self._who_spoke(u, text): # someone else took over: face() turned to them
+ return
+ t = self.current if self.current is not None and self.vision.present(self.current) else self.vision.only_person()
+ if t is not None and abs(t.angle - HEAD_SIGN * self.det_yaw()) > FOCUS_DEG:
+ self.turn_head(HEAD_SIGN * max(-head.YAW_LIMIT, min(head.YAW_LIMIT, t.angle)))
+
+ def _who_spoke(self, u, text):
self.voice_trusted = False # set again below only from this turn's own sound
self.voice_guess = None # this turn's direction, sure or not
yaw = self.det_yaw()
@@ -2810,6 +2838,7 @@ class Lumi:
if getattr(self, "look_me", None) is not None: # a "look at me" hold was for the one before
self.looked_at, self.look_me = 0.0, None
self.face(t)
+ return True
def det_yaw(self):
"""Current head yaw (deg), read from the body every 0.3 s (the torso camera does not know it)."""
@@ -3098,7 +3127,9 @@ class Lumi:
if NAME_ONLY.match(text): # just "Lumi?": they want attention, the head turns to them
look = threading.Thread(target=self.look_at_speaker, daemon=True) # while it answers
look.start()
- mouth.say(random.choice(NAME_REPLY["en" if self.lang == "en" else "ko"]))
+ reply = random.choice(NAME_REPLY["en" if self.lang == "en" else "ko"])
+ log(f" name call: {reply!r}") # every call is answered: the log shows it was
+ mouth.say(reply)
look.join()
self.keep_listening()
return
@@ -3142,7 +3173,7 @@ class Lumi:
if self.fetch_voice(text): # before the closing words: "thank you" while giving
return
if not (kind == "quick" and data and data[0] == "arm"):
- self.reach_done(text) # "okay, thanks" with the hand held out: the arm back to look
+ self.reach_done(text) # "okay, thanks", any other words: a held-out hand to look
place = consent_place(text, self.brain, self.markers)
if place: # "p3로 갈 수 있어요?" ... "그럼 가 보세요."
self.go_offered(place)
@@ -3303,7 +3334,10 @@ class Lumi:
if follow.running(): # following: talk_turn listens to the followed person only
return False
u = self.mic.next(0.0)
- if u is None or not (0.3 <= u.seconds <= WAKE_MAX_S):
+ if u is None or u.seconds < 0.3:
+ return False
+ if u.seconds > WAKE_MAX_S: # logged: a call lost in a long sound shows up in the log
+ log(f" {u.seconds:.1f} s of sound: too long to be a call, not checked")
return False
during = getattr(u, "during_speech", False) # said while Lumi talks: only a stop word counts
text = ears.transcribe(u.mono)
@@ -3312,6 +3346,8 @@ class Lumi:
self.stop_all()
return True
if during:
+ if text and WAKE.search(text):
+ log(f" heard {text!r} while I talked: not taken as a call (it could be my own voice)")
return False
m = WAKE.search(text or "")
if not m and HELLO_ONLY.match(text or ""): # a plain "Hi!" / "Hey" said on its own
@@ -3342,7 +3378,9 @@ class Lumi:
look = threading.Thread(target=self.look_at_speaker, daemon=True) # as "look at me": the cameras, the
look.start() # voice's side, behind; turns while it answers
if not command: # just "Hi Lumi": a short answer, then listen
- mouth.say(random.choice(WAKE_REPLY[lang]))
+ reply = random.choice(WAKE_REPLY[lang])
+ log(f" wake reply: {reply!r}")
+ mouth.say(reply)
look.join()
self.voice_until = time.time() + VOICE_SESSION_S
self.last_activity, self.prompts = time.time(), 0
@@ -4015,7 +4053,8 @@ def route(text, markers, b, holding=False, seen=None, last="", chain_ok=True):
arm_rule = brain_mod.intent(text, markers) # "would it be possible to wave at me?"); intent() itself refuses
if arm_rule and arm_rule[0] in ("wave", "arm"): # negations, later times, remarks, ability questions (A1)
return arm_quick(arm_rule, holding)
- if hold and not ((brain_mod.held_give(text, markers) or brain_mod.held_place(text, markers)) and
+ if hold and not ((brain_mod.held_give(text, markers) or brain_mod.held_place(text, markers) or
+ brain_mod.person_holds(text, b)) and
(holding() if callable(holding) else holding)): # "테이블에 놔 줄래? 영상 찍고 있어": the hand's
rule = brain_mod.intent(text, markers) # weather / search are no motion: "Weather outside?"
return (("end", None) if talk_fate(text) == "end" else ("sing", None) if sing.asked(text, last) else
diff --git a/docs/TUNING.md b/docs/TUNING.md
index 4e4fbd3..18d8e97 100644
--- a/docs/TUNING.md
+++ b/docs/TUNING.md
@@ -30,6 +30,7 @@ Every value here is a constant at the top of its file, with a comment on what it
| `manipulation/arm_route.py` | `LINK_HEAD_CLEAR_MM` | 220 mm | Every arm link (elbow, wrist) keeps this from the head's turning centre on every pose-graph move. Estimate below the least of the taught graph (267 mm at `wave`) |
| `manipulation/arm_route.py` | `JOIN_DEG` | 20° | An arm at no pose (free drive, stopped half way) joins the graph by one checked joint move to a pose, the nearest first; joins further than this run at the slow speed |
| `manipulation/arm_route.py` | `UP_MM` | 100, 200 mm | When no direct join passes the checks, the arm first goes this far straight up, then joins |
+| `manipulation/arm_route.py` | `FLIP_STEPS` | 4 | When neither passes and the wrist is turned over against the taught poses (J5's sign flipped), it first turns back where it is in this many checked joint moves (J4 and J6 half a turn against each other, J5 through 0, J1–J3 holding the grasp point); fewer steps let the gripper dip more between them |
| `robot/arm.py` | `RETRIES`, `RETRY_S` | 5, 0.2 s | A dropped controller connection is retried this often, the wait doubling each time (3 s in all); the controller closes connections for ~0.5 s every few seconds |
| `manipulation/arm_route.py` | `AT_POSE_DEG`, `EXACT_DEG` | 3°, 1° | At a pose for programs and `check` / further than 1° from the nearest pose a route first goes to it |
| `api/dashboard.html` | `MAP_POLL_MS` | 20000 ms | The dashboard reads the map's markers again this often (markers added on the base, a map switched) |
@@ -115,6 +116,7 @@ Every value here is a constant at the top of its file, with a comment on what it
| `tasks/fetch.py` | `HEAD_READS`, `HEAD_SAME_MM` | 4, 120 mm | Head camera frames read per view; a thing counts when seen at least twice within this distance |
| `tasks/fetch.py` | `HEAD_SIDE_DEG` | 60° | Head yaw towards the side of a turn on the spot, for the arm-sweep check (`head_hits`) |
| `tasks/fetch.py` | `HEAD_LOW_PITCH` | −5° | Head pitch for the search and `head_hits` (its lowest, where the head camera is calibrated) |
+| `tasks/fetch.py` | `HEAD_AIM_DEG`, `HEAD_AIM_EVERY_S` | 8°, 0.5 s | Once the object or the place is found, the head stays on it (approach, pick, put down): it turns back when the target is more than this far off its direction, checked this often while the base drives |
| `manipulation/skills.py` | `FRAME_LAG_S`, `FRESH_WAIT_S` | 0.15 s, 2 s | After a lift / waist / head / base move, depth and detections come from the first frame written this long after it (no fixed wait); give up after the second |
| `tasks/fetch.py` | `COAST_S` | 0.3 s | Frames after a straight `joy_control` drive are taken from this long after the stop. Estimate |
| `tasks/fetch.py` | `DRIVE_POLL_S`, `DRIVE_START_S` | 0.2 s, 3 s | Base status reads while driving; a drive not seen "running" counts as over after the second (at once when it reports "succeeded" at the goal pose) |
@@ -152,6 +154,7 @@ Every value here is a constant at the top of its file, with a comment on what it
| `tasks/fetch.py` | `PLACE_GRID_X`, `PLACE_GRID_Y` | x −260…−60 step 40, y 640…740 mm | Place spots tried in front (after the pick spot); IK refuses the ones out of reach |
| `tasks/fetch.py` | `PLACE_LOW_Z` | −480 mm | A level top lower than this (arm frame, lift 0) is a seat, never a place |
| `tasks/fetch.py` | `KEEP_R_MM`, `KEEP_STEP_MM`, `KEEP_TOL_MM` | 400, 40, 40 mm | A table seen once is kept on the map; after each move it is looked for only within this radius of its kept spot (on this grid) and this close to its kept height |
+| `tasks/fetch.py` | `KEEP_EDGE_MM` | 30 mm | Its level top is kept on the map too; a spot put on from memory (where the camera no longer sees it) lies at least this far in from the last level point seen in every direction |
| `tasks/fetch.py` | `PLACE_NAV_MAX` | 2 | Navigation drives round to a kept table at most this often per place, then straight ways only |
| `tasks/fetch.py` | `PLACE_GOAL` | (−160, 670) mm | Where the base brings a table spot seen further away |
| `tasks/fetch.py` | `FAR_R_MM`, `FAR_HALF_DEG`, `FAR_IN_MM` | 0.6–3 m, ±45°, 150 mm | A table further away: level tops looked for on sight lines this far, within this of where the camera looks; the base goes to the point this far in from its nearest edge |
@@ -185,6 +188,24 @@ Every value here is a constant at the top of its file, with a comment on what it
| `manipulation/skills.py` | `MIN_SEEN` | 5 of 8 frames | An object must be seen this often at the same place |
| `manipulation/skills.py` | `HAND_PROBE_MM`, `HAND_NEAR_MM`, `HAND_FAR_MM` | 30/50/70, 60, 250 mm | In-hand check by depth (`hand_sees`) |
+## Wave greeting
+
+| File | Name | Default | What it does |
+|---|---|---|---|
+| `tasks/wave_greet.py` | `GREET_M` | 3.0 m | People waving further away (head camera depth) are not answered |
+| `tasks/wave_greet.py` | `HOLD_S` | 60 s | The hand stays up this long after the last wave seen, then goes down to `look` |
+| `tasks/wave_greet.py` | `DOWN_SPEED` | "normal" | `motion.JOINT_SPEED` of the way down; the way up is `arm_route.SPEED` / `wave.ARRIVE_SPEED` (route, the Cobo π limit) |
+| `tasks/wave_greet.py` | `SWING_SPEED` | "swing" | `motion.JOINT_SPEED` of its swings (an asked wave uses `wave.SWING_SPEED`) |
+| `robot/motion.py` | `SPEED_ACCEL_FACTOR` | swing 4.0 | A joint speed with its own acceleration factor instead of `JOINT_ACCEL_FACTOR`: "swing" (60 °/s, 240 °/s²) for the greeting's short swings. Higher = snappier swings, more shaking |
+| `tasks/wave_greet.py` | `NEW_WAVE_S` | 5 s | No waving this long: the next wave gets a new greeting line |
+| `tasks/wave_greet.py` | `JOKE_AFTER_S`, `JOKE_EVERY_S` | 10 s, 12 s | Waving on and on: the first joke after this long, then one every this long |
+| `tasks/wave_greet.py` | `WAIST_MIN_DEG` | 10° | A person nearer the front than this: only the head turns, not the waist |
+| `tasks/wave_greet.py` | `WAIST_PARTS` | 1, 0.75, 0.5, 0.25 | A waist turn whose sweep is blocked is tried again this much of the way; the head covers the rest |
+| `tasks/wave_greet.py` | `REFUSED_S` | 30 s | After a refused wave (arm off, busy, holding) the next try waits this long |
+| `vision/waving.py` | `WINDOW_S`, `MIN_FLIPS` | 2 s, 2 | A wave: the hand's sideways motion changes direction this often within this long. Shorter window = quicker start and stop, slow waves missed |
+| `vision/waving.py` | `FLOW_PX` | 1.0 px / frame | Sideways hand motion (half-size frame) that counts as a swing. Lower = smaller waves count, more false waves |
+| `tasks/wave_lines.py` | `GREET`, `LONG` | 25 each | What Lumi says: greetings, and jokes for a long wave (English, Korean) |
+
## Voice
| File | Name | Default | What it does |
diff --git a/manipulation/arm_route.py b/manipulation/arm_route.py
index 841ef13..5a89c1f 100644
--- a/manipulation/arm_route.py
+++ b/manipulation/arm_route.py
@@ -13,8 +13,11 @@ the hand only the EDGES (fetch runs them as straight lines, the cup upright) and
arm at no pose (after free
drive, after a stop half way) joins the graph by one checked joint move to a pose of it, the nearest first; when no
such move passes, first straight up by UP_MM (a joint move to the IK pose above, checked the same way), then the
-join. Joins further than JOIN_DEG run at HOLD_SPEED. Only when nothing passes, nothing moves and Lumi asks for the
-arm to be brought near `look` by hand. A task's own
+join. When neither passes and the wrist is turned over against the taught poses (J5's sign flipped, J4 / J6 half a
+turn off: a straight move that ended on the other IK branch, free drive), it first turns back where it is (flip):
+FLIP_STEPS joint moves, J4 and J6 against each other, J5 through 0, J1-J3 holding the grasp point, each checked as
+every move is (the cup upright). Joins further than JOIN_DEG run at HOLD_SPEED. Only when nothing passes, nothing
+moves and Lumi asks for the arm to be brought near `look` by hand. A task's own
way back from the table (`leaf`: it went out from `look` along a checked plan) goes straight to its target.
Each joint move is checked at PATH_POINTS points (kine_forward): joint limits, no joint turning further than
@@ -66,6 +69,10 @@ AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every join
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 this close to one (every joint) joins it at the route speed
UP_MM = (100.0, 200.0) # mm straight up tried before a join when no direct join passes
+FLIP_STEPS = 4 # joint moves turning a turned-over wrist back (flip): 45 deg of J4 / J6 each.
+ # Offline, from the live stuck pose: 3 let the gripper dip 28 mm, 4 kept it within 16
+HOLD_MM = 0.5 # mm; flip: the grasp point is held where it was this closely at each step
+HOLD_STEPS = 20 # ... Newton steps on J1-J3 at most (offline, the live stuck pose: 7)
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
@@ -317,19 +324,61 @@ def _up(now, mm):
return r.get("jointPosition")
+def _grasp_point(j):
+ return _gripper(skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"])[1]
+
+
+def _hold(j, want):
+ """`j` with J1-J3 turned (Newton steps on kine_forward) so the grasp point is at `want` (mm); None when it does not
+ come within HOLD_MM in HOLD_STEPS."""
+ j = np.array(j, float)
+ for _ in range(HOLD_STEPS):
+ g = _grasp_point(j)
+ if np.linalg.norm(want - g) < HOLD_MM:
+ return [float(v) for v in j]
+ J = np.stack([(_grasp_point(j + 0.01 * np.eye(6)[i]) - g) / 0.01 for i in range(3)], 1)
+ j[:3] += np.clip(np.linalg.lstsq(J, want - g, rcond=None)[0], -5.0, 5.0)
+ return None
+
+
+def flip(now):
+ """Joints of the FLIP_STEPS joint moves that turn the wrist at `now` over where it is: J4 and J6 half a turn against
+ each other (the same way round they would tumble a held cup), J5 through 0 to minus itself, J1-J3 holding the grasp
+ point (_hold) on the way; the last one is `now`'s other wrist solution of the same flange pose. Either way round
+ J4 turns, inside the joint limits; None when the grasp point can't be held."""
+ g0 = _grasp_point(now)
+ for s in (1.0, -1.0):
+ end = [*now[:3], now[3] + 180.0 * s, -now[4], now[5] - 180.0 * s]
+ if any(abs(v) > lim - motion.LIMIT_MARGIN for v, lim in zip(end, motion.LIMITS)):
+ continue
+ way = [_hold([a + (b - a) * k / FLIP_STEPS for a, b in zip(now, end)], g0) for k in range(1, FLIP_STEPS)]
+ if None not in way:
+ return way + [end]
+ return None
+
+
def join(now, target, holding=False, skip=()):
"""[(pose, joints)] of a checked way from an arm at no pose of the graph to `target`: one joint move to a graph
- pose (the nearest first), then along the graph; else first straight up by UP_MM. RouteError(UNKNOWN) when no way
- passes the checks; nothing moved."""
+ pose (the nearest first), then along the graph; else first straight up by UP_MM; else, with the wrist turned over
+ (its other solution nearer the graph), first the wrist turned back where it is (flip). RouteError(UNKNOWN) when no
+ way passes the checks; nothing moved."""
nodes = graph(holding, skip)
if target not in nodes:
raise RouteError(*(SPILL if holding and target in WAVE_POSES else NOT_TAUGHT))
- order = sorted(nodes, key=lambda n: (_deg(now, nodes[n]), n != HOME))
- for mm in (None, *UP_MM):
- first = [] if mm is None else [("up", _up(now, mm))]
- if first and first[0][1] is None:
+ near = lambda j: min(_deg(j, p) for p in nodes.values())
+
+ def firsts(): # asked only when the one before found no way
+ yield []
+ for mm in UP_MM:
+ yield [("up", _up(now, mm))]
+ over = flip(now)
+ if over and near(over[-1]) < near(now):
+ yield [("wrist", j) for j in over]
+ for first in firsts():
+ if first and first[-1][1] is None:
continue
- for n in order: # the nearest pose first, then the way on from it
+ here = first[-1][1] if first else now
+ for n in sorted(nodes, key=lambda n: (_deg(here, nodes[n]), n != HOME)): # the nearest pose first, then on
try:
way = first + [(x, nodes[x]) for x in route(n, target, nodes, holding)]
return list(zip([x for x, _ in way], check_moves(now, [j for _, j in way], holding)))
diff --git a/robot/motion.py b/robot/motion.py
index 4b7e20c..0b63ffa 100644
--- a/robot/motion.py
+++ b/robot/motion.py
@@ -25,12 +25,14 @@ ROOT = Path(__file__).resolve().parents[1] # the project folder
POSES_FILE = ROOT / "data" / "arm_poses.json"
LIMITS = [360, 125, 130, 360, 120, 360] # deg, ± factory range per joint (docs/01_HARDWARE.md)
LIMIT_MARGIN = 5.0 # deg kept away from every limit
-JOINT_SPEED = {"slow": 20.0, "normal": 50.0, "quick": 50.0, "route": 60.0} # deg/s; slow / normal doubled for picks and
+JOINT_SPEED = {"slow": 20.0, "normal": 50.0, "quick": 50.0, "route": 60.0, "swing": 60.0} # deg/s; slow / normal doubled for picks and
# puts (owner, 2026-10-29); route: empty-hand pose-graph moves (the Cobo π joint speed limit, 60)
LINEAR_SPEED = {"slow": 40.0, "normal": 100.0} # mm/s; slow / normal doubled for picks and puts (owner, 2026-10-29)
ACCEL_FACTOR = 3.0 # straight moves: accel = speed x this (per s)
JOINT_ACCEL_FACTOR = 1.5 # joint moves: accel = speed x this (per s); estimate: x 3
# stopped at each pose with a jolt that shook the robot
+SPEED_ACCEL_FACTOR = {"swing": 4.0} # a speed with its own accel factor: the greeting's short swings
+ # (14.7 deg of J3) never reach their speed at 1.5
MAX_FLIP = 90.0 # deg; an IK answer turning J1 / J4 / J6 more than this is refused
MAX_TRAVEL = 200.0 # deg; a joint move turning any joint further is refused
FULL_TURN = (0, 3, 5) # J1, J4, J6: ±360 joints; a target and target ± 360 are the same pose
@@ -191,7 +193,7 @@ def move_path(moves, wait=True, queued=False):
if k and not queued and _stopped.wait(SETTLE_S):
raise MotionError("stopped")
deg_s = JOINT_SPEED[speed]
- r = arm.cmd("joint_move", relFlag=0, jointPosition=list(t), speed=deg_s, accel=deg_s * JOINT_ACCEL_FACTOR)
+ 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()
raise MotionError("stopped")
diff --git a/tasks/fetch.py b/tasks/fetch.py
index cae3017..6908b83 100644
--- a/tasks/fetch.py
+++ b/tasks/fetch.py
@@ -75,6 +75,9 @@ PLACE_LOW_Z = -480.0 # mm, arm frame at lift 0: a level top lowe
KEEP_R_MM = 400.0 # mm; a table kept on the map is looked for again within this of its kept spot ...
KEEP_STEP_MM = 40.0 # ... on a grid this fine ...
KEEP_TOL_MM = 40.0 # ... at its kept height +- this (measured from 1.5 m it can be ~30 mm off)
+KEEP_CELL_M = 0.01 # m; the kept table's level points are remembered one per cell this size
+KEEP_EDGE_MM = 30.0 # mm; a spot of the kept table put on from memory lies at least this far in from
+ # the last level point seen in every direction (_kept_spots)
PLACE_NAV_MAX = 2 # navigation drives round to a kept table at most this often, then straight ways only
TOP_NEAR_MM = 1500.0 # mm from the arm base; a named thing's top measured further away is not trusted
# (2026-10-20 a white thing 3.8 m away read -258, then -620 mm): go closer first
@@ -148,6 +151,9 @@ SELF_MM = 120.0 # depth this near the hand (flange -> grasp point -
# a finger 122 mm from the grasp point stopped a waist turn (2026-10-20)
HEAD_SIDE_DEG = 60.0 # head yaw (+ left) towards the side of a turn, to check the arm's sweep (head_hits)
HEAD_LOW_PITCH = -5.0 # head pitch for those checks and the search: its lowest, where the camera is calibrated
+HEAD_AIM_DEG = 8.0 # deg the target (the object to pick, the table / spot to put on) may drift off the head's
+ # direction before the head turns back onto it (_aim_head; as lumi.py FOCUS_DEG for a person)
+HEAD_AIM_EVERY_S = 0.5 # s between those checks while the base drives (as lumi.py FOCUS_EVERY_S)
HEAD_READS = 4 # head camera frames read per view (10 a second) ...
HEAD_SAME_MM = 120.0 # ... an object counts when seen at least twice within this distance
WAIST_VEL = 30 # % of the waist's speed: the arm sweeps sideways
@@ -222,7 +228,9 @@ _leg = {"rest": None, "tries": 0} # the steps from the drive running
_pause = threading.Event() # set by pause() (someone talks to Lumi on the way): drives halt, the run
# waits at the next step; resume() goes on where it was
_thread = None
-stay_put = False # set by assistant/lumi.py for a task asked by voice with only Greeter on:
+_aim = {"world": None, "z": 0.0, "thread": None} # the head's target once found: map point (m), height (mm, arm
+ # frame), the head move running while the base drives (_aim_head)
+stay_put = False # set by assistant/lumi.py for a task asked by voice with only Greeter on:
# head and lift only, no base move, no waist turn (NEED_PATROL)
NEED_PATROL = ("For that I'd have to drive or turn. Switch on Patrol, please.",
"그러려면 이동하거나 돌아야 해요. 패트롤을 켜 주세요.")
@@ -461,34 +469,50 @@ def _line_rows(target, label, start=None):
return rows
-def _line_holding(name):
+def _line_holding(name, join=True):
"""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."""
+ pose, all lines IK-, tilt- and head-checked before the first one starts, and where a line ends on the other wrist
+ branch, the joint move onto the pose's own joints too; after each line the pose's exact joints. When that is
+ refused, `join`: arm_route's checked joint moves from where the arm is (plan: a join, the wrist turned back, up
+ first), the cup upright. Nothing when it is there already."""
_go_on()
if _at_pose(name):
return
+ now = skills._joints()
try:
- names = arm_route.hops(skills._joints(), name, leaf=True, holding=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)
+ names = arm_route.hops(now, name, leaf=True, holding=True)
+ lines, start = [], None
+ for n in names:
+ j = motion.poses()[n]
+ target = skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"]
+ end = _line_rows(target, f"to {n}", start)[-1][2]
+ if max(abs(a - b) for a, b in zip(motion.nearest(j, end), end)) > 1.0: # live 2026-10-30: the line to
+ arm_route.check_moves(end, [j], holding=True) # give ended with the wrist turned over, stuck there
+ lines.append((n, target))
+ start = (target, j)
+ except (FetchError, arm_route.RouteError) as e:
+ if not join:
+ raise FetchError(*e.args) from e
+ try:
+ seq = arm_route.plan(name, holding=True, now=now)
+ except arm_route.RouteError:
+ raise FetchError(*e.args) from e
+ arm_route.move(seq, holding=True)
+ _go_on()
+ return
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)
+ if not _at_pose(n): # the pose's own joints (the controller's line ended elsewhere)
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)
+ motion.go(n, skills.HOLDING_SPEED)
+ except arm_route.RouteError: # e.g. the wrist turned over: arm_route's checked way from here
+ try:
+ arm_route.move(arm_route.plan(n, holding=True), holding=True)
+ except arm_route.RouteError as e:
+ raise FetchError(*e.args) from e
def _look():
@@ -508,11 +532,15 @@ def _wait_drive(watch_holding=False, again=None, goal=None):
try:
_drive_wait(watch_holding, again, goal)
finally:
+ t = _aim["thread"] # the head's last turn onto the target ends before the next step
+ while t is not None and t.is_alive() and not _stop.wait(0.1):
+ pass
skills.moved() # the cameras moved with the base: frames from now on
def _drive_wait(watch_holding, again, goal):
t0 = last_hold = time.time()
+ last_aim = 0.0
seen_running = False
anchor = None # (x, y, time) of the last real progress
while True:
@@ -537,6 +565,9 @@ def _drive_wait(watch_holding, again, goal):
st = full.get("move_status")
seen_running = seen_running or st == "running"
pose = full.get("current_pose")
+ if st == "running" and time.time() - last_aim >= HEAD_AIM_EVERY_S:
+ last_aim = time.time()
+ _aim_head(wait=False) # the head stays on the target while the base turns and drives
if st == "running" and pose:
if anchor is None or math.hypot(pose["x"] - anchor[0], pose["y"] - anchor[1]) > STUCK_M:
anchor = (pose["x"], pose["y"], time.time())
@@ -674,6 +705,74 @@ def _head_to(yaw, pitch):
skills.moved("head")
+def _aim_at(thing):
+ """From now on the head keeps to `thing` ({"x", "y"} mm in the arm frame now, "top_mm" its height when known):
+ its map place is kept, so it is found again after every base and waist move. None (a search, a drive to a place,
+ the object in the hand): no target, the head is free again."""
+ w = None if thing is None else map_xy(thing)
+ _aim.update(world=w, z=float((thing or {}).get("top_mm") or 0.0))
+
+
+def aiming():
+ """A task keeps the head on its target now (assistant/lumi.py leaves the head alone meanwhile); never after a
+ STOP."""
+ return _aim["world"] is not None and not _stop.is_set()
+
+
+def _head_yaw_for(p):
+ """Head yaw (deg, cut to head.YAW_LIMIT, 1 deg steps) that puts the arm-frame point `p` (x, y, z mm) in the
+ middle (left / right) of the head camera's view at HEAD_LOW_PITCH; None before the head camera is calibrated.
+ ponytail: the pitch stays HEAD_LOW_PITCH, everything picked or put on is below the head (its lowest pitch)."""
+ best = None
+ for yaw in np.arange(-head.YAW_LIMIT, head.YAW_LIMIT + 0.5, 1.0):
+ T = head_cam.base_from_head(float(yaw), HEAD_LOW_PITCH)
+ if T is None:
+ return None
+ q = np.linalg.inv(T) @ [p[0], p[1], p[2], 1.0]
+ off = abs(math.atan2(q[0], q[2]))
+ if best is None or off < best[0]:
+ best = (off, float(yaw))
+ return best[1]
+
+
+def _aim_head(thing=None, wait=True):
+ """The head onto the target (`thing`: a new one, _aim_at) when it is more than HEAD_AIM_DEG off. wait=False (the
+ base drives, _drive_wait): the move runs in its own thread, one at a time, and the drive goes on. A head error is
+ logged, never the end of the task."""
+ if thing is not None:
+ _aim_at(thing)
+ t = _aim["thread"]
+ if t is not None and t.is_alive():
+ if not wait:
+ return
+ while t.is_alive() and not _stop.wait(0.1):
+ pass
+ if _aim["world"] is None or arm_yaw() is None:
+ return
+ try:
+ x, y = arm_frame(_aim["world"])
+ yaw = _head_yaw_for((x, y, _aim["z"]))
+ if yaw is None:
+ return
+ lift, waist, y0, p0 = head.status()
+ if abs(yaw - y0) <= HEAD_AIM_DEG and abs(p0 - HEAD_LOW_PITCH) < 1.0:
+ return
+ if wait:
+ _head_to(yaw, HEAD_LOW_PITCH)
+ return
+
+ def run():
+ try:
+ head.moveto([lift, waist, yaw, HEAD_LOW_PITCH])
+ skills.moved("head")
+ except OSError as e:
+ log(f"head to the target: {e}")
+ _aim["thread"] = threading.Thread(target=run, daemon=True)
+ _aim["thread"].start()
+ except OSError as e:
+ log(f"head to the target: {e}")
+
+
def head_hits(deg, pts=None):
"""depth_hits with the head camera turned towards the side of the turn: the torso camera sees only ahead, the arm
sweeps to the side. None when clear, or when the head camera is not calibrated (then the other checks decide).
@@ -752,7 +851,8 @@ def _waist_to(rel, in_place=False, look=None):
def head_ahead():
- """Turn the head to HEAD_AHEAD (lift and waist stay) unless it is there already."""
+ """Turn the head to HEAD_AHEAD (lift and waist stay) unless it is there already; it has no target then."""
+ _aim_at(None)
lift, waist, yaw, pitch = head.status()
if abs(yaw - HEAD_AHEAD[0]) > 1.0 or abs(pitch - HEAD_AHEAD[1]) > 1.0:
head.moveto([lift, waist, *HEAD_AHEAD])
@@ -802,10 +902,13 @@ def _head_ok():
def _look_at(view, attempt):
"""Both cameras towards `view` deg from the front (+ left): the waist as far as WAIST_SCAN_MAX (when its sweep is
- clear and the arm's yaw is measured), the head the rest; then attempt()."""
+ clear and the arm's yaw is measured), the head the rest, or onto the target once one was found (_aim_head);
+ then attempt()."""
if arm_yaw() is not None:
_waist_to(max(-WAIST_SCAN_MAX, min(WAIST_SCAN_MAX, view)))
- if _head_ok():
+ if aiming():
+ _aim_head()
+ elif _head_ok():
_head_to(view - _waist_turn(), HEAD_LOW_PITCH)
return attempt()
@@ -827,6 +930,7 @@ def _look_around(attempt, holding=False, say=None):
head turns the rest), then to the other side. (c) The base turns towards that side (_search_turn) and all of it
again. (d) The lift goes to the other end of LIFT_TRIES and (a)-(c) again. Returns what attempt() found (the waist
and the head stay where it was seen), else None with the waist at the front."""
+ _aim_at(None) # the head looks around with the waist: no target while searching
got = _look_at(0.0, attempt)
if got is not None:
return got
@@ -1150,10 +1254,10 @@ def _is_task(o, task):
def arm_frame(world):
- """A map point (m) in the arm base frame now (mm)."""
+ """A map point (m), or an (N, 2) array of them, in the arm base frame now (mm)."""
x, y, th = agv.pose()
- b = _rot(-math.degrees(th)) @ (np.asarray(world, float) - [x, y])
- return _rot(-arm_yaw()) @ (b - arm_xy()) * 1000.0
+ b = (np.asarray(world, float) - [x, y]) @ _rot(-math.degrees(th)).T
+ return (b - arm_xy()) @ _rot(-arm_yaw()).T * 1000.0
def _go_to(thing, goal, tried, holding=False):
@@ -1173,6 +1277,7 @@ def _near_look(attempt, holding=False):
from the base). None when nothing is near or nothing is seen."""
if stay_put or _charging():
return None
+ _aim_at(None) # a search: the head looks with the waist
x, y, th = agv.pose()
near = [math.radians(d) for d in np.arange(-157.5, 180.1, 22.5)
if agv.clearance(x + NEAR_RING_M * math.cos(th + math.radians(d)),
@@ -1311,6 +1416,7 @@ def _approach(obj, yaw, tried, goal=PICK_ZONE_CENTRE, holding=False):
Patrol is off (stay_put)."""
if stay_put:
raise FetchError(*NEED_PATROL)
+ _aim_head(obj) # the head on it while the base brings it nearer
t = arm_xy()
x0, y0, th0 = agv.pose()
world = np.array([x0, y0]) + _rot(math.degrees(th0)) @ to_base((obj["x"], obj["y"]), yaw, t)
@@ -1573,6 +1679,7 @@ def _reach(task, obj, say, voice=False):
and with Patrol off no base move is tried: the waist only, then the person is asked."""
yaw, tried, why = arm_yaw(), set(), None # grasp turns past skills.TRUSTED_YAW_DEG only when the base can't help
_width_far["moves"] = 0
+ _aim_head(obj) # found: the head on it from now on (the search is over)
for i in range(APPROACH_TRIES + 1):
can_move = yaw is not None and i < APPROACH_TRIES and not (voice and stay_put) and not _charging() and \
"stuck" not in tried
@@ -1753,10 +1860,99 @@ def _place_view(top0):
return True if far and _place_far(top0, far) else far
-def _keep(xy, table):
+def _keep(xy, table, pts=()):
"""A table to put on, kept by its map place: seen at xy (mm, arm frame now) with its top at `table` mm (None: not
- measured yet). From then on it is looked for there (_kept_at), never another one."""
- return {"world": map_xy({"x": xy[0], "y": xy[1]}), "table": table, "lift": head.status()[0]}
+ measured yet), `pts` (x, y mm, arm frame now) of its level top (_remember). From then on it is looked for there
+ (_kept_at), never another one."""
+ kept = {"world": map_xy({"x": xy[0], "y": xy[1]}), "table": table, "lift": head.status()[0], "pts": {}}
+ _remember(kept, pts)
+ return kept
+
+
+def _remember(kept, pts):
+ """Keep the kept table's level points `pts` (x, y mm, arm frame now) on the map (one per KEEP_CELL_M cell): where
+ it was seen level stays known after a turn or a drive, also where the camera no longer sees it (its view starts
+ at y ~640 at table height, where the arm hardly reaches). Only with the waist at the front: fetch's map frame turns
+ the arm about the base centre, the waist turns it about the column (tests/pick_sweep.py)."""
+ yaw = arm_yaw()
+ if yaw is None or abs(_waist_turn()) >= 1.0 or not len(pts):
+ return
+ x, y, th = agv.pose()
+ b = np.asarray(pts, float)[:, :2] / 1000.0 @ _rot(yaw).T + arm_xy()
+ for w in b @ _rot(math.degrees(th)).T + [x, y]:
+ kept.setdefault("pts", {})[tuple(np.round(w / KEEP_CELL_M).astype(int))] = w
+
+
+def _see_kept(kept):
+ """far_table near the kept table's spot and height; seen, its spot, height and level points are kept (_remember).
+ The spot is where the torso camera's view of it starts, so after a drive closer it lies further again: the spots
+ it showed before are put on from memory (_place_remembered) before the base goes on (live 2026-10-30 it drove on
+ to the table's edge for 10 minutes). None when it is not in view."""
+ x, y, _ = _kept_at(kept)
+ far = far_table((x, y), _kept_band(kept))
+ if far is None:
+ return None
+ kept.update(world=map_xy(far), table=far["table"], lift=head.status()[0])
+ _remember(kept, far["points"])
+ return far
+
+
+def _kept_spots(kept, key):
+ """Spots (x, y mm, arm frame now) of the kept table's remembered level top, ordered by key(x, y): the remembered
+ points within FAR_REACH_MM with a remembered level point within TABLE_RING_MM - KEEP_EDGE_MM of every point of the
+ place ring (skills.TABLE_RING_MM all round: at least KEEP_EDGE_MM in from the last level point seen that way) and
+ FREE_MM from everything the camera sees standing now; at most PLACE_REFUSALS of them."""
+ if not kept.get("pts"):
+ return []
+ pts = arm_frame(np.array(list(kept["pts"].values())))
+ seen = skills.look()
+ ring = np.array([(0.0, 0.0)] + [(skills.TABLE_RING_MM * math.cos(a), skills.TABLE_RING_MM * math.sin(a))
+ for a in np.linspace(0, 2 * math.pi, 8, endpoint=False)])
+ out = []
+ for p in sorted(pts, key=lambda p: key(*p)):
+ if math.hypot(*p) > FAR_REACH_MM or any(math.hypot(p[0] - o["x"], p[1] - o["y"]) < skills.FREE_MM
+ for o in seen):
+ continue
+ near = pts[np.abs(pts - p).max(axis=1) <= skills.TABLE_RING_MM * 2]
+ d = np.linalg.norm(near[None, :, :] - (p + ring)[:, None, :], axis=2).min(axis=1)
+ if (d <= skills.TABLE_RING_MM - KEEP_EDGE_MM).all():
+ out.append((float(p[0]), float(p[1])))
+ if len(out) >= PLACE_REFUSALS:
+ break
+ return out
+
+
+def _place_remembered(top0, kept):
+ """Put it down on the kept table where its level top was seen (_remember), also where the camera sees it no more:
+ from here at its spots nearest PICK_ZONE_CENTRE, else after the waist turn (waist_for, in place) that brings one of
+ its spots nearest the column into the arm's comfortable reach. Only with the waist at the front, the table's height
+ known and the lift right for it. True when it is down."""
+ z = _kept_at(kept)[2]
+ lift = None if z is None else lift_for(z)
+ if lift is None or abs(lift - head.status()[0]) >= LIFT_TOL_MM or abs(_waist_turn()) >= 1.0:
+ return None
+ spots = _kept_spots(kept, lambda x, y: math.hypot(x - PICK_ZONE_CENTRE[0], y - PICK_ZONE_CENTRE[1]))
+ if not spots:
+ return None
+ top = _top_on(top0, z)
+ log(f"the table I keep at {z:.0f} mm: trying spots of it I saw")
+ if _place_at(spots[:FAR_SPOTS], top): # each refused spot costs IK time; the nearest are likeliest
+ return True
+ c = head_cam.head_centre()
+ if c is None:
+ return None
+ for x, y in _kept_spots(kept, lambda x, y: math.hypot(x - c[0], y - c[1]))[:FAR_SPOTS]:
+ if at_edge({"x": x, "y": y}):
+ break # the rest are further from the column: no turn brings them in
+ for deg in waist_for({"x": x, "y": y})[:1]:
+ t = turned({"x": x, "y": y}, deg)
+ if next(skills.place_options(t["x"], t["y"], top, skills._joints()), None) is None:
+ continue
+ log(f"spot ({x:.0f}, {y:.0f}) of the table I keep: turning my waist {deg:+.0f} deg")
+ if not _waist_to(_waist_turn() + deg, in_place=True):
+ return None
+ return _place_at([(t["x"], t["y"])], top)
+ return None
def _kept_at(kept):
@@ -1775,16 +1971,14 @@ def _kept_band(kept):
def _place_kept_view(top0, kept):
"""One look for the kept table: put it down on it in reach (True), else on it further away where the arm reaches a
- spot of it from here (True); else where it is now (far_table near its kept spot and height, kept from now on);
- None when it is not in view."""
+ spot of it from here (True), else on a spot of it seen before (_place_remembered, True); else where it is now
+ (_see_kept), None when it is not in view."""
if _place_here(top0, kept):
return True
- x, y, _ = _kept_at(kept)
- far = far_table((x, y), _kept_band(kept))
- if far is None:
- return None
- kept.update(_keep((far["x"], far["y"]), far["table"]))
- return True if _place_far(top0, far) else far
+ far = _see_kept(kept)
+ if far is not None and _place_far(top0, far):
+ return True
+ return True if _place_remembered(top0, kept) else far
def _place_kept(top0, kept, tried):
@@ -1853,6 +2047,7 @@ def _place_at(tries, top, turned=True):
rows = None # _line_rows said why
if rows and not rows[-1][3]:
_go_on()
+ _aim_head({"x": x, "y": y, "top_mm": top}) # the head on the spot, the arm still
log(f"putting it down at ({x:.0f}, {y:.0f})")
skills._guarded(lambda: motion.move_linear(target=way[0][1], speed=skills.HOLDING_SPEED,
path_checked=True)) # checked
@@ -1866,6 +2061,7 @@ def _place_at(tries, top, turned=True):
continue
opt = next(skills.place_options(x, y, top, skills._joints()), None) # another grasp turn or wrist (the
if opt: # cup's own turn does not matter)
+ _aim_head({"x": x, "y": y, "top_mm": top})
log(f"putting it down at ({x:.0f}, {y:.0f})")
skills._guarded(skills.place_turned, *opt) # ends at home (look), hand open
_set(holding=False)
@@ -2086,7 +2282,7 @@ def _put_on_table(top0, thing, label, tried):
measured yet: by the box until it is) and approached by its map place (_place_kept); in reach it is put down at
once."""
far = far_table((thing["x"], thing["y"]))
- kept = _keep((far["x"], far["y"]), far["table"]) if far else _keep((thing["x"], thing["y"]), None)
+ kept = _keep((far["x"], far["y"]), far["table"], far["points"]) if far else _keep((thing["x"], thing["y"]), None)
log(f"{label} at ({thing['x']:.0f}, {thing['y']:.0f}), " +
(f"its top at {far['table']:.0f} mm: I keep it" if far else "its top not measured yet: I keep it"))
try:
@@ -2195,9 +2391,10 @@ def _put_down(say=None, on=None):
if got is not None and arm_yaw() is not None and not _charging():
log(f"a table at {got['table']:.0f} mm further away ({got['camera']} camera), at ({got['x']:.0f}, "
f"{got['y']:.0f}): I keep it")
- kept = _keep((got["x"], got["y"]), got["table"])
+ kept = _keep((got["x"], got["y"]), got["table"], got["points"])
try:
- if _place_kept(top, kept, tried):
+ _see_kept(kept) # its level top on a fine grid, before any drive
+ if _place_remembered(top, kept) or _place_kept(top, kept, tried):
return
except FetchError as e:
_too_low({"table": _kept_at(kept)[2]}, e) # its height as last measured, nearest
@@ -2294,12 +2491,15 @@ def _pick_here(task, say):
def _pick(obj, waypoints, ja):
"""skills._do_pick; whenever it leaves the object held, also after a stop in the lift, the stand is noted with it
- (a put down goes straight back down from here: _put_back_here)."""
+ (a put down goes straight back down from here: _put_back_here). The head is on it while the arm takes it; once
+ it is in the hand the head is free again."""
+ _aim_head(obj)
try:
skills._guarded(skills._do_pick, obj, waypoints, ja)
finally:
if "top_mm" in skills._held:
_note_stand()
+ _aim_at(None)
def _note_stand():
@@ -2312,13 +2512,12 @@ def _note_stand():
def _carry_from(above, ja):
"""Holding, the arm at `above` (flange pose over the pick spot, joints `ja` there): to look the way a pick ends."""
try:
- _line_holding("carry") # straight: the cup stays upright (a turned grasp
+ _line_holding("carry", join=False) # straight: the cup stays upright (a turned grasp
except FetchError: # can't go straight to look) ...
plan = skills.carry_up(above, ja) # ... or, when that line jumps (carry has the elbow
- if plan is None: # almost straight), further up and one joint move
- raise
- skills._guarded(skills.carry_by_joints, plan)
- _line_holding(LOOK_POSE) # then look to drive
+ if plan is not None: # almost straight), further up and one joint move
+ skills._guarded(skills.carry_by_joints, plan)
+ _line_holding(LOOK_POSE) # then look to drive (else arm_route's checked way there)
def _carry_held():
@@ -2390,6 +2589,7 @@ def _clear():
_pause.clear()
_set(paused=False)
skills._cancel.clear()
+ _aim_at(None)
def _new_run():
@@ -2481,8 +2681,9 @@ def held_by_skill(what):
def pick_here(name, colour=None, say=None):
"""The voice pick ("take the cup", assistant/lumi.py's skill thread): the `name` (`colour`) seen from where Lumi
stands is reached as a fetch reaches it, with trusted grasp turns only (_reach voice=True: from here, else the
- waist in place, else with Patrol on the base, else the person is asked) and picked; it ends held just above the
- table. Returns the object."""
+ waist in place, else with Patrol on the base, else the person is asked) and picked, then carried to look as a
+ fetch's pick is (live 2026-10-30 it ended at the lift pose, the wrist turned over: no way back from there was
+ found). Returns the object."""
task = {"object": name, "colour": colour}
_clear()
try:
@@ -2493,8 +2694,13 @@ def pick_here(name, colour=None, say=None):
obj, waypoints, ja = _reach(task, obj, say, voice=True)
_step("picking")
_pick(obj, waypoints, ja)
+ held_by_skill(task) # held, also when the carry is refused
+ _step("carry")
+ skills._guarded(skills._line, "up", waypoints[0][1]) # straight up to the approach height first
+ _carry_from(waypoints[0][1], ja)
finally:
_set(step="")
+ _aim_at(None) # no runner's end (head_ahead) after a voice pick
return obj
@@ -3137,11 +3343,11 @@ def _arm(pose):
_set(holding=False)
log(f"gripper {pose}: {st}")
elif pose == "fold": # the arm's home
- _pose(LOOK_POSE)
+ _line_holding(LOOK_POSE) if _state["holding"] else _pose(LOOK_POSE)
elif pose == "reach": # the hand held out, as for a hand-over
if "give" not in motion.poses():
raise FetchError("I haven't learned how to reach out yet.")
- _pose("give")
+ _line_holding("give") if _state["holding"] else _pose("give")
def held_name(lang="en"):
@@ -3170,6 +3376,19 @@ def release_now():
_release.set()
+def let_go():
+ """The person says they hold what the hand holds ("I've got it", "내가 잡고 있어") while no task runs: open where the
+ arm is and forget the held thing. False while a task runs (its hand-over opens on release_now)."""
+ with _lock:
+ if _busy():
+ return False
+ log("the person holds it: opening")
+ gripper.open_()
+ skills._held.clear()
+ _set(holding=False, **({"status": "idle", "step": ""} if _state["status"] == "holding" else {}))
+ return True
+
+
def replace(steps, say=None):
"""The person a mission is for takes it here or changes it: end the rest of this run, start `steps`."""
sender = ((_state.get("task") or {}).get("sender"))
diff --git a/tasks/wave_greet.py b/tasks/wave_greet.py
new file mode 100644
index 0000000..7c93098
--- /dev/null
+++ b/tasks/wave_greet.py
@@ -0,0 +1,322 @@
+"""Wave back at people who wave at Lumi: the dashboard switch "Wave greeting". Greeter / Patrol are not needed; while
+either runs the assistant owns the robot and this waits. Runs in the API process (api/server.py starts it).
+
+Someone waving within GREET_M of the head camera (vision/waving.py): the head turns to them and the arm goes up at
+once (manipulation/wave.py checks and plans the way, look -> wave_out -> wave_start, at the route speed), Lumi says a
+greeting (tasks/wave_lines.py), swings once even when they stopped meanwhile, then turns the waist to face them
+(fetch._waist_to, its sweep checked; the head stays on them). It swings while they wave, stops when they stop and
+keeps the hand up; waving again swings again. A long wave gets a joke now and then. Nobody waving for HOLD_S: the arm
+goes down slowly to look, the waist to the front, the head to rest.
+
+Any stop or failure of the arm (STOP, a person too close while the arm goes up, a refused move) switches the greeting
+off: it never moves again by itself after a stop.
+"""
+import json
+import math
+import random
+import threading
+import time
+
+import cv2
+import numpy as np
+
+from manipulation import arm_route, wave
+from robot import head, motion
+from tasks import wave_lines
+from vision import camview, pose, waving
+
+CAM = "head"
+GREET_M = 3.0 # m; people waving further away are not answered
+HOLD_S = 60.0 # s the hand stays up after the last wave seen, then down to look
+FRESH_S = 0.5 # s a waving person seen counts as waving now
+NEW_WAVE_S = 5.0 # s without any waving after which a wave is greeted anew (a new greeting line)
+JOKE_AFTER_S = 10.0 # s of waving before the first joke ...
+JOKE_EVERY_S = 12.0 # ... and between jokes
+WAIST_MIN_DEG = 10.0 # deg; a person nearer the front than this: only the head turns
+WAIST_PARTS = (1.0, 0.75, 0.5, 0.25) # a blocked waist turn is tried again this much of the way (beside a wall)
+HEAD_MIN_DEG = 8.0 # deg the person may move off the head's direction before the head follows
+DOWN_SPEED = "normal" # motion.JOINT_SPEED of the way down (owner: 2x the first "slow")
+SWING_SPEED = "swing" # motion.JOINT_SPEED of the swings, 60 deg/s at 4x the usual acceleration (owner: faster;
+ # wave.SWING_SPEED of an asked wave is "quick")
+FREE_EVERY_S = 1.0 # s between checks that nothing else runs (it asks the AGV)
+REFUSED_S = 30.0 # s before trying again after the arm was refused (off, busy, holding something) and
+ # between tries to bring a blocked waist back to the front
+HEAD_TIMEOUT_S = 5.0 # s a head move may take; the body API now and then never answers a moveto, and the call
+ # holds the body lock all that time (the waist turn waited 30 s behind it)
+CLOSE_FRESH_S = 1.5 # s a camera service detection counts for the too-close check
+
+_seen = {"t": 0.0, "wavers": []} # wavers: [(bearing deg from the waist's front, + left; distance m)], nearest first
+_busy = threading.Event() # the arm is up or moving for a greeting
+_speaking = threading.Lock()
+_on = _free = _off = None # set by start()
+
+
+def log(*a):
+ print(time.strftime("%H:%M:%S"), "wave greeting:", *a, flush=True)
+
+
+def busy():
+ return _busy.is_set()
+
+
+# ---------- seeing ----------
+def _head_yaw():
+ """Head yaw (deg) the camera service saw its newest frame at."""
+ try:
+ return float(json.loads(camview.det_path(CAM).read_text()).get("head_yaw") or 0.0)
+ except (FileNotFoundError, ValueError):
+ return 0.0
+
+
+def _dist(depth, at):
+ """Median depth (m) around a pixel, None without depth there."""
+ if depth is None:
+ return None
+ x, y = int(at[0]), int(at[1])
+ patch = depth[max(0, y - 6):y + 7, max(0, x - 6):x + 7]
+ v = patch[patch > 0]
+ return float(np.median(v)) / 1000 if v.size >= 5 else None
+
+
+def _watch():
+ """Every head camera frame while the switch is on: who waves, where (_seen)."""
+ watcher, last, intr = waving.Watcher(), 0.0, None
+ while True:
+ if not _on():
+ watcher, intr = waving.Watcher(), None
+ time.sleep(0.5)
+ continue
+ camview.want(CAM)
+ try:
+ m = camview.raw_path(CAM).stat().st_mtime
+ except FileNotFoundError:
+ time.sleep(0.2)
+ continue
+ if m == last:
+ time.sleep(0.01)
+ continue
+ last = m
+ img = cv2.imread(str(camview.raw_path(CAM)))
+ intr = intr or camview.intrinsics(CAM)
+ if img is None or intr is None:
+ continue
+ depth, yaw = camview.depth(CAM), _head_yaw()
+ gray = cv2.cvtColor(cv2.resize(img, None, fx=waving.SCALE, fy=waving.SCALE), cv2.COLOR_BGR2GRAY)
+ wavers = []
+ for p, is_waving in watcher.update(m, gray, pose.detect(img)):
+ ls, rs = pose.seen(p["kp"], "left_shoulder"), pose.seen(p["kp"], "right_shoulder")
+ if not (is_waving and ls and rs):
+ continue
+ at = ((ls[0] + rs[0]) / 2, (ls[1] + rs[1]) / 2)
+ d = _dist(depth, at)
+ if d is not None and d <= GREET_M:
+ wavers.append((yaw - math.degrees(math.atan((at[0] - intr["cx"]) / intr["fx"])), d))
+ _seen.update(t=time.time(), wavers=sorted(wavers, key=lambda w: w[1]))
+
+
+def _waver():
+ """(bearing, distance) of the nearest person waving now, None when nobody waves."""
+ return _seen["wavers"][0] if _seen["wavers"] and time.time() - _seen["t"] < FRESH_S else None
+
+
+def _too_close():
+ """A person really close in either camera (the assistant's rule, lumi.too_close)."""
+ from assistant.lumi import too_close
+ for cam in ("head", "torso"):
+ try:
+ d = json.loads(camview.det_path(cam).read_text())
+ except (FileNotFoundError, ValueError):
+ continue
+ if time.time() - d["time"] < CLOSE_FRESH_S and \
+ too_close([p for p in d["people"] if p.get("distance_m") is not None], d["height"]):
+ return True
+ return False
+
+
+# ---------- moving and talking ----------
+def _bg(fn, *args):
+ threading.Thread(target=fn, args=args, daemon=True).start()
+
+
+def _say(lines, lang):
+ """One line of `lines` in language 0 (English) / 1 (Korean), in the background; skipped while Lumi speaks."""
+ def run():
+ if not _speaking.acquire(blocking=False):
+ return
+ try:
+ from audio import mouth
+ mouth.say(random.choice(lines)[lang])
+ except Exception as e:
+ log(f"say failed: {e!r}")
+ finally:
+ _speaking.release()
+ _bg(run)
+
+
+def _turn_head(yaw, pitch=None):
+ """head.turn with HEAD_TIMEOUT_S; a move that times out is logged (the head finishes it anyway)."""
+ try:
+ lift, waist, _, now_pitch = head.status()
+ yaw = max(-head.YAW_LIMIT, min(head.YAW_LIMIT, yaw))
+ head.moveto([lift, waist, yaw, now_pitch if pitch is None else pitch], timeout=HEAD_TIMEOUT_S)
+ except Exception as e:
+ log(f"head move: {e!r}")
+
+
+def _head_to(bearing):
+ """The head to a bearing from the waist's front, in the background, unless it looks there already."""
+ if abs(bearing - _head_yaw()) > HEAD_MIN_DEG:
+ _bg(_turn_head, bearing)
+
+
+def _up(route):
+ """The way up (wave.plan) at the route speed, the last move at ARRIVE_SPEED; the arm stops when a person comes
+ really close meanwhile (motion.MotionError)."""
+ if not route:
+ return
+ done = threading.Event()
+
+ def guard():
+ while not done.wait(0.1):
+ if _too_close():
+ log("a person is too close - STOP arm")
+ motion.stop()
+ return
+ threading.Thread(target=guard, daemon=True).start()
+ t0 = time.time()
+ try:
+ motion.move_path([(j, arm_route.SPEED) for _, j in route[:-1]] + [(route[-1][1], wave.ARRIVE_SPEED)])
+ finally:
+ done.set()
+ log(f"arm up after {time.time() - t0:.1f} s")
+
+
+def _swing():
+ """One swing, START -> SWING -> START, back to back."""
+ p, t0 = motion.poses(), time.time()
+ motion.move_path([(p[wave.SWING], SWING_SPEED), (p[wave.START], SWING_SPEED)], queued=True)
+ log(f"swing {time.time() - t0:.1f} s")
+
+
+def _face(bearing):
+ """Waist turned to the person (they face each other), the head staying on them; only the head when they are
+ nearly in front. A turn whose sweep is not clear is tried part of the way (WAIST_PARTS); the head covers the
+ rest."""
+ from tasks import fetch
+ fetch._stop.clear() # no task runs: an old stop must not end this turn
+ for part in WAIST_PARTS:
+ if abs(bearing * part) < WAIST_MIN_DEG:
+ break
+ if fetch._waist_to(fetch._waist_turn() + bearing * part, in_place=True, look=bearing):
+ return
+ _head_to(bearing)
+
+
+def _greet(bearing, lang):
+ """Head to them, a greeting, the arm up, one swing, the waist to them. False when the arm is refused."""
+ try:
+ route, _ = wave.plan()
+ except Exception as e: # refused (arm off, busy, holding) or the controller did not answer
+ log(f"not waving: {e.args[0] if isinstance(e, wave.WaveError) else repr(e)}")
+ return False
+ log(f"someone waves at {bearing:+.0f} deg: arm up")
+ _busy.set()
+ _head_to(bearing)
+ _say(wave_lines.GREET, lang)
+ _up(route)
+ _swing() # once, even if they stopped while the arm went up
+ w = _waver()
+ _face(w[0] if w else bearing)
+ return True
+
+
+def _down():
+ """Waist to the front first, the way it came with the hand up (in `look` the arm sticks out further and the same
+ turn back can be blocked), then the arm slowly down to look and the head to rest."""
+ from tasks import fetch
+ _busy.set()
+ try:
+ fetch._stop.clear()
+ _st["waist_out"] = not fetch._waist_to(0.0, in_place=True)
+ if arm_route.where() in arm_route.WAVE_POSES:
+ arm_route.move(arm_route.plan(arm_route.HOME), DOWN_SPEED)
+ _turn_head(0.0, head.HEAD_REST_PITCH)
+ log("arm down")
+ finally:
+ _busy.clear()
+
+
+_st = {"up": False, "last_wave": 0.0, "lang": 0, "next_joke": 0.0, "free": False, "free_at": 0.0, "refused_until": 0.0,
+ "waist_out": False} # waist_out: the way back to the front was blocked, tried again later
+
+
+def step(now):
+ """One look at what to do now (_run calls it every 50 ms)."""
+ st = _st
+ if not _on():
+ if st["up"]:
+ _down()
+ st["up"] = False
+ return
+ if now - st["free_at"] > FREE_EVERY_S:
+ st["free"], st["free_at"] = _free(), now
+ if not st["free"]: # the assistant or a task has the robot: it takes the arm from here
+ st["up"] = False
+ _busy.clear()
+ return
+ w = _waver()
+ new = bool(w) and now - st["last_wave"] > NEW_WAVE_S
+ if new:
+ st["lang"], st["next_joke"] = random.randrange(2), now + JOKE_AFTER_S
+ if w:
+ st["last_wave"] = now
+ if not st["up"]:
+ if w and now > st["refused_until"]:
+ st["up"] = _greet(w[0], st["lang"])
+ if not st["up"]:
+ st["refused_until"] = now + REFUSED_S
+ elif not w and st["waist_out"] and now > st["refused_until"]:
+ from tasks import fetch
+ fetch._stop.clear()
+ st["waist_out"] = not fetch._waist_to(0.0, in_place=True)
+ st["refused_until"] = now + REFUSED_S
+ elif w:
+ if arm_route.where() not in (wave.START, wave.SWING):
+ st["up"] = False # someone moved the arm: the next wave starts from where it is
+ return
+ if new:
+ _say(wave_lines.GREET, st["lang"])
+ elif now > st["next_joke"]:
+ _say(wave_lines.LONG, st["lang"])
+ st["next_joke"] = now + JOKE_EVERY_S
+ _head_to(w[0])
+ _swing()
+ elif now - st["last_wave"] > HOLD_S:
+ _down()
+ st["up"] = False
+
+
+def _stopped(e):
+ """A stop or a failure of the arm: switched off, it never goes on by itself."""
+ log(f"stopped ({e!r}) - switched off")
+ _busy.clear()
+ _st["up"] = False
+ _off()
+ _say([("I stopped my arm.", "팔을 멈췄어요.")], _st["lang"])
+
+
+def _run():
+ while True:
+ time.sleep(0.05)
+ try:
+ step(time.time())
+ except Exception as e:
+ _stopped(e)
+
+
+def start(on, free, off):
+ """`on()`: the switch is on; `free()`: nothing else has the robot; `off()`: turn the switch off."""
+ global _on, _free, _off
+ _on, _free, _off = on, free, off
+ threading.Thread(target=_watch, daemon=True).start()
+ threading.Thread(target=_run, daemon=True).start()
diff --git a/tasks/wave_lines.py b/tasks/wave_lines.py
new file mode 100644
index 0000000..3129a58
--- /dev/null
+++ b/tasks/wave_lines.py
@@ -0,0 +1,59 @@
+"""What Lumi says while it waves back at someone (tasks/wave_greet.py), (English, Korean). One language per wave,
+picked at random: a passer-by's language is not known. The lines fit a hello and a goodbye alike."""
+
+GREET = [
+ ("Hi there! Have a wonderful day!", "안녕하세요! 좋은 하루 보내세요!"),
+ ("Hello, hello! Nice to see you!", "안녕하세요! 반가워요!"),
+ ("Hey! I see you!", "어! 저 보여요, 보여요!"),
+ ("Hi! You made my day!", "안녕하세요! 덕분에 기분이 좋아졌어요!"),
+ ("Hello! Waving back at you!", "안녕하세요! 저도 손 흔들어요!"),
+ ("Hi friend! Take care!", "안녕하세요, 친구! 잘 지내요!"),
+ ("Hello! Lovely to see a friendly face!", "안녕하세요! 반가운 얼굴이네요!"),
+ ("Hey there! Big wave for you!", "안녕하세요! 크게 흔들어 드릴게요!"),
+ ("Hi! Thanks for saying hello!", "안녕하세요! 인사해 주셔서 고마워요!"),
+ ("Hello! You have a great wave!", "안녕하세요! 손 흔드는 모습이 멋져요!"),
+ ("Hi! I'm Lumi. Nice to meet you!", "안녕하세요! 저는 루미예요. 만나서 반가워요!"),
+ ("Hey! Have a good one!", "안녕하세요! 좋은 시간 보내세요!"),
+ ("Hello! Smile, it's a good day!", "안녕하세요! 웃어요, 좋은 날이에요!"),
+ ("Hi! You waved, so I wave!", "안녕하세요! 손 흔드시니까 저도 흔들어요!"),
+ ("Hello there! See you around!", "안녕하세요! 또 만나요!"),
+ ("Hi! Robots love waves too!", "안녕하세요! 로봇도 손 인사를 좋아해요!"),
+ ("Hey! Hello from Lumi!", "안녕하세요! 루미가 인사드려요!"),
+ ("Hi! Hope everything goes well today!", "안녕하세요! 오늘 일 다 잘 되길 바라요!"),
+ ("Hello! Thanks for noticing me!", "안녕하세요! 저를 봐 주셔서 고마워요!"),
+ ("Hi there! Sending you good energy!", "안녕하세요! 좋은 기운 보내 드려요!"),
+ ("Hello! Wave received, wave returned!", "안녕하세요! 인사 받았어요, 저도 인사해요!"),
+ ("Hi! Always happy to see you!", "안녕하세요! 언제 봐도 반가워요!"),
+ ("Hey! What a nice wave!", "안녕하세요! 정말 멋진 인사예요!"),
+ ("Hello! Take it easy!", "안녕하세요! 편하게 쉬엄쉬엄 하세요!"),
+ ("Hi! My hand says hello too!", "안녕하세요! 제 손도 인사하고 있어요!"),
+]
+
+# said while the waving goes on and on
+LONG = [
+ ("My arm is getting tired. Isn't yours?", "제 팔이 좀 아파요. 그쪽 팔은 괜찮아요?"),
+ ("Still waving? You have more energy than my battery!", "아직도요? 제 배터리보다 힘이 넘치시네요!"),
+ ("Okay, okay, I see you! Really!", "네, 네, 보여요! 정말 보여요!"),
+ ("Is this a waving contest? I'm not giving up!", "손 흔들기 대회인가요? 저도 안 져요!"),
+ ("We could do this all day. Should we?", "이러다 하루 종일 하겠어요. 그럴까요?"),
+ ("My motors are warming up nicely!", "제 모터가 따끈따끈해지고 있어요!"),
+ ("You win. My arm needs a coffee break.", "졌어요. 제 팔도 커피 한 잔 해야겠어요."),
+ ("I think we are best friends now.", "이제 우리 완전 친한 친구 같아요."),
+ ("Let's call it a tie, okay?", "우리 무승부로 할까요?"),
+ ("My elbow is asking for a holiday.", "제 팔꿈치가 휴가 달래요."),
+ ("If waving burned calories, I'd be very slim.", "손 흔들기로 살이 빠지면 저는 벌써 날씬해졌을 거예요."),
+ ("Careful, I can do this for hours. I'm a robot.", "조심하세요, 저는 로봇이라 몇 시간도 할 수 있어요."),
+ ("Your arm is stronger than mine, and mine is made of metal!", "제 팔은 금속인데도 그쪽 팔이 더 세네요!"),
+ ("Okay, one more wave, and then a snack.", "좋아요, 한 번만 더 하고 간식 먹어요."),
+ ("Are we saying hello or goodbye? I forgot.", "지금 인사하는 거예요, 헤어지는 거예요? 까먹었어요."),
+ ("Wave number one hundred! Just kidding, I'm not counting.", "백 번째 인사! 농담이에요, 세고 있진 않아요."),
+ ("I hope nobody is watching us.", "누가 우리 보고 있는 건 아니겠죠?"),
+ ("This is the longest hello of my life.", "제 인생에서 제일 긴 인사예요."),
+ ("You don't get tired, do you?", "혹시 안 지치세요?"),
+ ("My arm says: please, a little break!", "제 팔이 말해요: 잠깐만 쉬어요, 제발!"),
+ ("We should start a waving club.", "우리 손 흔들기 동아리 만들어야겠어요."),
+ ("I'll remember this wave forever. Well, until my next update.", "이 인사 영원히 기억할게요. 음, 다음 업데이트 전까지요."),
+ ("Okay, you are officially the best waver today.", "공식적으로 오늘 최고의 인사왕이세요."),
+ ("Even my battery is waving goodbye now.", "이제 제 배터리도 손 흔들고 있어요."),
+ ("Alright, alright! Hello, hello, hello!", "알았어요, 알았어요! 안녕, 안녕, 안녕하세요!"),
+]
diff --git a/tests/test_arm_flip.py b/tests/test_arm_flip.py
new file mode 100644
index 0000000..6d08e8f
--- /dev/null
+++ b/tests/test_arm_flip.py
@@ -0,0 +1,75 @@
+"""Self-check of an arm with its wrist turned over (J4 / J6 half a turn off and J5's sign flipped against the taught
+poses) while holding a cup, with the taught poses, the measured head centre and the offline arm kinematics
+(tests/pick_sweep.py simulator), no robot: python tests/test_arm_flip.py
+
+Live 2026-10-30 15:01: a voice pick ended at its lift pose with the wrist turned over; the straight move to give
+ended on the same wrist branch and from there every way back was refused (arm_route UNKNOWN)."""
+import sys
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import no_robot # noqa: F401 any connection to the robot fails the test
+from tests import pick_sweep as ps
+
+ps.install()
+fetch, skills, motion, kin = ps.fetch, ps.skills, ps.motion, ps.kin
+from manipulation import arm_route # noqa: E402
+
+STUCK = [-270.5, -88.9, -12.1, -348.9, -27.3, -51.9] # live: give's flange pose, the wrist turned over
+LIFT = [-282.3, -84.7, -44.5, 114.9, -16.3, -169.2] # the live pick's lift pose (-10, 499, -73), turned
+CENTRE = ps.HEAD_CENTRE
+
+
+def lowest(j):
+ return arm_route.profile(j, j, CENTRE)[1]
+
+
+def check_way(start, seq):
+ """Every move of a plan: no wave pose, the cup upright, clear of the head, no dip; the wrist turning back never
+ takes the gripper below where it started (PATH_SAG_MM)."""
+ prev, floor = list(start), lowest(start)
+ for n, j in seq:
+ assert n not in arm_route.WAVE_POSES, seq
+ clear, ends, low, tilt = arm_route.profile(prev, j, CENTRE)
+ assert tilt <= skills.MAX_TILT_DEG and clear >= arm_route.HEAD_CLEAR_MM, (n, clear, tilt)
+ assert low >= (floor if n == "wrist" else ends) - skills.PATH_SAG_MM, (n, low, floor, ends)
+ prev = j
+
+
+assert np.allclose(kin.pose(STUCK)[:3], kin.pose(motion.poses()["give"])[:3], atol=2.0) # the same hand, turned over
+
+# ---------- the planner: from the live stuck pose, holding, a checked way to each pose ----------
+for target in ("look", "carry", "give"):
+ seq = arm_route.plan(target, holding=True, now=list(STUCK))
+ assert seq and seq[0][0] == "wrist", seq # the wrist turns back first, where it is
+ assert max(abs(a - b) for a, b in zip(seq[-1][1], motion.nearest(motion.poses()[target], seq[-1][1]))) < 0.01
+ check_way(STUCK, seq)
+ print(target, "from the stuck pose:", " -> ".join(n for n, _ in seq))
+try:
+ arm_route.plan("wave_start", holding=True, now=list(STUCK))
+ raise AssertionError("a wave pose with a cup")
+except arm_route.RouteError as e:
+ assert e.args == arm_route.SPILL, e.args
+assert arm_route.plan("look", now=list(STUCK))[-1][0] == "look" # empty hand: a way too
+
+# ---------- fetch's moves with the cup from the turned-over lift pose: never left turned over at a pose ----------
+for target in ("give", "carry", fetch.LOOK_POSE):
+ ps.setup(ps.pick_at(-104, 656, -182, height=142), 0.0)
+ ps.W["hand"].update(holding=True, closed=True)
+ fetch._state.update(holding=True)
+ ps.W["J"] = list(LIFT)
+ fetch._line_holding(target)
+ assert fetch._at_pose(target), (target, [round(v, 1) for v in ps.W["J"]])
+ print(target, "from the lift pose: at", target)
+
+# ---------- the voice pick of the live scene: the turned-over grasp, then carried to look (not left at the lift) ----
+ps.setup(ps.pick_at(-104, 656, -182, height=142), 0.0)
+fetch.pick_here("cup")
+assert any("wrist J5 -13" in l for l in ps.W["lines"]), ps.W["lines"] # the live grasp: J4 of the other wrist near
+assert ps.W["hand"]["holding"] and fetch._state["holding"] # its limit (from look's +200) on the way up
+assert fetch._at_pose(fetch.LOOK_POSE), [round(v, 1) for v in ps.W["J"]]
+print("voice pick: held at look")
+
+print("arm flip ok")
diff --git a/tests/test_fetch.py b/tests/test_fetch.py
index 9e59d10..6cd049e 100644
--- a/tests/test_fetch.py
+++ b/tests/test_fetch.py
@@ -400,7 +400,8 @@ skills.on_table = lambda spots, table: [p for p in spots if p[1] >= 760][:1] if
else [p for p in spots if p[1] <= 700][:1]
far_held = dict(skills._held)
real_chain, real_options = skills.ik_chain, skills.place_options
-far_spot = lambda n: n.startswith("to (") and float(n.split(", ")[1].split(")")[0]) > 740 # line to a spot y > 740
+far_spot = lambda n: n.startswith("to (") and (float(n.split(", ")[1].split(")")[0]) > 740 # line to a spot y > 740
+ or not any(c[0] == "joy" for c in calls)) # any before the drive
skills.ik_chain = lambda wp, j: [[n, p, [0] * 6, "no IK solution" if far_spot(n) else None] for n, p in wp]
skills.place_options = lambda *a: iter(()) # ... the arm does not reach it from here
st = run(fetch.place)
@@ -827,6 +828,15 @@ st = run(fetch.give)
assert st["status"] == "done" and not st["holding"] and ("open",) in calls, (st, calls)
fetch.motion.poses = lambda: {"ready": [0] * 6, "carry": [3] * 6, "look": [0] * 6}
+# ---------- holding, the person says they hold it ("I've got it"): open where the arm is, nothing held ----------
+reset()
+st = run(fetch.start, ok)
+assert st["status"] == "holding", st
+calls.clear()
+assert fetch.let_go() is True
+st = fetch.state()
+assert st["status"] == "idle" and not st["holding"] and calls == [("open",)] and not skills._held, (st, calls)
+
# ---------- another process holds it: give / place here take it over ----------
reset()
skills._held.clear()
diff --git a/tests/test_fetch_head_aim.py b/tests/test_fetch_head_aim.py
new file mode 100644
index 0000000..ad76f68
--- /dev/null
+++ b/tests/test_fetch_head_aim.py
@@ -0,0 +1,136 @@
+"""Self-check of the head during a fetch (tasks/fetch.py _aim_head): once the object or the place is found the head
+turns to it and stays on it while the base turns, for the pick and the put down; assistant/lumi.py does not turn
+the head to people meanwhile. Fake head, base and head camera (no robot): python tests/test_fetch_head_aim.py"""
+import math
+import tempfile
+import time
+from pathlib import Path
+
+import numpy as np
+
+import no_robot # noqa: F401 any connection to the robot fails the test
+from manipulation import skills
+from tasks import fetch
+from assistant import lumi
+
+tmp = Path(tempfile.mkdtemp())
+fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file
+fetch.CALIB_FILE = tmp / "fetch_calib.json" # arm frame = base frame, the waist at the front
+fetch.CALIB_FILE.write_text('{"arm_yaw_in_base_deg": 0.0, "arm_xy_in_base_m": [0.0, 0.0], "waist_deg": 0.0}')
+fetch.DRIVE_POLL_S = 0.01
+fetch.HEAD_AIM_EVERY_S = 0.0
+
+body = [0.0, 0.0, 0.0, fetch.HEAD_LOW_PITCH] # lift, waist, head yaw, head pitch
+moves = [] # head yaw of every body move
+
+
+def moveto(pos, vel=None, acc=None, timeout=None):
+ moves.append(round(pos[2]))
+ body[:] = [float(p) for p in pos]
+
+
+fetch.head.status = lambda: list(body)
+fetch.head.moveto = moveto
+fetch.camview.want = lambda name: None
+skills.moved = lambda *a, **kw: None
+pose = [0.0, 0.0, 0.0] # map x, y (m), theta (rad)
+fetch.agv.pose = lambda: tuple(pose)
+fetch.agv.cancel = lambda: None
+
+
+def base_from_head(yaw, pitch):
+ """A head camera at the arm origin: yaw 0 looks along arm +y, + yaw turns it left (counter-clockwise)."""
+ s, c = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
+ T = np.eye(4)
+ T[:3, :3] = np.array([[c, s, 0.0], [0.0, 0.0, -1.0], [-s, c, 0.0]]).T # columns: right, down, forward
+ return T
+
+
+fetch.head_cam.base_from_head = base_from_head
+bearing = lambda x, y: math.degrees(math.atan2(-x, y)) # + left of arm +y
+
+
+def near(a, b, tol=1.0):
+ return abs(a - b) <= tol
+
+
+# a new run: no target, the head is lumi.py's (a person's) to turn
+fetch._clear()
+assert not fetch.aiming()
+heads = []
+lumi.head.turn = lambda yaw, pitch=None: heads.append(round(yaw))
+L = lumi.Lumi.__new__(lumi.Lumi)
+L.turn_head(20)
+time.sleep(0.2)
+assert heads == [20], heads
+
+# the torso camera found the cup at (-300, 600) (the pick: _reach): the head turns to it
+cup = {"x": -300.0, "y": 600.0, "top_mm": -250.0}
+fetch._aim_head(cup)
+assert fetch.aiming() and near(body[2], bearing(-300, 600)), body
+# lumi.py's focus on a person, a greeting, a voice: the head stays on the cup
+heads.clear()
+L.turn_head(-40)
+L.turn_head(0, force=True)
+time.sleep(0.2)
+assert heads == [], heads
+
+# a look again (_see_again, _look_at ahead) keeps the head on the cup, not ahead of the waist
+assert fetch._look_at(0.0, lambda: "seen") == "seen"
+assert near(body[2], bearing(-300, 600)), body
+
+# the base turns left to face it (+26.6 deg): the head turns back with it, staying on the cup
+step = math.atan2(300, 600) / 10
+polls = {"n": 0}
+
+
+def status():
+ polls["n"] += 1
+ if polls["n"] <= 10:
+ pose[2] += step
+ return {"move_status": "running", "current_pose": {"x": 0.0, "y": 0.0, "theta": pose[2]}}
+ return {"move_status": "succeeded", "current_pose": {"x": 0.0, "y": 0.0, "theta": pose[2]}}
+
+
+fetch.agv.status = status
+moves.clear()
+fetch._wait_drive()
+assert len(moves) >= 2 and all(b < a for a, b in zip(moves, moves[1:])), moves # several small turns back
+x, y = fetch.arm_frame(fetch._aim["world"])
+assert near(bearing(x, y), 0.0) and abs(body[2]) <= fetch.HEAD_AIM_DEG, (x, y, body)
+
+# the pick: the head turned away (head_hits checked a turn's sweep) comes back onto the cup before the arm moves
+body[2] = 60.0
+picked = []
+skills._held.clear()
+skills._guarded = lambda fn, *a: fn(*a)
+skills._do_pick = lambda obj, wp, ja: picked.append(body[2])
+fetch._pick({"x": x, "y": y, "top_mm": -250.0}, [], [0.0] * 6)
+assert len(picked) == 1 and near(picked[0], 0.0), picked
+assert not fetch.aiming() # in the hand: the head is free again
+
+# the put down: the head turns to the spot before the arm goes there
+placed = []
+skills._held.update(yaw=0.0)
+skills.plan_place = lambda x, y, top, yaw=0.0: [("above", [x, y, top + 100.0, 0, 0, 0]), ("place", [x, y, top, 0, 0, 0])]
+fetch._line_rows = lambda target, label, start=None: [[label, target, [0.0] * 6, None]]
+skills.ik_chain = lambda wp, j: [[n, p, [0.0] * 6, None] for n, p in wp]
+fetch.motion.move_linear = lambda target=None, **kw: None
+skills._do_place = lambda rows: placed.append(body[2])
+fetch._pose = lambda name, holding=False, leaf=False: None
+assert fetch._place_at([(-200.0, 650.0)], -320.0) is True
+assert len(placed) == 1 and near(placed[0], bearing(-200, 650)), placed
+assert fetch.aiming()
+
+# the task ends (head_ahead) or a STOP: the head is lumi.py's again
+fetch.head_ahead()
+assert not fetch.aiming() and body[2] == 0.0, body
+fetch._aim_head(cup)
+fetch._stop.set()
+assert not fetch.aiming()
+fetch._clear()
+heads.clear()
+L.turn_head(-40)
+time.sleep(0.2)
+assert heads == [-40], heads
+print("fetch head aim: ok")
diff --git a/tests/test_focus.py b/tests/test_focus.py
index 6fb2498..8ec6ef3 100644
--- a/tests/test_focus.py
+++ b/tests/test_focus.py
@@ -90,7 +90,7 @@ def settle():
# ---- talking with #1 (right), #2 walks in on the left and waves: no greeting, the head stays on #1 as they move ----
-L = fresh(a := Track(1, 30.0))
+L = fresh(a := Track(1, 30.0, 2.0)) # past 1.6 m: no calibration sample from it
a.greeted, L.current = True, a
L.vision.tracks.append(b := Track(2, -40.0))
up.append(-40.0)
@@ -125,7 +125,15 @@ for text, takes in (("The weather is nice today.", False), ("Stop.", True), ("Lu
a.greeted, L.current = True, a
L.who_spoke(U, text)
settle()
- assert (L.current is b) == takes and (moves == [S * -40] if takes else moves == []), (text, L.current.id, moves)
+ assert (L.current is b) == takes and moves == [S * (-40 if takes else 30)], (text, L.current.id, moves) # the head
+ # on whoever it talks with after every utterance (2026-10-30)
+lumi.doa.estimate = lambda mics, cal, ref=None: (-40.0, 0.0, 0.0) # no sure direction: still to the one talked with
+L = fresh(a := Track(1, 30.0, 2.0)) # past 1.6 m: no calibration sample from it
+a.greeted, L.current = True, a
+L.who_spoke(U, "What's the weather?")
+settle()
+assert moves == [S * 30], moves
+lumi.doa.estimate = lambda mics, cal, ref=None: (-40.0, 0.9, 0.0)
# ---- "look at me" (19:24:16): focus on the person found; a newcomer does not take the head; the head follows the
# looked-at person over the held look, also when their track gets a new id (#5 -> #7) ----
diff --git a/tests/test_held_hand.py b/tests/test_held_hand.py
index b4d3b73..fd7aa9e 100644
--- a/tests/test_held_hand.py
+++ b/tests/test_held_hand.py
@@ -47,6 +47,22 @@ NOT_GIVE = ["don't give it to me yet", "give it to me after the talk", "when my
"잠깐만 시간 좀 줘", "엄마, 그 가방 줘 봐", "지영아 물 좀 줘", "Jake, give me your phone for a sec", "주는 척만 해",
"give it to James at booth A", "bring it to p3", "거기 놓지 마세요", "put down 하지 마", "put the music on",
"I put it on the table yesterday", "put it on my tab", "lay down"]
+# the person says they hold it themselves: the hand opens (release); whisper's "cuff" for cup (live 2026-10-30)
+THEY_HOLD = ["I am holding the cuff. So let's open.", "I am holding the cup. So let's open.", "I've got it", "I'm holding it",
+ "I have it, let go", "I have it", "I've got the cup", "I'm holding the cup, you can let go",
+ "I got the cup, open your hand", "I took it", "I grabbed it, release", "It's in my hand now",
+ "okay I've got hold of it", "Lumi, I'm holding it now", "I'm holding on to it, let it go", "got it, let go",
+ "I got it, open", "잡았어", "잡았어요", "내가 잡고 있어", "제가 들고 있어요, 놓아", "제가 잡았어요", "내가 컵 잡고 있어",
+ "제가 컵을 들고 있어요", "내 손에 있어", "제가 잡고 있으니까 놔도 돼요", "루미야 내가 잡았어", "컵 잡았어. 손 펴",
+ "제가 받았어요", "I 잡았어", "내가 hold 하고 있어", "cup 잡았어요, open 해", "I'm holding it, 놔"]
+NOT_THEY_HOLD = ["Open your hand.", "open your hand", "손 펴", "don't open, I'm not holding it", "I'm not holding it yet",
+ "I haven't got it", "I don't have it", "not yet, I'm not holding it", "when I hold it, let go",
+ "if I'm holding it, open", "I'll hold it", "let me hold it", "can I hold it?", "아직 안 잡았어", "안 잡았어",
+ "못 잡았어", "잡았어?", "잡았어요?", "잡고 있어", "들고 있어", "그거 들고 있어", "꽉 잡고 있어", "내가 잡으면 놔",
+ "내가 잡을게", "놓지 마, 내가 잡고 있어", "아직 잡지 않았어요", "제가 잡기 전에 놓지 마세요", "got it", "I got it",
+ "okay, got it", "I'm holding my phone", "I have a question", "I'm holding the door", "I'm holding it, don't let go",
+ "what am I holding?", "am I holding it?", "she's holding it", "I'm going to take it", "I took it yesterday",
+ "I'm not holding it, 놓지 마", "아직 안 잡았어, don't open"]
def main():
@@ -95,9 +111,22 @@ def main():
for words in ["고개 원위치", "머리 원위치", "head back to centre"]:
if brain.intent(words, MARKERS) != ("look", "center"):
bad.append((words, "look center", brain.intent(words, MARKERS)))
+ for words in THEY_HOLD: # by the reader and by the route voice and the Command box take
+ if lumi.route(words, MARKERS, brain.Brain(), True) != ("hand", (("release", None), True)) or \
+ brain.hand_request(words, False, None, MARKERS) == ("release", None):
+ bad.append((words, "release", lumi.route(words, MARKERS, brain.Brain(), True)))
+ for words in NOT_THEY_HOLD:
+ got = lumi.route(words, MARKERS, brain.Brain(), True)
+ if got[0] == "hand" and got[1][0][0] == "release":
+ bad.append((words, "no release", got))
+ after = brain.Brain() # "got it" right after the refused open: they hold it now
+ after.history.append(("Open your hand.", "ACTION: refuse -"))
+ for words in ["got it", "I got it", "okay, got it"]:
+ if brain.hand_request(words, True, after, MARKERS) != ("release", None):
+ bad.append((words, "release after the refusal", brain.hand_request(words, True, after, MARKERS)))
assert not bad, "\n".join(f"{t!r}: want {w}, got {g}" for t, w, g in bad)
n = len(CALLS) * len(TAILS) * len(GIVE_EN + GIVE_KO) + len(CALLS) * (len(TAKE_KO) + len(PUT_DOWN) + len(PUT_BACK)) + \
- len(REACH) + len(FOLD) + len(NOT_FOLD) + len(NOT_GIVE) + 22
+ len(REACH) + len(FOLD) + len(NOT_FOLD) + len(NOT_GIVE) + len(THEY_HOLD) + len(NOT_THEY_HOLD) + 25
print(f"held hand ok ({n} cases)")
diff --git a/tests/test_look_me.py b/tests/test_look_me.py
index 92e812b..8d7011a 100644
--- a/tests/test_look_me.py
+++ b/tests/test_look_me.py
@@ -8,6 +8,7 @@ from assistant import lumi
turns, pitches = [], []
lumi.head.turn = lambda yaw, pitch=None: (turns.append(round(yaw)), pitches.append(pitch))
lumi.LOOK_ME_SETTLE_S = 0.0
+lumi.waist_turned = lambda: 0.0 # the waist at the front unless a case says otherwise
class Vision:
@@ -193,3 +194,18 @@ turns.clear()
L.look_at_speaker()
assert waist["calls"] == [(-120, True, -125.0)] and turns == [-60, 60, -5, 0], (waist, turns)
print("look me from behind, unsure voice: ok")
+
+# the waist left turned at -73 deg, the caller on the other side (2026-10-30): nobody in either head look, so the waist
+# goes to the front and the head looks again from there, the voice's side first (+20 from the turned waist = -53 now)
+waist.update(at=-73.0, calls=[])
+lumi.waist_home = lambda why, fold=False: waist.update(at=0.0) or True
+L = lumi.Lumi.__new__(lumi.Lumi)
+L.vision, L.current = Vision([], [(-50.0, 2.0)]), None
+L.vision.views = [[], [], [], [(-50.0, 2.0)]]
+L.voice_angle, L.voice_trusted, L.voice_guess = 0.0, False, 20.0
+L.det_yaw = lambda: 0.0
+L.modes = type("M", (), {"patrol": False})()
+turns.clear()
+L.look_at_speaker()
+assert turns == [60, -60, -60, -50] and waist["calls"] == [], (turns, waist)
+print("look me with the waist turned: ok")
diff --git a/tests/test_pick_sweep.py b/tests/test_pick_sweep.py
index 9e54a84..d40b5ad 100644
--- a/tests/test_pick_sweep.py
+++ b/tests/test_pick_sweep.py
@@ -77,4 +77,25 @@ for name, (sc, must) in PLACES.items():
or r["result"] in ("exception", "timeout"):
bad.append((name, r["result"], r.get("why"), r["moves"]))
assert not bad, bad
+
+# ---------- live 2026-10-30: a round table at -327 mm ahead-left, lift 0. The torso camera sees its top from y ~640,
+# where the arm hardly reaches at that height: the base drove closer again and again, up to the table's edge ----------
+ROUND = lambda deg, near: {"c": P(deg, near + 0.45), "r": 0.45, "z": -327.0}
+for name, table in (("table in reach ahead-left", ROUND(20, 0.65)), ("table in reach, further left", ROUND(35, 0.55))):
+ r = ps.run_scene(ps.place_at([table]), 1.0) # in reach (with a waist turn): put down, no base move
+ print(f"place {name:44s} {r['result']:8s} moves {[m[:3] for m in r['moves']]} {r.get('why') or ''}")
+ if r["result"] != "ok" or r["moves"]:
+ bad.append((name, r["result"], r.get("why"), r["moves"]))
+# ... out of reach: one drive closer; there the camera loses it (only part of it in view): put on the table kept from
+# before the drive, never another drive
+real_far, real_ahead = ps.fetch.far_table, ps.fetch.table_ahead
+ps.fetch.far_table = lambda *a, **k: None if ps.W["rec"]["moves"] else real_far(*a, **k)
+ps.fetch.table_ahead = lambda *a, **k: None if ps.W["rec"]["moves"] else real_ahead(*a, **k)
+r = ps.run_scene(ps.place_at([ROUND(0, 1.0)]), 1.0)
+ps.fetch.far_table, ps.fetch.table_ahead = real_far, real_ahead
+print(f"place {'table lost after the drive':44s} {r['result']:8s} moves {[m[:3] for m in r['moves']]} "
+ f"{r.get('why') or ''}")
+if r["result"] != "ok" or len(r["moves"]) != 1:
+ bad.append(("table lost after the drive", r["result"], r.get("why"), r["moves"]))
+assert not bad, bad
print("pick sweep scenes ok")
diff --git a/tests/test_reach.py b/tests/test_reach.py
index f5d6e16..933c2e9 100644
--- a/tests/test_reach.py
+++ b/tests/test_reach.py
@@ -108,6 +108,7 @@ arm_route.head_cam.head_centre = real_centre
C = arm_route.head_cam.head_centre()[:2]
body = {"waist": -20.31} # the waist of measure-axis = the front
fetch.head.status = lambda: [75.0, body["waist"], 0.0, -5.0]
+fetch.head.moveto = lambda pos, **kw: None # _reach turns the head onto the cup (_aim_head)
around = lambda r, b: cup(C[0] - r * math.sin(math.radians(b)), C[1] + r * math.cos(math.radians(b)))
o = cup(-300, 400)
diff --git a/tests/test_reach_live.py b/tests/test_reach_live.py
index 9fa87ed..8770777 100644
--- a/tests/test_reach_live.py
+++ b/tests/test_reach_live.py
@@ -89,25 +89,32 @@ for t in ["There is nothing in your hand.", "your hand is empty", "you're not ho
for t in ["is there anything in your hand?", "what's in your hand", "give me your hand"]:
assert not lumi.HAND_EMPTY_SAID.search(t), t
L = lumi.Lumi.__new__(lumi.Lumi)
-folds, status = [], {"now": "done"}
+folds, status, stops = [], {"now": "done"}, []
L.fetch_status = lambda: status["now"]
L.arm_pose = lambda target: folds.append(target) or True
-for text, want in [("Okay, thank you.", True), ("okay thanks", True), ("고마워", True), ("됐어", True),
- ("what's the weather?", False), (None, False)]:
+real_state, real_stop = fetch.state, fetch.stop
+fetch.state, fetch.stop = lambda: {"step": "reaching out"}, lambda: stops.append(1)
+for text in ["Okay, thank you.", "okay thanks", "고마워", "됐어", "what's the weather?", "go home"]: # any next words
folds.clear()
L.reached_at = time.time()
- assert L.reach_done(text) == want and folds == (["fold"] if want else []), (text, folds)
+ assert L.reach_done(text) and folds == ["fold"], (text, folds)
+L.reached_at, folds[:] = time.time(), []
+assert not L.reach_done() and not folds # nothing said yet: the hand stays out
L.reached_at = time.time() - lumi.REACH_HOLD_S - 1 # nobody said anything: the timeout folds
-folds.clear()
assert L.reach_done() and folds == ["fold"]
-status["now"] = "running" # still reaching: not yet
-L.reached_at, folds[:] = time.time() - lumi.REACH_HOLD_S - 1, []
-assert not L.reach_done("thanks") and not folds
-status["now"] = "failed" # the reach failed: the arm stays, no later fold
+status["now"] = "running" # still going toward their hand: stopped, folded
+L.reached_at, folds[:] = time.time(), []
+assert L.reach_done("okay thanks") and folds == ["fold"] and stops, (folds, stops)
+status["now"] = "failed" # the reach failed (a timeout, 2026-10-30): folded
+L.reached_at, folds[:] = time.time(), []
+assert L.reach_done("thanks") and folds == ["fold"]
+status["now"] = "stopped" # a stop word: the arm stays where it is
+L.reached_at, folds[:] = time.time(), []
assert not L.reach_done("thanks") and not folds and not L.reached_at
L.reached_at = 0.0
status["now"] = "done"
assert not L.reach_done("thanks") and not folds # no reach out: "thanks" moves nothing
+fetch.state, fetch.stop = real_state, real_stop
# an arm left half way (a reach stopped by a lost state reply) and the waist turned: an order to drive folds the empty
# arm along the checked route, then the waist comes to the front; a conversation's end or a held thing never folds it
diff --git a/tests/test_robot_free.py b/tests/test_robot_free.py
index 87665ae..75a6f9b 100644
--- a/tests/test_robot_free.py
+++ b/tests/test_robot_free.py
@@ -39,9 +39,9 @@ def refused(fn, *a):
JOG = server.JogBody(axis="head_yaw", direction=1)
manual = (lambda: server.jog(JOG), server.gripper_open, server.gripper_close)
-# a modes file from before "Come when called" was dropped still loads, without the old key
+# a modes file with keys no longer used ("drive", "wave" when asked) still loads, without them
server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": False, "wave": True, "drive": False}))
-assert server.read_modes() == {"greeter": True, "patrol": False, "wave": True}, server.read_modes()
+assert server.read_modes() == {"greeter": True, "patrol": False, "wave_greet": False}, server.read_modes()
# idle, Patrol on: allowed
server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": True}))
diff --git a/tests/test_wave_greet.py b/tests/test_wave_greet.py
new file mode 100644
index 0000000..b20a009
--- /dev/null
+++ b/tests/test_wave_greet.py
@@ -0,0 +1,209 @@
+"""Self-check of the wave greeting (tasks/wave_greet.py) with a fake arm, head, waist and speech, no robot, and of the
+waving detector (vision/waving.py) on the recordings of vision/wave_record.py when they are here (tests/data/waves,
+local only: people in the pictures): python tests/test_wave_greet.py"""
+from pathlib import Path
+
+import no_robot # noqa: F401 any connection to the robot fails the test
+from manipulation import arm_route, wave
+from robot import head, motion
+from tasks import fetch, wave_greet as g
+from vision import waving
+
+done = [] # what the robot did, in order
+arm = {"at": "look"}
+waver = {"w": None} # (bearing, distance) of the person waving now
+plan_error = {"e": None}
+POSES = {"look": [0.0] * 6, "wave_out": [1.0] * 6, "wave_start": [2.0] * 6, "wave": [3.0] * 6}
+
+
+def plan():
+ if plan_error["e"]:
+ raise plan_error["e"]
+ return ([("wave_out", POSES["wave_out"]), ("wave_start", POSES["wave_start"])] if arm["at"] == "look" else [],
+ [])
+
+
+def move_path(moves, wait=True, queued=False):
+ if moves[-1][0] == POSES["wave_start"] and len(moves) == 2 and queued:
+ done.append("swing")
+ else:
+ done.append(f"up {moves[-1][1]}")
+ arm["at"] = "wave_start"
+
+
+def route_move(seq, speed=None, holding=False):
+ done.append(f"down {speed}")
+ arm["at"] = "look"
+
+
+wave.plan = plan
+motion.poses = lambda: dict(POSES)
+motion.move_path = move_path
+arm_route.where = lambda now=None: arm["at"]
+arm_route.plan = lambda target, holding=False, leaf=False, now=None: [("wave_out", None), ("look", None)]
+arm_route.move = route_move
+head.status = lambda: [0.0, 0.0, 0.0, 10.0]
+head.moveto = lambda pos, **k: done.append(f"head {pos[2]:+.0f}" + (" rest" if pos[3] == head.HEAD_REST_PITCH else "")
+ + (" timeout" if k.get("timeout") != g.HEAD_TIMEOUT_S else ""))
+fetch._waist_turn = lambda: 0.0
+fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
+g._head_yaw = lambda: 0.0
+g._too_close = lambda: False
+g._waver = lambda: waver["w"]
+said = []
+g._say = lambda lines, lang: said.append(lines[0][lang])
+switch = {"on": True, "free": True}
+g._on, g._free = (lambda: switch["on"]), (lambda: switch["free"])
+g._off = lambda: switch.update(on=False)
+g._bg = lambda fn, *args: fn(*args) # the background parts run at once here
+
+
+def run(t0, t1, dt=0.5):
+ t = t0
+ while t <= t1:
+ try:
+ g.step(t)
+ except Exception as e: # as _run
+ g._stopped(e)
+ t += dt
+
+
+def fresh():
+ done.clear()
+ said.clear()
+ arm["at"] = "look"
+ g._st.update(up=False, last_wave=0.0, next_joke=0.0, free_at=0.0, refused_until=0.0, waist_out=False)
+ switch.update(on=True, free=True)
+ plan_error["e"] = None
+
+
+# someone waves 30 deg on the left at 2 m: head to them, a greeting, arm up at the route speed, one swing, waist to them
+fresh()
+waver["w"] = (30.0, 2.0)
+run(100.0, 100.0)
+assert done == ["head +30", "up route", "swing", "waist +30 look 30.0"], done
+assert len(said) == 1 and said[0] in sum(g.wave_lines.GREET, ()), said
+assert g.busy()
+
+# they keep waving: swings, and a joke after JOKE_AFTER_S, then not again before JOKE_EVERY_S
+done.clear()
+said.clear()
+run(100.5, 100.0 + g.JOKE_AFTER_S + 1)
+assert done.count("swing") >= 10 and "up route" not in done, done
+assert len(said) == 1 and said[0] in sum(g.wave_lines.LONG, ()), said
+
+# they stop: the hand stays up, no swings; waving again: swings again, no new greeting within NEW_WAVE_S
+waver["w"] = None
+done.clear()
+run(112.0, 115.0)
+assert done == [], done
+waver["w"] = (30.0, 2.0)
+said.clear()
+run(115.5, 116.0)
+assert done.count("swing") == 2 and said == [], (done, said)
+
+# nobody waves for HOLD_S: arm down slowly, waist to the front, head to rest; not before
+waver["w"] = None
+done.clear()
+run(116.5, 116.0 + g.HOLD_S - 1)
+assert done == [], done
+run(116.0 + g.HOLD_S + 0.5, 116.0 + g.HOLD_S + 0.5)
+assert done == ["waist +0 look None", "down normal", "head +0 rest"], done
+assert not g.busy() and arm["at"] == "look"
+
+# the waist's way back is blocked: the arm still goes down; the waist is tried again every REFUSED_S while nobody waves
+fresh()
+waver["w"] = (30.0, 2.0)
+run(150.0, 150.0)
+waver["w"] = None
+blocked = {"n": 1}
+fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f}") or (
+ blocked.update(n=blocked["n"] - 1) or False if blocked["n"] > 0 else True)
+done.clear()
+run(150.5 + g.HOLD_S, 150.5 + g.HOLD_S + g.REFUSED_S * 2.5)
+assert done[:3] == ["waist +0", "down normal", "head +0 rest"] and done[3:] == ["waist +0"], done
+fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
+
+# beside a wall the full waist turn is blocked: it turns as far as its sweep is clear, the head on the person
+fresh()
+waver["w"] = (-66.0, 2.0)
+fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or abs(rel) < 40
+run(160.0, 160.0)
+assert done[-3:] == ["waist -66 look -66.0", "waist -50 look -66.0", "waist -33 look -66.0"], done
+fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
+
+# a wave nearly in front: only the head turns, the waist stays
+fresh()
+waver["w"] = (5.0, 1.5)
+run(200.0, 200.0)
+assert done == ["up route", "swing"], done # the head looks there already (within HEAD_MIN_DEG)
+
+# the switch is turned off with the hand up: down at once
+switch["on"] = False
+done.clear()
+run(200.5, 200.5)
+assert done[:2] == ["waist +0 look None", "down normal"], done
+
+# the arm stops (STOP, a person too close) during a swing: switched off, nothing moves after it
+fresh()
+waver["w"] = (0.0, 2.0)
+run(300.0, 300.0)
+
+
+def stopped(*a, **k):
+ raise motion.MotionError("stopped")
+
+
+motion.move_path = stopped
+run(300.5, 300.5)
+assert switch["on"] is False and not g.busy() and said[-1] in ("I stopped my arm.", "팔을 멈췄어요."), said
+motion.move_path = move_path
+done.clear()
+run(301.0, 310.0)
+assert done == [], done
+
+# the arm refused (off, busy, something held): nothing moves, tried again after REFUSED_S only
+fresh()
+plan_error["e"] = wave.WaveError(*wave.OFF)
+run(400.0, 400.0 + g.REFUSED_S - 1)
+assert done == [] and switch["on"], done
+plan_error["e"] = None
+run(400.0 + g.REFUSED_S + 0.5, 400.0 + g.REFUSED_S + 0.5)
+assert "up route" in done, done
+
+# the assistant or a task has the robot: nothing moves
+fresh()
+switch["free"] = False
+run(500.0, 505.0)
+assert done == [] and not g.busy(), done
+
+# a hand at the head (scratching, a phone at the ear) is not a raised hand; the same hand held out to the side is
+import numpy as np # noqa: E402
+kp = np.zeros((17, 3))
+for name, xy in (("nose", (640, 200)), ("left_eye", (650, 190)), ("right_eye", (630, 190)), ("left_shoulder", (700, 320)),
+ ("right_shoulder", (580, 320)), ("right_elbow", (560, 260)), ("right_wrist", (600, 210))):
+ kp[g.pose.K[name]] = (*xy, 1.0)
+assert waving._hand(kp) is None # palm at (620, 185): beside the eye
+kp[g.pose.K["right_wrist"]] = (480, 200, 1.0)
+kp[g.pose.K["right_elbow"]] = (520, 280, 1.0)
+assert waving._hand(kp) is not None # palm at (460, 160): out to the side
+
+# the detector on the recordings: every wave found, nothing else ever counts as waving
+DATA = Path(__file__).parent / "data" / "waves"
+if DATA.exists():
+ for f in sorted(p for p in DATA.iterdir() if p.is_dir()):
+ r = waving.run_recording(f)
+ seen = [any(w) for _, w in r]
+ if f.name.startswith("no_"):
+ assert not any(seen), f.name
+ else:
+ first = next(t - r[0][0] for (t, _), s in zip(r, seen) if s)
+ assert first < 2.0, (f.name, first) # found within 2 s
+ if f.name != "pause_2m": # (it stops waving half way)
+ assert sum(seen) > 0.75 * len(seen), (f.name, sum(seen), len(seen))
+ r = waving.run_recording(DATA / "pause_2m") # stopped at ~6 s: no longer waving 2.5 s later
+ assert not any(any(w) for t, w in r if t - r[0][0] > 8.5)
+else:
+ print("(no recordings here: detector not checked)")
+
+print("wave greeting: ok")
diff --git a/vision/wave_record.py b/vision/wave_record.py
new file mode 100644
index 0000000..dba5ee2
--- /dev/null
+++ b/vision/wave_record.py
@@ -0,0 +1,116 @@
+"""Record people's keypoints from the head camera while Lumi reads out what to do: the waves (and the non-waves) the
+wave greeting is tuned and tested on. Moves nothing; Lumi only speaks (POST /say).
+
+ python vision/wave_record.py [first_step] # writes tests/data/waves/