Main Content

ros2genmsg

Generate custom messages from ROS 2 definitions

Description

example

ros2genmsg(folderpath) generates ROS 2 custom messages by reading ROS 2 custom messages and service definitions in the specified folder path. The function folder must contain one or more ROS 2 package. These packages contain the message definitions in .msg files and the service definitions in .srv files.

After you generate the custom messages, you can send and receive them in MATLAB® like all the other supported messages. You can create these messages using ros2message or view the list of messages by entering ros2 msg list at the MATLAB Command Window.

Note

  • To generate custom messages for ROS 2, you must build the ROS 2 packages. This process requires you to have a C++ compiler for your platform. For more information, see ROS Toolbox System Requirements.

  • With every new release of MATLAB, you must regenerate the custom messages from the ROS 2 definitions.

  • Custom messages that you generate in MATLAB now support eProsima Fast DDS and Eclipse Cyclone DDS middleware. For more information on ROS middleware implementations, see Switching Between ROS Middleware Implementations.

example

ros2genmsg(folderpath,Name=Value) specifies additional options using one or more name-value arguments.

Examples

collapse all

Custom messages are messages that you define. Use custom messages to extend the set of message types currently supported in ROS 2. If you are sending and receiving supported message types, you do not need to use custom messages. To see a list of supported message types, enter ros2 msg list in the MATLAB® Command Window. For more information about supported ROS 2 messages, see Work with Basic ROS 2 Messages.

If this if your first time working with ROS 2 custom messages, see ROS Toolbox System Requirements.

ROS 2 custom messages are specified in ROS 2 package folders that contain a folder named msg. The msg folder contains all your custom message type definitions. For example, the example_b_msgs package in the custom folder, has this folder and file structure.

The package contains the custom message type Standalone.msg. MATLAB uses these files to generate the necessary files for using the custom messages contained in the package.

In this example, you create ROS 2 custom messages in MATLAB. You must have a ROS 2 package that contains the required msg file.

After ensuring that your custom message package is correct, you specify the path to the parent folder and call ros2genmsg with the specified path. The following example provided three messages example_package_a, example_package_b, and example_package_c that have dependencies. This example also illustrates that you can use a folder containing multiple messages and generate them all at the same time.

Open a new MATLAB session and create a custom message folder in a local folder.

folderPath = fullfile(pwd,"custom");
copyfile("example_*_msgs",folderPath);

Specify the folder path for custom message files and use ros2genmsg to create custom messages.

ros2genmsg(folderPath)
Identifying message files in folder 'C:/Work/custom'.Done.
Removing previous version of Python virtual environment.Done.
Creating a Python virtual environment.Done.
Adding required Python packages to virtual environment.Done.
Copying include folders.Done.
Copying libraries.Done.
Validating message files in folder 'C:/Work/custom'.Done.
[3/3] Generating MATLAB interfaces for custom message packages... Done.
Running colcon build in folder 'C:/Work/custom/matlab_msg_gen/win64'.
Build in progress. This may take several minutes...
Build succeeded.build log

Call ros2 msg list to verify creation of new custom messages.

ros2 msg list
action_msgs/CancelGoalRequest
action_msgs/CancelGoalResponse
action_msgs/GoalInfo
action_msgs/GoalStatus
action_msgs/GoalStatusArray
actionlib_msgs/GoalID
actionlib_msgs/GoalStatus
actionlib_msgs/GoalStatusArray
builtin_interfaces/Duration
builtin_interfaces/Time
composition_interfaces/ListNodesRequest
composition_interfaces/ListNodesResponse
composition_interfaces/LoadNodeRequest
composition_interfaces/LoadNodeResponse
composition_interfaces/UnloadNodeRequest
composition_interfaces/UnloadNodeResponse
diagnostic_msgs/AddDiagnosticsRequest
diagnostic_msgs/AddDiagnosticsResponse
diagnostic_msgs/DiagnosticArray
diagnostic_msgs/DiagnosticStatus
diagnostic_msgs/KeyValue
diagnostic_msgs/SelfTestRequest
diagnostic_msgs/SelfTestResponse
example_a_msgs/DependsOnB
example_b_msgs/Standalone
example_c_msgs/DependsOnB
example_interfaces/AddTwoIntsRequest
example_interfaces/AddTwoIntsResponse
example_interfaces/Bool
example_interfaces/Byte
example_interfaces/ByteMultiArray
example_interfaces/Char
example_interfaces/Empty
example_interfaces/Float32
example_interfaces/Float32MultiArray
example_interfaces/Float64
example_interfaces/Float64MultiArray
example_interfaces/Int16
example_interfaces/Int16MultiArray
example_interfaces/Int32
example_interfaces/Int32MultiArray
example_interfaces/Int64
example_interfaces/Int64MultiArray
example_interfaces/Int8
example_interfaces/Int8MultiArray
example_interfaces/MultiArrayDimension
example_interfaces/MultiArrayLayout
example_interfaces/SetBoolRequest
example_interfaces/SetBoolResponse
example_interfaces/String
example_interfaces/TriggerRequest
example_interfaces/TriggerResponse
example_interfaces/UInt16
example_interfaces/UInt16MultiArray
example_interfaces/UInt32
example_interfaces/UInt32MultiArray
example_interfaces/UInt64
example_interfaces/UInt64MultiArray
example_interfaces/UInt8
example_interfaces/UInt8MultiArray
example_interfaces/WString
geometry_msgs/Accel
geometry_msgs/AccelStamped
geometry_msgs/AccelWithCovariance
geometry_msgs/AccelWithCovarianceStamped
geometry_msgs/Inertia
geometry_msgs/InertiaStamped
geometry_msgs/Point
geometry_msgs/Point32
geometry_msgs/PointStamped
geometry_msgs/Polygon
geometry_msgs/PolygonStamped
geometry_msgs/Pose
geometry_msgs/Pose2D
geometry_msgs/PoseArray
geometry_msgs/PoseStamped
geometry_msgs/PoseWithCovariance
geometry_msgs/PoseWithCovarianceStamped
geometry_msgs/Quaternion
geometry_msgs/QuaternionStamped
geometry_msgs/Transform
geometry_msgs/TransformStamped
geometry_msgs/Twist
geometry_msgs/TwistStamped
geometry_msgs/TwistWithCovariance
geometry_msgs/TwistWithCovarianceStamped
geometry_msgs/Vector3
geometry_msgs/Vector3Stamped
geometry_msgs/Wrench
geometry_msgs/WrenchStamped
lifecycle_msgs/ChangeStateRequest
lifecycle_msgs/ChangeStateResponse
lifecycle_msgs/GetAvailableStatesRequest
lifecycle_msgs/GetAvailableStatesResponse
lifecycle_msgs/GetAvailableTransitionsRequest
lifecycle_msgs/GetAvailableTransitionsResponse
lifecycle_msgs/GetStateRequest
lifecycle_msgs/GetStateResponse
lifecycle_msgs/State
lifecycle_msgs/Transition
lifecycle_msgs/TransitionDescription
lifecycle_msgs/TransitionEvent
logging_demo/ConfigLoggerRequest
logging_demo/ConfigLoggerResponse
map_msgs/GetMapROIRequest
map_msgs/GetMapROIResponse
map_msgs/GetPointMapROIRequest
map_msgs/GetPointMapROIResponse
map_msgs/GetPointMapRequest
map_msgs/GetPointMapResponse
map_msgs/OccupancyGridUpdate
map_msgs/PointCloud2Update
map_msgs/ProjectedMap
map_msgs/ProjectedMapInfo
map_msgs/ProjectedMapsInfoRequest
map_msgs/ProjectedMapsInfoResponse
map_msgs/SaveMapRequest
map_msgs/SaveMapResponse
map_msgs/SetMapProjectionsRequest
map_msgs/SetMapProjectionsResponse
nav_msgs/GetMapRequest
nav_msgs/GetMapResponse
nav_msgs/GetPlanRequest
nav_msgs/GetPlanResponse
nav_msgs/GridCells
nav_msgs/MapMetaData
nav_msgs/OccupancyGrid
nav_msgs/Odometry
nav_msgs/Path
nav_msgs/SetMapRequest
nav_msgs/SetMapResponse
pendulum_msgs/JointCommand
pendulum_msgs/JointState
pendulum_msgs/RttestResults
rcl_interfaces/DescribeParametersRequest
rcl_interfaces/DescribeParametersResponse
rcl_interfaces/FloatingPointRange
rcl_interfaces/GetParameterTypesRequest
rcl_interfaces/GetParameterTypesResponse
rcl_interfaces/GetParametersRequest
rcl_interfaces/GetParametersResponse
rcl_interfaces/IntegerRange
rcl_interfaces/ListParametersRequest
rcl_interfaces/ListParametersResponse
rcl_interfaces/ListParametersResult
rcl_interfaces/Log
rcl_interfaces/Parameter
rcl_interfaces/ParameterDescriptor
rcl_interfaces/ParameterEvent
rcl_interfaces/ParameterEventDescriptors
rcl_interfaces/ParameterType
rcl_interfaces/ParameterValue
rcl_interfaces/SetParametersAtomicallyRequest
rcl_interfaces/SetParametersAtomicallyResponse
rcl_interfaces/SetParametersRequest
rcl_interfaces/SetParametersResponse
rcl_interfaces/SetParametersResult
rosgraph_msgs/Clock
sensor_msgs/BatteryState
sensor_msgs/CameraInfo
sensor_msgs/ChannelFloat32
sensor_msgs/CompressedImage
sensor_msgs/FluidPressure
sensor_msgs/Illuminance
sensor_msgs/Image
sensor_msgs/Imu
sensor_msgs/JointState
sensor_msgs/Joy
sensor_msgs/JoyFeedback
sensor_msgs/JoyFeedbackArray
sensor_msgs/LaserEcho
sensor_msgs/LaserScan
sensor_msgs/MagneticField
sensor_msgs/MultiDOFJointState
sensor_msgs/MultiEchoLaserScan
sensor_msgs/NavSatFix
sensor_msgs/NavSatStatus
sensor_msgs/PointCloud
sensor_msgs/PointCloud2
sensor_msgs/PointField
sensor_msgs/Range
sensor_msgs/RegionOfInterest
sensor_msgs/RelativeHumidity
sensor_msgs/SetCameraInfoRequest
sensor_msgs/SetCameraInfoResponse
sensor_msgs/Temperature
sensor_msgs/TimeReference
shape_msgs/Mesh
shape_msgs/MeshTriangle
shape_msgs/Plane
shape_msgs/SolidPrimitive
simple_msgs/AddTwoIntsRequest
simple_msgs/AddTwoIntsResponse
simple_msgs/Num
statistics_msgs/MetricsMessage
statistics_msgs/StatisticDataPoint
statistics_msgs/StatisticDataType
std_msgs/Bool
std_msgs/Byte
std_msgs/ByteMultiArray
std_msgs/Char
std_msgs/ColorRGBA
std_msgs/Empty
std_msgs/Float32
std_msgs/Float32MultiArray
std_msgs/Float64
std_msgs/Float64MultiArray
std_msgs/Header
std_msgs/Int16
std_msgs/Int16MultiArray
std_msgs/Int32
std_msgs/Int32MultiArray
std_msgs/Int64
std_msgs/Int64MultiArray
std_msgs/Int8
std_msgs/Int8MultiArray
std_msgs/MultiArrayDimension
std_msgs/MultiArrayLayout
std_msgs/String
std_msgs/UInt16
std_msgs/UInt16MultiArray
std_msgs/UInt32
std_msgs/UInt32MultiArray
std_msgs/UInt64
std_msgs/UInt64MultiArray
std_msgs/UInt8
std_msgs/UInt8MultiArray
std_srvs/EmptyRequest
std_srvs/EmptyResponse
std_srvs/SetBoolRequest
std_srvs/SetBoolResponse
std_srvs/TriggerRequest
std_srvs/TriggerResponse
stereo_msgs/DisparityImage
test_msgs/Arrays
test_msgs/ArraysRequest
test_msgs/ArraysResponse
test_msgs/BasicTypes
test_msgs/BasicTypesRequest
test_msgs/BasicTypesResponse
test_msgs/BoundedSequences
test_msgs/Builtins
test_msgs/Constants
test_msgs/Defaults
test_msgs/Empty
test_msgs/EmptyRequest
test_msgs/EmptyResponse
test_msgs/MultiNested
test_msgs/Nested
test_msgs/Strings
test_msgs/UnboundedSequences
test_msgs/WStrings
trajectory_msgs/JointTrajectory
trajectory_msgs/JointTrajectoryPoint
trajectory_msgs/MultiDOFJointTrajectory
trajectory_msgs/MultiDOFJointTrajectoryPoint
unique_identifier_msgs/UUID
visualization_msgs/GetInteractiveMarkersRequest
visualization_msgs/GetInteractiveMarkersResponse
visualization_msgs/ImageMarker
visualization_msgs/InteractiveMarker
visualization_msgs/InteractiveMarkerControl
visualization_msgs/InteractiveMarkerFeedback
visualization_msgs/InteractiveMarkerInit
visualization_msgs/InteractiveMarkerPose
visualization_msgs/InteractiveMarkerUpdate
visualization_msgs/Marker
visualization_msgs/MarkerArray
visualization_msgs/MenuEntry

You can now use the above created custom message as the standard messages. For more information on sending and receiving messages, see Exchange Data with ROS 2 Publishers and Subscribers.

Create a publisher to use example_b_msgs/Standalone message.

node = ros2node("/node_1");
pub = ros2publisher(node,"/example_topic","example_b_msgs/Standalone");

Create a subscriber on the same topic.

sub = ros2subscriber(node,"/example_topic");

Create a message and send the message.

custom_msg = ros2message("example_b_msgs/Standalone");
custom_msg.int_property = uint32(12);
custom_msg.string_property='This is ROS 2 custom message example';
send(pub,custom_msg);
pause(3) % Allow a few seconds for the message to arrive

Use LatestMessage field to know the recent message received by the subscriber.

sub.LatestMessage
ans = struct with fields:
        MessageType: 'example_b_msgs/Standalone'
       int_property: 12
    string_property: 'This is ROS 2 custom message example'

Remove the created ROS objects.

clear node pub sub

Replacing Definitions of Built-In Messages with Custom Definitions

MATLAB provides a lot of built-in ROS 2 message types. You can replace the definitions of those message types with new definitions using the same custom message creation workflow detailed above. When you are replacing the definitions of a built-in message package, you must ensure that the custom message package folder contains new definitions (.msg files) for all the message types in the corresponding built-in message package.

In this example, you create a shareable ROS 2 custom message package in MATLAB. You must have a ROS 2 package that contains the required msg file. This figure shows an example of an appropriate folder structure.

After you prepare your custom message package folder, you specify the path to the parent folder and call ros2genmsg with the specified path.

Open a new MATLAB session and create a custom message package folder in a local folder. Choose a short folder path when you generate custom messages on a Windows machine to avoid limitations on the number of characters in the folder path. For example,

genDir = fullfile('C:/test/ros2CustomMessages')

genDir = fullfile(pwd,'ros2CustomMessages');
packagePath = fullfile(genDir,'simple_msgs');
mkdir(packagePath)

Create a folder named msg inside the custom message package folder.

mkdir(packagePath,'msg')

Create a file named .msg inside the msg folder.

messageDefinition = {'int64 num'};

fileID = fopen(fullfile(packagePath,'msg', ...
               'Num.msg'),'w');
fprintf(fileID,'%s\n',messageDefinition{:});
fclose(fileID);

Create a folder named srv inside the custom message package folder.

mkdir(packagePath,'srv')

Create a file named .srv inside the srv folder.

serviceDefinition = {'int64 a'
                     'int64 b'
                     '---'
                     'int64 sum'};
 
fileID = fopen(fullfile(packagePath,'srv', ...
               'AddTwoInts.srv'),'w');
fprintf(fileID,'%s\n',serviceDefinition{:});
fclose(fileID);

Generate custom messages from ROS 2 definitions in .msg and .srv files. Use the CreateShareableFile name-value argument to create a shareable ZIP archive of the generated custom messages.

For information about how to use use this ZIP archive to register the custom messages in another machine, see ros2RegisterMessages.

ros2genmsg(genDir,CreateShareableFile=true);
Identifying message files in folder 'C:/test/ros2CustomMessages'.Done.
Creating a Python virtual environment.Done.
Adding required Python packages to virtual environment.Done.
Copying include folders.Done.
Copying libraries.Done.
Validating message files in folder 'C:/test/ros2CustomMessages'.Done.
[1/1] Generating MATLAB interfaces for custom message packages... Done.
Running colcon build in folder 'C:/test/ros2CustomMessages/matlab_msg_gen/win64'.
Build in progress. This may take several minutes...
Build succeeded.build log
Generating zip file in the folder 'C:/test/ros2CustomMessages'.Done.

Verify creation of the new custom messages by entering ros2 msg list in the Command Window.

Input Arguments

collapse all

Path to the ROS interfaces folder, which is the parent folder of ROS message packages, specified as a string scalar or character vector. The parent folder must contain a package .xml and package folders. These folders contain a folder named /msg with .msg files for message definitions and a folder named /srv with .srv files for service definitions. For more information, see About ROS 2 Interfaces.

Example: 'C:/test/ros2CustomMessages'

Data Types: char | string

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: BuildConfiguration='fasterruns'

Build configuration, specified as the comma-separated pair consisting of BuildConfiguration and a character vector or string scalar containing 'fasterbuilds' or 'fasterruns'.

  • 'fasterbuilds' — Build the message libraries with compiler optimizations for shorter build times.

  • 'fasterruns' — Build the message libraries with compiler optimizations for faster execution.

Example: ros2genmsg('C:/test/ros2CustomMessages',BuildConfiguration='fasterruns')

Data Types: char | string

Option to create a sharable ZIP archive, specified as a numeric or logical 1 (true) or 0 (false).

When you specify this argument as 1 (true), the function creates a ZIP archive be compressing the install folder in the matlab_msg_gen folder. You can use this file with another machine running on the same platform and using the same MATLAB version.

When you specify this argument as 0 (false), the function does not create a ZIP archive.

Example: ros2genmsg('C:/test/ros2CustomMessages',CreateShareableFile=true)

Data Types: logical

Limitations

Restart Nodes

  • After you generate custom messages, restart any existing ROS 2 nodes.

Code Generation with custom messages:

  • Custom message and service types can be used with ROS 2 functionality for generating C++ code for a standalone ROS 2 node. The generated TGZ archive includes definitions for the custom messages, but not the ROS 2 custom message packages. When the function builds the generated code in the destination, the custom message packages must be available in the colcon workspace. Set this workspace as your current working directory. Install or copy the custom message package to your system before building the generated code.

MATLAB Compiler

  • MATLAB Compiler™ software do not support ROS custom messages and the ros2genmsg function.

Version History

Introduced in R2019b

expand all