From 8ec328f9dadac8654da1f1b8f734cbd80eb0b9ca Mon Sep 17 00:00:00 2001 From: Cutshion Date: Fri, 30 Oct 2026 20:55:05 +0900 Subject: [PATCH] Keep head moves from hanging, check a shut hand with the camera and follow round tight spots Co-Authored-By: Claude Opus 5.5 --- assistant/lumi.py | 46 +++++++++---- robot/head.py | 17 ++++- tasks/fetch.py | 99 +++++++++++++++++++++----- tasks/follow.py | 134 ++++++++++++++++++++++++++++++------ tests/parity_check.py | 2 +- tests/test_chain.py | 2 +- tests/test_come_give.py | 2 +- tests/test_command_box.py | 4 +- tests/test_detour.py | 1 + tests/test_fetch.py | 8 ++- tests/test_fetch_place.py | 6 +- tests/test_follow.py | 98 +++++++++++++++++++++++--- tests/test_hand_check.py | 103 +++++++++++++++++++++++++++ tests/test_mission_name.py | 2 +- tests/test_mission_route.py | 2 +- tests/test_quick_answers.py | 2 +- tests/test_reach_live.py | 7 ++ tests/test_task_switches.py | 2 +- 18 files changed, 458 insertions(+), 79 deletions(-) create mode 100644 tests/test_hand_check.py diff --git a/assistant/lumi.py b/assistant/lumi.py index 496aa87..918e8a0 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -422,6 +422,10 @@ HAND_EMPTY_SAID = re.compile( # the person says Lumi's hand is empty: checked r"\b(?:nothing|not anything) (?:is )?in (?:your|ur) hand\b|\b(?:your|ur) hand(?:'s| is) empty\b|" r"\byou(?:'re| are) not holding (?:anything|something)\b|\byou have nothing in (?:your|ur) hand\b|" r"손에 ?(?:아무것도|아무 ?것도|뭐 ?없|없)|손 ?비었|빈 ?손이", re.I) +HAND_FULL_SAID = re.compile( # the person says Lumi holds something: checked (fetch.look_at_hand), not just denied + r"\byou(?:'re| are) (?:still )?holding\b(?! (?:up|on|back|me|us|out)\b)|\b(?:look at|check) (?:your|ur) hand\b|" + r"\byou (?:still )?have (?:a|the|my|something) ?\w* in (?:your|ur) hand\b|\bthere(?:'s| is) (?:a|the|something) ?\w* in (?:your|ur) hand\b|" + r"손에 ?\S+ ?(?:있잖아|들고 ?있잖아|있어요|있어)|들고 ?있잖아", re.I) STUCK_DRIVE_S = 20.0 # s "running" without moving -> the drive is cancelled and Lumi says so MODES_FILE = "/dev/shm/lumi_modes.json" # written by api/server.py: {"greeter", "patrol", "wave"} CMD_FILE = "/dev/shm/lumi_cmd.json" # written by api/server.py: {"id", "cmd": go | go_point | cancel | calibrate @@ -2214,7 +2218,8 @@ class Lumi: self.fetch_say(*brain_mod.REFUSE_OPEN) return None if target in ("open", "close"): - st = safe(gripper.open_ if target == "open" else gripper.close) + st = safe(gripper.open_ if target == "open" else fetch.close_hand) # close: a thing seen between the + # fingers stays held when they shut on it (narrow) log(f" gripper {target}: {st}") return st is not None if target == "reach": @@ -2304,9 +2309,13 @@ class Lumi: 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: - return False status = self.fetch_status() + if text is None: # REACH_HOLD_S from when the hand got there: the reach + if status == "running": # itself once took 32 s to start (2026-10-30 18:26) and + return False # was folded back as it arrived + since = max(self.reached_at, safe(fetch.state, default={}).get("since") or 0.0) + if time.time() - since < REACH_HOLD_S: + return False 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 @@ -2328,11 +2337,13 @@ class Lumi: finally: self.typed_now = False - def held_now(self): + def held_now(self, look=False): """Something in the hand now: the hand is checked (fetch.check_hand, which also forgets a stale "holding"); - the state when it can't be. The stale state alone refused open / wave on an empty hand (2026-10-23 17:41).""" + the state when it can't be. The stale state alone refused open / wave on an empty hand (2026-10-23 17:41). + `look`: for an order that needs the hand or words about what is in it, a fully shut hand is looked at first + (fetch.look_at_hand: the arm to carry, slowly).""" from tasks import fetch - h = safe(fetch.check_hand) + h = safe(fetch.look_at_hand if look else fetch.check_hand) return self.fetch_status() == "holding" if h is None else bool(h) # ---------- dashboard commands, trips ---------- @@ -3153,7 +3164,9 @@ class Lumi: self.keep_listening() return from tasks import fetch # the way it goes: route(), as the dashboard's Command box - kind, data = route(text, self.markers, self.brain, self.held_now, + full = brain_mod.hand_request(text, True, self.brain, self.markers) # an order that needs the hand: a fully + needs = bool(full) and full[0] in ("give", "place") # shut hand is looked at first (live 2026-10-30: a cup + kind, data = route(text, self.markers, self.brain, lambda: self.held_now(look=needs), # put in it was "not held") seen=lambda x: seeing.answer(x, self.lang, slow_line=mouth.say), last=last, chain_ok=not part and not self.mission_running() and not self.chain_busy()) if kind == "stop": self.stop_all(text) # "stop", "stop, where are you going?": stop first, always @@ -3171,12 +3184,17 @@ class Lumi: mouth.say(data) self.keep_listening() return - if HAND_EMPTY_SAID.search(text) and self.fetch_status() != "running": # "there is nothing in your hand" - held = self.held_now() # checked again (AI_1, the torso camera), never just agreed - log(f" told my hand is empty: checked, holding {held}") + told = "empty" if HAND_EMPTY_SAID.search(text) else "full" if HAND_FULL_SAID.search(text) else None + if told and self.fetch_status() != "running": # "there is nothing in your hand", "you are holding the cup" + held = self.held_now(look=True) # checked again (AI_1, the torso camera), never just agreed + log(f" told my hand is {told}: checked, holding {held}") self.brain.history.append((text, "ACTION: none -")) - self.fetch_say(*(("I still feel something in my hand.", "아직 손에 뭔가 있는 것 같아요.") if held else - ("You're right, my hand is empty.", "맞아요, 손이 비어 있어요."))) + if told == "empty": + self.fetch_say(*(("I still feel something in my hand.", "아직 손에 뭔가 있는 것 같아요.") if held else + ("You're right, my hand is empty.", "맞아요, 손이 비어 있어요."))) + else: + self.fetch_say(*((f"Yes, I'm holding {fetch.held_name()}.", "네, 들고 있어요.") if held else + ("I checked, my hand is empty.", "확인해 보니 손이 비어 있어요."))) self.keep_listening() return if kind == "status": # what am I doing / where am I going @@ -3282,7 +3300,7 @@ class Lumi: if head_["action"] in ("receive", "give", "place"): # the model read a hand request the rules missed gen.close() from tasks import fetch - held = self.held_now() + held = self.held_now(look=head_["action"] != "receive") self.brain.history.append((text, f"ACTION: {head_['action']} -")) if head_["action"] == "receive": self.receive_from_hand(brain_mod._mentions(text, self.markers).get("object"), held) @@ -3585,7 +3603,7 @@ class Lumi: self.end_run(text) if self.come_to(self.current, say=True) is False: # stopped on the way return - if self.held_now(): + if self.held_now(look=True): self.fetch_finish("give") else: mouth.say(EMPTY_HAND_SAY[self.lang]) diff --git a/robot/head.py b/robot/head.py index 955f66b..367734c 100644 --- a/robot/head.py +++ b/robot/head.py @@ -8,10 +8,14 @@ import json import sys import threading +import time import urllib.request BODY = "http://192.168.10.90:5000/api/extaxis" YAW_LIMIT = 60.0 # deg; we keep the head well inside its +-180 range +STILL_S = 0.1 # s between two position reads that must agree before a move is sent +TURN_TIMEOUT_S = 8.0 # s a head turn may take (estimate, to measure); a move the controller never reported + # done held every other body move 30 s and Lumi stopped listening (2026-10-30) PITCH_RANGE = (-5.0, 35.0) # deg, hardware range HEAD_REST_PITCH = PITCH_RANGE[0] # deg; the head's rest: its lowest, looking down (+pitch = up), so sitting people # and near things are in view. Every "head back / ahead" uses it; yaw rests at 0 @@ -43,9 +47,16 @@ def moveto(pos, vel=VEL, acc=ACC, timeout=30): return None # ponytail: skipped silently, the owner turns it back pos = [max(lo, min(hi, float(p))) for p, (lo, hi) in zip(pos, AXIS_LIMITS)] with _one: - if not all(j["enable"] for j in _call("status")): # off after a controller power cycle; moveto needs them on + end = time.time() + timeout + joints = _call("status") + while time.time() < end: # another process's move still runs: a moveto sent meanwhile + time.sleep(STILL_S) # is dropped and its call never answers (checked 2026-10-30: + before, joints = joints, _call("status") # 20 s timeout, no motion). "vel" reads 0 while moving, so + if all(abs(a["pos"] - b["pos"]) < 0.05 for a, b in zip(before, joints)): # the positions tell + break + if not all(j["enable"] for j in joints): # off after a controller power cycle; moveto needs them on _call("enable", {"enable": 1}) - return _call("moveto", {"pos": pos, "vel": vel, "acc": acc}, timeout=timeout) + return _call("moveto", {"pos": pos, "vel": vel, "acc": acc}, timeout=max(1.0, end - time.time())) def status(): @@ -58,7 +69,7 @@ def turn(yaw, pitch=None, vel=VEL, acc=ACC, limit=YAW_LIMIT): lift, waist, _, cur_pitch = status() yaw = max(-limit, min(limit, yaw)) pitch = cur_pitch if pitch is None else max(PITCH_RANGE[0], min(PITCH_RANGE[1], pitch)) - return moveto([lift, waist, yaw, pitch], vel, acc) + return moveto([lift, waist, yaw, pitch], vel, acc, timeout=TURN_TIMEOUT_S) if __name__ == "__main__": diff --git a/tasks/fetch.py b/tasks/fetch.py index 6908b83..7ad388b 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -50,6 +50,9 @@ LOOK_POSE = "look" # drives, turns, looks and waits here, also with an # the torso view, too near for depth (ready if not taught). carry is only passed through after a # pick: in carry the hand is ~0.3 m before the base's front, where its 3D camera seems to see # it as an obstacle (every drive in carry stalled; the same drives in look went, 2026-10-16) +CHECK_POSE = "carry" # a fully shut hand is looked at here (look_at_hand): the torso camera sees the place between + # the fingers ~445 mm away (from the joints and the calibration; in look it is above the view, + # in give a person's hand can be there). Not yet tried live: the fingers may hide it MAX_TILT_DEG = skills.MAX_TILT_DEG # deg; the held cup's axis may lean this far from vertical on a straight move LINE_POINTS = 20 # points IK- and tilt-checked on a straight move with an object in the hand ... LINE_STEP_DEG = 25.0 # ... no joint may turn more than this between two of them (one IK branch all the way; @@ -785,14 +788,15 @@ def head_hits(deg, pts=None): return depth_hits(deg, "head", T, pts) -def turn_hits(deg, pts=None): +def turn_hits(deg, pts=None, pose=None): """The map point (x, y) where the arm would come closer than ARM_CLEAR_M to something the lidar or the map shows while the base turns by `deg`, checked every SWEEP_STEP_DEG along the way; None when the way is clear. The base - itself turns in its own footprint; navigation does not know about the arm sticking out. `pts`: as depth_hits.""" + itself turns in its own footprint; navigation does not know about the arm sticking out. `pts`: as depth_hits. + `pose`: the base's (x, y, th) to turn from, else where it is.""" if arm_yaw() is None: return None k0, pts = (1, arm_points()) if pts is None else (0, [to_base(p[:2], arm_yaw(), arm_xy()) for p in pts]) - x, y, th = agv.pose() + x, y, th = pose or agv.pose() n = max(1, math.ceil(abs(deg) / SWEEP_STEP_DEG)) for k in range(k0, n + 1): R = _rot(math.degrees(th) + deg * k / n) @@ -2625,29 +2629,89 @@ def _busy(): # ---------- public ---------- def _in_hand(): - """Is something in the hand, whatever the state file says? The torso depth camera first (skills.hand_sees: it - sees the place between the fingers); when it can't tell, the gripper's AI_1. AI_1 alone was wrong once: a cup - pulled out of the closed fingers left it reading "open" (2026-10-16). Fingers fully shut (AI_1 above - gripper.EMPTY_AI) hold nothing, whatever the camera sees: with the arm held out it saw the person's hand there and - "closed on nothing" became "holding" (2026-10-23 17:40).""" + """Is something in the hand, whatever the state file says? AI_1 stopped between gripper.CLOSED_AI and EMPTY_AI: + held. Fully shut (above EMPTY_AI): a thing narrower than the belly's closed gap sits in the hooks with AI_1 reading + as on nothing (live 2026-10-30: a cup put in the hand read 4143), so the torso camera decides, but only from + CHECK_POSE (look_at_hand); anywhere else it is held only when close_hand closed on a thing the camera saw between + the open fingers ("narrow"): with the arm held out the camera saw the person's hand there after a close and + "closed on nothing" became "holding" (2026-10-23 17:40). Open: the torso camera first (skills.hand_sees), "unknown" + = empty; AI_1 alone was wrong once: a cup pulled out of the closed fingers left it reading "open" (2026-10-16).""" try: g = gripper.state() - ai = bool(g["holding"]) - if g.get("ai", [0.0])[0] > gripper.EMPTY_AI: - return False + if g["holding"]: + return True + shut = g.get("ai", [0.0])[0] > gripper.EMPTY_AI except (ConnectionError, OSError, KeyError): - ai = None + shut = None + narrow = bool(_state["holding"] and skills._held.get("narrow")) try: + if shut and not (CHECK_POSE in motion.poses() and _at_pose(CHECK_POSE)): + return narrow seen = skills.hand_sees() - except (skills.SkillError, ConnectionError, OSError, KeyError): + except (skills.SkillError, motion.MotionError, ConnectionError, OSError, KeyError): seen = "unknown" if seen == "unknown": - return bool(ai) - if ai is not None and ai != (seen == "object"): - log(f"hand: the camera sees it {seen}, AI_1 says {'holding' if ai else 'empty'}: the camera is believed") + return narrow if shut else False + if seen == "object" and shut is False: + log("hand: the camera sees it object, AI_1 says empty: the camera is believed") + if shut: + log(f"hand: fully shut, the camera sees it {seen} from {CHECK_POSE}") + if seen == "object": + skills._held["narrow"] = True # held while shut: away from CHECK_POSE too return seen == "object" +def look_at_hand(): + """check_hand before an order that needs something in the hand (put down, give, bring) or when told what is in + it: a fully shut hand first goes slowly (holding) along the checked route to CHECK_POSE, so the camera can tell.""" + _to_check_pose() + return check_hand() + + +def _to_check_pose(): + """A fully shut hand to CHECK_POSE (look_at_hand), not while a task runs.""" + if _busy() or CHECK_POSE not in motion.poses(): + return + try: + shut = gripper.state().get("ai", [0.0])[0] > gripper.EMPTY_AI + except (ConnectionError, OSError, KeyError): + shut = False + if shut: + try: + if not _at_pose(CHECK_POSE): + log(f"hand: fully shut, the arm to {CHECK_POSE} to look at it") + arm_route.goto(CHECK_POSE, holding=True) + except (arm_route.RouteError, motion.MotionError, ConnectionError, OSError) as e: + log(f"hand: can't look at it from {CHECK_POSE}: {e}") + + +def close_hand(): + """The voice "close your hand": the camera looks between the open fingers first; closed fully on a thing it saw + there (narrower than the belly's closed gap), it is held all the same ("narrow", named by vision.scene when the + person's hand held it, else "something"); closed fully on nothing seen: nothing is held. Returns gripper.close()'s + state. A hand already closed is closed again and nothing else changes.""" + _adopt() + try: + before = None if gripper.state()["closed"] else skills.hand_sees() + except (skills.SkillError, ConnectionError, OSError, KeyError): + before = "unknown" + st = gripper.close() + if before is None: + return st + shut = st.get("ai", [0.0])[0] > gripper.EMPTY_AI + with _lock: + if shut and before == "object" or st.get("holding") and not _state["holding"]: + thing = _scene("object_in_hand") or {} + log(f"hand: closed on {thing.get('name') or 'something'} (camera before: {before}, AI_1 " + f"{st.get('ai', [0.0])[0]:.0f})") + skills._held.clear() + skills._held.update(received=True, narrow=shut) + held_by_skill({"object": thing.get("name"), "colour": thing.get("colour")}) + elif shut and _state["holding"]: + _forget_held() + return st + + def check_hand(): """Bring the state in line with the hand (_in_hand) while no task runs: forget a held object that is gone, take over one that is there. Returns whether something is held. The dashboard's command dialog asks this.""" @@ -2709,7 +2773,7 @@ def _hold_again(): put down needs. Live 2026-10-26 18:53:00 one hand read said empty with the cup in it; after that every reply said "something" and put down had no height. ponytail: the last forgotten thing is assumed; a thing put in the hand without receive would get its name.""" - if not skills._held and _last_held.get("held"): + if not set(skills._held) - {"narrow"} and _last_held.get("held"): skills._held.update(_last_held["held"]) _set(holding=True, held_object=_state.get("held_object") or _last_held.get("held_object")) @@ -2748,6 +2812,7 @@ END_WORDS = {"go": ("I'm here.", "도착했어요."), "place": PUT_DOWN_WORDS, " def _finish(fn, say, end=None): _adopt() + _to_check_pose() # a fully shut hand: looked at (_in_hand) before it is refused with _lock: if _busy(): raise FetchError("I'm busy with another task.") diff --git a/tasks/follow.py b/tasks/follow.py index aec482a..9595f11 100644 --- a/tasks/follow.py +++ b/tasks/follow.py @@ -12,10 +12,14 @@ turns further out: following starts with it where it is (turned toward the perso as the base comes round (unwind). Nothing waits for another. The base is driven with joy_control every TICK_S (one command lasts 0.5 s: a stuck loop stops the base by itself), the arm in look; forward only with the person near ahead and the waist near the front. Every command is checked first: where the base and the arm would be BRAKE_S later must be clear -(lidar + map, agv.clearance); when not, the base stands, and after BLOCKED_END_S it gives up. +(lidar + map, agv.clearance); when not, the base stands, and after BLOCKED_END_S it gives up. A turn on the spot whose +arm sweep is blocked goes the other way round, or from a spot a short straight move away (_room_to_turn); it never +turns faster than the head keeps the person in view (focus), and a head that can't follow them past its +-180 swings +through the front to meet them (meet) while the torso camera watches (torso_people). stop() from any thread: the event is set and the base is sent 0 at once """ +import json import math import re import threading @@ -26,7 +30,7 @@ import numpy as np from robot import agv, head, motion from tasks import fetch -from vision import reid +from vision import camview, reid FOLLOW_GAP_M = 1.0 # m; keep this far from the person (camera distance); nearer: no forward NEAR_STOP_M = 0.8 # m; nearer than this no turn either: the arm would swing close to them (estimate) @@ -39,7 +43,8 @@ REACT_S = 0.3 # s; from a person stopping to the base braking (fra ACCEL_MS2 = 0.5 # m/s^2; speeding up at most this fast (estimate, tune live) DECEL_MS2 = 0.8 # m/s^2; slowing down this fast, and never faster than lets it stop at the gap (estimate) TURN_GAIN = 1.5 # rad/s per rad the person is off to the side -TURN_MAX_RS = 0.6 # rad/s; turn speed cap (joy_control takes up to 1.0; the arm tips sweep 0.6 m out) +TURN_MAX_RS = 1.0 # rad/s; turn speed cap = joy_control's own clamp (docs/05; the arm tips sweep 0.6 m out, + # 0.6 m/s); slower while the head can't keep the person in view (FOCUS_*) TURN_ACCEL_RS2 = 2.0 # rad/s^2; turn speed changes at most this fast (estimate) TURN_DEAD_DEG = 5.0 # deg; the person this near the middle: no turn TURN_ONLY_DEG = 35.0 # deg; the person further aside: turn on the spot first, no forward @@ -62,6 +67,15 @@ JOIN_S = 2.0 # s a new "follow me" waits for the old loop to end BEHIND_DEG = 180.0 # deg; the person's angle from the base is kept within +-this (right behind: one side) ROUND_MAX_DEG = 225.0 # deg; the arm blocked turning toward them, the base turns the other way round when that is # at most this far (the person within 45 deg of right behind, beside a wall) +SHIFT_STEP_M = 0.1 # m; blocked both ways on the spot: straight moves this long, then twice ... tried (each +SHIFT_MAX_M = 0.4 # ... way clear and the turn from its end clear), up to this (estimate; between fetch's + # NEAR_BACK_M 0.3 back-off and STRAIGHT_MAX_M 0.6 straight drive) +SHIFT_MS = fetch.MOVE_SPEED # m/s; that move's speed (a mission's straight move, 0.10) +FOCUS_FULL_DEG = 5.0 # deg; the base turns at full speed while the head's gaze is at most this far behind the +FOCUS_EDGE_DEG = 25.0 # person, slower and slower up to this (the head camera sees +-47, vision/person.py; the + # rest is the person's own width and the braking at TURN_ACCEL_RS2). Estimates +HEAD_DEG_S = 40.0 # deg/s; the head's top speed (audio/sing.py, measured): where a swing through the front + # meets a person coming round HEAD_REL_MAX = 30.0 # deg; a turned waist unwinds until the person is this far from the base heading, the # head looks for the rest (it never turns further out while following, unwind()) WAIST_FOLLOW_MAX = 90.0 # deg from the front; a waist turned further unwinds to this first (estimate) @@ -81,7 +95,7 @@ HEAD_LEAD_MAX_S = 1.5 # much later at least, or as long as the last head m # the base turning 0.6 rad/s goes 35-45 deg round in one move, which left the head off them HEAD_VEL = 100 # speed and acceleration ratio %, the body API's maximum: the head's speed tops out from 50 # (~40 deg/s, audio/sing.py, measured at 100 / 100); the waist's moves keep WAIST_FOLLOW_VEL -HEAD_TIMEOUT_S = 5 # s; one head move (90 deg at ~40 deg/s takes ~2.5 s) +HEAD_TIMEOUT_S = 10 # s; one head move (a swing through the front, up to 360 deg at HEAD_DEG_S, takes ~9 s) CHARGER = ("I'm on the charger, I can't follow you from here.", "충전 중이라 따라갈 수 없어요.") ARM_BUSY = ("A program is running on my arm, so I can't follow you.", "팔에서 프로그램이 실행 중이라 따라갈 수 없어요.") @@ -133,15 +147,16 @@ def stop(): return was -def speeds(distance, angle_deg, v_last, w_last=0.0, walk=0.0, go=True, dt=TICK_S): +def speeds(distance, angle_deg, v_last, w_last=0.0, walk=0.0, go=True, dt=TICK_S, w_max=TURN_MAX_RS): """(v m/s, w rad/s) toward a person `distance` m away at `angle_deg` (+ left), walking `walk` m/s away (- toward the base): their speed plus SPEED_GAIN per m beyond the gap, never faster than lets the base stop at the gap, changed smoothly (ACCEL_MS2 / DECEL_MS2). - Never forward inside the gap; nothing at all inside NEAR_STOP_M. go=False: only slow down (and turn).""" + Never forward inside the gap; nothing at all inside NEAR_STOP_M. go=False: only slow down (and turn). w_max: the + turn's cap now (focus()).""" if distance < NEAR_STOP_M: return 0.0, 0.0 a = math.radians(angle_deg) - w_want = 0.0 if abs(angle_deg) < TURN_DEAD_DEG else max(-TURN_MAX_RS, min(TURN_MAX_RS, TURN_GAIN * a)) + w_want = 0.0 if abs(angle_deg) < TURN_DEAD_DEG else max(-w_max, min(w_max, TURN_GAIN * a)) w = w_last + max(-TURN_ACCEL_RS2 * dt, min(TURN_ACCEL_RS2 * dt, w_want - w_last)) room = distance - FOLLOW_GAP_M if room <= 0: @@ -163,7 +178,7 @@ def blocked(v, w, arm_pts, pose=None): x, y, th = pose or agv.pose() th2 = th + w * BRAKE_S x2, y2 = x + v * BRAKE_S * math.cos(th), y + v * BRAKE_S * math.sin(th) - if v > 0: + if v: # forward, or back (room to turn, _room_to_turn) ahead = agv.clearance(x2, y2) if ahead < BASE_CLEAR_M and ahead < agv.clearance(x, y): return f"an obstacle {ahead:.2f} m from the base's way" @@ -297,6 +312,64 @@ def unwind(w, b): return 0.0 if goal * w <= 0.0 else math.copysign(min(abs(goal), abs(w)), w) +def focus(a, gaze): + """The base's turn cap (rad/s) toward a person a deg from its heading while the head (waist + head) looks at gaze + deg: full while the gaze is within FOCUS_FULL_DEG of them, down to 0 at FOCUS_EDGE_DEG, but only when the turn takes + them further from the gaze (the head is further round than they are); turning them toward the gaze is never held. + The base turns ~57 deg/s at TURN_MAX_RS, the head ~40 (HEAD_DEG_S): unchecked it outran the head.""" + off = (a - gaze + 180.0) % 360.0 - 180.0 + if off * a >= 0.0 or abs(off) <= FOCUS_FULL_DEG: + return TURN_MAX_RS + return TURN_MAX_RS * max(0.0, (FOCUS_EDGE_DEG - abs(off)) / (FOCUS_EDGE_DEG - FOCUS_FULL_DEG)) + + +def meet(gaze, a, side): + """Where (deg from the base heading) the head, looking at gaze, meets the person a deg round (on `side`'s half, so + past +-180) while the base turns round that way at TURN_MAX_RS: the head can't follow them across its +-180, so it + swings through the front at HEAD_DEG_S toward them as they come round; never past the front, where they end.""" + rate = -side * math.degrees(TURN_MAX_RS) # deg/s their angle changes (toward the front) + closing = math.copysign(HEAD_DEG_S, a - gaze) - rate + if (a - gaze) * closing <= 0.0: + return 0.0 + m = a + rate * (a - gaze) / closing + return side * max(0.0, side * m) + + +def _room_to_turn(pose, p, turned, pts): + """Signed length (m, + forward) of the shortest straight move, up to SHIFT_MAX_M, after which the base can turn on + the spot toward the person at the map point p one way round or the other (the arm's sweep clear, fetch.turn_hits), + with the way there clear for the base and the arm (blocked(), every fetch.PROBE_STEP_M) and the person still + FOLLOW_GAP_M away; at each length away from them first. None when there is none.""" + x, y, th = pose + there = lambda s: (x + s * math.cos(th), y + s * math.sin(th), th) + for k in range(1, round(SHIFT_MAX_M / SHIFT_STEP_M) + 1): + for s in sorted((k * SHIFT_STEP_M, -k * SHIFT_STEP_M), key=lambda s: -_rel(there(s), p)[0]): + d, a = _rel(there(s), p) + if d < FOLLOW_GAP_M: + continue + n = math.ceil(abs(s) / fetch.PROBE_STEP_M - 1e-9) + # blocked() looks BRAKE_S ahead at speed v: v = s / BRAKE_S checks the point s m along + if any(blocked(s * i / n / BRAKE_S, 0.0, pts, pose) for i in range(1, n + 1)): + continue + for deg in (a, a - math.copysign(360.0, a)): + if abs(deg) <= ROUND_MAX_DEG and fetch.turn_hits(deg - turned, pose=there(s)) is None: + return s + return None + + +def torso_people(): + """The torso camera's fresh people [(distance m, waist-frame angle deg, age s, None)]: it turns with the waist and + sees ahead while the head swings off the person (the assistant's tracks come from the head camera only).""" + camview.want("torso") + try: + d = json.loads(camview.det_path("torso").read_text()) + age = time.time() - d["time"] + return [(p["distance_m"], p["angle_deg"], age, None) for p in d["people"] + if p["distance_m"] is not None and age < STALE_S] + except (FileNotFoundError, ValueError, KeyError, TypeError): + return [] + + def _head_follow(target, done, lift, front, w, waist_free, stats): """Turn the head to the person at target[0] (deg from the base heading, pitch), the waist back toward the front with it. Every move sends the head straight to them (up to +-BEHIND_DEG on the waist, never held back) and the waist @@ -385,16 +458,20 @@ def _run(see, say, people): turning, blocked_t, hold_v, log_t, odd_t, log_pose = False, None, 0.0, 0.0, 0.0, agv.pose() side = 0.0 # +-1: turning round the other way (one way blocked), until # the person is ahead again; 0: the near way - while not _stop.is_set(): + shift, shifted = None, False # (pose, m): a straight move to where it can turn; made once + while not _stop.is_set(): # for a turn now = time.time() pose = agv.pose() try: - turned = head.status()[1] - front + _, waist, yaw = head.status()[:3] + turned, gaze = waist - front, waist - front + yaw except (ConnectionError, OSError, KeyError): pass # the last reading: the body API may be busy seen_from = _seen_from(pose, turned) mine, was = see(), see - see, got = _pick(see, mine, people, person, seen_from, sig, now) + # the head off them (swinging round): the torso camera watches (no clothes: it only keeps where they are) + torso = [] if _fresh(mine) else [(see, *g) for g in torso_people()] + see, got = _pick(see, mine, lambda: (people() if people else []) + torso, person, seen_from, sig, now) if see is not was: fetch.log(f"follow: re-locked onto the person at {got[0]:.2f} m {got[1]:+.0f} deg") elif got is None and _fresh(mine) and now - odd_t > LOG_S: @@ -408,7 +485,7 @@ def _run(see, say, people): if people else [0.0] if got[3] is not None and all(e > JUMP_M or e < 0.05 for e in near): # alone (or themselves): sig = reid.blend(sig, got[3]) # these clothes are theirs - if side: + if side or shift: start_t = now # out of view while it turns round: lost counts after if now - max(person.t or 0.0, start_t) >= LOST_S: fetch.log("follow: lost the person") @@ -429,13 +506,24 @@ def _run(see, say, people): pose[2] + w * lead) # the base when the head gets there (v, w: this command) yaw = _rel(then, person.at(now + lead))[1] yaw = ref + (yaw - ref + 180.0) % 360.0 - 180.0 - if side and abs(yaw) > 90.0: # the head ahead (not round past its +-180): the person - yaw = 0.0 # comes into view as the base turns + if side: # the head can't follow them round past its +-180: it + yaw = meet(gaze, a, side) # swings through the front to meet them coming round target[0] = (max(-BEHIND_DEG, min(BEHIND_DEG, yaw)), HEAD_PITCH) walk = float(person.vel @ np.array([math.cos(pose[2]), math.sin(pose[2])])) go = now - person.t <= COAST_S and abs(turned) < WAIST_DRIVE_DEG # forward with the waist ahead - cmd = speeds(d, a, v, w, walk, go=go, dt=TICK_S) - spot = cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind) + cap = TURN_MAX_RS if side else focus(a, gaze) # never turning them out of the head's view + cmd = speeds(d, a, v, w, walk, go=go, dt=TICK_S, w_max=cap) + pts = [fetch._rot(turned) @ p for p in arm_pts] # the arm turned with the waist + if shift: # straight to where it can turn, then the turn checked again + (x0, y0, th0), m = shift + gone = (pose[0] - x0) * math.cos(th0) + (pose[1] - y0) * math.sin(th0) + if gone * math.copysign(1.0, m) >= abs(m) - 0.01: + shift, turning = None, False + else: + cmd = (math.copysign(min(SHIFT_MS, abs(v) + ACCEL_MS2 * TICK_S), m), 0.0) + spot = not shift and cmd[0] == 0.0 and cmd[1] != 0.0 # a turn on the spot (the person aside or behind) + if not spot and not shift and not turning: + shifted = False if spot and not turning: hit = fetch.turn_hits(a - turned) # the arm's whole sweep toward them (it is turned already) other = a - math.copysign(360.0, a) # the other way round (right behind: about as far) @@ -448,15 +536,19 @@ def _run(see, say, people): elif hit is not None: fetch.log(f"follow: turning {a:+.0f} deg my arm would hit something at " f"({hit[0]:.2f}, {hit[1]:.2f})") - fetch._say(say, "My arm can't turn here, something is in its way.", - "팔이 부딪힐 수 있어서 돌 수 없어요.") - return + m = None if shifted else _room_to_turn(pose, person.at(now), turned, pts) + if m is None: + fetch._say(say, "My arm can't turn here, something is in its way.", + "팔이 부딪힐 수 있어서 돌 수 없어요.") + return + fetch.log(f"follow: no turn either way here; driving {m:+.2f} m to turn from there") + shift, shifted, spot = (pose, m), True, False + cmd = (0.0, 0.0) turning = spot if side and abs(a) < TURN_ONLY_DEG: side = 0.0 # ahead again: angles go on from the head's target # stopped by something: on again only when the speed it was stopped at is clear (no creeping up to it) - pts = [fetch._rot(turned) @ p for p in arm_pts] # the arm turned with the waist - why = cmd != (0.0, 0.0) and blocked(max(cmd[0], hold_v) if cmd[0] else 0.0, cmd[1], pts, pose) + why = cmd != (0.0, 0.0) and blocked(max(cmd[0], hold_v) if cmd[0] > 0 else cmd[0], cmd[1], pts, pose) if why: if blocked_t is None: fetch.log(f"follow: standing, {why}") diff --git a/tests/parity_check.py b/tests/parity_check.py index 5bc78e6..4a695ab 100644 --- a/tests/parity_check.py +++ b/tests/parity_check.py @@ -41,7 +41,7 @@ ARM = re.compile(r"^(?:wave|reach|hand|arm|give|take|put|waist)") # intents of # ---------- fakes: nothing moves, nothing is written ---------- HAND = {"held": False} -fetch.check_hand = lambda: HAND["held"] +fetch.check_hand = fetch.look_at_hand = lambda: HAND["held"] fetch.held_name = lambda lang="en": "the cup" if lang == "en" else "컵" fetch.state = lambda: {"holding": HAND["held"]} fetch.log = lumi.log = lambda *a, **k: None diff --git a/tests/test_chain.py b/tests/test_chain.py index f86e9c1..91366af 100644 --- a/tests/test_chain.py +++ b/tests/test_chain.py @@ -50,7 +50,7 @@ fake = types.SimpleNamespace( quick_command=lambda w, rule=None: done.append(("quick", w)), answer=lambda w, part=False: done.append(("talk", w)), fetch_say=lambda en, ko: said.append(en), chain_wait=lambda: None, base_off=lambda *a, **k: False, stay=lambda: None) -fetch.check_hand = lambda: False +fetch.check_hand = fetch.look_at_hand = lambda: False runs = [] fetch.run_steps = lambda s, say=None, sender=None: runs.append(s) fetch.state = lambda: {"status": "failed" if runs and runs[-1][0].get("to") == "p5" else "done"} diff --git a/tests/test_come_give.py b/tests/test_come_give.py index e83e0c6..0f0d721 100644 --- a/tests/test_come_give.py +++ b/tests/test_come_give.py @@ -74,7 +74,7 @@ def come_to(track, say=False): L.come_to = come_to L.end_run = lambda text: events.append("end run") hand = {"held": True} -L.held_now = lambda: hand["held"] +L.held_now = lambda look=False: hand["held"] # the hand-over by voice goes to the person who asked: far -> comes to them first, near -> at once for text in ["Give me a cup.", "give it to me", "hand it over", "컵 줘", "이리 줘", "나한테 주세요"]: diff --git a/tests/test_command_box.py b/tests/test_command_box.py index dee6828..dcc0977 100644 --- a/tests/test_command_box.py +++ b/tests/test_command_box.py @@ -80,7 +80,7 @@ def hand(text): return rec("talk") -fetch.check_hand = lambda: False +fetch.check_hand = fetch.look_at_hand = lambda: False lumi.log = fetch.log = lambda *a: None lumi.mouth = types.SimpleNamespace(say=lambda *a, **k: None, lang_of=lambda t: "ko" if brain.HANGUL.search(t) else "en", recent_speech=lambda s=30.0: "") @@ -150,7 +150,7 @@ assert not bad # ---------- what the box plans: one short line per reading ---------- HELD = [False] -fetch.check_hand = lambda: HELD[0] +fetch.check_hand = fetch.look_at_hand = lambda: HELD[0] fetch.state = lambda: {"holding": HELD[0]} fetch.held_name = lambda lang="en": "the white cup" diff --git a/tests/test_detour.py b/tests/test_detour.py index f672668..972d3fe 100644 --- a/tests/test_detour.py +++ b/tests/test_detour.py @@ -110,6 +110,7 @@ for name in ("_drive_pose", "_waist_front", "head_ahead", "_lift_to", "_line_hol fetch.skills.moved = lambda: None fetch.gripper.state = lambda: {"holding": True} fetch._in_hand = lambda: False +fetch._to_check_pose = lambda: None # the hand check pose (a shut hand) is not this test's fetch._launch = lambda fn, *a: fn(*a) # in this thread: the test reads the end at once say = lambda en, ko=None: said.append(en) diff --git a/tests/test_fetch.py b/tests/test_fetch.py index 6cd049e..9d26b13 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -168,7 +168,8 @@ skills.home_joints = lambda: [0.0] * 6 up_rpy = list(skills.GRASP_RPY) tilt = {"rpy": up_rpy} skills._ask = lambda name, **a: {"errorCode": "0", "cartPosition": [0, 0, 0] + tilt["rpy"]} -fetch.gripper.state = lambda: {**hand, "ai": [3500 if hand["holding"] else 160], "di": [int(hand["holding"])]} +fetch.gripper.state = lambda: {**hand, "ai": [3500 if hand["holding"] else 4150 if hand["closed"] else 160], + "di": [int(hand["holding"])]} fetch.gripper.open_ = lambda: (calls.append(("open",)), hand.update(holding=False, closed=False), fetch.gripper.state())[-1] def in_room(obj): """A fake camera's object that stays put in the room: seen where it is from the base pose now (the CALIB_FILE yaw @@ -479,15 +480,16 @@ except fetch.FetchError: pass fetch._set(holding=False, status="idle") hand.update(holding=False, closed=False) -# the camera sees an empty hand while AI_1 still says holding (the fingers shut on nothing): believed, fetch starts +# the state says holding, the fingers shut on nothing (no close on a thing seen, tasks/fetch.close_hand): fetch starts reset() fetch._set(holding=True, status="holding") -hand.update(holding=True, closed=True) +hand.update(holding=False, closed=True) eye["hand"] = "empty" st = run(fetch.start, {**ok, "source": "here", "dest": "here"}) assert st["status"] == "holding" and ("open",) in calls, st["log"] # started, and opened the hand first # ... and place / give with an empty hand are refused, the state forgets it fetch._set(holding=True, status="holding") +hand.update(holding=False, closed=True) for fn in (fetch.place, fetch.give): try: fn() diff --git a/tests/test_fetch_place.py b/tests/test_fetch_place.py index 1b6c013..411e07a 100644 --- a/tests/test_fetch_place.py +++ b/tests/test_fetch_place.py @@ -36,7 +36,7 @@ assert brain.held_command("bring it to p5 and put it on the white chair") == "pl from api import server server.agv.markers = lambda: ["p1", "p8", "home"] for holding in (True, False): - fetch.check_hand = lambda: holding + fetch.check_hand = fetch.look_at_hand = lambda: holding fetch._state.update(holding=holding, held_object={"object": "cup", "colour": "white"} if holding else None) for text, said in (("put it on the grey table", "Put the white cup on the grey table."), ("put on the gray table", "Put the white cup on the grey table."), @@ -242,7 +242,7 @@ assert got["colour"] == "white" and said[-1] == "I couldn't see a blue cup, so I fetch._look_around, fetch._look_at, fetch._fitted, fetch._go_to = real_around, real_look_at, real_fitted, real_go_to # ---------- the dialog's sentence says what was understood ---------- -fetch.check_hand = lambda: True +fetch.check_hand = fetch.look_at_hand = lambda: True fetch._state.update(holding=True, held_object={"object": "cup", "colour": "grey"}) for text, said in (("put the cup on the white dinning table or chair", "Put the grey cup on the white dining table or chair."), ("put it on the white tabel", "Put the grey cup on the white table."), @@ -253,7 +253,7 @@ for text, said in (("put the cup on the white dinning table or chair", "Put the fetch._state.update(holding=False, held_object=None) # ---------- "take the smaller cup": typed, the sentence says it, the task carries it; fetch takes the smaller one ---- -fetch.check_hand = lambda: False +fetch.check_hand = fetch.look_at_hand = lambda: False for text, said, prefer in (("take the smaller cup to p1", "Take the smaller cup from here, bring it to p1 and hold it.", "small"), ("bring me the cup on the left", "Take the cup on the left from here, bring it here and " diff --git a/tests/test_follow.py b/tests/test_follow.py index 95f8086..4c96fc5 100644 --- a/tests/test_follow.py +++ b/tests/test_follow.py @@ -28,6 +28,7 @@ def forbid(*a, **k): fetch.motion.go = fetch.skills._ask = motion._ready = forbid +follow.torso_people = lambda: [] # never the real camera service's file (World.torso_view below) fetch._charging = lambda: False fetch._at_pose = lambda name: True # the arm is in look already fetch._pose = lambda name, speed=None: None @@ -50,7 +51,7 @@ class Body: def call(self, path, body=None, timeout=2): if path == "status": - return [{"enable": True, "pos": p} for p in self.pos] + return [{"enable": True, "pos": p, "vel": 0.0} for p in self.pos] # still (robot/head.py waits on vel) if path != "moveto": forbid() with self.lock: @@ -132,6 +133,12 @@ class World: look = None + def torso_view(self): + """follow.torso_people: the torso camera turns with the waist, sees +-HALF_FOV of its front.""" + d, a = self.sight(self.person_at()) + a -= body.pos[1] + return [(d, a, 0.0, None)] if abs(a) <= HALF_FOV else [] + def sight(self, p): """(distance, angle deg + left) of the map point p from the base now.""" x, y, th = self.pose() @@ -526,7 +533,8 @@ def person_deg(w): def watch(w, secs): - """[(t, waist, head yaw, base deg, gaze off the person deg)] every 20 ms; the angle of every forward command.""" + """[(t, waist, head yaw, base deg, gaze off the person deg, s since follow last had a sighting of them)] every + 20 ms; the angle of every forward command.""" samples, ahead, request = [], [], w.request def req(cmd): @@ -540,7 +548,9 @@ def watch(w, secs): while time.time() < t0 + secs: _, waist, yaw, _ = body.pos b = person_deg(w) - samples.append((time.time() - t0, waist, yaw, math.degrees(w.th), (b - waist - yaw + 180.0) % 360.0 - 180.0)) + seen = follow._followed[0] + samples.append((time.time() - t0, waist, yaw, math.degrees(w.th), (b - waist - yaw + 180.0) % 360.0 - 180.0, + time.time() - seen[1] if seen else 0.0)) time.sleep(0.02) return samples, ahead @@ -555,7 +565,8 @@ assert wait_end(0.5) moves = [m for m in body.moves if m[1] == "follow head"] first = moves[0] assert first[3] == 0.0 and first[4] > 90.0 and abs(first[4] - 170.0) < 10.0, first # the head alone on them -assert max(abs(s[4]) for s in samples[5:]) < 15.0, max(abs(s[4]) for s in samples[5:]) # gaze on them +late = [s for s in samples if s[0] > 0.1 + head.STILL_S] # the first move (head.moveto waits +assert max(abs(s[4]) for s in late) < 15.0, max(late, key=lambda s: abs(s[4])) # STILL_S first): gaze on them assert all(m[3] == 0.0 for m in moves), moves # the waist stays assert w.cmds[0][2] > 0.0 and w.cmds[0][0] - w.t0 < 0.5, w.cmds[:2] # turning at once assert max(b[0] - a[0] for a, b in zip(w.cmds, w.cmds[1:])) < 0.2 # no tick waits @@ -598,12 +609,15 @@ print("stopped turned: waist back to the front") # the real one the head alone must stay on them: the gaze within 25 deg (the camera sees +-47), the waist never out. +HEAD_DEG_S = [70.0] # the fake head's speed (the real one ~40, audio/sing.py) + + def real_body(path, b=None, timeout=2): """The body API as slow as live: ~0.45 s a move + the travel (head ~70, waist ~15 deg/s), moving all along.""" if path != "moveto": return body.call(path, b, timeout) start, goal, t0 = list(body.pos), list(b["pos"]), time.time() - dur = 0.45 + max(abs(goal[2] - start[2]) / 70.0, abs(goal[1] - start[1]) / 15.0) + dur = 0.45 + max(abs(goal[2] - start[2]) / HEAD_DEG_S[0], abs(goal[1] - start[1]) / 15.0) while time.time() - t0 < dur: body.pos = [a + (g - a) * (time.time() - t0) / dur for a, g in zip(start, goal)] time.sleep(0.02) @@ -638,7 +652,7 @@ turn_hits = fetch.turn_hits for why in ("sweep", "not look"): body.moves.clear() if why == "sweep": - fetch.turn_hits = lambda d: (1.0, 1.0) if threading.current_thread().name == "follow head" else None + fetch.turn_hits = lambda d, pose=None: (1.0, 1.0) if threading.current_thread().name == "follow head" else None else: calls = iter([True]) # ready() sees it in look, then fetch._at_pose = lambda name: next(calls, False) # it is moved out (by hand) @@ -672,13 +686,13 @@ time.sleep(0.6) follow.stop() assert wait_end(0.5) yaws = [m[4] for m in body.moves if m[1] == "follow head"] -assert yaws and all(y > 0 for y in yaws[1:]), yaws +assert len(yaws) > 1 and all(y * yaws[1] > 0 for y in yaws[1:]), yaws # which side depends on the first sighting print("right behind: one side") # right behind beside a wall (live 2026-10-30): the arm blocked turning left, the base turns right round to them # (head ahead, out of view a while), never back the blocked way; blocked both ways: it stops and says so blocked_dir = [1.0] -fetch.turn_hits = lambda d: (-5.08, 11.54) if d * blocked_dir[0] > 0 or not blocked_dir[0] else None +fetch.turn_hits = lambda d, pose=None: (-5.08, 11.54) if d * blocked_dir[0] > 0 or not blocked_dir[0] else None said.clear() body.pos = [50.0, 0.0, 180.0, follow.HEAD_PITCH] # "look at the back side": the head right behind head._call = real_body @@ -702,9 +716,75 @@ w = World(person=(1.3 * math.cos(math.radians(186.0)), 1.3 * math.sin(math.radia follow.start(w.see, say) assert wait_end(3.0) and any("can't turn" in x for x in said), said assert all(c[2] == 0.0 for c in w.cmds), w.cmds -fetch.turn_hits = turn_hits print("right behind, both ways blocked: stops, says so") +# the same turn round with a head as slow as the real one (~40 deg/s): it swings through the front to meet them at +# once, the torso camera watches meanwhile; the time without the head on them stays short, never lost +blocked_dir[0] = 1.0 +said.clear() +body.pos = [50.0, 0.0, 180.0, follow.HEAD_PITCH] +head._call, HEAD_DEG_S[0] = real_body, 40.0 +w = World(person=(1.3 * math.cos(math.radians(186.0)), 1.3 * math.sin(math.radians(186.0))), fov=True) +follow.torso_people = w.torso_view +samples, _ = watch(w, 8.0) +follow.stop() +assert wait_end(3.0) and not said, said +head._call, HEAD_DEG_S[0], follow.torso_people = body.call, 70.0, (lambda: []) +head_blind = sum(b[0] - a[0] for a, b in zip(samples, samples[1:]) if abs(a[4]) > HALF_FOV) +unseen = max(s[5] for s in samples) # longest without a sighting +assert head_blind < 4.0 and unseen < 2.5, (head_blind, unseen) +assert abs(samples[-1][4]) < 15.0, samples[-1] # on them at the end +print(f"turn round, real head speed: head off them {head_blind:.1f} s, without a sighting at most {unseen:.1f} s") +fetch.turn_hits = turn_hits + +# an ordinary turn (the person standing 120 deg to the left, the head on them, a head as slow as the real one): the +# base turns at up to joy_control's 1.0 rad/s but never faster than the head keeps them in its camera's view +said.clear() +body.pos = [50.0, 0.0, 120.0, follow.HEAD_PITCH] +head._call, HEAD_DEG_S[0] = real_body, 40.0 +w = at(120.0) +w.fov = True +samples, _ = watch(w, 7.0) +follow.stop() +assert wait_end(3.0) and not said, said +head._call, HEAD_DEG_S[0] = body.call, 70.0 +off = max(abs(s[4]) for s in samples) +top = max(abs(c[2]) for c in w.cmds) +assert follow.TURN_MAX_RS == 1.0 and top > 0.6, top # faster than before (0.6) +assert off < HALF_FOV - 7.0, max(samples, key=lambda s: abs(s[4])) # in view all along (their width) +assert abs(math.degrees(w.th) - 120.0) < 10.0, math.degrees(w.th) +print(f"ordinary turn, real head speed: top {top:.2f} rad/s, gaze off at most {off:.0f} deg") + +# beside the charger wall (live 2026-10-30), both ways blocked on the spot: the finger tips would sweep into two +# corners 0.64 m out. Room behind: it backs up a little (the way checked), turns from there and follows; no room +# (a wall 0.35 m behind too): it says it can't turn and never drives +CORNERS = [(0.5, 0.4), (0.5, -0.4)] +said.clear() +body.pos = [50.0, 0.0, 180.0, follow.HEAD_PITCH] +P186 = (2.0 * math.cos(math.radians(186.0)), 2.0 * math.sin(math.radians(186.0))) +w = World(person=P186, obstacles=CORNERS, fov=True) +assert fetch.turn_hits(186.0) is not None and fetch.turn_hits(-174.0) is not None # blocked both ways here +follow.start(w.see, say) +t = time.time() +while time.time() - t < 15.0 and not (abs(w.sight(w.person_at())[1]) < follow.TURN_DEAD_DEG + 1.0 and w.cmds + and w.cmds[-1][2] == 0.0): + time.sleep(0.05) +follow.stop() +assert wait_end(3.0) and not said, said +backed = -sum(c[1] * min(n[0] - c[0], 0.5) for c, n in zip(w.cmds, w.cmds[1:]) if c[1] < 0.0) +assert 0.05 < backed < follow.SHIFT_MAX_M + 0.05, backed # backed up a little, straight +assert abs(w.sight(w.person_at())[1]) < follow.TURN_DEAD_DEG + 1.0, w.sight(w.person_at()) +assert not any(c[1] < 0.0 and c[2] != 0.0 for c in w.cmds), "backed and turned at once" +print(f"both ways blocked, room behind: backed {backed:.2f} m, turned {math.degrees(w.th):.0f} deg to them") +said.clear() +body.pos = [50.0, 0.0, 180.0, follow.HEAD_PITCH] +WALL = [(-0.35, 0.05 * k) for k in range(-10, 11)] +w = World(person=P186, obstacles=CORNERS + WALL, fov=True) +follow.start(w.see, say) +assert wait_end(3.0) and any("can't turn" in x for x in said), said +assert all(c[1:] == (0.0, 0.0) for c in w.cmds), w.cmds +print("both ways blocked, no room: says so, never drives") + # lumi: act("stop") ends following; follow_me locks onto the person talking, refuses when it must lumi.agv.cancel = lumi.skills.cancel = lumi.motion.stop = lambda: None w = World(person=(3.0, 0.0)) diff --git a/tests/test_hand_check.py b/tests/test_hand_check.py new file mode 100644 index 0000000..3d05b42 --- /dev/null +++ b/tests/test_hand_check.py @@ -0,0 +1,103 @@ +"""A fully shut hand is looked at before it is called empty. Live 2026-10-30 18:26-18:30: "give me your hand", "open +your hand", the owner put a cup between the fingers, "close your hand" (AI_1 4143: the cup narrower than the belly's +closed gap, AI_1 read as on nothing), then "put the cup on the table" and "you are holding the cup" were answered +"my hand is empty". Replayed with fakes: the close counts the cup the camera saw between the open fingers, an order +that needs the hand takes a shut hand to carry and lets the torso camera decide, and a close on nothing (or the +person's hand seen after the close, 2026-10-23) stays empty. No robot. + + .venv/bin/python tests/test_hand_check.py +""" +import tempfile +import time +import types +from pathlib import Path + +import no_robot # noqa: F401 any connection to the robot fails the test +from assistant import lumi +from tasks import fetch + +fetch.STATE_FILE = Path(tempfile.mkdtemp()) / "lumi_task.json" +OPEN = {"ai": [160.0, 489.0], "closed": False, "holding": False} +SHUT = {"ai": [4143.0, 489.0], "closed": True, "holding": False} # the live close of 18:27:03 +grip, eye, arm, moves, put = dict(OPEN), {"sees": "object"}, {"pose": "give"}, [], [] +fetch.gripper.state = lambda: dict(grip) +fetch.gripper.close = lambda: grip.update(SHUT) or dict(grip) +fetch.skills.hand_sees = lambda: eye["sees"] +fetch.motion.poses = lambda: {"look": [0] * 6, "carry": [1] * 6, "give": [2] * 6} +fetch._at_pose = lambda name: arm["pose"] == name +fetch.arm_route.goto = lambda target, holding=False, **kw: moves.append((target, holding)) or arm.update(pose=target) +fetch._scene = lambda fn, *a: None # the owner's hand was gone: no name for it +fetch._put_down = lambda say, on=None: put.append(on) +fetch._lift_to = fetch.head_ahead = lambda *a, **k: None +L = lumi.Lumi.__new__(lumi.Lumi) +L.fetch_status = lambda: fetch.state().get("status") +B = types.SimpleNamespace(history=[]) + + +def reset(sees, pose="give"): + fetch._set(status="idle", step="", holding=False) + fetch.skills._held.clear() + fetch._last_held.clear() + grip.clear(), grip.update(OPEN) + eye["sees"], arm["pose"] = sees, pose + moves.clear(), put.clear() + + +def routed(text): + return lumi.route(text, ["home", "p1"], B, lambda: L.held_now(look=True)) + + +# ---------- the cup put between the open fingers, then "close your hand" ---------- +reset("object") +assert L.arm_pose("close") # the camera saw it between the open fingers +assert fetch.state()["holding"] and fetch.held_name() == "something", fetch.state() +assert fetch.check_hand() and not moves # "go to look position": still held, nothing moved +arm["pose"] = "look" +assert fetch.check_hand() and fetch.state()["holding"] +kind, data = routed("Put the cup on the table.") # an order that needs the hand: looked at from carry +assert kind == "hand" and data[0][0] == "place" and data[1] is True, (kind, data) +assert moves == [("carry", True)], moves # slowly, as with a cup in the hand +fetch.place() +fetch._thread.join(2) +assert put == [{"name": "dining table", "colour": None}] or put == [None], put # it went on to put it down +for t in ["You are holding the cup.", "You are holding cup.", "Look at your hand. You have a cup.", "손에 컵 있잖아"]: + assert lumi.HAND_FULL_SAID.search(t), t +for t in ["are you holding anything?", "you are holding me back", "give me your hand", "what's in your hand"]: + assert not lumi.HAND_FULL_SAID.search(t), t + +# ---------- the cup taken out of the shut hand: the camera at carry sees it empty ---------- +eye["sees"] = "empty" +assert not fetch.look_at_hand() and not fetch.state()["holding"] + +# ---------- "close your hand" on nothing: empty; told "you are holding a cup": looked at, still empty ---------- +reset("empty") +assert L.arm_pose("close") and not fetch.state()["holding"] +assert not fetch.check_hand() and not moves +assert routed("Put the cup on the table.")[0] != "hand" and moves == [("carry", True)] # looked at, then empty +try: + fetch.place() + raise AssertionError("put down with an empty hand") +except fetch.FetchError as e: + assert "empty" in e.args[0], e.args +assert not L.held_now(look=True) + +# ---------- shut, the state forgot it, the person insists: the camera at carry finds it ---------- +reset("object", pose="look") +grip.update(SHUT) +assert not fetch.check_hand() and not moves # from look nothing is seen there: shut = empty +assert L.held_now(look=True) and moves == [("carry", True)] and fetch.state()["holding"] +arm["pose"] = "look" # still held away from carry (the next words' check) +assert fetch.check_hand() and fetch.state()["holding"] + +# ---------- 2026-10-23: closed on nothing, the person's hand by the held-out fingers after the close ---------- +reset("unknown") +L.arm_pose("close") +eye["sees"] = "object" +fetch._set(holding=True, status="holding") # a stale "holding" (no close on a seen thing) +assert not fetch.check_hand() and not fetch.state()["holding"] + +# ---------- AI_1 stopped on something: held, whatever the camera says ---------- +reset("empty") +grip.update(ai=[3500.0, 489.0], closed=True, holding=True) +assert fetch.check_hand() and not moves +print("hand check ok (narrow cup closed on, looked at from carry, closed on nothing, the 2026-10-23 case)") diff --git a/tests/test_mission_name.py b/tests/test_mission_name.py index 40be847..b0f239b 100644 --- a/tests/test_mission_name.py +++ b/tests/test_mission_name.py @@ -38,7 +38,7 @@ fetch.end = lambda timeout=5.0: (done.append("end"), run.update(status="stopped" fetch.replace = lambda steps, say=None: done.append(("replace", steps)) fetch.proceed = lambda: done.append("proceed") fetch.run_steps = lambda steps, say=None, sender=None: done.append(("run", steps)) -fetch.check_hand = lambda: run["holding"] +fetch.check_hand = fetch.look_at_hand = lambda: run["holding"] fetch.held_name = lambda lang="en": "the cup" if lang == "en" else "컵" lumi.agv.cancel = lambda: done.append("agv cancel") lumi.mouth.say = lambda text, **k: done.append(("say", text)) diff --git a/tests/test_mission_route.py b/tests/test_mission_route.py index 82c08dc..2da5739 100644 --- a/tests/test_mission_route.py +++ b/tests/test_mission_route.py @@ -64,7 +64,7 @@ L.keep_listening = lambda: None L.fetch_say = lambda en, ko=None: said.append(en) L.fetch_status = lambda: None L.modes = types.SimpleNamespace(greeter=True, patrol=False, drive=True, wave=True) -fetch.check_hand = lambda: False +fetch.check_hand = fetch.look_at_hand = lambda: False lumi.fetch_dialog = types.SimpleNamespace(run_steps=lambda s, hear, say, describe, start: started.append(s) or "started") for text in ("take the cup, go to booth two, give it to James and come back", "스테이지 갔다 와", "go to the stage, wait 10 seconds, then come back"): diff --git a/tests/test_quick_answers.py b/tests/test_quick_answers.py index 2a89bed..cfe4bb1 100644 --- a/tests/test_quick_answers.py +++ b/tests/test_quick_answers.py @@ -91,7 +91,7 @@ def through_answer(): mouth.say = lambda text, lang=None, abort=None: said.append(text) lumi.ears.understood = lambda *a: True lumi.ears.last_stt = {"language": "english", "logprob": -0.1} - fetch.check_hand = lambda: False + fetch.check_hand = fetch.look_at_hand = lambda: False L = lumi.Lumi.__new__(lumi.Lumi) L.lang, L.current, L.closing_pending, L.markers = "en", None, None, ["home", "stage"] diff --git a/tests/test_reach_live.py b/tests/test_reach_live.py index 8770777..2c4bcc4 100644 --- a/tests/test_reach_live.py +++ b/tests/test_reach_live.py @@ -102,6 +102,13 @@ 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 assert L.reach_done() and folds == ["fold"] +status["now"] = "running" # still on its way after REACH_HOLD_S: no timeout +L.reached_at, folds[:] = time.time() - lumi.REACH_HOLD_S - 1, [] +assert not L.reach_done() and not folds +status["now"] = "done" # the hand got there only now: the hold counts +fetch.state = lambda: {"step": "", "since": time.time()} # from then, not from the order +assert not L.reach_done() and not folds +fetch.state = lambda: {"step": "reaching out"} 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) diff --git a/tests/test_task_switches.py b/tests/test_task_switches.py index c7b6555..24911c9 100644 --- a/tests/test_task_switches.py +++ b/tests/test_task_switches.py @@ -23,7 +23,7 @@ server.MODES_FILE = tmp / "lumi_modes.json" # never the real /dev/shm f fetch.STATE_FILE = tmp / "lumi_task.json" server.agv.request = server.agv.cancel = server.skills.cancel = server.arm.cmd = forbid server.agv.markers = lambda: M -fetch.check_hand = lambda: False +fetch.check_hand = fetch.look_at_hand = lambda: False fetch.log = lambda *a: None done = [] server.send_to_assistant = lambda cmd, **a: done.append(cmd)