Implementing ROS 2 Visualization and Simulation Plugins
local graph
Chapter 16 — Implementing ROS 2 Visualization and Simulation Plugins
Section titled “Chapter 16 — Implementing ROS 2 Visualization and Simulation Plugins”Plugins are essential in modern software development for creating modular, extensible systems. They integrate with host applications to provide extra functionality without modifying core code, relying on the host to load and execute them at runtime. By adhering to standard interfaces, plugins ensure compatibility and flexibility, making them ideal for enhancing tools such as simulators or visualizers. In ROS 2, plugins enable custom data filters, controllers, or visualizations, tailoring systems to specific needs.
Plugins are implemented as shared libraries and can be used in different applications. In this chapter, we will explore three types of plugins: an rqt plugin that implements a custom interface for controlling a robot integrated with the RQT framework, an RViz2 plugin that creates a custom visualization tool for your data in RViz2, and a Gazebo plugin that leverages Gazebo’s functionalities for direct integration with simulations.
By the end of this chapter, you will learn how to create new plugins for different scopes enabling the ROS 2 modularity and reusability of your code. This fosters cleaner design, easier integration, and adaptability in robotics applications.
As such, we will cover the following main topics in this chapter:
- Introducing the ROS 2 plugin
- Creating a plugin for
rqt - Developing a Gazebo plugin
- Developing plugins for
RViz2
Technical requirements
Section titled “Technical requirements”To follow this chapter, it is better to have a computer with Ubuntu 24.04 LTS installed or any other Ubuntu version.
The reference materials for this chapter can be found in the Chapter16 folder of the following GitHub repository: https://github.com/PacktPublishing/Mastering-ROS-2-for-Robotics-Programming/tree/main/Chapter16.
Introducing the ROS 2 plugin
Section titled “Introducing the ROS 2 plugin”In this book, we’ve already created a plugin, though we didn’t explicitly call it that. In Chapter 6, we developed controllers for the ROS 2 Control package. Unlike typical ROS nodes, these controllers lack a main function and cannot be compiled into executables. Instead, they provide specific functionality for use by other nodes or libraries. This distinction is key to understanding plugins in ROS. So, what is a library? In C++, a library is a collection of precompiled code reused across programs. Libraries can be:
- Static (
.a): Linked at compile time, making their code part of the executable. This increases file size but eliminates runtime dependencies. - Shared (
.soon Linux): Linked at runtime, enabling multiple programs to share the same library. This reduces file size and simplifies updates but requires the library to be available on the system at runtime.
A plugin in C++ is essentially a shared library. Plugins dynamically extend a system’s functionality by being loaded at runtime. In ROS 2, plugins are shared libraries managed through frameworks such as pluginlib, which enable modular, scalable components for robotics systems.
Notably, while ROS 2 supports Python for nodes, plugins cannot be written in Python. This limitation arises because Python cannot generate shared libraries directly. Next, let’s explore how plugins are managed in ROS 2.
Understanding pluginlib in ROS 2
Section titled “Understanding pluginlib in ROS 2”pluginlib is a C++ tool used in ROS for dynamically loading and unloading plugins within a package. With pluginlib, applications don’t need to be explicitly linked to the library containing these classes. Instead, pluginlib can load the library and its exported classes at runtime, without the application needing prior knowledge of the library or its headers. This is possible due to interface classes that the implementation inherits from, allowing the application to interact with plugins through polymorphism.
This allows for extending or modifying application behavior without altering the source code of the application itself. To use the pluginlib tool in ROS 2, it must be installed using the following command:
sudo apt-get install ros-jazzy-pluginlibBy using the pluginlib tool in ROS 2, we can implement a variety of plugins to be used in your robotic applications. For example, the following plugins can be found:
- Middleware plugins: DDS implementations (e.g., Fast RTPS and Cyclone DDS) for flexible communication
- Robot hardware interface plugins:
ros2_controlplugins for controlling hardware (e.g., actuators and sensors) - Perception and sensor plugins: Sensor drivers and perception filters for modular sensor integration (e.g., LiDAR and cameras)
- Navigation plugins:
Nav2plugins for custom path planners, costmaps, and recovery behaviors - Visualization plugins:
RVizplugins for custom data visualization - Behavior tree plugins: Custom actions, conditions, and decorators for decision-making tasks
- Diagnostics plugins: Plugins for monitoring and reporting robot health and sensor states
- Custom node plugins: Custom nodes for dynamic tasks (e.g., service servers and action servers)
rqtplugins: User interface plugins to exchange information with the robot
Glancing at steps for creating, compiling, and loading plugins
Section titled “Glancing at steps for creating, compiling, and loading plugins”Regardless of the type of plugin, the steps to create, compile, and load a given plugin are the same:
- Create a new package to store the files to generate the library. This package must depend on
pluginlib. - Create a base class that defines the interface your plugin will follow. This class will be used as a contract for the plugin, ensuring that all plugins conform to a specific set of methods.
- Implement the plugin by inheriting the interface. This implementation will depend on the plugin type that must be implemented.
- Register the plugin with
pluginliband describe it in an XML file. This allows thepluginlibtool to load the plugin when required. - Build the plugin by compiling the workspace.
After the above steps, we are ready to load the plugin in the application that will use it or in another ROS 2 node. Also, in this case, the loading method will depend on the plugin type. In the example contained in this chapter, we will use rqt, RViz, and Gazebo to automatically load the plugin when needed.
In the next section, we will discuss how to implement the above steps to create our first plugin, a plugin for the rqt interface.
Creating a plugin for rqt
Section titled “Creating a plugin for rqt”rqt is a Qt-based framework in ROS 2 that provides a set of GUI tools for monitoring, debugging, and visualizing robot systems. It is highly modular, with plugins that support tasks such as plotting data, visualizing topics, configuring parameters, and inspecting logs. But what does Qt-based mean? Qt is a cross-platform software development framework primarily used for creating GUIs It is released under a dual licensing model, which can pose challenges for closed-source and commercial projects due to its high licensing costs. Written in C++, it provides tools for designing intuitive and responsive UIs. We can exploit the rqt interface to add new plugins creating custom user interfaces to control our robots, using topics and services to exchange information with robots.
Of course, to develop an rqt plugin, we also need to create the user interface, apart from the source code. We will start from this point, after the creation of the ROS 2 package. Create the package using the following command to include all the needed dependencies:
ros2 pkg create cmd_vel --dependencies rclcpp qt_gui_cpp rqt_gui_cpp std_msgs Qt5Widgets geometry_msgsThe goal of this example is to create a custom plugin to control the velocity of a robot using a twist command and a clickable user interface.
Following the next steps, you will able to shape such an interface, like the one shown in Figure 16.1.

Figure 16.1: The rqt plugin for twist velocity commands
Figure 16.1: The rqt plugin for twist velocity commands
Let’s start by discussing how to develop a GUI like the one shown in the previous figure.
Creating a Qt user interface
Section titled “Creating a Qt user interface”All the files needed to create the plugin will be included in the package. Let’s begin with the user interface. The quickest way to create it is by using Qt Designer, a tool included in the Qt Creator program. While Qt Creator is primarily an integrated development environment (IDE) for programming and debugging Qt applications, it also supports C++ and Python development. Within Qt Creator, Qt Designer provides a visual design interface, allowing you to create layouts and widgets through drag-and-drop functionality without needing to write code. To proceed, let’s install Qt Designer using the following command:
sudo apt-get install designer-qt6To open the Designer instead, use the following command.
designerAfter executing this command, the Designer user interface is opened. It is easy to use and is organized into the following main components:
- Widget box: A panel containing a wide range of widgets (e.g., buttons, labels, sliders, and containers) that can be dragged and dropped into the design area.
- Design area: The central workspace where you design your user interface by arranging and customizing widgets. This area represents the application window or dialog you are creating.
- Property Editor: A side panel for modifying the properties of selected widgets, such as size, font, color, and alignment. It allows the fine-tuning of widget behavior and appearance.

Figure 16.2: Object property for the STOP button
Figure 16.2: Object property for the STOP button
The widgets can be directly dragged and dropped on the design area to create the desired interface. Considering the UI shown in Figure 16.1, we mainly used the following elements (also called widgets):
- QPushButton: To generate the velocity commands in different directions or publish zero velocities to stop the robot
- QLineEdit: To add text such as the topic name or the desired velocity
- QCheckBox: To enable or disable data streaming
You can arrange the widgets in any layout you prefer, or you can replicate the design shown in Figure 16.1. A crucial step is to assign meaningful names to each widget using the Property Editor. These names will be referenced in the C++ code to interact with the interface, such as detecting when a button is clicked or retrieving the text entered in a line box. For example, Figure 16.2 shows the Property box for a clickable button called stopButton.
After adding all the desired elements of the interface, you can save the source of the user interface in the src directory of the cmd_vel package. The extension of this file will be .ui.
The next step is to create the source code to react to the input received from the user interface, as discussed in the next section.
Implementing the plugin source
Section titled “Implementing the plugin source”The backend of the user interface is implemented as C++ source code. We will define a header file, located in the cmd_vel/include/cmd_vel/ directory, called cmd_vel.h, and source code placed in the cmd_vel/src folder, called cmd_vel.cpp. Let’s discuss the content of the header file (check the code repository of the book for the full source code):
- At the start, the header to use the functionalities of the
rqtplugin is imported. Using theplugin.hheader, we have access to the function allowing the registration of the plugin:#include "geometry_msgs/msg/twist.hpp"#include <rqt_gui_cpp/plugin.h> - The
.uifile is translated into a header file that gives us access to the components of the interface. The name of this file is the same as the one given to the.uifile but with the header file extension (ui_cmd_vel_ui.h). Later, we will discuss how we request the conversion from the.uifile to the.hone:#include "ui_cmd_vel_ui.h" - The plugin code must be included in a namespace. The namespace will be used in the
exportfunction. Here, we incorporate the code in the namespacecmd_vel:namespace cmd_vel { - The class that implements the function of the plugin is called
CmdVeland is inherited from therqt_gui_cpp::Pluginclass to integrate therqtframework. In addition, we must add a macro to our class, theQ_OBJECTmacro, which is part of the Qt framework. It enables Qt’s meta-object features, such as the slots (a sort of callback), dynamic properties, and introspection. Any class that defines custom signals or slots must include this macro:class CmdVel : public rqt_gui_cpp::Plugin {Q_OBJECTpublic:CmdVel(); - The
initPluginfunction is called when the plugin is initialized. This function must be implemented as part of therqtframework, such as the shutdown function. Then, we add a series of functions that will be called directly when the user interface is used. For example, theonTextChangedfunction is called when a new topic name is written into the text box. Some of these functions accept an input value, such as theonEnableButtonone:virtual void initPlugin(qt_gui_cpp::PluginContext& context);virtual void shutdownPlugin();void onTextChanged();void onEnableButton(int state);... - In the class variable list, we must add an object representing the widget class, generated from the user interface file (
.ui), and a pointer to aQWidget, the base class for all GUI objects in Qt that represent the whole plugin window:protected:Ui::CmdVelWidget ui_;QWidget* widget_; - In addition, we must include the ROS 2 variables, the publisher of the
twistcommand, thetwistcommand, and the ROS 2 node:rclcpp::Node::SharedPtr ros2_node;rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_publisher_;geometry_msgs::msg::Twist cmd_vel_msg_;
Now that the plugin class is prepared, we can implement its behavior in the C++ file, cmd_vel.cpp:
- In the C++ file, we must include everything that is needed for ROS 2 and Qt to work properly. The
rclcppand the pluginlib headers mainly contain all the functions needed by this code:#include "cmd_vel/cmd_vel.h"#include <pluginlib/class_list_macros.hpp>#include <rclcpp/rclcpp.hpp>#include <sstream> - The class is defined in the same plugin of the header file and extends the
Pluginclass. The Qt framework allows the initialization of the current working object with a reference name,CmdVel:namespace cmd_vel {CmdVel::CmdVel() : rqt_gui_cpp::Plugin(),widget_(0),enable_streaming_(false) {setObjectName("CmdVel");} - In the initialization function, we initialize the widget that is the connection point between this code and the elements included in the user interface:
void CmdVel::initPlugin(qt_gui_cpp::PluginContext& context) {widget_ = new QWidget();ui_.setupUi(widget_);if (context.serialNumber() > 1)widget_->setWindowTitle(widget_->windowTitle() + " (" + QString::number(context.serialNumber()) + ")");context.addWidget(widget_);
- After the initialization of the ROS 2 node that allows us to publish the
twistcommand data, we connect the elements of the user interface with the code. This is a similar approach to callbacks. When an element of the UI is touched correctly, the defined function is called:ros2_node_ = rclcpp::Node::make_shared("custom_cmd_vel_plugin"); - For example, we want to change the behavior of the plugin when a new text is written in the
topicNamebox. Of course, the callback of this element must be called only after that enter is pressed on the same box since this means that the user completed writing the desired topic name. For this reason, theonTextChangedfunction is called when the user presses Enter (returnPressed) on the text box:connect(ui_.topicName, &QLineEdit::returnPressed, this, &CmdVel::onTextChanged);connect(ui_.desVel, &QLineEdit::returnPressed, this, &CmdVel::onVelChanged); - Similarly, the callback of the
enableelement is called when its state changes. The other callbacks are called when the relative button is clicked:connect(ui_.enableButton, &QCheckBox::stateChanged, this, &CmdVel::onEnableButton);connect(ui_.stopButton, &QPushButton::clicked, this, &CmdVel::onStopButton); - In the callback of the
velocitytext box, we retrieve the inserted value, converting it into a double value when this is possible. If the conversion is not possible, the desiredvelocityquantity remains the same:void CmdVel::onVelChanged() {double str2double;std::istringstream iss( ui_.desVel->text().toStdString() );iss >> str2double;if (!(iss.fail() || !iss.eof()) )des_vel_ = str2double;} - Every time the topic name changes, the publisher of the twist velocity is updated:
void CmdVel::onTextChanged() {std::string topicNameValue = ui_.topicName->text().toStdString();if( topicNameValue != "" )cmd_vel_publisher_ = ros2_node_->create_publisher<geometry_msgs::msg::Twist>(topicNameValue, 10);}void CmdVel::onEnableButton(int state) {if( state == Qt::Checked ) {enable_streaming_ = true;}else {enable_streaming_ = false;}}
- Some robot models maintain the command of the last received velocity command, even if it is not published anymore. For this reason, our interface considers a STOP button that resets the streaming velocity:
void CmdVel::onStopButton() {cmd_vel_msg_ = geometry_msgs::msg::Twist();cmd_vel_publisher_->publish( cmd_vel_msg_ );
- Each of the other callbacks changes the current velocity message according to the clicked button.
void CmdVel::onForwardButton() {cmd_vel_msg_ = geometry_msgs::msg::Twist();cmd_vel_msg_.linear.x = des_vel_;if( enable_streaming_ && cmd_vel_publisher_ ) cmd_vel_publisher_->publish( cmd_vel_msg_ );
- At the end of the code, we must register the plugin in the
pluginlibsystem with thePLUGINLIB_EXPORT_CLASSmacro. This allows yourCmdVelclass to be dynamically loaded as a plugin by the ROS 2 framework:PLUGINLIB_EXPORT_CLASS(cmd_vel::CmdVel, rqt_gui_cpp::Plugin)
The source code is now complete. We can compile it and configure it.
Adding compilation and configuration files
Section titled “Adding compilation and configuration files”Each plugin needs an XML configuration file, defining the object that will be loaded when the plugin is requested. Let’s discuss the configuration file of the CmdVel plugin. Here, the <library> tag specifies the shared library, cmd_vel. The <class> tag registers the plugin cmd_vel::CmdVel (derived from rqt_gui_cpp::Plugin) with a unique name, cmd_vel/CmdVel. <description> provides a brief summary, while the <qtgui> section customizes the plugin’s appearance in the GUI:
<library path="cmd_vel"> <class name="cmd_vel/CmdVel" type="cmd_vel::CmdVel" base_class_type="rqt_gui_cpp::Plugin"> <description> A GUI plugin to control velocity commands. </description> <qtgui> <group> <label>Control</label> <icon type="theme">folder</icon> <statustip>Plugin</statustip> </group><label>Vel control</label> </qtgui></class></library>After compiling and sourcing the workspace, we can access this plugin in the rqt window by following these steps:
- Click on Plugins in the menu.
- Navigate to Control.
- Select Vel Control.
Finally, we must write the CMakeLists.txt file. The salient part of the file is reported in the following code. It defines a shared library for the cmd_vel plugin. It specifies the source (cmd_vel.cpp), headers (cmd_vel.h), and a Qt UI file (cmd_vel_ui.ui). Qt tools (qt5_wrap_cpp and qt5_wrap_ui) process MOC and UI files.
The library includes directories (such as ${CMAKE_BINARY_DIR}) and links to ROS 2 libraries (rclcpp, qt_gui_cpp, rqt_gui_cpp, and message packages) and Qt5::Widgets. It installs the library, headers, and plugin.xml, and exports the plugin description for pluginlib:
add_library(${PROJECT_NAME} SHARED ${cmd_vel_SRCS} ${cmd_vel_MOCS} ${cmd_vel_UIS_H )target_include_directories(${PROJECT_NAME} PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>" "$<INSTALL_INTERFACE:include/${PROJECT_NAME}>")target_link_libraries(${PROJECT_NAME} PUBLIC ${rclcpp_TARGETS} ${qt_gui_cpp_TARGETS} ${rqt_gui_cpp_TARGETS} ${sensor_msgs_TARGETS} ${geometry_msgs_TARGETS} Qt5::Widgets)install( TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME ARCHIVE DESTINATION lib/${PROJECT_NAME} LIBRARY DESTINATION lib/${PROJECT_NAME} RUNTIME DESTINATION bin/${PROJECT_NAME})install(DIRECTORY include/ DESTINATION include ${PROJECT_NAME})install(FILES plugin.xml DESTINATION share/${PROJECT_NAME})The plugin.xml file is referenced in the CMakeLists.txt file to correctly reference the loading procedure:
pluginlib_export_plugin_description_file(rqt_gui "plugin.xml")Finally, to convert the .ui file into the header one, we use the following line:qt5_wrap_ui(cmd_vel_UIS_H ${cmd_vel_UIS})To execute the rqt plugin, we must compile the workspace and start the rqt program:colcon build --symlink-installrqtNow, we can select the plugin and monitor the velocity commands published to the chosen topic. We can test this plugin on a simulated robot. This time, we’ll use a simulation plugin that integrates directly with the Gazebo simulator, as discussed in the next section.
Developing a Gazebo plugin
Section titled “Developing a Gazebo plugin”Gazebo plugins are components that extend the functionality of the Gazebo simulator. They allow users to add custom behavior to the simulation, such as controlling sensors, actuators, or environments, and interfacing with other software such as ROS 2. Gazebo plugins can be categorized into two main types: world plugins, which modify the simulation environment, allowing you to control how the world behaves or is initialized (e.g., setting up the environment and adding objects), and model plugins, which are attached to specific models (e.g., robots or sensors) to control their behavior, such as simulating a robot’s motion, controlling actuators, or interfacing with sensors. The plugins can be loaded into Gazebo at runtime via SDF or URDF files. Let’s develop a new model plugin that directly controls a differential drive robot by sending control commands on the Gazebo topic for twist velocity. The plugin receives the control data from an external source (such as the plugin developed in the previous section). So, in principle, this plugin emulates the behavior of the Gazebo bridge, but once it receives the desired velocity, it saturates them with a maximum value.
Writing the source code
Section titled “Writing the source code”The Gazebo plugin must be included in a ROS 2 package, so let’s start creating it:
ros2 pkg create cmd_vel_plugin --dependencies rclcpp std_msgs geometry_msg gz-cmake3The dependency from the gz-cmake3 library allows us to link the ROS 2 function with the Gazebo ones. We can now fill in the source code of the Gazebo plugin, pub_cmd_vel.cpp:
- First, ROS 2 and Gazebo header files are needed. Apart from the ROS ones, the
gzheader allows the registration and initialization of the new plugin:#include "rclcpp/rclcpp.hpp"#include <geometry_msgs/msg/twist.hpp>#include <gz/common/Console.hh>#include <gz/messages/details/twist.pb.h>#include <gz/plugin/Register.hh>#include <gz/sim/System.hh>#include <gz/transport/Node.hh>#include <sdf/sdf.hh> - We can define the plugin class. The
PubCmdVelclass inherits fromgz::sim::System, the base for all Gazebo plugins, and two specific interfaces:ISystemConfigureandISystemPostUpdate.ISystemConfigureallows the plugin to handle setup tasks during initialization, such as configuring ROS nodes and subscribers.ISystemPostUpdateenables the plugin to execute actions after each simulation update, such as processing data or publishing updates to Gazebo. These interfaces integrate the plugin into Gazebo’s lifecycle for configuration and runtime updates:namespace cmd_vel_plugin {class PubCmdVel:public gz::sim::System,public gz::sim::ISystemConfigure,public gz::sim::ISystemPostUpdate { - Some system functions that are called automatically with the Gazebo lifecycle can be implemented. The
PostUpdatefunction is called directly after an execution cycle of the simulation. In contrast, theConfigurefunction is called when the plugin is loaded:public: void PostUpdate(const gz::sim::UpdateInfo &_info, const gz::sim::EntityComponentManager &_ecm) override;public: void Configure(const gz::sim::Entity &_id,const std::shared_ptr<const sdf::Element> &_sdf, gz::sim::EntityComponentManager &_ecm, gz::sim::EventManager &_eventMgr) final; - Finally, the callback of the topic for the twist velocity, published on the ROS 2 network, is defined:
public: void cmd_vel_cb( const geometry_msgs::msg::Twist );
- As for class variables, a reference to the ROS 2 node connecting the simulation to the ROS 2 network is defined, along with the ROS 2 subscriber and the Gazebo publisher:
private: rclcpp::Node::SharedPtr ros_node_;private:rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr ros_subscriber_;gz::transport::Node::Publisher gz_publisher_;gz::transport::Node gz_node_;gz::msgs::Twist cmd_vel_msg_;
- The plugin is registered using the
GZ_ADD_PLUGINfunction. This line registers thePubCmdVelclass as a Gazebo plugin usingGZ_ADD_PLUGIN. It specifies thatPubCmdVelimplements thegz::sim::Systembase class and theISystemConfigureandISystemPostUpdateinterfaces. This registration allows Gazebo to recognize and load the plugin, enabling it to participate in the simulation lifecycle for configuration and post-update tasks:GZ_ADD_PLUGIN (cmd_vel_plugin::PubCmdVel,gz::sim::System,cmd_vel_plugin::PubCmdVel::ISystemConfigure,cmd_vel_plugin::PubCmdVel::ISystemPostUpdate) - In the twist message callback, we just saturate the input velocity to a fixed value,
0.2for linear and0.5for angular velocities:void PubCmdVel::cmd_vel_cb( const geometry_msgs::msg::Twist t) {_double vx = t.linear.x;if( vx > 0.2) vx = 0.2;else if (vx < -0.2) vx = -0.2;cmd_vel_msg_.mutable_linear()->set_x (vx);double vz = t.linear.z;if( vz > 0.2) vz = 0.2;else if (vz < -0.2) vz = -0.2;cmd_vel_msg_.mutable_linear()->set_z (vz);double vrot_z = t.angular.z;if( vrot_z > 0.5 ) vrot_z = 0.5;else if (vrot_z < -0.5) vrot_z = 0.5;cmd_vel_msg_.mutable_angular()->setz(vrot_z); - In the
Configurefunction, the ROS 2 node must be initialized along with the subscriber to the ROS 2 twist message:void PubCmdVel::Configure(const gz::sim::Entity &_entity, const std::shared_ptr<const sdf::Element> &_sdf, gz::sim::EntityComponentManager &, gz::sim::EventManager &){rclcpp::init(0, nullptr);ros_node_ = rclcpp::Node::make_shared("cmd_vel_plugin");ros_subscriber_ = ros_node_->create_subscription<geometry_msgs::msg::Twist>("/cmd_vel_from_ros", 10, std::bind(&PubCmdVel::cmd_vel_cb, this, std::placeholders::_1)); - The publisher of the Gazebo
cmd_veltopic, used from the robot to actuate the differential base, is initialized:gz_publisher_ = gz_node_.Advertise<gz::msgs::Twist>("/cmd_vel"); - In the
PostUpdatefunction, we must only apply the velocity commands received as input. We also request to spin the node to enable the input via the callbacks. Once a velocity message is sent, the robot will continue moving, even if no new messages are published. To stop the robot, a velocity message with a value of 0 must be published on the topic:void PubCmdVel::PostUpdate(const gz::sim::UpdateInfo &_info, const gz::sim::EntityComponentManager &/*_ecm*/) {rclcpp::spin_some( ros_node_ );gz_publisher_.Publish(cmd_vel_msg_);}
The source code is now complete and can be used. To use it, we must set up the compilation file and add the plugin to a simulation model, as discussed in the next section.
Compiling and executing the Gazebo plugin
Section titled “Compiling and executing the Gazebo plugin”The CMakeLists.txt of the package must be modified to add compilation options for the plugin. The following lines are used to link the Gazebo functions with the node:
gz_find_package(gz-plugin2 REQUIRED COMPONENTS register)set(GZ_PLUGIN_VER ${gz-plugin2_VERSION_MAJOR})gz_find_package(gz-sim8 REQUIRED)set(GZ_SIM_VER ${gz-sim8_VERSION_MAJOR})The shared library is generated starting from the C++ file:
add_library(CmdVelPlugin SHARED src/pub_cmd_vel.cpp)Additional libraries are used from the CmdVelPlugin one. Finally, ROS 2 dependencies are linked to it:
target_link_libraries(CmdVelPlugin gz-plugin${GZ_PLUGIN_VER}::gz-plugin${GZ_PLUGIN_VER} gz-sim${GZ_SIM_VER}::gz-sim${GZ_SIM_VER})ament_target_dependencies(CmdVelPlugin rclcpp std_msgs geometry_msgs)install(DIRECTORY launch urdf DESTINATION share/${PROJECT_NAME})After compiling the plugin, by compiling the workspace, we need to incorporate it into SDF or a .xacro file. In the online version of the package, in the book code repository, a differential drive robot model that already uses this plugin is provided. In particular, diff_drive.urdf.xacro contains the following line:
<plugin filename="CmdVelPlugin" name="cmd_vel_plugin::PubCmdVel"> </plugin>Here, we have the following elements:
filename="CmdVelPlugin": Specifies the name of the shared library file (e.g.,libCmdVelPlugin.so) that contains the plugin codename="cmd_vel_plugin::PubCmdVel": Specifies the fully qualified C++ class name (cmd_vel_plugin::PubCmdVel) that implements the plugin
This tells Gazebo to load the CmdVelPlugin library and initialize the PubCmdVel class as part of the simulation. Now, you can test the plugin by starting the simulation using the following command:
ros2 launch cmd_vel_plugin cmd_vel_plugin.launch.pyAt this point, you can publish desired velocity commands on the topic: /cmd_vel_from_ros. As promised above, this is a good chance to use the rqt plugin developed in the previous example.
At this point, it is quite clear how plugins can be useful to extend the functionality of software. Another software used in robotics is RViz2. In the next section, we will discuss our last example and learn how to create plugins for RViz2.
Developing plugins for RViz2
Section titled “Developing plugins for RViz2”An RViz2 plugin is a modular extension for RViz2, the visualization tool in ROS 2, designed to display and interact with robotic data. Plugins allow users to add custom functionality, such as new display types for specific message formats, custom visualization panels, or tools for user interaction. They are implemented as shared libraries using the pluginlib framework, enabling dynamic loading without modifying RViz2 ‘s core. By creating RViz2 plugins, developers can tailor the visualization experience to specific applications, enhancing debugging, monitoring, and control in robotic systems. In this example, we will create a plugin to display a circumference with a given center coordinates and a radius. The final shape of the circumference shown on RViz2 is displayed in Figure 16.3.

Figure 16.3: Circumference published on RViz2 using a custom plugin
Figure 16.3: Circumference published on RViz2 using a custom plugin
Writing the source code
Section titled “Writing the source code”To develop the plugin, let’s start by creating the ROS 2 packages containing the plugin files. First, we need a custom message to receive the data published on RViz2. For simplicity, we avoid discussing how the message is created. However, the type of the message is circle_msgs::Circle and the fields of the message are the following:
std_msgs/Header headerfloat32 xfloat32 yfloat32 radiusThe package implementing such a message can be found in the GitHub repository of the book. Let’s now create the package to implement the plugin:
ros2 pkg create circle_display_plugin --dependencies rclcpp pluginlib rviz_common rviz_rendering circle_msgsAlso, in this case, we will exploit the Qt framework to embed the plugin into the RViz2 window. However, differently from the rqt plugin, we will use the elements already available in RViz2 to set up the visualization properties.
Let’s start by discussing the header file of the plugin, circle_display.hpp:
- First, the headers to access
RViz2functionalities must be included. Depending on the shape to visualize, different headers must be included. In this example, we will use the Sphere and the Billboard shapes. For this reason, we will include the relative header files:#include <OgreVector3.h>#include <circle_msgs/msg/circle.hpp>#include#include <rviz_common/display_context.hpp>#include <rviz_common/frame_manager_iface.hpp>#include <rviz_common/interaction/selection_manager.hpp>#include <rviz_common/logging.hpp>#include <rviz_common/message_filter_display.hpp>#include <rviz_common/properties/parse_color.hpp>#include <rviz_rendering/objects/billboard_line.hpp>#include <rviz_rendering/objects/grid.hpp>#include <rviz_rendering/objects/shape.hpp> - Each object to visualize can be linked with some properties that are set from the
RViz2interface. For example, from the interface, we can modify the marker color and its width. For this reason, we need to receive a color and width property:#include <rviz_common/properties/property.hpp>#include <rviz_common/properties/float_property.hpp>#include <rviz_common/properties/color_property.hpp> - In this plugin, the code is encapsulated within a namespace. The plugin’s class is inherited from
rviz_common::MessageFilterDisplayto visualizecircle_msgs::msg::Circlemessages inRViz2. It uses Qt functionality via Q_OBJECT and defines two private slots,updateStyleandupdateStyleLine. These slots are functions triggered by inputs from theRViz2interface, allowing the display’s appearance to be updated dynamically:namespace rviz_circle_plugin {class CircleDisplay : public rviz_common::MessageFilterDisplay<circle_msgs::msg::Circle{Q_OBJECTprivate Q_SLOTS:void updateStylePoint();void updateStyleLine(); - As for the functions, we must provide an implementation for the initialization function. In addition, the
processMessagefunction is called every time a new message is received on the visualization topic:protected:void onInitialize() override;void processMessage(const circle_msgs::msg::Circle::ConstSharedPtr msg) override;std::unique_ptr<rviz_rendering::Shape> point_shape_;std::unique_ptr<rviz_rendering::BillboardLine> circle_line_; - The properties to customize the visualization are declared:
std::unique_ptr<rviz_common::properties::ColorProperty> color_property_;std::unique_ptr<rviz_common::properties::ColorProperty> line_color_property_;std::unique_ptr<rviz_common::properties::FloatProperty> line_width_property_;std::unique_ptr<rviz_common::properties::FloatProperty> circle_width_property_;
The header file is now complete. We must implement the behavior of the plugin in the source file, circle_display.cpp:
- Include the header file and define the namespace:
#include <circle_display_plugin/circle_display.hpp>namespace rviz_circle_plugin {using rviz_common::properties::StatusProperty;
- In the initialization method, the plugin is initialized with its base class and the required visual elements are created. A sphere (Shape) is used to represent the center point, and a
BillboardLineis created to depict the circle’s circumference. It also initializesRViz2properties, such as color and line width, with corresponding update methods (updateStyleandupdateStyleLine). These properties allow the dynamic adjustment of the circle’s appearance through theRViz2interface:void CircleDisplay::onInitialize() {MFDClass::onInitialize();point_shape_ = std::make_unique<rviz_rendering::Shape>(rviz_rendering::Shape::Type::Sphere, scene_manager_, scene_node_);circle_line_ = std::make_unique<rviz_rendering::BillboardLine>(scene_manager_, scene_node_);line_color_property_ = std::make_unique<rviz_common::properties::ColorProperty>("Circle Color", QColor(255, 0, 0), "Color to draw the circle.", this, SLOT(updateStyleLine()));line_width_property_ = std::make_unique<rviz_common::properties::FloatProperty>("Line Width", 0.1, "Width of the circle line.", this, SLOT(updateStyleLine()));color_property_ = std::make_unique<rviz_common::properties::ColorProperty>("Point Color", QColor(255, 0, 0), "Color to draw the point.", this, SLOT(updateStyle()));circle_width_property_ = std::make_unique<rviz_common::properties::FloatProperty>("Center Width", 0.1, "Width to center point.", this, SLOT(updateStyle()));updateStyle();updateStyleLine(); - The
processMessagemethod processes incomingcircle_msgs::msg::Circlemessages. It logs the message, validates the radius, and applies transformations to position the visual elements in the correct 3D space. The center point is set using the message’s coordinates, and a series of points approximating the circle’s circumference is generated based on its radius and number of segments, adding them to theBillboardLine. But how is this code linked to the input topic? When usingMessageFilterDisplay,RViz2provides a GUI where users can set the topic from which the plugin will subscribe. This is configured dynamically without requiring hardcoding:void CircleDisplay::processMessage(const circle_msgs::msg::Circle::ConstSharedPtr msg) {if( msg->radius <= 0.0 ) return;Ogre::Vector3 position;Ogre::Quaternion orientation;if (!context_->getFrameManager()->getTransform(msg->header, position, orientation)) {RVIZ_COMMON_LOG_DEBUG_STREAM("Error transforming from frame '" << msg->header.frame_id <<"' to frame '" << qPrintable(fixed_frame_) << "'");}scene_node_->setPosition(position);scene_node_->setOrientation(orientation);Ogre::Vector3 point_pos;point_pos.x = msg->x;point_pos.y = msg->y;point_shape_->setPosition(point_pos);// Generate points for the circleconst size_t num_segments = 100; // Number of segments to approximate the circleconst float radius = msg->radius;for (size_t i = 0; i <= num_segments; ++i) {float angle = static_cast<float>(i) * Ogre::Math::TWO_PI / static_cast<float>(num_segments);float x = msg->x + radius * std::cos(angle);float y = msg->y + radius * std::sin(angle);circle_line_->addPoint(Ogre::Vector3(x, y, 0.0f));}} - The
updateStylemethod adjusts the color and size of the center point using the configured properties.updateStyleLinemodifies the circle’s line color and width dynamically. These methods are triggered via Qt signals whenever the correspondingRViz2properties are updated, ensuring the visual elements reflect the user’s changes in real time:void CircleDisplay::updateStylePoint(){Ogre::ColourValue color = rviz_common::properties::qtToOgre(color_property_->getColor());If( point_shape_) {point_shape_->setColor(color);float size = circle_width_property_->getFloat();point_shape_->setScale(Ogre::Vector3(size, size, size));}void CircleDisplay::updateStyleLine(){if (circle_line_) {Ogre::ColourValue color = rviz_common::properties::qtToOgre(line_color_property_->getColor());circle_line_->setColor( color.r, color.g, color.b, 1 );float line_width = line_width_property_->getFloat();circle_line_->setLineWidth(line_width); - The plugin is registered using
PLUGINLIB_EXPORT_CLASS, enablingRViz2to dynamically load and integrate it into the visualization environment. This registration makesCircleDisplayavailable as a custom display type inRViz2:#include <pluginlib/class_list_macros.hpp>PLUGINLIB_EXPORT_CLASS(rviz_circle_plugin::CircleDisplay, rviz_common::Display)
As usual, the .xml file defining the plugin must be created. Here, the namespace and the plugin class must be correctly specified:
<library path="circle_display"> <class type="rviz_circle_plugin::CircleDisplay" base_class_type="rviz_common::Display"> <description></description> </class></library>Adding and configuring the RViz2 plugin
Section titled “Adding and configuring the RViz2 plugin”We are now ready to add the plugin. First, compile and source the workspace:
colcon build --symlink-installsource install/setup.bashNow, start RViz2:
rviz2If the plugin has been correctly compiled, by clicking the Add button of the RViz2 interface, we can select the new plugin. As you can see from Figure 16.4, it is named as the name of the package implementing the plugin plus the name of the class.

Figure 16.4: Add plugin panel in RViz2 where the custom plugin can be selected
Figure 16.4: Add plugin panel in RViz2 where the custom plugin can be selected
After adding the plugin, it appears in the display panel and can be correctly configured. An example of the use of the plugin can be seen in Figure 16.5, where the left part shows the configuration of the plugin, while the right shows rqt publishing the desired circle point. Finally, the center shows the result on RViz2.

Figure 16.5: CircleDisplay plugin with center coordinates 2, 2, and a 0.5 radius
Figure 16.5: CircleDisplay plugin with center coordinates 2, 2, and a 0.5 radius
As you can see from Figure 16.5, the topic on which the circle is published has been inserted, and it is /circle. On this topic, the circle_msgs::Circle is published, where the coordinates are x: 2 and y: 2. The radius instead is 0.5. At the same time, it is possible to change the width and the color of the circle and its center.
Implementing custom plugins simplifies the visualization process of robot data without depending on specific ROS 2 node implementations. Additionally, one can customize other aspects of RViz, such as interactive tools for manipulating different objects.
Summary
Section titled “Summary”Plugins are essential for extending the capabilities of ROS 2 and other software. ROS 2 supports various types of plugins, including controller plugins, visualization plugins, and rqt plugins. This chapter focused on visualization and rqt plugins, showcasing how to create a custom user interface for a robot and visualize ROS 2 data. Additionally, an example of a Gazebo plugin was presented, demonstrating how to use Gazebo’s features directly in C++ while integrating with the ROS 2 network.
Writing ROS 2 plugins is essential for extending the functionality of robotics systems, as it allows developers to customize and integrate hardware and software components efficiently. Learning to use ROS 2 ensures proficiency in a widely adopted framework, fostering modular development, scalability, and compatibility with cutting-edge robotics tools and technologies. In this chapter, we learned the basic way to develop and integrate plugins in our ROS 2 applications.
This chapter marks the conclusion of the journey through Mastering ROS 2. Throughout this book, we have explored and tested key topics in modern robotics, using realistic simulation environments to program mobile, aerial, and industrial robots.
We hope this book serves as a valuable reference for ROS 2 developers, offering guidance on specific topics for everyday projects. Now it’s your turn: apply what you’ve learned by experimenting with the programs and applications from these pages on your robot models, or even on your unique hardware setups.
The authors extend their heartfelt gratitude to you for reading and embracing this work.