您的位置:首页 > 编程语言

Rospy的官方教程代码讲解(三)获取订阅信息

2018-02-10 09:33 309 查看

Rospy的官方教程代码讲解(三)获取订阅信息

这一篇会比较短,其实应该放在上一篇的最后,之后几个都是讲service的,所以想放在一起写。

Rospy的官方教程代码讲解三获取订阅信息
获取订阅信息

获取订阅信息

在初始化发布器时,通过subscriber_listener设置订阅信息获取,即每次有新的订阅者加入或者有订阅者离开时触发回调

def talker_callback():
pub = rospy.Publisher("chatter", String, subscriber_listener=ChatterListener(), queue_size=10)
rospy.init_node(NAME, anonymous=True)


在订阅信息监听器中,根据加入与离开所产生的不同触发,执行不同的功能

class ChatterListener(rospy.SubscribeListener):
def peer_subscribe(self, topic_name, topic_publish, peer_publish):
print("a peer subscribed to topic [%s]" % topic_name)
str = "Hey everyone, we have a new friend!"
print(str)
topic_publish(String(str))
str = "greetings. welcome to topic "+topic_name
print(str)
peer_publish(String(str))

def peer_unsubscribe(self, topic_name, numPeers):
print("a peer unsubscribed from topic [%s]" % topic_name)
if numPeers == 0:
print("I have no friends")


其中

peer_subscribe(self, topic_name, topic_publish, peer_publish)


会在有新的订阅器加入时回调

peer_unsubscribe(self, topic_name, numPeers)


会在有订阅器离开时回调

完整代码如下:

#!/usr/bin/env python
# Software License Agreement (BSD License)
#
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.

## talker that receives notification of new subscriptions

NAME = 'talker_callback'

import sys
import rospy
from std_msgs.msg import String

class ChatterListener(rospy.SubscribeListener): def peer_subscribe(self, topic_name, topic_publish, peer_publish): print("a peer subscribed to topic [%s]" % topic_name) str = "Hey everyone, we have a new friend!" print(str) topic_publish(String(str)) str = "greetings. welcome to topic "+topic_name print(str) peer_publish(String(str)) def peer_unsubscribe(self, topic_name, numPeers): print("a peer unsubscribed from topic [%s]" % topic_name) if numPeers == 0: print("I have no friends")

def talker_callback(): pub = rospy.Publisher("chatter", String, subscriber_listener=ChatterListener(), queue_size=10) rospy.init_node(NAME, anonymous=True)
count = 0
while not rospy.is_shutdown():
str = "hello world %d"%count
print(str)
pub.publish(String(str))
count += 1
rospy.sleep(0.1)

if __name__ == '__main__':
try:
talker_callback()
except rospy.ROSInterruptException: pass


到此消息发布与订阅的基本就学完了,从下一篇起开始讲service。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: