ROS的Subscriber订阅者
什么是订阅者
接收信息,通过ROS Topic接收来自其它Node的信息,并通过回调函数处理
通常用于监测系统状态,如当机器人关节到达限位位置时触发运动中断
ROS Topic示例
Topic通信过程为:
- Publisher节点和Subscriber节点分别在Master进行注册
- Publisher发布Topic
- Subscriber在Master指挥下订阅Topic,从而建立起Pub-Sub之间的通信
Publisher Node Demo
#!/usr/bin/env python #-- coding:UTF-8 -- import rospy from std_msgs.msg import String def push_msgs(): rospy.init_node("push_node", anonymous=False) push_pub = rospy.Publisher("push", String, queue_size=10) rate = rospy.Rate(100) while not rospy.is_shutdown(): msg = "hello world" push_pub.publish(msg) rospy.loginfo("send message %s", msg) rate.sleep() if __name__ == "__main__": push_msgs()
Subscriber Node Demo
#!/usr/bin/env python #-- coding:UTF-8 -- import rospy from std_msgs.msg import String def stringSubscriberCallback(data): #data的数据类型与Subscriber接收的Topic对应的消息类型一致 rospy.loginfo('The contents of simple_topic: %s', data.data) def stringSubscriber(): rospy.init_node('sub_node', anonymous = False) #初始化ROS节点 rospy.Subscriber('push', String, stringSubscriberCallback) #定义Subscriber对象 rospy.spin() if __name__ == "__main__": stringSubscriber()
运行一下就是下面的效果