话题通信是ROS 2中非常常见的一种通信方式。它基于发布-订阅模式,这意味着有一个节点负责发布数据,而另一个节点则订阅这些数据。订阅节点只要订阅了某个话题,就能收到发布节点发送的数据。接下来,我会用简单的步骤和代码示例,展示如何使用Python实现节点之间的话题通信。
1. 安装ROS 2
首先,你需要安装ROS 2。如果你还没有安装,可以参考[ROS 2官方安装指南](https://docs.ros.org/en/foxy/Installation.html)。
2. 创建工作空间和包
首先,在你的工作目录中创建一个ROS 2工作空间:
mkdir -p ~/ros2_ws/src
cd ~/ros2_ws
colcon build
然后,在工作空间中创建一个新的ROS 2包:
cd ~/ros2_ws/src
ros2 pkg create --build-type ament_python my_package
3. 编写发布节点
在`my_package`目录下,创建一个新的Python脚本,例如`publisher_node.py`:
# my_package/my_package/publisher_node.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher')
self.publisher_ = self.create_publisher(String, 'topic', 10)
timer_period = 0.5 # 每0.5秒发布一次消息
self.timer = self.create_timer(timer_period, self.timer_callback)
self.i = 0
def timer_callback(self):
msg = String()
msg.data = f'Hello, ROS 2: {self.i}'
self.publisher_.publish(msg)
self.get_logger().info(f'Publishing: "{msg.data}"')
self.i += 1
def main(args=None):
rclpy.init(args=args)
minimal_publisher = MinimalPublisher()
rclpy.spin(minimal_publisher)
minimal_publisher.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
4. 编写订阅节点
在`my_package`目录下,创建另一个Python脚本,例如`subscriber_node.py`:
# my_package/my_package/subscriber_node.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
class MinimalSubscriber(Node):
def __init__(self):
super().__init__('minimal_subscriber')
self.subscription = self.create_subscription(
String,
'topic',
self.listener_callback,
10)
self.subscription # 防止未使用变量的警告
def listener_callback(self, msg):
self.get_logger().info(f'I heard: "{msg.data}"')
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = MinimalSubscriber()
rclpy.spin(minimal_subscriber)
minimal_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
5. 更新setup.py
编辑`my_package/setup.py`文件,添加入口点以便于启动节点:
from setuptools import setup
package_name = 'my_package'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
install_requires=['setuptools'],
zip_safe=True,
maintainer='Your Name',
maintainer_email='yourname@example.com',
description='Examples of minimal publisher/subscriber using rclpy',
license='Apache License 2.0',
tests_require=['pytest'],
entry_points={
'console_scripts': [
'publisher_node = my_package.publisher_node:main',
'subscriber_node = my_package.subscriber_node:main',
],
},
)
6. 更新package.xml
确保`package.xml`中包含以下依赖项:
<exec_depend>rclpy</exec_depend>
<exec_depend>std_msgs</exec_depend>
7. 编译和运行
在工作空间的根目录下编译包:
cd ~/ros2_ws
colcon build
编译完成后,运行发布节点:
source ~/ros2_ws/install/setup.bash
ros2 run my_package publisher_node
在另一个终端中,运行订阅节点:
source ~/ros2_ws/install/setup.bash
ros2 run my_package subscriber_node
通过以上步骤,你成功地使用Python实现了ROS 2中的话题通信。发布节点发布消息,订阅节点接收并打印这些消息。这就是ROS 2中话题通信的基本原理和实现方式。