Lumi robot software on the Jetson Thor

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 15:19:07 +09:00
co-authored by Claude Opus 5.5
commit 96b01fa12e
177 changed files with 39901 additions and 0 deletions
+123
View File
@@ -0,0 +1,123 @@
"""Drive the Lumi base through a list of markers, one after another (AGV /api/move).
python3 tools/agv_route.py --list # show the markers on the current map
python3 tools/agv_route.py wp_01 wp_02 wp_03 # visit them once, in order
python3 tools/agv_route.py wp_01 wp_02 --loop 3 # repeat the route 3 times (0 = forever)
python3 tools/agv_route.py --home # go back to the dock and charge
python3 tools/agv_route.py new_table_01 home # "home" = the dock marker, anywhere in a route
python3 tools/agv_route.py --speed 0.3 0.5 # navigation speed limit m/s, rad/s (reset at AGV restart)
The base plans its own path and avoids obstacles. Ctrl+C cancels the move and stops.
Markers are made with the `m` key in tools/agv_teleop.py or "add marker" in the web panel.
"""
import argparse
import json
import socket
import time
import uuid
AGV = ("192.168.10.10", 31001)
DOCK_FALLBACK = "충전위치로" # dock marker 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:
buf += s.recv(65536).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():
"""The charging-dock marker (type 11) of the current map; going there docks and charges."""
for name, m in (request("/api/markers/query_list").get("results") or {}).items():
if m.get("key") == 11:
return name
return DOCK_FALLBACK
def go(marker):
"""Send one move and wait for it to end. Returns the final move_status."""
reply = request(f"/api/move?marker={marker}")
if reply.get("status") != "OK":
print(f" {marker}: refused: {reply.get('status')} {reply.get('error_message')}")
return "refused"
print(f" -> {marker}", end="", flush=True)
time.sleep(0.5)
while True:
st = status()
if st.get("move_status") in ("succeeded", "failed", "canceled"):
p = st.get("current_pose", {})
print(f" {st['move_status']} (x={p.get('x', 0):+.2f}, y={p.get('y', 0):+.2f}, "
f"theta={p.get('theta', 0):+.2f})")
return st["move_status"]
if st.get("soft_estop_state") or st.get("hard_estop_state"):
print(" [E-stop on, waiting]", end="", flush=True)
time.sleep(0.5)
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("markers", nargs="*")
ap.add_argument("--loop", type=int, default=1, help="times to run the route, 0 = forever")
ap.add_argument("--list", action="store_true", help="list markers on the current map")
ap.add_argument("--home", action="store_true", help="go to the charging dock marker")
ap.add_argument("--speed", nargs=2, type=float, metavar=("V", "W"),
help="set max navigation speed: m/s (0.1-1.0) and rad/s (0.5-3.5)")
a = ap.parse_args()
if a.speed:
v, w = min(max(a.speed[0], 0.1), 1.0), min(max(a.speed[1], 0.5), 3.5)
request(f"/api/set_params?max_speed_linear={v}&max_speed_angular={w}")
print("Speed limits now:", request("/api/get_params").get("results"))
if not (a.markers or a.home or a.list):
return
if a.list:
dock = dock_marker()
for name, floor_type in (request("/api/markers/query_brief").get("results") or {}).items():
print(f" {name} (type-floor {floor_type}){' = home' if name == dock else ''}")
return
dock = dock_marker()
route = [dock] if a.home else [dock if m == "home" else m for m in a.markers]
if not route:
ap.error("give marker names, --list or --home")
st = status()
if st.get("move_status") == "running":
print("A move is already running; cancel it first (space in agv_teleop.py or Cancel in the panel).")
return
print(f"Battery {st.get('power_percent')} %, route: {' -> '.join(route)}")
try:
lap = 0
while a.loop == 0 or lap < a.loop:
lap += 1
print(f"Lap {lap}")
for m in route:
if go(m) in ("canceled", "refused"):
return
except KeyboardInterrupt:
print("\nCancelling...")
finally:
if status().get("move_status") == "running":
request("/api/move/cancel")
print("Move cancelled, base stopped.")
if __name__ == "__main__":
main()
+141
View File
@@ -0,0 +1,141 @@
"""Drive the Lumi base from the keyboard in a terminal (AGV /api/joy_control).
python3 tools/agv_teleop.py
Hold a key to move; release it and the base stops (each command lasts 0.5 s).
w / s forward / back a / d turn left / right
space stop + cancel any navigation goal
m save the current pose as a marker wp_01, wp_02, ... (for tools/agv_route.py)
+ / - speed up / down q quit (sends stop)
Speed is capped at 0.3 m/s and 0.6 rad/s; it starts at 0.1 m/s and 0.3 rad/s.
"""
import curses
import json
import socket
import time
import uuid
AGV = ("192.168.10.10", 31001)
MAX_V, MAX_W = 0.3, 0.6 # m/s, rad/s (API limit is 0.5 / 1.0)
KEY_HOLD = 0.6 # s without a key repeat before we treat the key as released (covers the OS repeat delay)
class Agv:
def __init__(self):
self.sock = socket.create_connection(AGV, timeout=3)
self.sock.setblocking(False)
def send(self, command):
command += ("&" if "?" in command else "?") + f"uuid={uuid.uuid4().hex}"
self.sock.sendall(command.encode())
try: # drop replies; we do not wait for them
while self.sock.recv(65536):
pass
except BlockingIOError:
pass
def drive(self, v, w):
self.send(f"/api/joy_control?angular_velocity={w:.3f}&linear_velocity={v:.3f}")
def stop(self):
self.drive(0.0, 0.0)
def request(command):
"""Send one command on a separate connection and return its response."""
tag = uuid.uuid4().hex
command += ("&" if "?" in command else "?") + f"uuid={tag}"
buf, dec = "", json.JSONDecoder()
with socket.create_connection(AGV, timeout=2) as s:
s.sendall(command.encode())
while True:
buf += s.recv(65536).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 save_marker():
"""Insert a marker at the current pose, named after the existing wp_NN markers."""
names = request("/api/markers/query_brief").get("results", {}) or {}
nums = [int(n[3:]) for n in names if n.startswith("wp_") and n[3:].isdigit()]
name = f"wp_{max(nums, default=0) + 1:02d}"
reply = request(f"/api/markers/insert?name={name}")
return f"{name}: {reply.get('status')} {reply.get('error_message', '')}"
def main(scr):
curses.curs_set(0)
scr.nodelay(True)
agv = Agv()
v_set, w_set = 0.1, 0.3
last_key, cmd = 0.0, (0.0, 0.0)
last_send, last_status, info, note = 0.0, 0.0, {}, ""
while True:
key = scr.getch()
now = time.time()
if key != -1:
ch = chr(key) if 0 <= key < 256 else ""
if ch == "q":
break
if ch == " ":
agv.stop()
agv.send("/api/move/cancel")
cmd = (0.0, 0.0)
elif ch == "m":
agv.stop()
cmd = (0.0, 0.0)
try:
note = "marker " + save_marker()
except OSError as e:
note = f"marker failed: {e}"
elif ch in "+=":
v_set, w_set = min(v_set + 0.05, MAX_V), min(w_set + 0.1, MAX_W)
elif ch == "-":
v_set, w_set = max(v_set - 0.05, 0.05), max(w_set - 0.1, 0.1)
elif ch in "wsad":
cmd = {"w": (v_set, 0.0), "s": (-v_set, 0.0),
"a": (0.0, w_set), "d": (0.0, -w_set)}[ch]
last_key = now
if now - last_key > KEY_HOLD:
cmd = (0.0, 0.0)
if now - last_send >= 0.1: # 10 Hz
if cmd != (0.0, 0.0):
agv.drive(*cmd)
last_send = now
if now - last_status >= 1.0:
try:
info = status()
except OSError:
info = {}
last_status = now
pose = info.get("current_pose", {})
scr.erase()
scr.addstr(0, 0, "Lumi base teleop w/s forward/back a/d turn space stop m marker +/- speed q quit")
scr.addstr(2, 0, f"speed setting: {v_set:.2f} m/s {w_set:.2f} rad/s")
scr.addstr(3, 0, f"command now: v={cmd[0]:+.2f} m/s w={cmd[1]:+.2f} rad/s")
scr.addstr(5, 0, f"pose: x={pose.get('x', 0):+.3f} m y={pose.get('y', 0):+.3f} m "
f"theta={pose.get('theta', 0):+.3f} rad")
scr.addstr(6, 0, f"move: {info.get('move_status')} soft E-stop: {info.get('soft_estop_state')} "
f"hard E-stop: {info.get('hard_estop_state')} battery: {info.get('power_percent')} %")
scr.addstr(8, 0, note)
scr.refresh()
time.sleep(0.02)
agv.stop()
if __name__ == "__main__":
curses.wrapper(main)
+79
View File
@@ -0,0 +1,79 @@
"""Run a Cobo π program on the Lumi arm over the controller's TCP command port (10001).
No JAKA SDK needed; works from any computer on the robot network.
python3 tools/arm_program.py state # power/enable, loaded program, program state
python3 tools/arm_program.py run hand_shaking # load the program and play it once, wait until done
python3 tools/arm_program.py stop # stop the running program
Ctrl+C while a program runs stops it.
"""
import json
import socket
import sys
import time
CONTROLLER = ("192.168.10.90", 10001)
def cmd(name, **args):
"""Send one command, return the reply as a dict."""
with socket.create_connection(CONTROLLER, timeout=5) as s:
s.sendall(json.dumps({"cmdName": name, **args}).encode())
buf = ""
while True:
buf += s.recv(65536).decode()
try:
return json.loads(buf)
except json.JSONDecodeError:
continue
def state():
r = cmd("get_robot_state")
return {"power": r.get("power"), "enable": r.get("enable"), "errcode": r.get("errcode"),
"loaded": cmd("get_loaded_program").get("programName"),
"program": cmd("get_program_state").get("programState")}
def run(program):
st = state()
if not (st["power"] and st["enable"]):
sys.exit(f"Arm is not powered and enabled: {st}. Turn on Power and Enable in Cobo π first.")
if st["program"] != "idle":
sys.exit(f"A program is {st['program']}; stop it first (python3 tools/arm_program.py stop).")
name = program if program.endswith(".jks") else program + ".jks"
if (st["loaded"] or "").lower() != name.lower():
r = cmd("load_program", programName=name)
print("load_program:", r.get("errorCode"), r.get("errorMsg"))
if r.get("errorCode") != "0":
sys.exit("Load failed. Check the program name in Cobo π → Program → File.")
r = cmd("play_program")
print("play_program:", r.get("errorCode"), r.get("errorMsg"))
if r.get("errorCode") != "0":
sys.exit("Play failed.")
try:
time.sleep(0.5)
while (s := cmd("get_program_state").get("programState")) != "idle":
print(f"\r {s} ", end="", flush=True)
time.sleep(0.3)
print("\r done ")
except KeyboardInterrupt:
print("\nStopping:", cmd("stop_program").get("errorCode"))
def main():
if len(sys.argv) < 2 or sys.argv[1] not in ("state", "run", "stop"):
sys.exit(__doc__)
if sys.argv[1] == "state":
print(state())
elif sys.argv[1] == "stop":
print("stop_program:", cmd("stop_program"))
else:
run(sys.argv[2] if len(sys.argv) > 2 else "hand_shaking")
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Read-only network check of the real Lumi. Nothing moves.
Run on the robot Wi-Fi (no internet needed):
python3 tools/robot_check.py
The report is printed and saved to docs/private/robot_check_<time>.txt (git-ignored).
"""
import datetime
import json
import pathlib
import socket
import ssl
import subprocess
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
CONTROLLER = "192.168.10.90" # arm (Cobo π, SDK) + body API
AGV = "192.168.10.10"
ROUTER = "192.168.10.79"
PORTS = {
CONTROLLER: [443, 80, 5000, 10000, 10001],
AGV: [31001, 9001, 8809, 8808],
ROUTER: [80],
}
lines = []
def out(text=""):
print(text)
lines.append(text)
def port_open(host, port, timeout=1.0):
try:
with socket.create_connection((host, port), timeout=timeout):
return True
except OSError:
return False
def http_get(url, timeout=3.0):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
with urllib.request.urlopen(url, timeout=timeout, context=ctx) as r:
return r.read().decode(errors="replace")
except Exception as e:
return f"ERROR {e}"
def agv(command, timeout=5.0):
"""Send one TCP command to the AGV, return its response message."""
tag = uuid.uuid4().hex
command += ("&" if "?" in command else "?") + f"uuid={tag}"
buf, dec = "", json.JSONDecoder()
try:
with socket.create_connection((AGV, 31001), timeout=timeout) as sock:
sock.sendall(command.encode())
while True:
buf += sock.recv(65536).decode()
while buf.strip():
try:
msg, end = dec.raw_decode(buf.lstrip())
except json.JSONDecodeError:
break
buf = buf.lstrip()[end:]
if msg.get("type") == "response" and msg.get("uuid") == tag:
return msg
except Exception as e:
return f"ERROR {e}"
def my_addresses():
try:
return subprocess.run(["ifconfig"], capture_output=True, text=True).stdout
except Exception as e:
return f"ERROR {e}"
def scan_subnet():
"""Find hosts on 192.168.10.0/24 with SSH (22) open: the onboard computer / Thor."""
hosts = [f"192.168.10.{i}" for i in range(1, 255)]
with ThreadPoolExecutor(64) as pool:
ssh = [h for h, ok in zip(hosts, pool.map(lambda h: port_open(h, 22, 0.5), hosts)) if ok]
web = [h for h, ok in zip(hosts, pool.map(lambda h: port_open(h, 80, 0.5), hosts)) if ok]
return ssh, web
def main():
out(f"Lumi read-only check {datetime.datetime.now():%Y-%m-%d %H:%M:%S}")
out("=" * 60)
out("\n[1] This computer's IPv4 addresses")
for line in my_addresses().splitlines():
if "inet " in line and "127.0.0.1" not in line:
out(" " + line.strip())
out("\n[2] Ports")
for host, ports in PORTS.items():
for p in ports:
out(f" {host}:{p:<6} {'OPEN' if port_open(host, p) else 'closed'}")
out("\n[3] Body API (read only)")
for ep in ("sysinfo", "status"):
out(f" /api/extaxis/{ep}: {http_get(f'http://{CONTROLLER}:5000/api/extaxis/{ep}')[:800]}")
out("\n[4] AGV (read only)")
for cmd in ("/api/robot_status", "/api/software/get_version", "/api/get_power_status",
"/api/map/get_current_map", "/api/markers/query_brief"):
reply = agv(cmd)
out(f" {cmd}: {json.dumps(reply, ensure_ascii=False)[:1500] if isinstance(reply, dict) else reply}")
out("\n[5] Cobo π page title")
page = http_get(f"https://{CONTROLLER}")
out(" " + (page[page.find("<title>"):page.find("</title>") + 8] if "<title>" in page else page[:200]))
out("\n[6] Devices on 192.168.10.x (looking for the Thor)")
ssh, web = scan_subnet()
out(f" SSH (22) open: {ssh or 'none'}")
out(f" HTTP (80) open: {web or 'none'}")
path = pathlib.Path(__file__).resolve().parent.parent / "docs" / "private" / \
f"robot_check_{datetime.datetime.now():%Y%m%d_%H%M%S}.txt"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(lines) + "\n")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()