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。
相关文章推荐
- Rospy的官方教程代码讲解(二)消息头和用户数据
- javaScript高级教程(六) 获取窗口,屏幕,文档信息
- (转)Android基础入门教程——1.10 反编译APK获取代码&资源
- 获取本机所有显卡的信息--代码
- Android初级教程获取手机系统联系人信息
- Android初级教程之内容提供者获取联系人信息
- 通过 GPS 信息获取当前所在城市名的代码 转自:hager的博客
- 获取磁盘(本地磁盘和移动磁盘)信息的Java代码
- Android初级教程获取手机位置信息GPS与动态获取最佳方式
- 使用node.js 获取客户端信息代码分享
- Java获取当前操作系统的信息实例代码
- DIY 获取 CLR 错误代码描述信息的小工具
- Android获取手机的版本号等信息的代码
- WCF 聊天室程序代码详细讲解教程
- 【caffe】Caffe的Python接口-官方教程-01-learning-Lenet-详细说明(含代码)
- Demo1.从服务器获取信息 客户端代码
- C# 脚本代码自动登录淘宝获取用户信息
- 通过android代码获取android系统的imei、手机型号、手机品牌、android系统的版本号、sdk版本号等信息
- 10行代码在C#中获取页面元素布局信息
- 获取Android各类系统相关信息的接口实现代码