ROS消息传递
- 编写简单的消息发布器和订阅器
python
wiki
- ROS中,节点之间通过发布话题和订阅话题来通信,在程序中是通过消息发布器和订阅器来实现,数据流通过话题的发布和订阅在节点之间传播,而数据流的数据类型则称为消息,例如ros入门教程中的节点talker和listener之间通过话题”chatter”来传递数据流,而数据流的具体数据类型则是std_msgs/String。
命令:
rosmsg list
- ROS发布Float32MultiArray消息C++/Python
在ros下发布一个字符串消息或整数消息,网上例程不少,ROSwiki上也有教程,有时就需要一次发送不止一个数据,这时候就得用到数组了,C++的也好找,不过python写的就比较少了,特此记录。
ROS-写一个简单的消息发布器与订阅器(Python)
发布
# -*- coding: utf-8 -*-
import rospy # 导入rospy包,rospy是ROS的python客户端
from std_msgs.msg import String # 导入python的标准字符处理库
def talker():
# 定义talker函数
# 定义发布的主题名称chatter, 消息类型String(实质是std_msgs.msg.String),设置队列条目个数.
pub = rospy.Publisher('chatter', String, queue_size=10)
# 初始化节点,节点名称为talker
# anonymous=True,要求每个节点都有唯一的名称,避免冲突。这样可以运行多个talker.py
rospy.init_node('talker', anonymous=True)
# 设置发布的频率,单位是每秒次数,这是每秒10次的频率发布主题
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown(): # rospy.is_shutdown()检查节点是否关闭
hello_str = "hello world %s" % rospy.get_time()
rospy.loginfo(hello_str) # 在屏幕输出日志信息,写入到rosout节点
pub.publish(hello_str) # 发布信息到主题
rate.sleep() # 睡眠一定持续时间,如果参数为负数,睡眠会立即返回
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
订阅
#-*- coding: utf-8 -*-
import rospy
from std_msgs.msg import String
def callback(data): #定义一个回调函数,这个回调函数将接收到的消息作为参数进行处理
rospy.loginfo(rospy.get_caller_id() + "I heard %s", data.data)
def listener():
#定义listener函数(订阅者)
#在ROS中节点要有唯一的名称。
#如果有一个同名节点出现,它会碰上前一个节点,这样就很容易的将前一个节点从网络上踢开
#初始化节点
rospy.init_node('listener', anonymous=True)
#订阅函数,订阅chatter主题,内容类型是std_msgs.msgs.String,
#当有新内容,调用callback函数处理。接受到的主题内容作为参数传递给callback
rospy.Subscriber("chatter", String, callback)
rospy.spin() #保持节点运行,直到节点关闭。不影响订阅的回调函数,因为回调函数有自己的线程
if __name__ == '__main__':
listener()
ROS-接收相机(彩色/深度)消息并显示
# coding: utf-8
from __future__ import print_function
from __future__ import division
# rosrun kinect2_bridge kinect2_bridge _depth_method:=opengl _reg_method:=cpu
import cv2
# ros
import rospy
from sensor_msgs.msg import Image, CameraInfo
import time
import numpy as np
from cv_bridge import CvBridge
bridge = CvBridge()
def callback(data):
start = time.time()
# data = rospy.wait_for_message('/kinect2/qhd/image_color_rect', Image)
frame = bridge.imgmsg_to_cv2(data, "bgr8")
# depth = rospy.wait_for_message("/kinect2/qhd/image_depth_rect", Image)
# depth = bridge.imgmsg_to_cv2(depth, "32FC1")
end = time.time()
c