玩命加载中 . . .

ROS自定义类


头文件

#ifndef EXAMPLE_H_
#define EXAMPLE_H_


#include <math.h>
#include <stdlib.h>
#include <string>
#include <vector>

#include <ros/ros.h> 

#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_srvs/Trigger.h> 

// rossrv show std_msgs/Trigger
// bool success
// string message

class Example
{
public:
    Example(ros::NodeHandle* nodehandle);   // 构造函数,传句柄地址
private:
    ros::NodeHandle nh_; 
    ros::Subscriber minimal_subscriber_;
    ros::ServiceServer minimal_service_;
    ros::Publisher  minimal_publisher_;
    
    double val_from_subscriber_; 
    double val_to_remember_; 
    

    void initializeSubscribers();   // 初始化订阅者成员函数
    void initializePublishers();    // 初始化发布者成员函数
    void initializeServices();      // 初始化服务端成员函数
    
    // 回调函数
    void subscriberCallback(const std_msgs::Float32 &msg); 
    bool serviceCallback(std_srvs::Trigger::Request &request, std_srvs::Trigger::Response &response);
};

#endif

源文件

#include "Example.h"

Example::Example(ros::NodeHandle* nodehandle) : nh_(*nodehandle)
{
    ROS_INFO("in class constructor of Example");
    initializeSubscribers(); 
    initializePublishers();
    initializeServices();
}

void Example::initializeSubscribers()
{
    ROS_INFO("Initializing Subscribers");
    minimal_subscriber_ = nh_.subscribe("input_topic", 1, &Example::subscriberCallback, this);
    //函数指针和this指针
}

void Example::initializePublishers()
{
    ROS_INFO("Initializing Publishers");
    minimal_publisher_ = nh_.advertise<std_msgs::Float32>("output_topic", 1, true);
}

void Example::initializeServices()
{
    ROS_INFO("Initializing Services");
    minimal_service_ = nh_.advertiseService("service", &Example::serviceCallback, this);
}

void Example::subscriberCallback(const std_msgs::Float32 &msg)
{
    val_from_subscriber_ = msg.data;
    ROS_INFO("Receive message: %f", msg.data);   
    val_to_remember_ += val_from_subscriber_;
    std_msgs::Float32 output_msg;
    output_msg.data = val_to_remember_;
    minimal_publisher_.publish(output_msg);
}

bool Example::serviceCallback(std_srvs::Trigger::Request &request, std_srvs::Trigger::Response &response)
{
    ROS_INFO("service callback");
    response.success = true;
    response.message = "response message";
}


int main(int argc, char** argv)
{
    ros::init(argc, argv, "Example");
    ros::NodeHandle nh;
    Example example(&nh);   // 构造函数的参数是句柄地址
    ros::spin();
    return 0;
}

生成库文件

add_libraries(Example src/Example.cpp)

可执行文件链接库

add_executable(test_node src/test.cpp)
target_link_libraries(test_node Example)    // 添加自定义库

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录