Recover the arm from any pose, put down on a remembered table and wave back at people

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 18:22:46 +09:00
co-authored by Claude Opus 5.5
parent b4ab7c71b1
commit eb8975ff6e
25 changed files with 1613 additions and 108 deletions
+75
View File
@@ -0,0 +1,75 @@
"""Self-check of an arm with its wrist turned over (J4 / J6 half a turn off and J5's sign flipped against the taught
poses) while holding a cup, with the taught poses, the measured head centre and the offline arm kinematics
(tests/pick_sweep.py simulator), no robot: python tests/test_arm_flip.py
Live 2026-10-30 15:01: a voice pick ended at its lift pose with the wrist turned over; the straight move to give
ended on the same wrist branch and from there every way back was refused (arm_route UNKNOWN)."""
import sys
from pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import no_robot # noqa: F401 any connection to the robot fails the test
from tests import pick_sweep as ps
ps.install()
fetch, skills, motion, kin = ps.fetch, ps.skills, ps.motion, ps.kin
from manipulation import arm_route # noqa: E402
STUCK = [-270.5, -88.9, -12.1, -348.9, -27.3, -51.9] # live: give's flange pose, the wrist turned over
LIFT = [-282.3, -84.7, -44.5, 114.9, -16.3, -169.2] # the live pick's lift pose (-10, 499, -73), turned
CENTRE = ps.HEAD_CENTRE
def lowest(j):
return arm_route.profile(j, j, CENTRE)[1]
def check_way(start, seq):
"""Every move of a plan: no wave pose, the cup upright, clear of the head, no dip; the wrist turning back never
takes the gripper below where it started (PATH_SAG_MM)."""
prev, floor = list(start), lowest(start)
for n, j in seq:
assert n not in arm_route.WAVE_POSES, seq
clear, ends, low, tilt = arm_route.profile(prev, j, CENTRE)
assert tilt <= skills.MAX_TILT_DEG and clear >= arm_route.HEAD_CLEAR_MM, (n, clear, tilt)
assert low >= (floor if n == "wrist" else ends) - skills.PATH_SAG_MM, (n, low, floor, ends)
prev = j
assert np.allclose(kin.pose(STUCK)[:3], kin.pose(motion.poses()["give"])[:3], atol=2.0) # the same hand, turned over
# ---------- the planner: from the live stuck pose, holding, a checked way to each pose ----------
for target in ("look", "carry", "give"):
seq = arm_route.plan(target, holding=True, now=list(STUCK))
assert seq and seq[0][0] == "wrist", seq # the wrist turns back first, where it is
assert max(abs(a - b) for a, b in zip(seq[-1][1], motion.nearest(motion.poses()[target], seq[-1][1]))) < 0.01
check_way(STUCK, seq)
print(target, "from the stuck pose:", " -> ".join(n for n, _ in seq))
try:
arm_route.plan("wave_start", holding=True, now=list(STUCK))
raise AssertionError("a wave pose with a cup")
except arm_route.RouteError as e:
assert e.args == arm_route.SPILL, e.args
assert arm_route.plan("look", now=list(STUCK))[-1][0] == "look" # empty hand: a way too
# ---------- fetch's moves with the cup from the turned-over lift pose: never left turned over at a pose ----------
for target in ("give", "carry", fetch.LOOK_POSE):
ps.setup(ps.pick_at(-104, 656, -182, height=142), 0.0)
ps.W["hand"].update(holding=True, closed=True)
fetch._state.update(holding=True)
ps.W["J"] = list(LIFT)
fetch._line_holding(target)
assert fetch._at_pose(target), (target, [round(v, 1) for v in ps.W["J"]])
print(target, "from the lift pose: at", target)
# ---------- the voice pick of the live scene: the turned-over grasp, then carried to look (not left at the lift) ----
ps.setup(ps.pick_at(-104, 656, -182, height=142), 0.0)
fetch.pick_here("cup")
assert any("wrist J5 -13" in l for l in ps.W["lines"]), ps.W["lines"] # the live grasp: J4 of the other wrist near
assert ps.W["hand"]["holding"] and fetch._state["holding"] # its limit (from look's +200) on the way up
assert fetch._at_pose(fetch.LOOK_POSE), [round(v, 1) for v in ps.W["J"]]
print("voice pick: held at look")
print("arm flip ok")
+11 -1
View File
@@ -400,7 +400,8 @@ skills.on_table = lambda spots, table: [p for p in spots if p[1] >= 760][:1] if
else [p for p in spots if p[1] <= 700][:1]
far_held = dict(skills._held)
real_chain, real_options = skills.ik_chain, skills.place_options
far_spot = lambda n: n.startswith("to (") and float(n.split(", ")[1].split(")")[0]) > 740 # line to a spot y > 740
far_spot = lambda n: n.startswith("to (") and (float(n.split(", ")[1].split(")")[0]) > 740 # line to a spot y > 740
or not any(c[0] == "joy" for c in calls)) # any before the drive
skills.ik_chain = lambda wp, j: [[n, p, [0] * 6, "no IK solution" if far_spot(n) else None] for n, p in wp]
skills.place_options = lambda *a: iter(()) # ... the arm does not reach it from here
st = run(fetch.place)
@@ -827,6 +828,15 @@ st = run(fetch.give)
assert st["status"] == "done" and not st["holding"] and ("open",) in calls, (st, calls)
fetch.motion.poses = lambda: {"ready": [0] * 6, "carry": [3] * 6, "look": [0] * 6}
# ---------- holding, the person says they hold it ("I've got it"): open where the arm is, nothing held ----------
reset()
st = run(fetch.start, ok)
assert st["status"] == "holding", st
calls.clear()
assert fetch.let_go() is True
st = fetch.state()
assert st["status"] == "idle" and not st["holding"] and calls == [("open",)] and not skills._held, (st, calls)
# ---------- another process holds it: give / place here take it over ----------
reset()
skills._held.clear()
+136
View File
@@ -0,0 +1,136 @@
"""Self-check of the head during a fetch (tasks/fetch.py _aim_head): once the object or the place is found the head
turns to it and stays on it while the base turns, for the pick and the put down; assistant/lumi.py does not turn
the head to people meanwhile. Fake head, base and head camera (no robot): python tests/test_fetch_head_aim.py"""
import math
import tempfile
import time
from pathlib import Path
import numpy as np
import no_robot # noqa: F401 any connection to the robot fails the test
from manipulation import skills
from tasks import fetch
from assistant import lumi
tmp = Path(tempfile.mkdtemp())
fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file
fetch.CALIB_FILE = tmp / "fetch_calib.json" # arm frame = base frame, the waist at the front
fetch.CALIB_FILE.write_text('{"arm_yaw_in_base_deg": 0.0, "arm_xy_in_base_m": [0.0, 0.0], "waist_deg": 0.0}')
fetch.DRIVE_POLL_S = 0.01
fetch.HEAD_AIM_EVERY_S = 0.0
body = [0.0, 0.0, 0.0, fetch.HEAD_LOW_PITCH] # lift, waist, head yaw, head pitch
moves = [] # head yaw of every body move
def moveto(pos, vel=None, acc=None, timeout=None):
moves.append(round(pos[2]))
body[:] = [float(p) for p in pos]
fetch.head.status = lambda: list(body)
fetch.head.moveto = moveto
fetch.camview.want = lambda name: None
skills.moved = lambda *a, **kw: None
pose = [0.0, 0.0, 0.0] # map x, y (m), theta (rad)
fetch.agv.pose = lambda: tuple(pose)
fetch.agv.cancel = lambda: None
def base_from_head(yaw, pitch):
"""A head camera at the arm origin: yaw 0 looks along arm +y, + yaw turns it left (counter-clockwise)."""
s, c = math.sin(math.radians(yaw)), math.cos(math.radians(yaw))
T = np.eye(4)
T[:3, :3] = np.array([[c, s, 0.0], [0.0, 0.0, -1.0], [-s, c, 0.0]]).T # columns: right, down, forward
return T
fetch.head_cam.base_from_head = base_from_head
bearing = lambda x, y: math.degrees(math.atan2(-x, y)) # + left of arm +y
def near(a, b, tol=1.0):
return abs(a - b) <= tol
# a new run: no target, the head is lumi.py's (a person's) to turn
fetch._clear()
assert not fetch.aiming()
heads = []
lumi.head.turn = lambda yaw, pitch=None: heads.append(round(yaw))
L = lumi.Lumi.__new__(lumi.Lumi)
L.turn_head(20)
time.sleep(0.2)
assert heads == [20], heads
# the torso camera found the cup at (-300, 600) (the pick: _reach): the head turns to it
cup = {"x": -300.0, "y": 600.0, "top_mm": -250.0}
fetch._aim_head(cup)
assert fetch.aiming() and near(body[2], bearing(-300, 600)), body
# lumi.py's focus on a person, a greeting, a voice: the head stays on the cup
heads.clear()
L.turn_head(-40)
L.turn_head(0, force=True)
time.sleep(0.2)
assert heads == [], heads
# a look again (_see_again, _look_at ahead) keeps the head on the cup, not ahead of the waist
assert fetch._look_at(0.0, lambda: "seen") == "seen"
assert near(body[2], bearing(-300, 600)), body
# the base turns left to face it (+26.6 deg): the head turns back with it, staying on the cup
step = math.atan2(300, 600) / 10
polls = {"n": 0}
def status():
polls["n"] += 1
if polls["n"] <= 10:
pose[2] += step
return {"move_status": "running", "current_pose": {"x": 0.0, "y": 0.0, "theta": pose[2]}}
return {"move_status": "succeeded", "current_pose": {"x": 0.0, "y": 0.0, "theta": pose[2]}}
fetch.agv.status = status
moves.clear()
fetch._wait_drive()
assert len(moves) >= 2 and all(b < a for a, b in zip(moves, moves[1:])), moves # several small turns back
x, y = fetch.arm_frame(fetch._aim["world"])
assert near(bearing(x, y), 0.0) and abs(body[2]) <= fetch.HEAD_AIM_DEG, (x, y, body)
# the pick: the head turned away (head_hits checked a turn's sweep) comes back onto the cup before the arm moves
body[2] = 60.0
picked = []
skills._held.clear()
skills._guarded = lambda fn, *a: fn(*a)
skills._do_pick = lambda obj, wp, ja: picked.append(body[2])
fetch._pick({"x": x, "y": y, "top_mm": -250.0}, [], [0.0] * 6)
assert len(picked) == 1 and near(picked[0], 0.0), picked
assert not fetch.aiming() # in the hand: the head is free again
# the put down: the head turns to the spot before the arm goes there
placed = []
skills._held.update(yaw=0.0)
skills.plan_place = lambda x, y, top, yaw=0.0: [("above", [x, y, top + 100.0, 0, 0, 0]), ("place", [x, y, top, 0, 0, 0])]
fetch._line_rows = lambda target, label, start=None: [[label, target, [0.0] * 6, None]]
skills.ik_chain = lambda wp, j: [[n, p, [0.0] * 6, None] for n, p in wp]
fetch.motion.move_linear = lambda target=None, **kw: None
skills._do_place = lambda rows: placed.append(body[2])
fetch._pose = lambda name, holding=False, leaf=False: None
assert fetch._place_at([(-200.0, 650.0)], -320.0) is True
assert len(placed) == 1 and near(placed[0], bearing(-200, 650)), placed
assert fetch.aiming()
# the task ends (head_ahead) or a STOP: the head is lumi.py's again
fetch.head_ahead()
assert not fetch.aiming() and body[2] == 0.0, body
fetch._aim_head(cup)
fetch._stop.set()
assert not fetch.aiming()
fetch._clear()
heads.clear()
L.turn_head(-40)
time.sleep(0.2)
assert heads == [-40], heads
print("fetch head aim: ok")
+10 -2
View File
@@ -90,7 +90,7 @@ def settle():
# ---- talking with #1 (right), #2 walks in on the left and waves: no greeting, the head stays on #1 as they move ----
L = fresh(a := Track(1, 30.0))
L = fresh(a := Track(1, 30.0, 2.0)) # past 1.6 m: no calibration sample from it
a.greeted, L.current = True, a
L.vision.tracks.append(b := Track(2, -40.0))
up.append(-40.0)
@@ -125,7 +125,15 @@ for text, takes in (("The weather is nice today.", False), ("Stop.", True), ("Lu
a.greeted, L.current = True, a
L.who_spoke(U, text)
settle()
assert (L.current is b) == takes and (moves == [S * -40] if takes else moves == []), (text, L.current.id, moves)
assert (L.current is b) == takes and moves == [S * (-40 if takes else 30)], (text, L.current.id, moves) # the head
# on whoever it talks with after every utterance (2026-10-30)
lumi.doa.estimate = lambda mics, cal, ref=None: (-40.0, 0.0, 0.0) # no sure direction: still to the one talked with
L = fresh(a := Track(1, 30.0, 2.0)) # past 1.6 m: no calibration sample from it
a.greeted, L.current = True, a
L.who_spoke(U, "What's the weather?")
settle()
assert moves == [S * 30], moves
lumi.doa.estimate = lambda mics, cal, ref=None: (-40.0, 0.9, 0.0)
# ---- "look at me" (19:24:16): focus on the person found; a newcomer does not take the head; the head follows the
# looked-at person over the held look, also when their track gets a new id (#5 -> #7) ----
+30 -1
View File
@@ -47,6 +47,22 @@ NOT_GIVE = ["don't give it to me yet", "give it to me after the talk", "when my
"잠깐만 시간 좀 줘", "엄마, 그 가방 줘 봐", "지영아 물 좀 줘", "Jake, give me your phone for a sec", "주는 척만 해",
"give it to James at booth A", "bring it to p3", "거기 놓지 마세요", "put down 하지 마", "put the music on",
"I put it on the table yesterday", "put it on my tab", "lay down"]
# the person says they hold it themselves: the hand opens (release); whisper's "cuff" for cup (live 2026-10-30)
THEY_HOLD = ["I am holding the cuff. So let's open.", "I am holding the cup. So let's open.", "I've got it", "I'm holding it",
"I have it, let go", "I have it", "I've got the cup", "I'm holding the cup, you can let go",
"I got the cup, open your hand", "I took it", "I grabbed it, release", "It's in my hand now",
"okay I've got hold of it", "Lumi, I'm holding it now", "I'm holding on to it, let it go", "got it, let go",
"I got it, open", "잡았어", "잡았어요", "내가 잡고 있어", "제가 들고 있어요, 놓아", "제가 잡았어요", "내가 컵 잡고 있어",
"제가 컵을 들고 있어요", "내 손에 있어", "제가 잡고 있으니까 놔도 돼요", "루미야 내가 잡았어", "컵 잡았어. 손 펴",
"제가 받았어요", "I 잡았어", "내가 hold 하고 있어", "cup 잡았어요, open 해", "I'm holding it, 놔"]
NOT_THEY_HOLD = ["Open your hand.", "open your hand", "손 펴", "don't open, I'm not holding it", "I'm not holding it yet",
"I haven't got it", "I don't have it", "not yet, I'm not holding it", "when I hold it, let go",
"if I'm holding it, open", "I'll hold it", "let me hold it", "can I hold it?", "아직 안 잡았어", "안 잡았어",
"못 잡았어", "잡았어?", "잡았어요?", "잡고 있어", "들고 있어", "그거 들고 있어", "꽉 잡고 있어", "내가 잡으면 놔",
"내가 잡을게", "놓지 마, 내가 잡고 있어", "아직 잡지 않았어요", "제가 잡기 전에 놓지 마세요", "got it", "I got it",
"okay, got it", "I'm holding my phone", "I have a question", "I'm holding the door", "I'm holding it, don't let go",
"what am I holding?", "am I holding it?", "she's holding it", "I'm going to take it", "I took it yesterday",
"I'm not holding it, 놓지 마", "아직 안 잡았어, don't open"]
def main():
@@ -95,9 +111,22 @@ def main():
for words in ["고개 원위치", "머리 원위치", "head back to centre"]:
if brain.intent(words, MARKERS) != ("look", "center"):
bad.append((words, "look center", brain.intent(words, MARKERS)))
for words in THEY_HOLD: # by the reader and by the route voice and the Command box take
if lumi.route(words, MARKERS, brain.Brain(), True) != ("hand", (("release", None), True)) or \
brain.hand_request(words, False, None, MARKERS) == ("release", None):
bad.append((words, "release", lumi.route(words, MARKERS, brain.Brain(), True)))
for words in NOT_THEY_HOLD:
got = lumi.route(words, MARKERS, brain.Brain(), True)
if got[0] == "hand" and got[1][0][0] == "release":
bad.append((words, "no release", got))
after = brain.Brain() # "got it" right after the refused open: they hold it now
after.history.append(("Open your hand.", "ACTION: refuse -"))
for words in ["got it", "I got it", "okay, got it"]:
if brain.hand_request(words, True, after, MARKERS) != ("release", None):
bad.append((words, "release after the refusal", brain.hand_request(words, True, after, MARKERS)))
assert not bad, "\n".join(f"{t!r}: want {w}, got {g}" for t, w, g in bad)
n = len(CALLS) * len(TAILS) * len(GIVE_EN + GIVE_KO) + len(CALLS) * (len(TAKE_KO) + len(PUT_DOWN) + len(PUT_BACK)) + \
len(REACH) + len(FOLD) + len(NOT_FOLD) + len(NOT_GIVE) + 22
len(REACH) + len(FOLD) + len(NOT_FOLD) + len(NOT_GIVE) + len(THEY_HOLD) + len(NOT_THEY_HOLD) + 25
print(f"held hand ok ({n} cases)")
+16
View File
@@ -8,6 +8,7 @@ from assistant import lumi
turns, pitches = [], []
lumi.head.turn = lambda yaw, pitch=None: (turns.append(round(yaw)), pitches.append(pitch))
lumi.LOOK_ME_SETTLE_S = 0.0
lumi.waist_turned = lambda: 0.0 # the waist at the front unless a case says otherwise
class Vision:
@@ -193,3 +194,18 @@ turns.clear()
L.look_at_speaker()
assert waist["calls"] == [(-120, True, -125.0)] and turns == [-60, 60, -5, 0], (waist, turns)
print("look me from behind, unsure voice: ok")
# the waist left turned at -73 deg, the caller on the other side (2026-10-30): nobody in either head look, so the waist
# goes to the front and the head looks again from there, the voice's side first (+20 from the turned waist = -53 now)
waist.update(at=-73.0, calls=[])
lumi.waist_home = lambda why, fold=False: waist.update(at=0.0) or True
L = lumi.Lumi.__new__(lumi.Lumi)
L.vision, L.current = Vision([], [(-50.0, 2.0)]), None
L.vision.views = [[], [], [], [(-50.0, 2.0)]]
L.voice_angle, L.voice_trusted, L.voice_guess = 0.0, False, 20.0
L.det_yaw = lambda: 0.0
L.modes = type("M", (), {"patrol": False})()
turns.clear()
L.look_at_speaker()
assert turns == [60, -60, -60, -50] and waist["calls"] == [], (turns, waist)
print("look me with the waist turned: ok")
+21
View File
@@ -77,4 +77,25 @@ for name, (sc, must) in PLACES.items():
or r["result"] in ("exception", "timeout"):
bad.append((name, r["result"], r.get("why"), r["moves"]))
assert not bad, bad
# ---------- live 2026-10-30: a round table at -327 mm ahead-left, lift 0. The torso camera sees its top from y ~640,
# where the arm hardly reaches at that height: the base drove closer again and again, up to the table's edge ----------
ROUND = lambda deg, near: {"c": P(deg, near + 0.45), "r": 0.45, "z": -327.0}
for name, table in (("table in reach ahead-left", ROUND(20, 0.65)), ("table in reach, further left", ROUND(35, 0.55))):
r = ps.run_scene(ps.place_at([table]), 1.0) # in reach (with a waist turn): put down, no base move
print(f"place {name:44s} {r['result']:8s} moves {[m[:3] for m in r['moves']]} {r.get('why') or ''}")
if r["result"] != "ok" or r["moves"]:
bad.append((name, r["result"], r.get("why"), r["moves"]))
# ... out of reach: one drive closer; there the camera loses it (only part of it in view): put on the table kept from
# before the drive, never another drive
real_far, real_ahead = ps.fetch.far_table, ps.fetch.table_ahead
ps.fetch.far_table = lambda *a, **k: None if ps.W["rec"]["moves"] else real_far(*a, **k)
ps.fetch.table_ahead = lambda *a, **k: None if ps.W["rec"]["moves"] else real_ahead(*a, **k)
r = ps.run_scene(ps.place_at([ROUND(0, 1.0)]), 1.0)
ps.fetch.far_table, ps.fetch.table_ahead = real_far, real_ahead
print(f"place {'table lost after the drive':44s} {r['result']:8s} moves {[m[:3] for m in r['moves']]} "
f"{r.get('why') or ''}")
if r["result"] != "ok" or len(r["moves"]) != 1:
bad.append(("table lost after the drive", r["result"], r.get("why"), r["moves"]))
assert not bad, bad
print("pick sweep scenes ok")
+1
View File
@@ -108,6 +108,7 @@ arm_route.head_cam.head_centre = real_centre
C = arm_route.head_cam.head_centre()[:2]
body = {"waist": -20.31} # the waist of measure-axis = the front
fetch.head.status = lambda: [75.0, body["waist"], 0.0, -5.0]
fetch.head.moveto = lambda pos, **kw: None # _reach turns the head onto the cup (_aim_head)
around = lambda r, b: cup(C[0] - r * math.sin(math.radians(b)), C[1] + r * math.cos(math.radians(b)))
o = cup(-300, 400)
+16 -9
View File
@@ -89,25 +89,32 @@ for t in ["There is nothing in your hand.", "your hand is empty", "you're not ho
for t in ["is there anything in your hand?", "what's in your hand", "give me your hand"]:
assert not lumi.HAND_EMPTY_SAID.search(t), t
L = lumi.Lumi.__new__(lumi.Lumi)
folds, status = [], {"now": "done"}
folds, status, stops = [], {"now": "done"}, []
L.fetch_status = lambda: status["now"]
L.arm_pose = lambda target: folds.append(target) or True
for text, want in [("Okay, thank you.", True), ("okay thanks", True), ("고마워", True), ("됐어", True),
("what's the weather?", False), (None, False)]:
real_state, real_stop = fetch.state, fetch.stop
fetch.state, fetch.stop = lambda: {"step": "reaching out"}, lambda: stops.append(1)
for text in ["Okay, thank you.", "okay thanks", "고마워", "됐어", "what's the weather?", "go home"]: # any next words
folds.clear()
L.reached_at = time.time()
assert L.reach_done(text) == want and folds == (["fold"] if want else []), (text, folds)
assert L.reach_done(text) and folds == ["fold"], (text, folds)
L.reached_at, folds[:] = time.time(), []
assert not L.reach_done() and not folds # nothing said yet: the hand stays out
L.reached_at = time.time() - lumi.REACH_HOLD_S - 1 # nobody said anything: the timeout folds
folds.clear()
assert L.reach_done() and folds == ["fold"]
status["now"] = "running" # still reaching: not yet
L.reached_at, folds[:] = time.time() - lumi.REACH_HOLD_S - 1, []
assert not L.reach_done("thanks") and not folds
status["now"] = "failed" # the reach failed: the arm stays, no later fold
status["now"] = "running" # still going toward their hand: stopped, folded
L.reached_at, folds[:] = time.time(), []
assert L.reach_done("okay thanks") and folds == ["fold"] and stops, (folds, stops)
status["now"] = "failed" # the reach failed (a timeout, 2026-10-30): folded
L.reached_at, folds[:] = time.time(), []
assert L.reach_done("thanks") and folds == ["fold"]
status["now"] = "stopped" # a stop word: the arm stays where it is
L.reached_at, folds[:] = time.time(), []
assert not L.reach_done("thanks") and not folds and not L.reached_at
L.reached_at = 0.0
status["now"] = "done"
assert not L.reach_done("thanks") and not folds # no reach out: "thanks" moves nothing
fetch.state, fetch.stop = real_state, real_stop
# an arm left half way (a reach stopped by a lost state reply) and the waist turned: an order to drive folds the empty
# arm along the checked route, then the waist comes to the front; a conversation's end or a held thing never folds it
+2 -2
View File
@@ -39,9 +39,9 @@ def refused(fn, *a):
JOG = server.JogBody(axis="head_yaw", direction=1)
manual = (lambda: server.jog(JOG), server.gripper_open, server.gripper_close)
# a modes file from before "Come when called" was dropped still loads, without the old key
# a modes file with keys no longer used ("drive", "wave" when asked) still loads, without them
server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": False, "wave": True, "drive": False}))
assert server.read_modes() == {"greeter": True, "patrol": False, "wave": True}, server.read_modes()
assert server.read_modes() == {"greeter": True, "patrol": False, "wave_greet": False}, server.read_modes()
# idle, Patrol on: allowed
server.MODES_FILE.write_text(json.dumps({"greeter": True, "patrol": True}))
+209
View File
@@ -0,0 +1,209 @@
"""Self-check of the wave greeting (tasks/wave_greet.py) with a fake arm, head, waist and speech, no robot, and of the
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 no_robot # noqa: F401 any connection to the robot fails the test
from manipulation import arm_route, wave
from robot import head, motion
from tasks import fetch, wave_greet as g
from vision import waving
done = [] # what the robot did, in order
arm = {"at": "look"}
waver = {"w": None} # (bearing, distance) of the person waving now
plan_error = {"e": None}
POSES = {"look": [0.0] * 6, "wave_out": [1.0] * 6, "wave_start": [2.0] * 6, "wave": [3.0] * 6}
def plan():
if plan_error["e"]:
raise plan_error["e"]
return ([("wave_out", POSES["wave_out"]), ("wave_start", POSES["wave_start"])] if arm["at"] == "look" else [],
[])
def move_path(moves, wait=True, queued=False):
if moves[-1][0] == POSES["wave_start"] and len(moves) == 2 and queued:
done.append("swing")
else:
done.append(f"up {moves[-1][1]}")
arm["at"] = "wave_start"
def route_move(seq, speed=None, holding=False):
done.append(f"down {speed}")
arm["at"] = "look"
wave.plan = plan
motion.poses = lambda: dict(POSES)
motion.move_path = move_path
arm_route.where = lambda now=None: arm["at"]
arm_route.plan = lambda target, holding=False, leaf=False, now=None: [("wave_out", None), ("look", None)]
arm_route.move = route_move
head.status = lambda: [0.0, 0.0, 0.0, 10.0]
head.moveto = lambda pos, **k: done.append(f"head {pos[2]:+.0f}" + (" rest" if pos[3] == head.HEAD_REST_PITCH else "")
+ (" timeout" if k.get("timeout") != g.HEAD_TIMEOUT_S else ""))
fetch._waist_turn = lambda: 0.0
fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
g._head_yaw = lambda: 0.0
g._too_close = lambda: False
g._waver = lambda: waver["w"]
said = []
g._say = lambda lines, lang: said.append(lines[0][lang])
switch = {"on": True, "free": True}
g._on, g._free = (lambda: switch["on"]), (lambda: switch["free"])
g._off = lambda: switch.update(on=False)
g._bg = lambda fn, *args: fn(*args) # the background parts run at once here
def run(t0, t1, dt=0.5):
t = t0
while t <= t1:
try:
g.step(t)
except Exception as e: # as _run
g._stopped(e)
t += dt
def fresh():
done.clear()
said.clear()
arm["at"] = "look"
g._st.update(up=False, last_wave=0.0, next_joke=0.0, free_at=0.0, refused_until=0.0, waist_out=False)
switch.update(on=True, free=True)
plan_error["e"] = None
# someone waves 30 deg on the left at 2 m: head to them, a greeting, arm up at the route speed, one swing, waist to them
fresh()
waver["w"] = (30.0, 2.0)
run(100.0, 100.0)
assert done == ["head +30", "up route", "swing", "waist +30 look 30.0"], done
assert len(said) == 1 and said[0] in sum(g.wave_lines.GREET, ()), said
assert g.busy()
# they keep waving: swings, and a joke after JOKE_AFTER_S, then not again before JOKE_EVERY_S
done.clear()
said.clear()
run(100.5, 100.0 + g.JOKE_AFTER_S + 1)
assert done.count("swing") >= 10 and "up route" not in done, done
assert len(said) == 1 and said[0] in sum(g.wave_lines.LONG, ()), said
# they stop: the hand stays up, no swings; waving again: swings again, no new greeting within NEW_WAVE_S
waver["w"] = None
done.clear()
run(112.0, 115.0)
assert done == [], done
waver["w"] = (30.0, 2.0)
said.clear()
run(115.5, 116.0)
assert done.count("swing") == 2 and said == [], (done, said)
# nobody waves for HOLD_S: arm down slowly, waist to the front, head to rest; not before
waver["w"] = None
done.clear()
run(116.5, 116.0 + g.HOLD_S - 1)
assert done == [], done
run(116.0 + g.HOLD_S + 0.5, 116.0 + g.HOLD_S + 0.5)
assert done == ["waist +0 look None", "down normal", "head +0 rest"], done
assert not g.busy() and arm["at"] == "look"
# the waist's way back is blocked: the arm still goes down; the waist is tried again every REFUSED_S while nobody waves
fresh()
waver["w"] = (30.0, 2.0)
run(150.0, 150.0)
waver["w"] = None
blocked = {"n": 1}
fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f}") or (
blocked.update(n=blocked["n"] - 1) or False if blocked["n"] > 0 else True)
done.clear()
run(150.5 + g.HOLD_S, 150.5 + g.HOLD_S + g.REFUSED_S * 2.5)
assert done[:3] == ["waist +0", "down normal", "head +0 rest"] and done[3:] == ["waist +0"], done
fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
# beside a wall the full waist turn is blocked: it turns as far as its sweep is clear, the head on the person
fresh()
waver["w"] = (-66.0, 2.0)
fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or abs(rel) < 40
run(160.0, 160.0)
assert done[-3:] == ["waist -66 look -66.0", "waist -50 look -66.0", "waist -33 look -66.0"], done
fetch._waist_to = lambda rel, in_place=False, look=None: done.append(f"waist {rel:+.0f} look {look}") or True
# a wave nearly in front: only the head turns, the waist stays
fresh()
waver["w"] = (5.0, 1.5)
run(200.0, 200.0)
assert done == ["up route", "swing"], done # the head looks there already (within HEAD_MIN_DEG)
# the switch is turned off with the hand up: down at once
switch["on"] = False
done.clear()
run(200.5, 200.5)
assert done[:2] == ["waist +0 look None", "down normal"], done
# the arm stops (STOP, a person too close) during a swing: switched off, nothing moves after it
fresh()
waver["w"] = (0.0, 2.0)
run(300.0, 300.0)
def stopped(*a, **k):
raise motion.MotionError("stopped")
motion.move_path = stopped
run(300.5, 300.5)
assert switch["on"] is False and not g.busy() and said[-1] in ("I stopped my arm.", "팔을 멈췄어요."), said
motion.move_path = move_path
done.clear()
run(301.0, 310.0)
assert done == [], done
# the arm refused (off, busy, something held): nothing moves, tried again after REFUSED_S only
fresh()
plan_error["e"] = wave.WaveError(*wave.OFF)
run(400.0, 400.0 + g.REFUSED_S - 1)
assert done == [] and switch["on"], done
plan_error["e"] = None
run(400.0 + g.REFUSED_S + 0.5, 400.0 + g.REFUSED_S + 0.5)
assert "up route" in done, done
# the assistant or a task has the robot: nothing moves
fresh()
switch["free"] = False
run(500.0, 505.0)
assert done == [] and not g.busy(), done
# 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))
for name, xy in (("nose", (640, 200)), ("left_eye", (650, 190)), ("right_eye", (630, 190)), ("left_shoulder", (700, 320)),
("right_shoulder", (580, 320)), ("right_elbow", (560, 260)), ("right_wrist", (600, 210))):
kp[g.pose.K[name]] = (*xy, 1.0)
assert waving._hand(kp) is None # palm at (620, 185): beside the eye
kp[g.pose.K["right_wrist"]] = (480, 200, 1.0)
kp[g.pose.K["right_elbow"]] = (520, 280, 1.0)
assert waving._hand(kp) is not None # palm at (460, 160): out to the side
# the detector on the recordings: every wave found, nothing else ever counts as waving
DATA = Path(__file__).parent / "data" / "waves"
if DATA.exists():
for f in sorted(p for p in DATA.iterdir() if p.is_dir()):
r = waving.run_recording(f)
seen = [any(w) for _, w in r]
if f.name.startswith("no_"):
assert not any(seen), f.name
else:
first = next(t - r[0][0] for (t, _), s in zip(r, seen) if s)
assert first < 2.0, (f.name, first) # found within 2 s
if f.name != "pause_2m": # (it stops waving half way)
assert sum(seen) > 0.75 * len(seen), (f.name, sum(seen), len(seen))
r = waving.run_recording(DATA / "pause_2m") # stopped at ~6 s: no longer waving 2.5 s later
assert not any(any(w) for t, w in r if t - r[0][0] > 8.5)
else:
print("(no recordings here: detector not checked)")
print("wave greeting: ok")