ROS中有两种获取消息的方式。一种是同步的,一种是异步的。
一、同步的方式
函数为:
rospy.wait_for_message(topic name,message type,queue_size,buff_size)
返回值为所获取的消息。
调用后程序将在这里等待该消息,获得后会继续执行后续的程序。
二、异步的方式
异步的方式是通过subscriber,并使用回调函数的方式来实现的。
示例如下:
#!/usr/bin/python
import rospy
from rospy.client import init_node
from sensor_msgs.msg import XXX
class getMessage:
def __init__(self):
self.sub=rospy.Subscriber(name,type,self.CB,queue_size,buff_size)
def CB(self,msg):
#回调函数的内容。。。
def main(self):
rospy.spin()
if __name__=='__main__':
rospy.init_node("get_message")
gm=getMessage()
gm.main()
其中,name表示要接受的topic的名字,type表示该消息的类型,可以在shell中用rostopic type 来查看。CB为回调函数,其参数msg就是接受到的消息。
使用这种方式,对方发送消息以后将执行CB函数中的内容。如果要总是接受最新的消息,可以设置queue_size=1,buff_size=52428800。原因见https://blog.csdn.net/qq_37082966/article/details/97172729