Added map endpoints for the Lumi app

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 18:22:17 +09:00
co-authored by Claude Opus 5.5
parent ed2c6bdafd
commit de2fb71c81
5 changed files with 324 additions and 2 deletions
+102 -2
View File
@@ -38,6 +38,7 @@ from robot import motion
from vision import objects
from robot import head
from manipulation import arm_route
from robot import rosbridge
from manipulation import skills
from manipulation import wave
from tasks import wave_greet
@@ -726,6 +727,20 @@ class MapBody(BaseModel):
floor: int = 1
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)")
class MarkerName(BaseModel):
name: str
class OnBody(BaseModel):
on: bool
@@ -764,15 +779,31 @@ def map_info():
"maps": [{"name": n, "floors": f} for n, f in sorted(maps.items())]}
DARK_UNKNOWN, DARK_FREE, DARK_WALL = (10, 11, 13), (22, 26, 31), (232, 232, 232) # RGB, the Lumi app's look
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()
@app.get("/map/image", tags=["map"], summary="Map picture (PNG) from the base; default the current map")
def map_image(map_name: str | None = None, floor: int | None = None):
def map_image(map_name: str | None = None, floor: int | None = None, dark: bool = False):
if map_name is None:
cur = agv.request("/api/map/get_current_map")["results"]
map_name, floor = cur["map_name"], cur["floor"]
url = f"{AGV_WEB}/maps/{urllib.request.quote(map_name)}/{floor or 1}/map.png"
try:
with urllib.request.urlopen(url, timeout=10) as r:
return Response(r.read(), media_type="image/png", headers={"Cache-Control": "max-age=60"})
png = r.read()
return Response(_dark(png) if dark else png, media_type="image/png", headers={"Cache-Control": "max-age=60"})
except Exception as e:
raise HTTPException(502, f"map picture not available: {e}")
@@ -787,6 +818,75 @@ def map_switch(body: MapBody):
return {"ok": True, "reply": r}
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)
if body.x is None or body.y is None:
r = agv.request(f"/api/markers/insert?name={name}&type=0&num=1")
else:
r = agv.request(f"/api/markers/insert_by_pose?name={name}&x={body.x}&y={body.y}&theta={body.theta}&type=0")
agv.known_markers(fresh=True) # drives to it work at once
return {"ok": True, "reply": r}
@app.post("/map/marker/delete", tags=["map"], summary="Delete a marker (never the main dock)")
def marker_delete(body: MarkerName):
name = _marker_name(body.name)
if name == agv.dock_marker():
raise HTTPException(409, "The charger's marker stays: Lumi docks with it.")
r = agv.request(f"/api/markers/delete?name={name}")
agv.known_markers(fresh=True)
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()
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}
@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():
+30
View File
@@ -301,3 +301,33 @@ Commissioning checks:
4. Try the soft E-stop on and off.
5. Subscribe to `human_detection`, walk around the robot, log positions (shows whether leg tracking is enabled).
6. Create a marker, `/api/move?marker=...`, poll until `succeeded`.
## 6. The map from the Lumi app (lumi-wave `/map/*`)
The Lumi app's Map screen does what the web monitor's map page does, through lumi-wave (`api/server.py`, tag `map`).
Tests: `tests/test_map_edit.py`, `tests/test_rosbridge.py` (no robot needed).
| Endpoint | What it does | On the base |
|---|---|---|
| `GET /map/info` | current map, size, resolution, origin, markers with poses, all maps | `map/get_current_map`, `markers/query_list` |
| `GET /map/image?dark=true` | the map picture; `dark` recolours it for the app (unknown, free, wall) | map PNG |
| `POST /map/switch` | use another map (the base service restarts, about 15 s; relocalise after) | `map/set_current_map` |
| `POST /map/marker` | save a marker where Lumi stands, or at `x, y, theta` | `markers/insert`, `markers/insert_by_pose` |
| `POST /map/marker/delete` | delete a marker; the main dock is refused (409) | `markers/delete` |
| `POST /map/position` | position correction at `x, y, theta` (only while the base is free) | `position_adjust_by_pose` |
| `POST /map/position/marker` | Lumi stands at this marker: pose taken from it | `position_adjust?marker=` |
| `GET /map/scan` | what the lidar sees now, points `[x ahead, y left]` (m) around the base's centre | rosbridge `/scan` |
| `POST /agv/go_point` | drive to a point on the map | `move?location=` |
Marker names: letters, digits, `_` and `-`, at most 50 (`MARKER_NAME`).
**The lidar.** The base runs rosbridge on `ws://192.168.10.10:9090` (its own web pages use it). `robot/rosbridge.py` is a
small WebSocket client of our own (no extra package) that reads one message of a topic. `/scan` (frame `front_laser`)
has 683 rays over ±120°, 0.05 to 30 m; `/map/scan` keeps every second ray and moves them by `LASER_X` 0.126 m (the
lidar sits ahead of the centre, URDF `Radar_Link`). `/tf_static` did not answer through rosbridge, so the offset is
taken from the URDF.
**Position correction in the app** works like §2.4: POSITION ▾ → *Tap or drag on the map*. The scan is drawn once a
second in red at the pose the base believes and in purple at the new pose; arrows move the new pose 5 cm, turns 2°;
a tap or a drag on the map sets the place and heading. When the purple dots sit on the walls, SET POSITION. Or
*Lumi is at* → a marker.
+67
View File
@@ -0,0 +1,67 @@
"""Read one message of a ROS topic from the AGV base's rosbridge (WebSocket, ws://192.168.10.10:9090; its own web
pages use it). Only what the Lumi app's position correction needs: the lidar scan. A small WebSocket client of our
own (no extra package): one connection per read, subscribe, the first message, unsubscribe, close."""
import base64
import json
import os
import socket
import struct
HOST, PORT = "192.168.10.10", 9090
def client_frame(data):
"""A masked text frame (a client must mask what it sends)."""
mask = os.urandom(4)
n = len(data)
head = bytes([0x81]) + (bytes([0x80 | n]) if n < 126 else bytes([0x80 | 126]) + struct.pack(">H", n)
if n < 65536 else bytes([0x80 | 127]) + struct.pack(">Q", n))
return head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data))
def read_message(sock, buf):
"""One JSON message (its frames joined) from the server, and the bytes read past it."""
def need(k):
nonlocal buf
while len(buf) < k:
chunk = sock.recv(65536)
if not chunk:
raise ConnectionError("rosbridge closed the connection")
buf += chunk
data = b""
while True:
need(2)
fin, n, i = buf[0] & 0x80, buf[1] & 0x7F, 2
if n == 126:
need(4)
n, i = struct.unpack(">H", buf[2:4])[0], 4
elif n == 127:
need(10)
n, i = struct.unpack(">Q", buf[2:10])[0], 10
need(i + n)
data, buf = data + buf[i:i + n], buf[i + n:]
if fin:
return json.loads(data), buf
def read_once(topic, timeout=3.0):
"""The next message of `topic` (rosbridge's {"op": "publish", "msg": ...}); raises OSError when there is none."""
with socket.create_connection((HOST, PORT), timeout=timeout) as s:
key = base64.b64encode(os.urandom(16)).decode()
s.sendall((f"GET / HTTP/1.1\r\nHost: {HOST}:{PORT}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
f"Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n").encode())
head = b""
while b"\r\n\r\n" not in head:
chunk = s.recv(4096)
if not chunk:
raise ConnectionError("rosbridge did not answer the handshake")
head += chunk
if b" 101 " not in head.split(b"\r\n", 1)[0]:
raise ConnectionError(f"rosbridge refused: {head.split(b'\\r\\n', 1)[0]!r}")
buf = head.split(b"\r\n\r\n", 1)[1]
s.sendall(client_frame(json.dumps({"op": "subscribe", "topic": topic, "queue_length": 1}).encode()))
while True:
msg, buf = read_message(s, buf)
if msg.get("op") == "publish" and msg.get("topic", topic) == topic:
s.sendall(client_frame(json.dumps({"op": "unsubscribe", "topic": topic}).encode()))
return msg
+75
View File
@@ -0,0 +1,75 @@
"""Self-check of the map edits for the Lumi app (2026-11-16): save a marker where Lumi stands or at a tapped pose,
delete one (never the main dock), set Lumi's position on the map. Fake base, no robot: python tests/test_map_edit.py"""
import no_robot # noqa: F401 any connection to the robot fails the test
from fastapi import HTTPException
from api import server
sent = []
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
server.agv.dock_marker = lambda: "Home"
server.agv.known_markers = lambda fresh=False: sent.append("refresh") if fresh else None
server.robot_free = lambda manual=False: None
def refused(fn, *a, code=409):
try:
fn(*a)
except HTTPException as e:
return e.status_code == code
return False
# where Lumi stands, and at a tapped pose (an existing name is moved there)
server.marker_save(server.MarkerBody(name="door_1"))
assert sent == ["/api/markers/insert?name=door_1&type=0&num=1", "refresh"], sent
sent.clear()
server.marker_save(server.MarkerBody(name="p11", x=1.5, y=-2.25, theta=0.5))
assert sent == ["/api/markers/insert_by_pose?name=p11&x=1.5&y=-2.25&theta=0.5&type=0", "refresh"], sent
sent.clear()
for bad in ("", "a b", "x/y", "로비", "a" * 51): # the base takes letters, digits, _ and - only
assert refused(server.marker_save, server.MarkerBody(name=bad), code=422), bad
assert sent == [], sent
# delete; never the main dock (docking needs it)
server.marker_delete(server.MarkerName(name="door_1"))
assert sent == ["/api/markers/delete?name=door_1", "refresh"], sent
sent.clear()
assert refused(server.marker_delete, server.MarkerName(name="Home"))
assert sent == [], sent
# Lumi's position on the map (relocalise), only while nothing runs
server.map_position(server.PointBody(x=-1.2, y=0.05, theta=-0.04))
assert sent == ["/api/position_adjust_by_pose?x=-1.2&y=0.05&theta=-0.04"], sent
sent.clear()
server.robot_free = lambda manual=False: (_ for _ in ()).throw(HTTPException(409, server.BUSY_MSG))
assert refused(server.map_position, server.PointBody(x=0, y=0))
assert sent == []
# the map picture in the app's dark look: unknown almost black, free space dark, walls light (same size)
import cv2 # noqa: E402
import numpy as np # noqa: E402
pic = np.full((4, 6), 205, np.uint8) # unknown
pic[1, 1:5] = 255 # free
pic[2, 2] = 0 # a wall
png = cv2.imencode(".png", pic)[1].tobytes()
server.agv.request = lambda cmd, timeout=3.0: {"results": {"map_name": "m", "floor": 1}}
server.urllib.request.urlopen = lambda url, timeout=10: type("R", (), {"read": lambda s: png, "__enter__": lambda s: s,
"__exit__": lambda s, *a: False})()
out = cv2.imdecode(np.frombuffer(server.map_image(dark=True).body, np.uint8), cv2.IMREAD_COLOR)
assert out.shape == (4, 6, 3), out.shape
assert tuple(out[0, 0]) == server.DARK_UNKNOWN[::-1] and tuple(out[1, 1]) == server.DARK_FREE[::-1], (out[0, 0], out[1, 1])
assert tuple(out[2, 2]) == server.DARK_WALL[::-1], out[2, 2]
assert server.map_image().body == png # as the base draws it, unless asked
# Lumi stands at a marker: the base takes its pose from it (after a map switch, the quickest way)
sent.clear()
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
server.robot_free = lambda manual=False: None
server.map_position_marker(server.MarkerName(name="Home"))
assert sent == ["/api/position_adjust?marker=Home"], sent
assert refused(server.map_position_marker, server.MarkerName(name="a b"), code=422)
print("ok: map edits")
+50
View File
@@ -0,0 +1,50 @@
"""Self-check of reading the base's lidar for the Lumi app's position correction: the rosbridge WebSocket frames
(robot/rosbridge.py) and the scan as points around the base's centre (api/server.py /map/scan). Fake socket, no robot:
python tests/test_rosbridge.py"""
import json
import math
import struct
import no_robot # noqa: F401 any connection to the robot fails the test
from robot import rosbridge
from api import server
# a client frame is masked and carries the JSON; a server frame (unmasked, maybe split over reads) is read back
f = rosbridge.client_frame(b'{"op":"x"}')
assert f[0] == 0x81 and f[1] & 0x80 and len(f) == 2 + 4 + 10, f
mask, body = f[2:6], f[6:]
assert bytes(b ^ mask[i % 4] for i, b in enumerate(body)) == b'{"op":"x"}'
big = json.dumps({"msg": {"ranges": [1.0] * 300}}).encode()
server_frame = bytes([0x81, 126]) + struct.pack(">H", len(big)) + big
class Sock:
def __init__(self, data, step=50):
self.data, self.step = data, step
def recv(self, n):
out, self.data = self.data[:self.step], self.data[self.step:]
return out
msg, rest = rosbridge.read_message(Sock(server_frame + b"\x81\x02{}"), b"")
assert msg["msg"]["ranges"][0] == 1.0 and len(msg["msg"]["ranges"]) == 300, msg
assert rest == b"\x81\x02{}" or rest == b"", rest
# the scan as points (x ahead, y left, m) around the base's centre: the lidar sits LASER_X ahead of it
scan = {"angle_min": -math.pi / 2, "angle_increment": math.pi / 2, "range_min": 0.05, "range_max": 30.0,
"ranges": [1.0, 2.0, 1.0, None, 0.01, 50.0]}
pts = server.scan_points(scan, every=1)
assert len(pts) == 3, pts # None, too near and too far left out
assert pts[0] == [round(server.LASER_X, 3), -1.0], pts[0] # right of the lidar
assert pts[1] == [round(server.LASER_X + 2.0, 3), 0.0], pts[1] # ahead
assert pts[2] == [round(server.LASER_X, 3), 1.0], pts[2] # left
assert len(server.scan_points({**scan, "ranges": [1.0] * 6}, every=2)) == 3 # every 2nd
# /map/scan reads one message of the base's /scan
server.rosbridge.read_once = lambda topic, timeout=3.0: {"msg": scan} if topic == "/scan" else None
r = server.map_scan()
assert r["points"] == server.scan_points(scan) and r["frame"] == "base", r # every 2nd ray by default
print("ok: rosbridge and scan")