diff --git a/api/dashboard.html b/api/dashboard.html index 88a6a6b..e65edab 100644 --- a/api/dashboard.html +++ b/api/dashboard.html @@ -253,8 +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
-
-
+
@@ -760,7 +759,7 @@ let modes = {}; function paintModes(m) { modes = m; $("modeGreeter").classList.toggle("on", !!m.greeter); $("modePatrol").classList.toggle("on", !!m.patrol); - $("useArm").checked = m.wave !== false; $("useDrive").checked = m.drive !== false; + $("useArm").checked = m.wave !== false; const on = [m.greeter && "greeter", m.patrol && "patrol"].filter(Boolean); $("asTag").textContent = on.length ? (m.running ? "● " : "starting… ") + on.join(" + ") : "off"; $("asTag").className = "tag " + (on.length && m.running ? "live" : ""); @@ -776,7 +775,6 @@ document.querySelectorAll(".mode").forEach(el => el.onclick = () => { setModes({[k]: on}, el); }); $("useArm").onchange = e => setModes({wave: e.target.checked}); -$("useDrive").onchange = e => setModes({drive: e.target.checked}); api("/assistant/modes").then(paintModes); setInterval(() => api("/assistant/modes").then(paintModes).catch(() => {}), 3000); $("stopAll").onclick = e => { holdStop(); act(e.target, () => api("/stop", {})); }; @@ -854,7 +852,7 @@ async function refreshLog() { const state = !st.running ? 'not running' : st.stuck ? 'STUCK' : st.log_age_s > 90 ? 'quiet (no log for ' + Math.round(st.log_age_s) + ' s)' : 'running'; $("stat").innerHTML = `Assistant
${state}${st.pids.length ? " · pid " + st.pids.join(", ") : ""}
- Modes
greeter ${st.modes.greeter ? "on" : "off"} · patrol ${st.modes.patrol ? "on" : "off"} · wave ${st.modes.wave ? "on" : "off"} · come ${st.modes.drive ? "on" : "off"}
+ Modes
greeter ${st.modes.greeter ? "on" : "off"} · patrol ${st.modes.patrol ? "on" : "off"} · wave ${st.modes.wave ? "on" : "off"}
Uptime
${up}
Cameras
${st.camera_service ? cams : 'camera service not running'}
${task ? `Task
${esc(task.status)}${task.step ? " · " + esc(task.step) : ""}${task.holding ? " · holding" : ""}
` : ""} Last line
${esc((robot ? lg.lines.slice(-1)[0] : st.last_line) || "–")}
`; diff --git a/api/server.py b/api/server.py index 8eb87fe..8370fd3 100644 --- a/api/server.py +++ b/api/server.py @@ -69,12 +69,13 @@ 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, "drive": True} +DEFAULT_MODES = {"greeter": False, "patrol": False, "wave": True} def read_modes(): try: - return {**DEFAULT_MODES, **json.loads(MODES_FILE.read_text())} + d = json.loads(MODES_FILE.read_text()) + return {k: d.get(k, v) for k, v in DEFAULT_MODES.items()} # keys no longer used (e.g. "drive") are dropped except (FileNotFoundError, ValueError): return dict(DEFAULT_MODES) @@ -86,10 +87,10 @@ def send_to_assistant(cmd, **args): os.replace(tmp, CMD_FILE) -def start_assistant(no_arm=False, no_drive=False): +def start_assistant(no_arm=False): if assistant_pids(): return None - args = [str(VENV_PY), str(ROOT / "assistant" / "lumi.py")] + ["--no-arm"] * no_arm + ["--no-drive"] * no_drive + args = [str(VENV_PY), str(ROOT / "assistant" / "lumi.py")] + ["--no-arm"] * no_arm log = open(CONSOLE_LOG, "a") log.write(f"\n===== {time.strftime('%Y-%m-%d %H:%M:%S')} start: {' '.join(args[1:])}\n") log.flush() @@ -214,7 +215,6 @@ class StartBody(BaseModel): once: bool = Field(True, description="drive the route once (true) or loop it forever (false)") pause: float = Field(1.0, ge=0, le=60, description="seconds to wait at each marker") no_arm: bool = False - no_drive: bool = False # ---------- status ---------- @@ -420,7 +420,7 @@ def assistant_start(body: StartBody): if unknown: raise HTTPException(400, f"unknown markers {unknown}; markers: {names}") args += ["--patrol", body.patrol, "--pause", str(body.pause)] + ["--once"] * body.once - args += ["--no-arm"] * body.no_arm + ["--no-drive"] * body.no_drive + args += ["--no-arm"] * body.no_arm log = open(CONSOLE_LOG, "a") log.write(f"\n===== {time.strftime('%Y-%m-%d %H:%M:%S')} start: {' '.join(args[1:])}\n") log.flush() @@ -1390,10 +1390,9 @@ 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") - drive: bool | None = Field(None, description='allow "come here" and voice "go to"') -@app.get("/assistant/modes", tags=["assistant"], summary="Greeter / patrol / wave / drive switches") +@app.get("/assistant/modes", tags=["assistant"], summary="Greeter / patrol / wave switches") def modes_get(): return {**read_modes(), "running": bool(assistant_pids())} diff --git a/assistant/lumi.py b/assistant/lumi.py index e4ab96b..ccea85c 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -2,7 +2,7 @@ python assistant/lumi.py # full: camera, greetings, conversation, commands python assistant/lumi.py --no-camera # no camera: press Enter to start a conversation (desk testing) - python assistant/lumi.py --no-arm --no-drive # no waving, no base driving + python assistant/lumi.py --no-arm # no waving python assistant/lumi.py --patrol a,b # walk between markers in a loop; stop for people in the way, talk, go on python assistant/lumi.py --patrol p1,p2,final,p10,home --once --pause 0.5 # drive the route once, end at the dock @@ -415,7 +415,7 @@ HAND_EMPTY_SAID = re.compile( # the person says Lumi's hand is empty: checked r"\byou(?:'re| are) not holding (?:anything|something)\b|\byou have nothing in (?:your|ur) hand\b|" r"손에 ?(?:아무것도|아무 ?것도|뭐 ?없|없)|손 ?비었|빈 ?손이", 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", "drive"} +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 # | fetch | fetch_give | fetch_place | fetch_stop | fetch_carry | fetch_release | fetch_steps # | fetch_pause | fetch_resume} @@ -878,7 +878,7 @@ class Modes: def __init__(self, args): self.greeter, self.patrol = True, bool(args.patrol) - self.wave, self.drive = not args.no_arm, not args.no_drive + self.wave = not args.no_arm self._read, self._mtime = 0.0, None self.refresh(force=True) @@ -892,7 +892,7 @@ class Modes: if m != self._mtime: self._mtime = m d = json.load(open(MODES_FILE)) - changed = {k: d[k] for k in ("greeter", "patrol", "wave", "drive") if k in d and d[k] != getattr(self, k)} + changed = {k: d[k] for k in ("greeter", "patrol", "wave") if k in d and d[k] != getattr(self, k)} for k, v in changed.items(): setattr(self, k, bool(v)) if changed and not force: @@ -1017,7 +1017,8 @@ class Lumi: def wave(self, ok=None, quiet=False): """Wave because someone asked or said "bye bye" in view (never on a greeting): manipulation/wave.py checks the arm, the hand, the start pose and the whole path first; a refusal is said unless `quiet`. Not while following, - on a mission or a task. `ok`: (English, Korean) said once the wave is checked. True if waved.""" + on a mission or a task. `ok`: (English, Korean) said once the wave is checked, while the arm already moves + (owner: no waiting for the words first). True if waved.""" from tasks import follow if not self.modes.wave: log(" waving is switched off (dashboard)") @@ -1032,7 +1033,8 @@ class Lumi: if self.vision: self.vision.arm_watch = True self.publish_busy("wave") - wave_mod.wave(on_start=(lambda: self.fetch_say(*ok)) if ok else None) + wave_mod.wave(on_start=(lambda: threading.Thread(target=self.fetch_say, args=ok, daemon=True).start()) + if ok else None) return True except wave_mod.WaveError as e: log(f" wave refused: {e.args[0]}") @@ -1101,15 +1103,11 @@ class Lumi: safe(skills.cancel) safe(motion.stop) # also a wave's waiting move elif action == "go_to": - if self.modes.drive: - self.start_trip(target) - else: - log(" driving by voice is switched off (dashboard: Come when called)") + self.start_trip(target) elif action in ("move", "turn"): self.move_by(action, target) elif action == "come_back": - if self.modes.drive: - self.come_back() + self.come_back() elif action == "detour": # the model read it from now_doing's block if target in detour.SAY: self.detour(target, speak=False) @@ -1191,7 +1189,7 @@ class Lumi: waist turns in place toward it (the base stays; fetch._waist_to checks the arm's sweep). Returns the voice's waist-frame angle after the turn (unchanged when nothing could turn).""" from tasks import fetch - if self.modes.drive and self.modes.patrol: + if self.modes.patrol: self.look_toward(angle) return 0.0 w = waist_turned() @@ -1270,9 +1268,6 @@ class Lumi: Left / right are a normal base move to a map point, so obstacles are avoided; forward and back are a straight drive of exactly that length (fetch._move). Returns False if not possible (an amount not read or past the limit is never driven: driving.read has asked / refused it).""" - if not self.modes.drive: - log(" driving by voice is switched off (dashboard: Come when called)") - return False parts = (target or "").split() direction = parts[0] if parts else "forward" try: @@ -1337,23 +1332,17 @@ class Lumi: if self.base_off("move"): return True log(f" action move {got[1]} (again)") - if not self.modes.drive: - say = "Sorry, driving is switched off." if lang == "en" else "죄송해요, 지금은 이동할 수 없어요." - elif not self.move_by("move", got[1]): + if not self.move_by("move", got[1]): return True - else: - say = driving.say_move(d, float(n), got[2], lang) + say = driving.say_move(d, float(n), got[2], lang) elif got[0] == "turn": # "again" / "a bit more" after a turn hist.append((text, f"ACTION: turn {got[1]}")) if self.base_off("turn"): return True log(f" action turn {got[1]} (again)") - if not self.modes.drive: - say = "Sorry, driving is switched off." if lang == "en" else "죄송해요, 지금은 이동할 수 없어요." - elif not self.move_by("turn", got[1]): + if not self.move_by("turn", got[1]): return True - else: - say = "Okay." if lang == "en" else "네." + say = "Okay." if lang == "en" else "네." elif got[0] in ("look", "lift"): # "one more" / "더" after a look or a lift: further that way hist.append((text, f"ACTION: {got[0]} {got[1]}")) log(f" action {got[0]} {got[1]} (again)") @@ -1435,9 +1424,6 @@ class Lumi: def fetch_request(self, text): """A fetch said by voice: parse strictly, ask what is missing, read back, start on yes or silence.""" - if not self.modes.drive: - self.fetch_say("Sorry, driving is switched off.", "죄송해요, 지금은 이동할 수 없어요.") - return status = self.fetch_status() if status == "holding": from tasks import fetch @@ -1888,10 +1874,8 @@ class Lumi: elif kind == "quick": self.quick_command(words, what) # chain.plan's reading ("나 보고", the bank's) else: - if {st["do"] for st in what} & DRIVE_STEPS and (self.base_off("go_to") or not self.modes.drive): + if {st["do"] for st in what} & DRIVE_STEPS and self.base_off("go_to"): failed = True - if self.modes.patrol: - self.fetch_say("Sorry, driving is switched off.", "죄송해요, 지금은 이동할 수 없어요.") continue problems = steps.check(what, fetch.check_hand(), self.markers) if problems: @@ -1947,9 +1931,6 @@ class Lumi: log(f" mission ({by}): {got}") if {st["do"] for st in got} & DRIVE_STEPS and self.base_off("go_to"): return True - if not self.modes.drive: - self.fetch_say("Sorry, driving is switched off.", "죄송해요, 지금은 이동할 수 없어요.") - return True self.end_run(text) from tasks import fetch problems = steps.check(got, fetch.check_hand(), self.markers) @@ -2198,7 +2179,7 @@ class Lumi: if track is None and self.vision.anyone(): # several seen, nobody raised a hand: raised_hand said so return None if track is not None and track.distance > REACH_COME_M: # far: go to them first, never reach from afar - if not self.modes.drive: + if not self.modes.patrol: # Greeter only: the base stays self.fetch_say(*COME_CLOSER_SAY) return None log(f" reach: person #{track.id} {track.distance:.2f} m away: coming closer first") @@ -2662,10 +2643,6 @@ class Lumi: return False if self.base_off("go_to"): return True - en = self.lang == "en" - if not self.modes.drive: - mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.") - return True if how == "back": if not stuck.get("start"): self.fetch_say(*detour.NO_START) @@ -2873,9 +2850,6 @@ class Lumi: self.brain.history.append((self.heard, f"ACTION: go_to {place}")) if self.base_off("go_to"): return - if not self.modes.drive: - mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.") - return self.start_trip(place) name = brain_mod.place_said(place) mouth.say(f"Okay, I'm going to {name}." if en else f"네, {name}로 갈게요.") @@ -2939,9 +2913,6 @@ class Lumi: limited = self.waist(target) mouth.say(LIMIT_SAY[limited][0 if en else 1] if limited else ("Okay." if en else "네.")) return True - if not self.modes.drive: - mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.") - return True if action == "come_back": self.come_back(speak=True) return True @@ -2966,9 +2937,13 @@ class Lumi: return True if action == "arm": done = {"open": ("Okay, opening my hand.", "네, 손을 펼게요."), "close": ("Okay, closing my hand.", "네, 손을 쥘게요.")} - if target in done: - mouth.say(done[target][0] if en else done[target][1]) + words = None + if target in done: # said while the gripper already moves + words = threading.Thread(target=mouth.say, args=(done[target][0] if en else done[target][1],), daemon=True) + words.start() ok = self.arm_pose(target) + if words: + words.join() if ok: if target in ("fold", "carry", "ready"): mouth.say("Okay." if en else "네.") @@ -3354,7 +3329,7 @@ class Lumi: if t is not None: return t view = CAMERA_HALF_FOV + (head.YAW_LIMIT if self.vision.camera == "head" else 0.0) - w = waist_turned() if abs(robot_angle) > view and self.modes.drive and self.modes.patrol else None + w = waist_turned() if abs(robot_angle) > view and self.modes.patrol else None if w is not None and waist_home("turning to a caller", fold=True): log(f" caller outside the camera ({robot_angle:+.0f} deg): turning toward the voice") self.turn_head(0, force=True) # a call or an order: also over a held look @@ -3388,7 +3363,7 @@ class Lumi: """Turn the head toward a waist-frame angle; turn the base too if it is outside the head's range.""" if abs(robot_angle) <= head.YAW_LIMIT: self.turn_head(HEAD_SIGN * robot_angle) - elif self.modes.drive and self.modes.patrol: + elif self.modes.patrol: w = waist_turned() if not waist_home("turning to a voice", fold=True): return @@ -3404,9 +3379,6 @@ class Lumi: def come_to(self, track, say=False): """Drive to the person (a visible track) and stop about COME_STOP in front of them. `say`: "I'm coming" once the base has the goal, spoken while it drives (the motion never waits for the words).""" - if not self.modes.drive: - mouth.say("Sorry, driving is switched off.") - return if track is None or not self.vision or not self.vision.visible(track): track = self.speaker_track() # who said it: the voice, the talk, the look, a raised hand if track is None: @@ -3478,7 +3450,7 @@ class Lumi: if word is None or self.base_off("go_to", "pointed"): return word is not None en = self.lang == "en" - if not self.modes.drive or self.mission_running() or self.skill_busy(): + if self.mission_running() or self.skill_busy(): mouth.say("Sorry, I can't drive right now." if en else "죄송해요, 지금은 이동할 수 없어요.") return True spot = safe(pointing.target, default={"why": "no_depth"}) or {"why": "no_depth"} @@ -3524,9 +3496,6 @@ class Lumi: and follow them in the background until a stop word, they are lost, or something is in the way.""" from tasks import follow en = self.lang == "en" - if not self.modes.drive: - mouth.say("Sorry, driving is switched off." if en else "죄송해요, 지금은 이동할 수 없어요.") - return self.end_run(getattr(self, "heard", "") or "follow me") if self.skill_busy(): self.fetch_say("Sorry, I'm on a task right now.", "죄송해요, 지금 다른 일을 하고 있어요.") @@ -4177,7 +4146,6 @@ if __name__ == "__main__": ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--no-camera", action="store_true") ap.add_argument("--no-arm", action="store_true") - ap.add_argument("--no-drive", action="store_true") # torso camera by default: the head camera shares a USB 2 hub with the speaker and drops out while Lumi talks ap.add_argument("--camera", default=None, choices=camview.CAMERAS, help="pin one camera (default: head standing, torso driving)") diff --git a/audio/mouth.py b/audio/mouth.py index 3f70af8..f6c6196 100644 --- a/audio/mouth.py +++ b/audio/mouth.py @@ -43,8 +43,7 @@ CACHED = ["Hi, I'm Lumi, the assistant robot. How can I help you?", "안녕하 "Let me check.", "확인해 볼게요.", "Okay, I'll be quiet.", "네, 조용히 할게요.", "Sorry, I'm not connected to the internet right now, so I can't look that up.", "Yes? How can I help?", "네? 무엇을 도와드릴까요?", - "Welcome back! How can I help you?", "다시 오셨네요, 무엇을 도와드릴까요?", "Okay, I'm going to my charging dock.", "네, 충전소로 갈게요.", - "Sorry, driving is switched off."] + [f"Okay, I'm going to p{i}." for i in range(1, 11)] + "Welcome back! How can I help you?", "다시 오셨네요, 무엇을 도와드릴까요?", "Okay, I'm going to my charging dock.", "네, 충전소로 갈게요."] + [f"Okay, I'm going to p{i}." for i in range(1, 11)] _tts = None _style = None diff --git a/docs/TUNING.md b/docs/TUNING.md index d5ac3ef..9d386ad 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -12,6 +12,7 @@ Every value here is a constant at the top of its file, with a comment on what it | `robot/motion.py` | `JOINT_ACCEL_FACTOR` | 1.5 | Joint moves: acceleration = speed × this per second (route 60 °/s², normal 37.5, slow 15). Lower = softer start and stop, longer moves. Estimate | | `manipulation/arm_route.py` | `SPEED` | "route" | Joint moves along the pose graph (to `look`, `carry`, `give`, `ready`, `wave_out`, `wave_start`, `wave`) with an empty hand; the wave's way up | | `manipulation/arm_route.py` | `HOLD_SPEED` | "slow" | The same with something in the hand | +| `manipulation/arm_route.py` | `GIVE_SPEED` | "slow" | The last move into `give`, from `give_pre` (only when `give_pre` is taught: every empty-hand way to `give` then ends `give_pre` → `give`) | | `manipulation/skills.py` | `EMPTY_SPEED` | "normal" | Arm with nothing in the hand: the joint move from `look` to above a cup | | `manipulation/skills.py` | `HOLDING_SPEED` | "slow" | With an object in the hand, and the last 10 cm down onto an object and up from it | | `manipulation/skills.py` | `ABOVE_MM` | 100 mm | Height above the grasp from where the arm goes straight down (slow) | @@ -62,8 +63,8 @@ Every value here is a constant at the top of its file, with a comment on what it | `tasks/follow.py` | `STALE_S`, `COAST_S`, `LOST_S` | 0.4 s, 1.0 s, 3 s | A sighting older than `STALE_S` is not new; unseen, the base drives on toward where they should be for `COAST_S`, then slows; "I lost you" after `LOST_S` | | `tasks/follow.py` | `VEL_TAU_S`, `WALK_MAX_MS` | 0.5 s, 2 m/s | Walking-velocity filter time constant; faster estimates are noise | | `tasks/follow.py` | `JUMP_M`, `GATE_GROW_MS`, `SWITCH_M`, `RELOCK_LOOK` | 0.5 m, 0.7 m/s, 0.15 m, 0.6 | Keeping the person: a sighting further than `JUMP_M` (+ `GATE_GROW_MS` per s unseen) from where they should be is someone else; another track must be `SWITCH_M` nearer to be taken; clothes `reid.same` below `RELOCK_LOOK` never taken. Estimates | -| `tasks/follow.py` | `HEAD_REL_MAX`, `HEAD_PITCH`, `HEAD_STEP_DEG`, `HEAD_LEAD_S`, `HEAD_VEL` | 30°, 10°, 3°, 0.3 s, 50 % | Head on the person while following: always straight on them (up to ±180° on the waist); a person further than `HEAD_REL_MAX` from the base heading turns the waist for the rest; fixed pitch, smallest move, sent where they will be this much later, speed | -| `tasks/follow.py` | `WAIST_FOLLOW_MAX`, `WAIST_STEP_DEG`, `WAIST_FOLLOW_VEL`, `WAIST_DRIVE_DEG`, `WAIST_RETRY_S` | 90°, 8°, 50 %, 15°, 1 s | Waist toward the person while following, at the same time as the head and the base: at most this far from the front (the base turns for the rest; it unwinds as the base turns), at most `WAIST_STEP_DEG` per body move (the head goes to its full target in the same move) at `WAIST_FOLLOW_VEL`, each step checked along the arm's sweep; the base drives forward only with the person near ahead and the waist within `WAIST_DRIVE_DEG` of the front; a blocked waist turn is tried again after `WAIST_RETRY_S`. Estimates | +| `tasks/follow.py` | `HEAD_REL_MAX`, `HEAD_PITCH`, `HEAD_STEP_DEG`, `HEAD_LEAD_S`, `HEAD_LEAD_MAX_S`, `HEAD_VEL` | 30°, 10°, 3°, 0.3 s, 1.5 s, 100 % | Head on the person while following: always straight on them (up to ±180° on the waist); a turned waist unwinds until the person is `HEAD_REL_MAX` from the base heading; fixed pitch, smallest move, sent where they will be (seen from where the base will be) as long as the last head move took, at least `HEAD_LEAD_S`, at most `HEAD_LEAD_MAX_S`, speed and acceleration (the maximum; the head is at its top speed from 50) | +| `tasks/follow.py` | `WAIST_FOLLOW_MAX`, `WAIST_STEP_DEG`, `WAIST_FOLLOW_VEL`, `WAIST_DRIVE_DEG`, `WAIST_RETRY_S` | 90°, 8°, 50 %, 15°, 1 s | Waist while following: never turned further out; turned at the start (after "look behind") it unwinds as the base turns, to at most `WAIST_FOLLOW_MAX` from the front, at most `WAIST_STEP_DEG` per body move (the head goes to its full target in the same move) at `WAIST_FOLLOW_VEL`, each step checked along the arm's sweep; the base drives forward only with the person near ahead and the waist within `WAIST_DRIVE_DEG` of the front; a blocked waist turn is tried again after `WAIST_RETRY_S`. Estimates | | `tasks/follow.py` | `BRAKE_S`, `BLOCKED_END_S` | 0.5 s, 5 s | Each command is checked where the base (`BASE_HALF_M + CLEAR_M`) and the arm (`ARM_CLEAR_M`) would be this much later; blocked this long: "Something is in my way" | | `tasks/follow.py` | `TICK_S`, `LOG_S` | 0.1 s, 1 s | Command rate (steady); `follow: v … w … driven … person … head … tick` line (driven = the base's real speed from its pose) in `logs/lumi_console.log` | | `assistant/lumi.py` | `MATCH_DEG_PER_M` | 10 °/m | Person tracking: each m of distance difference counts as this many degrees when a detection is given to a track. Estimate | @@ -93,10 +94,13 @@ Every value here is a constant at the top of its file, with a comment on what it | `manipulation/skills.py` | `IK_SEEDS` | ready, look, carry, give | Taught poses whose arm configurations (and wrist flips) seed the pick / place IK | | `tasks/fetch.py` | `PICK_ZONE_CENTRE` | (−100, 580) mm | Where a base move brings an object (arm base frame) | | `tasks/fetch.py` | `LOST_BACK_M`, `LOST_TURN_DEG` | 0.15 m, 20° | An object lost after a base move: back off, turn each way, look again | +| `tasks/fetch.py` | `BACK_DOWN_MM` | 60 mm | Holding a cup just picked, base, waist and lift unchanged and the hand this near (sideways) over the pick spot: a put down goes straight down there, without the arm to `look` first | +| `tasks/fetch.py` | `WAIST_STEP_DEG` | 10° | "Give me your hand" turns the waist toward the person while the arm moves, in moves this long: a STOP ends the turn after the move it is in. Bigger is smoother, smaller stops sooner | +| `manipulation/skills.py` | `BACK_OUT_NEAR_MM` | 30 mm | A pick stopped with the hand within this of its way in: the next pick first backs out the way it came (side: out, then up; top: up) | | `tasks/fetch.py` | `WIDTH_NEAR_MM` | 250 mm | A width further than this from the pick zone does not refuse a pick (far widths read ~8 mm too wide); measured again up close | -| `manipulation/skills.py` | `MIN_WIDTH`, `MAX_WIDTH` | 70, 81 mm | Object widths the gripper takes from above (the open ring 87 by tape, 6 margin for the camera; wider cups are taken from the side; belly closed 68; tips open 87 / close to 63; [10_GRIPPER.md](10_GRIPPER.md)). `MIN_WIDTH` 61 enables the finger-tip grasp (61–72 mm) | +| `manipulation/skills.py` | `MIN_WIDTH`, `MAX_WIDTH` | 70, 97 mm | Object widths the gripper takes from above (the open tips 100, margin 3; wider cups are taken from the side; belly 102 / 77, tips 100 / 73; [10_GRIPPER.md](10_GRIPPER.md)). `MIN_WIDTH` 61 enables the finger-tip grasp (61–72 mm) | | `manipulation/skills.py` | `BELLY_MIN_MM` | 70 mm | Thinner objects are held between the finger tips (the belly closes only to 68 mm) | -| `manipulation/skills.py` | `SIDE_MAX_WIDTH`, `SIDE_BAND_MM`, `SIDE_SEEN_MM` | 84, 12, 0 mm | Side grasp of a cup too wide at the top: the width the fingers meet (seen + `SIDE_SEEN_MM`; the camera reads a cup's lower part about right, unlike its rim) must be `MIN_WIDTH`..this (open tips 87 mm) from `SIDE_BAND_MM` below to above the grasp point (the hooks are ~16 mm thick) | +| `manipulation/skills.py` | `SIDE_MAX_WIDTH`, `SIDE_BAND_MM`, `SIDE_SEEN_MM` | 97, 12, 0 mm | Side grasp of a cup too wide at the top: the width the fingers meet (seen + `SIDE_SEEN_MM`; the camera reads a cup's lower part about right, unlike its rim) must be `MIN_WIDTH`..this (open tips 100 mm) from `SIDE_BAND_MM` below to above the grasp point (the hooks are ~16 mm thick) | | `manipulation/skills.py` | `SIDE_AT`, `SIDE_TOP_MM` | 0.42, 5 mm | Side grasp height: this share of the cup's height above the table, or the nearest height that fits; the hooks' top at least `SIDE_TOP_MM` under the rim | | `manipulation/skills.py` | `HOOK_BELOW_MM`, `SIDE_CLEAR_MM` | 8, 40 mm | Side grasp: the hand's lowest part this far below the grasp point (estimate from photos), kept `TIP_CLEAR_MM` above the table; the hand comes down this far from the cup's edge before its tips, then goes in level | | `manipulation/skills.py` | `TIPS_OFFSET` (`data/grasp_tips_teach.json` `tips_offset_flange`) | [−0.4, −4.6, 28.2] mm | Finger-tip grasp: the object's axis goes this far from the hooks' belly centre (flange frame, level, turned with the grasp); taught | diff --git a/manipulation/arm_route.py b/manipulation/arm_route.py index ef612c9..f98106a 100644 --- a/manipulation/arm_route.py +++ b/manipulation/arm_route.py @@ -1,9 +1,9 @@ """The arm moves between named poses only by joint moves between taught poses, every joint move checked before anything moves. - give - carry - look - wave_out - wave_start - wave (EDGES: the moves run live first) - | - ready + give_pre - give - carry - look - wave_out - wave_start - wave (EDGES: the moves run live first) + | + ready `look` is where every arm action starts (picks and puts go out from it and come back to it, skills.py). With an empty hand the arm goes from pose to pose by the route of least joint travel (each move its largest joint turn plus @@ -26,10 +26,16 @@ cup's lean at most skills.MAX_TILT_DEG. Refusals are RouteError with the reason A route runs one move at a time (motion.move_path): each to a full stop and SETTLE_S standing, then the next; SPEED with an empty hand, HOLD_SPEED with something in it. +With an empty hand and `give_pre` taught, every way to `give` ends give_pre -> give: the route goes to `give_pre` +(never through `give`), stands there, and the last move into `give` runs at GIVE_SPEED. Without `give_pre` the route +to `give` is the plain cheapest one. With something in the hand `give_pre` is not used (fetch's straight moves). + Cobo π programs start only from `look` (start_program); hand_shaking.jks never (it hit the head, 2026-10-21). python manipulation/arm_route.py check [pose] # the route from here to pose (default look), checked; moves nothing python manipulation/arm_route.py goto # go there along the route (SPEED; the owner at the STOP) + +Teach a pose (arm moved by hand in Cobo π first): python robot/motion.py teach give_pre (then teach give) """ import collections import heapq @@ -43,7 +49,10 @@ from robot import arm, gripper, kinematics, motion from vision import calib, head_cam HOME = "look" # every arm action starts here -EDGES = (("give", "carry"), ("carry", "look"), ("look", "wave_out"), ("wave_out", "wave_start"), +GIVE = "give" # the hand held out to a person +GIVE_PRE = "give_pre" # one step before GIVE: an empty-hand way to GIVE always ends GIVE_PRE -> GIVE +GIVE_SPEED = "slow" # motion.JOINT_SPEED of the last move, GIVE_PRE -> GIVE (first live runs: slow) +EDGES = (("give_pre", "give"), ("give", "carry"), ("carry", "look"), ("look", "wave_out"), ("wave_out", "wave_start"), ("wave_start", "wave"), ("look", "ready")) # the moves with something in the hand (both ways) NO_EDGES = {frozenset(("look", "wave_start"))} # never one joint move: passes 267 mm from the head (the wave # goes up and down through wave_out, 309 mm) @@ -94,10 +103,11 @@ def _deg(now, pose): return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) -def graph(holding=False): - """{pose: joints} of the graph's taught poses (`holding`: without WAVE_POSES).""" +def graph(holding=False, skip=()): + """{pose: joints} of the graph's taught poses but `skip` (`holding`: without WAVE_POSES and GIVE_PRE).""" p = motion.poses() - return {n: p[n] for e in EDGES for n in e if n in p and not (holding and n in WAVE_POSES)} + return {n: p[n] for e in EDGES for n in e + if n in p and n not in skip and not (holding and n in WAVE_POSES + (GIVE_PRE,))} def where(now=None): @@ -179,12 +189,13 @@ def route(a, b, nodes, holding=False): return path -def hops(now, target, leaf=False, holding=False): +def hops(now, target, leaf=False, holding=False, skip=()): """The poses the arm goes through from the joints `now` to `target`, in order (not the one it is at). `leaf`: the - arm is out on the task's own checked way from look (above a table): when it is at no pose, straight to target.""" + arm is out on the task's own checked way from look (above a table): when it is at no pose, straight to target. + `skip`: poses the way must not pass.""" if holding and target in WAVE_POSES: raise RouteError(*SPILL) - nodes = graph(holding) + nodes = graph(holding, skip) if target not in nodes: log(f"arm route: {target} is not taught (robot/motion.py teach {target})") raise RouteError(*NOT_TAUGHT) @@ -305,11 +316,11 @@ def _up(now, mm): return r.get("jointPosition") -def join(now, target, holding=False): +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.""" - nodes = graph(holding) + 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)) @@ -329,14 +340,22 @@ def join(now, target, holding=False): def plan(target, holding=False, leaf=False, now=None): - """[(pose, joints)] of the checked way from here to `target` ([] when it is there). RouteError to refuse.""" + """[(pose, joints)] of the checked way from here to `target` ([] when it is there). RouteError to refuse. + Empty hand to GIVE with GIVE_PRE taught: the way to GIVE_PRE (not through GIVE), then GIVE.""" now = skills._joints() if now is None else now + if target == GIVE and not holding and GIVE_PRE in graph() and where(now) != GIVE: + seq = _plan(GIVE_PRE, False, leaf, now, skip=(GIVE,)) + return seq + [(GIVE, check_moves(seq[-1][1] if seq else now, [motion.poses()[GIVE]])[0])] + return _plan(target, holding, leaf, now) + + +def _plan(target, holding, leaf, now, skip=()): try: - names = hops(now, target, leaf, holding) + names = hops(now, target, leaf, holding, skip) except RouteError as e: if e.args != UNKNOWN: raise - seq = join(now, target, holding) + seq = join(now, target, holding, skip) log(f"arm route: joining from {_r(now)} by {' -> '.join(n for n, _ in seq)}, checked") return seq p = motion.poses() @@ -351,7 +370,8 @@ def move(seq, speed=None, holding=False): t0 = time.time() log(f"arm to {' -> '.join(n for n, _ in seq)}") s = HOLD_SPEED if holding else speed or SPEED - motion.move_path([(j, s) for _, j in seq]) + last = GIVE_SPEED if not holding and GIVE_PRE in graph() else s # GIVE_PRE -> GIVE (plan) + motion.move_path([(j, last if n == GIVE else s) for n, j in seq]) log(f"arm at {seq[-1][0]} after {time.time() - t0:.1f} s") diff --git a/manipulation/skills.py b/manipulation/skills.py index 34e4484..6898385 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -65,10 +65,10 @@ LIFT_MM = 30.0 # first lift after closing, the MAX_TILT_DEG = 15.0 # deg; a held cup's axis may lean this far from vertical on a joint # move with it (place_options; tasks/fetch.py uses the same) PLACE_EXTRA_MM = 3.0 # put down this much higher than it was picked (same table) -MIN_WIDTH, MAX_WIDTH = 70.0, 81.0 # mm: the cup's top goes through the open hooks' ring (87 by tape) and - # the belly closes round it (closed 68). MAX_WIDTH: the owner's margin - # 6 for the camera (an 84 mm rim read 83-85); wider tops are taken from - # the side (side()). The tips grasp (61-72) missed twice live on a +MIN_WIDTH, MAX_WIDTH = 70.0, 97.0 # mm: the cup's top goes through the open hooks' ring (tips 100 open, + # owner's measure) and the belly closes round it. MAX_WIDTH: the + # owner's margin 3; wider tops are taken from the side (side()). The + # tips grasp (61-72) missed twice live on a # 66 mm can (2026-10-22): off by the owner until it is checked; 61 # brings it back SEEN_UNDER_MM = 8.0 # the camera's width is this much under the width the fingers meet @@ -119,9 +119,9 @@ BELOW_SHOULDER_MM = 80.0 # bottles: grasp this far below # the owner's taught tips grasp of a spray can, at its middle (2026-10-22, # grasp_tips_teach.json); the hand's lowest part (TIP_MM below) must # stay TIP_CLEAR_MM above the table (else its lowest point seen) -SIDE_MAX_WIDTH = 84.0 # mm; side grasp (a cup whose top is wider than MAX_WIDTH): the width the +SIDE_MAX_WIDTH = 97.0 # mm; side grasp (a cup whose top is wider than MAX_WIDTH): the width the # fingers meet (seen + SIDE_SEEN_MM) where the hooks go in from the - # side, under the open tips' 87 mm (owner's tape) with a margin 3 + # side, under the open tips' 100 mm (owner's measure) with a margin 3 SIDE_SEEN_MM = 0.0 # ... the camera's width of a cup's lower part is not under like its rim: # an 84 mm rim cup read 73-77 where the tape gave 71 (45 mm up) and # AI_1 74 (60 mm up, 2026-10-29) @@ -195,8 +195,11 @@ CONFIRM_DEG = 2.0 # deg; its inverse kinematics w RETRIES = 4 # the controller now and then answers with nothing: ask again, RETRY_S = 0.2 # waiting this long, twice as long each time (it drops connections) OPEN_AI = gripper.CLOSED_AI # AI_1 below this after opening = released +BACK_OUT_NEAR_MM = 30.0 # back_out: the hand this near the stopped pick's way in is still in it _held = {} # what pick() holds: {"top_mm", "x", "y"} for place() / put_down() +_pick_way = {} # the pick's waypoints {name: pose} from the move to above until the + # hand holds or has backed out (back_out after a stop) _cancel = threading.Event() # set by cancel(): the running skill makes no further move LOG = collections.deque(maxlen=40) # last log lines, shown by the API moved_at = {} # camera -> time its last move (lift, waist, base, head) ended: @@ -1015,6 +1018,7 @@ def _prepare(): if gripper.state()["ai"][0] > OPEN_AI: log("opening the gripper") gripper.open_() + back_out() if max(abs(a - b) for a, b in zip(_joints(), home_joints())) > 1.0: from manipulation import arm_route arm_route.goto(home()) @@ -1038,14 +1042,40 @@ def _give_up(reason, back=0.0): """Open, back up 100 mm (from a side grasp first `back` mm out sideways: the rim is wider than the hooks), home, raise. Only used while the object is at (or just above) the table.""" log(f"{reason}: opening, backing up") + _held.clear() gripper.open_() if back: _line("out sideways", back_off(motion.tcp(), back)) motion.move_linear(delta=[0, 0, ABOVE_MM], speed=HOLDING_SPEED) _back_home() + _pick_way.clear() raise SkillError(reason) +def back_out(): + """A pick stopped on its way in (_pick_way: the open hand beside the object or down around it): out the way it + came before anything else moves, a side grasp straight out against the tips' direction to its "side" point, then + straight up to its "above" height. Nothing when no pick was stopped there or the hand is no longer near its way.""" + if not _pick_way: + return + now, way = motion.tcp(), _pick_way + above, grasp = way["above"], way["grasp"] + start = way.get("side", grasp) + near = np.hypot(start[0] - grasp[0], start[1] - grasp[1]) + BACK_OUT_NEAR_MM + if now[2] >= above[2] - 1.0 or now[2] < grasp[2] - BACK_OUT_NEAR_MM or \ + np.hypot(now[0] - grasp[0], now[1] - grasp[1]) > near: + _pick_way.clear() # already up there, or moved away since: nothing to back out of + return + log("a pick was stopped here: backing out the way it came in") + if "side" in way: + d = float(np.dot(np.subtract(now[:2], start[:2]), tips_dir(yaw_of(now)))) + if d > 1.0: + now = back_off(now, d) + _line("out sideways", now) + _line("up", [now[0], now[1], above[2]] + list(now[3:])) + _pick_way.clear() + + def _do_pick(obj, waypoints, ja): """Pick with the planned joints `ja` above the object (pick_options); a side grasp goes down beside it first.""" way = dict(waypoints) @@ -1055,8 +1085,11 @@ def _do_pick(obj, waypoints, ja): if table is None: table = table_z(obj) if table_z(obj) is not None else table_near(obj) # what put down needs: the object's height log(f"it stands on a table at {table:.0f} mm" if table is not None else "the table under it is not in view") + _held.clear() # nothing held until the fingers close on it _prepare() _go_on() + _pick_way.clear() + _pick_way.update(way) log(f"above: joint move to ({above[0]:.0f}, {above[1]:.0f}, {above[2]:.0f})") motion.move_joints(ja, EMPTY_SPEED) if back: @@ -1068,14 +1101,17 @@ def _do_pick(obj, waypoints, ja): log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']} finger sensor {s['object_in_front']}") if not s["holding"]: _give_up("I missed it.", back) + # held from here on: a stop in the lift leaves it ready to put down + _held.update(top_mm=obj["top_mm"], x=obj["x"], y=obj["y"], yaw=yaw_of(grasp), table=table, + tips=grip_width(obj) < BELLY_MIN_MM, below=obj["top_mm"] - grasp_height(obj), back=back) + _pick_way.clear() _line("lift", lift) s = gripper.state() log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']}") if not s["holding"]: + _held.clear() _line("slipped, back down", grasp) _give_up("It slipped out of my hand.", back) - _held.update(top_mm=obj["top_mm"], x=obj["x"], y=obj["y"], yaw=yaw_of(grasp), table=table, - tips=grip_width(obj) < BELLY_MIN_MM, below=obj["top_mm"] - grasp_height(obj), back=back) def _do_place(waypoints): diff --git a/robot/gripper.py b/robot/gripper.py index db3f573..599b8cb 100644 --- a/robot/gripper.py +++ b/robot/gripper.py @@ -25,9 +25,9 @@ CLOSED_AI = 400 # AI_1 above this = closed on something (open reads # held in the cup fingers reads ~2200-2300, 2026-10-13) EMPTY_AI = 3900 # closed above this = nothing between the fingers (empty reads 4100-4200, noise +-50) AI_OPEN, AI_SHUT = 140.0, 4160.0 # AI_1 fully open / closed on nothing (2026-10-19) -# inner gap (mm) between the fingers, (open, closed), measured with a tape (docs/gripper/README.md; the straight part -# "shank" not measured on these fingers, the earlier one kept); the gap is taken as linear in AI_1 -GAP_MM = {"tips": (87.0, 63.0), "belly": (94.0, 68.0), "neck": (57.0, 30.0), "shank": (66.0, 39.0)} +# inner gap (mm) between the fingers, (open, closed), measured by the owner (docs/gripper/README.md; the neck and the +# straight part "shank" not measured again, the earlier ones kept); the gap is taken as linear in AI_1 +GAP_MM = {"tips": (100.0, 73.0), "belly": (102.0, 77.0), "neck": (57.0, 30.0), "shank": (66.0, 39.0)} MOVE_S = 1.5 # s a full stroke takes (measured ~1 s) SENSOR_DI = 0 # DI_1 READ_TRIES, READ_GAP_S = 5, 0.1 # get_data now and then answers without the tool I/O: ask again diff --git a/tasks/fetch.py b/tasks/fetch.py index 0f65982..00bddd9 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -102,6 +102,8 @@ SEARCH_BASE_DEG = (180.0, 90.0) # then the base turns towards that side, th LIFT_TRIES = LIFT_RANGE # mm; nothing found: all of it again at the other end of these SAME_BASE_M = 0.02 # m / rad; the base is still where it picked: the pick spot is still table SAME_BASE_RAD = 0.035 +BACK_DOWN_MM = 60.0 # mm; held with the flange this near (sideways) over the pick spot, base, waist and + # lift as they picked: a put down goes straight down there, no look first WAIST_REACH_STEPS = (0.0, 15.0, -15.0, 30.0, -30.0) # deg; a pick out of reach: waist turns tried around the one # that brings the object to PICK_ZONE_CENTRE's bearing about the column (the waist carries # the arm round the column: what it reaches beside it, it reaches ahead), before a base move @@ -149,6 +151,8 @@ HEAD_LOW_PITCH = -5.0 # head pitch for those checks and the search: its l 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 = 20 # % of the waist's speed: the arm sweeps sideways +WAIST_STEP_DEG = 10.0 # deg; a waist turn made together with an arm move goes in moves this long: the body API + # cannot stop a moveto, so a STOP ends the turn after the move it is in (_give_turning) HEAD_AHEAD = (0.0, head.HEAD_REST_PITCH) # head (yaw, pitch) deg before a drive to a place and after every task: ahead, at rest # (search turns and short moves keep the head where the search turned it) OFFSET_TURN_DEG = 15.0 # a move that turned the base at least this much tells where the arm base is (arm_offset) @@ -570,9 +574,11 @@ def _charging(): return True # unknown: better not drive off -def arm_points_3d(): - """(x, y, z) mm in the arm base frame of the flange, the grasp point and the finger tips, from the joints now.""" - c = skills._ask("kine_forward", jointPosition=[float(v) for v in skills._joints()])["cartPosition"] +def arm_points_3d(joints=None): + """(x, y, z) mm in the arm base frame of the flange, the grasp point and the finger tips, at `joints` (default: + the joints now).""" + joints = skills._joints() if joints is None else joints + c = skills._ask("kine_forward", jointPosition=[float(v) for v in joints])["cartPosition"] R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3]) g = f + R @ skills.GRASP_OFFSET return [f, g, g + R @ (skills.TIP_MM * skills.FINGER_DIR)] @@ -595,26 +601,28 @@ def _near_hand(p, pts): return best -def depth_hits(deg, camera="torso", T=None): +def depth_hits(deg, camera="torso", T=None, pts=None): """Like turn_hits, with the torso depth camera: the arm's points along the turn at their real height (a table top's edge, a shelf: the lidar at the base's height does not see them), (x, y, z) mm in the arm frame now of the first one the camera sees something at or in front of; None when clear. Points out of its view are left to the lidar; depth on the arm's own parts (in view, within SELF_MM of them) does not count. Another camera: its name and its - camera -> arm base transform T.""" + camera -> arm base transform T. `pts`: the arm-frame points (mm) of every pose the arm passes while it turns + (_route_points), checked from the start of the turn on; default the hand now, from the first step.""" yaw = arm_yaw() T = skills.objects.base_from_camera() if T is None else T if yaw is None or T is None: return None - pts, t, cam = arm_points_3d(), arm_xy(), T[:3, 3] + hand, t, cam = arm_points_3d(), arm_xy(), T[:3, 3] + k0, pts = (1, hand) if pts is None else (0, pts) n = max(1, math.ceil(abs(deg) / SWEEP_STEP_DEG)) cand = [] - for k in range(1, n + 1): + for k in range(k0, n + 1): R = _rot(deg * k / n) for p in pts: xy = _rot(-yaw) @ (R @ to_base(p[:2], yaw, t) - t) * 1000.0 cand.append(np.array([xy[0], xy[1], p[2]])) for c, h in zip(cand, skills.surface_points([tuple(c) for c in cand], camera=camera, T=T)): - if h is None or _near_hand(h, pts) < SELF_MM: + if h is None or _near_hand(h, hand) < SELF_MM: continue if np.linalg.norm(np.subtract(h, cam)) <= np.linalg.norm(c - cam) + ARM_CLEAR_M * 1000.0: return c @@ -653,7 +661,7 @@ def _head_to(yaw, pitch): skills.moved("head") -def head_hits(deg): +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). The head stays there: the next look or drive turns it where it needs it.""" @@ -662,18 +670,19 @@ def head_hits(deg): if T is None: return None _head_to(side, HEAD_LOW_PITCH) - return depth_hits(deg, "head", T) + return depth_hits(deg, "head", T, pts) -def turn_hits(deg): +def turn_hits(deg, pts=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.""" + itself turns in its own footprint; navigation does not know about the arm sticking out. `pts`: as depth_hits.""" if arm_yaw() is None: return None - pts, (x, y, th) = arm_points(), agv.pose() + 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() n = max(1, math.ceil(abs(deg) / SWEEP_STEP_DEG)) - for k in range(1, n + 1): + for k in range(k0, n + 1): R = _rot(math.degrees(th) + deg * k / n) for p in pts: w = np.array([x, y]) + R @ p @@ -682,15 +691,16 @@ def turn_hits(deg): return None -def _sweep_blocked(deg, what): +def _sweep_blocked(deg, what, pts=None): """True (and logged) when the arm would hit something while it swings by `deg` about the base centre: a base turn - on the spot and a waist turn sweep the same circles (turn_hits, depth_hits, head_hits).""" - hit = turn_hits(deg) + on the spot and a waist turn sweep the same circles (turn_hits, depth_hits, head_hits). `pts`: as depth_hits.""" + kw = {} if pts is None else {"pts": pts} + hit = turn_hits(deg, **kw) if hit is not None: log(f"not {what} {deg:+.0f} deg: my arm would hit something at ({hit[0]:.2f}, {hit[1]:.2f})") return True for cam, check in (("camera", depth_hits), ("head camera", head_hits)): - seen = check(deg) + seen = check(deg, **kw) if seen is not None: log(f"not {what} {deg:+.0f} deg: the {cam} sees something in my arm's way at ({seen[0]:.0f}, " f"{seen[1]:.0f}, {seen[2]:.0f}) mm") @@ -1656,10 +1666,7 @@ def place_spots(held, base_now, seen, table=None): """Where the held object may go: the pick spot when the base has not moved since the pick, then free grid spots the depth camera sees as table at `table` mm (default: the pick table's height), nearest the pick zone centre first. Free: FREE_MM from everything seen standing on the table.""" - b0 = held.get("base") - same = b0 is not None and math.hypot(base_now[0] - b0[0], base_now[1] - b0[1]) < SAME_BASE_M \ - and abs((base_now[2] - b0[2] + math.pi) % (2 * math.pi) - math.pi) < SAME_BASE_RAD \ - and abs(held.get("waist", 0.0) - _waist_turn()) < 1.0 + same = _same_stand(held, base_now) tries = [(held["x"], held["y"])] if same else [] others = [o for o in seen if not (same and math.hypot(o["x"] - held["x"], o["y"] - held["y"]) < skills.CLUSTER_MM)] table = held.get("table") if table is None else table @@ -1675,6 +1682,31 @@ def place_spots(held, base_now, seen, table=None): return tries + skills.on_table(grid, table) +def _same_stand(held, base_now): + """The base and the waist are still where `held` was picked: the pick spot is where it was in the arm frame.""" + b0 = held.get("base") + return b0 is not None and math.hypot(base_now[0] - b0[0], base_now[1] - b0[1]) < SAME_BASE_M \ + and abs((base_now[2] - b0[2] + math.pi) % (2 * math.pi) - math.pi) < SAME_BASE_RAD \ + and abs(held.get("waist", 0.0) - _waist_turn()) < 1.0 + + +def _put_back_here(top0): + """Held over the spot it was picked from (a voice pick ends just above it, a stop after the grasp leaves it there) + with the base, the waist and the lift as they picked: straight down there, checked like any place (_place_at), + no look first. Live 2026-10-29: "put it on the table" took the cup to look and back to the same table. None when + it is held elsewhere or the way down is refused (then the search from look).""" + h = skills._held + lift0 = h.get("lift") + if not _same_stand(h, agv.pose()) or lift0 is None or abs(lift0 - head.status()[0]) >= LIFT_TOL_MM: + return None + above = skills.plan_place(h["x"], h["y"], top0, yaw=h.get("yaw", 0.0))[0][1] + now = motion.tcp() + if math.hypot(now[0] - above[0], now[1] - above[1]) > BACK_DOWN_MM: + return None + log("held over the spot it was picked from: putting it back down there") + return _place_at([(h["x"], h["y"])], top0, turned=False) + + def _place_here(top0, kept=None): """One look for a place from where the arm is (look, the held object out of the view): measure the table (the kept one's height only, _kept_band), fit the lift, try the spots. True when the object was put down, else None.""" @@ -1792,9 +1824,9 @@ def _place_far(top0, far): return _place_at(spots, _top_on(top0, far["table"])) -def _place_at(tries, top): +def _place_at(tries, top, turned=True): """Put the held object down at the first of `tries` (x, y) whose way down passes IK: straight from here with the - held grasp turn, else any grasp turn and wrist (skills.place_options). True when it is down.""" + held grasp turn, else (`turned`) any grasp turn and wrist (skills.place_options). True when it is down.""" log(f"place spots: {', '.join(f'({x:.0f}, {y:.0f})' for x, y in tries[:6])}") for n, (x, y) in enumerate(tries): if n >= PLACE_REFUSALS: # the rest are further / lower: each refused spot costs ~1 s of @@ -1818,6 +1850,8 @@ def _place_at(tries, top): return True if rows: log(f"spot ({x:.0f}, {y:.0f}) refused at {rows[-1][0]}: {rows[-1][3]}") + if not turned: + 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) log(f"putting it down at ({x:.0f}, {y:.0f})") @@ -2131,6 +2165,10 @@ def _put_down(say=None, on=None): if top is None: raise FetchError("I'm not holding anything I picked.") _step("placing") + if not on or not on.get("pointed") and on.get("name") == "dining table" and not on.get("colour") and \ + on.get("prefer") in (None, "near"): + if _put_back_here(top): # held just above the table it came from + return _line_holding(LOOK_POSE) if on and on.get("pointed"): # "put it here / there" with a pointing hand return _put_pointed(top, say) @@ -2220,6 +2258,7 @@ def _pick_here(task, say): no = skills.refusal(task["object"]) if no: raise FetchError(*no) + skills._guarded(skills.back_out) # a pick stopped beside / around it: out the way it came for attempt in range(PICK_TRIES): _step("looking") obj = _see(task, say) @@ -2227,15 +2266,12 @@ def _pick_here(task, say): obj, waypoints, ja = _reach(task, obj, say) _step("picking") try: - skills._guarded(skills._do_pick, obj, waypoints, ja) # ends 3 cm above the table, holding + _pick(obj, waypoints, ja) # ends 3 cm above the table, holding break except skills.SkillError as e: if e.args[0] not in MISSES or attempt == PICK_TRIES - 1: raise _say(say, "I missed it. Let me try again.", "놓쳤어요. 다시 해 볼게요.") - skills._held["base"] = agv.pose() # place_spots: put back here if the base stays ... - skills._held["waist"] = _waist_turn() # ... and the waist too - skills._held["lift"] = head.status()[0] # _top_on when its table was not measured skills._held["what"] = {"object": task["object"], "colour": task.get("colour")} # held_name() when the state lost it _set(holding=True, held_object=skills._held["what"]) _say(say, "I've got it.", "잡았어요.") @@ -2244,6 +2280,23 @@ def _pick_here(task, say): _carry_from(waypoints[0][1], ja) +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).""" + try: + skills._guarded(skills._do_pick, obj, waypoints, ja) + finally: + if "top_mm" in skills._held: + _note_stand() + + +def _note_stand(): + """Where the body stood at the pick, kept with the held object.""" + skills._held["base"] = agv.pose() # place_spots, _put_back_here: put back here if the base + skills._held["waist"] = _waist_turn() # stays ... and the waist too + skills._held["lift"] = head.status()[0] # _top_on when its table was not measured + + 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: @@ -2421,12 +2474,13 @@ def pick_here(name, colour=None, say=None): task = {"object": name, "colour": colour} _clear() try: + skills._guarded(skills.back_out) # a pick stopped beside / around it: out the way it came obj = _find(task) log(f"found {obj['colour']} {obj['name']} at ({obj['x']:.0f}, {obj['y']:.0f}) top {obj['top_mm']:.0f} " f"width {obj['width_mm']:.0f}") obj, waypoints, ja = _reach(task, obj, say, voice=True) _step("picking") - skills._guarded(skills._do_pick, obj, waypoints, ja) + _pick(obj, waypoints, ja) finally: _set(step="") return obj @@ -2961,11 +3015,11 @@ def give_bearing(): def reach(angle=0.0, say=None, look=None): - """Hold the hand out to the person ("reach out to me", "손 내밀어"): first, when `angle` (deg, + left, waist - frame: the person tracker's) is not 0, the waist turns to face them (_waist_to, also with Patrol off: the base - stays; its arm sweep checked; past the waist's limits they are asked to stand in front; the waist stays turned - after; the head turns with it onto them and stays on them, also after), then the arm along the pose graph to give - (arm_route, every move checked), then at most RECEIVE_REACH_MM straight towards their hand or body + """Hold the hand out to the person ("reach out to me", "손 내밀어"): when `angle` (deg, + left, waist frame: the + person tracker's) is not 0, the waist turns to face them while the arm goes along the pose graph to give, both at + once (_give_turning, also with Patrol off: the base stays; the arm's sweep over the turn checked first; past the + waist's limits they are asked to stand in front; the waist stays turned after; the head stays on them, also + after); else only the arm to give (arm_route, every move checked); then at most RECEIVE_REACH_MM straight towards their hand or body (_person_point, _reach_to_hand). The arm stays out; "fold" brings it back to look. `look`: the person's angle the head stays on when the waist turns by another `angle` (to bring the hand, not the waist's front, onto them).""" if "give" not in motion.poses(): @@ -2981,10 +3035,11 @@ def reach(angle=0.0, say=None, look=None): try: if angle: # the waist, not the base: the person stays where they are lo, hi = head.AXIS_LIMITS[1] - if not lo <= head.status()[1] + angle <= hi or \ - not _waist_to(angle + _waist_turn(), in_place=True, look=angle if look is None else look): + if not lo <= head.status()[1] + angle <= hi: raise FetchError(*TURN_TO_PERSON) - _pose("give") + _give_turning(angle + _waist_turn(), angle if look is None else look) + else: + _pose("give") _reach_to_hand(*_person_point()) _set(status="done", step="") log("reached out") @@ -2993,6 +3048,67 @@ def reach(angle=0.0, say=None, look=None): _launch(run, ahead=False) # the head stays on the person, not ahead +def _route_points(seq): + """Arm-frame points (mm; flange, grasp point, finger tips) of the arm now, halfway along each joint move of the + arm_route plan `seq` and at its end: where the hand can be while it goes along it.""" + js, prev = [skills._joints()], skills._joints() + for _, j in seq: + js += [[(a + b) / 2 for a, b in zip(prev, j)], j] + prev = j + return [p for j in js for p in arm_points_3d(j)] + + +def _give_turning(rel, look): + """The waist turns to `rel` (as _waist_to, in place) while the arm goes along the pose graph to give, both at once: + the hand comes out toward the person while Lumi turns to them; the head stays on `look` (waist-frame deg, as + before the turn). Checked before anything moves: the arm route (arm_route: joints, the head; the arm and the head + both sit on the waist, so those checks hold at any waist angle) and the sweep of the hand at every pose it passes + (_route_points) over the whole turn, from its start (_sweep_blocked). FetchError(TURN_TO_PERSON) when the sweep is + not clear. The waist command goes out first, in its own thread in WAIST_STEP_DEG moves; then the arm route; then + both are waited for. A STOP or a failed arm move ends the waist turn after the move it is in.""" + waist = head.status()[1] + lo, hi = head.AXIS_LIMITS[1] + d = max(lo, min(hi, waist - _waist_turn() + rel)) - waist + if abs(d) < 1.0: + return _pose("give") + _go_on() + pitch = head.status()[3] # head_hits turns the head to the side: it comes back with the waist + try: + seq = arm_route.plan("give") + except arm_route.RouteError as e: + raise FetchError(*e.args) from e + if _sweep_blocked(d, "turning my waist with my arm", pts=_route_points(seq)): + raise FetchError(*TURN_TO_PERSON) + _go_on() + lift = head.status()[0] + n, halt, out = max(1, math.ceil(abs(d) / WAIST_STEP_DEG)), threading.Event(), {} + log(f"waist {waist:.0f} -> {waist + d:.0f} deg with the arm to give: {' -> '.join(x for x, _ in seq) or 'there'}") + + def turn(): + try: + for k in range(1, n + 1): + if halt.is_set(): + return + dk = d * k / n + y = max(-head.YAW_LIMIT, min(head.YAW_LIMIT, look - dk)) + _body_move([lift, waist + dk, y, pitch], vel=WAIST_VEL, acc=20, timeout=60) + except Exception as e: + out["error"] = e + t = threading.Thread(target=turn, name="waist", daemon=True) + t.start() + try: + arm_route.move(seq) + while t.is_alive(): + if _stop.wait(0.1): + raise Stopped() + finally: + halt.set() + if "error" in out: + raise out["error"] + skills.moved() + _go_on() + + def _arm(pose): if pose in ("open", "close"): st = gripper.open_() if pose == "open" else gripper.close() diff --git a/tasks/follow.py b/tasks/follow.py index 492d23e..a5877ac 100644 --- a/tasks/follow.py +++ b/tasks/follow.py @@ -6,10 +6,10 @@ put on the map (base pose + distance, angle) with a smoothed walking velocity, s toward where the person is now, not where they were seen (no stop-and-go when frames are missed). A sighting far from that place is someone else (a passer-by who took the track over); a lost track is swapped for a fresh one near that place whose clothes are not clearly different (re-lock). The head turns toward the person in its own thread (only -this task moves the body meanwhile: head.owners) and the waist with it, all at once: the head straight on them (up to -+-180 on the waist), the waist a short way toward them in the same move, the base turning toward them at the same time; -as the base comes round the waist and the head unwind (waist_for). Nothing waits for another. Following starts with the -waist where it is (turned toward the person after "look behind"). The base is driven with joy_control every TICK_S (one +this task moves the body meanwhile: head.owners), straight on them (up to +-180 on the waist), sent where they will be +seen from where the base will be when the move ends; the base turns toward them at the same time. The waist never +turns further out: following starts with it where it is (turned toward the person after "look behind") and it unwinds +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. @@ -60,10 +60,9 @@ TICK_S = 0.1 # s between commands, steady (joy_control wants > 2 LOG_S = 1.0 # s between "follow: v ... " lines (what the next live run is read from) 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) -HEAD_REL_MAX = 30.0 # deg; a person this near the base heading is looked at with the head alone; further, the - # waist turns toward them for the rest (the head is never held back by it) -WAIST_FOLLOW_MAX = 90.0 # deg from the front; the waist turns toward the person at most this far, the base turns - # for the rest (fetch.WAIST_SCAN_MAX 120 is the search's; less here, estimate) +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) WAIST_STEP_DEG = 8.0 # deg; one body move turns the waist at most this far, so every move is short (~0.4 s) and # the head's next correction is not held back; the waist keeps on in the next move WAIST_FOLLOW_VEL = 50 # speed ratio % of a move that turns the waist (the head in it too). The waist's deg/s at @@ -75,8 +74,11 @@ WAIST_DRIVE_DEG = 15.0 # deg; the base drives forward only with the waist t WAIST_RETRY_S = 1.0 # s; a waist turn found blocked is not tried again for this long (each try probes the map) HEAD_PITCH = 10.0 # deg; head pitch while following, a little up toward a standing person (as "look at me") HEAD_STEP_DEG = 3.0 # deg; a new head move only when the target is this far from where the head was sent -HEAD_LEAD_S = 0.3 # s; the head is sent where the person will be this much later (a moveto takes time) -HEAD_VEL = 50 # speed ratio %; the head is at its full speed from 50 (audio/sing.py, measured) +HEAD_LEAD_S = 0.3 # s; the head is sent where the person will be, seen from where the base will be, this +HEAD_LEAD_MAX_S = 1.5 # much later at least, or as long as the last head move took (live 0.5-1.3 s), at most this: + # 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) CHARGER = ("I'm on the charger, I can't follow you from here.", "충전 중이라 따라갈 수 없어요.") @@ -284,11 +286,20 @@ def waist_for(b): return max(-WAIST_FOLLOW_MAX, min(WAIST_FOLLOW_MAX, math.copysign(max(0.0, abs(b) - HEAD_REL_MAX), b))) +def unwind(w, b): + """Where the waist, turned w deg, goes for a person b deg from the base heading: toward waist_for(b), but only + back toward the front, never further out. Turning out made every move a slow waist move and, with the base turning + the same way, left the head 40-70 deg off the person (live 2026-10-29, lost): the head alone follows them, the + base turns, and the waist unwinds as the base comes round (the head's turn back gets smaller, not bigger).""" + goal = waist_for(b) + return 0.0 if goal * w <= 0.0 else math.copysign(min(abs(goal), abs(w)), w) + + def _head_follow(target, done, lift, front, w, waist_free, stats): - """Turn the head, and the waist with it, to the person at target[0] (deg from the base heading, pitch). Every move - sends the head straight to them (up to +-BEHIND_DEG on the waist, never held back) and the waist at most - WAIST_STEP_DEG toward waist_for() in the same move, so the waist keeps turning move after move while the base turns - and the head stays on the person all along. Every waist step is checked along the arm's sweep (fetch.turn_hits); + """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 + at most WAIST_STEP_DEG toward unwind() in the same move, so a turned waist comes back move after move while the base + turns and the head stays on the person all along. Every waist step is checked along the arm's sweep (fetch.turn_hits); blocked, or waist_free False (arm not in look, its place not measured): the waist stays and the head alone turns. `front`: the waist's reading at the front, `w`: its turn from there now. One moveto at a time, from this thread only: overlapping calls hang the body API. The drive loop never waits for it.""" @@ -299,7 +310,7 @@ def _head_follow(target, done, lift, front, w, waist_free, stats): done.wait(TICK_S / 2) continue b, pitch = t - want = waist_for(b) - w if waist_free and time.time() >= retry else 0.0 + want = unwind(w, b) - w if waist_free and time.time() >= retry else 0.0 step = max(-WAIST_STEP_DEG, min(WAIST_STEP_DEG, want)) if abs(step) < HEAD_STEP_DEG and (waist_for(b) != 0.0 or abs(step) < 0.5): step = 0.0 # small steps only for the last bit to the front @@ -405,7 +416,10 @@ def _run(see, say, people): ref = target[0][0] if target[0] else gaze d, a = _rel(pose, person.at(now)) a = ref + (a - ref + 180.0) % 360.0 - 180.0 - yaw = _rel(pose, person.at(now + HEAD_LEAD_S))[1] + lead = max(HEAD_LEAD_S, min((stats["head_ms"] or 0) / 1000.0, HEAD_LEAD_MAX_S)) + then = (pose[0] + v * lead * math.cos(pose[2]), pose[1] + v * lead * math.sin(pose[2]), + 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 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])])) diff --git a/tests/test_arm_give_route.py b/tests/test_arm_give_route.py index 5147dc3..8f07bda 100644 --- a/tests/test_arm_give_route.py +++ b/tests/test_arm_give_route.py @@ -60,4 +60,27 @@ try: raise AssertionError("went to a wave pose holding") except arm_route.RouteError as e: assert e.args == arm_route.SPILL, e.args + +# ---------- give_pre taught: an empty-hand way to give always ends give_pre -> give, the last move slow ---------- +POSES["give_pre"] = moved(POSES["give"], 4, 20) # give with J5 20 deg further (a stand-in) +for start in ("look", "wave_start", "wave", "carry", "ready", "wave_out", "give_pre"): + route = names("give", POSES[start]) + assert route[-2:] == ["give_pre", "give"] or start == "give_pre" and route == ["give"], (start, route) + assert route.count("give") == 1, (start, route) # never through give on the way to give_pre +assert names("give", POSES["give"]) == [] # there already: nothing moves +assert names("give", moved(POSES["give"], 4, 2)) == ["give"] # at give within AT_POSE_DEG: as before +assert names("give", moved(POSES["carry"], 0, -30))[-2:] == ["give_pre", "give"] # a join from far too +assert names("give", POSES["look"], holding=True) == ["carry", "give"] # holding: give_pre not used +assert "give_pre" not in arm_route.graph(holding=True) +assert names("look", POSES["give"]) == ["look"] # other targets as before +sent = [] +real_path, motion.move_path = motion.move_path, lambda moves, **k: sent.extend(moves) +arm_route.move(arm_route.plan("give", now=list(POSES["wave_start"]))) +assert [s for _, s in sent][-1] == arm_route.GIVE_SPEED and \ + all(s == arm_route.SPEED for _, s in sent[:-1]), sent # the last move, give_pre -> give, slow +del POSES["give_pre"] # not taught: the route and speed as before +sent.clear() +arm_route.move(arm_route.plan("give", now=list(POSES["wave_start"]))) +assert [s for _, s in sent] == [arm_route.SPEED], sent +motion.move_path = real_path print("arm give route ok") diff --git a/tests/test_detour.py b/tests/test_detour.py index b859268..f672668 100644 --- a/tests/test_detour.py +++ b/tests/test_detour.py @@ -171,7 +171,7 @@ class Patrol: class Modes: - patrol, drive = True, True + patrol = True L = lumi.Lumi.__new__(lumi.Lumi) diff --git a/tests/test_fetch.py b/tests/test_fetch.py index e024603..1e0b158 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -979,8 +979,9 @@ ahead = lambda mm, side=0.0: [g0[0] + mm, g0[1] + side, g0[2]] scene["person_in_front"] = {"position_mm": ahead(900.0), "hands": {"left": {"position_mm": ahead(600.0, 100.0), "distance_m": 1.1}, "right": {"position_mm": ahead(400.0), "distance_m": 0.9}}} turns = [] -real_waist_to = fetch._waist_to -fetch._waist_to = lambda deg, in_place=False, look=None: turns.append(deg) or in_place and deg < 90 # in place +real_blocked, real_route_points = fetch._sweep_blocked, fetch._route_points +fetch._sweep_blocked = lambda deg, what, pts=None: turns.append(deg) or deg >= 90 # the waist turn with the arm +fetch._route_points = lambda seq: [] def reached(angle=0.0): @@ -1005,8 +1006,8 @@ scene["person_in_front"] = None st, moves = reached() assert st["status"] == "done" and poses()[-1] == "give" and not moves, (st, moves) fetch.stay_put = True # Greeter only: the waist still turns (the base stays) -st, moves = reached(40.0) # to the side: the waist turns first, by the -assert turns == [40.0 + fetch._waist_turn()] and poses()[-1] == "give", (turns, poses()) # waist's offset too +st, moves = reached(40.0) # to the side: the waist turns with the arm +assert turns == [40.0] and poses()[-1] == "give", (turns, poses()) fetch.stay_put = False turns.clear() said.clear() @@ -1015,7 +1016,7 @@ assert st["status"] == "failed" and not poses() and said[-1] == fetch.TURN_TO_PE turns.clear() st, moves = reached(160.0) # past the waist's limit (-15 + 160 > 140): stand in front assert st["status"] == "failed" and not turns and not poses() and said[-1] == fetch.TURN_TO_PERSON[0], (st, turns) -fetch._waist_to = real_waist_to +fetch._sweep_blocked = real_blocked # the head on the person through the whole reach (live: the waist turned with the head kept at +46 on it, so the # head looked 90 deg left, away, until head_ahead at the end): Greeter only, person at -40 deg (waist frame), the # head on them; the sweep check turns the head to that side (head_hits); every head command looks their way, the @@ -1028,7 +1029,7 @@ def head_cmd(pos, **kw): hp.update(waist=pos[1], yaw=pos[2], pitch=pos[3]) gaze.append(pos[1] + 15.0 + pos[2]) fetch.head.moveto = head_cmd -fetch._sweep_blocked = lambda deg, what: head_cmd([75.0, hp["waist"], math.copysign(fetch.HEAD_SIDE_DEG, deg), +fetch._sweep_blocked = lambda deg, what, pts=None: head_cmd([75.0, hp["waist"], math.copysign(fetch.HEAD_SIDE_DEG, deg), fetch.HEAD_LOW_PITCH]) and False fetch.stay_put = True st, moves = reached(-40.0) @@ -1040,6 +1041,7 @@ st, moves = reached(0.0) # in front: no wai assert st["status"] == "done" and not gaze and hp["yaw"] == 0.0, gaze fetch.stay_put = False fetch.head.status, fetch.head.moveto, fetch._sweep_blocked = real_status, real_move, real_blocked +fetch._route_points = real_route_points fetch._line_rows, fetch._scene = real_line_rows, real_scene hand["front"] = False # the cup is in the hand but nobody says okay: the hand never closes (their fingers may be in it) diff --git a/tests/test_fetch_ways.py b/tests/test_fetch_ways.py index 719bd05..6a6c55b 100644 --- a/tests/test_fetch_ways.py +++ b/tests/test_fetch_ways.py @@ -232,12 +232,12 @@ placed = {"at": None} real_place_at = fetch._place_at -def place_at(tries, top): +def place_at(tries, top, **kw): for p in tries: if col(*p) <= REACH_MM: placed["at"] = p break - return real_place_at(tries, top) + return real_place_at(tries, top, **kw) skills.reachable_pick = reachable @@ -405,4 +405,65 @@ room["cups"].append({"id": 1, "map": np.array([0.15, 0.85])}) st = run(fetch.start, TASK) fetch._look_around = real_around assert st["status"] == "holding" and any("near me at +90 deg" in l for l in st["log"]), st["log"] +# ---------- 2026-10-29 13:50: "take the cup" (voice pick) held it just above the table, "stop", then "put the cup on +# the table": straight back down where it was picked, never to look first ---------- +setup(None, table=(0.355, 1.6, -1.0, 1.0)) +room["holding"] = {"id": 9, "map": None} +fetch._set(holding=True, status="holding", held_object={"object": "cup", "colour": "white"}) +skills._held.update(top_mm=-186.0, x=108.0, y=603.0, yaw=-15.0, table=-330.0, what={"object": "cup"}) +fetch._note_stand() # as pick_here leaves it +lifted = skills.up(skills.plan_place(108.0, 603.0, -186.0, yaw=-15.0)[1][1], skills.LIFT_MM - skills.PLACE_EXTRA_MM) +real_tcp, real_holding, real_place = fetch.motion.tcp, fetch._line_holding, skills._do_place +fetch.motion.tcp = lambda: list(lifted) +arm["j"] = [5.0] * 6 # over the table, not at look +fetch._line_holding = lambda name: (log.append(("line", name)), real_holding(name))[1] +skills._do_place = lambda wp: (do_place(wp), arm.update(j=[0.0] * 6))[0] # the real one ends at look +st = run(fetch.place, None, {"name": "dining table", "colour": None}) +done = [l for l in log if l[0] == "place"] +assert st["status"] == "done" and done == [("place", 108, 603)], (st["log"], log) +assert ("line", "look") not in log and not any("arm to look" in l for l in st["log"]), (st["log"], log) +# ... the base moved since the pick: the usual search from look +setup(None, table=(0.355, 1.6, -1.0, 1.0)) +room["holding"] = {"id": 9, "map": None} +fetch._set(holding=True, status="holding", held_object={"object": "cup", "colour": "white"}) +skills._held.update(top_mm=-186.0, x=108.0, y=603.0, yaw=-15.0, table=-330.0, what={"object": "cup"}) +fetch._note_stand() +base["pose"] = (0.1, 0.0, 0.0) +arm["j"] = [5.0] * 6 +fetch._line_holding = lambda name: (log.append(("line", name)), arm.update(j=[0.0] * 6)) +run(fetch.place) +assert log and log[0] == ("line", "look"), log +fetch.motion.tcp, fetch._line_holding, skills._do_place = real_tcp, real_holding, real_place +arm["j"] = [0.0] * 6 +print("held over the pick spot after a stop: put straight back down at", done[0][1:]) +# ... the STOP came in the 30 mm lift of the voice pick itself (pick_here), the fingers already holding it: the same +setup((108.0, 603.0), table=(0.355, 1.6, -1.0, 1.0)) +def stopped_in_lift(obj, wp, ja): # _do_pick holds it (skills._held) from the close on + do_pick(obj, wp, ja) + raise skills.SkillError("Stopped.") +real_back_out, skills._do_pick = skills.back_out, stopped_in_lift +skills.back_out = lambda: log.append(("back out",)) +fetch.stay_put = True +try: + fetch.pick_here("cup", None) + raise AssertionError("not stopped") +except skills.SkillError: + pass +fetch.stay_put = False +skills._do_pick, skills.back_out = do_pick, real_back_out +assert log[0] == ("back out",) and skills._held.get("base") is not None, (log, skills._held) # out first; stand noted +fetch._set(holding=True, status="holding", held_object={"object": "cup", "colour": None}) +h = skills._held +lifted = skills.up(skills.plan_place(h["x"], h["y"], h["top_mm"])[1][1], skills.LIFT_MM / 2 - skills.PLACE_EXTRA_MM) +fetch.motion.tcp = lambda: list(lifted) +arm["j"] = [5.0] * 6 +log.clear() +fetch._line_holding = lambda name: (log.append(("line", name)), real_holding(name))[1] +skills._do_place = lambda wp: (do_place(wp), arm.update(j=[0.0] * 6))[0] +st = run(fetch.place, None, {"name": "dining table", "colour": None}) +assert st["status"] == "done" and [l for l in log if l[0] == "place"] == [("place", 108, 603)], (st["log"], log) +assert ("line", "look") not in log, log +fetch.motion.tcp, fetch._line_holding, skills._do_place = real_tcp, real_holding, real_place +arm["j"] = [0.0] * 6 +print("stopped in the lift of a voice pick: put straight back down") print("fetch ways ok") diff --git a/tests/test_follow.py b/tests/test_follow.py index 2f55c97..b828a5d 100644 --- a/tests/test_follow.py +++ b/tests/test_follow.py @@ -507,10 +507,12 @@ assert math.degrees(w.th) > 120.0 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.4, (m print(f"past the side to behind: waist + head up to {max(gaze):.0f} deg, base turned {math.degrees(w.th):.0f} deg, " f"gap {w.dist[-1]:.2f} m") -# owner, live: the head waited for a slow stepwise waist and lost the person. Now head, waist and base all at once: -# the person right behind (170 deg) -> the first move puts head + waist on them (the head not held to HEAD_REL_MAX), -# the waist keeps turning move after move while the base turns, the base forward only once they are ahead +# owner, live: the head waited for a slow stepwise waist and lost the person. Now the head and the base at once: the +# person right behind (170 deg) -> the first move puts the head on them (never held to HEAD_REL_MAX), the waist stays +# (it only ever unwinds), the base turns at once, forward only once they are ahead assert follow.waist_for(10.0) == 0.0 and follow.waist_for(-70.0) == -40.0 and follow.waist_for(170.0) == 90.0 +assert follow.unwind(0.0, 170.0) == 0.0 and follow.unwind(-55.0, -169.0) == -55.0 # never further out +assert follow.unwind(60.0, 70.0) == 40.0 and follow.unwind(60.0, 10.0) == 0.0 and follow.unwind(30.0, -90.0) == 0.0 def at(deg, r=2.0): @@ -552,17 +554,16 @@ follow.stop() assert wait_end(0.5) moves = [m for m in body.moves if m[1] == "follow head"] first = moves[0] -assert 0.0 < first[3] <= follow.WAIST_STEP_DEG and first[4] > 90.0 and abs(first[3] + first[4] - 170.0) < 10.0, first +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 -turning = [s for s in samples if 10.0 < s[3] < 90.0] # the base turning ... -assert turning and max(s[1] for s in turning) >= 3 * follow.WAIST_STEP_DEG, turning[:3] # ... the waist too +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 assert ahead and max(abs(a) for a in ahead) <= follow.TURN_ONLY_DEG + 5.0, max(abs(a) for a in ahead) assert abs(body.pos[1]) < 1e-6 and abs(body.pos[2]) <= follow.TURN_DEAD_DEG + follow.HEAD_STEP_DEG, body.pos assert abs(math.degrees(w.th) - 170.0) < 10.0 and w.dist[-1] < follow.FOLLOW_GAP_M + 0.3, (math.degrees(w.th), w.dist[-1]) -print(f"behind 170 deg: first move waist {first[3]:+.0f} head {first[4]:+.0f}, waist up to " - f"{max(s[1] for s in samples):.0f} deg while the base turned, forward only within {max(map(abs, ahead)):.0f} deg") +print(f"behind 170 deg: first move head {first[4]:+.0f}, the waist stays, forward only within " + f"{max(map(abs, ahead)):.0f} deg") # "look behind" turned the waist and the head to the owner, then "follow me": nothing turns away from them said.clear() @@ -579,6 +580,7 @@ print(f"start turned to the owner: gaze off at most {max(abs(s[4]) for s in samp # stopped with the waist turned: it comes back to the front (sweep checked), the head to rest body.moves.clear() +body.pos = [50.0, 60.0, 10.0, follow.HEAD_PITCH] # on them at 70 deg w = at(70.0) follow.TURN_MAX_RS, turn_max = 0.05, follow.TURN_MAX_RS # a slow base follow.start(w.see, say) @@ -590,6 +592,47 @@ follow.TURN_MAX_RS = turn_max assert body.moves[-1][3:] == (0.0, 0.0, head.HEAD_REST_PITCH), body.moves[-1] print("stopped turned: waist back to the front") +# live 2026-10-29 14:18: the person walked round the right side to behind at ~0.75 m (no base turn that near), then +# stepped out and the base turned 0.6 rad/s. Every move also turned the waist further out (a slow ~1 s move), the +# head lagged 30-40 deg, then the base and the waist both turned the same way: off them, lost. With a body as slow as +# the real one the head alone must stay on them: the gaze within 25 deg (the camera sees +-47), the waist never out. + + +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) + 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) + body.pos = goal + body.moves.append((time.time(), threading.current_thread().name, *goal)) + return {"code": 0} + + +def round_right(t): + a = math.radians(-20.0 - 25.0 * min(t, 6.0)) + r = 0.75 + 0.3 * min(max(t - 6.0, 0.0), 2.0) + return r * math.cos(a), r * math.sin(a) + + +said.clear() +body.moves.clear() +body.pos = [50.0, 0.0, -20.0, follow.HEAD_PITCH] +head._call = real_body +w = World(path=round_right, fov=True) +samples, _ = watch(w, 12.0) +follow.stop() +assert wait_end(3.0) and not said, said +head._call = body.call +off = max(abs(s[4]) for s in samples) +assert off < 25.0, max(samples, key=lambda s: abs(s[4])) +assert all(abs(s[1]) < 1e-6 for s in samples), max(samples, key=lambda s: abs(s[1])) # the waist never out +assert math.degrees(w.th) < -120.0, math.degrees(w.th) # the base came round +print(f"round the side to behind, slow body: gaze off at most {off:.0f} deg, base turned {math.degrees(w.th):.0f} deg") + # the arm's sweep blocked for the waist, or the arm not in look: the waist stays, the head alone goes on them turn_hits = fetch.turn_hits for why in ("sweep", "not look"): @@ -647,7 +690,7 @@ follow.start = lambda see, say=None, people=None: started.append(see) track = types.SimpleNamespace(id=7, distance=1.8, angle=10.0, greeted=False, history=[1.7], last_seen=time.time(), look=None) L.lang, L.voice_angle, L.voice_trusted = "en", 0.0, False -L.modes = types.SimpleNamespace(drive=True, patrol=True) +L.modes = types.SimpleNamespace(patrol=True) L.skill_busy = lambda: False L.keep_listening = lambda: None L.fetch_say = lambda en, ko: spoken.append(en) @@ -670,10 +713,7 @@ L.follow_me() assert started and L.current is track L.voice_trusted = False started.clear() -L.modes.drive = False -L.follow_me() -assert not started and "switched off" in spoken[-1] -L.modes.drive, L.skill_busy = True, lambda: True +L.skill_busy = lambda: True L.follow_me() assert not started and "on a task" in spoken[-1] L.skill_busy, real_ready = (lambda: False), follow.ready diff --git a/tests/test_give_together.py b/tests/test_give_together.py new file mode 100644 index 0000000..d503d2e --- /dev/null +++ b/tests/test_give_together.py @@ -0,0 +1,125 @@ +"""Self-check of "give me your hand" with a waist turn (tasks/fetch.py reach, _give_turning): the waist and the arm +move together (the waist command goes out before the arm route ends, the arm starts before the waist is there), the +sweep is checked with the hand at every pose of the route over the whole turn (refused when only the route's pose +would hit something), and STOP ends both. Fake body, arm and map, no robot: python tests/test_give_together.py""" +import json +import math +import tempfile +import threading +import time +from pathlib import Path + +import no_robot # noqa: F401 any connection to the robot fails the test +from robot import motion +from tasks import fetch + +tmp = Path(tempfile.mkdtemp()) +fetch.STATE_FILE = tmp / "lumi_task.json" +fetch.CALIB_FILE = tmp / "base_axis.json" +fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": 0.0, "arm_xy_in_base_m": [0.0, 0.0], "waist_deg": 0.0})) +fetch.log = lambda *a: None + +body = {"pos": [0.0, 0.0, 0.0, 0.0]} # lift, waist, head yaw, head pitch +events = [] # (time, what) +CHUNK_S = 0.15 # s one fake waist move takes + + +def moveto(pos, **kw): + events.append((time.time(), "waist start", pos[1])) + time.sleep(CHUNK_S) + body["pos"] = list(pos) + events.append((time.time(), "waist end", pos[1])) + return {"status": 0} + + +fetch.head.moveto = moveto +fetch.head.status = lambda: list(body["pos"]) +fetch.skills.moved = lambda *a, **k: None +fetch.skills.objects.base_from_camera = lambda: None # no depth: the lidar / map check decides +fetch.head_cam.base_from_head = lambda yaw, pitch: None +fetch.agv.pose = lambda: (0.0, 0.0, 0.0) +fetch.motion.poses = lambda: {"give": [2.0] * 6, "give_pre": [1.0] * 6, "look": [0.0] * 6} +fetch._person_point = lambda: ((0.0, 600.0, 0.0), 100.0) +fetch._reach_to_hand = lambda *a: events.append((time.time(), "hand")) +joints = {"now": [0.0] * 6} +fetch.skills._joints = lambda: list(joints["now"]) +fetch.arm_points_3d = lambda j=None: [(500.0 * math.cos(math.radians(45.0 * (joints["now"] if j is None else j)[0])), + 500.0 * math.sin(math.radians(45.0 * (joints["now"] if j is None else j)[0])), + 0.0)] * 3 # j0 0 / 1 / 2 (look, give_pre, give): the hand at 0 / 45 / 90 deg +SEQ = [("give_pre", [1.0] * 6), ("give", [2.0] * 6)] +fetch.arm_route.plan = lambda target, holding=False, leaf=False, now=None: list(SEQ) +arm_stop = threading.Event() + + +def arm_move(seq, speed=None, holding=False): + events.append((time.time(), "arm start")) + for _, j in seq: + if arm_stop.wait(0.2): + raise motion.MotionError("stopped") + joints["now"] = list(j) + events.append((time.time(), "arm end")) + + +fetch.arm_route.move = arm_move +fetch.skills.cancel = lambda: arm_stop.set() +fetch.agv.cancel = lambda: None +obstacle = {"at": None} +fetch.agv.clearance = lambda x, y: 0.0 if obstacle["at"] and math.dist((x, y), obstacle["at"]) < 0.05 else 1.0 + + +def when(what): + return [e[0] for e in events if e[1] == what] + + +def reset(): + events.clear() + body["pos"] = [0.0, 0.0, 0.0, 0.0] + joints["now"] = [0.0] * 6 + arm_stop.clear() + + +# ---------- clear: waist and arm together, the head stays on the person ---------- +reset() +fetch.reach(30.0, look=30.0) +fetch._thread.join(10) +st = fetch.state() +assert st["status"] == "done", st +w0, arm0, arm1, w1 = when("waist start")[0], when("arm start")[0], when("arm end")[0], when("waist end")[-1] +assert w0 <= arm0 < arm1, events # the waist command went out first, before the arm route ended +assert arm0 < w1, events # the arm started before the waist got there +assert len(when("waist start")) == math.ceil(30.0 / fetch.WAIST_STEP_DEG), events +assert abs(body["pos"][1] - 30.0) < 1e-6 and abs(body["pos"][2]) < 1e-6, body # waist 30, head yaw 30 - 30 = 0 +assert events[-1][1] == "hand" and joints["now"] == [2.0] * 6 + +# ---------- only the give pose, turned, meets something: refused, nothing moves ---------- +reset() +obstacle["at"] = (500.0 * math.cos(math.radians(120.0)) / 1000.0, 500.0 * math.sin(math.radians(120.0)) / 1000.0) +assert fetch.turn_hits(30.0) is None # the old check (the hand where it is now) sees nothing +fetch.reach(30.0, look=30.0) +fetch._thread.join(10) +st = fetch.state() +assert st["status"] == "failed" and not events and joints["now"] == [0.0] * 6, (st, events) +obstacle["at"] = None + +# ---------- STOP while both move: the arm stops now, the waist after the move it is in ---------- +reset() +fetch.reach(40.0, look=40.0) +time.sleep(0.1) +assert when("arm start") and when("waist start"), events +t = time.time() +fetch.end() +assert time.time() - t < 1.0 and not fetch._busy() +time.sleep(3 * CHUNK_S) # nothing more is sent after the move in progress +assert arm_stop.is_set() and not when("arm end"), events +assert len(when("waist start")) <= 2 and all(s < t + 0.05 for s in when("waist start")), events +assert fetch.state()["status"] == "stopped" and body["pos"][1] < 40.0 + +# ---------- no turn: only the arm (the plain route) ---------- +reset() +posed = [] +real_pose, fetch._pose = fetch._pose, lambda name, **k: posed.append(name) +fetch.reach(0.0) +fetch._thread.join(5) +assert posed == ["give"] and not when("waist start") and fetch.state()["status"] == "done" +fetch._pose = real_pose +print("give together ok (ordering, route sweep refusal, stop ends both, no turn)") diff --git a/tests/test_gripper.py b/tests/test_gripper.py index 20d08b6..6bfa622 100644 --- a/tests/test_gripper.py +++ b/tests/test_gripper.py @@ -2,9 +2,9 @@ import no_robot # noqa: F401 any connection to the robot fails the test from robot import gripper as g -assert g.gap_mm(g.AI_OPEN) == 94.0 and g.gap_mm(g.AI_SHUT) == 68.0 # belly, open / closed (tape) -assert g.gap_mm(50) == 94.0 and g.gap_mm(5000) == 68.0 # readings past the ends are clamped -assert abs(g.gap_mm((g.AI_OPEN + g.AI_SHUT) / 2) - 81.0) < 0.01 # linear between -assert g.gap_mm(g.AI_SHUT, "tips") == 63.0 and g.gap_mm(g.AI_OPEN, "shank") == 66.0 +assert g.gap_mm(g.AI_OPEN) == 102.0 and g.gap_mm(g.AI_SHUT) == 77.0 # belly, open / closed (owner) +assert g.gap_mm(50) == 102.0 and g.gap_mm(5000) == 77.0 # readings past the ends are clamped +assert abs(g.gap_mm((g.AI_OPEN + g.AI_SHUT) / 2) - 89.5) < 0.01 # linear between +assert g.gap_mm(g.AI_SHUT, "tips") == 73.0 and g.gap_mm(g.AI_OPEN, "shank") == 66.0 assert all(hasattr(g, n) for n in ("MOVE_S", "SENSOR_DI", "READ_TRIES", "READ_GAP_S", "CLOSED_AI", "EMPTY_AI")) print("gripper ok") diff --git a/tests/test_look_me.py b/tests/test_look_me.py index 855db73..b1a9915 100644 --- a/tests/test_look_me.py +++ b/tests/test_look_me.py @@ -125,7 +125,7 @@ fetch._waist_to = fake_waist_to L = lumi.Lumi.__new__(lumi.Lumi) L.vision, L.current = Vision([]), None L.voice_angle, L.voice_trusted = 170.0, True -L.modes = type("M", (), {"drive": True, "patrol": False})() +L.modes = type("M", (), {"patrol": False})() turns.clear() L.look_at_speaker() assert waist["calls"] == [(120, True, 170.0)], waist diff --git a/tests/test_reach_live.py b/tests/test_reach_live.py index ed315b4..41799ec 100644 --- a/tests/test_reach_live.py +++ b/tests/test_reach_live.py @@ -11,6 +11,7 @@ import threading import time from pathlib import Path +import no_robot # noqa: F401 any connection to the robot fails the test from assistant import brain from tasks import fetch @@ -45,6 +46,10 @@ fetch._pose = lambda name: moved.append(name) fetch._person_point = lambda: ((0.0, 600.0, 0.0), 100.0) fetch._reach_to_hand = lambda *a: moved.append("hand") fetch._sweep_blocked = lambda *a, **k: False # never the real base's pose and map (it failed at the charger) +fetch._route_points = lambda seq: [] +real_route = (fetch.arm_route.plan, fetch.arm_route.move) +fetch.arm_route.plan = lambda target, holding=False, leaf=False, now=None: [(target, [0] * 6)] +fetch.arm_route.move = lambda seq, speed=None, holding=False: moved.append("route " + seq[-1][0]) fetch.reach(-22.7) time.sleep(0.3) @@ -57,12 +62,14 @@ except fetch.FetchError as e: t = time.time() fetch.end() # "stop" / a new command assert time.time() - t < 1.0 and not fetch._busy(), "stop waited for the hung body call" -assert fetch.state()["status"] == "stopped" and moved == [] +assert fetch.state()["status"] == "stopped" and moved == ["route give"] # the arm went with the hung waist turn +moved.clear() hung.set() # the body answers again fetch.reach(0.0) # the next "give me your hand": starts, not "busy" fetch._thread.join(2) assert moved == ["give", "hand"] and fetch.state()["status"] == "done", (moved, fetch.state()["status"]) +fetch.arm_route.plan, fetch.arm_route.move = real_route # ---------- closed on nothing is empty, whatever the camera sees ---------- grip = {"ai": [4153.0, 489.0], "holding": False} # the live close of 17:40:39 fetch.gripper.state = lambda: dict(grip) diff --git a/tests/test_robot_free.py b/tests/test_robot_free.py index 60833bb..87665ae 100644 --- a/tests/test_robot_free.py +++ b/tests/test_robot_free.py @@ -39,6 +39,10 @@ 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 +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() + # idle, Patrol on: allowed server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": True})) task("idle") diff --git a/tests/test_skills.py b/tests/test_skills.py index 638c61d..c5599a2 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -31,7 +31,7 @@ for yaw in (-30, 45): # a t p = dict(skills.plan_place(-200, 600, cup["top_mm"], yaw=yaw))["place"] assert np.allclose(np.array(p[:3]) + calib.rpy_matrix(*p[3:]) @ skills.GRASP_OFFSET, [-200, 600, g[2] + 3]) -for bad in (88, 30, 50): # seen widths: +SEEN_UNDER_MM over 92, under 61 +for bad in (95, 30, 50): # seen widths: +SEEN_UNDER_MM over 97, under 61 try: skills.plan_pick({**cup, "width_mm": bad}) raise AssertionError(f"width {bad} accepted") @@ -221,7 +221,7 @@ skills.flat_points = real_flat print("skills fresh / flat ok") # ---------- a pick stores what put down needs: the table under the object, also when its bottom was not in view ------ -skills._prepare = lambda: None +real_prepare, skills._prepare = skills._prepare, lambda: None skills._cancel.clear() # cancel() above skills.motion.move_joints = lambda j, speed=None: None skills.gripper.close = lambda: {"ai": [3500.0], "holding": True, "object_in_front": False} @@ -365,29 +365,29 @@ print("skills on_table ok") # ---------- side grasp: a cup too wide at the top for the hooks to come down over it, narrower lower down ---------- top = cup["top_mm"] -wide = {**cup, "width_mm": 90.0, "height_mm": 120.0, # 98 the fingers would meet: over MAX_WIDTH - "profile": [(top - 10.0 * i, 88.0 if i < 4 else 72.0) for i in range(12)]} # 96 at the rim, 80 from 40 mm down +wide = {**cup, "width_mm": 92.0, "height_mm": 120.0, # 100 the fingers would meet: over MAX_WIDTH + "profile": [(top - 10.0 * i, 100.0 if i < 4 else 72.0) for i in range(12)]} # 100 at the rim, 72 from 40 mm down assert skills.side(wide) and not skills.side(cup) d = skills.tips_dir() assert np.isclose(np.linalg.norm(d), 1.0) and d[1] > 0.5 # the tips point away from the robot z = skills.side_height(wide) assert z == top - 65.0, z # nearest SIDE_AT of its 120 mm (50 mm up, top - 70) where the band is all 72 short = {**wide, "top_mm": top - 50.0, "height_mm": 70.0, # a 70 mm cup on the same table - "profile": [(top - 50.0 - 10.0 * i, 88.0 if i < 2 else 74.0) for i in range(7)]} + "profile": [(top - 50.0 - 10.0 * i, 100.0 if i < 2 else 74.0) for i in range(7)]} assert skills.side_height(short) == top - 50.0 - 45.0 # 25 mm up: the hooks' bottom 17 over it way = skills.plan_pick(wide) assert [n for n, _ in way] == ["above", "side", "grasp", "lift"], way p = dict(way) assert np.isclose(p["side"][2], p["grasp"][2]) and p["side"][3:] == p["grasp"][3:] # in level at the grasp height back = skills.side_back(wide) -assert np.isclose(back, 98.0 / 2 + np.linalg.norm(skills.TIPS_OFFSET) + skills.SIDE_CLEAR_MM) +assert np.isclose(back, 100.0 / 2 + np.linalg.norm(skills.TIPS_OFFSET) + skills.SIDE_CLEAR_MM) assert np.allclose(np.subtract(p["grasp"][:2], p["side"][:2]), d * back) # it goes in along the tips' direction assert np.allclose(np.subtract(p["above"][:3], p["side"][:3]), [0, 0, skills.clear_above(top - z)]) g = np.array(p["grasp"][:3]) + calib.rpy_matrix(*p["grasp"][3:]) @ skills.GRASP_OFFSET assert np.allclose(g, [wide["x"], wide["y"], z]) # the hooks' point on the cup axis assert [n for n, _ in skills.plan_pick(cup)] == ["above", "grasp", "lift"] # a cup whose top fits: from above, as before -for bad in ([(top - 10.0 * i, 88.0) for i in range(12)], # wide all the way down - [(top - 10.0 * i, 88.0 if i < 10 else 72.0) for i in range(12)], # narrow only where the hooks hit the table +for bad in ([(top - 10.0 * i, 100.0) for i in range(12)], # wide all the way down + [(top - 10.0 * i, 100.0 if i < 10 else 72.0) for i in range(12)], # narrow only where the hooks hit the table None): # its widths down its height not measured try: skills.plan_pick({**wide, "profile": bad}) @@ -428,3 +428,74 @@ assert [n for n, _ in lines_] == ["side", "grasp", "out sideways", "up"], lines_ assert np.allclose(np.subtract(p["grasp"][:2], lines_[2][1][:2]), d * back) skills._held.clear() print("skills side grasp ok") + +# ---------- a pick stopped on its way in (the open hand beside / around the cup): the next pick backs out the way it +# came first, never a diagonal move from there; a stop once the fingers hold it leaves it ready to put down ---------- +def stop_at(where, at): # STOP while moving to waypoint `where`: the hand ends at `at` + def line(name, pose): + lines_.append((name, pose)) + if name == where: + skills.motion.tcp = lambda: list(at) + raise skills.SkillError("Stopped.") + skills.motion.tcp = lambda: list(pose) + return line +skills.gripper.close = lambda: {"ai": [3500.0], "holding": True, "object_in_front": False} +skills.gripper.state = lambda: {"ai": [150.0], "holding": False} # open: the stop came before the close +skills._joints = skills.home_joints = lambda: [0.0] * 6 # back at home after backing out: no route +mid = list(np.add(p["side"], p["grasp"]) / 2) # half way in, beside the cup +for way_, where, at, want in ((way, "grasp", mid, ["out sideways", "up"]), # side grasp, half way in + (way, "grasp", p["grasp"], ["out sideways", "up"]), # ... around it + (way, "side", p["side"], ["up"]), # ... still coming down + (skills.plan_pick(cup), "grasp", grasp, ["up"])): # down around it from above + w = dict(way_) + skills._held.update(top_mm=-1.0, x=0.0, y=0.0) # from an earlier pick + lines_.clear() + skills._line = stop_at(where, at) + try: + skills._do_pick(wide if "side" in w else cup, way_, READY) + raise AssertionError("not stopped") + except skills.SkillError: + pass + try: # "put it down": nothing is held, nothing moves + skills.put_down() + raise AssertionError("put down with an open hand") + except skills.SkillError as e: + assert e.args[0] == "I'm not holding anything I picked.", e.args + lines_.clear() + real_prepare() # "take the cup" again + assert [n for n, _ in lines_] == want, (where, lines_) + out, top_ = lines_[-2][1] if len(lines_) > 1 else at, lines_[-1][1] + start_ = w.get("side", w["grasp"]) + assert np.allclose(out[:3], [start_[0], start_[1], at[2]], atol=1e-6), (out, start_) # out along the way in + assert np.allclose(top_[:3], [start_[0], start_[1], w["above"][2]], atol=1e-6) # then straight up to above + lines_.clear() + real_prepare() # backed out once: nothing more + assert not lines_, lines_ +skills.motion.tcp = lambda: [0.0, 300.0, 0.0] + list(skills.GRASP_RPY) # moved away since (another task): no lines +skills._line = stop_at("grasp", grasp) +try: + skills._do_pick(cup, skills.plan_pick(cup), READY) +except skills.SkillError: + pass +skills.motion.tcp = lambda: [0.0, 300.0, 0.0] + list(skills.GRASP_RPY) +lines_.clear() +real_prepare() +assert not lines_ and not skills._pick_way, lines_ +# STOP in the lift, the fingers holding it: put down knows it (as at the end of a pick), the next pick backs out nothing +for way_, obj_ in ((way, wide), (skills.plan_pick(cup), cup)): + skills._held.clear() + skills._line = stop_at("lift", dict(way_)["grasp"]) + try: + skills._do_pick(obj_, way_, READY) + raise AssertionError("not stopped") + except skills.SkillError: + pass + assert skills._held["top_mm"] == obj_["top_mm"] and np.isclose(skills._held["back"], back if obj_ is wide else 0.0) + assert np.isclose(skills._held["below"], obj_["top_mm"] - skills.grasp_height(obj_)) and not skills._pick_way + placed = [] + real_place_first, skills._place_first = skills._place_first, lambda tries, refusal: placed.append(tries[0]) + skills.put_down(back=True) + skills._place_first = real_place_first + assert placed == [(obj_["x"], obj_["y"])], placed +skills._held.clear() +print("skills stopped pick ok") diff --git a/tests/test_stop_live.py b/tests/test_stop_live.py index 92d0ee1..6dae00f 100644 --- a/tests/test_stop_live.py +++ b/tests/test_stop_live.py @@ -127,13 +127,13 @@ lumi.head.status = lambda: [0, 0, 0, 0] lumi.nav.person_on_map = lambda *a: (3.0, 0.0) lumi.nav.approach = lambda *a: (2.0, 0.0, 0.0) L = fresh(U("Stop!"), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {})(), lambda *a, **k: None base["move_status"] = "running" t = time.time() L.come_to(Track()) assert stopped(L) and time.time() - t < 3, done L = fresh(U("What is your name?"), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {})(), lambda *a, **k: None base["move_status"] = "running" threading.Timer(1.0, lambda: base.update(move_status="succeeded")).start() L.come_to(Track()) @@ -142,7 +142,7 @@ assert "agv cancel" not in done and L.pending_text == "What is your name?", done # right after Lumi said "Okay, I stopped.", "Stop." is no echo of it (own_echo counts "stop" in "stopped") lumi.mouth.recent_speech = lambda s: "Okay, I stopped. Let's go to p5." L = fresh(U("Stop."), trip=False) -L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {"drive": True})(), lambda *a, **k: None +L.vision, L.modes, L.turn_head = Vision(), type("Modes", (), {})(), lambda *a, **k: None base["move_status"] = "running" L.come_to(Track()) assert stopped(L), done diff --git a/tests/test_switches.py b/tests/test_switches.py index d47b2f7..e56049a 100644 --- a/tests/test_switches.py +++ b/tests/test_switches.py @@ -55,7 +55,7 @@ DOES = {"go_to": "start_trip", "follow": "follow_me", "come": "come_to", "move": "look": "look", "lift": "lift"} # ---------- Greeter only: the base refused aloud (no "Okay" first), everything in place done ---------- -L.modes = types.SimpleNamespace(greeter=True, patrol=False, drive=True, wave=True) +L.modes = types.SimpleNamespace(greeter=True, patrol=False, wave=True) for text in BASE: moved.clear() said.clear() @@ -211,10 +211,10 @@ L.vision.present = lambda t: True L.come_to = lambda t: came.append(t.id) or setattr(t, "distance", 1.1) reached.clear(), said.clear() assert L.reach_out(False) and came == [8] and reached == [21.0], (came, reached) -person.distance, L.modes.drive = 3.0, False # far and driving switched off: asked to come, no reach +person.distance, L.modes.patrol = 3.0, False # far, Greeter only (the base stays): asked to come, no reach reached.clear(), said.clear(), came.clear() assert L.reach_out(False) is None and not reached and not came and said == [lumi.COME_CLOSER_SAY[0]], (said, reached) -L.modes.drive, person.distance = True, 1.0 +L.modes.patrol, person.distance = True, 1.0 fetch.give_bearing = lambda: 0.0 L.turn_head = lambda *a, **k: moved.append("head") seen_vision, L.vision = L.vision, None # nobody seen, the voice's direction not trusted: ask @@ -278,7 +278,7 @@ P = lumi.Patrol(["p3"]) P.tick(force=True) assert order == ["waist", ("go", "home")] and P.mode == "going_home", order lumi.agv.status = lambda: {"move_status": "idle", "power_percent": 90} -L.modes.patrol, L.modes.drive = True, True +L.modes.patrol = True real_turned, lumi.waist_turned = lumi.waist_turned, lambda: 30.0 # turned 30 left for someone order.clear() L.look_toward(150.0) # a voice behind: the base turns to it from the base's front @@ -294,5 +294,13 @@ assert order == ["waist"], order lumi.waist_home, lumi.waist_turned = real_home, real_turned for name in ("status", "go", "go_point", "turn_by"): setattr(lumi.agv, name, forbid) +# a modes file from before "Come when called" was dropped still loads; its "drive" key is ignored +import json, tempfile, os +with tempfile.TemporaryDirectory() as tmp: + lumi.MODES_FILE = os.path.join(tmp, "lumi_modes.json") + json.dump({"greeter": True, "patrol": True, "wave": False, "drive": False}, open(lumi.MODES_FILE, "w")) + m = lumi.Modes(types.SimpleNamespace(patrol=None, no_arm=False)) + assert (m.greeter, m.patrol, m.wave) == (True, True, False) and not hasattr(m, "drive"), vars(m) + print(f"switches ok: {len(BASE)} base phrases refused with Greeter only, {len(IN_PLACE)} in place done; " "arm off asks; Patrol allows all; stop always") diff --git a/tests/test_wave.py b/tests/test_wave.py index 3f87b84..847e3d5 100644 --- a/tests/test_wave.py +++ b/tests/test_wave.py @@ -196,6 +196,39 @@ assert L.wave() is True and said == [] and not fetch.state()["holding"], said wave.wave = real_wave fetch.STATE_FILE.unlink() +# ---------- the arm moves while the words are said, never after them (wave, open / close) ---------- +gate, order = threading.Event(), [] + + +def slow_say(text, **k): # speech that ends only when the test says so + order.append(("say", text)) + gate.wait(30) + + +lumi.mouth = types.SimpleNamespace(say=slow_say) +L.lang = "en" +wave.wave = lambda on_start=None: (on_start(), order.append("move")) +done = [] +th = threading.Thread(target=lambda: done.append(L.wave(("Okay!", "네!")))) +th.start() +th.join(10) +assert done == [True] and "move" in order, (done, order) # waved with the words still being said +gate.set() +wave.wave = real_wave +gate.clear(), order.clear() +L.arm_pose = lambda target: order.append("gripper") or True +L.base_off = lambda *a, **k: False +L.arm_off = lambda: False +L.brain = types.SimpleNamespace(history=[]) +th = threading.Thread(target=L.quick_command, args=("open your hand", ("arm", "open"))) +th.start() +th.join(1) +assert "gripper" in order and th.is_alive(), order # the gripper started while the words go on +gate.set() +th.join(5) +del L.arm_pose, L.base_off, L.arm_off +lumi.mouth = types.SimpleNamespace(say=lambda text, **k: said.append(text)) + # ---------- "bye bye" to the person in view: a (quiet) wave beside the goodbye; else only the goodbye ---------- waves = [] L.wave = lambda **k: waves.append(k)