From 775b32bc5281d7ed471d20ee1abeba0a77536105 Mon Sep 17 00:00:00 2001 From: Cutshion Date: Wed, 21 Oct 2026 16:26:55 +0900 Subject: [PATCH] Greeter / Patrol switches, dashboard hand controls only when idle or paused, push script Co-Authored-By: Claude Opus 5.5 --- api/server.py | 57 ++++++++++--- assistant/lumi.py | 114 +++++++++++++++++++++++-- manipulation/wave.py | 2 +- tasks/fetch.py | 22 ++++- tasks/follow.py | 3 +- tests/test_follow.py | 2 +- tests/test_robot_free.py | 100 ++++++++++++++++++++++ tests/test_switches.py | 174 +++++++++++++++++++++++++++++++++++++++ tests/test_wave.py | 1 + tools/gitea_push.sh | 19 +++++ 10 files changed, 471 insertions(+), 23 deletions(-) create mode 100644 tests/test_robot_free.py create mode 100644 tests/test_switches.py create mode 100755 tools/gitea_push.sh diff --git a/api/server.py b/api/server.py index 0543440..d3b34c4 100644 --- a/api/server.py +++ b/api/server.py @@ -96,17 +96,49 @@ def start_assistant(no_arm=False, no_drive=False): start_new_session=True).pid -def robot_free(manual=False): - """Refuse while the assistant owns the robot. manual: a hand control on the dashboard (jog, head, lift, gripper, - arm buttons), allowed beside Greeter while Lumi is not on a task or on patrol (Lumi may turn its head back to a - visitor afterwards).""" - if not assistant_pids(): - return +BUSY_FILE = Path("/dev/shm/lumi_busy.json") # written by lumi.py: {"busy": skill | follow | drive | wave | null} +BUSY_MSG = "Busy with a task. Pause or stop it first." +_waving = threading.Event() # /arm/wave runs here + + +def running_now(): + """What the robot is doing now (a task or mission, a skill, following, a wave, a drive), None when idle. A + paused task does not count.""" from tasks import fetch - busy = fetch.state().get("status") in ("running", "waiting") or read_modes().get("patrol") - if not manual or busy: - raise HTTPException(409, "Lumi is busy with a task or on patrol: stop it first." if manual else - "The assistant (lumi.py) is running and owns the robot. POST /assistant/stop first.") + lumi = assistant_pids() + st = fetch.state() + if st.get("status") in ("running", "waiting") and not st.get("paused") and (lumi or fetch._busy()): + return "task" # (lumi or _busy: the file of a runner that died does not count) + if _skill["thread"] and _skill["thread"].is_alive(): + return "skill" + if _route.thread and _route.thread.is_alive(): + return "route" + if _waving.is_set(): + return "wave" + if lumi: + try: + what = json.loads(BUSY_FILE.read_text()).get("busy") + if what: + return what + except (FileNotFoundError, ValueError): + pass + try: # a drive to a marker / point / dock, by anyone + if agv.request("/api/robot_status", timeout=0.5)["results"].get("move_status") == "running": + return "drive" + except Exception: + pass + return None + + +def robot_free(manual=False): + """manual: a hand control on the dashboard (jog, lift, waist, head, arm buttons and poses, gripper): refused while + something runs (running_now), allowed when idle or paused, Greeter / Patrol on or off. Anything else is refused + while the assistant runs (it owns the robot). STOP never asks here.""" + if manual: + if running_now(): + raise HTTPException(409, BUSY_MSG) + elif assistant_pids(): + raise HTTPException(409, "The assistant (lumi.py) is running and owns the robot. POST /assistant/stop first.") def tail(path, n): @@ -326,12 +358,15 @@ def body_move(body: BodyBody): @app.post("/arm/wave", tags=["arm"], summary="Wave from look along the checked route (manipulation/wave.py, slow)") def arm_wave(): robot_free(manual=True) + _waving.set() try: wave.wave() except wave.WaveError as e: raise HTTPException(409, e.args[0]) except motion.MotionError as e: raise HTTPException(409, str(e)) + finally: + _waving.clear() return {"ok": True} @@ -705,7 +740,7 @@ def arm_enable(body: OnBody): @app.post("/arm/run", tags=["arm"], summary="Run a Cobo π program (.jks) once; returns at once") def arm_run(body: ProgramBody): - robot_free() + robot_free(manual=True) if not arm.ready(): raise HTTPException(409, "arm not ready: power/enable off, or a program is running") try: diff --git a/assistant/lumi.py b/assistant/lumi.py index ac27b19..a807c8d 100644 --- a/assistant/lumi.py +++ b/assistant/lumi.py @@ -37,7 +37,11 @@ Behaviour Modes (switched live from the dashboard through /dev/shm/lumi_modes.json, see api/server.py /assistant/modes): - greeter: while standing, greet people who come close, talk, listen for "Hi Lumi". - patrol: while driving anywhere (a marker picked on the dashboard, "go to p2", a --patrol route), stop for a - person in the path, greet and talk, then drive on to the same destination. + person in the path, greet and talk, then drive on to the same destination. Patrol also allows the + base and the waist by voice: with it off (Greeter only) Lumi does what it can standing in place (talk, + head, lift, arm and gripper within reach, wave) and refuses a drive, a base turn or a waist turn + (base_off says BASE_OFF_SAY; a task runs with fetch.stay_put). The dashboard's own buttons and "stop" + work either way. - wave / drive: wave when asked; allow "come here" and voice "go to". The dashboard's Go / Cancel are sent to this program (/dev/shm/lumi_cmd.json) while it runs, so it can stop for people on the way. A calibration session for the sound direction can also be started from there. @@ -140,6 +144,17 @@ GIVE_ME = re.compile(r"\b(give|hand|mine|for me|to me|i'?ll take it|i will take r"제 거|제가 받을게|받을게", re.I) MOVING_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn", "arm", "pick", "put", "move_object", "fetch", "give", "place", "wave", "lift"} +BASE_ACTIONS = {"go_to", "come", "come_back", "follow", "move", "turn"} # need the base: Patrol on +DRIVE_STEPS = {"go", "move", "turn"} # mission steps that drive +BASE_OFF_SAY = ("I can't drive or turn my waist right now. Switch on Patrol for that.", # Greeter only: a base / + "지금은 이동하거나 허리를 돌릴 수 없어요. 패트롤을 켜 주세요.") # waist motion asked for +ARM_OFF_SAY = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") # an arm action with the arm switched off +ARM_TASKS = {"pick", "put", "move_object", "fetch", "give", "place", "receive", "wave"} # + arm reach / fold + + +def needs_arm(action, target=""): + """The action moves the arm (the gripper alone, open / close, does not ask for it).""" + return action in ARM_TASKS or action == "arm" and target not in ("open", "close") 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}도까지 돌릴 수 있어요."), @@ -262,6 +277,8 @@ CMD_FILE = "/dev/shm/lumi_cmd.json" # written by api/server.py: {"id", "cm # | fetch | fetch_give | fetch_place | fetch_stop | fetch_carry | fetch_release | fetch_steps # | fetch_pause | fetch_resume} CALIB_FILE = "/dev/shm/lumi_calib.json" # progress of a calibration session, for the dashboard +BUSY_FILE = "/dev/shm/lumi_busy.json" # what runs here now, for api/server.py robot_free(): {"busy": skill | + # follow | drive | wave | null} (fetch tasks are in lumi_task.json) CALIB_S = 120.0 # s a calibration session lasts CALIB_NEAR = 2.0 # m; the speaker for a calibration sample is the nearest person within this CALIB_ALONE_DEG = 30.0 # ... with nobody else within this angle (closer than 4 m) @@ -657,6 +674,7 @@ class Lumi: self.closing_pending = None # time of a weak closing word ("okay", "got it"): silence after it ends the talk self.lang = "en" self.skill_thread = None # pick / put / move_object running in the background + self.busy_now = "" # last written to BUSY_FILE ("" = nothing written yet) self.last_song = None # the song sung last ("another song" is a different one) self.mic = mic.get() self.modes = Modes(args) @@ -700,6 +718,7 @@ class Lumi: raise wave_mod.WaveError(*why) 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) return True except wave_mod.WaveError as e: @@ -712,10 +731,42 @@ class Lumi: finally: if self.vision: self.vision.arm_watch = False + self.publish_busy(None) return False + def base_off(self, action, target="", say=True): + """Greeter only (Patrol switched off on the dashboard): Lumi works standing in place (head, lift, arm, + gripper) but never drives, turns the base or the waist. True (and said unless `say` is False) if `action` + needs the base. The dashboard's own buttons and "stop" are not asked here.""" + if action not in BASE_ACTIONS or self.modes.patrol: # "stop" never reads the switches + return False + log(f" {action} {target} refused: Patrol is off") + if say: + self.fetch_say(*BASE_OFF_SAY) + self.keep_listening() + return True + + def arm_off(self): + """An arm action asked with the arm switched off (not powered / enabled in Cobo π): "Please enable my arm + first." is said, True. An arm that does not answer is left to the task's own checks.""" + st = safe(arm.cmd, "get_robot_state") + if not isinstance(st, dict) or "enable" not in st or st.get("power") and st.get("enable"): + return False + log(" the arm is switched off: asked to enable it") + self.fetch_say(*ARM_OFF_SAY) + self.keep_listening() + return True + + def stay(self, voice=True): + """Tasks asked by voice with only Greeter on stay in place (fetch.stay_put: head and lift only, no base, no + waist); the dashboard's tasks do not.""" + from tasks import fetch + fetch.stay_put = voice and not self.modes.patrol + def act(self, action, target): log(f"action: {action} {target}") + if self.base_off(action, target, say=False): # answer() has said why + return if action in MOVING_ACTIONS and self.mission_running(): log(f" {action} refused: on a mission") # the LLM's action must not take Lumi off its task return @@ -800,6 +851,7 @@ class Lumi: if action == "move" and direction in ("back", "forward"): # straight with joy_control, checked like a from tasks import fetch # mission's move: navigation may turn round and log(f" move {direction} {amount:g} m straight") # stops within its own tolerance + self.stay() try: fetch.run_steps([{"do": "move", "dir": direction, "m": amount}], say=self.fetch_say) except fetch.FetchError as e: @@ -842,6 +894,8 @@ class Lumi: elif got[0] == "move": # "again" / "a few centimetres more" after a move d, n = got[1].split() hist.append((text, f"ACTION: move {got[1]}")) + 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 "죄송해요, 지금은 이동할 수 없어요." @@ -873,9 +927,13 @@ class Lumi: # a stopped / failed task can still have the object in the hand: give / place must still work return "holding" if st.get("holding") and st.get("status") != "running" else st.get("status") - def fetch_finish(self, how, on=None): - """Give / place what the hand holds; a refusal ("I haven't learned how to hand things over yet") is spoken.""" + def fetch_finish(self, how, on=None, voice=True): + """Give / place what the hand holds; a refusal ("I haven't learned how to hand things over yet") is spoken. + `voice`: asked by voice (else from the dashboard).""" from tasks import fetch + if voice and self.arm_off(): + return + self.stay(voice) try: if how == "give": fetch.give(say=self.fetch_say) @@ -892,6 +950,9 @@ class Lumi: def fetch_start(self, task): """Start a task; "here" becomes the robot's map pose now, so it does not move with the robot.""" from tasks import fetch + if any(task.get(k) not in (None, "here") for k in ("source", "dest")) and self.base_off("go_to"): + return # Greeter only: a fetch from / to a place drives + self.stay() pose = safe(agv.pose) task = dict(task) for k in ("source", "dest"): @@ -1262,6 +1323,8 @@ class Lumi: self.keep_listening() return True 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 @@ -1277,6 +1340,7 @@ class Lumi: return True def start(s): + self.stay() try: fetch.run_steps(s, say=self.fetch_say, sender=steps.sender(text)) except fetch.FetchError as e: @@ -1333,6 +1397,8 @@ class Lumi: if held: self.fetch_say(f"My hand is full, I'm holding {fetch.held_name()}.", "손에 이미 물건을 들고 있어요.") return + if self.arm_off(): + return no = name and skills.refusal(name) if no: # "take my laptop": my fingers can't hold it self.fetch_say(*no) @@ -1359,6 +1425,7 @@ class Lumi: if not (sees or answer and (brain_mod.confirm_answer(answer) == "yes" or RECEIVE_OK.search(answer))): self.fetch_say("Okay.", "네.") return + self.stay() try: fetch.run_steps([{"do": "receive", "object": name, "from_hand": True}], say=self.fetch_say) except fetch.FetchError as e: @@ -1398,6 +1465,8 @@ class Lumi: if self.skill_busy(): mouth.say("I'm still busy with my arm." if en else "아직 팔로 하는 일이 있어요.") return + if self.arm_off(): + return if action == "put": back = target == "back" said = ("Okay, putting it back.", "네, 제자리에 놓을게요.") if back else ("Okay, putting it down.", "네, 내려놓을게요.") @@ -1489,6 +1558,7 @@ class Lumi: self.resume_mission() elif cmd in ("fetch", "fetch_give", "fetch_place", "fetch_stop", "fetch_carry", "fetch_release", "fetch_steps"): from tasks import fetch # dashboard tasks are confirmed there: no read-back + self.stay(voice=False) if cmd == "fetch": try: fetch.start(d["task"], say=self.fetch_say) @@ -1510,7 +1580,7 @@ class Lumi: log(f" mission refused: {e}") self.fetch_say(str(e), "죄송해요, 지금은 할 수 없어요.") else: - self.fetch_finish(cmd[6:], d.get("on")) + self.fetch_finish(cmd[6:], d.get("on"), voice=False) elif cmd == "calibrate": self.calib_until = time.time() + CALIB_S if d.get("on", True) else 0.0 self.calib_n = 0 @@ -1544,6 +1614,29 @@ class Lumi: mouth.say("Okay, I'm going back." if en else "네, 원래 자리로 돌아갈게요.") return True + def publish_busy(self, what): + """Tell the API what runs (it refuses the dashboard's hand controls then); written only on a change.""" + if what == getattr(self, "busy_now", ""): + return + self.busy_now = what + try: + tmp = BUSY_FILE + ".tmp" + with open(tmp, "w") as f: + json.dump({"busy": what, "time": time.time()}, f) + os.replace(tmp, BUSY_FILE) + except OSError: + pass + + def doing(self): + from tasks import follow + if self.skill_thread is not None and self.skill_thread.is_alive(): + return "skill" + if follow.running(): + return "follow" + if self.patrol is not None and self.patrol.mode in ("patrol", "going_home"): + return "drive" + return None + def traveling(self): return self.patrol is not None and self.patrol.mode != "done" @@ -1794,6 +1887,8 @@ class Lumi: """Drive to a place the visitor just agreed to; the conversation stays open.""" en = self.lang == "en" 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 @@ -1808,6 +1903,8 @@ class Lumi: self.fetch_say("Sorry, I'm on a task right now. I can help you when I've finished.", "죄송해요, 지금 다른 일을 하고 있어요. 끝나면 도와드릴게요.") return True + if rule and (self.base_off(*rule) or needs_arm(*rule) and self.arm_off()): + return True if not rule or rule[0] not in ("go_to", "come", "follow", "quiet", "weather", "search", "move", "turn", "arm", "pick", "put", "move_object", "fetch", "look", "lift", "wave", "come_back"): return False @@ -1980,6 +2077,10 @@ class Lumi: gen = self.brain.respond_stream(text, self.markers, now=self.now_doing()[0] + seeing.facts_for(text)) head_ = next(gen) log(f" action {head_['action']} {head_['target']} ({time.time() - t:.1f} s)") + if self.base_off(head_["action"], head_["target"]) or \ + needs_arm(head_["action"], head_["target"]) and self.arm_off(): # the model's "Okay" is not said + gen.close() + return if head_["action"] == "come": gen.close() mouth.say("Okay, I'm coming." if self.lang == "en" else "네, 갈게요.") @@ -2096,7 +2197,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) - if abs(robot_angle) > view and self.modes.drive: + if abs(robot_angle) > view and self.modes.drive and self.modes.patrol: log(f" caller outside the camera ({robot_angle:+.0f} deg): turning toward the voice") self.turn_head(0) safe(agv.turn_by, math.radians(robot_angle)) @@ -2117,7 +2218,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: + elif self.modes.drive and self.modes.patrol: log(f" voice behind ({robot_angle:+.0f} deg): turning the base") self.turn_head(0) safe(agv.turn_by, math.radians(robot_angle)) @@ -2238,6 +2339,7 @@ class Lumi: """One pass of the camera behaviour (see the module docstring).""" self.modes.refresh() self.poll_commands() + self.publish_busy(self.doing()) if self.patrol and self.patrol.mode == "done" and not self.a.patrol: self.patrol = None # a dashboard / voice trip has arrived moving = self.traveling() diff --git a/manipulation/wave.py b/manipulation/wave.py index fed437d..c2ac3b1 100644 --- a/manipulation/wave.py +++ b/manipulation/wave.py @@ -36,7 +36,7 @@ HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turn # is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266 # Why Lumi does not wave, (English, Korean) -OFF = ("My arm is switched off, so I can't wave.", "팔이 꺼져 있어서 손을 흔들 수 없어요.") +OFF = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") BUSY = ("I'm busy with my arm right now.", "지금 팔로 하는 일이 있어요.") DRIVING = ("I can't wave while I'm moving.", "움직이는 동안에는 손을 흔들 수 없어요.") HOLDING = ("I'm holding something, so I won't wave.", "손에 물건을 들고 있어서 손을 흔들지 않을게요.") diff --git a/tasks/fetch.py b/tasks/fetch.py index 0dda05a..04e4fe3 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -172,6 +172,10 @@ _rest = [] # the running mission's steps still _pause = threading.Event() # set by pause() (someone talks to Lumi on the way): drives halt, the run # waits at the next step; resume() goes on where it was _thread = None +stay_put = False # set by assistant/lumi.py for a task asked by voice with only Greeter on: + # head and lift only, no base move, no waist turn (NEED_PATROL) +NEED_PATROL = ("For that I'd have to drive or turn. Switch on Patrol, please.", + "그러려면 이동하거나 돌아야 해요. 패트롤을 켜 주세요.") _task = {"start_pose": None, # map pose (x, y, theta) where the current task was given "trip_from": None} # where Lumi stood before its last trip, task or mission: "come back" # returns there (lumi.come_back); short moves and turns don't set it @@ -623,6 +627,9 @@ def _waist_to(rel): d = max(lo, min(hi, waist - _waist_turn() + rel)) - waist if abs(d) < 1.0: return True + if stay_put: + log("not turning my waist: Patrol is off") + return False _go_on() if _sweep_blocked(d, "turning my waist"): return False @@ -645,13 +652,18 @@ def _waist_front(): """Every base move starts with the waist at the front: navigation does not know the arm, and sideways it sticks out further. FetchError when the way back is not clear.""" if not _waist_to(0.0): + if stay_put: + raise FetchError(*NEED_PATROL) raise FetchError("My arm can't turn back to the front: something is in its way.", "팔을 앞으로 돌릴 수 없어요. 뭔가 막고 있어요.") def _turn(deg, holding=False, why="to look further"): """Turn the base on the spot by `deg` (+ = left), arm in look (holding: it is there already), the lift where it - is. False when it must not: charging, or the arm would hit something on the way (turn_hits).""" + is. False when it must not: Patrol off (stay_put), charging, or the arm would hit something on the way (turn_hits).""" + if stay_put: + log("not turning: Patrol is off") + return False if _charging(): log("on the charger: I don't turn") return False @@ -811,6 +823,8 @@ def _drive_to(place, say, watch_holding=False): abs((th - pth + math.pi) % (2 * math.pi) - math.pi) < SAME_ANGLE_RAD: return place = {"x": x, "y": y, "theta": th} + if stay_put: + raise FetchError(*NEED_PATROL) _waist_front() head_ahead() _lift_to(LIFT_DRIVE_MM) @@ -1065,7 +1079,9 @@ def _straight_clear(dist, speed=None): def _approach(obj, yaw, tried, goal=PICK_ZONE_CENTRE, holding=False): """One base move that should bring `obj` (x, y in the arm frame) to `goal`: turn on the spot and drive straight when the way is short and free; else navigation (around obstacles) to a stand-off point on a side of it not in - `tried`, facing it. FetchError when no side can be reached.""" + `tried`, facing it. FetchError when no side can be reached, or Patrol is off (stay_put).""" + if stay_put: + raise FetchError(*NEED_PATROL) t = arm_xy() move = approach_move((obj["x"], obj["y"]), yaw, t, goal) if move is None: @@ -2324,6 +2340,8 @@ def _straight(dist_m, speed=None): speed change applies at once) with joy_control (no turning), then stop. The last command lasts only the time left (no overshoot of up to 0.1 s). Stopped() on STOP; a pause stops it early. Returns the distance driven (m, by time).""" + if stay_put: + raise FetchError(*NEED_PATROL) rate = speed if callable(speed) else (lambda: speed or AXIS_SPEED) done, t = 0.0, time.time() try: diff --git a/tasks/follow.py b/tasks/follow.py index 37be7ef..07248aa 100644 --- a/tasks/follow.py +++ b/tasks/follow.py @@ -44,8 +44,7 @@ HEAD_VEL = 50 # speed ratio %; the head is at its full speed from 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.", "충전 중이라 따라갈 수 없어요.") -ARM_OFF = ("My arm is switched off, so I can't drive safely. Please enable it.", - "팔이 꺼져 있어서 안전하게 이동할 수 없어요. 팔을 켜 주세요.") +ARM_OFF = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.") # only when the arm must go to look ARM_BUSY = ("A program is running on my arm, so I can't follow you.", "팔에서 프로그램이 실행 중이라 따라갈 수 없어요.") LOST = ("I lost you, so I stopped. Stand in front of me and say follow me again.", "놓쳐서 멈췄어요. 제 앞에 서서 다시 따라오라고 말해 주세요.") diff --git a/tests/test_follow.py b/tests/test_follow.py index cb462a6..d43e53f 100644 --- a/tests/test_follow.py +++ b/tests/test_follow.py @@ -355,7 +355,7 @@ real_start = follow.start 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()) L.lang, L.voice_angle, L.voice_trusted = "en", 0.0, False -L.modes = types.SimpleNamespace(drive=True) +L.modes = types.SimpleNamespace(drive=True, patrol=True) L.skill_busy = lambda: False L.keep_listening = lambda: None L.fetch_say = lambda en, ko: spoken.append(en) diff --git a/tests/test_robot_free.py b/tests/test_robot_free.py new file mode 100644 index 0000000..7262361 --- /dev/null +++ b/tests/test_robot_free.py @@ -0,0 +1,100 @@ +"""Self-check of the dashboard's hand controls (api/server.py robot_free): refused while a task, a skill, following, +a wave or a drive runs; allowed when idle or paused, Patrol on or off; STOP always works. Fake state, no robot: +python tests/test_robot_free.py""" +import json +import tempfile +from pathlib import Path + +from fastapi import HTTPException + +from api import server +from tasks import fetch + +tmp = Path(tempfile.mkdtemp()) +fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm files +server.BUSY_FILE = tmp / "lumi_busy.json" +server.MODES_FILE = tmp / "lumi_modes.json" +base = {"move_status": "idle"} +server.agv.request = lambda cmd, timeout=3.0: {"results": dict(base)} +held = [] +server.jogger.hold = lambda *a: held.append(a) +server.gripper.open_ = server.gripper.close = lambda: {"ok": True} +server.assistant_pids = lambda: [12345] # lumi.py "runs" + + +def task(status, paused=False): + fetch.STATE_FILE.write_text(json.dumps({"status": status, "paused": paused})) + + +def refused(fn, *a): + try: + fn(*a) + except HTTPException as e: + assert e.status_code == 409 and e.detail == server.BUSY_MSG, e.detail + return True + return False + + +JOG = server.JogBody(axis="head_yaw", direction=1) +manual = (lambda: server.jog(JOG), server.gripper_open, server.gripper_close) + +# idle, Patrol on: allowed +server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": True})) +task("idle") +server.BUSY_FILE.write_text(json.dumps({"busy": None})) +assert not any(refused(f) for f in manual) +task("holding") +assert not refused(manual[0]) + +# a task or mission running: refused; paused: allowed +for status in ("running", "waiting"): + task(status) + assert all(refused(f) for f in manual), status + task(status, paused=True) + assert not any(refused(f) for f in manual), status + +# a running file whose runner died (no lumi.py, not this process) does not lock the controls +task("running") +server.assistant_pids = lambda: [] +assert not refused(manual[0]) +server.assistant_pids = lambda: [12345] +task("idle") + +# lumi.py follows / waves / drives / runs a skill: refused +for what in ("follow", "wave", "drive", "skill"): + server.BUSY_FILE.write_text(json.dumps({"busy": what})) + assert refused(manual[0]), what +server.BUSY_FILE.write_text(json.dumps({"busy": None})) + +# a drive to a marker (by the API or anyone): refused; the base unreachable: not busy +base["move_status"] = "running" +assert refused(manual[0]) +base["move_status"] = "succeeded" +assert not refused(manual[0]) +server.agv.request = lambda *a, **k: (_ for _ in ()).throw(OSError("no route")) +assert not refused(manual[0]) + +# non-manual robot calls still need lumi.py stopped +try: + server.robot_free() + raise AssertionError("robot_free() allowed while lumi.py runs") +except HTTPException as e: + assert e.status_code == 409 and "assistant" in e.detail + +# STOP works while a task runs +task("running") +calls = [] +server.jogger.stop = lambda: calls.append("jog") +server._route.stop = lambda: calls.append("route") +server._fetch_stop = lambda: calls.append("fetch") +server.assistant_stop = lambda: {"stopped": []} +server.send_to_assistant = lambda *a, **k: calls.append(a[0]) +server.agv.cancel = lambda: calls.append("agv") +server.skills.cancel = lambda: calls.append("arm") +server.stop_all() +server.task_stop() +server.jog_stop() +server.arm_stop() +assert {"jog", "route", "fetch", "agv", "arm", "fetch_stop"} <= set(calls), calls +assert len(held) == 7, held # the jogs that were allowed reached the (fake) jogger +print("robot_free: ok") diff --git a/tests/test_switches.py b/tests/test_switches.py new file mode 100644 index 0000000..93e4416 --- /dev/null +++ b/tests/test_switches.py @@ -0,0 +1,174 @@ +"""Self-check of the dashboard switches and the arm's state: with Greeter only Lumi works in place (head, lift, arm, +gripper, wave) and refuses the base and the waist with one line; Patrol on allows them; "stop" works either way; an +arm action with the arm switched off asks to enable it, nothing else asks. Fake state, no robot: +python tests/test_switches.py""" +import types + +from assistant import lumi +from tasks import fetch, follow + +M = ["home", "p3", "p8"] +moved, said = [], [] + + +def forbid(*a, **k): + raise AssertionError("a test reached the robot") + + +for mod in (lumi.agv, lumi.head, lumi.arm, lumi.gripper, lumi.motion, lumi.skills): # nothing may reach the robot + for name in dir(mod): + if not name.startswith("_") and callable(getattr(mod, name)) and not isinstance(getattr(mod, name), type): + setattr(mod, name, forbid) +lumi.wave_mod.wave = forbid +lumi.log = fetch.log = lambda *a: None +lumi.mouth = types.SimpleNamespace(say=lambda text, **k: said.append(text)) +arm_state = {"power": 1, "enable": 1} +lumi.arm.cmd = lambda name, **a: dict(arm_state) if name == "get_robot_state" else forbid() + +L = lumi.Lumi.__new__(lumi.Lumi) +L.lang, L.markers, L.current, L.patrol, L.vision, L.voice_angle = "en", M, None, None, None, 0.0 +L.turn_head = lambda *a: moved.append("head") +L.brain = types.SimpleNamespace(history=[]) +L.keep_listening = lambda: None +L.mission_running = lambda: False +L.fetch_status = lambda: None +L.skill_busy = lambda: False +FAKED = ("start_trip", "move_by", "come_to", "follow_me", "fetch_request", "object_task", "arm_pose", "lift", "look", + "come_back", "receive_from_hand") +for name in FAKED: + setattr(L, name, lambda *a, _n=name, **k: moved.append(_n) or _n != "look") # look: True would be "past range" +L.wave = lambda *a, **k: None # quick_command starts it in a thread + +BASE = {"go to p3": "go_to", "p3로 가": "go_to", "follow me": "follow", "따라와": "follow", "come here": "come", + "이리 와": "come", "move forward 1 meter": "move", "1미터 앞으로 가": "move", "turn left": "turn", + "come back": "come_back"} +IN_PLACE = {"look left": "look", "고개 들어": "look", "look behind you": "look", "lift up": "lift", "키 좀 낮춰": "lift", + "pick up the cup": "pick", "open your hand": "arm", "reach out your hand": "arm", "wave": "wave", + "bring me the cup": "fetch"} +for text, action in {**BASE, **IN_PLACE}.items(): + got = lumi.brain_mod.intent(text, M) + assert got and got[0] == action, (text, got) +DOES = {"go_to": "start_trip", "follow": "follow_me", "come": "come_to", "move": "move_by", "turn": "move_by", + "arm": "arm_pose", "pick": "object_task", "fetch": "fetch_request", "come_back": "come_back", + "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) +for text in BASE: + moved.clear() + said.clear() + assert L.quick_command(text) and moved == [] and said == [lumi.BASE_OFF_SAY[0]], (text, moved, said) +L.lang = "ko" +said.clear() +assert L.quick_command("p3로 가") and said == [lumi.BASE_OFF_SAY[1]] +L.lang = "en" +for text, action in IN_PLACE.items(): + moved.clear() + said.clear() + L.quick_command(text) + assert lumi.BASE_OFF_SAY[0] not in said, (text, said) + assert action == "wave" or moved == [DOES[action]], (text, moved) +for action, target in (("go_to", "p3"), ("follow", ""), ("move", "forward 1"), ("turn", "left 90"), ("come", "")): + moved.clear() + L.act(action, target) # the LLM's action: answer() has said the line + assert moved == [] and L.base_off(action, target, say=False), action +for action, target in (("look", "left"), ("lift", "up"), ("arm", "reach")): + moved.clear() + L.act(action, target) + assert moved == [DOES[action]], (action, moved) +said.clear() +assert L.mission_request("go to p3, wait 10 seconds and come back") and said == [lumi.BASE_OFF_SAY[0]] +said.clear() +L.heard = "그럼 가 보세요" +L.go_offered("p3") +assert said == [lumi.BASE_OFF_SAY[0]] + +# a fetch from or to a place drives: refused; one here runs in place (fetch.stay_put) +started = [] +real_start = fetch.start +fetch.start = lambda task, say=None: started.append((task, fetch.stay_put)) +lumi.agv.pose = lambda: (1.0, 2.0, 0.0) +said.clear() +L.fetch_start({"object": "cup", "source": {"marker": "p3"}, "dest": "here", "finish": "hold"}) +assert started == [] and said == [lumi.BASE_OFF_SAY[0]] +L.fetch_start({"object": "cup", "source": "here", "dest": "here", "finish": "hold"}) +assert started and started[-1][1] is True # in place: head and lift only + +# fetch.stay_put: no base, no waist; the search is the head and the lift +fetch.stay_put = True +fetch.head.status = lambda: [50.0, 30.0, 0.0, 0.0] # the waist turned 30 deg (jogged before) +fetch._waist_turn = lambda: 30.0 +fetch.head.moveto = forbid +fetch.agv.turn_by = fetch.agv.go_point = fetch.agv.go = fetch.agv.request = forbid +assert fetch._waist_to(0.0) is False and fetch._turn(90.0) is False +for fn, args in ((fetch._waist_front, ()), (fetch._straight, (0.5,)), (fetch._approach, ({"x": 0, "y": 900}, 0.0, set())), + (fetch._drive_to, ({"marker": "p3"}, None))): + try: + fn(*args) + raise AssertionError(f"{fn.__name__} moved with Patrol off") + except fetch.FetchError as e: + assert e.args == fetch.NEED_PATROL, (fn.__name__, e.args) +fetch.stay_put = False +fetch.start = real_start + +# ---------- the arm switched off: arm actions ask to enable it, the rest runs ---------- +arm_state.update(enable=0) +for text in ("pick up the cup", "reach out your hand", "wave", "bring me the cup"): + moved.clear() + said.clear() + assert L.quick_command(text) and moved == [] and said == [lumi.ARM_OFF_SAY[0]], (text, moved, said) +for text in ("look left", "lift up", "open your hand"): # the gripper alone does not ask + moved.clear() + said.clear() + L.quick_command(text) + assert lumi.ARM_OFF_SAY[0] not in said and moved, (text, said) +said.clear() +L.lang = "ko" +lumi.Lumi.receive_from_hand(L, "cup") +assert said == [lumi.ARM_OFF_SAY[1]] +L.lang = "en" +assert lumi.wave_mod.OFF == follow.ARM_OFF == lumi.ARM_OFF_SAY + +# follow: an enabled arm never refuses; a disabled one only when it must move to look +follow.fetch._charging = lambda: False +at_look = [True] +follow.fetch._at_pose = lambda name: at_look[0] +follow.fetch._look = lambda: "look" +follow.motion._ready = lambda: None if arm_state["enable"] else (_ for _ in ()).throw(follow.motion.MotionError("off")) +arm_state.update(enable=1) +assert follow.ready() is None +at_look[0] = False +assert follow.ready() is None # enabled: it may go to look +arm_state.update(enable=0) +assert follow.ready() == follow.ARM_OFF # off and not at look: ask +at_look[0] = True +assert follow.ready() is None # off but already at look: follows + +# ---------- stop works either way ---------- +stopped = [] +real_follow_stop, real_fetch_stop = follow.stop, fetch.stop +follow.stop = lambda: stopped.append("follow") +fetch.stop = lambda: stopped.append("fetch") +lumi.agv.cancel = lambda: stopped.append("base") +lumi.skills.cancel = lambda: stopped.append("skill") +lumi.motion.stop = lambda: stopped.append("arm") +said.clear() +L.stop_all() +assert stopped == ["fetch", "follow", "base", "skill", "arm"] and said == ["Okay, I stopped."], (stopped, said) +assert lumi.stop_order("stop", M) and lumi.stop_order("멈춰", M) + +# ---------- Patrol on: the base moves too ---------- +arm_state.update(enable=1) +L.modes.patrol = True +for text, action in {**BASE, **IN_PLACE}.items(): + moved.clear() + said.clear() + L.quick_command(text) + assert lumi.BASE_OFF_SAY[0] not in said, (text, said) + assert action == "wave" or moved == [DOES[action]], (text, moved) +moved.clear() +L.act("go_to", "p3") +assert moved == ["start_trip"] +follow.stop, fetch.stop = real_follow_stop, real_fetch_stop +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 3e402b9..7b10225 100644 --- a/tests/test_wave.py +++ b/tests/test_wave.py @@ -14,6 +14,7 @@ from tasks import fetch from vision import head_cam fetch.STATE_FILE = Path(tempfile.mkdtemp()) / "lumi_task.json" # never the real /dev/shm file +lumi.BUSY_FILE = str(fetch.STATE_FILE.parent / "lumi_busy.json") # nor the real busy file LOOK = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] POSES = {"look": LOOK, "wave_start": [-50.0, 0.0, 0.0, 0.0, 0.0, 0.0], "wave": [-50.0, 0.0, 60.0, 0.0, 30.0, 0.0]} HEAD = np.array([-100.0, -200.0, 700.0]) # mm, the head's turning centre in the toy arm diff --git a/tools/gitea_push.sh b/tools/gitea_push.sh new file mode 100755 index 0000000..ac38396 --- /dev/null +++ b/tools/gitea_push.sh @@ -0,0 +1,19 @@ +#!/bin/bash +# Publish the committed state of main to Gitea as one new commit on the clean `gitea` branch. +# Local main keeps the full history; Gitea only sees clean snapshots. Self-checks must pass first. +# tools/gitea_push.sh "what changed" +set -euo pipefail +cd "$(dirname "$0")/.." +TOKEN_FILE=~/.config/lumi/gitea_token # the owner's Gitea token, one line, chmod 600, never in git +MSG=${1:-"Update"} + +[ "$(git rev-parse main^{tree})" = "$(git rev-parse gitea^{tree})" ] && { echo "nothing new to push"; exit 0; } +for t in tests/test_*.py; do + .venv/bin/python "$t" > /dev/null 2>&1 || { echo "FAIL $t: not pushed"; exit 1; } +done +c=$(git commit-tree main^{tree} -p gitea -m "$MSG + +Co-Authored-By: Claude Opus 5.5 ") +git -c credential.helper= -c http.extraHeader="Authorization: token $(cat "$TOKEN_FILE")" push origin "$c:main" +git branch -f gitea "$c" +echo "pushed $c"