Update map picture and order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+79
-3
@@ -834,6 +834,53 @@ def line_delete(body: MarkerName):
|
|||||||
return {"ok": True}
|
return {"ok": True}
|
||||||
|
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
|
||||||
@app.get("/map/info", tags=["map"], summary="Current map, its geometry, the markers with poses and all maps")
|
@app.get("/map/info", tags=["map"], summary="Current map, its geometry, the markers with poses and all maps")
|
||||||
def map_info():
|
def map_info():
|
||||||
cur = agv.request("/api/map/get_current_map")["results"]
|
cur = agv.request("/api/map/get_current_map")["results"]
|
||||||
@@ -842,10 +889,15 @@ def map_info():
|
|||||||
markers = [{"name": n, "type": m.get("key"), "x": m["pose"]["position"]["x"], "y": m["pose"]["position"]["y"],
|
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"])}
|
"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"]]
|
for n, m in marks.items() if m.get("floor", 1) == cur["floor"]]
|
||||||
|
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,
|
return {"map_name": cur["map_name"], "floor": cur["floor"], **cur.get("info", {}), "markers": markers,
|
||||||
"lines": _forbidden_lines(cur["floor"]),
|
"lines": _forbidden_lines(cur["floor"]),
|
||||||
"main_dock": agv.dock_marker(), # "home"; further docks (dock2) keep their names
|
"main_dock": agv.dock_marker(), # "home"; further docks (dock2) keep their names
|
||||||
"maps": [{"name": n, "floors": f} for n, f in sorted(maps.items())]}
|
"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)]}
|
||||||
|
|
||||||
|
|
||||||
DARK_UNKNOWN, DARK_FREE, DARK_WALL = (10, 11, 13), (22, 26, 31), (232, 232, 232) # RGB, the Lumi app's look
|
DARK_UNKNOWN, DARK_FREE, DARK_WALL = (10, 11, 13), (22, 26, 31), (232, 232, 232) # RGB, the Lumi app's look
|
||||||
@@ -863,14 +915,36 @@ def _dark(png):
|
|||||||
return cv2.imencode(".png", out)[1].tobytes()
|
return cv2.imencode(".png", out)[1].tobytes()
|
||||||
|
|
||||||
|
|
||||||
|
# The base's own page draws ui_map.png: clean outlines of the free space (BGR 250 unknown, 253/241/234 free, 194/177/161
|
||||||
|
# outline), where map.png is the raw lidar grid (spotty, thick walls when zoomed; the owner asked for the clean one).
|
||||||
|
UI_COLOURS = ((250, 250, 250), (253, 241, 234), (194, 177, 161)) # BGR: unknown, free, outline
|
||||||
|
|
||||||
|
|
||||||
|
def _dark_ui(png):
|
||||||
|
"""The base's ui_map.png in the app's dark look, same size: each pixel by the nearest of its three colours."""
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
g = cv2.imdecode(np.frombuffer(png, np.uint8), cv2.IMREAD_COLOR).astype(np.int32)
|
||||||
|
d = np.stack([((g - np.array(c)) ** 2).sum(axis=2) for c in UI_COLOURS])
|
||||||
|
look = np.array([DARK_UNKNOWN[::-1], DARK_FREE[::-1], DARK_WALL[::-1]], np.uint8)
|
||||||
|
return cv2.imencode(".png", look[d.argmin(axis=0)])[1].tobytes()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/map/image", tags=["map"], summary="Map picture (PNG) from the base; default the current map")
|
@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, dark: bool = False):
|
def map_image(map_name: str | None = None, floor: int | None = None, dark: bool = False):
|
||||||
if map_name is None:
|
if map_name is None:
|
||||||
cur = agv.request("/api/map/get_current_map")["results"]
|
cur = agv.request("/api/map/get_current_map")["results"]
|
||||||
map_name, floor = cur["map_name"], cur["floor"]
|
map_name, floor = cur["map_name"], cur["floor"]
|
||||||
url = f"{AGV_WEB}/maps/{urllib.request.quote(map_name)}/{floor or 1}/map.png"
|
folder = f"{AGV_WEB}/maps/{urllib.request.quote(map_name)}/{floor or 1}"
|
||||||
|
if dark: # the app: the clean picture, the raw grid when a map has none
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(f"{folder}/ui_map.png", timeout=10) as r:
|
||||||
|
png = r.read()
|
||||||
|
return Response(_dark_ui(png), media_type="image/png", headers={"Cache-Control": "max-age=60"})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(url, timeout=10) as r:
|
with urllib.request.urlopen(f"{folder}/map.png", timeout=10) as r:
|
||||||
png = r.read()
|
png = r.read()
|
||||||
return Response(_dark(png) if dark else png, media_type="image/png", headers={"Cache-Control": "max-age=60"})
|
return Response(_dark(png) if dark else png, media_type="image/png", headers={"Cache-Control": "max-age=60"})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -903,6 +977,7 @@ def marker_save(body: MarkerBody):
|
|||||||
else:
|
else:
|
||||||
r = agv.request(f"/api/markers/insert_by_pose?name={name}&x={body.x}&y={body.y}&theta={body.theta}&{kind}")
|
r = agv.request(f"/api/markers/insert_by_pose?name={name}&x={body.x}&y={body.y}&theta={body.theta}&{kind}")
|
||||||
agv.known_markers(fresh=True) # drives to it work at once
|
agv.known_markers(fresh=True) # drives to it work at once
|
||||||
|
_mark_time(name, time.time())
|
||||||
return {"ok": True, "reply": r}
|
return {"ok": True, "reply": r}
|
||||||
|
|
||||||
|
|
||||||
@@ -921,6 +996,7 @@ def marker_delete(body: MarkerName):
|
|||||||
name = _marker_name(body.name)
|
name = _marker_name(body.name)
|
||||||
r = agv.request(f"/api/markers/delete?name={name}")
|
r = agv.request(f"/api/markers/delete?name={name}")
|
||||||
agv.known_markers(fresh=True)
|
agv.known_markers(fresh=True)
|
||||||
|
_mark_time(name, None)
|
||||||
return {"ok": True, "reply": r}
|
return {"ok": True, "reply": r}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+32
-14
@@ -4,6 +4,11 @@ import no_robot # noqa: F401 any connection
|
|||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from api import server
|
from api import server
|
||||||
|
import tempfile, pathlib
|
||||||
|
server.MARKER_TIMES = pathlib.Path(tempfile.mkdtemp()) / "marker_times.json" # not the real file
|
||||||
|
server._map_dates = lambda: {}
|
||||||
|
dated = []
|
||||||
|
server._mark_time = lambda name, when: dated.append((name, when is not None)) # the date book is test_map_info's
|
||||||
|
|
||||||
sent = []
|
sent = []
|
||||||
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
|
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
|
||||||
@@ -23,6 +28,7 @@ def refused(fn, *a, code=409):
|
|||||||
# where Lumi stands, and at a tapped pose (an existing name is moved there)
|
# where Lumi stands, and at a tapped pose (an existing name is moved there)
|
||||||
server.marker_save(server.MarkerBody(name="door_1"))
|
server.marker_save(server.MarkerBody(name="door_1"))
|
||||||
assert sent == ["/api/markers/insert?name=door_1&type=0&num=1", "refresh"], sent
|
assert sent == ["/api/markers/insert?name=door_1&type=0&num=1", "refresh"], sent
|
||||||
|
assert dated == [("door_1", True)], dated # dated, so the app lists it first
|
||||||
sent.clear()
|
sent.clear()
|
||||||
server.marker_save(server.MarkerBody(name="p11", x=1.5, y=-2.25, theta=0.5))
|
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
|
assert sent == ["/api/markers/insert_by_pose?name=p11&x=1.5&y=-2.25&theta=0.5&type=0", "refresh"], sent
|
||||||
@@ -58,23 +64,35 @@ assert refused(server.map_position, server.PointBody(x=0, y=0))
|
|||||||
assert sent == []
|
assert sent == []
|
||||||
|
|
||||||
|
|
||||||
# the map picture in the app's dark look: unknown almost black, free space dark, walls light (same size)
|
# the map picture in the app's dark look: unknown almost black, free space dark, walls light (same size). The base's
|
||||||
|
# clean ui_map.png (three colours, BGR) when it has one; else its raw grid map.png (205 unknown, 255 free, 0 walls)
|
||||||
import cv2 # noqa: E402
|
import cv2 # noqa: E402
|
||||||
import numpy as np # noqa: E402
|
import numpy as np # noqa: E402
|
||||||
pic = np.full((4, 6), 205, np.uint8) # unknown
|
ui = np.full((4, 6, 3), 250, np.uint8) # unknown
|
||||||
pic[1, 1:5] = 255 # free
|
ui[1, 1:5] = (253, 241, 234) # free
|
||||||
pic[2, 2] = 0 # a wall
|
ui[2, 2] = (194, 177, 161) # outline
|
||||||
png = cv2.imencode(".png", pic)[1].tobytes()
|
grid = np.full((4, 6), 205, np.uint8)
|
||||||
|
grid[1, 1:5] = 255
|
||||||
|
grid[2, 2] = 0
|
||||||
|
pngs = {"ui_map.png": cv2.imencode(".png", ui)[1].tobytes(), "map.png": cv2.imencode(".png", grid)[1].tobytes()}
|
||||||
|
|
||||||
|
|
||||||
|
def fake_open(url, timeout=10):
|
||||||
|
name = url.rsplit("/", 1)[1]
|
||||||
|
if name not in pngs:
|
||||||
|
raise OSError("404")
|
||||||
|
return type("R", (), {"read": lambda s: pngs[name], "__enter__": lambda s: s, "__exit__": lambda s, *a: False})()
|
||||||
|
|
||||||
|
|
||||||
server.agv.request = lambda cmd, timeout=3.0: {"results": {"map_name": "m", "floor": 1}}
|
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,
|
server.urllib.request.urlopen = fake_open
|
||||||
"__exit__": lambda s, *a: False})()
|
for _ in range(2): # with ui_map.png, then without it
|
||||||
out = cv2.imdecode(np.frombuffer(server.map_image(dark=True).body, np.uint8), cv2.IMREAD_COLOR)
|
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 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[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 tuple(out[2, 2]) == server.DARK_WALL[::-1], out[2, 2]
|
||||||
assert server.map_image().body == png # as the base draws it, unless asked
|
pngs.pop("ui_map.png", None)
|
||||||
|
assert server.map_image().body == pngs["map.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)
|
# Lumi stands at a marker: the base takes its pose from it (after a map switch, the quickest way)
|
||||||
sent.clear()
|
sent.clear()
|
||||||
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
|
server.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {"status": "OK", "results": {}}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ import time
|
|||||||
|
|
||||||
import no_robot # noqa: F401 any connection to the robot fails the test
|
import no_robot # noqa: F401 any connection to the robot fails the test
|
||||||
from api import server
|
from api import server
|
||||||
|
import tempfile, pathlib
|
||||||
|
server.MARKER_TIMES = pathlib.Path(tempfile.mkdtemp()) / "marker_times.json" # not the real file
|
||||||
|
server._map_dates = lambda: {}
|
||||||
from robot import agv
|
from robot import agv
|
||||||
|
|
||||||
MARKS = {"home_dock": {"key": 11, "num": 1, "floor": 1, "pose": {"position": {"x": 0, "y": 0},
|
MARKS = {"home_dock": {"key": 11, "num": 1, "floor": 1, "pose": {"position": {"x": 0, "y": 0},
|
||||||
@@ -48,4 +51,14 @@ assert agv.known_markers(fresh=True) == ["home", "p13"] # a name not
|
|||||||
agv._known["t"] = time.time() - agv.MARKERS_FRESH_S - 1
|
agv._known["t"] = time.time() - agv.MARKERS_FRESH_S - 1
|
||||||
del MARKS["p13"]
|
del MARKS["p13"]
|
||||||
assert agv.known_markers() == ["home"] # and within MARKERS_FRESH_S anyway
|
assert agv.known_markers() == ["home"] # and within MARKERS_FRESH_S anyway
|
||||||
|
# newest first: markers by when this API saved them (undated ones after, in the base's order), maps by folder date
|
||||||
|
server.MARKER_TIMES.write_text(json.dumps({"office/1/p13": 200, "office/1/z9": 100}))
|
||||||
|
MARKS.update({n: {"key": 0, "floor": 1, "pose": {"position": {"x": 0, "y": 0}, "orientation": {"z": 0, "w": 1}}}
|
||||||
|
for n in ("p13", "z9", "a1")})
|
||||||
|
assert names(server.map_info()) == ["p13", "z9", "home_dock", "a1"], names(server.map_info())
|
||||||
|
server._map_dates = lambda: {"old": "2026-01-01 00:00", "office": "2026-11-17 09:00"}
|
||||||
|
real_request = agv.request
|
||||||
|
agv.request = server.agv.request = lambda cmd, timeout=3.0: ({"results": {"office": [1], "old": [1], "nodate": [1]}}
|
||||||
|
if cmd == "/api/map/list" else real_request(cmd, timeout))
|
||||||
|
assert [m["name"] for m in server.map_info()["maps"]] == ["office", "old", "nodate"], server.map_info()["maps"]
|
||||||
print("map info ok")
|
print("map info ok")
|
||||||
|
|||||||
Reference in New Issue
Block a user