ROS机器人话题之自定义消息

ROS提供了丰富的内建消息,std_msgs包定义了一些基本的类型。

具体例子

首先定义一个消息类型的文件叫做Complex

例Complex.msg

float32 real
float32 imaginary

Complex.msg文件位于basic包的msg目录中,定义了两个相同类型的值

一旦消息被定义了,我们就需要运行catkin_make命令和source devel/setup.bash命令来产生语言相关的代码,这能够使得我们可以用这些消息实现计算机 和其他平台的无缝通信。

为了让ROS生成语言相关的代码,我们需要确保已经告知构建系统新消息的定义。

需要向package.xml文件中添加以下代码来实现

<build_depend>message_generation<build_depend>
<exec_depend>message_runtime</run_depend>

接下来,我们需要更改CMakeLists.txt文件

更改如下

需要在fins_package()调用的末尾添加message_generation,这样catkin就知道了去那寻找message_generation包:
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation )
告知catkin我们将运行时使用消息,即在catkin_package()调用末尾调加message_runtime

catkin_package( CATKIN_DEPENDS message_runtime )
在add_message_flies()调用的末尾调加消息定义文件Complex.msg来告知catkin我们要编译它
add_message_files( FILES Complex.msg )

最后在CMakeLists.txt文件中,需要确保去掉generation_message()调用的注释,并包含 了消息的所赖的所有依赖项

generation_message(
     DEPENDENCIES
      std_msgs
)

我们已经告知catkin需要知道的一切,然后到catkin工作空间的根目录下使用命令catkin_make编译它,还需运行source devel/setup.bash

还会生成python类代码,不过我没找到

这样的话就定义了自己的消息类型

使用新定义的消息

例message_publisher.py

发布者:

1 #!/usr/bin/env python
 2 import rospy
 3 from basic.msg import Complex
 4 from random import random
 5 
 6 rospy.init_node('message_publisher')
 7 pub=rospy.Publisher('complex',Complex,queue_size='number')
 8 rate=rospy.Rate(2)                                                     
 9 
10 while not rospy.is_shutdown():
11     msg=Complex()
12     msg.real=random()
13     msg.imaginary=random()
14 
15     pub.publish(msg)
16     rate.sleep()

导入你的新消息类型就像导入其他标准的消息类型一样,然后你就能创建消息类的实例了,一但你创建了一个实例,就能给不同的字段赋值,任何没有显示赋值的字段的值都视为未定义

例message_subscriber.py

订阅者:

1 #!/usr/bin/env python                                                  
 2 import rospy
 3 from basic.msg import Complex
 4 def callback(msg):
 5     print 'Real:',msg.real
 6     print 'Imaginary:',msg.imaginary
 7     print 
 8  
 9 rospy.init_node('message_subscriber')
10 sub=rospy.Subscriber('complex',Complex,callback)
11 rospy.spin()

 然后运行节点就能看到消息发布被订阅了

如下

qqtsj@qqtsj-Nitro-AN515-51:~/catkin_ws$ rosrun basic message_subscriber.py 
Real: 0.704654157162
Imaginary: 0.752943456173

Real: 0.425590842962
Imaginary: 0.338110715151

Real: 0.839413583279
Imaginary: 0.193065851927

Real: 0.748129308224
Imaginary: 0.966568589211

Real: 0.105406813323
Imaginary: 0.329872667789

Real: 0.735990107059
Imaginary: 0.0604162067175

Real: 0.208381637931
Imaginary: 0.373496472836

Real: 0.959863781929
Imaginary: 0.433356046677

Real: 0.11781616509
Imaginary: 0.00478984974325

Real: 0.0790134221315
Imaginary: 0.709028303623

Real: 0.11989364773
Imaginary: 0.0398832447827

然后rosmsg命令能让你看到某个消息类型的内容

qqtsj@qqtsj-Nitro-AN515-51:~/catkin_ws$ rosmsg show Complex
[basic/Complex]:
float32 real
float32 imaginary
原文地址:https://www.cnblogs.com/tanshengjiang/p/11776940.html