Implementing ROS 2 Concepts
local graph
Chapter 3 — Implementing ROS 2 Concepts
Section titled “Chapter 3 — Implementing ROS 2 Concepts”In the last chapter, we discussed various ROS 2 concepts that we need to know before starting to program with ROS 2.
In this chapter, we will continue with a few topics we left out in Chapter 2. After discussing these concepts, we will start implementing them using rclcpp, the ROS 2 client library for C++.
This chapter will help you build a strong foundation for implementing different ROS 2 concepts. We will see the detailed implementation of ROS 2 concepts using C++ that can be used in various robot use cases. It is very important to understand all these basic ROS 2 concepts before diving into the more advanced concepts of ROS 2.
Here are the important topics we will discuss in this chapter:
- What is a ROS 2 action?
- What is a ROS 2 parameter?
- What is a ROS 2 launch file?
- How do we build a ROS 2 package?
- Introduction to ROS 2 client libraries
- Diving into ROS 2 nodes
- Implementing ROS 2 topics in C++
- Implementing ROS 2 parameters in C++
- Implementing ROS 2 services in C++
- Implementing ROS 2 actions in C++
- Configuring DDS/Zenoh and domain IDs
Technical requirements
Section titled “Technical requirements”To follow along with this chapter, you will need to have a computer/embedded board (e.g., Raspberry Pi, Jetson boards, etc.) with any OS with Ubuntu 24.04 LTS in WSL2, a VM, Docker, or a real machine itself. The reference materials for this chapter can be found in the Chapter03 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter03.
What is a ROS 2 action?
Section titled “What is a ROS 2 action?”Let’s start with ROS 2 actions. We have seen what a ROS 2 service is. It is a request/reply kind of communication; it is suitable for short tasks like enabling/disabling some components in the robot. If the task execution of the service takes time, the client must wait for a reply. There is no option to cancel the service if it is taking longer than expected. Also, there is no feedback from the server node on whether to cancel the request or not. That is where ROS actions come in.
A ROS action is well suited for long-running tasks, such as navigation of the robot from A to B, moving an arm from the current position to the goal position, etc. In these kinds of tasks, the task can take time, and getting feedback on the status of the task will be useful. A ROS action involves two key participants: the action client, which sends a goal and can request feedback or cancel it, and the action server, which receives the goal, processes it, and returns the result, possibly with intermediate feedback. The following image illustrates how a ROS action works.

Figure 3.1: ROS 2 action
Figure 3.1: ROS 2 action
Like a ROS service, we can interact with a ROS 2 action with the ros2 action command. To list the action with its action types, you can use:
ros2 action list -tIf you are running the turtlesim node, you can find the following action with the action type:
/turtle1/rotate_absolute [turtlesim/action/RotateAbsolute]If you want to see the action field, you can use:
ros2 interface show turtlesim/action/RotateAbsoluteYou will get the following output:
# The desired heading in radiansfloat32 theta---# The angular displacement in radians to the starting positionfloat32 delta---# The remaining rotation in radiansfloat32 remainingThe above action definition has three main fields: the first one is the goal request field (theta), the second one is the result (delta), and the third one is the feedback (remaining). The action definition is for rotating the turtle at a certain angle. Once we send the goal angle, the client will start getting feedback about the remaining angle. This is stored in the remaining variable, and after completing the rotation, the result will be stored in the delta variable, which is the angular displacement in radians from the starting position.
Like the ROS 2 service, you can use the ros2 action command to send the goal values. The goal value is 1.57 in radians. The send_goal command is used to send the action goal:
ros2 action send_goal --feedback /turtle1/rotate_absolute turtlesim/action/RotateAbsolute "{theta: 1.5708}"Once you execute the command, you will see the turtle rotating 90 degrees in the anticlockwise direction, and after that, you will see a message like this in the terminal:
Feedback: remaining: 0.018799901008605957Result: delta: -3.1040000915527344Goal finished with status: SUCCEEDEDAnother command you can try is ros2 action info, which shows the information of this ROS 2 action, like which node is the action server and which node is the action client:
ros2 action info /turtle1/rotate_absoluteWe can refer to the page linked here to find out more about ROS 2 actions [1].
So far, we have briefly covered the ROS topic, service, and action concepts. Now, we can discuss another useful concept: the ROS parameter.
What is a ROS parameter?
Section titled “What is a ROS parameter?”A ROS node can be configured using parameters. It can store parameters such as integers, floats, Booleans, strings, and lists. The node can read these parameters and control the program flow. These parameter values can be set/get through the ros2 param command-line tool. Commonly, in robotic applications, we use a YAML file to hold this parameter. The main reason is that there will be multiple parameters per node, and there can be multiple nodes inside a robotic application. Keeping parameters inside a YAML file will give great flexibility in saving and loading during the startup of the node. The ROS launch files help to load multiple nodes along with all these parameter files. ROS 2 parameters are stored in the nodes themselves, and whenever there is a change in the parameter, it can be handled inside the node using a callback if required. We will see more about the launch file in the next section.
Here is the ROS 2 command-line tool to list set/get parameters.
Here is how we list the parameters of the running nodes:
ros2 param listHere are the main parameters of the /turtlesim node:
/turtlesim: background_b background_g background_r holonomic ................You can see the r, g, b color values as parameters, which refer to the background color of the turtlesim. We can change these values through the command line and the color of the background color will change instantly.
Here is the syntax and an example of setting the parameter value:
ros2 param set <node_name> <parameter_name> <value>ros2 param set /turtlesim background_r 150After setting the red element of the background to 150, you can see that the background color changes from blue to violet.
Also, if you want to get the value of some parameter, you can use ros2 param get.
Here is the syntax of the ros2 param get command:
ros2 param get <node_name> <parameter_name>In this example, we are retrieving the same parameter we have already set, and we will get the same value we have set as the output:
ros2 param get /turtlesim background_rHere is what the output looks like:
Integer value is: 150We can even initialize the ROS 2 parameters during the initialization of the node by passing them as a command-line argument. You can use --ros-args -p to mention the parameters as command-line arguments. Here is an example usage:
ros2 run turtlesim turtlesim_node --ros-args -p background_r:=255 -p background_g:=255 -p background_b:=255You can learn more about ROS parameters using the following link [2].
Now, let us look at the ROS launch file in the following section.
What is a ROS 2 launch file?
Section titled “What is a ROS 2 launch file?”ROS 2 launch files are powerful tools for launching multiple nodes, configuring parameters, remapping topic names, and controlling the execution of nodes in a complex robotic system. Launch files are extremely useful if your application has multiple nodes. It is not easy to run each node using the ros2 run command, but launch files provide a way to run nodes with all their settings, and you can run these launch files with a single command.
The ros2 launch command is used to launch a launch file. Launch files are kept inside the ros 2 package. In ROS 2, the launch file can be written using Python, XML, and YAML. The Python launch file gives more flexibility compared to other options, especially in complex robotics applications. If you are writing the Python launch file, the extension will be *.py, and usually a naming convention like *.launch.py is followed.
The syntax of the ros2 launch command is given below:
ros2 launch pkg_name launch_file_name.pyHere is an example of running a launch file. This launch file is already inside the demo_nodes_cpp package:
ros2 launch demo_nodes_cpp talker_listener_launch.pyThis launch file will start the talker and listener, and you will see the following message:
[INFO] [launch]: Default logging verbosity is set to INFO[INFO] [talker-1]: process started with pid [1505][INFO] [listener-2]: process started with pid [1506][talker-1] [INFO] [1726427687.713985453] [talker]: Publishing: 'Hello World: 1'[listener-2] [INFO] [1726427687.714343316] [listener]: I heard: [Hello World: 1][talker-1] [INFO] [1726427688.712840861] [talker]: Publishing: 'Hello World: 2'[listener-2] [INFO] [1726427688.713186962] [listener]: I heard: [Hello World: 2]Here is what this launch file looks like:
"""Launch a talker and a listener."""from launch import LaunchDescriptionimport launch_ros.actionsdef generate_launch_description(): return LaunchDescription([ launch_ros.actions.Node( package='demo_nodes_cpp', executable='talker', output='screen'), launch_ros.actions.Node( package='demo_nodes_cpp', executable='listener', output='screen'), ])In this launch file, you can find a set of Python modules that are used inside the launch file. You can also find a single function called generate_launch_description(). This function is standard in ROS 2 launch files, and whenever we run a launch file, it will call this function and should return a LaunchDescription object. The LaunchDescription class is a container object for the launch file, which has information about what nodes, parameters, etc. have to be launched. We can also see the Node() class, which helps to run a node with its configuration. Node objects are put inside the LaunchDescription and returned by the generate_launch_description(), which runs the nodes inside it.
We will discuss more details about the ROS 2 launch file in the next chapter. Here is the link to read more about ROS 2 launch files [3].
After discussing the most important ROS 2 concepts, let’s get hands-on with ROS 2 demo packages.
Building a ROS 2 package
Section titled “Building a ROS 2 package”Packages are basic software units in ROS 2. They are organized in a ROS 2 workspace, where we can build the packages and run the nodes. Creating a ROS 2 workspace is very easy; we can create any number of ROS workspaces in our OS. The main purpose of creating a ROS workspace is to organize a set of packages. For example, if we are working on a navigation project, we can keep all the navigation-related packages inside this workspace. This is a good practice to get into to organize the robot packages.
There are two types of workspaces in ROS 2. First is the base workspace, which refers to the ROS 2 installation itself. We are adding the source /opt/ros/<distro>/setup.bash command in the ~/.bashrc file to source the base workspace. If the base workspace is not sourced, the core ROS packages and tools will not be visible in the terminal. The next type of workspace is an overlay workspace. These are user- created workspaces. Once created, you can build the workspace and overlay it on the base workspace by sourcing its setup.bash file in the install folder. We can create multiple workspaces in ROS 2 and overlay them.
Let’s see the instruction to create an overlay workspace in ROS 2.
Creating a ROS 2 workspace
Section titled “Creating a ROS 2 workspace”The ROS 2 workspace is simply a folder that contains the src subfolder. Here is a command to create a ROS 2 workspace called master_ros2_ws in the home folder. The command also creates a src folder inside the master_ ros2_ws:
mkdir -p ~/master_ros2_ws/srcAfter creating both folders, switch to the src folder. Here is where we can create new packages or copy the existing packages:
cd ~/master_ros2_ws/srcOnce you are done with the packages, switch to the ROS 2 workspace folder:
cd ~/master_ros2_wsNow we can build the workspace. We can build the workspace even without any packages in the workspace.
Building a workspace
Section titled “Building a workspace”Before building the workspace, it is best to use the following command to install the dependencies of these packages:
rosdep install -i --from-path src --rosdistro jazzy -yThe rosdep command finds the dependencies of the packages inside the src folder and checks whether the packages have already been installed on the OS. If not installed, they will be automatically installed. This is a handy command for managing dependency issues in ROS 2.
After installing the dependencies, you can finally build a workspace.
You can use the following command to build the packages inside the workspace:
colcon buildThe colcon command is the build tool commonly used in ROS 2 to build the packages inside the ROS 2 workspace. We have to be in the ROS 2 workspace folder before building the packages. We can either build all packages or selectively build the packages in the workspace. The colcon build command will build all the packages inside the ROS 2 workspace. The colcon build --packages-select <package_name> command will selectively build the packages in the workspace. The colcon build --symlink-install is another command to build the workspace. The symlink-install part creates symbolic links (symlinks) in the install/ directory instead of copying files. This is a good option when you are using ROS 2 Python nodes. If we modify the Python node, we don’t have to rebuild the package because there is no copying to the install folder, but the actual node is already linked in the install directory.
Once you execute this command, you can see messages confirming that these packages have been built. The building of packages involves building the source code, like C++. After successfully building, you can find three main folders along with the src folder, which are build, logs, and install. The install folder is where the installed executable, scripts, and configuration files are stored, and the build folder is where the intermediate build files are stored. The logs folder contains log messages of ROS 2 nodes. You can read more about the colcon command using the following link [4].
After successfully building the workspace, we can add an overlay to the workspace using the following command:
source ~/master_ros2_ws/install/setup.bashAfter this overlay, we can run the nodes and launch files inside these packages.
We will learn more about ROS workspaces in the next chapter. You can read more about ROS workspaces with this link [5].
We have discussed most of the important concepts in ROS 2. Now, let us see how we can implement these concepts in our ROS 2 code.
Introduction to ROS 2 client libraries
Section titled “Introduction to ROS 2 client libraries”The ROS 2 concepts we have seen in this chapter can be implemented in our nodes. We can create any number of topics, services, actions, and parameters in our ROS nodes. So, how can we implement these concepts in our program? The answer is ROS 2 client libraries. ROS 2 comes with a set of libraries called client libraries. These libraries provide APIs that allow users to implement all the concepts in ROS 2. There are two popular client libraries that ROS 2 officially supports. Those are rclcpp and rclpy. The rclcpp library is the client library for C++, and rclpy is the client library for Python. As developers, we only need to learn the APIs provided by these libraries to implement ROS 2 nodes.
We can choose the client library for our application. If you are working with faster and more efficient code, you can go with the C++ client library, and if you require faster development time, you can go with Python. One important thing to note is that ROS 2 nodes written in different client libraries can communicate and share messages with each other.
All client libraries in ROS 2 are built on a common layer called the ROS Client Library (rcl) [6]. This layer implements logic and behavior of ROS concepts that are not specific to any language. This makes the client library development easier for any language.
There are multiple client libraries in ROS 2, other than the two previously mentioned official libraries. A list is given below. These libraries are community-maintained:
- Rust:
rclrsis the client library for writing ROS 2 nodes in Rust. - Node.js:
rclnodejsis a Node.js client for ROS 2. - JVM and Android:
rcljavais the ROS 2 Java client, andros2_java_androidis the Android bindings for ROS 2. rclc: This is a client library for C programming.- C#/.NET:
rcldotnetis a C#/.NET client library for ROS 2.
We can also write a client library for a programming language. Here is the API of rcl to implement language-specific client libraries [7].
You can refer to the following link if you want to read more about ROS 2 client libraries[8].
We have covered the basics of ROS 2 client libraries. Now, let’s explore more concepts relating to the ROS 2 node before implementing ROS 2 nodes using C++.
Diving into ROS 2 nodes
Section titled “Diving into ROS 2 nodes”In Chapter 2, we discussed what a ROS 2 node is. When we run a ROS 2 program/executable, it can start a single or multiple nodes. In ROS 2, a node is a fundamental component of a robotic system that performs a specific task, such as sensor data processing, actuation, or communication. While a node is often associated with a process, ROS 2 allows multiple nodes to exist within a single process, offering greater flexibility and efficiency.
According to the ROS 2 documentation, “ A node is a participant in the ROS 2 graph, which uses a client library to communicate with other nodes. Nodes can communicate with other nodes within the same process, in a different process, or on a different machine. Nodes are typically the unit of computation in a ROS graph; each node should do one logical thing.”
Depending on the robotics application in ROS 2, multiple nodes can work and communicate together to accomplish a robotics application. Nodes in ROS 2 use topics, services, and actions to communicate with each other. We can run nodes in the same machine or multiple machines, and it can communicate over a network. This allows developers to build complex robotics applications that are scalable and modular.
Different types of ROS 2 nodes
Section titled “Different types of ROS 2 nodes”ROS 2 comes with different types of nodes. Here is a comparison of different types of nodes, their advantages, and their disadvantages.
Standard (non-composable) nodes
Section titled “Standard (non-composable) nodes”Definition: A non-composable node in ROS 2 runs as an independent process with its own memory space. An executor manages how a node processes callbacks, using single- or multithreaded models. The executors are responsible for coordinating the execution of callbacks (like subscribe callbacks/functions) in ROS 2 nodes. There are single-threaded executors and multithreaded executors. A single-threaded executor executes the callbacks of a node in a single thread, whereas a multithreaded executor executes in parallel using multiple threads, which allows greater concurrency.
The executor in ROS 2 acts as a scheduler, deciding when the callback has to run. When multiple nodes are loaded into the container, the executor helps manage the callbacks of all nodes within that container. Depending on the choice of executor type, the nodes’ callbacks execute either sequentially or in parallel (multiple threads).
You can run multiple nodes in one process by manually creating them and sharing an executor. This offers isolation and simplicity, but with higher resource overhead. They can be individually launched from the command line or launch files. Non-composable nodes are isolated processes, so in terms of CPU usage, more memory will be consumed, and there will be potential latency in communication between nodes. There are advantages to this method; for example, if one node crashes, it will not affect the other nodes. This makes the system more robust in some situations.
Usage: It can be used where the nodes need to be less dependent on one another, meaning a crash of one node will not directly make the other node crash.
Example: An example of a non-composable node is a standalone sensor driver node like LIDAR, camera, etc., which reads sensor data and publishes it. The other nodes can subscribe to these topics for processing. The driver node can independently run without depending on other nodes.
Composable/component nodes
Section titled “Composable/component nodes”Definition: In composable nodes, we can load multiple nodes into a container and execute all nodes in the same process along with other nodes. A container in ROS 2 is essentially a process that can host multiple composable nodes. It works like a node manager. The container uses ROS 2 (usually multithreaded) to manage all loaded components. Composable nodes allow multiple nodes to share computational resources and memory, thereby reducing communication latency through zero-copy communication and improving overall efficiency. They provide a more modular and resource-efficient design. These nodes can be dynamically loaded and unloaded into a container at runtime.
Usage: Composable nodes are a good choice if many nodes need to communicate frequently, like in a robot navigation system. This will help minimize the communication overhead.
Example: Here is one example of composable nodes. Node 1 reads from a LIDAR sensor and publishes LIDAR data, Node 2 creates a map using LIDAR data, and Node 3 navigates the robot using the map created. We can execute all nodes in a multithreaded executor to make the application faster. The single-threaded executor will be appropriate for applications where there is little processing in each node’s callback.
Lifecycle nodes (managed nodes)
Section titled “Lifecycle nodes (managed nodes)”Definition: The lifecycle node is a newly added feature in ROS 2 that provides a managed state machine inside the node. This will help the node transition from specific states such as unconfigured, inactive, active, and finalized. This feature gives more control over the node’s initialization, execution, and cleanup process.

Figure 3.2: Lifecycle node
Figure 3.2: Lifecycle node
As you can see in Figure 3.2, the lifecycle node transitions from four states. Compared to standard nodes, which directly go from inactive to active, the state of the lifecycle node can be controlled. Here is an overview of the lifecycle node states:
- Unconfigured: This is the initial state of the lifecycle node when it is created. The node started but has not yet performed its functionality. In this state, the node can’t communicate with other nodes and has no communication with subscribers or services. The node is idle.
- Inactive: After transitioning from the
unconfigurestate, the node moves to theInactivestate. In this state, the node has been configured but it is not performing a task like publishing and subscribing. - Active: If we switch the state from
InactivetoActive, the node can fully operate, including publishing, subscribing, services, action, etc. In this state, the node will work like a standard node. - Finalized: This is the final state of the node. After reaching this state, the node can’t transition to any other state. After this state, the node will shut down.
You can read more about lifecycle nodes at the following link [9].
Usage: Lifecycle nodes are ideal when controlled startup, shutdown, and runtime configuration are needed. This is best suited for industrial robots or autonomous vehicles.
Example: A robotic arm control node needs to be initialized, actively controlled, and safely shut down.
We have seen various types of nodes in ROS 2. Here are key takeaways from this section:
- Non-composable nodes: These are useful for isolated tasks but take more resources and have latency in communication.
- Composable/component nodes: Composable nodes allow multiple nodes to run within a single process, improving efficiency and reducing overhead. They provide a modular approach to deploying ROS 2 applications by enabling dynamic loading of nodes at runtime. This makes them especially suitable for resource-constrained environments, such as embedded systems.
- Lifecycle nodes: Lifecycle nodes introduce a state machine that defines how a node transitions between different stages of operation. This allows developers to control when a node initializes, starts doing work, stops, or shuts down—useful in complex systems.
In the next section, we will see how ROS 2 nodes communicate with each other.
How do ROS 2 nodes communicate?
Section titled “How do ROS 2 nodes communicate?”We know DDS is the core of ROS 2, which provides features like discovery, data distribution, and quality of service (QoS). Here is how nodes communicate in ROS 2:
- Discovery mechanism: DDS offers automatic discovery for ROS 2 nodes using its discovery protocol. Once we start the ROS 2 node, it will broadcast its presence on the network. If a node begins publishing a topic and another subscribes to the same topic with the same message type, DDS will connect the nodes automatically and they will start communicating with each other. Once the node is shut down, the node sends an update to DDS about it as well.
- QoS: The QoS policies in ROS 2 allow developers to control communication parameters like reliability, latency, durability, etc. These policies help the ROS 2 node to handle different network conditions and ensure reliable data transmission.
- Transport mechanism: DDS uses UDP, TCP, and shared memory based on the QoS policies set by the developer.
In ROS 2 node communication, understanding the various QoS policies is important to configure each node for different applications. The coming section will discuss various QoS policies and their importance.
Diving into QoS in ROS 2 nodes
Section titled “Diving into QoS in ROS 2 nodes”In this section, we will look at different QoS policies we can use to configure a ROS 2 node. We will discuss each policy, the values we can configure, and example use cases. Here is a table that shows a comparison of each policy.
| QoS Policy | Description | Possible Values | Example Use Cases |
|---|---|---|---|
| Reliability | This policy controls the guarantees of message delivery between nodes. | Reliable: This value ensures every message is delivered. Best-Effort: This value sends messages without ensuring delivery. | Reliable: Use for important messages like the robot velocity command. Best-Effort: Use for high-frequency sensor data like camera or LIDAR drivers. |
| Durability | This policy determines whether the past message is available for late subscribers. | Volatile: The message will be discarded after sending the message. Transient Local: This option will store and deliver past messages and new subscribers. | Volatile: Useful for real-time sensor driver nodes where old data is invalid. Transient Local: Option is useful for sharing parameters of map data. |
| History | This policy decides how much data should be stored for late subscribers. | Keep Last: This option only stores recent messages. Keep All: This option will store all messages until processed or the memory is exhausted. | Keep Last: This is for real-time streaming, where the latest data matters. Keep All: This will be ideal for critical control and data logging. |
| Depth | This policy sets the maximum number of messages in the queue before overwriting older ones. | The value is an integer. | Low depth (e.g., 5 –10): Suited for low-latency applications. High depth: Suited for bursty communication, meaning a short period of intense activity followed by long periods of silence. |
| Deadline | This policy ensures messages are delivered or received within a certain time frame. The node will receive a callback if it is violated. | The possible values are in milliseconds (e.g., 100ms). | Sensor data must arrive within a specific time interval. |
| Liveliness | This policy controls how the nodes declare whether they are still alive despite not communicating. | Automatic: The DDS (middleware) automatically manages liveliness. Manual: The node must send a liveliness signal explicitly. | Automatic: Most nodes use this method. Manual: Critical nodes like controllers use the manual method. |
| Lifespan | This policy defines the duration for which a message is valid. After this duration, the message will be discarded and not delivered. | Duration (e.g. 3s, 10s) | Use for sensitive data where outdated information must be ignored. |
| Ownership | This policy determines whether the publisher has exclusive ownership of a message on a topic. | Shared ownership: This enables multiple publishers to write about a topic. Exclusive ownership: Only one publisher can send a message on the topic. | Shared ownership: Suited for distributed systems with multiple publishers on the same topic. Exclusive ownership: Suited for critical topics with only one publisher. |
Table 3.1: QoS policies in ROS 2
We can refer to this table to configure the nodes we are going to develop in the upcoming sections.
You can read more about QoS in ROS 2 at the following link [10].
Now, we will start implementing ROS 2 nodes. We will see how to implement ROS 2 topics, parameters, services, and actions.
Implementing ROS 2 topics in C++
Section titled “Implementing ROS 2 topics in C++”This section will show how to implement a publisher and subscriber using C++ with rclcpp APIs. We will see how to implement a publisher node using custom ROS 2 message interfaces and standard ROS 2 messages. The publisher’s objective is to publish string data using the standard string msg-type and a string with an integer using a custom message interface. The subscriber node will subscribe to both of these topics.
Figure 3.3 shows how communication happens between the publisher and subscriber nodes. The names of the topics the publisher publishes are /custom_topic and /std_string_topic. The /custom_topic publishes custom ROS 2 messages, whereas std_string_topic uses standard string ROS 2 messages.

Figure 3.3: ROS 2 publisher and subscriber
Figure 3.3: ROS 2 publisher and subscriber
In Figure 3.3, you can see publisher_node on the left and subscriber_node on the right. In between, we can see the topics these nodes are publishing and subscribing to.
Now, let’s start implementing the custom ROS 2 message interface, as well as the publisher and subscriber nodes, in C++.
First, we have to create the custom interface; then we can use it for publishing and subscribing.
Creating a custom interface ROS 2 package
Section titled “Creating a custom interface ROS 2 package”The first step is to create a ROS 2 package. Take a terminal and switch to the src folder of our current ROS 2 workspace that we have created.
Creating a ROS 2 package for a custom interface
Section titled “Creating a ROS 2 package for a custom interface”Here is the command we can use to do this:
cd ~/master_ros2_ws/srcros2 pkg create master_ros2_interface --build-type ament_cmakeros2 pkg is the command used to work with the ROS 2 package. You can use this command to create a new ROS 2 package. It also helps to list the installed ROS 2 packages on the computer.
Using the ros2 pkg create subcommand, you can first give the package’s name and then mention its build type. We can use the ament_cmake build type if we are using CMake as the build tool and ament_python build for a Python package. If we want to create a custom interface package, we must use the ament_cmake build type because the custom messages must be converted into corresponding C++ or Python code for our application.
Defining the custom message
Section titled “Defining the custom message”Create an msg folder inside this package and add a custom message file called CustomMsg.msg:
cd ~/master_ros2_ws/src/master_ros2_interfacemkdir msgYou can use a text editor and enter these two data fields:
string dataint32 numberNote that we can add any data here, including standard message types from ROS 2 and even custom ROS 2 messages. After that, you can save the file as CustomMsg.msg in the master_ros2_interface/msg folder. The custom ROS 2 message for publish and subscribe can be defined in the .msg file, which can be organized into an msg folder. This custom ROS 2 message contains string and integer data.
Editing CMakeLists.txt to add message generation
Section titled “Editing CMakeLists.txt to add message generation”After adding the .msg file, we have to edit CMakeLists.txt to convert the .msg file into C++/Python files.
You can find this line in CMakeLists.txt:
find_package(ament_cmake REQUIRED)Just after this line, add the following lines to generate the message:
find_package(rosidl_default_generators REQUIRED)rosidl_generate_interfaces(${PROJECT_NAME} "msg/CustomMsg.msg")The ROS Interface Definition Language (IDL) default generator creates C++ and Python code for messages, services, and actions. This package automates the conversion of .msg, .srv, and .action to a usable ROS interface. IDL is the data types and structures used by DDS, which is the core of ROS 2.
Editing package.xml to add dependencies.
Section titled “Editing package.xml to add dependencies.”package.xml contains the metadata about the package. It has the package name, version, description, dependencies, licensing, and authorship. The colcon build tool will check package.xml and include the dependencies for building the package.
To build the custom ROS 2 message, you must add the following dependencies to build the messages:
<build_depend>rosidl_default_generators</build_depend><exec_depend>rosidl_default_runtime</exec_depend><member_of_group>rosidl_interface_packages</member_of_group>After updating package.xml, we can build the package.
Building the interface package
Section titled “Building the interface package”We can build the interface package using the following command:
cd ~/master_ros2_ws/colcon build --packages-select master_ros2_interfaceIf everything goes well, you will get the following message:
Summary: 0 packages finished [0.20s]This means that the interface package is built properly.
Now we can create the main package, which has publisher and subscriber code.
Creating the main ROS 2 package
Section titled “Creating the main ROS 2 package”Let’s start building the main ROS 2 package. We will see how to create publishers and subscribers.
Creating the package
Section titled “Creating the package”Here is the command to create a new package:
cd ~/master_ros2_ws/srcros2 pkg create master_ros2_pkg --build-type ament_cmake --dependencies rclcpp std_msgs master_ros2_interfaceThe name of the package we have created is master_ros2_pkg. The build-type value is ament_cmake. We can also explicitly mention the package dependencies using --dependencies along with the creation of the package.
Creating the src directory for a C++ node
Section titled “Creating the src directory for a C++ node”The src folder inside a ROS 2 package is where we commonly keep our C++ source code. The following command creates a src folder inside the master_ros2_pkg:
cd ~/master_ros2_ws/srcmkdir -p ~/master_ros2_pkg/srcWe can start with a publisher node in C++. You can find the publisher source code in Chapter03 | master_ros2_pkg | src | publisher_node.cpp.
You can copy this code directly from the repository into the src folder of your ROS 2 package. Let’s discuss how this code works.
What does a publisher node do?
Section titled “What does a publisher node do?”The publisher’s objective is to publish two topics. The first topic, /std_string_topic, uses a standard ROS string message (std_msgs::msg::String), and the next topic, /custom_topic, publishes a custom ROS message type (master_ros2_interface::msg::CustomMsg) that we have already created. These two topics will be published every second.
Let’s dive into the publisher code now.
Node header files
Section titled “Node header files”The publisher node requires the main header file, which is rclcpp/rclcpp.hpp. This is the header file of the rclcpp client library. If we include this header file, we will get access to APIs for creating topics, services, actions, parameters, etc. This is the main header file to include in every C++ ROS 2 node for accessing ROS2 C++ APIs:
#include "rclcpp/rclcpp.hpp"#include "std_msgs/msg/string.hpp"#include "master_ros2_interface/msg/custom_msg.hpp"In order to get access to the standard string message and custom message, we have to include these header files.
Node class definition
Section titled “Node class definition”In the publisher code, we are going to create a non-composable node. To create an independent C++ node, we have to create a class that is inherited from rclcpp::Node. The following code snippet shows the inheritance:
class PublisherNode : public rclcpp::Node {public: PublisherNode() : Node("publisher_node") {Node("publisher_node") calls the base class constructor to initialize the node with the name "publisher_node".
You can get the complete reference of rclcpp::Node from the following link [11].
Setting QoS policies
Section titled “Setting QoS policies”We can define the QoS policies to the publisher in this ROS 2 node. We can specify QoS policies using the rclcpp::QoS class. In this publisher, we have configured three main policies:
auto qos_profile = rclcpp::QoS(rclcpp::KeepLast(10)).reliable().transient_local();We have set the History QoS as KeepLast(10), meaning it will keep the last 10 messages. We set the Reliability QoS as reliable, meaning messages are guaranteed to be delivered. The third setting is for the Durability QoS. We have set the value as transient_local, meaning it will keep the last published message so new publishers can immediately receive it.
You can get the complete QoS policies setting from the following link [12].
Creating publishers
Section titled “Creating publishers”The node creates two publishers, one for each type of message:
publisher_ = this->create_publisher<std_msgs::msg::String>("std_string_topic", qos_profile);custom_publisher_ = this->create_publisher<master_ros2_interface::msg::CustomMsg>("custom_topic", qos_profile);The create_publisher function creates a publisher for a specific message type. The first publisher publishes the std_msgs::msg:String message on the "std_string_topic" topic. The second publisher publishes master_ros2_interface::msg::CustomMsg on the "custom_topic" topic.
We can include the qos_profile object for each publisher to apply the QoS profile for each ROS 2 topic.
You can refer to rclcpp::Node class [12] for more information on this API.
Timers for periodic publishing
Section titled “Timers for periodic publishing”We have declared the two publishers; now, we have to publish the data using a publisher.
create_wall_timer() creates a timer that triggers at fixed intervals. In our case, it is 1 second:
timer_ = this->create_wall_timer( std::chrono::seconds(1), std::bind(&PublisherNode::publish_messages, this));When the timer times out, it will call a publish_messages function inside the PublisherNode class. This function publishes the data for std_string_topic and custom_topic topics.
Publishing messages
Section titled “Publishing messages”publish_messages publishes data to both of these topics:
void publish_messages() { auto string_msg = std_msgs::msg::String(); string_msg.data = "Hello, world!"; RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", string_msg.data.c_str()); publisher_->publish(string_msg);In the above snippet, we are creating an instance of std_msgs::msg::String, and then setting the data field inside the message to "Hello World". After updating the string message inside the data field, we use the publish() function inside the publisher we have created for the standard string message. This will publish the given data:
auto custom_msg = master_ros2_interface::msg::CustomMsg();custom_msg.data = "Custom Hello";custom_msg.number = 42;RCLCPP_INFO(this->get_logger(), "Publishing custom message: data='%s', number=%d", custom_msg.data.c_str(), custom_msg.number);custom_publisher_->publish(custom_msg);In the second publisher, we are doing the same process, but instead of a standard string, we are creating the instance of master_ros2_interface::msg::CustomMsg, and setting the data field of string member inside the custom message to "Custom Hello" and an integer value, 42. After setting both the values, we publish this topic.
Main function
Section titled “Main function”In the main() function, we can see that rclcpp::init(argc, argv) will initialize the resources needed by the middleware and the client library. This is a mandatory function to be called to start a ROS 2 C++ node. The next function is rclcpp::spin(std::make_shared<PublisherNode>()), which will start the node and wait for the timer to call the publish function we have defined. The spin() function basically executes the callback functions in ROS 2 and, finally, the rclcpp::shutdown() function shuts down the ROS 2 node and cleans up its resources.
Now we can start discussing subscriber code.
What does the subscriber node do?
Section titled “What does the subscriber node do?”The subscriber’s objective is to subscribe to two topics. The first topic, /std_string_topic, uses a standard ROS string message (std_msgs::msg::String), and the next topic, /custom_topic, uses a custom ROS message type (master_ros2_interface::msg::CustomMsg). Let’s dive into the subscriber code now.
If you check both publisher and subscriber code, you will find the same header file and Node class with different node names. The QoS setting is also the same. So, what is different in subscriber code? The main difference is that instead of publishing, we are using subscribe APIs to subscribe to topics.
You can find the subscriber source code in Chapter03 | master_ros2_pkg | src | subscriber_node.cpp.
Subscribe to topics
Section titled “Subscribe to topics”The following code snippet shows how to create a subscriber object for a specific topic and message with the defined qos_profile. The first line is for subscribing std_string_topic:
subscription_ = this->create_subscription<std_msgs::msg::String>( "std_string_topic", qos_profile, std::bind(&SubscriberNode::string_callback, this, std::placeholders::_1));The second line is for subscribing to the custom message we have created. Once a message is received, the subscribers will call a callback or a function:
custom_subscription_ = this->create_subscription<master_ros2_interface::msg::CustomMsg>( "custom_topic", qos_profile, std::bind(&SubscriberNode::custom_msg_callback, this, std::placeholders::_1));When the subscriber receives a message, the first subscriber calls the string_callback(const std_msgs::msg::String::SharedPtr msg) callback, and the second calls the custom_msg_callback(const master_ros2_interface::msg::CustomMsg::SharedPtr msg) callback.
Callback functions
Section titled “Callback functions”These are the functions that handle the message once they are received by the subscriber. We can manipulate the received data according to our logic. In our current code, we are simply printing the received messages.
This is the first callback, and it is receiving std_msgs::msg::String:
void string_callback(const std_msgs::msg::String::SharedPtr msg) { RCLCPP_INFO(this->get_logger(), "Received: '%s'", msg->data.c_str());}The second callback, which will print the received data from the custom message we have created, looks as follows:
void custom_msg_callback(const master_ros2_interface::msg::CustomMsg::SharedPtr msg) { RCLCPP_INFO(this->get_logger(), "Received custom message: data='%s', number=%d", msg->data.c_str(), msg->number);}If you check the main() function of the code, it is also the same as the publisher code; the only difference is the change in the node class name.
As of now, we have walked through the publisher and subscriber code. Now, we will continue with the modifications we need to make to compile and build the source code to create executables.
Editing CMakeLists.txt to build the node
Section titled “Editing CMakeLists.txt to build the node”After adding publisher and subscriber source code, we have to edit CMakeLists.txt in the package. We have to add lines to CMakeLists.txt for building and installing the executables of the publisher and subscriber. Here is how we do that.
After the find_package(), you can add the following lines to create executables of the two sets of source code we have created. These lines will be compiling, linking, and installing the executables. Once it is installed, we can run these executables using the ros2 run command:
# Add executable for publisher nodeadd_executable(publisher_node src/publisher_node.cpp)ament_target_dependencies(publisher_node rclcpp std_msgs master_ros2_interface)# Add executable for subscriber nodeadd_executable(subscriber_node src/subscriber_node.cpp)ament_target_dependencies(subscriber_node rclcpp std_msgs master_ros2_interface)install(TARGETS publisher_node subscriber_node DESTINATION lib/${PROJECT_NAME})After changing CMakeLists.txt, next is editing the package.xml file.
Edit package.xml
Editing package.xml is needed if we are using new dependencies other than those we gave during package creation. In our case, we are not using new dependencies, so we don’t have to edit the package.xml.
Building the package
Section titled “Building the package”We are done with creating packages that contain publisher and subscriber code. Now, let’s build the package and run the executable.
To build all the packages in the workspace, we can use the following command:
colcon buildYou can selectively build this package using the following command:
colcon build --packages-select master_ros2_pkgIf you are done with building packages, you will get the following output if everything is successful:
Starting >>> master_ros2_interfaceFinished <<< master_ros2_interface [0.94s]Starting >>> master_ros2_pkgFinished <<< master_ros2_pkg [1.09s]Summary: 2 packages finished [2.23s]Congratulations! You are done with building the packages. Now it’s time to run the nodes.
Running the nodes
Section titled “Running the nodes”To run the executables, you have to first source the master ros2_ws we created. You can either add the following line to the .bashrc file or execute the command in all the terminals you create.
To run the publisher and subscriber, two terminals are required.
We can run the publisher node in the first terminal:
source ~/master_ros2_ws/install/setup.bashros2 run master_ros2_pkg publisher_nodeWe can run the subscriber node in the second terminal:
source ~/master_ros2_ws/install/setup.bashros2 run master_ros2_pkg subscriber_nodeIf everything works well, you will get the following output in the terminals. You can see that the publisher and subscriber are communicating with each other.

Figure 3.4: Output of publisher (left) and subscriber (right)
Figure 3.4: Output of publisher (left) and subscriber (right)
In the next section, we will see how to work with ROS 2 parameters.
Implementing ROS 2 parameters in C++
Section titled “Implementing ROS 2 parameters in C++”We are going to implement ROS 2 parameters in the publisher code we have already worked with. Here is the objective of the updated code.
The new node we are going to create will have two parameters: a string and an integer. The value will be published using the custom message topic we have already created. So, if we set these parameters outside the node during the runtime, those values will be taken for publishing. After publishing the new value, the parameter will be set to default values. You can find the source code in Chapter03 | master_ros2_pkg | src | publisher_node_params.cpp.
Let’s check out this code and see how we can declare the parameters in a C++ node.
Declaring ROS 2 parameters
Section titled “Declaring ROS 2 parameters”This is how we declare new parameters in a C++ node. The declare_parameters function is used to declare a new parameter. Here is an example usage of this function:
this->declare_parameter<std::string>("custom_string", "Hello World"); this->declare_parameter<int>("custom_number", 42);Inside the node class, you can find the declaration of string and integer parameters. The parameters’ names are custom_string and custom_number.
When we declare a new parameter, we can add a default value for that parameter. In this case, the default string value is "Hello World" and the integer value is 42.
Reading values of ROS 2 parameters
Section titled “Reading values of ROS 2 parameters”After declaring the parameters, we access the values of these parameters inside the publish_message function. Using the get_parameter function, we can read the value of the parameter to a variable.
In the following snippet, we can see how we read and store the value of ROS 2 parameters:
std::string custom_string_param;int custom_number_param;this->get_parameter("custom_string", custom_string_param);this->get_parameter("custom_number", custom_number_param);After reading the values from the parameters, we assign these two data to the custom message we have created. After putting the data in the custom ROS message, we publish this message to the custom ROS topic.
Note that we can also use a callback function to receive the changes in the ROS 2 parameter. So, whenever the parameter changes from outside, this callback function will be called. Inside the callback function, we can do the rest of the processing if needed. Here is a reference that explains how to do this [19].
Setting ROS 2 parameters
Section titled “Setting ROS 2 parameters”After publishing the topic, we set the default values back to the parameters using the set_parameter() function:
this->set_parameter(rclcpp::Parameter("custom_string", "Hello String"));this->set_parameter(rclcpp::Parameter("custom_number", 42));After creating the source code, we can edit CMakeLists.txt to build the source code.
Editing CMakeLists.txt
Section titled “Editing CMakeLists.txt”Adding to CMakeLists.txt follows the same procedure we have used for publisher and subscriber nodes. We have added lines for compiling and building the code and the target executable inside the install () function:
add_executable(publisher_node_params src/publisher_node_params.cpp)ament_target_dependencies(publisher_node_params rclcpp std_msgs master_ros2_interface)After editing CMakeLists.txt, you can carry out colcon build, and if everything builds correctly, you can execute the node.
Starting a ROS 2 node with parameters
Section titled “Starting a ROS 2 node with parameters”In this section, we will see how to run publisher_node_params and how to set the ROS 2 parameter in the command line.
Here is the command to run the publisher node with parameters:
ros2 run master_ros2_pkg publisher_node_paramsAfter running this node, you can see it start to print a message in the terminal.
Now, start the subscriber_node that we have already created. The publisher_node_params and publisher_node are the same with the same topics and ROS message type; the only difference is the inclusion of ROS 2 parameters.
Here is the command to start the subscriber:
ros2 run master_ros2_pkg subscriber_nodeNow, take a new terminal and set the parameters using the ros2 param command:
ros2 param set publisher_node_params custom_string "Test"ros2 param set publisher_node_params custom_number 20Now, you can see the values we have set as ROS 2 parameters are printed in the terminal, and the exact value is published in the ROS 2 topic.
So, when we set the parameters, the values that the ROS 2 node publishes change. After publishing the new values, in the next iteration, the default values mentioned in the code get assigned for publishing.
You can see the changed value in subscribers as well.

Figure 3.5: Output of the publisher (left), subscriber (right), and set parameters (bottom)
Figure 3.5: Output of the publisher (left), subscriber (right), and set parameters (bottom)
In Figure 3.5, on the left side, you can see the publisher_node_params messages; on the right side, you can find messages of subscriber_node, and at the bottom, you can find the setting of the ROS 2 parameter. We have set the custom_string parameter to Test. Once we set the parameter, you can see the publisher and subscriber messages change. The change of message is shown as bold in Figure 3.5.
In the next section, we will see the implementation of the ROS 2 service.
Implementing ROS 2 services in C++
Section titled “Implementing ROS 2 services in C++”In this section, we will implement a ROS 2 service server and client using C++. The service server listens to a service called concat_strings with a custom service type of master_ros2_interface::srv::ConcatStrings. If it gets a request from the service client, the server will concatenate both strings it got and reply to the client.
You can find the server and client code in Chapter03 | master_ros2_pkg | src | simple_server.cpp and simple_client.cpp.
Adding a custom service interface
Section titled “Adding a custom service interface”The first thing to do before writing server and client code is to write a custom service type.
Here is the custom service type we have defined:
string str1string str2---string concatenated_strWe have to save this definition as master_ros2_interface/srv/ConcatStrings.srv. The first two strings are for the request field, and the third is for the reply field. The request and reply are separated by ---.
Editing CMakeLists.txt
Section titled “Editing CMakeLists.txt”After saving the srv definition, we have to edit the CMakeLists.txt to convert the srv file definition into C++/Python modules:
rosidl_generate_interfaces(${PROJECT_NAME} "msg/CustomMsg.msg" "srv/ConcatStrings.srv")We are done with adding a custom service interface. Now, it’s time to write the server and client.
ROS 2 service server
Section titled “ROS 2 service server”In simple_server.cpp, you can find the header file for the custom service type. It is mandatory to include this header to access the service type in the server and client code:
#include "master_ros2_interface/srv/concat_strings.hpp"Now, we can define a ROS 2 service using the create_service function. In this function, we can include the type of the service, the name of the service, and its callback:
service_ = this->create_service<master_ros2_interface::srv::ConcatStrings>( "concat_strings", std::bind(&StringConcatService::handle_service, this, std::placeholders::_1, std::placeholders::_2));When the service server gets a request, it will call a callback called handle_service. This callback will receive those two strings, concatenate both strings, and send the response as a concatenated string that will be received by the client:
void handle_service( const std::shared_ptr<master_ros2_interface::srv::ConcatStrings::Request> request, std::shared_ptr<master_ros2_interface::srv::ConcatStrings::Response> response){ response->concatenated_str = request->str1 + request->str2;}Now we will see what is happening to the service client.
ROS 2 service client
Section titled “ROS 2 service client”In the service client, like the service server, we have the create_client function to create a service client. We can mention the service type and the name of the service to which the client has to communicate:
client_ = this->create_client<master_ros2_interface::srv::ConcatStrings>("concat_strings");After creating a client, we can send a request to the server using the send_request (const std::string &str1, const std::string &str2) function. This function allows us to pass two strings, and the string will be sent to the server using the async_send_request function:
void send_request(const std::string &str1, const std::string &str2){ auto request = std::make_shared<master_ros2_interface::srv::ConcatStrings::Request>(); request->str1 = str1; request->str2 = str2; auto future_result = client_->async_send_request(request); if (rclcpp::spin_until_future_complete(this->get_node_base_interface(), future_result) == rclcpp::FutureReturnCode::SUCCESS) { RCLCPP_INFO(this->get_logger(), "Result: concatenated_str='%s'", future_result.get()->concatenated_str.c_str());If the client is successful, it will get the response from the server, which is the concatenated string.
After writing the server and client, we can build the nodes by editing CMakeLists.txt.
Building server and client nodes
Section titled “Building server and client nodes”In order to build the server and client, we can edit the CMakeLists.txt by adding the following lines:
add_executable(simple_server src/simple_server.cpp)ament_target_dependencies(simple_server rclcpp master_ros2_interface)add_executable(simple_client src/simple_client.cpp)ament_target_dependencies(simple_client rclcpp master_ros2_interface)We can also add the executables in the install () function to install the generated executables.
After editing CMakeLists.txt, we can carry out colcon build to build all packages.
Running nodes
Section titled “Running nodes”After building, we can run the server and client for testing.
You can run the server node in terminal 1:
ros2 run master_ros2_pkg simple_serverYou can run the client node in terminal 2:
ros2 run master_ros2_pkg simple_clientIf everything works fine, you will get the following output in the terminal:

Figure 3.6: Output of service server and client
Figure 3.6: Output of service server and client
In the next section, we will discuss implementing a ROS 2 action.
Implementing a ROS 2 action in C++
Section titled “Implementing a ROS 2 action in C++”In this section, we will implement an action server and action client in ROS 2 C++ APIs. The custom action type we will create is master_ros2_interface/action/MyCustomAction.action, and the action name is "my_custom_action". The action client will send a value as the goal value, and the action server will count from 0 to that value with a 1-second delay. The action server will also send the client feedback on the current count. If the count is complete, it will send the final count.
You can find the action server and action client in Chapter03 | master_ros2_pkg | src | action_server.cpp and action_client.cpp.
Creating a custom action interface for the ROS 2 action and server
Section titled “Creating a custom action interface for the ROS 2 action and server”Let’s create a custom action type inside the master_ros2_interface/action folder. The name of the action file is MyCustomAction.action. The .action file is used to define an action type in ROS 2. Here is the definition of the MyCustomAction.action file:
# Goalint32 goal_value---# Resultint32 result_value---# Feedbackfloat32 progressThe action files have three sections: the first is for the goal value, the second is for the result, and the third is for the feedback. We have to separate each data field with “---.”
After creating our action file, we just need to edit CMakeLists.txt and package.xml.
Editing CMakeLists.txt and package.xml
Section titled “Editing CMakeLists.txt and package.xml”In CMakeLists.txt, update rosidl_generate_interfaces() by adding the action file:
rosidl_generate_interfaces(${PROJECT_NAME} "msg/CustomMsg.msg" "srv/ConcatStrings.srv" "action/MyCustomAction.action")In package.xml, we have to add action_msgs to build the custom action type:
<depend>action_msgs</depend>Writing a ROS 2 action server
Section titled “Writing a ROS 2 action server”After creating the custom action, we can start writing the action server.
To access the custom action in the action server code, we have to include the header file that will be generated by the master_ros2_interface package:
#include "master_ros2_interface/action/my_custom_action.hpp"Here is the declaration of the action server. The rclcpp_action::create_server() is used to declare a new action. We have to mention the action type and the name of the action in the function. Along with these, we need to add three callbacks as well. One is for handling the goal, one is for handling/executing the goal, and one is for handling the cancellation of the goal:
action_server_ = rclcpp_action::create_server<MyCustomAction>( this, "my_custom_action", std::bind(&ActionServer::handle_goal, this, std::placeholders::_1, std::placeholders::_2), std::bind(&ActionServer::handle_cancel, this, std::placeholders::_1), std::bind(&ActionServer::handle_accepted, this, std::placeholders::_1));When the action server receives a goal, it first calls the handle_goal function, receives the goal value, and returns whether we have to accept the execution. If the execution is accepted, the handle_accepted callback is called, and the execution function called execute(const std::shared_ptr<GoalHandle> goal_handle) starts. This is the main function of the action server that processes the goal. If the client cancels the goal, it calls the handle_cancel function.
The execute(const std::shared_ptr<GoalHandle> goal_handle) function is given below. The function gets the goal value and starts a feedback loop. After the loop, the result values are published:
void execute(const std::shared_ptr<GoalHandle> goal_handle) {const auto goal = goal_handle->get_goal(); auto result = std::make_shared<MyCustomAction::Result>(); auto feedback = std::make_shared<MyCustomAction::Feedback>(); for (int i = 1; i <= goal->goal_value; ++i) { feedback->progress = i ; goal_handle->publish_feedback(feedback); rclcpp::sleep_for(std::chrono::milliseconds(500)); } result->result_value = goal->goal_value; goal_handle->succeed(result); RCLCPP_INFO(this->get_logger(), "Goal succeeded"); }The rest of the code is the same as the nodes that we have already seen before. Now we will see what is in the action client code.
Writing the ROS 2 action client
Section titled “Writing the ROS 2 action client”In the action client, we use the rclcpp_action::create_client function, and inside this function, we have to mention the type of the action and the name of the action. After creating the client object, we call the send_goal() function:
client_ = rclcpp_action::create_client<MyCustomAction>(this, "my_custom_action");send_goal();In the send_goal() function, we create a goal message and set the goal value to send to the server as 10:
auto goal_msg = MyCustomAction::Goal();goal_msg.goal_value = 10;We also assign callbacks for feedback and the results when the client receives feedback and the result from the server:
auto send_goal_options = rclcpp_action::Client<MyCustomAction>::SendGoalOptions();send_goal_options.feedback_callback = [this](GoalHandle::SharedPtr, const std::shared_ptr<const MyCustomAction::Feedback> feedback) { RCLCPP_INFO(this->get_logger(), "Feedback: %.2f", feedback->progress); }; send_goal_options.result_callback = [this](const GoalHandle::WrappedResult &result) { RCLCPP_INFO(this->get_logger(), "Result: %d", result.result->result_value); };After assigning the callback, we use the async_send_goal function to send the goal message we have assigned:
client_->async_send_goal(goal_msg, send_goal_options);After calling this function, the client will send the goal immediately to the server.
Building nodes
Section titled “Building nodes”To build the nodes, we must add the same lines we did for the previous nodes in CMakeList.txt. After editing CMakeLists.txt, you can build using the colcon build command.
Running nodes
Section titled “Running nodes”After building the nodes, we can run the nodes using the following command.
You can run the action server in terminal 1:
ros2 run master_ros2_pkg action_serverAfter running the action server, you can run the action client in terminal 2:
ros2 run master_ros2_pkg action_clientIn Figure 3.7, you can see the goal received message in the server and see that the client gets feedback from the server and the result.

Figure 3.7: Output of action server and client
Figure 3.7: Output of action server and client
In the next section, we will see how we can launch these nodes from the launch files.
Writing launch files for nodes
Section titled “Writing launch files for nodes”In this section, we will see the launch files for launching these nodes together. In the Chapter03 | master_ros2_pkg | launch folder, you can find the following launch files to start nodes together. We’ve already discussed how to write a basic launch file, so we will not discuss the concept in detail:
pub_sub.launch.py: This launch file will start the publisher and subscriber.pub_params_sub.launch.py: This launch file will start thepublisher_node_paramsnode and a normal subscriber.server_client.launch.py: This will start the service server and client.action_server_client.launch.py: This will start the action server and client.
Implementing ROS 2 composable nodes
In this chapter, we have focused mainly on non-composable nodes. Here is the reference if you want to implement composable nodes [13]. Here is the reference for different types of executors available in ROS 2 [14].
Before concluding this chapter, you must understand a few tips on configuring different DDS for communication and configuring ROS_DOMAIN_ID.
Configuring ROS 2 DDS/Zenoh and ROS_DOMAIN_ID
Section titled “Configuring ROS 2 DDS/Zenoh and ROS_DOMAIN_ID”Let’s start by configuring DDS for your ROS 2 installation. So, you may ask why we need to change DDS rather than using the default one. The answer is each DDS is different. Some DDS implementations work best for some applications. So, to get better results, it is better to change the DDS.
Let’s explore how to change the DDS of your ROS 2 installation.
Configuring ROS 2 DDS
Section titled “Configuring ROS 2 DDS”Setting a new DDS is straightforward. First, select the DDS you want to use in a robot, and then install the DDS implementation packages if they are not already installed.
We will look at the installations of different DDSs here:
- Install Fast DDS: You can use the following command to install Fast DDS:
sudo apt install -y ros-jazzy-rmw-fastrtps-cpp
After installing Fast DDS, you can export the RMW_IMPLEMENTATION variable to rmw_fastrtps_cpp. You can do this by adding the following line to the end of the .bashrc file. We have to re-source the terminal or take a new terminal to see the updated DDS settings. After setting this, Fast DDS will be used as the new DDS:
echo "export RMW_IMPLEMENTATION=rmw_fastrtps_cpp" >> ~/.bashrcThe same procedure is used to install Cyclone DDS.
- Install Cyclone DDS: Let’s see how we can install and configure Cyclone DDS.
We can use the following command to install Cyclone DDS on our machine:
sudo apt install -y ros-jazzy-rmw-cyclonedds-cppAfter installing Cyclone DDS, set it as the new DDS using the following command:
echo "export RMW_IMPLEMENTATION= rmw_cyclonedds_cpp" >> ~/.bashrc- Installing Zenoh: We can also set non-DDS frameworks like Zenoh as middleware. You can install Zenoh from the
aptpackage manager or build it manually using the source code. Here is the command to install Zenoh from the apt package manager.sudo apt install ros-jazzy-rmw-zenoh-cpp.
Here is the GitHub repository to build it from the source code [15]. After building the middleware, you can export the variable:
echo "export RMW_IMPLEMENTATION= rmw_zenoh_cpp" >> ~/.bashrcYou can read more about DDS configuration at this link [16]. Here are some detailed references to configuring Fast DDS [17] and Cyclone DDS [18] specifically.
Setting ROS_DOMAIN_ID
Section titled “Setting ROS_DOMAIN_ID”ROS_DOMAIN_ID in ROS 2 is a unique identifier that isolates a group of nodes that can communicate with each other. For example, if there are multiple robots in the same network, we can use this identifier to isolate the communication for each robot. Nodes running on the same domain ID can find each other, but they are isolated and cannot communicate with another domain ID. The default value of ROS_DOMAIN_ID is 0. It is an integer, and you can set values from 0 to 232, which can vary based on the underlying DDS and the OS.
Setting a domain ID is very easy, like configuring DDS, which we did earlier.
For example, this is how we set the ID to 10:
echo "export ROS_DOMAIN_ID=10" >> ~/.bashrcIn this section, we have learned how to set up and configure different DDS in ROS 2 and set up ROS_DOMAIN_ID to isolate nodes in the robot network. Configuring DDS in robots may be required because of different working environments.
The following section will show how to configure Docker, Docker Compose, and Dev Container for ROS 2 Jazzy development.
Setting up ROS 2 Jazzy development in Docker
Section titled “Setting up ROS 2 Jazzy development in Docker”The scripts and Dockerfiles from Chapter03/docker_dev can be used to build and run the ROS 2 packages in Chapter03 using Docker.
Here is the command to build the ROS 2 Jazzy custom image.
./build_image.sh ros2_dev:v0.1 master_ros2_ws robotHere, ros2_dev:v0.1 is the name of the custom image, master_ros2_ws is our ROS 2 workspace where we can put our Chapter03 ROS 2 packages, and the robot is the user’s name inside the container.
After building the ROS 2 custom image, we can create the container using the following command.
./create_container.sh ros2_dev:v0.1 master_ros2_ws ros2_devWe need to provide the image name, the ROS 2 workspace name, and the container name we need to make.
After creating the container, you can see that the master_ros2_ws is mounted inside the container. We can build the ROS 2 workspace inside the container and run the nodes.
If we want to open more terminals for the same container, you can use the following command:
./start_container.sh ros2_devThis will attach a new terminal if the container is already running or start it if it has stopped. You need to provide the container name as the argument for this script.
After attaching a new terminal, make sure you have source the ros_entry_point script using the following command:
source /ros_entrypoint.shThe following section provides instructions for building, creating, and running containers using Docker Compose.
Setting up ROS 2 Development in Docker Compose
Section titled “Setting up ROS 2 Development in Docker Compose”This section shows how to build and start containers for Chapter03 packages using Docker Compose.
Switch to Chapter03 | docker_compose_dev folder and execute the following command to start building the Docker image and starting the container:
Use the following command if you are using a non-NVIDIA graphics card on your PC.
docker compose -f docker-compose-gui.yml builddocker compose -f docker-compose-gui.yml upIf you do have an NVIDIA graphics card and the driver is properly installed, use the following command to start the container.
docker compose -f docker-compose-nvidia.yml builddocker compose -f docker-compose-nvidia.yml upOnce you start this command, the image will be built first, and the container will start. You have to use another terminal to attach to the container. You don’t have to close this terminal; if you cancel the command by pressing Ctrl + C, it will stop the running container.
Using the following command, you can create a new terminal from the running container.
./start_container.sh ros2_devNow source the ROS 2 environment using the following command and you can build the ROS 2 workspace which is mounted inside the container.
source /ros_entrypoint.shAfter starting the container, if you want to stop or remove it, you can execute the command from a new host terminal. Make sure you are executing inside the docker_compose_dev folder.
docker compose -f docker-compose-gui.yml downor
docker compose -f docker-compose-nvidia.yml downNext, let’s see how to set up VS Code Dev Container for ROS 2 development.
ROS 2 Development using VS Code Dev Container
Section titled “ROS 2 Development using VS Code Dev Container”If you want to set up a Dev Container [20] in VS Code, make sure you have created the ROS 2 workspace named master_ros2_ws and open the Chapter03 folder using VS Code. This folder has a .devcontainer folder, which has the devcontainer.json file, and the instructions for using the docker-compose file we have used in the above section for the container. When you open the folder, it will prompt you to install the Dev Container extension and Reopen in Container. If you select this option, it will build the container, set the environment, mount the ROS 2 workspace as a volume, and connect the editor to it. We can also see the mounted volume, which is the master_ros2_ws folder in VS Code itself.
Summary
Section titled “Summary”This chapter covered implementing key ROS 2 concepts using the rclcpp library for C++. It introduced ROS 2 actions, comparing them to services, highlighting that actions are more suited for long-running tasks with feedback and cancellation capabilities.
The chapter also discussed parameters and how they can be used to configure nodes using YAML files for flexibility. Additionally, it covered the creation of ROS 2 launch files to manage multiple nodes efficiently, and how to build a ROS 2 workspace. The rclcpp client library (C++) was introduced, allowing users to implement nodes.
The chapter also discussed different types of ROS 2 node (non-composable, composable, and lifecycle nodes). It explained how nodes communicate using DDS, offering various QoS configurations to ensure reliability and efficiency. The chapter also touched on building custom interfaces and messages, managing ROS parameters, and setting up DDS/Zenoh and ROS domain ID configurations for better node communication.
In the next chapter, we will see how to build 3D robot models in ROS 2 using URDF.
References
Section titled “References”- [1] https://docs.ros.org/en/jazzy/Tutorials/Beginner-CLI-Tools/Understanding-ROS2-Actions/Understanding-ROS2-Actions.html
- [2] https://docs.ros.org/en/jazzy/Tutorials/Beginner-CLI-Tools/Understanding-ROS2-Parameters/Understanding-ROS2-Parameters.html
- [3] https://docs.ros.org/en/jazzy/Tutorials/Intermediate/Launch/Creating-Launch-Files.html
- [4] https://docs.ros.org/en/jazzy/Tutorials/Beginner-Client-Libraries/Colcon-Tutorial.html
- [5] https://docs.ros.org/en/jazzy/Tutorials/Beginner-Client-Libraries/Creating-A-Workspace/Creating-A-Workspace.html
- [6] https://github.com/ros2/rcl
- [7] https://docs.ros.org/en/jazzy/p/rcl/
- [8] https://docs.ros.org/en/jazzy/Concepts/Basic/About-Client-Libraries.html
- [9] https://design.ros2.org/articles/node_lifecycle.html
- [10] https://docs.ros.org/en/jazzy/Concepts/Intermediate/About-Quality-of-Service-Settings.html
- [11] https://docs.ros.org/en/jazzy/p/rclcpp/generated/index.html
- [12] https://docs.ros.org/en/ros2_packages/jazzy/api/rclcpp/generated/classrclcpp_1_1QoS.html
- [13] https://docs.ros.org/en/jazzy/Tutorials/Intermediate/Composition.html
- [14] https://docs.ros.org/en/jazzy/Concepts/Intermediate/About-Executors.html#executors
- [15] https://github.com/ros2/rmw_zenoh
- [16] https://docs.ros.org/en/jazzy/Installation/DDS-Implementations.html
- [17] https://fast-dds.docs.eprosima.com/en/latest/fastdds/ros2/ros2_configure.html
- [18] https://husarion.com/tutorials/other-tutorials/husarnet-cyclone-dds/
- [19] https://docs.ros.org/en/jazzy/Tutorials/Intermediate/Monitoring-For-Parameter-Changes-CPP.html
- [20] https://code.visualstudio.com/docs/devcontainers/containers