diff --git a/api/server.py b/api/server.py index ccda4a9..27055c5 100644 --- a/api/server.py +++ b/api/server.py @@ -766,6 +766,18 @@ def jog_stop(): return {"ok": True} +def _forbidden_lines(floor): + """The map's no-go lines drawn in the base's web page (forbidden_manager): [{name, points [[x, y], ...]}] on + this floor, in map metres. Empty when the base does not answer: the map still shows.""" + 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 [] + return [{"name": n, "points": l["points"]} for n, l in sorted(lines.items()) + if l.get("floor", 1) == floor and len(l.get("points") or []) >= 2] + + @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"] @@ -775,6 +787,7 @@ def map_info(): "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"]] return {"map_name": cur["map_name"], "floor": cur["floor"], **cur.get("info", {}), "markers": markers, + "lines": _forbidden_lines(cur["floor"]), "main_dock": agv.dock_marker(), # "home"; further docks (dock2) keep their names "maps": [{"name": n, "floors": f} for n, f in sorted(maps.items())]} diff --git a/robot/rosbridge.py b/robot/rosbridge.py index 01f02f4..7581966 100644 --- a/robot/rosbridge.py +++ b/robot/rosbridge.py @@ -1,6 +1,6 @@ """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.""" +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.""" import base64 import json import os @@ -44,9 +44,10 @@ def read_message(sock, buf): 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: +def _connect(timeout): + """An open WebSocket to rosbridge and the bytes read past its handshake.""" + s = socket.create_connection((HOST, PORT), timeout=timeout) + try: 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()) @@ -58,10 +59,33 @@ def read_once(topic, timeout=3.0): 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] + return s, head.split(b"\r\n\r\n", 1)[1] + except BaseException: + s.close() + raise + + +def read_once(topic, timeout=3.0): + """The next message of `topic` (rosbridge's {"op": "publish", "msg": ...}); raises OSError when there is none.""" + s, buf = _connect(timeout) + with s: 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 + + +def call_service(service, args, timeout=3.0): + """Call a ROS service of the base and return its values; raises OSError or RuntimeError when it fails.""" + s, buf = _connect(timeout) + with s: + s.sendall(client_frame(json.dumps({"op": "call_service", "id": "lumi", "service": service, + "args": args}).encode())) + while True: + msg, buf = read_message(s, buf) + if msg.get("op") == "service_response": + if not msg.get("result", False): + raise RuntimeError(f"{service} failed: {msg.get('values')}") + return msg.get("values") or {} diff --git a/tests/test_map_info.py b/tests/test_map_info.py index f21033d..ff33029 100644 --- a/tests/test_map_info.py +++ b/tests/test_map_info.py @@ -1,5 +1,7 @@ """Self-check: a marker added on the base after the API started is in /map/info, /agv/markers and the assistant's -list at once (api/server.py, robot/agv.py), with a fake base, no robot: python tests/test_map_info.py""" +list at once, and the no-go lines of this floor (api/server.py, robot/agv.py), with a fake base, no robot: +python tests/test_map_info.py""" +import json import time import no_robot # noqa: F401 any connection to the robot fails the test @@ -21,9 +23,20 @@ def fake(cmd, timeout=3.0): raise AssertionError(cmd) +LINES = {"door": {"floor": 1, "points": [[0, 1], [2, 1]], "type": "forbidden"}, + "up": {"floor": 2, "points": [[0, 0], [1, 0]]}, "dot": {"floor": 1, "points": [[3, 3]]}} + + +def fake_service(service, args, timeout=3.0): + assert service == "/forbidden_manager/action_service" and args["cmd"] == "list_lines", (service, args) + return {"success": True, "message": json.dumps(LINES)} + + agv.request = server.agv.request = fake +server.rosbridge.call_service = fake_service names = lambda d: [m["name"] for m in d["markers"]] assert names(server.map_info()) == ["home_dock"] +assert server.map_info()["lines"] == [{"name": "door", "points": [[0, 1], [2, 1]]}] # this floor, two points or more assert server.markers()["markers"] == ["home"] and agv.known_markers() == ["home"] MARKS["p13"] = {"key": 0, "floor": 1, "pose": {"position": {"x": 1.0, "y": 2.0}, "orientation": {"z": 0, "w": 1}}}