ros的节点通信机制
时间: 2025-03-02 11:00:50 浏览: 57
### ROS 中节点间的通信机制
#### 话题通信(Topic)
在ROS中,话题通信是一种异步的消息传递方式。节点可以通过发布者-订阅者的模式与其他节点交互数据。当一个节点发布某个主题时,其他订阅该主题的节点可以接收并处理这些消息。这种通信方式适用于广播性质的数据传输场景[^1]。
例如,假设有一个传感器节点不断向`/sensor_data`这个主题发送测量值,任何对该信息感兴趣的分析模块都可以成为此主题下的订阅方:
```python
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('/sensor_data', String, queue_size=10)
rospy.init_node('sensor_talker')
rate = rospy.Rate(1) # 1 Hz
while not rospy.is_shutdown():
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str)
pub.publish(hello_str)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
```
#### 服务通信(Service)
不同于话题的一对多关系,服务提供了一种同步请求-应答式的交流途径。客户端发起特定的服务调用后会等待服务器端返回的结果;只有完成整个过程之后才会继续执行后续操作。这种方式适合用于需要即时反馈的任务,比如查询数据库或获取配置文件内容等。
下面是一个简单的加法器服务的例子:
```python
#!/usr/bin/env python
import rospy
from beginner_tutorials.srv import AddTwoInts,AddTwoIntsResponse
def handle_add_two_ints(req):
print "Returning [%s + %s = %s]"%(req.a, req.b, (req.a + req.b))
return AddTwoIntsResponse(req.a + req.b)
def add_two_ints_server():
rospy.init_node('add_two_ints_server')
s = rospy.Service('add_two_ints', AddTwoInts, handle_add_two_ints)
print "Ready to add two ints."
rospy.spin()
if __name__ == "__main__":
add_two_ints_server()
```
#### 动作通信(Action)
动作库提供了更复杂的任务管理功能,它允许定义目标、取消以及状态更新等功能。对于长时间运行的操作特别有用,因为它支持中途改变计划甚至终止正在进行的工作流。这使得机器人能够更好地适应动态环境变化的需求。
阅读全文
相关推荐


















