Files

2306 lines
102 KiB
Python
Raw Permalink Normal View History

2026-10-21 15:19:07 +09:00
"""Lumi robot API: HTTP endpoints for the base, head, arm, voice and the lumi.py assistant, with Swagger at /docs.
python api/server.py # http://<thor>:8100/docs (robot network: http://192.168.10.240:8100/docs)
# live cameras: http://192.168.10.240:8100/view
Started at boot by a crontab @reboot line (see README.md), so nothing has to be run by hand.
While the assistant (lumi.py) is running it owns the robot: motion and speech endpoints answer 409.
/status, /agv/markers and the log always work.
"""
import json
import math
import os
2026-11-18 13:30:09 +09:00
import random
2026-10-21 15:19:07 +09:00
import re
import signal
import subprocess
import sys
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor, wait
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] # the project folder
VENV_PY = ROOT / ".venv" / "bin" / "python"
if VENV_PY.exists() and Path(sys.prefix).resolve() != (ROOT / ".venv").resolve():
os.execv(str(VENV_PY), [str(VENV_PY), str(Path(__file__).resolve())] + sys.argv[1:])
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, Response, StreamingResponse
from pydantic import BaseModel, Field
from robot import agv
from robot import arm
from vision import camview
from robot import gripper
from robot import motion
from vision import objects
from robot import head
from manipulation import arm_route
2026-11-16 18:22:17 +09:00
from robot import rosbridge
2026-10-21 15:19:07 +09:00
from manipulation import skills
from manipulation import wave
from tasks import wave_greet
2026-10-21 15:19:07 +09:00
from api.control import jogger
PORT = 8100
LUMI_LOG = ROOT / "logs" / "lumi.log" # written by lumi.py itself
CONSOLE_LOG = ROOT / "logs" / "lumi_console.log" # lumi.py stdout/stderr when started from here (tracebacks)
API_LOG = ROOT / "logs" / "api.log" # this server's output (lumi-api.service): tasks, arm, errors
ERROR_RE = re.compile(r"\b(error|failed|stuck|refused|cannot|traceback|stopped)\b|E-stop pressed|not answering",
re.I) # whole words only
app = FastAPI(title="Lumi robot API", version="0.1.0",
description="Base (AGV), head, arm, voice and the greeter/patrol assistant of our Lumi. "
"Motion endpoints really move the robot.")
_brain = None
_voice_lock = threading.Lock()
CAMERA_NAMES = ("head", "torso")
DASHBOARD = ROOT / "api" / "dashboard.html"
# ---------- helpers ----------
def assistant_pids():
"""PIDs of running lumi.py processes (started from here or from a terminal)."""
out = subprocess.run(["pgrep", "-f", "assistant/lumi[.]py"], capture_output=True, text=True).stdout
return [int(p) for p in out.split() if int(p) != os.getpid()]
# ---------- the assistant's live modes and commands (see lumi.py) ----------
MODES_FILE = Path("/dev/shm/lumi_modes.json")
CMD_FILE = Path("/dev/shm/lumi_cmd.json")
CALIB_FILE = Path("/dev/shm/lumi_calib.json")
DEFAULT_MODES = {"greeter": False, "patrol": False, "wave_greet": False, "welcome": False}
def any_on(m):
"""Each of the four switches works on its own (owner, 2026-11-16): lumi.py runs while any is on."""
return any(m.get(k) for k in DEFAULT_MODES)
2026-10-21 15:19:07 +09:00
def read_modes():
try:
d = json.loads(MODES_FILE.read_text())
return {k: d.get(k, v) for k, v in DEFAULT_MODES.items()} # keys no longer used (e.g. "drive") are dropped
2026-10-21 15:19:07 +09:00
except (FileNotFoundError, ValueError):
return dict(DEFAULT_MODES)
def send_to_assistant(cmd, **args):
"""lumi.py runs and owns the robot: it drives (and stops for people with patrol mode on)."""
tmp = CMD_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps({"id": time.time_ns(), "time": time.time(), "cmd": cmd, **args}))
os.replace(tmp, CMD_FILE)
def start_assistant(no_arm=False):
2026-10-21 15:19:07 +09:00
if assistant_pids():
return None
args = [str(VENV_PY), str(ROOT / "assistant" / "lumi.py")] + ["--no-arm"] * no_arm
2026-10-21 15:19:07 +09:00
log = open(CONSOLE_LOG, "a")
log.write(f"\n===== {time.strftime('%Y-%m-%d %H:%M:%S')} start: {' '.join(args[1:])}\n")
log.flush()
return subprocess.Popen(args, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
start_new_session=True).pid
BUSY_FILE = Path("/dev/shm/lumi_busy.json") # written by lumi.py: {"busy": skill | follow | drive | wave | null}
BUSY_MSG = "Busy with a task. Pause or stop it first."
_waving = threading.Event() # /arm/wave runs here
_posing = threading.Event() # /arm/pose runs here
def running_now():
"""What the robot is doing now (a task or mission, a skill, following, a wave, a drive), None when idle. A
paused task does not count."""
2026-10-21 15:19:07 +09:00
from tasks import fetch
lumi = assistant_pids()
st = fetch.state()
if st.get("status") in ("running", "waiting") and not st.get("paused") and (lumi or fetch._busy()):
return "task" # (lumi or _busy: the file of a runner that died does not count)
if _skill["thread"] and _skill["thread"].is_alive():
return "skill"
if _route.thread and _route.thread.is_alive():
return "route"
2026-11-18 13:30:09 +09:00
if _sing["thread"] and _sing["thread"].is_alive():
return "song"
if _waving.is_set():
return "wave"
if wave_greet.busy():
return "wave_greet"
if _posing.is_set():
return "arm"
if lumi:
try:
what = json.loads(BUSY_FILE.read_text()).get("busy")
if what:
return what
except (FileNotFoundError, ValueError):
pass
try: # a drive to a marker / point / dock, by anyone
if agv.request("/api/robot_status", timeout=0.5)["results"].get("move_status") == "running":
return "drive"
except Exception:
pass
return None
def robot_free(manual=False):
"""manual: a hand control on the dashboard (jog, lift, waist, head, arm buttons and poses, gripper): refused while
something runs (running_now), allowed when idle or paused, Greeter / Patrol on or off. Anything else is refused
while the assistant runs (it owns the robot). STOP never asks here."""
if manual:
if running_now():
raise HTTPException(409, BUSY_MSG)
elif assistant_pids():
raise HTTPException(409, "The assistant (lumi.py) is running and owns the robot. POST /assistant/stop first.")
2026-10-21 15:19:07 +09:00
2026-11-23 18:12:02 +09:00
TAIL_BLOCK = 64 * 1024 # bytes read at a time from a log's end
2026-10-21 15:19:07 +09:00
def tail(path, n):
2026-11-23 18:12:02 +09:00
"""The last n lines of a log, read from its end in blocks: lumi.log is close to 1 GB and reading it whole took
about 6 s a call (2026-11-23, the app's TALK reads it every few seconds)."""
2026-10-21 15:19:07 +09:00
try:
2026-11-23 18:12:02 +09:00
with open(path, "rb") as f:
f.seek(0, os.SEEK_END)
pos = f.tell()
data = b""
while pos > 0 and data.count(b"\n") <= n:
step = min(TAIL_BLOCK, pos)
pos -= step
f.seek(pos)
data = f.read(step) + data
if pos > 0: # the first line read may be cut: drop it
data = data.split(b"\n", 1)[1] if b"\n" in data else b""
return data.decode(errors="replace").splitlines()[-n:] if n > 0 else []
2026-10-21 15:19:07 +09:00
except FileNotFoundError:
return []
def part(fn):
"""Run one status read; an unreachable device gives {"error": ...} instead of failing the whole call."""
try:
return fn()
except Exception as e:
return {"error": str(e)}
# A hung or switched-off controller (2026-10-15) made /status take ~20 s: every arm read waits for ARP to give up
# and is retried. The reads now run side by side and /status answers within this time with "no reply" for the rest.
STATUS_DEADLINE_S = 2.5
_status_pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="status")
_status_reads = {} # part name -> its read, reused while it is still running (no pile-up of threads)
_status_lock = threading.Lock()
def parts(**fns):
"""Run status reads in parallel; one that has not answered within STATUS_DEADLINE_S reads as {"error": ...}."""
with _status_lock:
for name, fn in fns.items():
f = _status_reads.get(name)
if f is None or f.done():
_status_reads[name] = _status_pool.submit(part, fn)
futures = {name: _status_reads[name] for name in fns}
done, _ = wait(futures.values(), timeout=STATUS_DEADLINE_S)
return {name: f.result() if f in done else {"error": f"no reply within {STATUS_DEADLINE_S} s"}
for name, f in futures.items()}
# ---------- request bodies ----------
class GoBody(BaseModel):
marker: str = Field(examples=["aisle_a"], description='Marker name; "home" = the charging dock')
class HeadBody(BaseModel):
yaw: float = Field(0, ge=-180, le=180, description="deg")
pitch: float | None = Field(None, ge=-5, le=35, description="deg; empty = keep the current pitch")
class BodyBody(BaseModel):
lift_mm: float | None = Field(None, ge=0, le=head.LIFT_MAX_MM, examples=[75], description="lifting column, 0 = lowest")
waist_deg: float | None = Field(None, ge=-140, le=140, description="waist rotation")
head_yaw_deg: float | None = Field(None, ge=-180, le=180)
head_pitch_deg: float | None = Field(None, ge=-5, le=35)
speed: float = Field(15, ge=1, le=50, description="speed ratio %, slow by default")
class SayBody(BaseModel):
text: str = Field(examples=["안녕하세요, 저는 루미예요."], description="English or Korean (Hangul = Korean)")
class AskBody(BaseModel):
question: str = Field(examples=["What can you do?"])
speak: bool = Field(True, description="also say the answer on the robot's speaker")
class StartBody(BaseModel):
patrol: str | None = Field(None, examples=["p1,p2,p3,p4,p5,p6,p7,p8,final,p9,p10,home"],
description="markers to drive through; empty = stay at the current place")
once: bool = Field(True, description="drive the route once (true) or loop it forever (false)")
pause: float = Field(1.0, ge=0, le=60, description="seconds to wait at each marker")
no_arm: bool = False
2026-11-18 13:30:09 +09:00
# ---------- E-STOP, base sensors, planned path (the Lumi app's Map, 2026-11-18) ----------
class EstopBody(BaseModel):
on: bool = Field(description="true: halt where it is (motors free), the drive waits; false: the same drive goes on")
@app.post("/agv/estop", tags=["base"], summary="E-STOP: pause the base where it is (on) and go on with the same drive (off)")
def agv_estop(body: EstopBody):
r = agv.estop(body.on)
if r.get("status") != "OK":
raise HTTPException(502, f"AGV refused: {r.get('error_message') or r.get('status')}")
return {"ok": True, "on": body.on}
ULTRA, ULTRA_EX, IR = ("/water_uavcan_master/rx_in_ultrasonic", "/water_uavcan_master/rx_in_ultrasonic_ex",
"/water_uavcan_master/rx_in_ir_v2")
def _ranges(msg, first=None):
"""A Float64MultiArray of the base (label "ultrasonic_ l1 m r1": a prefix, then sensor names; data in that
order, as the base page reads it) as {name: m}; 0 / under 1 mm = nothing in range -> None."""
dims = (msg.get("layout") or {}).get("dim") or [{}]
names = (dims[0].get("label") or "").split()[1:]
data = msg.get("data") or []
out = {}
for i, n in enumerate(names[:first] if first else names):
if "_" in n or i >= len(data):
continue
v = data[i]
out[n] = round(v, 3) if v and v > 0.001 else None
return out
@app.get("/agv/sensors", tags=["base"], summary="Speed, ultrasonic and infrared ranges of the base (the base page's "
"ultrasonic / infrared)")
def agv_sensors():
try:
got = rosbridge.read_many(["/robot_status", ULTRA, ULTRA_EX, IR], timeout=0.8)
except OSError as e:
raise HTTPException(502, f"base sensors not available: {e}")
vel = (got.get("/robot_status") or {}).get("velocity") or {}
return {"linear": (vel.get("linear") or {}).get("x"), "angular": (vel.get("angular") or {}).get("z"),
"ultrasonic": {**_ranges(got.get(ULTRA) or {}), **_ranges(got.get(ULTRA_EX) or {})},
"infrared": _ranges(got.get(IR) or {}, 8)}
@app.get("/agv/plan", tags=["base"], summary="The path the base plans to its goal now (the base page's global path); "
"empty when it is not driving")
def agv_plan():
try:
got = rosbridge.read_many(["/move_base/NavfnROS/plan"], timeout=1.2)
except OSError as e:
raise HTTPException(502, f"plan not available: {e}")
poses = (got.get("/move_base/NavfnROS/plan") or {}).get("poses") or []
pts = [[round(p["pose"]["position"]["x"], 3), round(p["pose"]["position"]["y"], 3)] for p in poses]
step = max(1, len(pts) // 200)
return {"points": pts[::step] + (pts[-1:] if pts and (len(pts) - 1) % step else [])}
2026-11-18 18:07:32 +09:00
# ---------- the base's settings (the Lumi app's Map SETTINGS, 2026-11-18) ----------
class BaseSettingBody(BaseModel):
name: str = Field(examples=["max_speed_linear"], description="max_speed_linear, max_speed_angular, pose_tolerance "
"or theta_tolerance")
value: float = Field(description="m/s, rad/s, m or rad; cut to the range the base page allows")
@app.get("/agv/settings", tags=["base"], summary="Four of the base page's configuration settings: values now and ranges")
def agv_settings():
from robot import base_settings
try:
now, limits = base_settings.read(), base_settings.ranges()
except (OSError, RuntimeError, ValueError) as e:
raise HTTPException(502, f"base settings not available: {e}")
return {"settings": [{"name": n, "value": now[n], "min": s[1], "max": s[2], "step": s[3], "default": s[4]}
for n, s in limits.items()]}
@app.post("/agv/settings", tags=["base"], summary="Save one base setting, as the base page's configuration saves it")
def agv_settings_set(body: BaseSettingBody):
from robot import base_settings
if body.name not in base_settings.SETTINGS:
raise HTTPException(400, f"unknown setting {body.name}")
try:
saved = base_settings.write(body.name, body.value)
except (OSError, RuntimeError, ValueError) as e:
raise HTTPException(502, f"base did not save it: {e}")
return {"ok": True, "name": body.name, "value": saved}
2026-11-18 13:30:09 +09:00
# ---------- songs (the Lumi app's Commands, 2026-11-18) ----------
class SingBody(BaseModel):
id: str | None = Field(None, description="a song id from GET /songs; empty = any of them")
_sing = {"thread": None, "stop": threading.Event(), "id": None}
@app.get("/songs", tags=["voice"], summary="The songs Lumi sings: id and title (English, Korean)")
def songs_list():
from audio import sing
return {"songs": [{"id": k, "title": s.get("title") or k, "title_ko": s.get("title_ko") or s.get("title") or k}
for k, s in sing.songs().items()],
"singing": _sing["id"] if _sing["thread"] and _sing["thread"].is_alive() else None}
@app.post("/sing", tags=["voice"], summary="Sing a song with head moves; returns at once (STOP or /sing/stop ends it)")
def sing_start(body: SingBody):
from audio import sing
all_songs = sing.songs()
if body.id is not None and body.id not in all_songs:
raise HTTPException(404, f"no song {body.id}; songs: {list(all_songs)}")
if assistant_pids(): # it owns the speaker and the head: it sings, as if it heard it
title = all_songs[body.id]["title"] if body.id else None
send_to_assistant("heard", text=f"sing {title}" if title else "sing a song")
return {"ok": True, "by": "assistant"}
robot_free(manual=True) # not while a task, a wave or a drive runs
if _sing["thread"] and _sing["thread"].is_alive():
raise HTTPException(409, "Already singing.")
song = body.id or random.choice(list(all_songs))
stop = _sing["stop"] = threading.Event()
def run():
try:
with _voice_lock:
sing.sing(song, abort=stop.is_set)
finally:
_sing["id"] = None
_sing["id"] = song
_sing["thread"] = threading.Thread(target=run, daemon=True)
_sing["thread"].start()
return {"ok": True, "by": "api", "id": song}
@app.post("/sing/stop", tags=["voice"], summary="Stop the song (music, voice and head)")
def sing_stop():
_sing["stop"].set()
return {"ok": True}
2026-10-21 15:19:07 +09:00
# ---------- status ----------
@app.get("/status", tags=["status"], summary="Battery, position, base / head / arm state, assistant")
def status():
def base():
s = agv.status()
return {k: s.get(k) for k in ("power_percent", "charge_state", "current_pose", "move_status", "move_target",
2026-11-18 13:30:09 +09:00
"running_status", "error_code", "estop_state", "is_paused",
"soft_estop_state", "hard_estop_state")}
2026-10-21 15:19:07 +09:00
def body():
j = head.joints()
return {**dict(zip(["lift_mm", "waist_deg", "head_yaw_deg", "head_pitch_deg"], (round(x["pos"], 2) for x in j))),
"enabled": all(x["enable"] for x in j)}
2026-10-21 15:19:07 +09:00
def arm_state():
r = arm.cmd("get_robot_state")
return {"power": bool(r.get("power")), "enable": bool(r.get("enable")), "program": arm.program_state()}
return {**parts(base=base, body=body, arm=arm_state),
"assistant": {"running": bool(assistant_pids()), "pids": assistant_pids()}}
# ---------- base ----------
@app.get("/agv/markers", tags=["base"], summary="Markers on the current map")
def markers():
return {"markers": agv.markers()}
def fetch_head_ahead():
from tasks import fetch
fetch.head_ahead() # drives look ahead, wherever the head was turned
def held_to_look():
"""Something held goes to look before the base drives (fetch.drive_ready); 409 when it can't (no drive)."""
from tasks import fetch
try:
fetch.drive_ready()
except Exception as e:
raise HTTPException(409, f"the arm is not ready to drive: {e}")
2026-10-21 15:19:07 +09:00
@app.post("/agv/go", tags=["base"], summary="Drive to a marker (returns at once; watch /status move_status)")
def go(body: GoBody):
_route.stop()
names = agv.markers()
if body.marker not in names:
raise HTTPException(400, f"unknown marker {body.marker!r}; markers: {names}")
if assistant_pids():
send_to_assistant("go", marker=body.marker)
return {"ok": True, "marker": body.marker, "by": "assistant"}
held_to_look()
2026-10-21 15:19:07 +09:00
part(fetch_head_ahead)
ok, msg = agv.go(body.marker)
if not ok:
raise HTTPException(502, f"AGV refused: {msg}")
return {"ok": True, "marker": body.marker}
# ---------- several markers in a row ----------
class RouteBody(BaseModel):
markers: list[str] = Field(examples=[["p1", "p3", "home"]], min_length=1)
pause: float = Field(1.0, ge=0, le=60, description="seconds to wait at each marker")
loop: bool = Field(False, description="there and back again (a, b, c, b, a, ...); needs the assistant "
"(Greeter / Patrol on)")
rounds: int = Field(0, ge=0, le=99, description="with loop: this many times there and back, 0 = until stopped")
2026-10-21 15:19:07 +09:00
class RouteRunner:
"""Drives marker after marker when the assistant is not running (it does this itself when it runs)."""
def __init__(self):
self.thread, self.stop_flag, self.state = None, threading.Event(), {}
def start(self, markers, pause):
self.stop()
self.stop_flag = threading.Event()
self.state = {"route": markers, "index": 0, "status": "starting"}
self.thread = threading.Thread(target=self._run, args=(markers, pause, self.stop_flag), daemon=True)
self.thread.start()
def stop(self):
self.stop_flag.set()
def _run(self, markers, pause, stop):
for i, m in enumerate(markers):
if stop.is_set():
break
self.state.update(index=i, status=f"driving to {m}")
ok, msg = agv.go(m)
if not ok:
self.state["status"] = f"{m}: AGV refused ({msg})"
return
time.sleep(1.0)
while not stop.is_set():
ms = (part(agv.status) or {}).get("move_status")
if ms != "running":
break
time.sleep(0.5)
if stop.is_set():
break
if ms != "succeeded":
self.state["status"] = f"{m}: {ms}"
return
stop.wait(pause)
self.state["status"] = "cancelled" if stop.is_set() else "done"
_route = RouteRunner()
@app.post("/agv/route", tags=["base"], summary="Drive through several markers in order (once)")
def go_route(body: RouteBody):
names = agv.markers()
unknown = [m for m in body.markers if m not in names]
if unknown:
raise HTTPException(400, f"unknown markers {unknown}; markers: {names}")
if assistant_pids():
send_to_assistant("route", markers=body.markers, pause=body.pause, loop=body.loop, rounds=body.rounds)
2026-10-21 15:19:07 +09:00
return {"ok": True, "route": body.markers, "by": "assistant"}
if body.loop:
raise HTTPException(409, SWITCHES_OFF)
held_to_look()
2026-10-21 15:19:07 +09:00
_route.start(body.markers, body.pause)
return {"ok": True, "route": body.markers, "by": "api"}
@app.get("/agv/route", tags=["base"], summary="Progress of the last route driven by the API")
def route_state():
return _route.state
@app.post("/agv/cancel", tags=["base"], summary="Stop the current drive")
def cancel():
_route.stop()
if assistant_pids():
send_to_assistant("cancel")
return {"status": agv.cancel()}
# ---------- head / arm ----------
@app.post("/head/turn", tags=["body"], summary="Turn the head (slow); waits until the move ends")
def head_turn(body: HeadBody):
robot_free(manual=True)
lift, waist, _, pitch = head.status()
head.moveto([lift, waist, body.yaw, pitch if body.pitch is None else body.pitch]) # +-180, not head.turn's YAW_LIMIT
return {"body": dict(zip(["lift_mm", "waist_deg", "head_yaw_deg", "head_pitch_deg"],
(round(p, 2) for p in head.status())))}
@app.post("/body/move", tags=["body"], summary="Lift / waist / head (slow); empty fields keep their value")
def body_move(body: BodyBody):
robot_free(manual=True)
cur = head.status()
target = [cur[i] if v is None else v
for i, v in enumerate((body.lift_mm, body.waist_deg, body.head_yaw_deg, body.head_pitch_deg))]
reply = head.moveto(target, body.speed, 20, timeout=60)
return {"reply": reply, "body": dict(zip(["lift_mm", "waist_deg", "head_yaw_deg", "head_pitch_deg"],
(round(p, 2) for p in head.status())))}
2026-11-20 12:10:58 +09:00
def _wave_hello():
"""One line of wave_lines.ASKED in English or Korean (picked at random, as Wave greet does), said in the background
once the hand is up; skipped when Lumi is already speaking."""
from tasks import wave_lines
line = random.choice(wave_lines.ASKED)[random.randrange(2)]
def run():
if not _voice_lock.acquire(blocking=False):
return
try:
from audio import mouth
mouth.say(line)
except Exception as e:
print(f"wave hello: say failed: {e!r}", flush=True)
finally:
_voice_lock.release()
_bg(run)
@app.post("/arm/wave", tags=["arm"], summary="Wave, checked first (manipulation/wave.py): look -> wave_out -> "
2026-11-20 12:10:58 +09:00
"wave_start, the swings, stays at wave_start; with Greeter or "
"Patrol on Lumi says hello (EN or KO) as the hand comes up")
2026-10-21 15:19:07 +09:00
def arm_wave():
robot_free(manual=True)
2026-11-20 12:10:58 +09:00
m = read_modes()
talk = m["greeter"] or m["patrol"] # owner 2026-11-20: a hello out loud only with Greeter or Patrol on
_waving.set()
2026-10-21 15:19:07 +09:00
try:
2026-11-20 12:10:58 +09:00
wave.wave(on_up=_wave_hello if talk else None)
2026-10-21 15:19:07 +09:00
except wave.WaveError as e:
raise HTTPException(409, e.args[0])
except motion.MotionError as e:
raise HTTPException(409, str(e))
finally:
_waving.clear()
2026-10-21 15:19:07 +09:00
return {"ok": True}
@app.post("/arm/stop", tags=["arm"], summary="Stop the running arm program, motion or skill")
def arm_stop():
return skills.cancel()
# ---------- voice ----------
@app.post("/say", tags=["voice"], summary="Lumi says the text on its speaker; returns when finished")
def say(body: SayBody):
robot_free()
from audio import mouth
with _voice_lock:
t = time.time()
mouth.say(body.text)
return {"ok": True, "seconds": round(time.time() - t, 1)}
@app.post("/ask", tags=["voice"], summary="Ask Lumi a question (knowledge base + LLM), optionally spoken")
def ask(body: AskBody):
global _brain
if body.speak:
robot_free()
from assistant.brain import Brain
_brain = _brain or Brain()
t = time.time()
reply, hits = _brain.answer(body.question)
took = round(time.time() - t, 1)
if body.speak:
from audio import mouth
with _voice_lock:
mouth.say(reply)
return {"answer": reply, "llm_seconds": took, "sources": [src for _, src, _ in hits]}
# ---------- assistant (lumi.py) ----------
@app.post("/assistant/start", tags=["assistant"], summary="Start lumi.py (greeter + conversation, optional patrol)")
def assistant_start(body: StartBody):
if assistant_pids():
raise HTTPException(409, "already running")
args = [str(VENV_PY), str(ROOT / "assistant" / "lumi.py")]
if body.patrol:
names = agv.markers()
unknown = [m for m in body.patrol.split(",") if m not in names]
if unknown:
raise HTTPException(400, f"unknown markers {unknown}; markers: {names}")
args += ["--patrol", body.patrol, "--pause", str(body.pause)] + ["--once"] * body.once
args += ["--no-arm"] * body.no_arm
2026-10-21 15:19:07 +09:00
log = open(CONSOLE_LOG, "a")
log.write(f"\n===== {time.strftime('%Y-%m-%d %H:%M:%S')} start: {' '.join(args[1:])}\n")
log.flush()
p = subprocess.Popen(args, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,
start_new_session=True)
return {"ok": True, "pid": p.pid, "args": args[2:]}
@app.post("/assistant/stop", tags=["assistant"], summary="Stop lumi.py and the base")
2026-11-17 15:17:38 +09:00
def assistant_stop(arm_too=True):
2026-10-21 15:19:07 +09:00
pids = assistant_pids()
for pid in pids:
os.kill(pid, signal.SIGINT) # lumi.py exits at once on Ctrl+C
time.sleep(1.0)
for pid in assistant_pids():
os.kill(pid, signal.SIGKILL)
part(agv.cancel) # a patrol drive would otherwise go on to its marker
2026-11-17 15:17:38 +09:00
if arm_too:
part(arm.stop)
2026-10-21 15:19:07 +09:00
return {"stopped": pids}
@app.get("/assistant/log", tags=["assistant"], summary="Last lines of lumi.log (and errors from the console)")
def assistant_log(lines: int = 50):
return {"lumi_log": tail(LUMI_LOG, lines), "console": tail(CONSOLE_LOG, 15)}
@app.get("/logs/robot", tags=["assistant"], summary="Last lines of this server's log (fetch tasks, arm, base, errors "
"and tracebacks) and the errors among the last 400")
def robot_log(lines: int = 50):
recent = tail(API_LOG, 400)
return {"lines": [l[:300] for l in recent[-lines:]], "errors": [l[:200] for l in recent if ERROR_RE.search(l)][-15:]}
# ---------- live cameras and the dashboard ----------
class ViewSettings(BaseModel):
box_color: str | None = Field(None, pattern=r"^#[0-9a-fA-F]{6}$", examples=["#22c55e"])
thickness: int | None = Field(None, ge=1, le=6)
boxes: bool | None = None
labels: bool | None = None
def _camera_name(name):
if name not in CAMERA_NAMES:
raise HTTPException(404, f"camera must be one of {CAMERA_NAMES}")
return name
@app.get("/", include_in_schema=False)
@app.get("/view", tags=["cameras"], summary="Dashboard: both cameras live + robot controls (open in a browser)",
response_class=HTMLResponse)
def view():
return DASHBOARD.read_text()
@app.get("/camera/{name}.mjpg", tags=["cameras"], summary="Live MJPEG stream of one camera (head / torso)")
def camera_stream(name: str):
name = _camera_name(name)
def frames():
last = 0.0
while True:
camview.want(name) # full speed while someone watches
path = camview.frame_path(name)
try:
mtime = path.stat().st_mtime
if mtime != last:
last = mtime
yield b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + path.read_bytes() + b"\r\n"
except FileNotFoundError:
pass
time.sleep(0.05)
return StreamingResponse(frames(), media_type="multipart/x-mixed-replace; boundary=frame")
@app.get("/camera/stream", tags=["cameras"],
summary="Live video of both cameras in ONE connection: camera JPEGs at full rate + detections")
def camera_stream_all(max_fps: float = 15.0):
"""Binary records: 1 byte camera (0 head, 1 torso), 1 byte kind (0 JPEG, 1 detections JSON),
4 bytes length (big endian), payload. The dashboard draws the boxes itself, so the video is not slowed
down by person detection."""
import struct
names = list(CAMERA_NAMES)
camview.ensure_running()
def records():
seen, last_want, gap = {}, 0.0, 1.0 / max(1.0, max_fps)
sent = {n: 0.0 for n in names}
while True:
now = time.time()
if now - last_want > 1.0:
last_want = now
for n in names:
camview.want(n)
for i, n in enumerate(names):
for kind, path in ((0, camview.raw_path(n)), (1, camview.det_path(n))):
try:
m = path.stat().st_mtime
except FileNotFoundError:
continue
if seen.get((n, kind)) == m or (kind == 0 and now - sent[n] < gap):
continue
seen[(n, kind)] = m
data = path.read_bytes()
if kind == 1: # only what the dashboard draws
try:
d = json.loads(data)
data = json.dumps({"w": d["width"], "h": d["height"], "people": [
{k: p.get(k) for k in ("box", "distance_m", "angle_deg", "focus", "near")}
for p in d["people"]], "objects": [
{k: o.get(k) for k in ("box", "name", "colour", "width_mm", "position_mm")}
for o in d.get("objects", [])]}).encode()
except (ValueError, KeyError):
continue
else:
sent[n] = now
yield struct.pack(">BBI", i, kind, len(data)) + data
time.sleep(0.01)
return StreamingResponse(records(), media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})
@app.get("/camera/{name}/latest.jpg", tags=["cameras"], summary="Latest picture right away (the dashboard polls this)")
def camera_latest(name: str):
name = _camera_name(name)
camview.want(name) # full speed while someone watches
camview.ensure_running()
try:
return Response(camview.frame_path(name).read_bytes(), media_type="image/jpeg",
headers={"Cache-Control": "no-store"})
except FileNotFoundError:
raise HTTPException(404, "no picture yet")
2026-11-18 18:37:10 +09:00
@app.get("/camera/{name}/hd.jpg", tags=["cameras"],
summary="Latest picture at the camera's own size (1280 x 720) with person boxes (the Lumi app's Drive)")
def camera_hd(name: str):
name = _camera_name(name)
camview.want(name) # full speed while someone watches
camview.ensure_running()
try:
return Response(camview.picture_hd(name), media_type="image/jpeg", headers={"Cache-Control": "no-store"})
except FileNotFoundError:
raise HTTPException(404, "no picture yet")
2026-10-21 15:19:07 +09:00
@app.get("/camera/{name}.jpg", tags=["cameras"], summary="Latest picture of one camera")
def camera_snapshot(name: str):
name = _camera_name(name)
camview.ensure_running()
for _ in range(50): # up to 5 s for a fresh picture
camview.want(name)
age = camview.picture_age(name)
if age is not None and age < camview.FRESH_S:
return Response(camview.frame_path(name).read_bytes(), media_type="image/jpeg")
time.sleep(0.1)
raise HTTPException(503, _camera_error(name) or "no picture from this camera yet")
@app.get("/camera/{name}/info", tags=["cameras"], summary="Who has the camera and the people it sees")
def camera_info(name: str):
name = _camera_name(name)
try:
info = json.loads(camview.info_path(name).read_text())
except (FileNotFoundError, ValueError):
info = {"time": 0, "source": None, "people": []}
info["age_s"] = round(time.time() - info["time"], 1) if info["time"] else None
info["error"] = _camera_error(name)
return info
def _camera_error(name):
if not camview.service_pid():
return "camera service not running"
st = camview.status().get("cameras", {}).get(name)
return None if st in (None, "ok") else st
@app.get("/view/settings", tags=["cameras"], summary="How person boxes are drawn")
def view_settings():
return camview.settings()
@app.post("/view/settings", tags=["cameras"], summary="Change box colour / thickness, show boxes / labels")
def view_settings_set(body: ViewSettings):
return camview.save_settings(body.model_dump())
class VolumeBody(BaseModel):
percent: int = Field(55, ge=0, le=100)
@app.get("/volume", tags=["voice"], summary="Speaker volume (%)")
def volume_get():
from audio import mouth
return {"percent": mouth.volume()}
@app.post("/volume", tags=["voice"], summary="Set the speaker volume (%); kept for every program")
def volume_set(body: VolumeBody):
from audio import mouth
mouth.set_volume(body.percent)
return {"percent": mouth.volume()}
2026-11-17 15:17:38 +09:00
# An arm that is off or unreachable takes ~14 s per stop (no route to host, 2026-11-17): STOP then answered after
# ~30 s and the app showed "no answer". The base stops first; the arm is stopped meanwhile and waited for this long.
STOP_ARM_WAIT_S = 2.0
_stop_pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="stop")
2026-10-21 15:19:07 +09:00
@app.post("/stop", tags=["status"], summary="STOP everything: base drive, arm program and the assistant")
def stop_all():
2026-11-17 15:17:38 +09:00
part(agv.cancel) # the base first, at once
_waving_off() # first: the supervisor must not bring lumi.py back to wave
2026-10-21 15:19:07 +09:00
jogger.stop()
_route.stop()
2026-11-18 13:30:09 +09:00
_sing["stop"].set() # a song from /sing
2026-10-21 15:19:07 +09:00
task = part(_fetch_stop) # first, so the runner starts nothing new
2026-11-17 15:17:38 +09:00
arm_parts = [_stop_pool.submit(part, skills.cancel)]
stopped = assistant_stop(arm_too=False)
arm_parts.append(_stop_pool.submit(part, arm.stop)) # after lumi.py is gone, as before
base = part(agv.cancel) # again: nothing started a drive meanwhile
done, _ = wait(arm_parts, timeout=STOP_ARM_WAIT_S)
arm_reply = (arm_parts[0].result() if arm_parts[0] in done
else {"error": f"no reply within {STOP_ARM_WAIT_S:g} s; still being stopped"})
return {"assistant": stopped["stopped"], "agv": base, "arm": arm_reply, "task": task}
2026-10-21 15:19:07 +09:00
def _charging():
"""The base stands on its charger (charging), not driving."""
try:
st = agv.status() or {}
except Exception:
return False
return bool(st.get("charge_state")) and st.get("move_status") != "running"
def _waving_off():
"""STOP switches Wave and Welcome off (they would raise the arm again by itself); Greeter and Patrol keep theirs."""
m = {**read_modes(), "wave_greet": False, "welcome": False}
tmp = MODES_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(m))
os.replace(tmp, MODES_FILE)
def _bg(fn):
threading.Thread(target=fn, daemon=True).start()
_lowering = threading.Lock() # one stop_when_lowered at a time
def stop_when_lowered(wait_s=10.0, every=0.2):
"""The last switch off: lumi.py lowers the hand (wave_greet sees the switch off) before it is stopped, at most
`wait_s` s; a stop part-way down would leave the hand up (review 2026-11-16). A switch on again meanwhile: not
stopped after all (it was, and the supervisor started lumi.py again and again, 2026-11-16 16:31). None then."""
if not _lowering.acquire(blocking=False):
return None # one is waiting already; it checks the switches at its end
try:
return _stop_when_lowered(wait_s, every)
finally:
_lowering.release()
def _stop_when_lowered(wait_s, every):
end = time.time() + wait_s
while time.time() < end:
try:
if arm_route.where() not in arm_route.WAVE_POSES:
break
except Exception:
break
time.sleep(every)
if any_on(read_modes()):
return None # switched on again while the hand came down
if any_on(read_modes()):
return None
return assistant_stop()
2026-10-21 15:19:07 +09:00
def _fetch_stop():
from tasks import fetch
return fetch.stop()
# ---------- hold-to-move, map, arm (dashboard) ----------
AGV_WEB = "http://192.168.10.10:9001"
class JogBody(BaseModel):
2026-11-19 16:33:17 +09:00
axis: str = Field(examples=["head_yaw"], description="base_drive, base_turn, lift, waist, head_yaw, head_pitch, j1..j6, "
"tcp_x, tcp_y, tcp_z (the hand in a straight line, arm base frame)")
2026-10-21 15:19:07 +09:00
direction: int = Field(1, description="+1 or -1")
speed: float = Field(0.5, ge=0.05, le=1.0, description="0..1 of the axis' top speed")
class PointBody(BaseModel):
x: float
y: float
theta: float = Field(0.0, description="rad, map frame")
class MapBody(BaseModel):
map_name: str
floor: int = 1
2026-11-16 18:22:17 +09:00
MARKER_NAME = r"^[A-Za-z0-9_-]{1,50}$" # the base takes letters, digits, _ and - only, at most 50 characters
class MarkerBody(BaseModel):
name: str = Field(examples=["door_1"], description="letters, digits, _ and - (an existing name is moved)")
x: float | None = Field(None, description="m, map frame; none: where Lumi stands now")
y: float | None = None
theta: float = Field(0.0, description="rad, map frame (with x, y)")
2026-11-17 15:17:38 +09:00
charger: bool = Field(False, description="a charger's marker (type 11): the base docks with it")
2026-11-16 18:22:17 +09:00
class MarkerName(BaseModel):
name: str
2026-11-17 16:41:06 +09:00
class NoGoLineBody(BaseModel):
name: str = Field(examples=["door_1"], description="letters, digits, _ and - (an existing name is replaced)")
points: list[list[float]] = Field(min_length=2, examples=[[[0.0, 1.0], [2.0, 1.0]]],
description="[x, y] in m, map frame, in order")
2026-10-21 15:19:07 +09:00
class OnBody(BaseModel):
on: bool
class ProgramBody(BaseModel):
program: str = Field(examples=["arm_reach.jks"])
2026-10-21 15:19:07 +09:00
@app.post("/jog", tags=["control"], summary="Hold-to-move: call every ~150 ms while a button is held")
def jog(body: JogBody):
robot_free(manual=True)
try:
jogger.hold(body.axis, body.direction, body.speed)
except ValueError as e:
raise HTTPException(400, str(e))
err, jogger.last_error = jogger.last_error, None # report each error once, not on every call
return {"ok": True, "error": err}
@app.post("/jog/stop", tags=["control"], summary="Stop every hold-to-move axis now")
def jog_stop():
jogger.stop()
return {"ok": True}
2026-11-17 13:22:40 +09:00
def _forbidden_lines(floor):
"""The map's no-go lines drawn in the base's web page (forbidden_manager): [{name, points [[x, y], ...]}] on
2026-11-17 16:41:06 +09:00
this floor, in map metres, the newest first. Empty when the base does not answer: the map still shows."""
2026-11-17 13:22:40 +09:00
try:
values = rosbridge.call_service("/forbidden_manager/action_service", {"cmd": "list_lines", "message": ""})
lines = json.loads(values.get("message") or "{}") if values.get("success") else {}
except Exception:
return []
2026-11-17 16:41:06 +09:00
newest = sorted(lines.items(), key=lambda nl: (nl[1].get("date") or "", nl[0]), reverse=True) # the base dates each
return [{"name": n, "points": l["points"]} for n, l in newest
2026-11-17 13:22:40 +09:00
if l.get("floor", 1) == floor and len(l.get("points") or []) >= 2]
2026-11-17 16:41:06 +09:00
FORBIDDEN = "/forbidden_manager/action_service" # the base's no-go lines (its web page :9001 uses it)
def _lines_call(cmd, message):
"""One forbidden_manager command; raises 502 when the base refuses or does not answer."""
try:
v = rosbridge.call_service(FORBIDDEN, {"cmd": cmd, "message": json.dumps(message)})
except Exception as e:
raise HTTPException(502, f"the base did not answer: {e}")
if not v.get("success"):
raise HTTPException(502, f"the base refused: {v.get('message')}")
return v
@app.post("/map/line", tags=["map"], summary="Save a no-go line on this floor (the base never drives across it)")
def line_save(body: NoGoLineBody):
name = _marker_name(body.name)
if any(len(pt) != 2 for pt in body.points):
raise HTTPException(422, "Each point is [x, y].")
floor = agv.request("/api/map/get_current_map")["results"]["floor"]
line = {"name": name, "type": "forbidden", "floor": floor, "points": [[round(x, 3), round(y, 3)] for x, y in body.points],
"comment": "", "properties": "{}"}
_lines_call("add_lines", {"data": [line]})
return {"ok": True, "line": line}
@app.post("/map/line/delete", tags=["map"], summary="Delete a no-go line")
def line_delete(body: MarkerName):
name = _marker_name(body.name)
_lines_call("delete_lines", {"names": [name]})
return {"ok": True}
2026-11-17 18:33:14 +09:00
# The base keeps no dates for markers (query_list is by name): the app's markers are dated here when saved, so the app
# lists the newest first. Maps: the base's map folders on :9001 carry their dates (nginx index).
MARKER_TIMES = ROOT / "data" / "marker_times.json" # {"<map>/<floor>/<name>": unix time}
MAP_DATE = re.compile(r'href="([^"/]+)/">[^<]*</a>\s+(\d\d-\w{3}-\d{4} \d\d:\d\d)')
def _marker_times():
try:
return json.loads(MARKER_TIMES.read_text())
except (OSError, ValueError):
return {}
def _mark_time(name, when):
"""Note when a marker of the current map was saved (`when` None: it was deleted); never fails the call."""
try:
cur = agv.request("/api/map/get_current_map")["results"]
key = f"{cur['map_name']}/{cur['floor']}/{name}"
times = _marker_times()
if when is None:
times.pop(key, None)
else:
times[key] = when
tmp = MARKER_TIMES.with_suffix(".tmp")
tmp.write_text(json.dumps(times))
os.replace(tmp, MARKER_TIMES)
except Exception:
pass
def _map_dates():
"""{map name: "YYYY-MM-DD HH:MM"} from the base's map folders; {} when the base does not answer."""
import datetime
try:
with urllib.request.urlopen(f"{AGV_WEB}/maps/", timeout=3) as r:
page = r.read().decode(errors="replace")
except Exception:
return {}
out = {}
for name, when in MAP_DATE.findall(page):
try:
out[urllib.request.unquote(name)] = datetime.datetime.strptime(when, "%d-%b-%Y %H:%M").strftime("%Y-%m-%d %H:%M")
except ValueError:
pass
return out
2026-10-21 15:19:07 +09:00
@app.get("/map/info", tags=["map"], summary="Current map, its geometry, the markers with poses and all maps")
def map_info():
cur = agv.request("/api/map/get_current_map")["results"]
marks = agv.request("/api/markers/query_list")["results"] or {} # None on a map without markers
2026-10-21 15:19:07 +09:00
maps = agv.request("/api/map/list")["results"]
markers = [{"name": n, "type": m.get("key"), "x": m["pose"]["position"]["x"], "y": m["pose"]["position"]["y"],
"theta": 2 * math.atan2(m["pose"]["orientation"]["z"], m["pose"]["orientation"]["w"])}
for n, m in marks.items() if m.get("floor", 1) == cur["floor"]]
2026-11-17 18:33:14 +09:00
times = _marker_times()
when = lambda n: times.get(f"{cur['map_name']}/{cur['floor']}/{n}", 0)
markers.sort(key=lambda m: -when(m["name"])) # the newest first; undated ones keep the base's order
dates = _map_dates()
return {"map_name": cur["map_name"], "floor": cur["floor"], **cur.get("info", {}), "markers": markers,
2026-11-17 13:22:40 +09:00
"lines": _forbidden_lines(cur["floor"]),
2026-10-21 15:19:07 +09:00
"main_dock": agv.dock_marker(), # "home"; further docks (dock2) keep their names
2026-11-17 18:33:14 +09:00
"maps": [{"name": n, "floors": f} # the newest first (folder date), then by name
for n, f in sorted(sorted(maps.items()), key=lambda nf: dates.get(nf[0], ""), reverse=True)]}
2026-10-21 15:19:07 +09:00
2026-11-18 10:47:26 +09:00
DARK_UNKNOWN, DARK_FREE, DARK_WALL = (10, 11, 13), (52, 58, 66), (232, 232, 232) # RGB, the Lumi app look; free clearly lighter than unknown, like :9001
2026-11-16 18:22:17 +09:00
def _dark(png):
"""The base's grey map (205 unknown, 255 free, 0 walls) in the app's dark look, same size."""
import cv2
import numpy as np
g = cv2.imdecode(np.frombuffer(png, np.uint8), cv2.IMREAD_GRAYSCALE)
out = np.empty(g.shape + (3,), np.uint8)
out[:] = DARK_UNKNOWN[::-1] # BGR
out[g > 230] = DARK_FREE[::-1]
out[g < 60] = DARK_WALL[::-1]
return cv2.imencode(".png", out)[1].tobytes()
2026-10-21 15:19:07 +09:00
@app.get("/map/image", tags=["map"], summary="Map picture (PNG) from the base; default the current map")
2026-11-16 18:22:17 +09:00
def map_image(map_name: str | None = None, floor: int | None = None, dark: bool = False):
2026-10-21 15:19:07 +09:00
if map_name is None:
cur = agv.request("/api/map/get_current_map")["results"]
map_name, floor = cur["map_name"], cur["floor"]
2026-11-17 18:33:14 +09:00
folder = f"{AGV_WEB}/maps/{urllib.request.quote(map_name)}/{floor or 1}"
2026-11-18 10:47:26 +09:00
# the app draws the raw lidar grid map.png like the base's own page (:9001): free space as the sensor saw it,
# walls and small obstacles as scanned, unknown left plain (owner, 2026-11-18; ui_map.png's clean outline is gone)
2026-10-21 15:19:07 +09:00
try:
2026-11-17 18:33:14 +09:00
with urllib.request.urlopen(f"{folder}/map.png", timeout=10) as r:
2026-11-16 18:22:17 +09:00
png = r.read()
return Response(_dark(png) if dark else png, media_type="image/png", headers={"Cache-Control": "max-age=60"})
2026-10-21 15:19:07 +09:00
except Exception as e:
raise HTTPException(502, f"map picture not available: {e}")
@app.post("/map/switch", tags=["map"], summary="Use another map (the base service restarts; relocalise after)")
def map_switch(body: MapBody):
robot_free()
2026-11-17 18:33:14 +09:00
scan_free()
2026-10-21 15:19:07 +09:00
try:
r = agv.request(f"/api/map/set_current_map?map_name={body.map_name}&floor={body.floor}", timeout=10)
except Exception as e: # the base restarts and may not answer
r = {"note": f"no reply ({e}); the base is restarting"}
return {"ok": True, "reply": r}
2026-11-16 18:22:17 +09:00
def _marker_name(name):
if not re.match(MARKER_NAME, name or ""):
raise HTTPException(422, "A marker name has letters, digits, _ and - only (at most 50).")
return name
@app.post("/map/marker", tags=["map"], summary="Save a marker where Lumi stands, or at x, y, theta (the Lumi app)")
def marker_save(body: MarkerBody):
name = _marker_name(body.name)
2026-11-17 15:17:38 +09:00
kind = f"type=11&num={_dock_num(name)}" if body.charger else "type=0"
2026-11-16 18:22:17 +09:00
if body.x is None or body.y is None:
2026-11-17 15:17:38 +09:00
r = agv.request(f"/api/markers/insert?name={name}&{kind}" + ("" if body.charger else "&num=1"))
2026-11-16 18:22:17 +09:00
else:
2026-11-17 15:17:38 +09:00
r = agv.request(f"/api/markers/insert_by_pose?name={name}&x={body.x}&y={body.y}&theta={body.theta}&{kind}")
2026-11-16 18:22:17 +09:00
agv.known_markers(fresh=True) # drives to it work at once
2026-11-17 18:33:14 +09:00
_mark_time(name, time.time())
2026-11-16 18:22:17 +09:00
return {"ok": True, "reply": r}
2026-11-17 15:17:38 +09:00
def _dock_num(name):
"""A charger marker's dock number: its own when it is one already, else the next free one (the lowest is the main
dock, agv.dock_marker), so a renamed charger (saved anew, then the old one deleted) becomes the main dock again."""
marks = agv.request("/api/markers/query_list")["results"] or {}
if marks.get(name, {}).get("key") == 11:
return marks[name].get("num", 1)
nums = [m.get("num", 1) for m in marks.values() if m.get("key") == 11]
return max(nums) + 1 if nums else 1
@app.post("/map/marker/delete", tags=["map"], summary="Delete a marker (a charger's too: the app warns first)")
2026-11-16 18:22:17 +09:00
def marker_delete(body: MarkerName):
name = _marker_name(body.name)
r = agv.request(f"/api/markers/delete?name={name}")
agv.known_markers(fresh=True)
2026-11-17 18:33:14 +09:00
_mark_time(name, None)
2026-11-16 18:22:17 +09:00
return {"ok": True, "reply": r}
@app.post("/map/position", tags=["map"], summary="Set where Lumi is on the map (relocalise; x, y in m, theta in rad)")
def map_position(body: PointBody):
robot_free()
2026-11-17 18:33:14 +09:00
scan_free()
2026-11-16 18:22:17 +09:00
r = agv.request(f"/api/position_adjust_by_pose?x={body.x}&y={body.y}&theta={body.theta}")
return {"ok": True, "reply": r}
LASER_X = 0.126 # m the 2D lidar sits ahead of the base's centre (URDF Radar_Link, docs/01_HARDWARE.md)
def scan_points(scan, every=2, laser_x=LASER_X):
"""A sensor_msgs/LaserScan as points [x ahead, y left] (m) around the base's centre; every `every`-th ray, rays
without a reading or out of range left out."""
a0, da = scan.get("angle_min", 0.0), scan.get("angle_increment", 0.0)
lo, hi = scan.get("range_min", 0.0), scan.get("range_max", 1e9)
out = []
for i, r in enumerate(scan.get("ranges") or []):
if i % every or r is None or not (lo <= r <= hi):
continue
a = a0 + i * da
out.append([round(laser_x + r * math.cos(a), 3), round(r * math.sin(a), 3)])
return out
@app.get("/map/scan", tags=["map"], summary="What the lidar sees now, as points around the base (the Lumi app's "
"position correction)")
def map_scan():
try:
m = rosbridge.read_once("/scan", timeout=3.0)
except OSError as e:
raise HTTPException(502, f"lidar not available: {e}")
return {"frame": "base", "points": scan_points(m["msg"])}
@app.post("/map/position/marker", tags=["map"], summary="Lumi stands at this marker: its pose is taken from it")
def map_position_marker(body: MarkerName):
name = _marker_name(body.name)
robot_free()
r = agv.request(f"/api/position_adjust?marker={name}")
return {"ok": True, "reply": r}
2026-11-17 18:33:14 +09:00
# ---------- a new map (the base's own map builder on :8809, docs/05_AGV_BASE.md §7) ----------
# Its page map-build/map.html talks to a small HTTP API (map-build-api/start, get_info, stop) and reads the live map
# picture (maps/<name>/<floor>/map-temp.png) with its geometry (/map_metadata), the pose (/robot_pose) and the
# optimizing progress (/optimizing_progress) over rosbridge. The base has no "cancel": a scan ends by saving it.
MAP_BUILD = "http://192.168.10.10:8809"
NEW_MAP_NAME = r"^[A-Za-z0-9_]{1,36}$" # the base's map tool: letters, digits and _ only, at most 36
SCAN_DELTAS = {"small": 0, "middle": 1, "large": 2} # map size -> index in /map_build_tool/deltas (m per pixel)
SCAN_DELTAS_DEFAULT = [0.02, 0.03, 0.05] # what the base answered, 2026-11-17
SCAN_FILE = Path("/dev/shm/lumi_mapping.json") # the scan this API started: {name, floor, maps before}
SCAN_SAVE_S = 180 # the base answers `stop` once the map is saved
_scan_meta = {} # (width, height) -> the map's geometry at that size (newest kept)
class NewMapBody(BaseModel):
name: str = Field(examples=["office_2"], description="letters, digits and _ (at most 36); not a map that exists")
size: str = Field("small", description="small (< 3600 m²), middle (3600 to 10000 m²) or large")
def _build_get(path, timeout=5.0):
"""One GET of the base's map builder (MAP_BUILD + path): the raw body."""
with urllib.request.urlopen(f"{MAP_BUILD}/{path}", timeout=timeout) as r:
return r.read()
def _scan_info():
"""The map builder's state: {mapping, name, floor, map_type}; 502 when it does not answer."""
try:
d = json.loads(_build_get("map-build-api/get_info?hotelid=&floor="))
except Exception as e:
raise HTTPException(502, f"the base's map builder did not answer: {e}")
return {"mapping": bool(d.get("mapbuilding")), "name": d.get("hotelid") or "",
"floor": int(d.get("floor") or 1), "map_type": d.get("map_type") or ""}
def _scanning():
"""A scan this API started is still running (checked with the base only when one was started here)."""
if not SCAN_FILE.exists():
return False
try:
if _scan_info()["mapping"]:
return True
except HTTPException:
return True # the base does not say: keep refusing until it does
SCAN_FILE.unlink(missing_ok=True) # saved from the base's own page
return False
def scan_free():
if _scanning():
raise HTTPException(409, "A new map is being made. Save or cancel it first.")
def _scan_meta_keep(m):
"""Remember the geometry of a /map_metadata message by its size; the picture is matched to it."""
if not m or not m.get("width"):
return None
o = (m.get("origin") or {}).get("position") or {}
g = {"width": m["width"], "height": m["height"], "resolution": round(m.get("resolution", 0.05), 6),
"origin_x": o.get("x", 0.0), "origin_y": o.get("y", 0.0)}
_scan_meta[(g["width"], g["height"])] = g
while len(_scan_meta) > 20:
del _scan_meta[next(iter(_scan_meta))]
return g
@app.post("/map/scan/start", tags=["map"], summary="Start making a new map (the base leaves the current map)")
def scan_start(body: NewMapBody):
if not re.match(NEW_MAP_NAME, body.name or ""):
raise HTTPException(422, "A map name has letters, digits and _ only (at most 36).")
if body.size not in SCAN_DELTAS:
raise HTTPException(422, "size is small, middle or large.")
robot_free()
robot_free(manual=True)
info = _scan_info()
if info["mapping"]:
raise HTTPException(409, f"A new map is being made already: {info['name']}. Save or cancel it first.")
maps = agv.request("/api/map/list")["results"] or {}
if body.name in maps:
raise HTTPException(409, f"A map named {body.name} exists already.")
try:
deltas = json.loads(json.loads(rosbridge.call_service("/rosapi/get_param",
{"name": "/map_build_tool/deltas"})["value"]))
delta = float(deltas[SCAN_DELTAS[body.size]])
except Exception:
delta = SCAN_DELTAS_DEFAULT[SCAN_DELTAS[body.size]]
SCAN_FILE.write_text(json.dumps({"name": body.name, "floor": 1, "maps": sorted(maps), "time": time.time()}))
try:
reply = _build_get(f"map-build-api/start?hotelid={body.name}&floor=1&delta={delta:g}&map_type=v2", 30)
except Exception as e:
SCAN_FILE.unlink(missing_ok=True)
raise HTTPException(502, f"the base did not start the scan: {e}")
return {"ok": True, "name": body.name, "floor": 1, "delta": delta, "reply": reply.decode(errors="replace")[:300]}
@app.get("/map/scan/state", tags=["map"], summary="The new map being made: its name, Lumi's pose, optimizing progress")
def scan_state():
info = _scan_info()
if not info["mapping"]:
return {**info, "pose": None, "progress": None, "map": None}
try:
got = rosbridge.read_many(["/robot_pose", "/map_metadata", "/optimizing_progress"], timeout=1.2)
except OSError:
got = {}
p = got.get("/robot_pose")
pose = None
if p and "position" in p:
q = p.get("orientation") or {}
pose = {"x": p["position"]["x"], "y": p["position"]["y"],
"theta": 2 * math.atan2(q.get("z", 0.0), q.get("w", 1.0))}
prog = (got.get("/optimizing_progress") or {}).get("data")
return {**info, "pose": pose, "map": _scan_meta_keep(got.get("/map_metadata")),
"progress": None if prog is None else min(1.0, max(0.0, float(prog)))}
@app.get("/map/scan/picture", tags=["map"], summary="The new map as it grows: a picture (PNG, base64) and its geometry")
def scan_picture(dark: bool = True):
import base64
import cv2
import numpy as np
info = _scan_info()
if not info["mapping"]:
raise HTTPException(409, "No new map is being made.")
try:
png = _build_get(f"maps/{urllib.request.quote(info['name'])}/{info['floor']}/map-temp.png?t={time.time():.0f}",
10)
h, w = cv2.imdecode(np.frombuffer(png, np.uint8), cv2.IMREAD_GRAYSCALE).shape
except Exception as e:
raise HTTPException(502, f"the new map's picture is not there yet: {e}")
try:
_scan_meta_keep(rosbridge.read_once("/map_metadata", timeout=1.5).get("msg"))
except OSError:
pass
geo = _scan_meta.get((w, h))
exact = geo is not None
if not exact: # the picture and its geometry come apart while the map grows
if not _scan_meta:
raise HTTPException(502, "the new map's size is not known yet")
geo = {**list(_scan_meta.values())[-1], "width": w, "height": h}
return {**geo, "exact": exact, "png": base64.b64encode(_dark(png) if dark else png).decode()}
def _scan_end():
"""Ends the scan the base's way (`stop` saves it); the name and floor it had."""
info = _scan_info()
if not info["mapping"]:
raise HTTPException(409, "No new map is being made.")
try:
_build_get("map-build-api/stop", SCAN_SAVE_S)
except Exception as e:
raise HTTPException(502, f"the base did not save the map: {e}")
return info
@app.post("/map/scan/save", tags=["map"], summary="Save the new map (best after optimizing reaches 100 %)")
def scan_save():
robot_free(manual=True)
info = _scan_end()
SCAN_FILE.unlink(missing_ok=True)
return {"ok": True, "name": info["name"], "floor": info["floor"]}
@app.post("/map/scan/cancel", tags=["map"], summary="Stop making the new map and delete it")
def scan_cancel():
"""The base cannot drop a scan: it is saved, then deleted, but only a map this API started under a new name and
one the base does not use now. Otherwise it stays (deleted: false, note says why)."""
robot_free(manual=True)
try:
started = json.loads(SCAN_FILE.read_text())
except (FileNotFoundError, ValueError):
started = {}
info = _scan_end()
SCAN_FILE.unlink(missing_ok=True)
name, floor = info["name"], info["floor"]
if started.get("name") != name or name in started.get("maps", [name]):
return {"ok": True, "name": name, "deleted": False, "note": "not a map this API started: it stays"}
try:
cur = agv.request("/api/map/get_current_map")["results"]
if cur.get("map_name") == name:
return {"ok": True, "name": name, "deleted": False, "note": "the base uses this map now: it stays"}
v = rosbridge.call_service("/water_map_manager/map_service",
{"cmd": "delete_map", "message": json.dumps({"mapName": name, "floors": [floor]})},
timeout=10)
except Exception as e:
return {"ok": True, "name": name, "deleted": False, "note": f"the base did not delete it: {e}"}
if not v.get("success"):
return {"ok": True, "name": name, "deleted": False, "note": f"the base did not delete it: {v.get('message')}"}
return {"ok": True, "name": name, "deleted": True}
2026-10-21 15:19:07 +09:00
@app.post("/agv/go_point", tags=["base"], summary="Drive to a point on the map (x, y in m, theta in rad)")
def go_point(body: PointBody):
if assistant_pids():
send_to_assistant("go_point", point=[body.x, body.y, body.theta])
return {"ok": True, "by": "assistant"}
held_to_look()
2026-10-21 15:19:07 +09:00
part(fetch_head_ahead)
ok, msg = agv.go_point(body.x, body.y, body.theta)
if not ok:
raise HTTPException(502, f"AGV refused: {msg}")
2026-10-21 15:19:07 +09:00
return {"ok": True}
2026-11-18 18:37:10 +09:00
@app.get("/arm/joints", tags=["arm"], summary="Joints (deg) only: one controller read (~10 ms), for a live 3D arm "
"(the Lumi app asks it 5 times a second)")
def arm_joints():
try:
d = arm.cmd("get_data")
except (ConnectionError, OSError) as e:
raise HTTPException(502, f"arm controller: {e}")
return {"joints": [round(v, 2) for v in d.get("joint_actual_position", [])]}
2026-10-21 15:19:07 +09:00
@app.get("/arm/state", tags=["arm"], summary="Joints (deg), TCP (mm, deg), power, enable, program")
def arm_state():
d = arm.cmd("get_data")
st = arm.cmd("get_robot_state")
return {"joints": [round(v, 2) for v in d.get("joint_actual_position", [])],
"tcp": [round(v, 1) for v in d.get("actual_position", [])],
"power": bool(st.get("power")), "enable": bool(st.get("enable")),
"program": arm.program_state(), "loaded": arm.cmd("get_loaded_program").get("programName")}
@app.post("/arm/power", tags=["arm"], summary="Arm power on / off")
def arm_power(body: OnBody):
robot_free(manual=True)
return arm.cmd("power_on" if body.on else "power_off")
@app.post("/arm/enable", tags=["arm"], summary="Arm servo enable / disable")
def arm_enable(body: OnBody):
robot_free(manual=True)
return arm.cmd("enable_robot" if body.on else "disable_robot")
@app.post("/body/enable", tags=["body"], summary="Enable / disable the lift, waist and head (all four joints)")
def body_enable(body: OnBody):
robot_free(manual=True)
return {"enabled": head.set_enabled(body.on)}
@app.post("/arm/run", tags=["arm"], summary="Run a Cobo π program (.jks) once, only from look; returns at once")
2026-10-21 15:19:07 +09:00
def arm_run(body: ProgramBody):
robot_free(manual=True)
2026-10-21 15:19:07 +09:00
if not arm.ready():
raise HTTPException(409, "arm not ready: power/enable off, or a program is running")
try:
arm_route.start_program(body.program)
except arm_route.RouteError as e:
raise HTTPException(409, e.args[0])
2026-10-21 15:19:07 +09:00
except RuntimeError as e:
raise HTTPException(400, str(e))
return {"ok": True, "program": body.program}
class PoseBody(BaseModel):
name: str = Field(examples=["look"], description="a pose of the pose graph (manipulation/arm_route.py)")
speed: str = Field(arm_route.SPEED, description="slow / normal / route (empty hand; holding: always slow)")
2026-10-21 15:19:07 +09:00
class LineBody(BaseModel):
dx: float = 0.0
dy: float = 0.0
dz: float = Field(0.0, examples=[30.0], description="mm, arm base frame (z up); orientation is kept")
speed: str = "slow"
class NameBody(BaseModel):
name: str = Field(examples=["ready"])
def _motion(fn, *args, **kw):
robot_free(manual=True)
try:
return {"ok": True, "joints": fn(*args, **kw)}
except motion.MotionError as e:
raise HTTPException(409, str(e))
2026-11-19 16:33:17 +09:00
class SpeedBody(BaseModel):
percent: float = Field(examples=[80], description="% of every arm speed as tuned (100)")
def _speed_reply():
lo, hi = motion.SPEED_RANGE
return {"percent": motion.speed_percent(), "min": lo, "max": hi}
@app.get("/arm/speed", tags=["arm"], summary="The arm speed %: every arm move (poses, wave, picks, jog) runs at it")
def arm_speed():
return _speed_reply()
@app.post("/arm/speed", tags=["arm"], summary="Set the arm speed % (kept over restarts)")
def arm_speed_set(body: SpeedBody):
try:
motion.set_speed_percent(body.percent)
except ValueError as e:
raise HTTPException(400, str(e))
return _speed_reply()
@app.get("/arm/poses", tags=["arm"], summary="The poses the arm can go to (deg): the pose graph's and the saved ones")
2026-10-21 15:19:07 +09:00
def arm_poses():
2026-11-19 16:33:17 +09:00
return {**arm_route.graph(), **motion.saved_poses()}
@app.get("/arm/poses/saved", tags=["arm"], summary="Only the poses saved from the app (deg)")
def arm_poses_saved():
return motion.saved_poses()
@app.delete("/arm/poses/{name}", tags=["arm"], summary="Delete a pose saved from the app")
def arm_pose_delete(name: str):
if name in motion.poses():
raise HTTPException(409, f"{name} is one of Lumi's own poses")
try:
motion.delete_pose(name)
except KeyError:
raise HTTPException(404, f"no saved pose {name}")
return {"ok": True}
2026-10-21 15:19:07 +09:00
@app.post("/arm/pose", tags=["arm"], summary="Go to a named pose along the pose graph (every joint move checked first; "
"returns when there)")
2026-10-21 15:19:07 +09:00
def arm_pose(body: PoseBody):
if body.speed not in motion.JOINT_SPEED:
raise HTTPException(400, f"speed: {', '.join(motion.JOINT_SPEED)}")
2026-11-19 16:33:17 +09:00
saved = body.name in motion.saved_poses()
if body.name not in arm_route.graph() and not saved:
2026-10-21 15:19:07 +09:00
raise HTTPException(404, f"no pose {body.name}")
robot_free(manual=True)
_posing.set()
try:
2026-11-19 16:33:17 +09:00
holding = gripper.state()["holding"]
route = (arm_route.goto_saved(body.name, holding) if saved
else arm_route.goto(body.name, holding, speed=body.speed))
return {"ok": True, "route": route,
"joints": motion.joints()}
except arm_route.RouteError as e:
raise HTTPException(409, e.args[0])
except motion.MotionError as e:
raise HTTPException(409, str(e))
finally:
_posing.clear()
2026-10-21 15:19:07 +09:00
@app.post("/arm/line", tags=["arm"], summary="Straight TCP move by dx / dy / dz mm (IK-checked first)")
def arm_line(body: LineBody):
if body.speed not in motion.LINEAR_SPEED:
raise HTTPException(400, f"speed: {', '.join(motion.LINEAR_SPEED)}")
return _motion(motion.move_linear, delta=[body.dx, body.dy, body.dz], speed=body.speed)
2026-11-19 16:33:17 +09:00
@app.post("/arm/teach", tags=["arm"], summary="Save the arm's current joints as a new pose (not one of Lumi's own)")
2026-10-21 15:19:07 +09:00
def arm_teach(body: NameBody):
2026-11-19 16:33:17 +09:00
name = body.name.strip()
if not re.fullmatch(rf"[A-Za-z0-9_-]{{1,{motion.SAVED_NAME_MAX}}}", name):
raise HTTPException(400, f"name: 1 to {motion.SAVED_NAME_MAX} letters, digits, _ or -")
if name in motion.poses():
raise HTTPException(409, f"{name} is one of Lumi's own poses. Choose another name.")
try:
return {"ok": True, "name": name, "joints": motion.save_pose(name)}
except motion.MotionError as e:
raise HTTPException(409, str(e))
2026-10-21 15:19:07 +09:00
@app.get("/objects", tags=["objects"],
summary="Objects the torso camera sees: class, colour, centre / top / width / height in the arm base frame (mm)")
def objects_seen():
camview.want(objects.CAMERA)
return objects.latest()
@app.get("/gripper/state", tags=["gripper"], summary="Open / closed / holding, finger sensor, raw tool I/O")
def gripper_state():
return gripper.state()
@app.post("/gripper/open", tags=["gripper"], summary="Open the gripper; returns the state after the stroke (~1.5 s)")
def gripper_open():
robot_free(manual=True)
return gripper.open_()
@app.post("/gripper/close", tags=["gripper"], summary="Close the gripper (keep hands away); returns the state after")
def gripper_close():
robot_free(manual=True)
return gripper.close()
# ---------- skills: pick and place (manipulation/skills.py) ----------
class ObjectBody(BaseModel):
object: str = Field("cup", description="COCO class name the camera sees, e.g. cup, bottle")
colour: str | None = Field(None, examples=["white"], description="only an object of this colour")
class MoveBody(ObjectBody):
x: float | None = Field(None, description="place spot, mm in the arm base frame; empty = a free spot nearby")
y: float | None = None
class PlaceBody(BaseModel):
back: bool = Field(False, description="where it was picked; otherwise a free spot nearby")
x: float | None = Field(None, description="or this spot, mm in the arm base frame")
y: float | None = None
_skill = {"thread": None, "state": {"status": "idle"}}
def _run_skill(name, fn, *args, **kw):
"""Run a skill in the background (it takes up to a minute); /skills/state shows how it goes, STOP ends it."""
robot_free(manual=True)
if _skill["thread"] and _skill["thread"].is_alive():
raise HTTPException(409, f"{_skill['state']['skill']} is still running")
st = _skill["state"] = {"skill": name, "status": "running", "since": time.time()}
def run():
try:
st.update(status="done", result=fn(*args, **kw))
except skills.SkillError as e:
st.update(status="refused", reason=e.args[0])
2026-10-21 15:19:07 +09:00
except motion.MotionError as e:
st.update(status="stopped", reason=str(e))
except Exception as e:
st.update(status="failed", reason=repr(e))
st["took_s"] = round(time.time() - st["since"], 1)
_skill["thread"] = threading.Thread(target=run, daemon=True)
_skill["thread"].start()
return {"ok": True, "skill": name}
@app.post("/skills/plan", tags=["skills"], summary="Dry run of moving an object: what is seen, the place spot, "
"every waypoint with IK joints. Nothing moves")
def skill_plan(body: MoveBody):
seen = skills.look()
try:
obj = skills.find(body.object, body.colour, seen)
xy, rows = skills.plan_move(obj, (body.x, body.y) if body.x is not None else None, seen)
except skills.SkillError as e:
return {"ok": False, "reason": str(e), "seen": seen}
return {"ok": True, "object": obj, "place": xy, "seen": seen,
"waypoints": [{"name": n, "flange": [round(v, 1) for v in pose], "joints": [round(v, 1) for v in j]}
for n, pose, j, _ in rows]}
@app.post("/skills/move", tags=["skills"], summary="Pick the object up and put it at x, y or a free spot nearby; "
"returns at once, watch /skills/state")
def skill_move(body: MoveBody):
to = (body.x, body.y) if body.x is not None and body.y is not None else None
return _run_skill("move", skills.move_object, body.object, body.colour, to)
@app.post("/skills/pick", tags=["skills"], summary="Pick the object up and hold it 3 cm above the table; returns at once")
def skill_pick(body: ObjectBody):
return _run_skill("pick", skills.pick, body.object, body.colour)
@app.post("/skills/place", tags=["skills"], summary="Put down what /skills/pick holds; returns at once")
def skill_place(body: PlaceBody):
if body.x is not None and body.y is not None:
return _run_skill("place", skills.place, body.x, body.y)
return _run_skill("place", skills.put_down, body.back)
@app.get("/skills/state", tags=["skills"], summary="The last skill: running / done / refused / stopped, reason, log")
def skill_state():
return {**_skill["state"], "log": list(skills.LOG)[-12:]}
# ---------- fetch tasks: bring an object from one place to another (tasks/fetch.py, docs/16) ----------
class TaskBody(BaseModel):
object: str = Field(examples=["apple"], description="cup, bottle, apple, orange, banana")
colour: str | None = Field(None, examples=["red"], description="only an object of this colour; empty = any")
source: str | dict = Field("here", examples=[{"marker": "p1"}],
description='"here", {"marker": name} or {"x", "y" m, "theta" rad} in the map frame')
dest: str | dict = Field(examples=[{"marker": "home"}], description="same forms as source")
finish: str = Field("hold", examples=["hold"], description="hold (wait for give / place) or place on the table")
prefer: str | None = Field(None, examples=["small"], description="which of several: small, big, near, far, left, right")
SWITCHES_OFF = "Switch on Greeter or Patrol first."
WELCOME_OFF_CHARGER = "Welcome works only on the charger." # owner, 2026-11-16: it is the home mode
BASE_OFF = "I can't drive or turn my waist right now. Switch on Patrol for that." # lumi.BASE_OFF_SAY, as by voice
def _switches(base):
"""Every task the dashboard starts obeys the switches as voice does: nothing with both off, the base or the waist
(`base`: a drive or a turn in it) only with Patrol on; with Greeter only a task stays in place (fetch.stay_put).
STOP, pause, jog and the manual buttons are not asked here."""
m = read_modes()
if not (m["greeter"] or m["patrol"]):
raise HTTPException(409, SWITCHES_OFF)
if base and not m["patrol"]:
raise HTTPException(409, BASE_OFF)
from tasks import fetch
fetch.stay_put = not m["patrol"]
def _drives(steps):
from assistant import lumi
return bool({s.get("do") for s in steps} & lumi.DRIVE_STEPS)
def _plan_drives(r):
"""A /tasks/parse result drives or turns the base / waist."""
a, task = r.get("action"), r.get("task") or {}
return a == "carry" or a == "steps" and _drives(r["steps"]) or r.get("base", False) or \
a == "fetch" and any(task.get(k) not in (None, "here") for k in ("source", "dest"))
2026-10-21 15:19:07 +09:00
def _fetch_call(name, cmd, *args, **fields):
"""start / give / place: the assistant does it while it runs (it owns the robot), else the runner here."""
from tasks import fetch
if assistant_pids():
send_to_assistant(cmd, **fields)
return {"ok": True, "by": "assistant"}
try:
getattr(fetch, name)(*args)
except fetch.FetchError as e:
raise HTTPException(409, str(e))
return {"ok": True, "by": "api"}
def _task_problems(task):
"""fetch.validate plus: a map point must be a place the base can stand on."""
from tasks import fetch
from robot import nav
problems = fetch.validate(task, agv.markers())
for key, what in (("source", "take it from"), ("dest", "bring it to")):
p = task.get(key)
if isinstance(p, dict) and "x" in p and not part(lambda: nav.reachable(p["x"], p["y"])) is True:
problems.append(f"I can't drive to the point chosen to {what}: pick a free spot on the map.")
return problems
@app.post("/tasks/describe", tags=["tasks"], summary="The task as a sentence and what is wrong with it. Nothing moves")
def task_describe(body: TaskBody):
from tasks import fetch
task = body.model_dump()
return {"sentence": fetch.describe(task, "en"), "problems": _task_problems(task)}
class ParseBody(BaseModel):
text: str = Field(examples=["bring the red apple from p1 to home"], description="the command in English or Korean")
source: str | dict | None = Field(None, description="from the dialog, used when the text names no place to take it from")
dest: str | dict | None = Field(None, description="from the dialog, used when the text names no place to bring it to")
llm: bool = Field(False, description="words the rules leave are read by the LLM as by voice (Enter in the dialog; "
"not while typing)")
def _talk(sentence, problems=(), kind="talk"):
"""What voice would only answer (a question, talk, a refusal): shown, nothing to start."""
return {"action": None, "task": None, "talk": kind, "sentence": sentence, "problems": list(problems), "read_by": "rules"}
def _answer(text, sentence, kind="talk", read_by="rules"):
"""What voice answers out loud (a question, seeing, the status, a song, a voice setting, "more" / "again" with
the assistant's own last command): Start hands the words to the assistant, as if heard (/tasks/command)."""
return {"action": "command", "text": text, "talk": kind, "sentence": sentence, "problems": [], "read_by": read_by}
def _rule_steps(rule):
"""A keyword command that the mission runner does the same way as voice: its steps, else None (look, lift, wave,
come, follow, quiet need the assistant: /tasks/command)."""
a, t = rule
d, _, n = (t or "").partition(" ")
if a == "go_to":
return [{"do": "go", "to": t}]
if a == "move" and d in ("forward", "back", "left", "right"):
return [{"do": "move", "dir": d, "m": float(n or 1)}]
if a == "turn":
return [{"do": "turn", "deg": 180.0 if d == "around" else (1 if d == "left" else -1) * float(n or 90)}]
if a == "arm":
return [{"do": "arm", "pose": t}]
if a == "pick":
w = t.split()
return [{"do": "pick", "object": w[-1], "colour": w[0] if len(w) > 1 else None}]
return None
2026-10-21 15:19:07 +09:00
def _said(kind, words, what):
2026-10-21 15:19:07 +09:00
from assistant import brain, steps
if kind == "steps":
return steps.describe(what).rstrip(".")
if kind == "talk":
return f"answer \u201c{words}\u201d"
a, t = what
return {"look": f"look {t}", "lift": f"lift {t}", "wave": "wave", "come": "come to me and give it to you" if t == "give" else "come to me", "come_back": "go back",
"follow": "follow me", "go_to": f"go to {brain.place_said(t)}", "arm": f"arm {t}",
"quiet": "be quiet", "waist": f"turn my waist {t}"}.get(a, f"{a} {t}".strip())
@app.post("/tasks/parse", tags=["tasks"], summary="A typed command (English or Korean) read exactly as by voice "
"(lumi.route): a mission, a fetch, a command or chain for the assistant, or what Lumi would only answer. "
"Nothing moves")
def task_parse(body: ParseBody):
from assistant import brain, driving, lumi, seeing, steps
2026-10-21 15:19:07 +09:00
from tasks import fetch
markers = agv.markers()
text = body.text.strip()
lang = "ko" if brain.HANGUL.search(text) else "en"
held = bool(fetch.check_hand()) # the camera sees the hand; a stale "holding" is forgotten
if not text:
return _held_parse(body, markers) if held else _talk("–")
if lumi.FOREIGN_SCRIPT.search(text):
return _talk("–", ["Please write the command in English or Korean."])
from assistant import voice_words
voice = voice_words.read(text, "") # Lumi.voice_setting comes first, as by voice
if voice:
return _answer(text, {("volume", 1): "Speak louder.", ("volume", -1): "Speak quieter.",
("speed", 1): "Speak faster.", ("speed", -1): "Speak slower."}.get(voice, "Voice setting."),
"voice")
fixed = brain.self_correct(text, markers) # "go to start, no, end": as by voice (lumi.answer)
if not fixed:
return _talk("–", ["Which one did you mean? Please write it again." if fixed is None else "Taken back: nothing to do."])
body = body.model_copy(update={"text": fixed})
drive = driving.read(brain._norm(fixed), None, False) # lumi.drive_words: speed, a distance asked or refused
if drive == ("ask", ""): # "more", "again", "한 번 더": the assistant's last command
return _answer(fixed, "Again.", "again")
if drive and drive[0] in ("refuse", "ask"):
d, _, n = drive[1].partition(" ")
return _talk(driving.say_refused(d, float(n), "en") if drive[0] == "refuse" else driving.say_ask(drive[1], "en"))
if drive and drive[0] == "speed":
return {"action": "command", "text": fixed, "sentence": "Faster." if drive[1] > 0 else "Slower.", "problems": [],
"read_by": "rules"}
if lumi.NAME_ONLY.match(fixed):
return _talk("Yes?")
seen = lambda x: "seeing" if seeing.answer(x, frames=[]) else None # no camera here: whether it is one
kind, data = lumi.route(fixed, markers, brain.Brain(), held, seen=seen)
if kind == "stop":
return {"action": "command", "text": fixed, "sentence": "Stop.", "problems": [], "read_by": "rules"}
if kind == "detour": # after a blocked drive (assistant/detour.py): the assistant does it
from assistant import detour
return {"action": "command", "text": fixed, "sentence": detour.SAY[data][0], "problems": [], "read_by": "rules",
"base": True}
if kind == "chain":
base = any(k == "steps" and _drives(x) or k == "quick" and x[0] in lumi.BASE_ACTIONS for k, _, x in data)
return {"action": "command", "text": fixed, "parts": [[k, w] for k, w, _ in data], "problems": [], "read_by": "rules",
"base": base,
"sentence": ", then ".join(_said(*p) for p in data).capitalize() + "."}
if kind == "hand":
(hand, _) = data
if hand[0] == "receive" and not held:
got = [{"do": "receive", "object": hand[1], "from_hand": True}]
return {"action": "steps", "steps": got, "lang": lang, "sender": None, "read_by": "rules", **_steps_said(got, markers)}
if hand[0] in ("give", "place"): # voice's reading of the hand (brain.hand_request), not a second one
return _held_parse(body, markers, hand[0]) if held else _talk("–", ["My hand is empty, I'm not holding anything."])
return _talk(hand[1][0] if hand[0] == "refuse" else "–", kind="refuse")
if kind == "mission":
got, unread, by = data
if unread:
problem = brain.place_problem(" ".join(unread), markers) # "go to p12", "go to booth" (two)
return _talk("–", [problem[0] if problem else f"I didn't understand: {', '.join(unread)}"])
return {"action": "steps", "steps": got, "lang": lang, "sender": steps.sender(fixed), "read_by": by,
**_steps_said(got, markers)}
if not held and (lumi.empty_hand_request(fixed) or kind is None and brain.place_on(fixed) and
not brain._mentions(fixed, markers).get("object")): # as by voice: "put it on the table" with
# nothing held (the LLM reads a place)
return _talk("–", ["My hand is empty, I'm not holding anything."])
if kind == "quick" and data[0] == "fetch":
return _fetch_parse(body, markers)
if kind == "quick" and data[0] == "put":
return _held_parse(body, markers, "place") if held else _talk("–", ["My hand is empty, I'm not holding anything."])
if kind == "quick" and data[0] in ("weather", "search"):
return _answer(fixed, "Look it up and answer.", "lookup")
if kind == "quick":
if held and data[0] == "go_to":
return _held_parse(body, markers) # holding: a carry there
got = _rule_steps(data)
prefer = data[0] == "pick" and got and brain.pick_prefer(fixed)[0]
if prefer:
got[0]["prefer"] = prefer # "왼쪽 컵 집어", "the smaller cup": which of several (fetch picks it)
if got:
return {"action": "steps", "steps": got, "lang": lang, "sender": None, "read_by": "rules",
**_steps_said(got, markers)}
return {"action": "command", "text": fixed, "sentence": _said("quick", fixed, data).capitalize() + ".",
"problems": [], "read_by": "rules", "base": data[0] in lumi.BASE_ACTIONS, "rule": list(data)}
problem = brain.place_problem(fixed, markers)
if problem: # quick_command says it: "I don't have a place called p12"
return _talk(problem[0], kind="refuse")
if held and kind is None and brain.held_carry(fixed, markers) and not brain.ARM_TALK.search(fixed) and \
not brain.to_someone_else(fixed): # "p5로 가져가": a carry there. Nothing else the rules left is done
return _held_parse(body, markers) # with the hand here: as by voice, the LLM reads it (no motion)
if kind is None and body.llm: # the rules leave it: the LLM, one call, as by voice
gen = brain.Brain().respond_stream(fixed, markers)
head = next(gen)
first = next(gen, "") or ""
gen.close()
rule = (head["action"], head["target"])
if rule[0] == "fetch" and brain._mentions(fixed, markers).get("object"):
return _fetch_parse(body, markers)
got = _rule_steps(rule) if rule[0] in ("go_to", "move", "turn", "arm", "pick") else None
if got:
return {"action": "steps", "steps": got, "lang": lang, "sender": None, "read_by": "llm",
**_steps_said(got, markers)}
if rule[0] in ("look", "lift", "wave", "come", "follow", "come_back", "quiet"):
return {"action": "command", "text": fixed, "sentence": first or "–", "problems": [], "read_by": "llm",
"base": rule[0] in lumi.BASE_ACTIONS}
return _answer(fixed, first or "Answer.", "talk", "llm")
return _answer(fixed, {"seeing": "Say what I see.", "status": "Say what I'm doing.", "end": "Say goodbye.",
"sing": "Sing.", "correction": "Correct the last command."}.get(kind, "Answer."), kind or "talk")
def _fetch_parse(body, markers):
"""A fetch really read (an object named): the dialog's object / colour / place / finish choices."""
from assistant import brain
from tasks import fetch
if fetch.check_hand():
2026-10-21 15:19:07 +09:00
return _held_parse(body, markers)
if not brain._mentions(body.text, markers).get("object"): # no object named: never a fetch (nor an LLM guess)
return _talk("–", [f"I didn't understand: {body.text.strip()}"])
fields, read_by = brain.fetch_from_text(body.text, markers)
2026-10-21 15:19:07 +09:00
task = {"object": fields.get("object"), "colour": fields.get("colour"),
"source": fields.get("source") or body.source or "here", "dest": fields.get("dest") or body.dest,
"finish": fields.get("finish", "hold"), **({"prefer": fields["prefer"]} if fields.get("prefer") else {})}
problems = [] if task["object"] else ["Which object? I know cup, bottle, apple, orange and banana."]
problems += [x for x in _task_problems(task) if x not in problems]
if read_by == "other": # not English or Korean: nothing else is worth saying
problems = ["Please write the command in English or Korean."]
return {"action": "fetch", "task": task, "sentence": fetch.describe(task, "en"), "problems": problems,
"read_by": read_by, "from_text": sorted(fields), "choices": _choices()}
class CommandBody(BaseModel):
text: str = Field(description="a command /tasks/parse read as action \"command\"")
@app.post("/tasks/command", tags=["tasks"], summary="Do a typed command the way voice does it (the assistant hears "
"it): look, lift, wave, come, follow, several parts in a row")
def task_command(body: CommandBody):
r = task_parse(ParseBody(text=body.text)) # read again here (rules), never the client's word for it
if r.get("sentence") == "Stop." and not assistant_pids():
return task_stop() # "stop" never reads the switches
if r.get("sentence") != "Stop.":
_switches(_plan_drives(r))
if not assistant_pids():
raise HTTPException(409, SWITCHES_OFF)
send_to_assistant("heard", text=body.text)
return {"ok": True, "by": "assistant"}
2026-10-21 15:19:07 +09:00
def _steps_said(got, markers):
from assistant import steps
from tasks import fetch
problems = steps.check(got, bool(fetch.state().get("holding")), markers) # read only: the runner may be in
try: # the assistant's process
sentence = steps.describe(got)
except (KeyError, TypeError, IndexError, AttributeError):
sentence = "–"
return {"sentence": sentence, "problems": problems}
class StepsBody(BaseModel):
steps: list[dict] = Field(examples=[[{"do": "pick", "object": "cup", "colour": None},
{"do": "move", "dir": "right", "m": 1.0}, {"do": "place", "on": None}]],
description="the steps as /tasks/parse read them (docs/17)")
lang: str = Field("en", description="language Lumi speaks in while running it: en or ko")
sender: str | None = Field(None, description="who sends it (from /tasks/parse): may change or cancel it on the way")
@app.post("/tasks/steps/describe", tags=["tasks"], summary="Steps as a sentence and what is wrong with them. Nothing moves")
def steps_describe(body: StepsBody):
return _steps_said(body.steps, agv.markers())
@app.post("/tasks/steps", tags=["tasks"], summary="Start a mission: the steps in order; returns at once, watch /tasks/state")
def steps_run(body: StepsBody):
_switches(_drives(body.steps))
2026-10-21 15:19:07 +09:00
if assistant_pids():
send_to_assistant("fetch_steps", steps=body.steps, sender=body.sender)
return {"ok": True, "by": "assistant"}
from audio import mouth
from tasks import fetch
try:
fetch.run_steps(body.steps, say=lambda en, ko: mouth.say(ko if body.lang == "ko" else en), sender=body.sender)
except fetch.FetchError as e:
raise HTTPException(409, str(e))
return {"ok": True, "by": "api"}
def _choices():
"""What the dialog may change by hand after reading a command."""
from tasks import fetch
return {"object": list(fetch.PICKABLE), "colour": list(fetch.COLOURS), "finish": list(fetch.FINISH),
"then": [t for t in fetch.THEN if t]}
def _held_parse(body, markers, said=None):
2026-10-21 15:19:07 +09:00
"""A command while something is held: what to do with it, read by the rules only (fast; the object named in it is
the held one, so "give me the cup" is a give, not a new fetch). A marker named anywhere in the text is where to
bring it, else the dialog's To; then put it on a table, hand it over or keep holding it. said: what voice's reader
(lumi.route: the hand, the put rule) already made of the words, "give" or "place"."""
from assistant import brain, steps
2026-10-21 15:19:07 +09:00
from tasks import fetch
held, text = fetch.held_name(), brain.give_clause(body.text) # not where the person it is for goes
m, t = brain._mentions(text, markers), brain._norm(text, markers) # "booth 3" is the map's booth_3
2026-10-21 15:19:07 +09:00
if isinstance(m.get("source"), dict) and not brain.held_command(text): # "take the bottle from p2": a new fetch
return {"action": None, "task": None, "sentence": "–", "problems": [
f"I'm holding {held}: give it to you, put it on a table, or say where to bring it first."]}
named = [brain._as_place(brain._resolve(x, markers)) for x in re.finditer(brain._place_re(markers), t)]
named = [p for p in named if isinstance(p, dict)]
dest = named[0] if named else (body.dest if body.dest not in (None, "here") else None)
on = brain.place_on(text) # "on the orange chair": what to put it on
then = said or ("place" if on else brain.held_command(text) or ("place" if m.get("finish") == "place" else None))
2026-10-21 15:19:07 +09:00
if then == "give" and named and not re.search(r"\b(give|hand)\b|줘|주세요|건네", t):
then = None # "bring it to p2" is a carry, not a hand-over
table = "dining table" if re.search(r"\bdin+(?:n|i)?ing\b|\bdinner table\b", t) else "table" # as it was said
which = {"low": "lower", "high": "higher", "small": "smaller", "big": "bigger", "far": "farther"}.get(
(on or {}).get("prefer")) # "the lower one": which of several
on_words = " ".join(w for w in (which, on.get("colour"), " or ".join(n.replace("dining table", table) for n in
[on["name"]] + on.get("alts", []))) if w) if on else "table"
side = steps._side(t) if then == "place" else None # "왼쪽 테이블에 놔", "put it on the right side": the mission's
if dest is None and side: # place step turns to that side first (fetch.place does not)
got = [{"do": "place", "on": {"name": "dining table", "colour": None, **(on or {}), "side": side}}]
return {"action": "steps", "steps": got, "lang": "ko" if brain.HANGUL.search(text) else "en", "sender": None,
"read_by": "rules", **_steps_said(got, markers)}
2026-10-21 15:19:07 +09:00
if dest is None:
if then:
return {"action": then, "task": {"on": on}, "problems": [], "choices": _choices(),
"sentence": f"Hand {held} to you." if then == "give" else
f"Put {held} on the {on_words}." if on else f"Put {held} on the table near me."}
return {"action": None, "task": None, "sentence": "–", "problems": [
f"I'm holding {held}: say give it to me, put it on the table, or where to bring it."]}
problems = _task_problems({"dest": dest, "object": "cup", "finish": "hold"}) # only the dest can be wrong
return {"action": "carry", "task": {"dest": dest, "then": then, "on": on}, "problems": problems,
"choices": _choices(), "sentence": fetch.carry_sentence(dest, then).replace("Bring it", f"Bring {held}", 1)
.replace("on the table there", f"on the {on_words} there")}
@app.post("/tasks/fetch", tags=["tasks"], summary="Start a fetch: drive, pick, carry, hold or place; returns at once, "
"watch /tasks/state")
def task_fetch(body: TaskBody):
from tasks import fetch
task = body.model_dump()
problems = _task_problems(task)
if problems:
raise HTTPException(400, "; ".join(problems))
_switches(any(task.get(k) not in (None, "here") for k in ("source", "dest"))) # from / to a place drives
2026-10-21 15:19:07 +09:00
return _fetch_call("start", "fetch", task, task=task)
@app.post("/tasks/give", tags=["tasks"], summary="Hand the held object to the person in front")
def task_give():
_switches(False)
2026-10-21 15:19:07 +09:00
return _fetch_call("give", "fetch_give")
class TaskPlaceBody(BaseModel):
on: dict | None = Field(None, examples=[{"name": "chair", "colour": "orange"}],
description="put it on this instead of a table: camera class and colour (or null)")
@app.post("/tasks/place", tags=["tasks"], summary="Put the held object on the table in front")
def task_place(body: TaskPlaceBody | None = None):
on = body.on if body else None
_switches(False)
2026-10-21 15:19:07 +09:00
return _fetch_call("place", "fetch_place", None, on, on=on)
@app.post("/tasks/release", tags=["tasks"], summary="While giving: the person holds it, open the gripper")
def task_release():
if assistant_pids():
send_to_assistant("fetch_release")
return {"ok": True, "by": "assistant"}
from tasks import fetch
fetch.release_now()
return {"ok": True, "by": "api"}
class CarryBody(BaseModel):
dest: dict = Field(examples=[{"marker": "p1"}], description='{"marker": name} or {"x", "y", "theta"} (map)')
then: str | None = Field(None, description='there: null = keep holding it, "place" = on a table, "give" = hand it over')
on: dict | None = Field(None, description='put it on this instead of a table: {"name": camera class, "colour"}')
@app.post("/tasks/carry", tags=["tasks"], summary="Bring the held object to a place, then keep holding it, put it on "
"a table there or hand it over")
def task_carry(body: CarryBody):
_switches(True)
2026-10-21 15:19:07 +09:00
return _fetch_call("carry_to", "fetch_carry", body.dest, body.then, None, body.on, dest=body.dest, then=body.then,
on=body.on)
@app.post("/tasks/pause", tags=["tasks"], summary="Halt the task where it is (the base stops); /tasks/resume goes on")
def task_pause():
from tasks import fetch
if assistant_pids():
send_to_assistant("fetch_pause")
return {"ok": True, "by": "assistant"}
return {"ok": fetch.pause(), "by": "api"}
@app.post("/tasks/resume", tags=["tasks"], summary="Go on with a paused task")
def task_resume():
from tasks import fetch
if assistant_pids():
send_to_assistant("fetch_resume")
return {"ok": True, "by": "assistant"}
fetch.resume()
return {"ok": True, "by": "api"}
@app.post("/tasks/stop", tags=["tasks"], summary="Stop the fetch task, the base and the arm")
def task_stop():
if assistant_pids():
send_to_assistant("fetch_stop")
return {"task": part(_fetch_stop), "agv": part(agv.cancel), "arm": part(skills.cancel)}
class TeachBody(BaseModel):
name: str = Field(examples=["chair"], description="camera class of the thing (chair, couch, dining table, ...)")
colour: str = Field(examples=["yellow"], description="the colour to call it from now on")
@app.post("/objects/teach", tags=["objects"], summary="The nearest thing of this class seen now is this colour, from now "
"on and from any side (kept by its place on the map)")
def objects_teach(body: TeachBody):
from tasks import fetch
if body.colour not in fetch.COLOURS:
raise HTTPException(400, f"colour: {', '.join(fetch.COLOURS)}")
try:
o, w = fetch.teach_thing(body.name, body.colour)
except fetch.FetchError as e:
raise HTTPException(409, str(e))
return {"name": body.name, "colour": body.colour, "seen_at_mm": [round(o["x"]), round(o["y"])],
"camera_said": o.get("colour"), "map": [round(float(v), 3) for v in w]}
@app.get("/tasks/state", tags=["tasks"], summary="The fetch task: status, step, task, holding, log")
def task_state():
from tasks import fetch
return fetch.state()
class ModesBody(BaseModel):
greeter: bool | None = Field(None, description="standing: greet people who come close, talk, wake word")
patrol: bool | None = Field(None, description="driving anywhere: stop for people in the way, talk, drive on")
wave_greet: bool | None = Field(None, description="Wave: on the way wave at people (each once), wave back at people "
"who wave, keep alive; alone or with Greeter / Patrol")
welcome: bool | None = Field(None, description="Welcome: on the charger the hand up in wave_start, wave at people "
"who come into view, wave back, keep alive; alone or with the others")
2026-10-21 15:19:07 +09:00
@app.get("/assistant/modes", tags=["assistant"], summary="Greeter / patrol / wave greeting switches")
2026-10-21 15:19:07 +09:00
def modes_get():
return {**read_modes(), "running": bool(assistant_pids())}
@app.post("/assistant/modes", tags=["assistant"],
summary="Switch Greeter / Patrol / Wave / Welcome (lumi.py runs while any is on, stops when all are off)")
2026-10-21 15:19:07 +09:00
def modes_set(body: ModesBody):
if body.welcome and not _charging():
raise HTTPException(409, WELCOME_OFF_CHARGER)
2026-10-21 15:19:07 +09:00
m = {**read_modes(), **{k: v for k, v in body.model_dump().items() if v is not None}}
tmp = MODES_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(m))
os.replace(tmp, MODES_FILE)
calibrating = _calib_active()
if any_on(m) and not assistant_pids():
2026-10-21 15:19:07 +09:00
start_assistant()
elif not any_on(m) and assistant_pids() and not calibrating:
_bg(stop_when_lowered) # the hand down first; the reply does not wait for it
2026-10-21 15:19:07 +09:00
return {**m, "running": bool(assistant_pids())}
def _calib_active():
try:
c = json.loads(CALIB_FILE.read_text())
return c.get("state") == "collecting" and c.get("until", 0) > time.time()
except (FileNotFoundError, ValueError):
return False
@app.get("/assistant/status", tags=["assistant"], summary="Is the assistant running, stuck, failing? (Settings > Logs)")
def assistant_status():
pids = assistant_pids()
lines = tail(LUMI_LOG, 400)
errors = [l for l in lines if re.search(r"\b(error|failed|stuck|refused|cannot|traceback)\b", l, re.I)]
# (whole words only: "median_error_deg" in a calibration line is not an error)
last = lines[-1] if lines else ""
age = None
if pids:
try:
age = round(time.time() - LUMI_LOG.stat().st_mtime, 1)
except FileNotFoundError:
pass
started = None
if pids:
try:
started = round(time.time() - Path(f"/proc/{pids[0]}").stat().st_mtime)
except FileNotFoundError:
pass
stuck = any("MAIN LOOP STUCK" in l for l in lines[-30:])
return {"running": bool(pids), "pids": pids, "uptime_s": started, "log_age_s": age, "stuck": stuck,
"modes": read_modes(), "cameras": camview.status().get("cameras"), "camera_service": camview.service_pid(),
"errors": errors[-15:], "last_line": last, "console_tail": tail(CONSOLE_LOG, 25)}
class CalibBody(BaseModel):
on: bool = True
@app.post("/doa/calibrate", tags=["voice"], summary="Start / stop a 2-minute calibration of the voice direction")
def doa_calibrate(body: CalibBody):
if body.on and not assistant_pids():
start_assistant()
time.sleep(1.0)
CALIB_FILE.write_text(json.dumps({"state": "starting" if body.on else "stopped", "samples": 0,
"until": time.time() + 120 if body.on else 0, "time": time.time()}))
send_to_assistant("calibrate", on=body.on)
return {"ok": True}
@app.get("/doa/status", tags=["voice"], summary="Calibration progress and the current calibration")
def doa_status():
from audio import doa
try:
prog = json.loads(CALIB_FILE.read_text())
except (FileNotFoundError, ValueError):
prog = {"state": "idle", "samples": 0}
return {"progress": prog, "calibration": doa.load_calib()}
@app.post("/doa/reset", tags=["voice"], summary="Forget the voice-direction calibration and its samples")
def doa_reset():
from audio import doa
for f in (doa.CALIB, doa.SAMPLES):
f.unlink(missing_ok=True)
return {"ok": True}
def _supervise():
"""Keep lumi.py running while any switch is on (it can crash or be killed);
2026-10-21 15:19:07 +09:00
wait longer after each quick failure so a broken start does not loop."""
wait, last_start = 5.0, 0.0
while True:
time.sleep(5.0)
try:
m = read_modes()
if not any_on(m) or assistant_pids() or time.time() - last_start < wait:
2026-10-21 15:19:07 +09:00
if assistant_pids() and time.time() - last_start > 120:
wait = 5.0 # it has been running fine: reset the back-off
continue
with open(CONSOLE_LOG, "a") as f:
f.write(f"\n{time.strftime('%H:%M:%S')} supervisor: a switch is on but lumi.py is not running - starting it\n")
2026-10-21 15:19:07 +09:00
start_assistant()
last_start, wait = time.time(), min(wait * 2, 120.0)
except Exception:
pass
@app.get("/health", tags=["status"])
def health():
return {"ok": True}
def start_services():
"""Speech to text, knowledge search and the LLM, loaded now so the assistant and /ask answer at once."""
from assistant import brain, knowledge
from audio import ears
for name, start in (("whisper", ears.ensure_stt_server), ("embeddings", knowledge.ensure_embed_server),
("llm", brain.warm_up)):
try:
start()
print(f"{time.strftime('%H:%M:%S')} {name} ready", flush=True)
except Exception as e: # the API keeps working without it
print(f"{time.strftime('%H:%M:%S')} {name} failed: {e}", flush=True)
def _drive_log():
"""Every drive of the base in this log (robot/drive_log.py): start, on the way, standing still, the end."""
from robot import drive_log
drive_log.watch(lambda line: print(f"{time.strftime('%H:%M:%S')} {line}", flush=True))
if __name__ == "__main__":
camview.ensure_running() # the camera service owns both cameras
threading.Thread(target=start_services, daemon=True).start()
threading.Thread(target=_drive_log, daemon=True).start()
# the supervisor here, not on import: a test importing this module started real lumi.py processes (2026-10-28)
threading.Thread(target=_supervise, daemon=True).start()
wave_greet.start(lambda: read_modes()["wave_greet"],
lambda: not assistant_pids() and running_now() in (None, "wave_greet"),
lambda: modes_set(ModesBody(wave_greet=False, welcome=False)))
2026-10-21 15:19:07 +09:00
uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="warning")