头文件
#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>
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);
}
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)