ROS版本: ROS Kinetic
操作系统:Ubuntu16.04 LTS

方法一,采用类的方法

参考网站
https://blog.csdn.net/ethan_guo/article/details/80226121
当然也可以用python 实现,我们与例程中的方法为例,这里只谈如何实现在类的订阅并讨论其机制。telker代码不变:

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import Stringdef talker():pub = rospy.Publisher('hello', String, queue_size=1)rospy.init_node('talker', anonymous=True)rate = rospy.Rate(10) # 10hzwhile 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

以下是listener 代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
import timepub = rospy.Publisher('pub_with_sub', String, queue_size=10)  #发布话题设为全局变量class listener():def __init__(self):print("class comeing!")rospy.init_node('listener', anonymous=True)rospy.Subscriber("hello", String, self.callback,queue_size = 1)# spin() simply keeps python from exiting until this node is stoppeddef callback(self,data):rospy.loginfo( "I heard %s", data.data)print("call back comeing!")pub.publish(data.data)if __name__ == '__main__':listener()print("class circulation!!")rospy.spin()

执行这两端代码,观察输出,可以发现只有在启动时,会执行

print("call back comeing!")
print("class comeing!")

这两段代码,而回调函数中的

print("call back comeing!")

会在每次订阅到发布的消息后执行,这里就涉及到rospy.spin()的工作机制,它并不是一直循环这个listener()类。而是循环进入类后的订阅函数,这个函数叫做ROS消息回调处理函数。可以参考官方网站查看其具体原理。

到这里其实还有一个小问题,那就是关于画图,如果我们想在回调函数中实现画图,或者在回调函数中修改变量的值,而在类的构造函数中执行与此变量有关的操作,那么我们只需要在类中加一个循环即可:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
import timepub = rospy.Publisher('pub_with_sub', String, queue_size=10)  #发布话题设为全局变量class listener():def __init__(self):print("class comeing!")self.da = []rospy.init_node('listener', anonymous=True)rospy.Subscriber("hello", String, self.callback,queue_size = 1)# spin() simply keeps python from exiting until this node is stopped#############加入的循环####################while not rospy.is_shutdown():print(self.da)#此处可以是画图的语句##########################################def callback(self,data):rospy.loginfo( "I heard %s", data.data)self.da = data.dataprint("call back comeing!")pub.publish(data.data)if __name__ == '__main__':listener()print("class circulation!!")rospy.spin()

这时候可以发现,回调函数中得到的变量在构造函数的循环中执行了。实时画图在后面的文章中讨论。

方法二,全局变量

下面介绍一下Python中用全局变量的方法实现.
以ros wiki上面的话题通信教程为例。
http://wiki.ros.org/ROS/Tutorials/WritingPublisherSubscriber%28python%29
这里定义了talker 和 listener :
talker:

#!/usr/bin/env python
# license removed for brevity
import rospy
from std_msgs.msg import Stringdef talker():pub = rospy.Publisher('pub1', String, queue_size=1)rospy.init_node('talker', anonymous=True)rate = rospy.Rate(10) # 10hzwhile 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

这里我么修改listener,在文件中加入了一个全局变量pub,然后直接将订阅的话题通过
pub再次发布出去,当然,这里只是个测试,实际中肯定是对该消息进行处理后再发布的,写改后的listener如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
import timepub = rospy.Publisher('pub_with_sub', String, queue_size=10)  #发布话题设为全局变量
def callback(data):rospy.loginfo( "I heard %s", data.data)pub.publish(data.data)
def listener():rospy.init_node('listener', anonymous=True)rospy.Subscriber("pub1", String, callback,queue_size = 1)# spin() simply keeps python from exiting until this node is stoppedrospy.spin()if __name__ == '__main__':listener()

这时,我们像教程中一样运行这两个程序结果并没有什么区别,但如果我们用rostopic list 查看,就会发现比原教程中多了一个话题,就是问在listener中发布的,接下来,我们创建一个listen_listener.py的文件来订阅这个话题:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
import timedef callback(data):rospy.loginfo( "I heard %s", data.data)
def listener():rospy.init_node('listener', anonymous=True)rospy.Subscriber("pub_with_sub", String, callback,queue_size = 1)# spin() simply keeps python from exiting until this node is stoppedrospy.spin()if __name__ == '__main__':listener()

ok,别忘了将文件设置为可执行文件,这是后,我们同时打开这三个文件。会发现显示同样的内容。实际上是这样一个结构:
talker发布->listener订阅 再发布 -> listen_listener再订阅!

ROS在同一节点同时订阅和发布消息相关推荐

  1. ROS 基础: 在同一个节点里订阅和发布消息

    在一些应用中,可能有的人需要在同一个节点中实现订阅一个消息,然后在该消息的回调函数中处理一下这些数据后再发布到另一个topic上. ROS answers中也有人有相同的疑问,这里贴出Martin P ...

  2. ROS wiki系列|通过ROS wiki-tutorials学习节点

    前面几期我们讲的都是一些入门相关的内容-- ROS wiki系列|ROS wiki初探(自用) ROS wiki系列|Documentation-ROS部分讲解 ROS wiki系列|ROS入门基础概 ...

  3. ros中cpp节点创建

    目录 1.创建工作空间 2.创建功能包 3.在src中创建广播a.cpp 4.创建订阅b.cpp 5.修改cmake文件 6.编译 7.运行,在终端输入roscore启动 8.查看消息节点 1.创建工 ...

  4. ROS底盘控制节点 源码分析

    先在机器人端通过launch文件启动底盘控制. @robot:~$ roslaunch base_control base_control.launch ... logging to /home/jy ...

  5. ros下创建节点后运行总是出现[rospack] Error: package '***' not found

    ros下创建节点后运行总是出现[rospack] Error: package '***' not found 这是由于没有配置环境的原因所造成的,解决方法:输入命令行source ~/catkin_ ...

  6. ros系列-解决节点处理bag文件,输出无内容问题

    运行系统:Ubuntu18.04 运行环境:python2.7.17 ROS初学者-记录 问题描述:初学ROS,用自己的激光雷达点云bag文件跑无人驾驶汽车系统入门(二十四)--激光雷达的地面-非地面 ...

  7. ROS学习之节点间话题通信的

    一.学习要点: 1.发布节点 a.启动该节点并设置其名称,名称必须唯一 b.设置节点进程的句柄 c.将节点设置成发布者,并将所发布主题的类型和名称告知节点管理器. d.设置发送数据的频率: 2.订阅节 ...

  8. MQTT.fx客户端MQTT接入阿里云物联网平台,登录、订阅、发布消息

    目录 1. 准备 2. MQTT.fx 设置登录名.密码 3. MQTT.fx 接入阿里云,订阅Topic 4. 阿里云下发数据给 MQTT.fx 5. MQTT.fx 发布消息给服务器 相关链接:M ...

  9. ROS 机器人模型节点的运动控制原理

    一般我们启动机器人模型是通过以下的.launch文件启动,如下所示: <launch><param name="robot_description" comman ...

最新文章

  1. 不止最佳长论文,腾讯AI在ACL上还有这些NLP成果(附论文链接)
  2. android适配右到左布局注意事项
  3. jquery-1 jquery几个小实例
  4. Codeforces Round #404 (Div. 2) B. Anton and Classes 水题
  5. 2440启动文件分析
  6. 机器学习实验中的编程技术(part3)--numpy
  7. 不学Python的同学,“跳一跳”都输了
  8. CentOS 6.6 搭建Zabbix 3.0.3 过程
  9. PAT乙级(1006 换个格式输出整数)
  10. 【华为云技术分享】【昇腾】【玩转Atlas200DK系列】基于Pycharm专业版构建开发板python开发运行环境
  11. hexo需要先编辑好html文件吗,教你定制Hexo的landscape打造自己的主题_html/css_WEB-ITnose...
  12. Excel宏的自动运行设置
  13. filezilla的root账户无法连接服务器解决办法
  14. java根据坐标轴_java 根据坐标截取图片实例代码
  15. 酒店消防安全知识培训PPT模板
  16. Smarty中文手册
  17. java 象棋人机开源码,中国象棋人机博弈程序(扁平化棋局) C语言实现
  18. Linux 发展史小览
  19. 计算机网络工程用排线架,网络配线架使用和安装说明【图解】
  20. 递归和循环两种方法完成树的镜像转换

热门文章

  1. 【时空序列预测第四篇】PredRNN++: Towards A Resolution of the Deep-in-Time Dilemma in Spatiotemporal Predictive
  2. 程序猿的感悟:做人应该不知足
  3. 后端程序员生产力工具合集
  4. android ppt素材,华为ppt素材库
  5. 纯净简洁绿色的解压缩软件
  6. 用SDK包开发K66FX18学习笔记(1)
  7. 读《爱因斯坦文集》第一卷
  8. 仿【咪咕动漫】列表下拉刷新上拉加载
  9. FPGA的NIOS-II开发入门
  10. FPGA学习-rom只读存储器(嵌入式块应用)