Step 3 - Explanation of hello_world.cpp

Here is the explanation of the code:

#include <pluginlib/class_list_macros.h> 
#include <nodelet/nodelet.h> 
#include <ros/ros.h> 
#include <std_msgs/String.h> 
#include <stdio.h> 

These are the header files of this code. We should include class_list_macro.h and nodelet.h to access the pluginlib APIs and nodelets APIs:

namespace nodelet_hello_world 
{ 
  class Hello : public nodelet::Nodelet 
  { 

Here, we create a nodelet class called Hello, which inherits a standard nodelet base class. All nodelet classes should inherit from the nodelet base class and be dynamically loadable using pluginlib. Here, the Hello class is going to be used for dynamic loading:

  virtual void onInit() 
  { 
    ros::NodeHandle& private_nh = getPrivateNodeHandle(); 
    NODELET_DEBUG("Initialized the Nodelet"); 
    pub = private_nh.advertise<std_msgs::String>("msg_out",5); 
    sub = private_nh.subscribe("msg_in",5, &Hello::callback, this); 
  } 

This is the initialization function of a nodelet. This function should not block or do significant work. Inside the function, we are creating a node handle object, topic publisher, and subscriber on the topic msg_out and msg_in, respectively. There are macros to print debug messages while executing a nodelet. Here, we use NODELET_DEBUG to print debug messages in the console. The subscriber is tied up with a callback function called callback(), which is inside the Hello class:

  void callback(const std_msgs::StringConstPtr input) 
  { 
    std_msgs::String output; 
    output.data = input->data; 
    NODELET_DEBUG("Message data = %s",output.data.c_str()); 
    ROS_INFO("Message data = %s",output.data.c_str()); 
    pub.publish(output); 
  } 

In the callback() function, it will print the messages from the /msg_in topic and publish to the /msg_out topic:

PLUGINLIB_EXPORT_CLASS(nodelet_hello_world::Hello,nodelet::Nodelet); 

Here, we are exporting Hello as a plugin for the dynamic loading.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.198.60