Creating a nodelet

First of all, we will create a package called nodelet_hello_ros using the following command in our workspace:

$ catkin_create_pkg nodelet_hello_ros nodelet roscpp std_msgs 

Here, the nodelet package provides APIs to build a ROS nodelet. Now, we will create a file called /src/hello_world.cpp, which contains the source code for nodelet implementation inside the package. Alternatively, we could use the existing package from chapter3_tutorials/nodelet_hello_ros on GitHub:

#include <pluginlib/class_list_macros.h> 
#include <nodelet/nodelet.h> 
#include <ros/ros.h> 
#include <std_msgs/String.h> 
#include <stdio.h> 
 
namespace nodelet_hello_ros 
{ 
class Hello : public nodelet::Nodelet 
{ 
private: 
   virtual void onInit() 
   { 
         ros::NodeHandle& private_nh = getPrivateNodeHandle(); 
         NODELET_DEBUG("Initialized Nodelet"); 
         pub = private_nh.advertise<std_msgs::String>("ros_out",5); 
         sub = private_nh.subscribe("ros_in",5, &Hello::callback, this); 
    
   } 
   void callback(const std_msgs::StringConstPtr input) 
   { 
 
         std_msgs::String output; 
         output.data = input->data; 
 
         NODELET_DEBUG("msg data = %s",output.data.c_str()); 
         ROS_INFO("msg data = %s",output.data.c_str()); 
         pub.publish(output); 
          
   } 
  ros::Publisher pub; 
  ros::Subscriber sub; 
}; 
} 
PLUGINLIB_DECLARE_CLASS(nodelet_hello_ros,Hello,nodelet_hello_ros::Hello, nodelet::Nodelet); 

Here, we will create a nodelet class called Hello, which is inherited from a standard nodelet base class. In the ROS framework, all nodelet classes should inherit from the nodelet base class and be dynamically loadable using pluginlib. Here, the Hello class will be dynamically loadable.

In the initialization function on the nodelet, we will create a node handle object, a publisher topic, /ros_out, and a subscriber on the topic, /ros_in. The subscriber is bound to a callback function called callback(). This is where we would print the messages from the /ros_in topic onto the console and publish to the /ros_out topic.

Finally, we will export the Hello class as a plugin for dynamic loading using the PLUGINLIB_EXPORT_CLASS macro.