Skip to content

2.1.3 Topic Communication Custom msg

In the ROS communication protocol, the data carrier is a relatively important component. ROS encapsulates some native data types through std_msgs, such as: String, Int32, Int64, Char, Bool, Empty... However, these data types generally only contain one data field. The simplicity of the structure implies functional limitations. When transmitting some complex data, such as LiDAR information... std_msgs appear inadequate due to poor descriptiveness. In such scenarios, custom message types can be used.

msgs are simple text files, each line has a field type and field name. The available field types are:

  • int8, int16, int32, int64 (or unsigned types: uint*)
  • float32, float64
  • string
  • time, duration
  • other msg files
  • variable-length array[] and fixed-length array[C]

There is also a special type in ROS: Header. The header contains timestamp and coordinate frame information commonly used in ROS. You will often see the first line of a msg file has Header.


Requirement: Create a custom message that contains person information: name, height, age, etc.

Process:

  1. Create the msg file according to the fixed format
  2. Edit the configuration files
  3. Compile to generate intermediate files that can be called by Python or C++

1. Define msg file

Create a new msg directory under the functional package, add the file Person.msg

string name
uint16 age
float64 height

2. Edit configuration files

Add build dependencies and execution dependencies in package.xml

xml
  <build_depend>message_generation</build_depend>
  <exec_depend>message_runtime</exec_depend>
  <!-- 
  exce_depend 以前对应的是 run_depend 现在非法
  -->

Edit msg-related configurations in CMakeLists.txt

find_package(catkin REQUIRED COMPONENTS
  roscpp
  rospy
  std_msgs
  message_generation
)
# Need to include message_generation, must have std_msgs
## Configure msg source files
add_message_files(
  FILES
  Person.msg
)
# Depends on std_msgs when generating messages
generate_messages(
  DEPENDENCIES
  std_msgs
)
# Execution dependencies
catkin_package(
#  INCLUDE_DIRS include
#  LIBRARIES demo02_talker_listener
  CATKIN_DEPENDS roscpp rospy std_msgs message_runtime
#  DEPENDS system_lib
)

3. Compile

View the compiled intermediate files:

Intermediate files needed for Python calls (.../workspace/devel/lib/python3/dist-packages/package_name/msg)

img

Subsequent calls to related msg will be made from these intermediate files.