12.2 编写Subscriber Node

12.2.1 The Code

将listener.py文件下载到脚本目录中

$ roscd beginner_tutorials/scripts/
$ wget https://raw.github.com/ros/ros_tutorials/kinetic-devel/rospy_tutorials/001_talker_listener/listener.py

文件内容看起来为:

#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)

def listener():

    # In ROS, nodes are uniquely named. If two nodes with the same
    # node are launched, the previous one is kicked off. The
    # anonymous=True flag means that rospy will choose a unique
    # name for our 'listener' node so that multiple listeners can
    # run simultaneously.
    rospy.init_node('listener', anonymous=True)

    rospy.Subscriber("chatter", String, callback)

    # spin() simply keeps python from exiting until this node is stopped
    rospy.spin()

if __name__ == '__main__':
    listener()

不要忘记给该节点增加执行权限

$ chmod +x listener.py

12.2.2 The Code Explained

listener.py的代码与talker.py类似,只是我们引入了一个新的基于回调的订阅消息机制。

rospy.init_node('listener', anonymous=True)

rospy.Subscriber("chatter", String, callback)

# spin() simply keeps python from exiting until this node is stopped
rospy.spin()

这声明你的节点订阅了类型为std_msgs.msgs.String的chatter话题。当收到新消息时,回调将作为第一个参数与消息一起调用。

我们也改变了对rospy.init_node()的调用。我们添加了anonymous = True关键字参数。 ROS要求每个节点都有唯一的名称。如果一个名字相同的节点出现,它会颠覆之前的节点。这样可以很容易地将故障节点从网络中踢出。 anonymous = True标志告诉rospy为节点生成一个唯一的名称,以便您可以轻松地运行多个listener.py节点。

最后加上,rospy.spin()只是让你的节点退出,直到节点关闭。与roscpp不同,rospy.spin()不影响订阅者回调函数,因为这些函数有自己的线程。

Last updated