Source code for reli.robot.rosbridge

"""ROS 1 and ROS 2 robots through rosbridge (``roslibpy``).

Talking to the robot over the rosbridge WebSocket keeps ReLI independent of the robot's ROS
distribution and Python version: the same code drives a ROS Noetic robot (Python 3.8 on the robot)
and a ROS 2 Humble/Jazzy robot, and ReLI itself can run on a separate GPU workstation.

Robot side:  ROS 1 ``roslaunch rosbridge_server rosbridge_websocket.launch``
             ROS 2 ``ros2 launch rosbridge_server rosbridge_websocket_launch.xml``

Interfaces used (all names configurable under ``robot.rosbridge``):
  cmd_vel (geometry_msgs/Twist or TwistStamped), odom (nav_msgs/Odometry),
  pose in the map frame (geometry_msgs/PoseWithCovarianceStamped, e.g. AMCL),
  navigation action (move_base_msgs/MoveBase in ROS 1, nav2_msgs/NavigateToPose
  in ROS 2), colour/depth images and camera info, and ReLI's text topics.
"""

from __future__ import annotations

import base64
import logging
import math
import threading
import time
from collections.abc import Callable

import numpy as np

from ..camera import Camera, CameraFrame
from ..config import CameraConfig, Intrinsics, RobotConfig, RosbridgeSettings
from ..types import Pose2D
from .base import CANCELLED, MotionResult, Robot

log = logging.getLogger(__name__)


def yaw_from_quaternion(q: dict) -> float:
    x, y, z, w = (float(q.get(k, 0.0)) for k in ("x", "y", "z", "w"))
    return math.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (y * y + z * z))


def quaternion_from_yaw(yaw: float) -> dict:
    return {"x": 0.0, "y": 0.0, "z": math.sin(yaw / 2.0), "w": math.cos(yaw / 2.0)}


def _bytes(data) -> bytes:
    """rosbridge sends uint8[] as base64 text (JSON) or raw bytes (CBOR)."""
    if isinstance(data, str):
        return base64.b64decode(data)
    if isinstance(data, list):
        return bytes(data)
    return bytes(data)


_ENCODINGS = {
    "rgb8": (np.uint8, 3),
    "bgr8": (np.uint8, 3),
    "rgba8": (np.uint8, 4),
    "bgra8": (np.uint8, 4),
    "mono8": (np.uint8, 1),
    "8uc1": (np.uint8, 1),
    "mono16": (np.uint16, 1),
    "16uc1": (np.uint16, 1),
    "32fc1": (np.float32, 1),
}


def decode_image(msg: dict) -> np.ndarray:
    """sensor_msgs/Image (JSON) -> numpy array (HxW or HxWxC)."""
    enc = str(msg["encoding"]).lower()
    if enc not in _ENCODINGS:
        raise ValueError(f"unsupported image encoding {msg['encoding']!r}")
    dtype, ch = _ENCODINGS[enc]
    h, w, step = int(msg["height"]), int(msg["width"]), int(msg["step"])
    dt = np.dtype(dtype).newbyteorder(">" if msg.get("is_bigendian") else "<")
    raw = np.frombuffer(_bytes(msg["data"]), dtype=np.uint8).reshape(h, step)
    arr = raw[:, : w * ch * dt.itemsize].copy().view(dt).reshape(h, w, ch)
    return arr[:, :, 0] if ch == 1 else arr


def decode_compressed(msg: dict) -> np.ndarray:
    import cv2

    data = _bytes(msg["data"])
    if "compresseddepth" in str(msg.get("format", "")).lower():
        data = data[12:]  # compressed_depth_image_transport header
        return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_UNCHANGED)
    return cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR)


class RosbridgeConnection:
    def __init__(self, s: RosbridgeSettings):
        import roslibpy

        self.s = s
        self.roslibpy = roslibpy
        self.ros = roslibpy.Ros(host=s.host, port=s.port)
        self.ros.run(timeout=s.connect_timeout_s)
        log.info("Connected to rosbridge at %s:%d (ROS %d)", s.host, s.port, s.ros_version)

    def type(self, package: str, name: str, kind: str = "msg") -> str:
        return f"{package}/{kind}/{name}" if self.s.ros_version == 2 else f"{package}/{name}"

    def topic(self, name: str, package: str, msg: str, **kwargs):
        return self.roslibpy.Topic(self.ros, name, self.type(package, msg), **kwargs)

    def close(self) -> None:
        try:
            self.ros.close()
        except Exception:  # closing is best effort
            log.debug("rosbridge close failed", exc_info=True)


[docs] class RosbridgeRobot(Robot): def __init__(self, cfg: RobotConfig, conn: RosbridgeConnection): super().__init__(cfg.limits, cfg.control) self.s = cfg.rosbridge self.conn = conn t = self.s.topics self._lock = threading.Lock() self._odom: Pose2D | None = None self._map_pose: Pose2D | None = None cmd_type = "TwistStamped" if self.s.cmd_vel_stamped else "Twist" self._cmd = conn.topic(t.cmd_vel, "geometry_msgs", cmd_type) self._cmd.advertise() conn.topic(t.odom, "nav_msgs", "Odometry", queue_length=1).subscribe(self._on_odom) if t.pose: conn.topic( t.pose, "geometry_msgs", "PoseWithCovarianceStamped", queue_length=1 ).subscribe(self._on_pose) self._nav = None self._nav_cancel: Callable[[], None] | None = None action = self.s.navigation_action or ( "/move_base" if self.s.ros_version == 1 else "/navigate_to_pose" ) try: if self.s.ros_version == 1: from roslibpy.ros1.actionlib import ActionClient self._nav = ActionClient(conn.ros, action, "move_base_msgs/MoveBaseAction") else: self._nav = conn.roslibpy.ActionClient( conn.ros, action, "nav2_msgs/action/NavigateToPose" ) self.has_navigation_stack = True except Exception as exc: # fall back to the built-in controller log.warning( "Navigation action %s unavailable (%s); using the built-in " "point controller without obstacle avoidance.", action, exc, ) deadline = time.monotonic() + self.s.connect_timeout_s while self._odom is None and time.monotonic() < deadline: time.sleep(0.05) if self._odom is None: log.warning("No odometry on %s yet.", t.odom) # ---------------------------------------------------------------- state def _on_odom(self, msg: dict) -> None: p = msg["pose"]["pose"] with self._lock: self._odom = Pose2D( p["position"]["x"], p["position"]["y"], yaw_from_quaternion(p["orientation"]) ) def _on_pose(self, msg: dict) -> None: p = msg["pose"]["pose"] with self._lock: self._map_pose = Pose2D( p["position"]["x"], p["position"]["y"], yaw_from_quaternion(p["orientation"]) ) def odometry(self) -> Pose2D: with self._lock: if self._odom is None: raise RuntimeError("no odometry received from the robot") return self._odom def pose(self) -> Pose2D: with self._lock: if self._map_pose is not None: return self._map_pose return self.odometry() # -------------------------------------------------------------- command def _command(self, v: float, w: float) -> None: twist = {"linear": {"x": v, "y": 0.0, "z": 0.0}, "angular": {"x": 0.0, "y": 0.0, "z": w}} if self.s.cmd_vel_stamped: twist = {"header": {"frame_id": self.s.base_frame}, "twist": twist} self._cmd.publish(self.conn.roslibpy.Message(twist)) def stop(self) -> None: cancel = self._nav_cancel if cancel is not None: cancel() super().stop() def navigate_to( self, x: float, y: float, yaw: float | None, speed: float, cancel: threading.Event | None = None, ) -> MotionResult: if self._nav is None: return super().navigate_to(x, y, yaw, speed, cancel) self._begin() if yaw is None: p = self.pose() yaw = math.atan2(y - p.y, x - p.x) pose = { "header": {"frame_id": self.s.map_frame}, "pose": { "position": {"x": x, "y": y, "z": 0.0}, "orientation": quaternion_from_yaw(yaw), }, } if self.s.ros_version == 1: return self._navigate_ros1(pose, cancel) return self._navigate_ros2(pose, cancel) def _wait( self, finished: Callable[[], bool], cancel_goal: Callable[[], None], cancel: threading.Event | None, ) -> MotionResult | None: self._nav_cancel = cancel_goal deadline = time.monotonic() + self.control.navigation_timeout_s try: while not finished(): if self._cancelled(cancel): cancel_goal() return CANCELLED if time.monotonic() > deadline: cancel_goal() return MotionResult(False, "navigation timeout") time.sleep(0.1) finally: self._nav_cancel = None return None def _navigate_ros1(self, pose: dict, cancel) -> MotionResult: from roslibpy.ros1.actionlib import Goal, GoalStatus goal = Goal(self._nav, self.conn.roslibpy.Message({"target_pose": pose})) goal.send() early = self._wait(lambda: goal.is_finished, goal.cancel, cancel) if early is not None: return early status = (goal.status or {}).get("status") if status == GoalStatus.SUCCEEDED: return MotionResult(True) return MotionResult(False, f"move_base finished with status {status}") def _navigate_ros2(self, pose: dict, cancel) -> MotionResult: roslibpy = self.conn.roslibpy done = threading.Event() outcome: dict = {} def on_result(result) -> None: outcome["status"] = result["status"] done.set() def on_error(error) -> None: outcome["status"] = error.get("status") if isinstance(error, dict) else error done.set() goal_id = self._nav.send_goal( roslibpy.Goal({"pose": pose}), on_result, lambda fb: None, on_error ) early = self._wait(done.is_set, lambda: self._nav.cancel_goal(goal_id), cancel) if early is not None: return early if outcome.get("status") == roslibpy.GoalStatus.SUCCEEDED: return MotionResult(True) return MotionResult(False, f"Nav2 finished with status {outcome.get('status')}")
[docs] class RosbridgeCamera(Camera): def __init__(self, cfg: CameraConfig, conn: RosbridgeConnection): super().__init__(cfg) t = conn.s.topics self.has_depth = bool(t.depth) self._lock = threading.Lock() self._image: np.ndarray | None = None self._depth: np.ndarray | None = None self._driver_K: Intrinsics | None = None self._stamp = 0.0 if t.color: compressed = t.color.endswith("/compressed") conn.topic( t.color, "sensor_msgs", "CompressedImage" if compressed else "Image", queue_length=1 ).subscribe(self._on_color) if t.depth: compressed = "compressed" in t.depth conn.topic( t.depth, "sensor_msgs", "CompressedImage" if compressed else "Image", queue_length=1, throttle_rate=conn.s.depth_throttle_ms, ).subscribe(self._on_depth) if t.camera_info: conn.topic( t.camera_info, "sensor_msgs", "CameraInfo", queue_length=1, throttle_rate=1000 ).subscribe(self._on_info) def _on_color(self, msg: dict) -> None: try: if "format" in msg: img = decode_compressed(msg) else: img = decode_image(msg) enc = msg["encoding"].lower() if enc.startswith("rgb"): img = np.ascontiguousarray(img[:, :, 2::-1]) elif enc.startswith("bgra"): img = np.ascontiguousarray(img[:, :, :3]) elif img.ndim == 2: img = np.repeat(img[:, :, None], 3, axis=2) except Exception: # a bad frame must not kill the subscriber log.exception("Could not decode the colour image") return with self._lock: self._image, self._stamp = img, time.time() def _on_depth(self, msg: dict) -> None: try: raw = decode_compressed(msg) if "format" in msg else decode_image(msg) except Exception: # a bad frame must not kill the subscriber log.exception("Could not decode the depth image") return depth = raw.astype(np.float32) if raw.dtype == np.uint16: depth *= 0.001 # REP 118: 16UC1 depth is in millimetres with self._lock: self._depth = depth def _on_info(self, msg: dict) -> None: K = msg.get("K") or msg.get("k") if K and K[0] > 0: with self._lock: self._driver_K = Intrinsics(fx=K[0], fy=K[4], cx=K[2], cy=K[5]) def read(self) -> CameraFrame | None: with self._lock: if self._image is None: return None image = self._image.copy() depth = self._depth.copy() if self._depth is not None else None driver, stamp = self._driver_K, self._stamp if depth is not None and depth.shape != image.shape[:2]: log.debug( "Depth resolution differs from colour; ignoring depth (use an aligned depth topic)." ) depth = None h, w = image.shape[:2] return CameraFrame(image, depth, self.intrinsics_for(w, h, driver), stamp)
[docs] class RosbridgeIO: """ReLI's text interface on ROS topics: input, response, TTS, image, e-stop.""" def __init__( self, conn: RosbridgeConnection, on_text: Callable[[str], None], on_stop: Callable[[], None] ): t = conn.s.topics self.conn = conn self._response = conn.topic(t.response, "std_msgs", "String") self._tts = conn.topic(t.tts, "std_msgs", "String") self._image = conn.topic(t.image, "sensor_msgs", "CompressedImage") for topic in (self._response, self._tts, self._image): topic.advertise() conn.topic(t.input, "std_msgs", "String").subscribe(lambda m: on_text(m["data"])) conn.topic(t.emergency_stop, "std_msgs", "Empty").subscribe(lambda m: on_stop()) def say(self, text: str) -> None: msg = self.conn.roslibpy.Message({"data": text}) self._response.publish(msg) self._tts.publish(msg) def image(self, image_bgr: np.ndarray) -> None: import cv2 ok, buf = cv2.imencode(".jpg", image_bgr) if ok: self._image.publish( self.conn.roslibpy.Message( {"format": "jpeg", "data": base64.b64encode(buf.tobytes()).decode()} ) )