2. 编写并运行Python发布者节点

任务目标

在ROS 2环境中,使用Python编写一个发布者节点,周期性地向指定话题发布字符串消息,并通过rqt_graph工具验证节点间的通信关系。

环境准备

确保已安装ROS 2(Humble或更新版本),并完成环境配置。本案例需要rclpy库,ROS 2默认自带。创建工作空间并创建功能包:

mkdir -p ~/ros2_ws/src
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python py_pub_node

完整实现代码

在~/ros2_ws/src/py_pub_node/py_pub_node/目录下创建publisher_node.py文件,内容如下:

import rclpy
from rclpy.node import Node
from std_msgs.msg import String

class SimplePublisher(Node):
    def __init__(self):
        super().__init__('simple_publisher')
        self.publisher_ = self.create_publisher(String, 'chatter', 10)
        self.timer = self.create_timer(0.5, self.timer_callback)
        self.count = 0

    def timer_callback(self):
        msg = String()
        msg.data = f'Hello ROS2: {self.count}'
        self.publisher_.publish(msg)
        self.get_logger().info(f'Publishing: "{msg.data}"')
        self.count += 1

def main(args=None):
    rclpy.init(args=args)
    node = SimplePublisher()
    try:
        rclpy.spin(node)
    except KeyboardInterrupt:
        pass
    finally:
        node.destroy_node()
        rclpy.shutdown()

if __name__ == '__main__':
    main()

配置与运行

编辑setup.py,在entry_points中添加:

entry_points={
    'console_scripts': [
        'publisher_node = py_pub_node.publisher_node:main',
    ],
},

编译并运行:

cd ~/ros2_ws
colcon build --packages-select py_pub_node
source install/setup.bash
ros2 run py_pub_node publisher_node

验证方法

打开新终端,执行以下命令验证节点通信:

source ~/ros2_ws/install/setup.bash
ros2 topic echo /chatter

预期输出:持续显示data: Hello ROS2: 0、Hello ROS2: 1等递增消息,证明发布者节点正常工作。

再开一个终端,运行rqt_graph查看通信图:

rqt_graph

在图形界面中应看到/simple_publisher节点连接到/chatter话题,且话题被订阅(若同时运行ros2 topic echo,则显示订阅关系)。

常见问题

  • 找不到功能包:确认已执行source install/setup.bash,且编译无报错。
  • rqt_graph无显示:确保发布者节点正在运行,且刷新图形界面(点击左上角刷新按钮)。
  • 消息频率不符:定时器周期为0.5秒,即每秒发布2条消息,可通过修改create_timer参数调整。
/simple_publisher Python节点 /chatter 话题 发布消息 std_msgs/String