From fc73a90208679f93bf9109263ac5170f40b2edf2 Mon Sep 17 00:00:00 2001 From: Cutshion Date: Thu, 22 Oct 2026 16:42:37 +0900 Subject: [PATCH] Navigation drives watch the arm: the base is stopped before the arm would touch something and goes on when clear Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 2 +- api/server.py | 6 +- assistant/lumi.py | 9 ++ robot/agv.py | 36 ++++++-- robot/nav_guard.py | 185 ++++++++++++++++++++++++++++++++++++++++ tasks/fetch.py | 2 + tests/test_nav_guard.py | 134 +++++++++++++++++++++++++++++ 8 files changed, 362 insertions(+), 13 deletions(-) create mode 100644 robot/nav_guard.py create mode 100644 tests/test_nav_guard.py diff --git a/.gitignore b/.gitignore index 179caaf..ec02629 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,4 @@ docs/14_VOICE_ASSISTANT.md docs/15_PICK_AND_PLACE.md docs/16_FETCH_TASKS.md docs/17_MISSIONS.md +notes/ diff --git a/README.md b/README.md index e2ea4f0..be9c65d 100644 --- a/README.md +++ b/README.md @@ -131,7 +131,7 @@ lumi-wave/ run with the venv: .venv/bin/python / the move ends: the drive waiters' stuck checks are 20 / 30 s +REASON = ("I stopped: my arm would hit something on the way.", "팔이 가는 길에 있는 것에 부딪힐 것 같아서 멈췄어요.") + + +def log(msg): + print(time.strftime("%H:%M:%S"), "nav guard:", msg, flush=True) + + +def _arm(): + """The arm's points (x, y) m in the base frame, None when they can't be known (arm axis not measured, arm + controller not answering): then navigation drives unguarded, as before.""" + try: + from tasks import fetch # imported here: fetch imports agv, which starts this + return [tuple(p) for p in fetch.arm_points()] if fetch.arm_yaw() is not None else None + except Exception as e: # never stop a drive because the arm could not be asked + log(f"no arm points ({e}): unguarded") + return None + + +def _world(pose, p): + x, y, th = pose + c, s = math.cos(th), math.sin(th) + return x + c * p[0] - s * p[1], y + s * p[0] + c * p[1] + + +def ahead(pose, path, turn_rate): + """Base poses (x, y, theta) to check: the pose turned on at turn_rate (rad/s) for TURN_AHEAD_S, then every STEP_M + along `path` ([[x, y], ...], from its point nearest the base) up to LOOKAHEAD_M, heading along the path. + ponytail: the base is taken to drive forward along the path; a reversing drive is checked at the turn only.""" + out = [(pose[0], pose[1], pose[2] + turn_rate * TURN_AHEAD_S)] if abs(turn_rate) > 0.05 else [] + if len(path) < 2: + return out + i = min(range(len(path)), key=lambda k: math.hypot(path[k][0] - pose[0], path[k][1] - pose[1])) + want, done = STEP_M, 0.0 + for a, b in zip(path[i:], path[i + 1:]): + seg = math.hypot(b[0] - a[0], b[1] - a[1]) + if seg < 1e-6: + continue + th = math.atan2(b[1] - a[1], b[0] - a[0]) + while want <= min(done + seg, LOOKAHEAD_M) + 1e-9: + f = (want - done) / seg + out.append((a[0] + f * (b[0] - a[0]), a[1] + f * (b[1] - a[1]), th)) + want += STEP_M + done += seg + if done >= LOOKAHEAD_M: + break + return out + + +def hit(pose, poses, pts): + """The map point where an arm point at one of `poses` comes nearer than MARGIN_M to an obstacle and nearer than + it is at `pose` now (getting further from one is fine: it may start next to a table); None when clear.""" + for p in pts: + now = agv.clearance(*_world(pose, p)) + for q in poses: + w = _world(q, p) + c = agv.clearance(*w) + if c < MARGIN_M and c < now: + return w + return None + + +def watch(command, gen): + """Guard the navigation move `command` (sent just now) until it ends or agv's guard generation moves on.""" + threading.Thread(target=_run, args=(command, gen), daemon=True, name="nav-guard").start() + + +def _status(): + return agv.request("/api/robot_status").get("results") or {} + + +def _pose(st): + p = st.get("current_pose") or {} + return (p["x"], p["y"], p["theta"]) if "x" in p else None + + +def _run(command, gen): + pts = _arm() + if not pts: + return + mine = lambda: agv._guard["gen"] == gen + sent, path, path_t, last, rate, blocked = time.time(), [], 0.0, None, 0.0, 0.0 + while mine(): + time.sleep(POLL_S) + try: + st = _status() + pose = _pose(st) + if st.get("move_status") != "running": + if time.time() - sent > START_S: + agv._guard["held"] = False + return # arrived, failed, or cancelled by someone else + continue + agv._guard["held"] = False # going again after a hold + if pose is None: + continue + now = time.time() + if last is not None and now > last[1]: + rate = ((pose[2] - last[0][2] + math.pi) % (2 * math.pi) - math.pi) / (now - last[1]) + last = (pose, now) + if now - path_t > PATH_EVERY_S: + path, path_t = agv.request("/api/get_planned_path").get("results", {}).get("path") or [], now + w = hit(pose, ahead(pose, path, rate), pts) + except (OSError, KeyError, TypeError, ValueError): + continue + if w is None or not mine(): + continue + agv._guard["held"] = True # before the cancel: waiters never see "canceled" + try: + agv.request("/api/move/cancel") + except OSError as e: + log(f"cancel failed: {e}") + log(f"stopped at ({pose[0]:.2f}, {pose[1]:.2f}): the arm would come within {MARGIN_M:.2f} m of something " + f"at ({w[0]:.2f}, {w[1]:.2f})") + blocked = _hold(command, gen, path, rate, pts, blocked) + if blocked is None: + return + sent, last, path_t = time.time(), None, 0.0 + + +def _hold(command, gen, path, rate, pts, blocked): + """Wait, the base stopped, until the way it was going is clear for CLEAR_S, then send `command` again; returns + the time blocked so far. None when the guard ends here: BLOCK_S blocked in all (the move fails with REASON), an + E-stop, or agv moved on (cancel, a new go).""" + t0, clear_since = time.time(), None + while agv._guard["gen"] == gen: + time.sleep(POLL_S) + if blocked + time.time() - t0 > BLOCK_S: + agv._guard.update(held=False, reason=REASON) + log(f"blocked {BLOCK_S:.0f} s: the move ends") + return None + try: + st = _status() + if st.get("soft_estop_state") or st.get("hard_estop_state") or st.get("estop_state"): + agv._guard.update(held=False, reason=REASON) + log("E-stop while stopped: the move ends") + return None + pose = _pose(st) + w = None if pose is None else hit(pose, ahead(pose, path, rate), pts) + except (OSError, KeyError, TypeError, ValueError): + continue + if pose is None or w is not None: + clear_since = None + continue + clear_since = clear_since or time.time() + if time.time() - clear_since < CLEAR_S: + continue + if agv._guard["gen"] != gen: + break + try: + r = agv.request(command) + except OSError as e: + r = {"error_message": str(e)} + if r.get("status") != "OK": + agv._guard.update(held=False, reason=REASON) + log(f"could not go on ({r.get('error_message') or r.get('status')}): the move ends") + return None + log("the way is clear: going on") # held until the base reports "running" (_run) + return blocked + time.time() - t0 + return None diff --git a/tasks/fetch.py b/tasks/fetch.py index 9e545a5..69a84be 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -470,6 +470,8 @@ def _drive_wait(watch_holding, again, goal): raise FetchError("I dropped it.") there = st == "succeeded" and goal is not None and pose is not None and _at(pose, goal) if st != "running" and (seen_running or there or time.time() - t0 > DRIVE_START_S): + if isinstance(full.get("guard"), (list, tuple)): + raise FetchError(*full["guard"]) # robot/nav_guard.py ended it: the arm would hit something if st != "succeeded": raise FetchError(f"I couldn't get there (base: {st}).") return diff --git a/tests/test_nav_guard.py b/tests/test_nav_guard.py new file mode 100644 index 0000000..ea4a874 --- /dev/null +++ b/tests/test_nav_guard.py @@ -0,0 +1,134 @@ +"""Self-check of the arm guard on navigation drives (robot/nav_guard.py, agv.go_point / status / cancel) with a fake +base that drives its planned path and fake distance probes, no robot, no network: python tests/test_nav_guard.py""" +import math +import re +import threading +import time + +from robot import agv, nav_guard +from tasks import fetch + +nav_guard.POLL_S = 0.01 +nav_guard.CLEAR_S = 0.1 +nav_guard.START_S = 0.3 +nav_guard.PATH_EVERY_S = 0.05 +nav_guard.BLOCK_S = 1.0 +nav_guard.log = lambda msg: logs.append(msg) +ARM = [(0.30, 0.40), (0.36, 0.40), (0.42, 0.40)] # m, base frame: flange, grasp point, tips out to the left +fetch.arm_yaw = lambda: -86.0 +fetch.arm_points = lambda: ARM +fetch.skills._ask = lambda *a, **k: (_ for _ in ()).throw(AssertionError("a test reached the arm")) +logs = [] + + +class Base: + """Drives straight along +x at SPEED from (0, 0) to the goal while "running"; obstacles are points; a cancel + stops it on the spot.""" + SPEED = 0.6 + + def __init__(self, obstacles): + self.obstacles = list(obstacles) + self.x, self.status, self.t, self.goal = 0.0, "idle", time.time(), 0.0 + self.sent, self.closest = [], float("inf") + self.lock = threading.Lock() + agv.request = self.request + + def _drive(self): + now = time.time() + if self.status == "running": + self.x = min(self.goal, self.x + self.SPEED * (now - self.t)) + if self.x >= self.goal: + self.status = "succeeded" + self.t = now + for p in ARM: # the arm's real distance to the obstacles + self.closest = min([self.closest] + [math.hypot(self.x + p[0] - ox, p[1] - oy) for ox, oy in self.obstacles]) + + def request(self, cmd, timeout=3.0): + with self.lock: + self._drive() + if cmd == "/api/robot_status": + return {"results": {"move_status": self.status, "current_pose": {"x": self.x, "y": 0.0, "theta": 0.0}}} + m = re.match(r"/api/move\?location=([-\d.]+),", cmd) + if m: + self.sent.append(cmd) + self.status, self.goal = "running", float(m.group(1)) + return {"status": "OK"} + if cmd == "/api/move/cancel": + self.status = "canceled" if self.status == "running" else self.status + return {"status": "OK"} + if cmd == "/api/get_planned_path": + return {"results": {"path": [[self.x + k * 0.05, 0.0] for k in range(int((self.goal - self.x) / 0.05) + 1)] + if self.status == "running" else []}} + m = re.match(r"/api/map/distance_probe\?x=([-\d.]+)&y=([-\d.]+)$", cmd) + if m: + x, y = float(m.group(1)), float(m.group(2)) + d = min([math.hypot(x - ox, y - oy) for ox, oy in self.obstacles] or [-1]) + return {"results": {"env_dist": {"obstacle": d, "static": -1}}} + raise AssertionError(f"unexpected command {cmd}") + + +def wait_end(limit=5.0): + t0 = time.time() + while time.time() - t0 < limit: + st = agv.status() + if st["move_status"] != "running": + return st + time.sleep(0.02) + raise AssertionError("the move never ended") + + +# 1. A table edge 0.45 m left of the path, where the arm passes 0.05 m from it: stopped before, the table taken +# away (a person walks off): the same goal again, arrived. +base = Base([(1.5, 0.45)]) +assert agv.go_point(3.0, 0.0, 0.0) == (True, "OK") +t0 = time.time() +while not any("stopped" in m for m in logs) and time.time() - t0 < 3: + time.sleep(0.01) +assert any("stopped" in m for m in logs), logs +time.sleep(0.2) +st = agv.status() +assert st["move_status"] == "running" and st["guard"] == "held", st # waiters wait on +assert base.status == "canceled" and base.x < 1.5 - ARM[-1][0], base.x # stopped before the edge +assert base.closest > nav_guard.MARGIN_M / 2, base.closest +base.obstacles.clear() +st = wait_end() +assert st["move_status"] == "succeeded" and len(base.sent) == 2 and base.x == 3.0, (st, base.sent) +assert any("going on" in m for m in logs), logs + +# 2. The table stays: stopped, then after BLOCK_S the move ends "failed" with the reason (EN + KO); no new goal. +logs.clear() +base = Base([(1.5, 0.45)]) +agv.go_point(3.0, 0.0, 0.0) +st = wait_end() +assert st["move_status"] == "failed" and st["guard"] == nav_guard.REASON, st +assert len(base.sent) == 1 and base.x < 1.5 - ARM[-1][0] and base.closest > nav_guard.MARGIN_M / 2, (base.sent, base.x) +assert any("blocked" in m for m in logs), logs +agv.go_point(0.0, 0.0, 0.0) # a new goal forgets the reason +assert agv.status().get("guard") is None + +# 3. Starting next to a table (the arm over its edge) and driving away from it: never stopped. +logs.clear() +base = Base([(0.36, 0.45)]) +base.x = 0.0 +agv.go_point(1.0, 0.0, 0.0) +st = wait_end() +assert st["move_status"] == "succeeded" and not any("stopped" in m for m in logs), (st, logs) + +# 4. STOP (agv.cancel) while held: the goal is never sent again. +logs.clear() +base = Base([(1.5, 0.45)]) +agv.go_point(3.0, 0.0, 0.0) +t0 = time.time() +while not any("stopped" in m for m in logs) and time.time() - t0 < 3: + time.sleep(0.01) +agv.cancel() +base.obstacles.clear() +time.sleep(0.5) +assert len(base.sent) == 1 and agv.status()["move_status"] == "canceled", base.sent + +# 5. Lookahead along a bent path, and the turn rate: poses checked. +p = nav_guard.ahead((0.0, 0.0, 0.0), [[0, 0], [0.1, 0], [0.1, 0.5]], 1.0) +assert len(p) == 3 and abs(p[0][2] - nav_guard.TURN_AHEAD_S) < 1e-9, p # turned on, then 0.15, 0.30 +assert abs(p[1][0] - 0.1) < 1e-9 and abs(p[1][1] - 0.05) < 1e-9 and abs(p[2][1] - 0.2) < 1e-9, p +assert abs(p[2][2] - math.pi / 2) < 1e-9, p +print("nav guard ok")