Skip to content
ImagineWorld

Implementing ROS 2 Visualization and Simulation Plugins

node_idnode-book_mastering-ros-2-for-robotics-programming_chapter-16-implementing-ros-2-visualization-and-simulation-plugins
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num16
chapter_titleImplementing ROS 2 Visualization and Simulation Plugins
governed_byCORPUS
constitutional_citationCONSTITUTION
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

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.

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 (.so on 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.

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-pluginlib

By 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_control plugins 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: Nav2 plugins for custom path planners, costmaps, and recovery behaviors
  • Visualization plugins: RViz plugins 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)
  • rqt plugins: 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:

  1. Create a new package to store the files to generate the library. This package must depend on pluginlib.
  2. 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.
  3. Implement the plugin by inheriting the interface. This implementation will depend on the plugin type that must be implemented.
  4. Register the plugin with pluginlib and describe it in an XML file. This allows the pluginlib tool to load the plugin when required.
  5. 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.

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_msgs

The 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.

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-qt6

To open the Designer instead, use the following command.

designer

After 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.

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 rqt plugin is imported. Using the plugin.h header, 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 .ui file 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 .ui file but with the header file extension (ui_cmd_vel_ui.h). Later, we will discuss how we request the conversion from the .ui file to the .h one:
    #include "ui_cmd_vel_ui.h"
  • The plugin code must be included in a namespace. The namespace will be used in the export function. Here, we incorporate the code in the namespace cmd_vel:
    namespace cmd_vel {
  • The class that implements the function of the plugin is called CmdVel and is inherited from the rqt_gui_cpp::Plugin class to integrate the rqt framework. In addition, we must add a macro to our class, the Q_OBJECT macro, 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_OBJECT
    public:
    CmdVel();
  • The initPlugin function is called when the plugin is initialized. This function must be implemented as part of the rqt framework, 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, the onTextChanged function is called when a new topic name is written into the text box. Some of these functions accept an input value, such as the onEnableButton one:
    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 a QWidget, 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 twist command, the twist command, 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:

  1. In the C++ file, we must include everything that is needed for ROS 2 and Qt to work properly. The rclcpp and 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>
  2. The class is defined in the same plugin of the header file and extends the Plugin class. 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");
    }
  3. 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_);
  4. After the initialization of the ROS 2 node that allows us to publish the twist command 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");
  5. For example, we want to change the behavior of the plugin when a new text is written in the topicName box. 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, the onTextChanged function 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);
  6. Similarly, the callback of the enable element 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);
  7. In the callback of the velocity text box, we retrieve the inserted value, converting it into a double value when this is possible. If the conversion is not possible, the desired velocity quantity 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;
    }
  8. 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;
    }
    }
  9. 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_ );
  10. 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_ );
  11. At the end of the code, we must register the plugin in the pluginlib system with the PLUGINLIB_EXPORT_CLASS macro. This allows your CmdVel class 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:

  1. Click on Plugins in the menu.
  2. Navigate to Control.
  3. 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-install
rqt

Now, 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.

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.

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-cmake3

The 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:

  1. First, ROS 2 and Gazebo header files are needed. Apart from the ROS ones, the gz header 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>
  2. We can define the plugin class. The PubCmdVel class inherits from gz::sim::System, the base for all Gazebo plugins, and two specific interfaces: ISystemConfigure and ISystemPostUpdate. ISystemConfigure allows the plugin to handle setup tasks during initialization, such as configuring ROS nodes and subscribers. ISystemPostUpdate enables 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 {
  3. Some system functions that are called automatically with the Gazebo lifecycle can be implemented. The PostUpdate function is called directly after an execution cycle of the simulation. In contrast, the Configure function 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;
  4. 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 );
  5. 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_;
  6. The plugin is registered using the GZ_ADD_PLUGIN function. This line registers the PubCmdVel class as a Gazebo plugin using GZ_ADD_PLUGIN. It specifies that PubCmdVel implements the gz::sim::System base class and the ISystemConfigure and ISystemPostUpdate interfaces. 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)
  7. In the twist message callback, we just saturate the input velocity to a fixed value, 0.2 for linear and 0.5 for 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);
  8. In the Configure function, 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));
  9. The publisher of the Gazebo cmd_vel topic, used from the robot to actuate the differential base, is initialized:
    gz_publisher_ = gz_node_.Advertise<gz::msgs::Twist>("/cmd_vel");
  10. In the PostUpdate function, 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.

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 code
  • name="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.py

At 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.

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

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 header
float32 x
float32 y
float32 radius

The 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_msgs

Also, 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:

  1. First, the headers to access RViz2 functionalities 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>
  2. Each object to visualize can be linked with some properties that are set from the RViz2 interface. 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>
  3. In this plugin, the code is encapsulated within a namespace. The plugin’s class is inherited from rviz_common::MessageFilterDisplay to visualize circle_msgs::msg::Circle messages in RViz2. It uses Qt functionality via Q_OBJECT and defines two private slots, updateStyle and updateStyleLine. These slots are functions triggered by inputs from the RViz2 interface, allowing the display’s appearance to be updated dynamically:
    namespace rviz_circle_plugin {
    class CircleDisplay : public rviz_common::MessageFilterDisplay<circle_msgs::msg::Circle{
    Q_OBJECT
    private Q_SLOTS:
    void updateStylePoint();
    void updateStyleLine();
  4. As for the functions, we must provide an implementation for the initialization function. In addition, the processMessage function 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_;
  5. 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:

  1. Include the header file and define the namespace:
    #include <circle_display_plugin/circle_display.hpp>
    namespace rviz_circle_plugin {
    using rviz_common::properties::StatusProperty;
  2. 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 BillboardLine is created to depict the circle’s circumference. It also initializes RViz2 properties, such as color and line width, with corresponding update methods (updateStyle and updateStyleLine). These properties allow the dynamic adjustment of the circle’s appearance through the RViz2 interface:
    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();
  3. The processMessage method processes incoming circle_msgs::msg::Circle messages. 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 the BillboardLine. But how is this code linked to the input topic? When using MessageFilterDisplay, RViz2 provides 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 circle
    const size_t num_segments = 100; // Number of segments to approximate the circle
    const 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));
    }
    }
  4. The updateStyle method adjusts the color and size of the center point using the configured properties. updateStyleLine modifies the circle’s line color and width dynamically. These methods are triggered via Qt signals whenever the corresponding RViz2 properties 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);
  5. The plugin is registered using PLUGINLIB_EXPORT_CLASS, enabling RViz2 to dynamically load and integrate it into the visualization environment. This registration makes CircleDisplay available as a custom display type in RViz2:
    #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>

We are now ready to add the plugin. First, compile and source the workspace:

colcon build --symlink-install
source install/setup.bash

Now, start RViz2:

rviz2

If 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.

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.