Source code for scene_service.ingest.ros_subscribers

# SPDX-License-Identifier: MulanPSL-2.0
"""ROS 2 ingest: an rclpy node on its own thread keeps the latest message of
each observation kind in a thread-safe slot that asyncio code reads on its own
schedule. Topics come from Atlas or `observations[]` in the config.
"""
from __future__ import annotations

import logging
import threading
import time
from dataclasses import dataclass
from typing import Any

log = logging.getLogger(__name__)


# Deferred so Scene imports without rclpy (unit tests).
def _import_ros():
    import rclpy  # type: ignore
    from rclpy.node import Node  # type: ignore
    from rclpy.qos import QoSProfile, ReliabilityPolicy, DurabilityPolicy, HistoryPolicy  # type: ignore
    from rclpy.duration import Duration  # type: ignore
    from rclpy.time import Time  # type: ignore
    from sensor_msgs.msg import Image, LaserScan, PointCloud2, CameraInfo  # type: ignore
    from geometry_msgs.msg import PoseWithCovarianceStamped, TransformStamped  # type: ignore
    from nav_msgs.msg import Odometry, OccupancyGrid  # type: ignore
    from tf2_ros import Buffer, TransformListener  # type: ignore
    # From the generated ros2_idl overlay; without it only this subscription is lost.
    try:
        from map.msg import MapLifecycle  # type: ignore
    except ImportError:
        MapLifecycle = None
    return {
        "rclpy": rclpy,
        "Node": Node,
        "QoSProfile": QoSProfile,
        "ReliabilityPolicy": ReliabilityPolicy,
        "DurabilityPolicy": DurabilityPolicy,
        "HistoryPolicy": HistoryPolicy,
        "Duration": Duration,
        "Time": Time,
        "Image": Image,
        "LaserScan": LaserScan,
        "CameraInfo": CameraInfo,
        "PointCloud2": PointCloud2,
        "PoseWithCovarianceStamped": PoseWithCovarianceStamped,
        "TransformStamped": TransformStamped,
        "Odometry": Odometry,
        "OccupancyGrid": OccupancyGrid,
        "MapLifecycle": MapLifecycle,
        "Buffer": Buffer,
        "TransformListener": TransformListener,
    }


[docs] @dataclass class TopicSpec: """One observation kind (rgb, depth, lidar2d, pose, ...) wired to a ROS topic; `qos_profile` is the publisher's declaration from Atlas.""" kind: str topic: str msg_type: str # "Image" | "LaserScan" | "PoseWithCovarianceStamped" | "Odometry" qos_profile: str = "default"
[docs] def topic_qos_policy(spec: TopicSpec) -> tuple[str, str, int]: """Reliability, durability and depth for one topic. Follows the publisher's declaration: a RELIABLE request cannot connect to a BEST_EFFORT publisher.""" sensor_kinds = {"rgb", "depth", "lidar2d", "lidar3d", "intrinsics"} if spec.kind in { "rgb", "depth", "intrinsics", "occupancy_grid", "nav_costmap", "map_lifecycle", "camera_extrinsics", }: depth = 1 elif spec.kind in {"lidar2d", "lidar3d"}: depth = 2 else: depth = 10 declared = str(spec.qos_profile or "default").strip().lower().replace("-", "_") if declared in {"best_effort", "sensor_data"}: return "best_effort", "volatile", depth if declared == "reliable" and spec.kind in {"occupancy_grid", "nav_costmap"}: return "reliable", "transient_local", depth if declared == "reliable": return "reliable", "volatile", depth if declared in {"latched", "transient_local"}: return "reliable", "transient_local", depth if declared not in {"", "default"}: log.warning( "[scene-ros] unsupported Atlas QoS %r for %s; using safe kind default", spec.qos_profile, spec.kind, ) if spec.kind in sensor_kinds: return "best_effort", "volatile", depth if spec.kind in {"occupancy_grid", "nav_costmap", "map_lifecycle", "camera_extrinsics"}: return "reliable", "transient_local", depth return "reliable", "volatile", depth
class _LatestSlot: """The latest message on one topic, written by rclpy callbacks.""" def __init__(self) -> None: self._lock = threading.Lock() self._msg: Any = None self._stamp_unix: float = 0.0 self._count: int = 0 def write(self, msg: Any) -> None: with self._lock: self._msg = msg self._stamp_unix = time.time() self._count += 1 def read(self) -> tuple[Any, float, int]: with self._lock: return self._msg, self._stamp_unix, self._count
[docs] class SubscribersHub: """The rclpy node, its spin thread and one latest-message slot per kind.""" def __init__(self, specs: list[TopicSpec], *, node_name: str = "scene_subscribers") -> None: self.specs = specs self.node_name = node_name self._slots: dict[str, _LatestSlot] = {s.kind: _LatestSlot() for s in specs} self._ros: dict[str, Any] | None = None self._node: Any = None self._spin_thread: threading.Thread | None = None self._stop_evt = threading.Event() self._tf_buffer: Any = None self._tf_listener: Any = None # ── lifecycle ──────────────────────────────────────────────────────────
[docs] async def start(self) -> None: if self._ros is not None: return try: self._ros = _import_ros() except ImportError as e: log.error("[scene-ros] rclpy not available: %s", e) self._ros = None return rclpy = self._ros["rclpy"] rclpy.init(args=None) Node = self._ros["Node"] node = Node(self.node_name) self._node = node Buffer = self._ros["Buffer"] TransformListener = self._ros["TransformListener"] self._tf_buffer = Buffer() self._tf_listener = TransformListener(self._tf_buffer, node) for spec in self.specs: self._subscribe(spec) self._spin_thread = threading.Thread( target=self._spin_loop, name="scene-rclpy-spin", daemon=True, ) self._spin_thread.start() log.info("[scene-ros] hub up: %d topic(s) + tf2", len(self.specs))
[docs] def add_spec(self, spec: TopicSpec) -> bool: """Subscribe to a topic that appeared after start(). False when the kind is already known or its message class is unavailable.""" if self._ros is None: return False if spec.kind in self._slots: return False self._slots[spec.kind] = _LatestSlot() if not self._subscribe(spec): del self._slots[spec.kind] return False self.specs.append(spec) log.info("[scene-ros] dynamic add: %s on %s", spec.kind, spec.topic) return True
[docs] def has_kinds(self) -> set[str]: return set(self._slots.keys())
[docs] async def stop(self) -> None: if self._ros is None: return self._stop_evt.set() try: if self._node is not None: self._node.destroy_node() except Exception: # noqa: BLE001 pass try: self._ros["rclpy"].shutdown() except Exception: # noqa: BLE001 pass if self._spin_thread is not None: self._spin_thread.join(timeout=2.0) self._ros = None self._node = None
# ── spin loop ────────────────────────────────────────────────────────── def _spin_loop(self) -> None: rclpy = self._ros["rclpy"] # type: ignore[index] while not self._stop_evt.is_set(): try: rclpy.spin_once(self._node, timeout_sec=0.1) except Exception as e: # noqa: BLE001 log.debug("[scene-ros] spin tick: %s", e) # ── subscription wiring ──────────────────────────────────────────────── def _subscribe(self, spec: TopicSpec) -> bool: """Create one subscription; False (with a warning) when the message class is missing.""" assert self._ros is not None msg_cls = self._ros.get(spec.msg_type) if msg_cls is None: log.warning( "[scene-ros] msg type %r unavailable — skipping %s on %s " "(generated interface overlay missing?)", spec.msg_type, spec.kind, spec.topic, ) return False QoSProfile = self._ros["QoSProfile"] ReliabilityPolicy = self._ros["ReliabilityPolicy"] DurabilityPolicy = self._ros["DurabilityPolicy"] HistoryPolicy = self._ros["HistoryPolicy"] reliability_name, durability_name, depth = topic_qos_policy(spec) reliability = ( ReliabilityPolicy.BEST_EFFORT if reliability_name == "best_effort" else ReliabilityPolicy.RELIABLE ) durability = ( DurabilityPolicy.TRANSIENT_LOCAL if durability_name == "transient_local" else DurabilityPolicy.VOLATILE ) qos = QoSProfile( reliability=reliability, durability=durability, history=HistoryPolicy.KEEP_LAST, depth=depth, ) slot = self._slots[spec.kind] _kind = spec.kind # closure capture def _cb(msg: Any, _slot: _LatestSlot = slot, _k: str = _kind) -> None: _slot.write(msg) # Proves the wiring works; "subscribed but nothing arrives" is otherwise silent. if _slot._count == 1: log.info("[scene-ros] FIRST msg on %s (kind=%s)", spec.topic, _k) self._node.create_subscription(msg_cls, spec.topic, _cb, qos) log.info( "[scene-ros] subscribed: %s on %s (%s, qos=%s/%s depth=%d)", spec.kind, spec.topic, spec.msg_type, reliability_name, durability_name, depth, ) return True # ── consumer-side accessors ────────────────────────────────────────────
[docs] def latest(self, kind: str) -> tuple[Any, float, int]: """(msg, stamp_unix, count); msg is None until the first message arrives.""" slot = self._slots.get(kind) if slot is None: return None, 0.0, 0 return slot.read()
[docs] def has(self, kind: str) -> bool: return kind in self._slots
# ── tf2 accessors ────────────────────────────────────────────────────
[docs] def lookup_transform_4x4( self, target_frame: str, source_frame: str, stamp: Any = None, ): """4x4 transform mapping points from `target_frame` into `source_frame`, or None. `stamp` (a message header stamp) asks for the transform at that moment: a frame is placed with the pose the robot had when it was captured, not the pose it has once detection on it has finished. Outside the buffered history the latest transform is used, as before. """ if self._ros is None or self._tf_buffer is None: return None import numpy as np Time = self._ros["Time"] Duration = self._ros["Duration"] tf = None if stamp is not None: try: tf = self._tf_buffer.lookup_transform( source_frame, target_frame, Time.from_msg(stamp), Duration(seconds=0.1), ) except Exception as e: # noqa: BLE001 log.debug("[scene-ros] tf2 %s→%s at the frame stamp failed: %s", source_frame, target_frame, e) if tf is None: try: tf = self._tf_buffer.lookup_transform( source_frame, target_frame, Time(), Duration(seconds=0.1), ) except Exception as e: # noqa: BLE001 log.debug("[scene-ros] tf2 4x4 %s→%s failed: %s", source_frame, target_frame, e) return None t = tf.transform.translation q = tf.transform.rotation # Quaternion → 3x3 rotation. x, y, z, w = float(q.x), float(q.y), float(q.z), float(q.w) n = x*x + y*y + z*z + w*w if n < 1e-12: return None s = 2.0 / n wx, wy, wz = s*w*x, s*w*y, s*w*z xx, xy, xz = s*x*x, s*x*y, s*x*z yy, yz, zz = s*y*y, s*y*z, s*z*z R = np.array([ [1.0 - (yy + zz), xy - wz, xz + wy], [xy + wz, 1.0 - (xx + zz), yz - wx], [xz - wy, yz + wx, 1.0 - (xx + yy)], ], dtype=np.float64) T = np.eye(4, dtype=np.float64) T[:3, :3] = R T[:3, 3] = [float(t.x), float(t.y), float(t.z)] return T