From 0a2d25e1d313cb89791256d892cb77eb302a87e3 Mon Sep 17 00:00:00 2001 From: Cutshion Date: Tue, 17 Nov 2026 18:33:14 +0900 Subject: [PATCH] Added mapping Co-Authored-By: Claude Opus 5.5 --- api/server.py | 191 +++++++++++++++++++++++++++++++++++++++++ docs/05_AGV_BASE.md | 30 +++++++ robot/rosbridge.py | 32 ++++++- tests/test_map_scan.py | 156 +++++++++++++++++++++++++++++++++ 4 files changed, 406 insertions(+), 3 deletions(-) create mode 100644 tests/test_map_scan.py diff --git a/api/server.py b/api/server.py index fa38288..3482a75 100644 --- a/api/server.py +++ b/api/server.py @@ -880,6 +880,7 @@ def map_image(map_name: str | None = None, floor: int | None = None, dark: bool @app.post("/map/switch", tags=["map"], summary="Use another map (the base service restarts; relocalise after)") def map_switch(body: MapBody): robot_free() + scan_free() 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 @@ -926,6 +927,7 @@ def marker_delete(body: MarkerName): @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() + scan_free() r = agv.request(f"/api/position_adjust_by_pose?x={body.x}&y={body.y}&theta={body.theta}") return {"ok": True, "reply": r} @@ -965,6 +967,195 @@ def map_position_marker(body: MarkerName): return {"ok": True, "reply": r} +# ---------- 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///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} + + @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(): diff --git a/docs/05_AGV_BASE.md b/docs/05_AGV_BASE.md index b54e5b7..37d0404 100644 --- a/docs/05_AGV_BASE.md +++ b/docs/05_AGV_BASE.md @@ -331,3 +331,33 @@ taken from the URDF. 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. + +## 7. Making a new map from the Lumi app (lumi-wave `/map/scan/*`) + +The base's map builder (§2.2, `http://192.168.10.10:8809/map-build/map.html?hotelid=&floor=1&map_type=v2`) is a +page over a small HTTP API (CherryPy) plus rosbridge. Read from its scripts (`map-build/js/src/Map.js`, 2026-11-17): + +| Step | The base's page | lumi-wave | +|---|---|---| +| Start | `GET :8809/map-build-api/start?hotelid=&floor=1&delta=&map_type=v2`; `delta` from rosparam `/map_build_tool/deltas` = `[0.02, 0.03, 0.05]` (small, middle, large map). The 9001 page's *Create Map* only opens this page | `POST /map/scan/start {name, size}` (size small by default) | +| State | `GET :8809/map-build-api/get_info` → `{mapbuilding, hotelid, floor, map_type, resolution, iscontinue}` | `GET /map/scan/state` | +| Live map | picture `:8809/maps///map-temp.png` (or `map-temp-mini.png`) once a second; its geometry from topic `/map_metadata` (`nav_msgs/MapMetaData`), matched by width and height (they come apart while the map grows) | `GET /map/scan/picture` (PNG as base64 in the dark look, with `width, height, resolution, origin_x, origin_y, exact`) | +| Pose | topic `/robot_pose` (`geometry_msgs/Pose`) | in `/map/scan/state` | +| Optimizing | topic `/optimizing_progress` (`std_msgs/Float32`, 0..1, v2 only): "suggested to save after optimization" | `progress` in `/map/scan/state` | +| Drive | keys publish `geometry_msgs/Twist` on `/ctrl_cmd_vel` (the TCP API's `joy_control` publishes there too, node `/water_tcp_socket`) | the app's joystick, `/jog` | +| Save | publishes `/web_operation` `{operation: "new_save"}` (only logged by `/log_manager`), then `GET :8809/map-build-api/stop`; the builder then sends `{"event": "new_save"}` on `/map_build_tool/map_event` | `POST /map/scan/save` | +| Cancel | none: a scan ends only by saving it | `POST /map/scan/cancel`: saves, then deletes it with `/water_map_manager/map_service` `delete_map` (message `{"mapName", "floors"}` as JSON), but only a map this API started under a new name and not the map in use; else it stays (`deleted: false`) | + +Other calls of the page, not used: continue scan (`start ...&iscontinue=true`), auto scan (topic `/map_explore/ctrl` +`on`, `off`, `jump`), loop closure range (`set_loop_closure_range?value=`), view distance (topic +`set_map_view_distance`; the page saves only at the full 150 m), `list_exist_hotels`, `list_status`, `list_all_status`. +The 9001 page's map list comes from `/water_map_manager/map_service` `get_local_map_list`. + +Rules in lumi-wave: a name has letters, digits and `_` (at most 36, the 9001 page's rule) and is not a map that exists; +start is refused while the assistant runs or a task or drive runs (`robot_free`), save and cancel while a task runs; +one scan at a time. While a scan this API started runs, `/map/switch` and `/map/position` answer 409 +(`/dev/shm/lumi_mapping.json`, checked with the base). After saving, the new map is in `/map/info` `maps`; switch to it +(`/map/switch`) and set the position. Test: `tests/test_map_scan.py` (no robot). + +Not tried live yet (2026-11-17): what `start` and `stop` do to the base's services and its current map, how long `stop` +takes, whether `joy_control` drives while scanning, and the `delete_map` message format. diff --git a/robot/rosbridge.py b/robot/rosbridge.py index 7581966..4a01687 100644 --- a/robot/rosbridge.py +++ b/robot/rosbridge.py @@ -1,11 +1,13 @@ -"""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 needs: the lidar scan for position correction and the map's no-go lines. A -small WebSocket client of our own (no extra package): one connection per read or service call, then close.""" +"""Read ROS topics from the AGV base's rosbridge (WebSocket, ws://192.168.10.10:9090; its own web pages use it). +Only what the Lumi app needs: the lidar scan for position correction, the map's no-go lines and a new map while it is +made (pose, map size, optimizing progress). A small WebSocket client of our own (no extra package): one connection +per read or service call, then close.""" import base64 import json import os import socket import struct +import time HOST, PORT = "192.168.10.10", 9090 @@ -89,3 +91,27 @@ def call_service(service, args, timeout=3.0): if not msg.get("result", False): raise RuntimeError(f"{service} failed: {msg.get('values')}") return msg.get("values") or {} + + +def read_many(topics, timeout=1.5): + """The next message of each topic, read on one connection: {topic: msg}. A topic that sends nothing within + `timeout` is left out (the map builder sends /optimizing_progress only while it optimizes).""" + s, buf = _connect(timeout) + got = {} + with s: + for t in topics: + s.sendall(client_frame(json.dumps({"op": "subscribe", "topic": t, "queue_length": 1}).encode())) + end = time.monotonic() + timeout + try: + while len(got) < len(topics): + left = end - time.monotonic() + if left <= 0: + break + s.settimeout(left) + msg, buf = read_message(s, buf) + t = msg.get("topic") + if msg.get("op") == "publish" and t in topics and t not in got: + got[t] = msg.get("msg") or {} + except TimeoutError: + pass + return got diff --git a/tests/test_map_scan.py b/tests/test_map_scan.py new file mode 100644 index 0000000..764d447 --- /dev/null +++ b/tests/test_map_scan.py @@ -0,0 +1,156 @@ +"""Self-check of making a new map from the Lumi app (2026-11-17, api/server.py /map/scan/*): start under a new name +(refused while busy, for a bad or taken name, or while a scan runs), the state with the pose and progress, the +growing picture matched to its geometry, save, and cancel (saved then deleted, only a map started here). Fake base, +map builder and rosbridge, no robot: python tests/test_map_scan.py""" +import base64 +import json +import tempfile +from pathlib import Path + +import cv2 +import numpy as np + +import no_robot # noqa: F401 any connection to the robot fails the test +from fastapi import HTTPException + +from api import server + +server.SCAN_FILE = Path(tempfile.mkdtemp()) / "lumi_mapping.json" # never the real /dev/shm file +gets, calls = [], [] +builder = {"mapbuilding": False, "hotelid": "", "floor": ""} +picture = cv2.imencode(".png", np.full((4, 6), 255, np.uint8))[1].tobytes() # 6 x 4 pixels, all free + + +def build_get(path, timeout=5.0): + gets.append(path) + if path.startswith("map-build-api/get_info"): + return json.dumps({"success": True, **builder}).encode() + if path.startswith("map-build-api/start"): + builder.update(mapbuilding=True, hotelid=path.split("hotelid=")[1].split("&")[0], floor="1", map_type="v2") + return b'{"success": true}' + if path == "map-build-api/stop": + builder.update(mapbuilding=False) + return b'{"success": true}' + if path.startswith("maps/"): + return picture + raise AssertionError(path) + + +current = {"map_name": "office", "floor": 1} +server._build_get = build_get +server.agv.request = lambda cmd, timeout=3.0: {"results": {"office": [1], "lab": [1]} if cmd == "/api/map/list" + else dict(current)} +delete_reply = {"success": True, "message": ""} + + +def call_service(service, args, timeout=3.0): + calls.append((service, args)) + if service == "/rosapi/get_param": + return {"value": '"[0.02,0.03,0.05]"'} + return delete_reply + + +meta = {"width": 6, "height": 4, "resolution": 0.05, "origin": {"position": {"x": -1.0, "y": -2.0, "z": 0}}} +server.rosbridge.call_service = call_service +server.rosbridge.read_once = lambda topic, timeout=3.0: {"op": "publish", "topic": topic, "msg": meta} +server.rosbridge.read_many = lambda topics, timeout=1.5: { + "/robot_pose": {"position": {"x": 1.0, "y": 2.0, "z": 0}, + "orientation": {"x": 0, "y": 0, "z": 0.7071068, "w": 0.7071068}}, + "/map_metadata": meta, "/optimizing_progress": {"data": 1.4}} +busy = {"assistant": False, "task": False} + + +def robot_free(manual=False): + if (manual and busy["task"]) or (not manual and busy["assistant"]): + raise HTTPException(409, "busy") + + +server.robot_free = robot_free + + +def refused(fn, *a, code=409): + try: + fn(*a) + except HTTPException as e: + return e.status_code == code + return False + + +# nothing runs: the state says so, nothing to see or save +assert server.scan_state() == {"mapping": False, "name": "", "floor": 1, "map_type": "", "pose": None, + "progress": None, "map": None} +assert refused(server.scan_picture) and refused(server.scan_save) and refused(server.scan_cancel) + +# refused: a bad name, a size it does not know, a map that exists, while busy (nothing is started) +for bad in ("", "a b", "a-b", "로비", "a" * 37): + assert refused(server.scan_start, server.NewMapBody(name=bad), code=422), bad +assert refused(server.scan_start, server.NewMapBody(name="hall", size="huge"), code=422) +assert refused(server.scan_start, server.NewMapBody(name="lab")) +for what in ("assistant", "task"): + busy[what] = True + assert refused(server.scan_start, server.NewMapBody(name="hall")), what + busy[what] = False +assert not any(g.startswith("map-build-api/start") for g in gets), gets + +# start: small map (the base's first delta), v2, floor 1; remembered with the maps there were +r = server.scan_start(server.NewMapBody(name="hall_2")) +assert r["ok"] and r["delta"] == 0.02, r +assert "map-build-api/start?hotelid=hall_2&floor=1&delta=0.02&map_type=v2" in gets, gets +assert json.loads(server.SCAN_FILE.read_text())["maps"] == ["lab", "office"] +assert refused(server.scan_start, server.NewMapBody(name="other")) # one at a time +assert refused(server.map_switch, server.MapBody(map_name="lab")) # no other map while scanning +assert refused(server.map_position, server.PointBody(x=0, y=0)) + +# the state: pose (90° here), progress kept within 0..1, the map's geometry +s = server.scan_state() +assert s["mapping"] and s["name"] == "hall_2" and s["progress"] == 1.0, s +assert abs(s["pose"]["theta"] - 1.5708) < 1e-3 and s["pose"]["x"] == 1.0, s +assert s["map"] == {"width": 6, "height": 4, "resolution": 0.05, "origin_x": -1.0, "origin_y": -2.0}, s + +# the picture: the growing map (map-temp.png) in the app's look, matched to its geometry by size +p = server.scan_picture() +assert any(g.startswith("maps/hall_2/1/map-temp.png") for g in gets), gets +assert p["exact"] and p["width"] == 6 and p["height"] == 4 and p["origin_x"] == -1.0, p +img = cv2.imdecode(np.frombuffer(base64.b64decode(p["png"]), np.uint8), cv2.IMREAD_COLOR) +assert img.shape == (4, 6, 3) and tuple(img[0, 0]) == server.DARK_FREE[::-1], img[0, 0] +picture = cv2.imencode(".png", np.full((5, 7), 255, np.uint8))[1].tobytes() # grew; its geometry not seen yet +p = server.scan_picture() +assert not p["exact"] and (p["width"], p["height"]) == (7, 5), p + +# save: the base's stop, then nothing runs +assert server.scan_save()["name"] == "hall_2" +assert "map-build-api/stop" in gets and not server.SCAN_FILE.exists() +assert refused(server.scan_save) + +# cancel: saved, then deleted (a new name started here, not the map in use) +server.scan_start(server.NewMapBody(name="hall_3")) +calls.clear() +r = server.scan_cancel() +assert r["deleted"] is True, r +assert calls == [("/water_map_manager/map_service", + {"cmd": "delete_map", "message": json.dumps({"mapName": "hall_3", "floors": [1]})})], calls + +# cancel of a scan not started here (the base's own page), or of the map in use: it stays +builder.update(mapbuilding=True, hotelid="office", floor="1") +calls.clear() +r = server.scan_cancel() +assert r["deleted"] is False and calls == [], (r, calls) +server.scan_start(server.NewMapBody(name="hall_4")) +current["map_name"] = "hall_4" +calls.clear() +r = server.scan_cancel() +assert r["deleted"] is False and calls == [], (r, calls) +current["map_name"] = "office" + +# a base that refuses the delete: the map stays, said so +server.scan_start(server.NewMapBody(name="hall_5")) +delete_reply = {"success": False, "message": "no"} +r = server.scan_cancel() +assert r["deleted"] is False and "no" in r["note"], r + +# a scan saved from the base's page: switching maps works again +server.SCAN_FILE.write_text(json.dumps({"name": "hall_6"})) +server.agv.request = lambda cmd, timeout=3.0: {"results": {}} +server.map_switch(server.MapBody(map_name="lab")) +assert not server.SCAN_FILE.exists() +print("ok: map scan")