使用Protobuf来定义ROS消息格式[C++/Python]

一般我们自定义ROS消息使用ros_msgs来定义的,但是考虑到proto在传输消息优于ros自定义的消息格式,我们这里使用proto来定义ros消息
问题来源:之前看apollo的代码,就发现里面的消息使用proto来传输的,那我们我们自己用如何定义和使用呢,主要参考代码https://github.com/ApolloAuto/apollo-platform仓库里面的ros下面的pb_msgs里面的代码
下面的内容也都是里面的代码粘贴复制,感兴趣的直接看源代码就可以

1.生成自定义的proto_msg

https://github.com/ApolloAuto/apollo-platform/blob/master/ros/pb_msgs

1.1 代码结构

使用Protobuf来定义ROS消息格式[C++/Python]_第1张图片

1.2 代码

1.2.1 msg
__init__.py
 import pkgutil 

__path__ = pkgutil.extend_path(__path__, "modules")
for importer, modname, ispkg in pkgutil.walk_packages(path=__path__, prefix=__name__+'.'):
    if modname.endswith("pb2"):
        try:
            exec("from %s import *" % modname)
        except:
            pass
1.2.2 proto
time.proto
syntax = "proto2";

package pb_msgs;

message Time {
    required int64 sec = 1;
    required int64 nsec = 2;
}
1.2.3 src/pb_msgs
__init__.py
#空
1.2.4 CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(pb_msgs)

find_package(catkin REQUIRED COMPONENTS genmsg gencpp genpy)

# catkin_python_setup()

add_proto_files(
    DIRECTORY proto
    FILES
    time.proto
)
generate_messages()

catkin_package(
#   INCLUDE_DIRS include
  LIBRARIES pb_msgs_proto
#  CATKIN_DEPENDS other_catkin_pkg
  DEPENDS genmsg gencpp genpy
)

if(NOT EXISTS msg)
  file(MAKE_DIRECTORY msg)
endif()

install(DIRECTORY proto msg
  DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
1.2.4 package.xml
<package>
<name>pb_msgsname>
  <version>1.0.0version>
  <description>
    Protobuf messages for adu common proto.
  description>
  <maintainer email="[email protected]">Apollo Authorsmaintainer>
  <license>BSDlicense>
  <buildtool_depend>catkinbuildtool_depend>
  <build_depend>roscppbuild_depend>
  <build_depend>gencppbuild_depend>
  <build_depend>genmsgbuild_depend>
  <build_depend>genpybuild_depend>
  <run_depend>roscpprun_depend>
  <run_depend>gencpprun_depend>
  <run_depend>genmsgrun_depend>
  <run_depend>genpyrun_depend>

package>
1.2.5 setup.py
#!/usr/bin/env python

from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup

d = generate_distutils_setup(
    packages=['pb_msgs'],
    package_dir={'': 'src'},
)

setup(**d)

你可能感兴趣的:(ros)