Main Content

ros2genmsg

Generate custom messages from ROS 2 definitions

Description

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, service definitions in .srv files, and action definitions in .action 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.

example

Examples

collapse all

Use custom messages to extend the set of message types currently supported in ROS 2. Custom messages are messages that you define. 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.

ROS 2 custom message folder 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/GoalInfo
action_msgs/GoalStatusArray
actionlib_msgs/GoalID
actionlib_msgs/GoalStatus
builtin_interfaces/Duration
builtin_interfaces/Time composition_interfaces/ListNodesRequest
composition_interfaces/ListNodesResponse
diagnostic_msgs/AddDiagnosticsRequest
diagnostic_msgs/AddDiagnosticsResponse
example_a_msgs/DependsOnB
example_b_msgs/Standalone
example_interfaces/AddTwoIntsRequest
example_interfaces/AddTwoIntsResponse
example_interfaces/Bool
example_interfaces/Byte...

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.

ROS 2 Custom Messages 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);

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

mkdir(packagePath,'action')

Create a file named .action inside the action folder.

actionDefinition = {'int64 goal'
                    '---'
                    'int64 result'
                    '---'
                    'int64 feedback'};
 
fileID = fopen(fullfile(packagePath,'action', ...
               'Test.action'),'w');
fprintf(fileID,'%s\n',actionDefinition{:});
fclose(fileID);

Generate custom messages from ROS 2 definitions in .msg, .srv and .action 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:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages'.Validating message files in folder 'C:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages'.Done.
Creating a Python virtual environment.Done.
Adding required Python packages to virtual environment.Done.
Copying include folders.Done.
Copying libraries.Done.
Done.
[1/1] Generating MATLAB interfaces for custom message packages... Done.
Running colcon build in folder 'C:/Users/echakrab/OneDrive - MathWorks/Documents/MATLAB/ExampleManager/echakrab.Bdoc23a.ROS2transform/ros-ex71849911/ros2CustomMessages/matlab_msg_gen/win64'.
Build in progress. This may take several minutes...

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

ROS 2 custom messages creation

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, a folder named /srv with .srv files for service definitions, and a folder named /action with .action files for action definitions. For more information, see ROS 2 Topics, ROS 2 Services, and ROS 2 Actions.

Example: 'C:/test/ros2CustomMessages'

Data Types: char | string

Name-Value Arguments

collapse all

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.

Tips

  • During the Microsoft® Visual Studio® installation, ensure that you select Desktop development with C++ workload. This installs the MSVC compiler and all necessary dependencies required to generate custom messages.

  • Ensure that the path to the custom message folder does not exceed 64 characters.

  • Verify that the python environment configuration is correct. For more information, see ROS Toolbox System Requirements.

  • The custom message libraries generated for ROS 2 are user-created files that integrate into the internal ROS workflow. To safeguard these files from unauthorized access and maintain system integrity, set appropriate directory permissions to restrict access to only intended user accounts.

Version History

Introduced in R2019b

expand all