官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 揭西县| 丰顺县| 原阳县| 肃北| 富锦市| 南乐县| 蒙城县| 翼城县| 开原市| 民县| 湄潭县| 山阳县| 新竹县| 苍南县| 海丰县| 长沙县| 潮州市| 衡阳市| 通化市| 河曲县| 精河县| 萨嘎县| 万载县| 河间市| 井陉县| 日喀则市| 新田县| 绥滨县| 蓝田县| 晋城| 桐柏县| 台东县| 武山县| 昂仁县| 塔河县| 吐鲁番市| 龙陵县| 保山市| 本溪| 大厂| 略阳县|