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 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 16:42:37 +09:00
co-authored by Claude Opus 5.5
parent c4d9b07558
commit fc73a90208
8 changed files with 362 additions and 13 deletions
+1
View File
@@ -42,3 +42,4 @@ docs/14_VOICE_ASSISTANT.md
docs/15_PICK_AND_PLACE.md docs/15_PICK_AND_PLACE.md
docs/16_FETCH_TASKS.md docs/16_FETCH_TASKS.md
docs/17_MISSIONS.md docs/17_MISSIONS.md
notes/
+1 -1
View File
@@ -131,7 +131,7 @@ lumi-wave/ run with the venv: .venv/bin/python <folder>/<mo
├── assistant/ the voice assistant: main loop (lumi.py), answers (brain.py), knowledge, web lookups ├── assistant/ the voice assistant: main loop (lumi.py), answers (brain.py), knowledge, web lookups
├── audio/ microphones, speech to text, text to speech, voice direction ├── audio/ microphones, speech to text, text to speech, voice direction
├── vision/ camera service (the only camera owner), detection, objects in mm, calibration ├── vision/ camera service (the only camera owner), detection, objects in mm, calibration
├── robot/ one driver per piece of hardware: base, body, arm, gripper; checked arm motion ├── robot/ one driver per piece of hardware: base, body, arm, gripper; checked arm motion; the arm guard on navigation drives
├── manipulation/ pick and place skills, the arm's pose graph, the wave ├── manipulation/ pick and place skills, the arm's pose graph, the wave
├── tasks/ whole jobs made of skills, driving and talking ├── tasks/ whole jobs made of skills, driving and talking
├── tests/ self-checks without the robot ├── tests/ self-checks without the robot
+3 -3
View File
@@ -715,9 +715,9 @@ def go_point(body: PointBody):
send_to_assistant("go_point", point=[body.x, body.y, body.theta]) send_to_assistant("go_point", point=[body.x, body.y, body.theta])
return {"ok": True, "by": "assistant"} return {"ok": True, "by": "assistant"}
part(fetch_head_ahead) part(fetch_head_ahead)
r = agv.request(f"/api/move?location={body.x:.3f},{body.y:.3f},{body.theta:.3f}") ok, msg = agv.go_point(body.x, body.y, body.theta)
if r.get("status") != "OK": if not ok:
raise HTTPException(502, f"AGV refused: {r.get('error_message') or r}") raise HTTPException(502, f"AGV refused: {msg}")
return {"ok": True} return {"ok": True}
+9
View File
@@ -569,6 +569,7 @@ class Patrol:
self.moving = False # a move that we started is running self.moving = False # a move that we started is running
self.progress = None # (pose, time) of the last movement, to notice a stuck drive self.progress = None # (pose, time) of the last movement, to notice a stuck drive
self.stuck = None # target of a drive that could not get anywhere (Lumi says so) self.stuck = None # target of a drive that could not get anywhere (Lumi says so)
self.stuck_why = None # (en, ko) when robot/nav_guard.py ended it (the arm would hit something)
self.wait_until = 0.0 self.wait_until = 0.0
self.last_poll = 0.0 self.last_poll = 0.0
@@ -638,6 +639,8 @@ class Patrol:
self.i = (self.i + 1) % len(self.route) self.i = (self.i + 1) % len(self.route)
self.wait_until = now + self.pause_s self.wait_until = now + self.pause_s
else: else:
if isinstance(st.get("guard"), (list, tuple)):
self.stuck, self.stuck_why = self.route[self.i], st["guard"]
log(f"patrol move {ms} - retry in 5 s") log(f"patrol move {ms} - retry in 5 s")
self.wait_until = now + 5 self.wait_until = now + 5
return return
@@ -1979,6 +1982,10 @@ class Lumi:
def say_stuck(self): def say_stuck(self):
if self.patrol and self.patrol.stuck: if self.patrol and self.patrol.stuck:
target, self.patrol.stuck = self.patrol.stuck, None target, self.patrol.stuck = self.patrol.stuck, None
why, self.patrol.stuck_why = self.patrol.stuck_why, None
if why:
mouth.say(why[0] if self.lang == "en" else why[1])
return
name = "my charging dock" if target == "home" else target name = "my charging dock" if target == "home" else target
mouth.say(f"Sorry, I can't find a way to {name}. Something may be blocking the path.") mouth.say(f"Sorry, I can't find a way to {name}. Something may be blocking the path.")
@@ -2543,6 +2550,8 @@ class Lumi:
st = safe(agv.status, default={}) or {} st = safe(agv.status, default={}) or {}
if st.get("move_status") != "running": if st.get("move_status") != "running":
log(f" arrived ({st.get('move_status')})") log(f" arrived ({st.get('move_status')})")
if isinstance(st.get("guard"), (list, tuple)):
mouth.say(st["guard"][0] if self.lang == "en" else st["guard"][1])
break break
if self.vision.present(track): if self.vision.present(track):
if track.distance <= COME_STOP: if track.distance <= COME_STOP:
+27 -9
View File
@@ -20,6 +20,9 @@ _known = {"t": 0.0, "names": []}
# connection still answered after 90 s. # connection still answered after 90 s.
_conn = {"sock": None, "buf": ""} _conn = {"sock": None, "buf": ""}
_conn_lock = threading.Lock() _conn_lock = threading.Lock()
# robot/nav_guard.py's state of the navigation move this process sent: gen counts go / go_point / cancel (a guard
# whose gen is old stops); held: the guard cancelled it until the way is clear; reason: (en, ko) why it ended it.
_guard = {"gen": 0, "held": False, "reason": None}
def _ask(command, tag, timeout): def _ask(command, tag, timeout):
@@ -65,7 +68,27 @@ def request(command, timeout=3.0):
def status(): def status():
return request("/api/robot_status").get("results", {}) """robot_status. A move nav_guard holds reads "running", one it ended "failed" with "guard": (en, ko)."""
st = request("/api/robot_status").get("results", {})
if st.get("move_status") in ("canceled", "idle"):
if _guard["held"]:
return {**st, "move_status": "running", "guard": "held"}
if _guard["reason"]:
return {**st, "move_status": "failed", "guard": _guard["reason"]}
return st
def _move(command):
"""Send a navigation move (cancelling one that runs) and guard the arm along it (robot/nav_guard.py)."""
if status().get("move_status") == "running":
cancel()
r = request(command)
ok = r.get("status") == "OK"
_guard.update(gen=_guard["gen"] + 1, held=False, reason=None)
if ok:
from robot import nav_guard # imported here: it needs the arm (tasks.fetch), which imports this
nav_guard.watch(command, _guard["gen"])
return ok, r.get("error_message") or r.get("status")
def dock_marker(): def dock_marker():
@@ -97,18 +120,12 @@ def known_markers(fresh=False):
def go(marker): def go(marker):
"""Start driving to a marker. Returns (ok, message).""" """Start driving to a marker. Returns (ok, message)."""
marker = (dock_marker() or DOCK_FALLBACK) if marker == "home" else marker marker = (dock_marker() or DOCK_FALLBACK) if marker == "home" else marker
if status().get("move_status") == "running": return _move(f"/api/move?marker={marker}")
request("/api/move/cancel")
r = request(f"/api/move?marker={marker}")
return r.get("status") == "OK", r.get("error_message") or r.get("status")
def go_point(x, y, theta): def go_point(x, y, theta):
"""Start driving to a map point (m, rad). Returns (ok, message).""" """Start driving to a map point (m, rad). Returns (ok, message)."""
if status().get("move_status") == "running": return _move(f"/api/move?location={x:.3f},{y:.3f},{theta:.3f}")
request("/api/move/cancel")
r = request(f"/api/move?location={x:.3f},{y:.3f},{theta:.3f}")
return r.get("status") == "OK", r.get("error_message") or r.get("status")
def pose(): def pose():
@@ -136,6 +153,7 @@ def clearance(x, y):
def cancel(): def cancel():
_guard.update(gen=_guard["gen"] + 1, held=False, reason=None)
return request("/api/move/cancel").get("status") return request("/api/move/cancel").get("status")
+185
View File
@@ -0,0 +1,185 @@
"""Keeps the arm off things while navigation drives (/api/move to a marker or a point). The base plans and avoids
obstacles for its own footprint only; the arm sticks out past it (in look the flange is ~0.44 m from the base
centre). agv.go() / go_point() start watch() for every navigation move. While the move runs, the arm's points
(flange, grasp point, finger tips: tasks.fetch.arm_points) are checked at the base's pose now, turned on at its turn
rate for TURN_AHEAD_S, and along the planned path up to LOOKAHEAD_M ahead. An arm point that would come nearer than
MARGIN_M to anything the lidar or the map shows (agv.clearance), and nearer than it is now, cancels the move (the base
has no pause command; cancel stops it on the spot). The same goal is sent again once that way has been clear for
CLEAR_S; blocked BLOCK_S in all, the move ends "failed" with REASON (agv.status() "guard").
While the guard holds a move, agv.status() reports it "running", so every waiter (fetch, missions, come here,
the dashboard route) waits on; agv.cancel() or a new go ends the guard.
"""
import math
import threading
import time
from robot import agv
MARGIN_M = 0.10 # m; an arm point nearer than this to an obstacle stops the drive (estimate, tune live)
LOOKAHEAD_M = 0.30 # m along the planned path checked ahead of the base: ~1 s at 0.3 m/s, its stop included (estimate)
STEP_M = 0.15 # m between the path points checked
TURN_AHEAD_S = 0.5 # s; a turning base (on the spot at a goal too) is checked this far ahead at its turn rate now
POLL_S = 0.1 # s between checks (a check is ~10 distance probes at 5-15 ms each: ~5-8 Hz in all)
PATH_EVERY_S = 1.0 # s between reads of the planned path
START_S = 3.0 # s after a move is sent in which a status other than "running" is not believed yet
CLEAR_S = 1.0 # s the way must stay clear before the goal is sent again
BLOCK_S = 10.0 # s blocked in all (per goal) -> 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
+2
View File
@@ -470,6 +470,8 @@ def _drive_wait(watch_holding, again, goal):
raise FetchError("I dropped it.") raise FetchError("I dropped it.")
there = st == "succeeded" and goal is not None and pose is not None and _at(pose, goal) 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 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": if st != "succeeded":
raise FetchError(f"I couldn't get there (base: {st}).") raise FetchError(f"I couldn't get there (base: {st}).")
return return
+134
View File
@@ -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")