diff --git a/README.md b/README.md index 756f38a..6fc11e0 100644 --- a/README.md +++ b/README.md @@ -37,10 +37,10 @@ Jetson AGX Thor inside the robot and turns it into a conversational service robo | **Answer questions** | About itself and Cutshion, and about the world with live information from the internet, in English or Korean. | | **Describe what it sees** | People, clothing, gestures, what someone is holding, and objects around it. | | **Follow a person** | Walks with a visitor at their pace and keeps them in view. | -| **Go to places** | Drives to any named location on the map or to a spot a person points at, patrols a route, and returns to its dock to charge. | -| **Fetch and deliver** | Picks up a cup or bottle, brings it to a person or a place, puts it down, or hands it over. | +| **Go to places** | Drives to any named location on the map or to a spot a person points at, patrols a route there and back until stopped, and returns to its dock to charge. | +| **Fetch and deliver** | Picks up a cup or bottle, brings it to a person or a place, puts it down, or hands it over. Carries a bag hung on its hand to a named place and hands it over on request. | | **Run missions** | Carries out several steps from one spoken request, such as fetching an item, delivering it and passing on a message. | -| **Sing and gesture** | Sings songs from its repertoire, waves when asked, and waves back at people who wave at it from up to 3 m, turning to face them and greeting them. | +| **Sing and gesture** | Sings songs from its repertoire, waves when asked, and waves back at people who wave at it from up to 3 m, turning to face them and greeting them. Holds out its hand on request. While waiting at its dock it keeps its hand raised, waves to passers-by now and then and follows them with its head. With the wave greeting on it drives with its hand raised and stops on the way to wave at people. | --- @@ -225,10 +225,10 @@ Lumi는 쿳션이 개발한 **JAKA Lumi** 모바일 매니퓰레이터용 소프 | **질문 답변** | 자신과 쿳션에 대한 질문은 물론, 인터넷의 실시간 정보로 세상의 다양한 질문에 영어나 한국어로 답합니다. | | **보이는 것 설명** | 사람, 옷차림, 제스처, 손에 든 물건, 주변 사물을 설명합니다. | | **사람 따라가기** | 방문객의 걸음에 맞춰 함께 이동하며 계속 지켜봅니다. | -| **장소 이동** | 지도에 있는 어느 장소나 사람이 가리키는 곳으로 이동하고, 순찰하며, 충전 도크로 돌아갑니다. | -| **가져오기와 전달** | 컵이나 병을 집어 사람이나 장소로 가져가고, 내려놓거나 건네줍니다. | +| **장소 이동** | 지도에 있는 어느 장소나 사람이 가리키는 곳으로 이동하고, 멈출 때까지 경로를 왕복 순찰하며, 충전 도크로 돌아갑니다. | +| **가져오기와 전달** | 컵이나 병을 집어 사람이나 장소로 가져가고, 내려놓거나 건네줍니다. 손에 건 가방을 지정한 장소로 옮기고, 요청하면 건네줍니다. | | **미션 수행** | 물건 가져오기, 전달하기, 메시지 전하기처럼 한 번의 요청으로 여러 단계를 수행합니다. | -| **노래와 제스처** | 레퍼토리의 노래를 부르고, 요청하면 손을 흔들며, 3 m 안에서 손을 흔드는 사람에게는 몸을 돌려 마주 보고 인사하며 함께 손을 흔듭니다. | +| **노래와 제스처** | 레퍼토리의 노래를 부르고, 요청하면 손을 흔들며, 3 m 안에서 손을 흔드는 사람에게는 몸을 돌려 마주 보고 인사하며 함께 손을 흔듭니다. 요청하면 손을 내밉니다. 충전 독에서 대기하는 동안에는 손을 든 채 지나가는 사람들에게 가끔 손을 흔들고 고개로 그들을 따라 봅니다. 손 인사가 켜져 있으면 손을 든 채 이동하며, 가는 길에 멈춰 사람들에게 손을 흔듭니다. | --- diff --git a/api/dashboard.html b/api/dashboard.html index 50558f3..2f3d02a 100644 --- a/api/dashboard.html +++ b/api/dashboard.html @@ -229,6 +229,8 @@ input[type=color]{width:30px;height:28px;border:1px solid var(--line);border-rad

Go to

+
+
@@ -726,7 +728,7 @@ $("goBtn").onclick = e => { const stops = destDD.values, name = n => n === "home" ? "the dock" : n; if (!stops.length) return note("Choose a place first"); if (stops.length === 1) return act(e.target, () => api("/agv/go", {marker: stops[0]})); - act(e.target, () => api("/agv/route", {markers: stops, pause: +$("pause").value || 0})); + act(e.target, () => api("/agv/route", {markers: stops, pause: +$("pause").value || 0, loop: $("loop").checked, rounds: +$("rounds").value || 0})); }; $("dockBtn").onclick = e => act(e.target, () => api("/agv/go", {marker: "home"})); $("cancelBtn").onclick = e => act(e.target, () => api("/agv/cancel", {})); diff --git a/api/server.py b/api/server.py index 61fe600..30e05e6 100644 --- a/api/server.py +++ b/api/server.py @@ -281,6 +281,9 @@ def go(body: GoBody): class RouteBody(BaseModel): markers: list[str] = Field(examples=[["p1", "p3", "home"]], min_length=1) pause: float = Field(1.0, ge=0, le=60, description="seconds to wait at each marker") + loop: bool = Field(False, description="there and back again (a, b, c, b, a, ...); needs the assistant " + "(Greeter / Patrol on)") + rounds: int = Field(0, ge=0, le=99, description="with loop: this many times there and back, 0 = until stopped") class RouteRunner: @@ -333,8 +336,10 @@ def go_route(body: RouteBody): if unknown: raise HTTPException(400, f"unknown markers {unknown}; markers: {names}") if assistant_pids(): - send_to_assistant("route", markers=body.markers, pause=body.pause) + send_to_assistant("route", markers=body.markers, pause=body.pause, loop=body.loop, rounds=body.rounds) return {"ok": True, "route": body.markers, "by": "assistant"} + if body.loop: + raise HTTPException(409, SWITCHES_OFF) held_to_look() _route.start(body.markers, body.pause) return {"ok": True, "route": body.markers, "by": "api"} diff --git a/assistant/lumi.py b/assistant/lumi.py index ee071ff..9da140f 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -228,8 +228,9 @@ def on_charger(): def waist_home_rest(why): """On the charger with nothing to do (after a drive home, at a conversation's end): the empty arm slowly from its rest (arm_route.REST) to look and the waist to HOME_WAIST_DEG (owner, 2026-11-04); every order that moves the arm - or the base takes it to REST first again (waist_home fold). Checked like every move. Not while a task runs, with - something in the hand or the arm out (a hand held out). True when both are there.""" + or the base takes it to REST first again (waist_home fold). With the wave greeting on and the hand up, the waist + turns with the hand kept up (owner, 2026-11-07). Checked like every move. Not while a task runs, with something in + the hand or the arm out (a hand held out). True when both are there.""" from tasks import fetch if not on_charger(): return False @@ -240,7 +241,10 @@ def waist_home_rest(why): log(f" arm and waist stay ({why}): a task runs or something is in my hand") return False fetch._stop.clear() - if not fetch._at_pose(arm_route.HOME): + if wave_greet_on() and arm_route.where() in arm_route.WAVE_POSES: + wave_greet._quiet(10.0) # the hand up for the greeting: the waist turns with it up, + # its swings ended first + elif not fetch._at_pose(arm_route.HOME): if not fetch._at_pose(arm_route.rest_pose()): log(f" arm and waist stay ({why}): my arm is out") return False @@ -260,34 +264,58 @@ def waist_home(why, fold=False): limits. Not while a task runs (it turns the waist itself) or the arm is out of its rest (a hand held out): logged, the waist stays, unless `fold` (an order to drive or turn): something held goes to look first wherever the waist is (fetch.drive_ready: straight checked lines, holding speed), an empty arm to its rest (arm_route.REST, owner - 2026-11-04) along the checked pose graph. True when the waist is at the front (and the arm at its rest).""" + 2026-11-04; look for a drive, fetch.drive_arm, owner 2026-11-07) along the checked pose graph; with the wave + greeting on, the empty arm drives with the hand up (wave_greet.raise_for_drive, owner 2026-11-07). True when the + waist is at the front (and the arm at its rest or up for the drive).""" from tasks import fetch with _waist_lock: try: - if fold: - wave_greet.lower() # a hand up for a wave greeting comes down before any drive holding, running = fetch.state().get("holding"), fetch.state().get("status") == "running" + empty = fold and not holding and not running if fold and holding: fetch.drive_ready() # a drive with the cup held out in carry / give: never - if fold and not holding and not running and not fetch._at_pose(rest := arm_route.rest_pose()): - log(f" arm to {rest} first ({why})") # every drive and turn starts with the empty arm at rest - arm_route.move(arm_route.plan(rest, holding=False), None, False) # (a bag on the hooks too), - if abs(fetch._waist_turn()) < 1.0: # wherever the waist is - return True - if running: - log(f" waist stays turned ({why}): a task runs") - return False - rest = arm_route.rest_pose(holding) # look with a cup; look on the charger too (waist_home_rest) - if not fetch._at_pose(rest) and not fetch._at_pose(arm_route.HOME): - log(f" waist stays turned ({why}): my arm is not at {rest}") - return False - fetch._stop.clear() # no task runs: an old stop must not end this; a new one does - if fetch._waist_to(0.0, in_place=True): + if empty and abs(fetch._waist_turn()) >= 1.0 and wave_greet.front_hand_up(): + log(f" waist to the front with the hand up ({why})") + if empty and abs(fetch._waist_turn()) >= 1.0: # turned (the rest at home): the waist comes round with + wave_greet.lower() # the arm at its rest, its smallest sweep (in look it hit + if not fetch._at_pose(rest := arm_route.rest_pose()): # the wall behind the dock) + log(f" arm to {rest} first ({why})") + arm_route.move(arm_route.plan(rest, holding=False), None, False) + if abs(fetch._waist_turn()) >= 1.0: + if running: + log(f" waist stays turned ({why}): a task runs") + return False + rest = arm_route.rest_pose(holding) # look with a cup; look on the charger too (waist_home_rest) + if not fetch._at_pose(rest) and not fetch._at_pose(arm_route.HOME): + log(f" waist stays turned ({why}): my arm is not at {rest}") + return False + fetch._stop.clear() # no task runs: an old stop must not end this; a new one does + if not fetch._waist_to(0.0, in_place=True): + return False log(f" waist to the front ({why})") - return True + if empty: + _drive_arm(why) + return True except Exception as e: log(f" waist stays turned ({why}): {e!r}") return False + + +def _drive_arm(why): + """The empty arm for a drive, the waist at the front: the hand up with the wave greeting on (wave_greet. + raise_for_drive), else look (fetch.drive_arm; its rest with a bag on the hooks).""" + from tasks import fetch + try: + if wave_greet.raise_for_drive(): + return + except wave_mod.WaveError as e: # the way up refused: the drive goes in look + log(f" hand not up for the drive ({why}): {e.args[0]}") + wave_greet.lower() # a hand up for a wave greeting comes down before any drive + if not fetch._at_pose(rest := fetch.drive_arm()): + log(f" arm to {rest} first ({why})") + arm_route.move(arm_route.plan(rest, holding=False), None, False) + + LIFT_VEL = 20 # speed ratio % for a lift move asked by voice (head.VEL is 40) LIMIT_SAY = {"yaw": (f"I can turn my head up to {head.AXIS_LIMITS[2][1]:g} degrees each way.", f"고개는 좌우로 {head.AXIS_LIMITS[2][1]:g}도까지 돌릴 수 있어요."), @@ -517,6 +545,12 @@ HEALTH_S = 30.0 # s between "camera ok" lines in the log PATROL_WAIT_S = 8.0 # s; on patrol, after the greeting or the last answer, wait this long for speech LOW_BATTERY, RESUME_BATTERY = 5, 60 # % PAUSE_AT_END = 3.0 # s to wait at each patrol point +PASSER_WAVE_EVERY_S = 15.0 # s; a drive with the hand up stops to wave at people at most this often (else the + # same person is waved at again and again; estimate) +DOCK_QUIET_M = 2.0 # m; on the way to the dock nearer than this no stop for a wave (the docking starts + # there and a stop undid it; estimate) +PASSER_MARKERS = "line" # drives to markers named so stop to wave at everyone passing; to the others only at + # someone waving (owner, 2026-11-07) LOG_FILE = os.path.join(ROOT, "logs", "lumi.log") @@ -842,6 +876,11 @@ class Patrol: def __init__(self, route, once=False, pause_s=PAUSE_AT_END): self.route, self.i = route, 0 self.once, self.pause_s = once, pause_s + self.hand_up = False # this leg drives with the hand up (waist_home): it stops to wave at people + # (PASSER_MARKERS) + self.dock_leg = False # this leg goes to the dock: a stop near it undid the docking (dock_far) + self.waving = None # the thread swinging for people passing (wave_greet.passer_wave) + self.wave_after = 0.0 # no wave for passers before this (PASSER_WAVE_EVERY_S) self.mode = "patrol" # patrol | going_home | charging | done self.moving = False # a move that we started is running self.progress = None # (pose, time) of the last movement, to notice a stuck drive @@ -868,7 +907,7 @@ class Patrol: return battery, ms = st.get("power_percent", 100), st.get("move_status") - if self.mode == "done": + if self.mode == "done" or self.waving is not None and self.waving.is_alive(): return if self.mode == "charging": if battery >= RESUME_BATTERY: @@ -886,6 +925,17 @@ class Patrol: return if self.moving: + if ms == "running" and self.hand_up and now >= self.wave_after and wave_greet_on(): + self.wave_after = now + 1.0 # asked about once a second while driving + target = self.route[self.i] + waver = wave_greet._waver() and (not self.dock_leg or self.dock_far(st)) + if waver or not self.dock_leg and isinstance(target, str) and target.startswith(PASSER_MARKERS) and \ + wave_greet._someone_within(wave_greet.GREET_M): + self.pause() # the base stops; the next tick drives on to the same marker + self.wave_after = now + PASSER_WAVE_EVERY_S + self.waving = threading.Thread(target=self.passer_wave, daemon=True) + self.waving.start() + return if ms == "running": pose = st.get("current_pose") or {} xy = (pose.get("x", 0.0), pose.get("y", 0.0), pose.get("theta", 0.0)) @@ -944,12 +994,30 @@ class Patrol: ok, msg = safe(agv.go, target, default=(False, "error")) if ok: self.moving = True + self.hand_up = safe(arm_route.where, default=None) in arm_route.WAVE_POSES # every drive (owner) + self.dock_leg = target in ("home", safe(agv.dock_marker, default=None)) log(f"patrol -> {target}") else: log(f"patrol cannot go to {self.route[self.i]}: {msg}") self.wait_until = now + 5 + def dock_far(self, st): + """On the way to the dock, still further than DOCK_QUIET_M from it: a stop for someone waving is allowed.""" + xy = safe(agv.marker_xy, "home", default=None) + pose = st.get("current_pose") or {} + return xy is not None and math.hypot(pose.get("x", 0.0) - xy[0], pose.get("y", 0.0) - xy[1]) > DOCK_QUIET_M + + def passer_wave(self): + """Swings for the people passing (wave_greet.passer_wave); a stop or a failure of the arm ends the patrol (the + arm never moves again by itself after a stop).""" + try: + wave_greet.passer_wave() + except Exception as e: + log(f"patrol ended: the arm stopped ({e!r})") + self.mode = "done" + + class Modes: """Live switches from the dashboard (MODES_FILE); the command line gives the defaults.""" @@ -2442,7 +2510,7 @@ class Lumi: elif cmd == "go_point": self.start_trip(tuple(d["point"])) elif cmd == "route": - self.start_trip(d["markers"], d.get("pause", 1.0)) + self.start_trip(d["markers"], d.get("pause", 1.0), loop=d.get("loop", False), rounds=d.get("rounds", 0)) elif cmd == "cancel": if self.mission_running(): # running or paused: never goes on after a cancel from tasks import fetch @@ -2490,16 +2558,24 @@ class Lumi: self.calib_n = 0 self.write_calib("collecting" if self.calib_until else "stopped") - def start_trip(self, target, pause_s=0.0, remember=True): + def start_trip(self, target, pause_s=0.0, remember=True, loop=False, rounds=0): """Drive to a marker, a map point or a list of markers in order; with patrol mode on, people in the - way are greeted on the way. `remember`: where Lumi stands now is where "come back" returns to.""" + way are greeted on the way. `remember`: where Lumi stands now is where "come back" returns to. `loop`: the + markers there and back again (a, b, c, b, a, ...), `rounds` times (ending where it started), 0: until stopped.""" if remember: from tasks import fetch fetch._task["trip_from"] = safe(agv.pose) or fetch._task["trip_from"] detour.forget() # a new trip: "try again" no longer means a blocked one if self.patrol: self.patrol.pause() - self.patrol = Patrol(list(target) if isinstance(target, list) else [target], once=True, pause_s=pause_s) + route = list(target) if isinstance(target, list) else [target] + if loop and len(route) > 1 and rounds: + back, forth = route[-2::-1], route[1:] + self.patrol = Patrol(route + (back + forth) * (rounds - 1) + back, once=True, pause_s=pause_s) + elif loop and len(route) > 1: + self.patrol = Patrol(route + route[-2:0:-1], once=False, pause_s=pause_s) + else: + self.patrol = Patrol(route, once=True, pause_s=pause_s) self.patrol.tick(force=True) def come_back(self, speak=False): diff --git a/data/arm_poses.json b/data/arm_poses.json index fe80ef1..0d6fdb0 100644 --- a/data/arm_poses.json +++ b/data/arm_poses.json @@ -40,20 +40,20 @@ -201.64 ], "wave_start": [ - -178.86, - -77.26, - -2.49, + -178.87, + -88.92, + -3.36, -175.06, - 38.21, + 38.22, -219.73 ], "wave": [ - -178.86, - -77.26, - -17.24, + -178.87, + -88.72, + 10.48, -175.06, - 38.37, - -219.7 + 38.22, + -219.73 ], "give_pre": [ -270.52, @@ -62,5 +62,21 @@ -168.9, 65.55, -231.86 + ], + "bag": [ + -276.03, + -80.29, + -29.47, + -170.75, + 81.42, + -235.63 + ], + "rest": [ + -288.51, + -44.72, + -55.82, + -180.45, + 88.32, + -247.07 ] } \ No newline at end of file diff --git a/data/fetch_calib.json b/data/fetch_calib.json index 8846791..4bf0497 100644 --- a/data/fetch_calib.json +++ b/data/fetch_calib.json @@ -1 +1 @@ -{"arm_yaw_in_base_deg": -95.5, "objects": ["cup", "cup"], "waist_deg": -20.31, "measured": "2026-10-19 15:55 (median of -96.4, -94.9, -95.5; one run that paired both cups with one was left out)", "arm_xy_in_base_m": [0.09, -0.111], "arm_xy_measured": "2026-10-29 19:38", "arm_xy_samples": [[0.111, -0.086], [0.093, -0.095], [0.187, -0.113], [0.117, -0.129], [0.066, -0.109], [0.041, -0.114], [0.051, -0.127], [0.087, -0.078]]} \ No newline at end of file +{"arm_yaw_in_base_deg": -95.5, "objects": ["cup", "cup"], "waist_deg": -20.31, "measured": "2026-10-19 15:55 (median of -96.4, -94.9, -95.5; one run that paired both cups with one was left out)", "arm_xy_in_base_m": [0.074, -0.085], "arm_xy_measured": "2026-10-30 20:49", "arm_xy_samples": [[0.041, -0.114], [0.051, -0.127], [0.087, -0.078], [0.074, -0.085], [0.069, -0.085], [0.049, -0.08], [0.095, -0.104], [0.08, -0.079], [0.075, -0.092]]} \ No newline at end of file diff --git a/docs/TUNING.md b/docs/TUNING.md index d8c1044..1e7978a 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -144,7 +144,9 @@ Every value here is a constant at the top of its file, with a comment on what it | `assistant/steps.py` | `WAIT_ORDER_S` | 5 min | "do what they tell you": no instruction by then, the mission goes on with its rest | | `tasks/fetch.py` | `RECEIVE_REACH_MM`, `RECEIVE_SHORT_MM`, `RECEIVE_MIN_MM` | 150, 100, 20 mm | "Take this from my hand" and "reach out to me": the hand moves at most this far from `give` towards the thing in the hand (or their hand), stops this far before it, leaves out a shorter move. Estimates | | `tasks/fetch.py` | `REACH_BODY_MM` | 300 mm | "Reach out to me" with no hand of theirs seen: the hand stops this far before the person's body. Estimate | -| `assistant/lumi.py` | `REACH_FRONT_DEG`, `REACH_COME_M` | 10°, 1.5 m | "Reach out to me": a person further than this from where the hand points in `give` is turned to with the waist until the hand points at them (Greeter or Patrol; the base stays); a person further away is driven to first (`COME_STOP`). Estimates | +| `assistant/lumi.py` | `REACH_COME_M` | 1.5 m | A hand-over by voice to a person further than this drives to them first (`COME_STOP`); "reach out to me" never turns or drives: the hand goes out the way the waist faces. Estimate | +| `assistant/lumi.py` | `HOME_WAIST_DEG`, `HOME_ARM_SPEED`, `HOME_DOCK_WAIT_S` | 85.8°, slow, 3 s | On the charger with nothing to do (arrived home, a conversation over) the empty arm goes from `rest` to `look` at this speed and the waist turns this far left of the front; any arm order or drive takes the arm to `rest` and the waist to the front first. The charger is asked this long after arriving home (estimate) | +| `tasks/fetch.py` | `BAG_HANG_S` | 8 s | A mission's bag step ("take the bag to p1"): after the arm reaches the `bag` pose and Lumi asks for the bag, it waits this long before the next step drives (estimate) | | `assistant/lumi.py` | `REACH_HOLD_S` | 30 s | The hand stays held out this long after a reach without "thanks" / "okay", then the arm folds back to `look`. Estimate | | `tasks/fetch.py` | `POINT_STEPS_MM` | 0, ±50, ±100 mm | "Put it here" with pointing: spot grid around the pointed point | | `tasks/fetch.py` | `RECEIVE_DI_S` | 0.5 s | `receive`: the finger sensor (DI_1) must see something this long before Lumi asks the person to let go (the hand closes on their "okay") | @@ -204,6 +206,9 @@ Every value here is a constant at the top of its file, with a comment on what it | `robot/motion.py` | `SPEED_ACCEL_FACTOR` | swing 4.0 | A joint speed with its own acceleration factor instead of `JOINT_ACCEL_FACTOR`: "swing" (60 °/s, 240 °/s²) for the greeting's short swings. Higher = snappier swings, more shaking | | `tasks/wave_greet.py` | `NEW_WAVE_S` | 5 s | No waving this long: the next wave gets a new greeting line | | `tasks/wave_greet.py` | `JOKE_AFTER_S`, `JOKE_EVERY_S` | 10 s, 12 s | Waving on and on: the first joke after this long, then one every this long | +| `tasks/wave_greet.py`, `assistant/lumi.py` | `IDLE_WAVE_EVERY_S`, `IDLE_SWINGS`, `IDLE_AFTER_S` | 15 s, 3, 15 s | On the charger with the wave greeting on and nothing said to Lumi for `IDLE_AFTER_S`: the hand goes up and stays up, this many swings every `IDLE_WAVE_EVERY_S`; a call stops the swings (the hand stays up), a drive or an arm order takes it down. Estimates | +| `assistant/lumi.py` | `PASSER_WAVE_EVERY_S`, `PASSER_MARKERS`, `DOCK_QUIET_M` | 15 s, "line", 2 m | With the wave greeting on, the empty arm drives with the hand up (`wave_start`). On the way to markers whose names start with `PASSER_MARKERS` the base stops for anyone within 3 m and waves; to other markers only for someone waving; at most every `PASSER_WAVE_EVERY_S`; never nearer than `DOCK_QUIET_M` to the dock (a stop there undoes the docking). Estimates | +| `assistant/lumi.py` | `PASSER_MAX_M`, `PASSER_EVERY_S`, `PASSER_DEG` | 4 m, 2 s, 10° | On the charger with nobody talking to Lumi: the head turns to the nearest person this near, at most this often, when they are this far off where it looks (the body stays). Estimates | | `tasks/wave_greet.py` | `WAIST_MIN_DEG` | 10° | A person nearer the front than this: only the head turns, not the waist | | `tasks/wave_greet.py` | `WAIST_FOLLOW_DEG`, `FOLLOW_EVERY_S` | 20°, 3 s | The waving person moved this far off the waist's front: the waist turns to them again between swings, at most this often | | `tasks/wave_greet.py` | `WAIST_PARTS` | 1, 0.75, 0.5, 0.25 | A waist turn whose sweep is blocked is tried again this much of the way; the head covers the rest | diff --git a/tasks/fetch.py b/tasks/fetch.py index 9577e9a..9851b3d 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -424,12 +424,18 @@ def bag_off(): log("no bag: the arm at rest") +def drive_arm(): + """The empty arm's pose for a drive or a base turn: look (owner, 2026-11-07), its rest with a bag on the hooks + (in look the bag hangs before the base's 3D camera, BAG_POSE).""" + return arm_route.rest_pose() if _state.get("bag") else arm_route.HOME + + def _drive_pose(holding=False): - """The arm to its rest (arm_route.rest_pose; look with something held) before the base drives or turns. A switched-off arm (Cobo π: not powered or not enabled) stays + """The arm to its drive pose (drive_arm; look with something held) before the base drives or turns. A switched-off arm (Cobo π: not powered or not enabled) stays where it is: drives and talk need no arm, and the arm's points are still checked from its joints. Powered off, it reads all joints 0: where it is is not known, so no drive (ARM_UNSEEN).""" try: - _line_holding(LOOK_POSE) if holding else _pose(arm_route.rest_pose()) # a bag on the hooks too + _line_holding(LOOK_POSE) if holding else _pose(drive_arm()) except (FetchError, motion.MotionError) as e: if tuple(e.args[:1]) != arm_route.OFF[:1] and "not powered" not in str(e): raise @@ -1953,15 +1959,16 @@ def _kept_spots(kept, key): def _place_remembered(top0, kept): """Put it down on the kept table where its level top was seen (_remember), also where the camera sees it no more: from here at its spots nearest PICK_ZONE_CENTRE, else after the waist turn (waist_for, in place) that brings one of - its spots nearest the column into the arm's comfortable reach. Only with the waist at the front, the table's height - known and the lift right for it. True when it is down.""" + its spots nearest the column into the arm's comfortable reach; none of its level top remembered as a spot: at its + kept spot (_place_kept_spot). Only with the waist at the front, the table's height known and the lift right for it. + True when it is down.""" z = _kept_at(kept)[2] lift = None if z is None else lift_for(z) if lift is None or abs(lift - head.status()[0]) >= LIFT_TOL_MM or abs(_waist_turn()) >= 1.0: return None spots = _kept_spots(kept, lambda x, y: math.hypot(x - PICK_ZONE_CENTRE[0], y - PICK_ZONE_CENTRE[1])) if not spots: - return None + return _place_kept_spot(top0, kept) top = _top_on(top0, z) log(f"the table I keep at {z:.0f} mm: trying spots of it I saw") if _place_at(spots[:FAR_SPOTS], top): # each refused spot costs IK time; the nearest are likeliest @@ -1983,6 +1990,25 @@ def _place_remembered(top0, kept): return None +def _place_kept_spot(top0, kept): + """Put it down at the kept table's own spot (_kept_at: FAR_IN_MM in from its nearest level point when last seen) + when no remembered level point of it makes a spot: up close the torso camera may see the table no more (out of its + view, too near for depth, no depth frame) and the base has brought the spot into reach. Only within FAR_REACH_MM, + FREE_MM from everything seen standing, and never where the camera sees a surface other than the kept height (the + table is not where it was kept). True when it is down.""" + x, y, z = _kept_at(kept) + if math.hypot(x, y) > FAR_REACH_MM or any(math.hypot(x - o["x"], y - o["y"]) < skills.FREE_MM + for o in skills.look()): + return None + seen = skills.surface_heights([(x, y)], z)[0] + if seen is not None and abs(seen - z) > KEEP_TOL_MM: + log(f"where I keep the table ({x:.0f}, {y:.0f}) I see {seen:.0f} mm, not its top at {z:.0f} mm") + return None + log(f"the table I keep at {z:.0f} mm{' is out of view' if seen is None else ''}: putting it at its spot " + f"({x:.0f}, {y:.0f})") + return _place_at([(x, y)], _top_on(top0, z)) + + def _kept_at(kept): """(x, y, height) mm, arm frame now, of the table kept on the map (height None: not measured yet).""" x, y = arm_frame(kept["world"]) diff --git a/tasks/wave_greet.py b/tasks/wave_greet.py index 4fbc9d0..2f5bc06 100644 --- a/tasks/wave_greet.py +++ b/tasks/wave_greet.py @@ -53,9 +53,9 @@ REFUSED_S = 30.0 # s before trying again after the arm was refused ( # between tries to bring a blocked waist back to the front HEAD_TIMEOUT_S = 5.0 # s a head move may take; the body API now and then never answers a moveto, and the call # holds the body lock all that time (the waist turn waited 30 s behind it) -IDLE_WAVE_EVERY_S = 20.0 # s between two waves while nothing is asked of Lumi on the charger (owner: now and then for +IDLE_WAVE_EVERY_S = 15.0 # s between two waves while nothing is asked of Lumi on the charger (owner: now and then for # the passers-by; estimate), from the end of the last one (or anyone's last wave) -IDLE_SWINGS = 2 # swings of such a wave +IDLE_SWINGS = 3 # swings of such a wave IDLE_CLEAR_M = 1.0 # m; nobody this near in either camera when such a wave starts (one coming closer while the # arm goes up still stops it: _too_close); estimate IDLE_RETRY_S = 1.0 # s between two asks whether Lumi is idle (it asks the base whether it charges) @@ -330,17 +330,21 @@ def _idle_wave(): """Nobody asks anything (on the charger, _idle): the hand goes up and stays up (owner, 2026-11-04: "held"), the waist where it is, no words; it swings IDLE_SWINGS times now and then (step) so passers-by see Lumi is on. A drive or an order for the arm takes it down (lower, a task), the switch turned off too. False when the arm is refused.""" - if _someone_within(IDLE_CLEAR_M) or arm_route.where() != _rest_arm(): + at = arm_route.where() + if _someone_within(IDLE_CLEAR_M) or at not in (_rest_arm(), wave.START, wave.SWING): return True # someone near the arm, or the arm still on its way to rest: next time - try: - route, _ = wave.plan() - except Exception as e: - log(f"no idle wave: {e.args[0] if isinstance(e, wave.WaveError) else repr(e)}") - return False + route = None # the hand already up (a wave's way down did not run): it swings from there + if at == _rest_arm(): + try: + route, _ = wave.plan() + except Exception as e: + log(f"no idle wave: {e.args[0] if isinstance(e, wave.WaveError) else repr(e)}") + return False log("nothing asked for a while: the hand up for the passers-by") _busy.set() try: - _up(route) + if route: + _up(route) _st.update(up=True, held=True, held_at=0.0) _idle_swings() finally: @@ -362,21 +366,87 @@ def _idle_swings(): _swing() -def _down(waist=None): +def raise_for_drive(): + """With the switch on, the empty arm drives with the hand up at START (owner, 2026-11-07): the way up (wave.plan) + unless it is up already. A stop or a failure switches the greeting off (_stopped) and raises. True when it is up.""" + if _on is None or not _on(): + return False + if arm_route.where() in arm_route.WAVE_POSES: + return True + if _too_close(): + log("a drive: someone right by me, the hand stays down") + return False + route, _ = wave.plan() + log("a drive: the hand up") + _busy.set() + try: + _up(route) + except Exception as e: + _stopped(e) + raise + finally: + _busy.clear() + return True + + +def _nearest(m): + """Bearing (deg from the waist's front, + left) of the nearest person within `m` metres in either camera's fresh + detections, None when there is none.""" + near = [] + for cam in ("head", "torso"): + try: + d = json.loads(camview.det_path(cam).read_text()) + except (FileNotFoundError, ValueError): + continue + if time.time() - d["time"] < CLOSE_FRESH_S: + near += [(p["distance_m"], p["angle_deg"]) for p in d["people"] + if p.get("distance_m") is not None and p["distance_m"] < m] + return min(near)[1] if near else None + + +def passer_wave(): + """A drive with the hand up (lumi.Patrol, the base stopped): the head to the one waving, else the nearest person + within GREET_M, and IDLE_SWINGS swings, waited for, then the head ahead again; none when nobody is within GREET_M + or someone is within IDLE_CLEAR_M of the arm. A stop or a failure switches the greeting off (_stopped) and + raises. True when it swung.""" + w = _waver() + bearing = w[0] if w else _nearest(GREET_M) + if _on is None or not _on() or bearing is None or _someone_within(IDLE_CLEAR_M) or \ + arm_route.where() not in (wave.START, wave.SWING): + return False + log(f"{'someone waves' if w else 'people passing'} at {bearing:+.0f} deg: a wave") + _busy.set() + _head_to(bearing) + try: + for _ in range(IDLE_SWINGS): + if _someone_within(IDLE_CLEAR_M): + break + _swing() + except Exception as e: + _stopped(e) + raise + finally: + _busy.clear() + _turn_head(0.0) # the drive goes on looking ahead + return True + + +def _down(waist=None, arm_to=None): """Waist to its rest (`waist` deg from the front, else _rest()) first, the way it came with the hand up (in `look` the arm sticks out further and the same turn back can be blocked), then the arm slowly down (_rest_arm) and the head to rest.""" from tasks import fetch _busy.set() try: - if _st["up"] and arm_route.where() is None: + if arm_route.where() is None: _settle() # mid-swing: the queued swings end first fetch._stop.clear() _st["waist_out"] = not fetch._waist_to(_rest() if waist is None else waist, in_place=True) - if arm_route.where() in arm_route.WAVE_POSES: - arm_route.move(arm_route.plan(_rest_arm()), DOWN_SPEED) + at = arm_route.where() + if at in arm_route.WAVE_POSES: + arm_route.move(arm_route.plan(arm_to or _rest_arm()), DOWN_SPEED) _turn_head(0.0, head.HEAD_REST_PITCH) - log("arm down") + log("arm down" if at in arm_route.WAVE_POSES or at in (_rest_arm(), arm_to) else f"arm left where it is ({at or 'between poses'})") finally: _busy.clear() @@ -486,21 +556,40 @@ def up(): return _st["up"] +def _quiet(wait_s): + """The way up and the swings sent without waiting end first (at most `wait_s` for the way up).""" + end = time.time() + wait_s + while _busy.is_set() and time.time() < end: + time.sleep(0.05) + if _st["swing_end"] > time.time() - SWING_S: + _settle() + _st["swing_end"] = 0.0 + + +def front_hand_up(wait_s=10.0): + """Before a drive with the switch on and the hand up (lumi.waist_home): the swings end and the waist turns to the + front with the hand kept up, as _down turns it (owner, 2026-11-07: not down and up again). True when it did.""" + if _on is None or not _on(): + return False + _quiet(wait_s) + if arm_route.where() not in arm_route.WAVE_POSES: + return False + from tasks import fetch + fetch._stop.clear() + return fetch._waist_to(0.0, in_place=True) + + def lower(wait_s=10.0): """A drive or a turn takes the robot (lumi.waist_home): the way up and the queued swings end, then a hand left in a wave pose comes down to look, the waist to the front. Never driven with the hand up. Nothing when the greeting does not run in this process (start() not called).""" if _on is None: return - end = time.time() + wait_s - while _busy.is_set() and time.time() < end: - time.sleep(0.05) - if _st["swing_end"] > time.time() - SWING_S: - _settle() # swings sent without waiting may still run - _st["swing_end"] = 0.0 + _quiet(wait_s) _st["up"] = arm_route.where() in arm_route.WAVE_POSES if _st["up"]: - _down(0.0) # a drive follows: the waist to the front + from tasks import fetch + _down(0.0, fetch.drive_arm()) # a drive follows: the waist to the front, the arm to its drive pose _st["up"] = _st["held"] = False diff --git a/tests/test_fetch_place.py b/tests/test_fetch_place.py index 411e07a..3b9ac6f 100644 --- a/tests/test_fetch_place.py +++ b/tests/test_fetch_place.py @@ -222,6 +222,43 @@ fetch._place_kept = real_kept fetch._state.update(holding=False, held_object=None) skills.flat_points = flat +# ---------- a table seen further away, lost up close (out of the torso camera's view, no depth frame, and no level +# point of it remembered: seen by the head camera): put on its kept spot once the base brought it into reach ---------- +ROUND.update(c=(-160.0, 1350.0), r=400.0) +TABLE_Z = -390.0 +far = fetch.far_table() +assert far and abs(far["table"] - TABLE_Z) < 1.0, far +kept = fetch._keep((far["x"], far["y"]), far["table"]) # no level points kept +spot_world = fetch._kept_at(kept) +fetch.agv.pose = lambda: (0.60, 0.0, 0.0) # the base drove 0.6 m towards it +x, y, z = fetch._kept_at(kept) +assert math.hypot(x, y) <= fetch.FAR_REACH_MM and abs(y - (spot_world[1] - 600.0)) < 60.0, (x, y) +assert math.hypot(x - ROUND["c"][0], y - (ROUND["c"][1] - 600.0)) < ROUND["r"] # on the table, moved with it +real_place_at, real_look = fetch._place_at, skills.look +put = [] +fetch._place_at = lambda tries, top, turned=True: put.append((tries, top)) or True +skills.look = lambda *a, **kw: [] +skills._held.clear() +skills._held.update(top_mm=-300.0, table=-400.0) +VIEW_Y = 1e9 # lost: the camera sees nothing of it +assert fetch._kept_spots(kept, lambda x, y: 0.0) == [] +assert fetch._place_remembered(-300.0, kept) is True, lines +assert put == [([(x, y)], -290.0)], put # its spot, the cup's top 10 mm higher +# never where the camera sees something else, nor next to a thing standing there, nor out of reach +put.clear() +VIEW_Y = 0.0 +ROUND["c"] = (-160.0, 2500.0) # the floor where it was kept: not there +assert fetch._place_remembered(-300.0, kept) is None and not put +VIEW_Y = 1e9 +skills.look = lambda *a, **kw: [{"name": "cup", "x": x + 50.0, "y": y, "top_mm": -300.0}] +assert fetch._place_remembered(-300.0, kept) is None and not put +skills.look = lambda *a, **kw: [] +fetch.agv.pose = lambda: (0.0, 0.0, 0.0) # where it was seen from: too far +assert fetch._place_remembered(-300.0, kept) is None and not put +VIEW_Y = 655.0 +fetch._place_at, skills.look = real_place_at, real_look +skills._held.clear() + # ---------- several cups: the said colour / size / place first; that colour nowhere: the closest, said ---------- cups = [{"name": "cup", "colour": c, "x": x, "y": y, "top_mm": -260.0, "width_mm": w, "seen": 8, "spread": 2.0} for c, x, y, w in (("white", -150.0, 600.0, 80.0), ("red", 100.0, 700.0, 70.0), ("white", -300.0, 900.0, 64.0))] diff --git a/tests/test_switches.py b/tests/test_switches.py index 60e0ab9..be42bc7 100644 --- a/tests/test_switches.py +++ b/tests/test_switches.py @@ -235,13 +235,14 @@ fetch._at_pose = lambda name: name == "look" # in look on the charge assert lumi.waist_home("test") and calls == [(0.0, True)], calls fetch._waist_to = lambda rel, in_place=False: False # the arm's sweep is not clear assert lumi.waist_home("test") is False -# a drive or turn (fold): the empty arm goes to rest first wherever it is, also with the waist at the front already +# a drive or turn (fold), the wave greeting off: the empty arm goes to look first wherever it is (fetch.drive_arm), +# also with the waist at the front already went = [] real_plan, real_move, real_lower = lumi.arm_route.plan, lumi.arm_route.move, lumi.wave_greet.lower lumi.arm_route.plan, lumi.wave_greet.lower = (lambda target, holding=False: [target]), (lambda: None) lumi.arm_route.move = lambda seq, speed=None, holding=False: went.append(seq[-1]) -fetch._waist_turn, fetch._at_pose, fetch.state = (lambda: 0.4), (lambda name: name == "look"), (lambda: {"status": "idle"}) -assert lumi.waist_home("drive", fold=True) and went == ["rest"], went +fetch._waist_turn, fetch._at_pose, fetch.state = (lambda: 0.4), (lambda name: name == "rest"), (lambda: {"status": "idle"}) +assert lumi.waist_home("drive", fold=True) and went == ["look"], went went.clear() fetch.state = lambda: {"status": "idle", "holding": True} # a cup: look (drive_ready), never rest real_ready, fetch.drive_ready = fetch.drive_ready, lambda: went.append("drive_ready") diff --git a/tests/test_wave_greet.py b/tests/test_wave_greet.py index 6a0a923..885a6d1 100644 --- a/tests/test_wave_greet.py +++ b/tests/test_wave_greet.py @@ -2,6 +2,7 @@ waving detector (vision/waving.py) on the recordings of vision/wave_record.py when they are here (tests/data/waves, local only: people in the pictures): python tests/test_wave_greet.py""" from pathlib import Path +import time import no_robot # noqa: F401 any connection to the robot fails the test from manipulation import arm_route, wave @@ -246,7 +247,7 @@ g._st["idle_at"] = 700.0 # the last idle wave run(700.0, 700.0 + g.IDLE_WAVE_EVERY_S - 1) assert done == [] and said == [], done # not before IDLE_WAVE_EVERY_S run(700.0 + g.IDLE_WAVE_EVERY_S + 0.5, 700.0 + g.IDLE_WAVE_EVERY_S + 0.5) -assert done == ["up route", "swing", "swing"] and said == [] and g._st["up"] and g._st["held"], (done, said) +assert done == ["up route"] + ["swing"] * g.IDLE_SWINGS and said == [] and g._st["up"] and g._st["held"], (done, said) done.clear() t = 700.0 + g.IDLE_WAVE_EVERY_S + 1 run(t, t + g.IDLE_WAVE_EVERY_S - 2) @@ -260,10 +261,15 @@ run(1000.0, 1100.0) assert done == [] and g._st["up"], done talk["on"] = False # quiet again: the swings go on run(1101.0, 1102.0) -assert done == ["swing", "swing"], done +assert done == ["swing"] * g.IDLE_SWINGS, done done.clear() g.lower() # a drive: down to the front first assert "down normal" in done and not g._st["up"] and not g._st["held"], done +done.clear() # the hand left up (its way down did not run): swings from there +arm["at"], g._st["idle_at"] = "wave_start", 0.0 +run(1200.0, 1200.0) +assert done == ["swing"] * g.IDLE_SWINGS and g._st["held"], done +g.lower() g._idle = lambda: True done.clear() said.clear() # someone waves back during an idle wave: greeted as always, @@ -304,6 +310,25 @@ waver["w"] = W(0.0) run(621.0, 621.0) assert said[-1] in sum(g.wave_lines.INTRO, ()), said +# a loop patrol's wave for people passing: only with the hand up, someone within GREET_M, nobody by the arm +near = {"m": None} +waver["w"] = None +g._someone_within = lambda m: near["m"] is not None and near["m"] < m +g._nearest = lambda m: 20.0 if near["m"] is not None and near["m"] < m else None +saved, arm["at"] = arm["at"], "wave_start" +done.clear() +assert not g.passer_wave() and not done # nobody there +near["m"] = 0.5 +assert not g.passer_wave() and not done # someone right by the arm +near["m"] = 2.0 +assert g.passer_wave() and done.count("swing") == g.IDLE_SWINGS +time.sleep(0.2) # the head turns in the background +assert "head +20" in done and done[-1] == "head +0" # to them, then ahead again for the drive +arm["at"], near["m"] = "look", 2.0 +assert not g.passer_wave() # the hand is not up +arm["at"] = saved +done.clear() + # a hand at the head (scratching, a phone at the ear) is not a raised hand; the same hand held out to the side is import numpy as np # noqa: E402 kp = np.zeros((17, 3))