Lumi robot software on the Jetson Thor
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+109
@@ -0,0 +1,109 @@
|
||||
"""Mobile base (AGV) over its TCP API (192.168.10.10:31001).
|
||||
|
||||
python robot/agv.py # status + markers
|
||||
python robot/agv.py go point1 # drive to a marker (returns at once)
|
||||
python robot/agv.py cancel
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
AGV = ("192.168.10.10", 31001)
|
||||
DOCK_FALLBACK = "충전위치로" # dock marker name on the old map; on any map the type-11 marker is used
|
||||
|
||||
|
||||
def request(command, timeout=3.0):
|
||||
tag = uuid.uuid4().hex
|
||||
command += ("&" if "?" in command else "?") + f"uuid={tag}"
|
||||
buf, dec = "", json.JSONDecoder()
|
||||
with socket.create_connection(AGV, timeout=timeout) as s:
|
||||
s.sendall(command.encode())
|
||||
while True:
|
||||
chunk = s.recv(65536)
|
||||
if not chunk: # the base closed the connection: never loop forever
|
||||
raise ConnectionError(f"AGV closed the connection ({command.split('?')[0]})")
|
||||
buf += chunk.decode()
|
||||
while buf.strip():
|
||||
try:
|
||||
msg, end = dec.raw_decode(buf.lstrip())
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
buf = buf.lstrip()[end:]
|
||||
if msg.get("uuid") == tag:
|
||||
return msg
|
||||
|
||||
|
||||
def status():
|
||||
return request("/api/robot_status").get("results", {})
|
||||
|
||||
|
||||
def dock_marker():
|
||||
"""Name of the main charging-dock marker on the current map ("home"): of the type-11 markers the one with the
|
||||
lowest dock number (num); None when there is none. Further docks keep their own names (dock2, ...)."""
|
||||
docks = [(m.get("num", 1), name) for name, m in (request("/api/markers/query_list").get("results") or {}).items()
|
||||
if m.get("key") == 11]
|
||||
return min(docks)[1] if docks else None
|
||||
|
||||
|
||||
def markers():
|
||||
"""Marker names on the current map; the dock marker is called "home"."""
|
||||
names = list((request("/api/markers/query_brief").get("results") or {}).keys())
|
||||
dock = dock_marker()
|
||||
return ["home" if n == dock else n for n in names]
|
||||
|
||||
|
||||
def go(marker):
|
||||
"""Start driving to a marker. Returns (ok, message)."""
|
||||
marker = (dock_marker() or DOCK_FALLBACK) if marker == "home" else marker
|
||||
if status().get("move_status") == "running":
|
||||
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):
|
||||
"""Start driving to a map point (m, rad). Returns (ok, message)."""
|
||||
if status().get("move_status") == "running":
|
||||
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():
|
||||
"""(x, y, theta) of the base on the map."""
|
||||
p = status()["current_pose"]
|
||||
return p["x"], p["y"], p["theta"]
|
||||
|
||||
|
||||
def turn_by(angle_rad):
|
||||
"""Turn in place by angle_rad (+ = left); the base plans it like a normal move."""
|
||||
x, y, th = pose()
|
||||
return go_point(x, y, (th + angle_rad + 3.14159265) % 6.2831853 - 3.14159265)
|
||||
|
||||
|
||||
def probe(x, y):
|
||||
"""(live, map): distance (m) from the map point (x, y) to the nearest obstacle the sensors see now and to the
|
||||
nearest one on the map; inf when there is none in range."""
|
||||
d = request(f"/api/map/distance_probe?x={x:.3f}&y={y:.3f}").get("results", {}).get("env_dist", {})
|
||||
return tuple(v if v is not None and v >= 0 else float("inf") for v in (d.get("obstacle"), d.get("static")))
|
||||
|
||||
|
||||
def clearance(x, y):
|
||||
"""Distance (m) from the map point (x, y) to the nearest obstacle the sensors see now or the map holds."""
|
||||
return min(probe(x, y))
|
||||
|
||||
|
||||
def cancel():
|
||||
return request("/api/move/cancel").get("status")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 2 and sys.argv[1] == "go":
|
||||
print(go(sys.argv[2]))
|
||||
elif len(sys.argv) > 1 and sys.argv[1] == "cancel":
|
||||
print(cancel())
|
||||
else:
|
||||
st = status()
|
||||
print({k: st.get(k) for k in ("move_status", "move_target", "charge_state", "power_percent", "current_pose")})
|
||||
print("markers:", markers())
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Run a Cobo π program on the arm over the controller's TCP command port 10001 (no SDK).
|
||||
|
||||
python robot/arm.py # state
|
||||
python robot/arm.py run # play hand_shaking.jks once and wait
|
||||
python robot/arm.py stop
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
|
||||
CONTROLLER = ("192.168.10.90", 10001)
|
||||
WAVE = "hand_shaking.jks"
|
||||
# The controller now and then closes the connection without a reply (seen on get_data, get_program_state,
|
||||
# kine_inverse, stop_program, moveL, set_digital_output). Commands that only read are asked again, and so are those
|
||||
# that set an absolute value: moves to an absolute target (relFlag 0) and setting an output; sent twice they do the
|
||||
# same. Relative moves are never repeated here.
|
||||
READ_ONLY = {"get_data", "get_joint_pos", "get_tcp_pos", "get_robot_state", "get_program_state", "get_loaded_program",
|
||||
"kine_inverse", "kine_forward"}
|
||||
ABSOLUTE_MOVES = {"moveL", "joint_move"}
|
||||
SET_VALUE = {"set_digital_output", "stop_program"}
|
||||
RETRIES, RETRY_S = 3, 0.2
|
||||
|
||||
|
||||
def cmd(name, **args):
|
||||
again = name in READ_ONLY or name in SET_VALUE or (name in ABSOLUTE_MOVES and args.get("relFlag") == 0)
|
||||
tries = RETRIES if again else 1
|
||||
for i in range(tries):
|
||||
try:
|
||||
return _send(name, args)
|
||||
except (ConnectionError, OSError):
|
||||
if i == tries - 1:
|
||||
raise
|
||||
time.sleep(RETRY_S)
|
||||
|
||||
|
||||
def _send(name, args):
|
||||
with socket.create_connection(CONTROLLER, timeout=10) as s:
|
||||
s.sendall(json.dumps({"cmdName": name, **args}).encode())
|
||||
buf = ""
|
||||
while True:
|
||||
chunk = s.recv(65536)
|
||||
if not chunk: # the controller closed the connection: never loop forever
|
||||
raise ConnectionError(f"arm controller closed the connection ({name})")
|
||||
buf += chunk.decode()
|
||||
try:
|
||||
return json.loads(buf)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
|
||||
def ready():
|
||||
"""True when the arm is powered, enabled and no program is running."""
|
||||
r = cmd("get_robot_state")
|
||||
return bool(r.get("power")) and bool(r.get("enable")) and cmd("get_program_state").get("programState") == "idle"
|
||||
|
||||
|
||||
def program_state():
|
||||
return cmd("get_program_state").get("programState")
|
||||
|
||||
|
||||
def start(program=WAVE):
|
||||
"""Load (if needed) and start a program; returns at once."""
|
||||
if (cmd("get_loaded_program").get("programName") or "").lower() != program.lower():
|
||||
if cmd("load_program", programName=program).get("errorCode") != "0":
|
||||
raise RuntimeError(f"cannot load {program}")
|
||||
if cmd("play_program").get("errorCode") != "0":
|
||||
raise RuntimeError("play_program failed")
|
||||
|
||||
|
||||
def stop():
|
||||
return cmd("stop_program")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
what = sys.argv[1] if len(sys.argv) > 1 else "state"
|
||||
if what == "run":
|
||||
if not ready():
|
||||
sys.exit("arm not ready (power/enable off, or a program is running)")
|
||||
start()
|
||||
time.sleep(0.5)
|
||||
while program_state() != "idle":
|
||||
time.sleep(0.3)
|
||||
print("done")
|
||||
elif what == "stop":
|
||||
print(stop())
|
||||
else:
|
||||
print(cmd("get_robot_state"), program_state(), cmd("get_loaded_program").get("programName"))
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Writes every drive of the base to the log, whoever started it (dashboard, fetch, assistant): the start, where it
|
||||
is on the way and how far it still has to go, standing still, the end (arrived / failed / cancelled), E-stop and
|
||||
error codes. The base's own status is read once a second. api/server.py runs it; the lines show in the dashboard's
|
||||
Settings -> Logs.
|
||||
|
||||
python robot/drive_log.py # watch and print here (Ctrl+C)
|
||||
"""
|
||||
import math
|
||||
import time
|
||||
|
||||
from robot import agv
|
||||
|
||||
POLL_S = 1.0 # s between base status reads
|
||||
PROGRESS_S = 5.0 # s between "on the way" lines
|
||||
STILL_M = 0.05 # m; moving less than this ...
|
||||
STILL_S = 5.0 # ... for this long while driving -> "standing still" (again every STILL_S)
|
||||
STUCK_S = 15.0 # standing still this long -> "seems stuck" (shown among the errors)
|
||||
OK_CODE = "00000000" # robot_status error_code when there is no error
|
||||
|
||||
|
||||
class DriveLog:
|
||||
"""Turns base status reads into log lines (update() returns the new ones)."""
|
||||
|
||||
def __init__(self, marker_xy):
|
||||
self.marker_xy = marker_xy # f(name) -> (x, y) or None
|
||||
self.drive = None # target, start time, start pose of the drive in progress
|
||||
self.last_line = self.anchor = None # time of the last progress line; (x, y, t) of the last real move
|
||||
self.flags = {} # error_code / estop / paused as last logged
|
||||
|
||||
def _where(self, p, target):
|
||||
xy = self.marker_xy(target)
|
||||
left = f", {math.hypot(xy[0] - p['x'], xy[1] - p['y']):.2f} m to go" if xy else ""
|
||||
return f"at ({p['x']:.2f}, {p['y']:.2f}){left}"
|
||||
|
||||
def update(self, st, now):
|
||||
out = []
|
||||
for key, bad, on, off in (("error_code", lambda v: v not in (None, OK_CODE), "base error code {v}",
|
||||
"base error code cleared"),
|
||||
("estop_state", bool, "base E-stop pressed", "base E-stop released"),
|
||||
("is_paused", bool, "base paused", "base running again")):
|
||||
v = st.get(key)
|
||||
if bad(v) != self.flags.get(key, False):
|
||||
self.flags[key] = bad(v)
|
||||
out.append(on.format(v=v) if bad(v) else off)
|
||||
status, target, p = st.get("move_status"), st.get("move_target"), st.get("current_pose")
|
||||
if p is None:
|
||||
return out
|
||||
running = status == "running"
|
||||
if running and (self.drive is None or self.drive["target"] != target):
|
||||
self.drive = {"target": target, "t0": now}
|
||||
self.last_line, self.anchor = now, (p["x"], p["y"], now)
|
||||
out.append(f"drive to {target}: started {self._where(p, target)}")
|
||||
elif running:
|
||||
moved = math.hypot(p["x"] - self.anchor[0], p["y"] - self.anchor[1])
|
||||
if moved >= STILL_M:
|
||||
self.anchor = (p["x"], p["y"], now)
|
||||
still = now - self.anchor[2]
|
||||
if still >= STILL_S and now - self.last_line >= STILL_S:
|
||||
word = "seems stuck" if still >= STUCK_S else "standing still"
|
||||
out.append(f"drive to {target}: {word} for {still:.0f} s {self._where(p, target)}")
|
||||
self.last_line = now
|
||||
elif still < STILL_S and now - self.last_line >= PROGRESS_S:
|
||||
out.append(f"drive to {target}: on the way {self._where(p, target)}")
|
||||
self.last_line = now
|
||||
elif self.drive is not None:
|
||||
took = now - self.drive["t0"]
|
||||
word = {"succeeded": "arrived", "failed": "failed", "canceled": "cancelled"}.get(status, status)
|
||||
out.append(f"drive to {self.drive['target']}: {word} after {took:.0f} s {self._where(p, self.drive['target'])}")
|
||||
self.drive = None
|
||||
return out
|
||||
|
||||
|
||||
def marker_positions():
|
||||
"""f(name) -> (x, y) of a marker on the current map; re-read when a name is not known yet."""
|
||||
cache = {}
|
||||
|
||||
def xy(name):
|
||||
if name not in cache:
|
||||
try:
|
||||
for n, m in (agv.request("/api/markers/query_list").get("results") or {}).items():
|
||||
cache[n] = (m["pose"]["position"]["x"], m["pose"]["position"]["y"])
|
||||
except (ConnectionError, OSError, KeyError):
|
||||
pass
|
||||
cache.setdefault(name, None) # a map point's generated name: no marker
|
||||
return cache[name]
|
||||
return xy
|
||||
|
||||
|
||||
def watch(log=print):
|
||||
d, down = DriveLog(marker_positions()), False
|
||||
while True:
|
||||
try:
|
||||
st = agv.status()
|
||||
except (ConnectionError, OSError):
|
||||
if not down:
|
||||
log("base not answering")
|
||||
down = True
|
||||
time.sleep(POLL_S)
|
||||
continue
|
||||
if down:
|
||||
log("base answering again")
|
||||
down = False
|
||||
for line in d.update(st, time.time()):
|
||||
log(line)
|
||||
time.sleep(POLL_S)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
watch(lambda line: print(time.strftime("%H:%M:%S"), line, flush=True))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
@@ -0,0 +1,80 @@
|
||||
"""The Zimmer electric gripper on the arm's tool connector (TIO), driven by two digital outputs.
|
||||
|
||||
Wiring found 2026-10-13 (Cobo π → I/O → Tool(S), outputs set to PNP):
|
||||
DO_1 on -> the gripper closes, DO_2 on -> it opens (a stroke takes ~1 s)
|
||||
AI_1 -> finger position: ~160 open, ~4100-4200 closed on nothing, ~3500 closed on a cup (cup test
|
||||
11:39:12); in between while moving. A close runs to the end once started: DO_1 off half way
|
||||
(AI_1 2730) still ended at 4190 (2026-10-19), so the fingers can't be stopped on a soft cup.
|
||||
A soft plastic cup squeezed flat reads like "empty" (3 of 4 cup closes reached ~4150).
|
||||
DI_1 -> optical sensor under the gripper: 1 while something is below it, not between the fingers (PNP);
|
||||
a held object shows only in AI_1 (gap_mm)
|
||||
Only one output may be on at a time: both on = close and open at once.
|
||||
|
||||
python robot/gripper.py # state
|
||||
python robot/gripper.py open
|
||||
python robot/gripper.py close
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
from robot import arm
|
||||
|
||||
TOOL = 1 # set_digital_output type: 0 cabinet, 1 tool (TIO), 2 extended
|
||||
CLOSE_DO, OPEN_DO = 0, 1 # DO_1, DO_2 (0-based)
|
||||
CLOSED_AI = 400 # AI_1 above this = closed on something (open reads 130-165; an 82 mm metal cup
|
||||
# held in the cup fingers reads ~2200-2300, 2026-10-13)
|
||||
EMPTY_AI = 3900 # closed above this = nothing between the fingers (empty reads 4100-4200, noise +-50)
|
||||
AI_OPEN, AI_SHUT = 140.0, 4160.0 # AI_1 fully open / closed on nothing (2026-10-19)
|
||||
# inner gap (mm) between the fingers, (open, closed), measured with a tape 2026-10-19 (docs/gripper/README.md); the gap
|
||||
# is taken as linear in AI_1: an 82 mm metal cup read 2189-2310 (2026-10-13), the line gives 81-83 mm at the belly
|
||||
GAP_MM = {"tips": (88.0, 59.0), "belly": (96.0, 70.0), "neck": (73.0, 47.0), "shank": (66.0, 39.0)}
|
||||
MOVE_S = 1.5 # s a full stroke takes (measured ~1 s)
|
||||
SENSOR_DI = 0 # DI_1
|
||||
READ_TRIES, READ_GAP_S = 5, 0.1 # get_data now and then answers without the tool I/O: ask again
|
||||
|
||||
|
||||
def state():
|
||||
for _ in range(READ_TRIES):
|
||||
d = arm.cmd("get_data")
|
||||
if all(k in d for k in ("tio_ain", "tio_din", "tio_dout")):
|
||||
break
|
||||
time.sleep(READ_GAP_S)
|
||||
else:
|
||||
raise ConnectionError("the arm controller sends no tool I/O")
|
||||
ai = d["tio_ain"][0]
|
||||
return {"closed": ai > CLOSED_AI, "holding": CLOSED_AI < ai < EMPTY_AI, "object_in_front": bool(d["tio_din"][SENSOR_DI]),
|
||||
"ai": d["tio_ain"], "do": d["tio_dout"], "di": d["tio_din"], "gap_mm": round(gap_mm(ai))}
|
||||
|
||||
|
||||
def gap_mm(ai, where="belly"):
|
||||
"""Inner gap (mm) between the fingers at `where` (GAP_MM) for an AI_1 reading: the held object's width there."""
|
||||
opened, closed = GAP_MM[where]
|
||||
f = min(1.0, max(0.0, (ai - AI_OPEN) / (AI_SHUT - AI_OPEN)))
|
||||
return opened + f * (closed - opened)
|
||||
|
||||
|
||||
def _out(index, value):
|
||||
r = arm.cmd("set_digital_output", type=TOOL, index=index, value=int(value))
|
||||
if r.get("errorCode") != "0":
|
||||
raise RuntimeError(f"set_digital_output failed: {r}")
|
||||
|
||||
|
||||
def close(wait=True):
|
||||
_out(OPEN_DO, 0) # never both on
|
||||
_out(CLOSE_DO, 1)
|
||||
if wait:
|
||||
time.sleep(MOVE_S)
|
||||
return state()
|
||||
|
||||
|
||||
def open_(wait=True):
|
||||
_out(CLOSE_DO, 0)
|
||||
_out(OPEN_DO, 1)
|
||||
if wait:
|
||||
time.sleep(MOVE_S)
|
||||
return state()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
what = sys.argv[1] if len(sys.argv) > 1 else "state"
|
||||
print({"open": open_, "close": close}.get(what, state)())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Turn Lumi's head (body HTTP API on the arm/body controller).
|
||||
|
||||
python robot/head.py # print lift, waist, head yaw, head pitch
|
||||
python robot/head.py 10 # head yaw to +10 deg (slow), other joints unchanged
|
||||
python robot/head.py 10 5 # head yaw +10 deg, head pitch +5 deg
|
||||
python robot/head.py 30 --vel 60 # try another speed (speed ratio %, 1-100)
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.request
|
||||
|
||||
BODY = "http://192.168.10.90:5000/api/extaxis"
|
||||
YAW_LIMIT = 60.0 # deg; we keep the head well inside its +-180 range
|
||||
PITCH_RANGE = (-5.0, 35.0) # deg, hardware range
|
||||
VEL = 40 # speed ratio %, 1-100 (was 15: too slow to follow a visitor)
|
||||
ACC = 40 # acceleration ratio %, 1-100
|
||||
# Temporary (2026-10-20): the head camera's cable is too short, a higher lift pulls it out. Back to 250 mm (what
|
||||
# tasks/fetch.py used before; the body API allows 300) when the longer cable is in.
|
||||
LIFT_MAX_MM = 105.0
|
||||
# [lift mm, waist, head yaw, head pitch] limits of the body API (docs/03), the lift held to LIFT_MAX_MM. The controller
|
||||
# drops a whole moveto when any value is outside, and its own encoders read a little past the ends (pitch -5.003 at
|
||||
# the bottom stop).
|
||||
AXIS_LIMITS = ((0.0, LIFT_MAX_MM), (-140.0, 140.0), (-180.0, 180.0), (-5.0, 35.0))
|
||||
|
||||
_one = threading.Lock() # one moveto at a time: overlapping calls hang the body API
|
||||
owners = () # threads that own the body now (tasks/follow.py); empty: anyone may move it
|
||||
|
||||
|
||||
def _call(path, body=None, timeout=2):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(f"{BODY}/{path}", data=data, headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read())
|
||||
|
||||
|
||||
def moveto(pos, vel=VEL, acc=ACC, timeout=30):
|
||||
"""Move all four body joints; every value is clamped into AXIS_LIMITS. Blocks until the motion ends (and while
|
||||
another thread's moveto runs). None, nothing sent, when other threads own the body (`owners`)."""
|
||||
if owners and threading.current_thread() not in owners:
|
||||
return None # ponytail: skipped silently, the owner turns it back
|
||||
pos = [max(lo, min(hi, float(p))) for p, (lo, hi) in zip(pos, AXIS_LIMITS)]
|
||||
with _one:
|
||||
if not all(j["enable"] for j in _call("status")): # off after a controller power cycle; moveto needs them on
|
||||
_call("enable", {"enable": 1})
|
||||
return _call("moveto", {"pos": pos, "vel": vel, "acc": acc}, timeout=timeout)
|
||||
|
||||
|
||||
def status():
|
||||
"""[lift mm, waist deg, head yaw deg, head pitch deg]"""
|
||||
return [j["pos"] for j in _call("status")]
|
||||
|
||||
|
||||
def turn(yaw, pitch=None, vel=VEL, acc=ACC):
|
||||
"""Move the head; blocks until the motion ends. Returns the controller's reply."""
|
||||
lift, waist, _, cur_pitch = status()
|
||||
yaw = max(-YAW_LIMIT, min(YAW_LIMIT, yaw))
|
||||
pitch = cur_pitch if pitch is None else max(PITCH_RANGE[0], min(PITCH_RANGE[1], pitch))
|
||||
return moveto([lift, waist, yaw, pitch], vel, acc)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[1:]
|
||||
vel = VEL
|
||||
if "--vel" in args:
|
||||
i = args.index("--vel")
|
||||
vel = float(args[i + 1])
|
||||
del args[i:i + 2]
|
||||
if not args:
|
||||
print(dict(zip(["lift_mm", "waist", "head_yaw", "head_pitch"], (round(p, 2) for p in status()))))
|
||||
else:
|
||||
print(turn(float(args[0]), float(args[1]) if len(args) > 1 else None, vel))
|
||||
print("now:", [round(p, 2) for p in status()])
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
"""Checked arm motion over the controller's TCP command port (10001, JSON, no SDK): named poses, joint moves,
|
||||
straight-line TCP moves, stop.
|
||||
|
||||
Every move is checked before it is sent: joint limits with a margin, and for linear moves an IK solution
|
||||
(the controller's kine_inverse) that does not swing J1 / J4 / J6 around. Moves wait until the arm is there,
|
||||
and return early with an error when STOP was pressed or the controller stopped the arm.
|
||||
|
||||
python robot/motion.py # joints, TCP, named poses
|
||||
python robot/motion.py go tuck [normal] # move to a named pose (slow by default)
|
||||
python robot/motion.py teach ready # save the arm's current joints as a named pose (move it in Cobo π first)
|
||||
python robot/motion.py line 0 0 30 # straight TCP move by dx dy dz mm (base frame), slow
|
||||
python robot/motion.py stop
|
||||
|
||||
Poses taught with `teach` are kept in arm_poses.json next to this file.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from robot import arm
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] # the project folder
|
||||
POSES_FILE = ROOT / "data" / "arm_poses.json"
|
||||
TUCK = [179.3, -88.6, -13.9, -15.8, -14.5, -121.3] # deg, arm folded beside the column (fits doorways)
|
||||
LIMITS = [360, 125, 130, 360, 120, 360] # deg, ± factory range per joint (docs/01_HARDWARE.md)
|
||||
LIMIT_MARGIN = 5.0 # deg kept away from every limit
|
||||
JOINT_SPEED = {"slow": 10.0, "normal": 25.0} # deg/s
|
||||
LINEAR_SPEED = {"slow": 20.0, "normal": 50.0} # mm/s
|
||||
ACCEL_FACTOR = 3.0 # accel = speed x this (per s)
|
||||
MAX_FLIP = 90.0 # deg; an IK answer turning J1 / J4 / J6 more than this is refused
|
||||
MAX_TRAVEL = 200.0 # deg; a joint move turning any joint further is refused
|
||||
FULL_TURN = (0, 3, 5) # J1, J4, J6: ±360 joints; a target and target ± 360 are the same pose
|
||||
AT_JOINT_DEG = 0.3 # arrived when every joint is this close ...
|
||||
AT_TCP_MM = 1.0 # ... or the TCP this close (linear moves)
|
||||
POLL_S = 0.1
|
||||
EXTRA_S = 10.0 # s allowed on top of 3x the planned move time
|
||||
STILL_S = 2.0 # s without joint motion (and not there) -> the move ended short
|
||||
STILL_DEG = 0.05 # joint change that counts as motion
|
||||
BLIND_S = 1.0 # s without a valid state reply while moving -> stop the arm
|
||||
|
||||
_stopped = threading.Event() # set by stop(): a waiting move gives up
|
||||
|
||||
|
||||
class MotionError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _read(name, key):
|
||||
"""A value read from the controller. It now and then answers with another command's reply (get_data or
|
||||
get_robot_state to get_joint_pos, 2026-10-16): ask again."""
|
||||
for _ in range(arm.RETRIES):
|
||||
r = arm.cmd(name)
|
||||
if key in r:
|
||||
return r[key]
|
||||
time.sleep(arm.RETRY_S)
|
||||
raise MotionError(f"{name} failed: {r.get('errorMsg') or r.get('cmdName') or r}")
|
||||
|
||||
|
||||
def joints():
|
||||
return _read("get_joint_pos", "joint_pos")
|
||||
|
||||
|
||||
def tcp():
|
||||
return _read("get_tcp_pos", "tcp_pos")
|
||||
|
||||
|
||||
def poses():
|
||||
"""Named poses: tuck plus everything taught."""
|
||||
try:
|
||||
taught = json.loads(POSES_FILE.read_text())
|
||||
except FileNotFoundError:
|
||||
taught = {}
|
||||
return {"tuck": TUCK, **taught}
|
||||
|
||||
|
||||
def teach(name):
|
||||
"""Save the current joints as pose `name`."""
|
||||
if name == "tuck":
|
||||
raise MotionError("tuck is fixed in motion.py")
|
||||
check(j := [round(v, 2) for v in joints()])
|
||||
taught = {k: v for k, v in poses().items() if k != "tuck"}
|
||||
taught[name] = j
|
||||
POSES_FILE.write_text(json.dumps(taught, indent=1))
|
||||
return j
|
||||
|
||||
|
||||
def check(target):
|
||||
"""Raise MotionError if a joint target is out of range (with LIMIT_MARGIN)."""
|
||||
if len(target) != 6:
|
||||
raise MotionError(f"need 6 joints, got {len(target)}")
|
||||
for i, (v, lim) in enumerate(zip(target, LIMITS)):
|
||||
if abs(v) > lim - LIMIT_MARGIN:
|
||||
raise MotionError(f"J{i + 1} {v:.1f} deg is beyond ±{lim - LIMIT_MARGIN:.0f}")
|
||||
|
||||
|
||||
def _ready():
|
||||
st = arm.cmd("get_robot_state")
|
||||
if not (st.get("power") and st.get("enable")):
|
||||
raise MotionError("arm is not powered / enabled")
|
||||
if arm.program_state() != "idle":
|
||||
raise MotionError("a Cobo π program is running")
|
||||
|
||||
|
||||
def _wait(arrived, planned_s):
|
||||
"""Wait while the arm moves. Big joint moves run slower than speed / travel suggests (measured: 157 deg
|
||||
of J6 at 10 deg/s took well over 21 s), so the limit is generous; a move that stops short is caught by
|
||||
STILL_S instead."""
|
||||
t0 = last_move = last_seen = time.time()
|
||||
last = None
|
||||
while time.time() - t0 < 3 * planned_s + EXTRA_S:
|
||||
if _stopped.is_set():
|
||||
raise MotionError("stopped")
|
||||
try:
|
||||
d = arm.cmd("get_data")
|
||||
except (ConnectionError, OSError):
|
||||
d = {}
|
||||
if "joint_actual_position" not in d: # the controller now and then answers a poll with nothing
|
||||
if time.time() - last_seen > BLIND_S:
|
||||
stop()
|
||||
raise MotionError("lost the arm state while moving - stopped")
|
||||
time.sleep(POLL_S)
|
||||
continue
|
||||
last_seen = time.time()
|
||||
if d.get("protective_stop") or d.get("emergency_stop"):
|
||||
raise MotionError("the controller stopped the arm (protective / emergency stop)")
|
||||
if d.get("inpos") and arrived(d):
|
||||
return d
|
||||
j = d["joint_actual_position"]
|
||||
if last is None or max(abs(a - b) for a, b in zip(j, last)) > STILL_DEG:
|
||||
last, last_move = j, time.time()
|
||||
elif time.time() - last_move > STILL_S and time.time() - t0 > STILL_S + 1:
|
||||
raise MotionError("the arm stopped before the target")
|
||||
time.sleep(POLL_S)
|
||||
stop()
|
||||
raise MotionError(f"not there after {time.time() - t0:.0f} s - stopped")
|
||||
|
||||
|
||||
def nearest(target, start):
|
||||
"""For the ±360 joints use target or target ± 360, whichever is closest to where the joint is now:
|
||||
the same pose, without spinning the arm a full turn around the column."""
|
||||
out = list(target)
|
||||
for i in FULL_TURN:
|
||||
lim = LIMITS[i] - LIMIT_MARGIN
|
||||
options = [v for v in (target[i] - 360, target[i], target[i] + 360) if abs(v) <= lim]
|
||||
out[i] = min(options, key=lambda v: abs(v - start[i]))
|
||||
return out
|
||||
|
||||
|
||||
def move_joints(target, speed="slow", wait=True):
|
||||
"""Joint move to absolute angles (deg). Returns the joints reached (or the target if wait=False)."""
|
||||
check(target)
|
||||
_ready()
|
||||
deg_s = JOINT_SPEED[speed]
|
||||
start = joints()
|
||||
target = nearest(target, start)
|
||||
for i, (a, b) in enumerate(zip(target, start)):
|
||||
if abs(a - b) > MAX_TRAVEL:
|
||||
raise MotionError(f"J{i + 1} would turn {a - b:+.0f} deg - refused")
|
||||
travel = max(abs(a - b) for a, b in zip(target, start))
|
||||
_stopped.clear()
|
||||
r = arm.cmd("joint_move", relFlag=0, jointPosition=list(target), speed=deg_s, accel=deg_s * ACCEL_FACTOR)
|
||||
if r.get("errorCode") != "0":
|
||||
raise MotionError(f"joint_move refused: {r.get('errorMsg') or r}")
|
||||
if not wait:
|
||||
return list(target)
|
||||
d = _wait(lambda d: max(abs(a - b) for a, b in zip(d["joint_actual_position"], target)) < AT_JOINT_DEG,
|
||||
travel / deg_s)
|
||||
return d["joint_actual_position"]
|
||||
|
||||
|
||||
def go(name, speed="slow", wait=True):
|
||||
p = poses()
|
||||
if name not in p:
|
||||
raise MotionError(f"no pose {name!r} (known: {', '.join(p)})")
|
||||
return move_joints(p[name], speed, wait)
|
||||
|
||||
|
||||
def move_linear(target=None, delta=None, speed="slow", wait=True, path_checked=False):
|
||||
"""Straight TCP move to `target` [x, y, z mm, rx, ry, rz deg] or by `delta` (dx, dy, dz mm), base frame.
|
||||
The end pose is checked with the controller's IK first. `path_checked`: the caller checked the whole line in
|
||||
small steps (fetch._line_rows), so a big J1 / J4 / J6 turn over it is a real one, not another IK branch."""
|
||||
now_j, now_p = joints(), tcp()
|
||||
if target is None:
|
||||
target = [now_p[i] + (delta[i] if i < len(delta) else 0.0) for i in range(3)] + list(now_p[3:])
|
||||
for _ in range(3): # the controller now and then answers "0" without the joints: ask again
|
||||
ik = arm.cmd("kine_inverse", jointPosition=now_j, cartPosition=list(target))
|
||||
if "jointPosition" in ik or ik.get("errorCode") not in ("0", None):
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if "jointPosition" not in ik:
|
||||
raise MotionError(f"no IK solution for {[round(v, 1) for v in target]}: {ik.get('errorMsg') or ik}")
|
||||
end_j = ik["jointPosition"][:6] # some answers carry a 7th (external axis) value
|
||||
check(end_j)
|
||||
for i in () if path_checked else (0, 3, 5):
|
||||
if abs(end_j[i] - now_j[i]) > MAX_FLIP:
|
||||
raise MotionError(f"J{i + 1} would turn {end_j[i] - now_j[i]:+.0f} deg - refused")
|
||||
_ready()
|
||||
mm_s = LINEAR_SPEED[speed]
|
||||
dist = sum((a - b) ** 2 for a, b in zip(target[:3], now_p[:3])) ** 0.5
|
||||
_stopped.clear()
|
||||
r = arm.cmd("moveL", relFlag=0, cartPosition=list(target), speed=mm_s, accel=mm_s * ACCEL_FACTOR)
|
||||
if r.get("errorCode") != "0":
|
||||
raise MotionError(f"moveL refused: {r.get('errorMsg') or r}")
|
||||
if not wait:
|
||||
return list(target)
|
||||
d = _wait(lambda d: sum((a - b) ** 2 for a, b in zip(d["actual_position"][:3], target[:3])) ** 0.5 < AT_TCP_MM,
|
||||
dist / mm_s)
|
||||
return d["actual_position"]
|
||||
|
||||
|
||||
def stop():
|
||||
"""Stop any arm motion (also a running Cobo π program)."""
|
||||
_stopped.set()
|
||||
for _ in range(2): # the controller stops the arm but sometimes closes the connection without a reply
|
||||
try:
|
||||
return arm.cmd("stop_program")
|
||||
except ConnectionError:
|
||||
pass
|
||||
return {"sent": True, "reply": None}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = sys.argv[1:]
|
||||
try:
|
||||
if not a:
|
||||
print("joints", [round(v, 2) for v in joints()])
|
||||
print("tcp ", [round(v, 1) for v in tcp()])
|
||||
for k, v in poses().items():
|
||||
print(f"pose {k:8s}", v)
|
||||
elif a[0] == "go":
|
||||
print(go(a[1], a[2] if len(a) > 2 else "slow"))
|
||||
elif a[0] == "teach":
|
||||
print(a[1], teach(a[1]))
|
||||
elif a[0] == "line":
|
||||
print(move_linear(delta=[float(v) for v in a[1:4]]))
|
||||
elif a[0] == "stop":
|
||||
print(stop())
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
except KeyboardInterrupt:
|
||||
print(stop())
|
||||
except MotionError as e:
|
||||
sys.exit(f"refused / failed: {e}")
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
"""Where to drive to reach a person: a free spot about STOP_DIST in front of them that the base can get to.
|
||||
|
||||
The base's own /api/map/accessible_point_query answers every point unchanged, so the check is done here
|
||||
on the map picture: free cells (white) that are at least ROBOT_RADIUS from any wall or unknown area, and
|
||||
connected to where the robot stands now. Among those, the spot nearest to "STOP_DIST before the person on
|
||||
the line from the robot" wins; the robot then faces the person.
|
||||
|
||||
python robot/nav.py 1.0 2.0 # best spot to reach a person at map x=1.0, y=2.0 from where the robot is
|
||||
"""
|
||||
import math
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
from robot import agv
|
||||
|
||||
AGV_WEB = "http://192.168.10.10:9001"
|
||||
STOP_DIST = 1.0 # m between the robot centre and the person
|
||||
RING = (0.9, 1.6) # m, distances from the person that are tried
|
||||
ROBOT_RADIUS = 0.35 # m of clearance needed (base 0.54 m wide + the arm)
|
||||
CLOSE_ENOUGH = 1.3 # m; nearer than this the robot does not move
|
||||
|
||||
_map = {}
|
||||
|
||||
|
||||
def load_map():
|
||||
"""Current map: dict(name, res, ox, oy, h, clear (bool mask), comp (component ids))."""
|
||||
cur = agv.request("/api/map/get_current_map")["results"]
|
||||
key = (cur["map_name"], cur["floor"])
|
||||
if _map.get("key") != key:
|
||||
url = f"{AGV_WEB}/maps/{urllib.request.quote(cur['map_name'])}/{cur['floor']}/map.png"
|
||||
img = cv2.imdecode(np.frombuffer(urllib.request.urlopen(url, timeout=10).read(), np.uint8),
|
||||
cv2.IMREAD_GRAYSCALE)
|
||||
info = cur["info"]
|
||||
res = info["resolution"]
|
||||
free = (img > 240).astype(np.uint8)
|
||||
clearance = cv2.distanceTransform(free, cv2.DIST_L2, 5) * res
|
||||
clear = clearance >= ROBOT_RADIUS
|
||||
_, comp = cv2.connectedComponents(clear.astype(np.uint8), connectivity=8)
|
||||
_map.update(key=key, res=res, ox=info["origin_x"], oy=info["origin_y"], h=img.shape[0], w=img.shape[1],
|
||||
clear=clear, comp=comp, free=free.astype(bool))
|
||||
return _map
|
||||
|
||||
|
||||
def _cell(m, x, y):
|
||||
return int((x - m["ox"]) / m["res"]), int(m["h"] - (y - m["oy"]) / m["res"])
|
||||
|
||||
|
||||
def _robot_component(m, x, y):
|
||||
"""Component id of the robot's place (or of the nearest clear cell within 0.6 m: it may stand near a wall)."""
|
||||
cx, cy = _cell(m, x, y)
|
||||
r = int(0.6 / m["res"])
|
||||
best = None
|
||||
for dy in range(-r, r + 1, 2):
|
||||
for dx in range(-r, r + 1, 2):
|
||||
px, py = cx + dx, cy + dy
|
||||
if 0 <= px < m["w"] and 0 <= py < m["h"] and m["clear"][py, px]:
|
||||
d = dx * dx + dy * dy
|
||||
if best is None or d < best[0]:
|
||||
best = (d, m["comp"][py, px])
|
||||
return None if best is None else best[1]
|
||||
|
||||
|
||||
def approach(person_x, person_y, robot=None):
|
||||
"""(x, y, theta) to drive to, "close" if already near enough, or None if no reachable spot."""
|
||||
rx, ry, _ = robot or agv.pose()
|
||||
if math.hypot(person_x - rx, person_y - ry) <= CLOSE_ENOUGH:
|
||||
return "close"
|
||||
m = load_map()
|
||||
comp = _robot_component(m, rx, ry)
|
||||
if comp is None:
|
||||
return None
|
||||
toward = math.atan2(ry - person_y, rx - person_x) # from the person back to the robot
|
||||
ideal = (person_x + STOP_DIST * math.cos(toward), person_y + STOP_DIST * math.sin(toward))
|
||||
best = None
|
||||
for dist in np.arange(RING[0], RING[1] + 1e-6, 0.1):
|
||||
for a in np.radians(np.arange(0, 360, 10)):
|
||||
gx, gy = person_x + dist * math.cos(a), person_y + dist * math.sin(a)
|
||||
px, py = _cell(m, gx, gy)
|
||||
if not (0 <= px < m["w"] and 0 <= py < m["h"]) or not m["clear"][py, px] or m["comp"][py, px] != comp:
|
||||
continue
|
||||
score = math.hypot(gx - ideal[0], gy - ideal[1])
|
||||
if best is None or score < best[0]:
|
||||
best = (score, gx, gy)
|
||||
if best is None:
|
||||
return None
|
||||
_, gx, gy = best
|
||||
return gx, gy, math.atan2(person_y - gy, person_x - gx)
|
||||
|
||||
|
||||
def reachable(x, y, robot=None):
|
||||
"""True when the base can stand at map (x, y): a free cell, next to (0.6 m) the open area the robot is in.
|
||||
Near walls and furniture is allowed: that is where it stands to reach a table."""
|
||||
m = load_map()
|
||||
px, py = _cell(m, x, y)
|
||||
if not (0 <= px < m["w"] and 0 <= py < m["h"]) or not m["free"][py, px]:
|
||||
return False
|
||||
rx, ry, _ = robot or agv.pose()
|
||||
here = _robot_component(m, x, y)
|
||||
return here is not None and here == _robot_component(m, rx, ry)
|
||||
|
||||
|
||||
def person_on_map(distance_m, angle_deg, waist_deg=0.0, robot=None):
|
||||
"""Map position of a person seen at distance / angle (deg, + left, waist frame) from the robot."""
|
||||
rx, ry, th = robot or agv.pose()
|
||||
a = th + math.radians(angle_deg + waist_deg)
|
||||
return rx + distance_m * math.cos(a), ry + distance_m * math.sin(a)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
x, y = float(sys.argv[1]), float(sys.argv[2])
|
||||
print("robot", agv.pose())
|
||||
print("drive to", approach(x, y))
|
||||
Reference in New Issue
Block a user