ROS2 Topic List 实现分析

1. 概述

本文档分析 ros2 topic list 命令的实现过程,从用户输入到最终输出的完整调用链。


2. 调用流程

2.1 用户命令

ros2 topic list [options]

支持的选项:

  • -t, --show-types: 显示话题类型
  • -c, --count-topics: 仅显示话题数量
  • --include-hidden-topics: 包含隐藏话题
  • -v, --verbose: 显示详细信息

3. 实现组件

组件文件路径职责
ListVerbros2topic/verb/list.pyCLI 命令入口
get_topic_names_and_typesros2topic/api/__init__.pyAPI 函数
Noderclpy/node.pyROS2 节点封装
_rclpyC 扩展底层 DDS 通信

4. 时序图

┌─────────┐     ┌──────────┐     ┌─────────────┐     ┌──────────────┐     ┌─────────┐
│  用户   │     │  ros2cli │     │ ros2topic   │     │    rclpy     │     │  DDS   │
└────┬────┘     └────┬─────┘     └──────┬──────┘     └──────┬───────┘     └────┬────┘
     │               │                  │                   │                │
     │ ros2 topic   │                  │                   │                │
     │ list         │                  │                   │                │
     │─────────────▶│                  │                   │                │
     │               │                  │                   │                │
     │               │ ListVerb.main()  │                   │                │
     │               │─────────────────▶│                   │                │
     │               │                  │                   │                │
     │               │                  │ get_topic_names_  │                │
     │               │                  │ and_types()       │                │
     │               │                  │───────────────────▶│                │
     │               │                  │                   │                │
     │               │                  │                   │ node.get_topic │
     │               │                  │                   │ _names_and_   │
     │               │                  │                   │ types()       │
     │               │                  │                   │───────────────▶│
     │               │                  │                   │                │
     │               │                  │                   │    DDS查询    │
     │               │                  │                   │◀──────────────│
     │               │                  │                   │                │
     │               │                  │   返回话题列表    │                │
     │               │                  │◀─────────────────│                │
     │               │                  │                   │                │
     │               │  过滤隐藏话题    │                   │                │
     │               │◀────────────────│                   │                │
     │               │                  │                   │                │
     │               │  格式化输出     │                   │                │
     │               │◀────────────────│                   │                │
     │               │                  │                   │                │
     │  /chatter    │                  │                   │                │
     │  /scan       │                  │                   │                │
     │  /cmd_vel    │                  │                   │                │
     │◀─────────────│                  │                   │                │
     │               │                  │                   │                │

5. 详细实现

5.1 命令入口 (list.py)

class ListVerb(VerbExtension):
    def main(self, *, args):
        # 1. 创建节点策略
        with NodeStrategy(args) as node:
            # 2. 获取话题名称和类型
            topic_names_and_types = get_topic_names_and_types(
                node=node,
                include_hidden_topics=args.include_hidden_topics)
            
            # 3. 如果需要详细信息,统计发布者/订阅者数量
            if args.verbose:
                pub_count = node.count_publishers(topic_name)
                sub_count = node.count_subscribers(topic_name)
        
        # 4. 输出结果
        print(topic_name)

5.2 API 层 (api/init.py)

def get_topic_names_and_types(*, node, include_hidden_topics=False):
    # 1. 调用节点的底层方法
    topic_names_and_types = node.get_topic_names_and_types()
    
    # 2. 如果不包含隐藏话题,则过滤
    if not include_hidden_topics:
        topic_names_and_types = [
            (n, t) for (n, t) in topic_names_and_types
            if not topic_or_service_is_hidden(n)]
    return topic_names_and_types

5.3 rclpy 节点层 (node.py)

def get_topic_names_and_types(self, no_demangle: bool = False):
    # 调用 C 扩展接口
    with self.handle:
        return _rclpy.rclpy_get_topic_names_and_types(
            self.handle, no_demangle)

5.4 C 扩展层

_rclpy.rclpy_get_topic_names_and_types 是 C 扩展函数,直接与 DDS 中间件通信:

  1. 调用 rcl_get_topic_names_and_types() (RCL API)
  2. RCL 调用 DDS 的 get_topic_names_and_types()
  3. 返回话题列表

6. 关键函数

6.1 count_publishers / count_subscribers

def count_publishers(self, topic_name: str) -> int:
    """返回指定话题的发布者数量"""
    with self.handle:
        return self._count_publishers_or_subscribers(
            topic_name, self.handle.get_count_publishers)

def count_subscribers(self, topic_name: str) -> int:
    """返回指定话题的订阅者数量"""
    with self.handle:
        return self._count_publishers_or_subscribers(
            topic_name, self.handle.get_count_subscribers)

6.2 NodeStrategy

NodeStrategy 支持两种节点模式:

  1. Daemon 模式: 使用后台守护进程
  2. Direct 模式: 直接创建节点
class NodeStrategy:
    def __init__(self, args):
        # 优先使用 daemon
        if use_daemon and is_daemon_running(args):
            self._daemon_node = DaemonNode(args)
            if not self._daemon_node.connected:
                self._direct_node = DirectNode(args)
        else:
            self._direct_node = DirectNode(args)

7. 数据流

用户输入
    │
    ▼
ListVerb.main()
    │
    ├──▶ NodeStrategy.__enter__()
    │       │
    │       ├── DaemonNode 或 DirectNode
    │       │
    ▼
get_topic_names_and_types(node)
    │
    ├──▶ node.get_topic_names_and_types()
    │       │
    │       └──▶ _rclpy.rclpy_get_topic_names_and_types()
    │               │
    │               └──▶ RCL API → DDS 中间件
    │
    ├──▶ 过滤隐藏话题 (可选)
    │
    ▼
格式化输出
    │
    ▼
终端显示

8. 类图

┌─────────────────────────────────────────────────────────────┐
│                        ListVerb                              │
├─────────────────────────────────────────────────────────────┤
│ + add_arguments(parser, cli_name)                          │
│ + main(args)                                              │
│ + show_topic_info(topic_info, is_publisher)               │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                    get_topic_names_and_types                │
├─────────────────────────────────────────────────────────────┤
│ + node: Node                                              │
│ + include_hidden_topics: bool                             │
│ Returns: List[Tuple[str, List[str]]]                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                         Node                                │
├─────────────────────────────────────────────────────────────┤
│ + get_topic_names_and_types(no_demangle)                  │
│ + count_publishers(topic_name)                            │
│ + count_subscribers(topic_name)                           │
│ - handle: NodeHandle                                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                       _rclpy                               │
├─────────────────────────────────────────────────────────────┤
│ + rclpy_get_topic_names_and_types(handle, no_demangle)    │
│ + rclpy_count_publishers(handle, topic_name)              │
│ + rclpy_count_subscribers(handle, topic_name)             │
└─────────────────────────────────────────────────────────────┘

9. 总结

ros2 topic list 的实现是一个典型的 ROS2 CLI 架构:

  1. CLI 层: 使用 click 框架实现子命令
  2. API 层: 提供高层抽象接口
  3. rclpy 层: Python 到 C 的桥梁
  4. RCL 层: ROS2 客户端库
  5. DDS 层: 底层通信中间件

整个调用链遵循 ROS2 的分层架构设计,层次清晰,便于扩展。

Logo

聚焦RDK与具身智能,汇集机器人开发教程、开源案例和技术交流

更多推荐