一般模式
学过C++类的都知道C++的类该怎么使用,对于ROS来说也是同样的做法。 在头文件中定义类:
- 定义私有和共有成员变量
- 定义类的构造函数
- 定义私有和共有成员函数
单独编写一个实现文件
头文件
#ifndef EXAMPLE_ROS_CLASS_H_
#define EXAMPLE_ROS_CLASS_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 ExampleRosClass
{
private:
ExampleRosClass(ros::NodeHandle* nodehandle);
public:
ros::NodeHandle n;
ros::Publisher minimal_publisher;
ros::Subscriber minimal_subscriber;
ros::ServiceServer minimal_service;
double val_from_subscriber;
double val_to_remember;
void initializePublishers();
void initializeSubscribers();
void initializeServices();
void subscriberCallback(const std_msgs::Float32& message_holder);
bool serviceCallback(std_srvs::TriggerRequest& request,std_srvs::TriggerResponse& response);
};
#endif
#实现文件
#include <example_ros_class.h>
ExampleRosClass::ExampleRosClass(ros::NodeHandle* nodehandle):n(*nodehandle)
{
ROS_INFO("in class constructor of ExampleRosClass");
initializePublishers();
initializeSubscribers();
initializeServices();
val_to_remember=0.0;
}
void ExampleRosClass::initializePublishers()
{
ROS_INFO("Initializing Publishers");
minimal_publisher=n.advertise<std_msgs::Float32>("example_class_output_topic",1,true);
}
void ExampleRosClass::initializeSubscribers()
{
ROS_INFO("Initializing Subscribers");
minimal_subscriber=n.subscribe("example_class_input_topic",1,&ExampleRosClass::subscriberCallback,this);
}
void ExampleRosClass::initializeServices()
{
ROS_INFO("Initializing Services");
minimal_service=n.advertiseService("example_minimal_service",&ExampleRosClass::serviceCallback,this);
}
void ExampleRosClass::subscriberCallback(const std_msgs::Float32& message_holder)
{
val_from_subscriber=message_holder.data;
ROS_INFO("myCallback activated: received value %f",val_from_subscriber);
std_msgs::Float32 output_msg;
val_to_remember += val_from_subscriber;
output_msg.data=val_to_remember;
minimal_publisher.publish(output_msg);
}
bool ExampleRosClass::serviceCallback(std_srvs::TriggerRequest& request,std_srvs::TriggerResponse& response)
{
ROS_INFO("service callback activated");
response.success = true;
response.message = "here is a response string";
return true;
}
int main(int argc,char **argv)
{
ros::init(argc,argv,"exampleRosClass");
ros::NodeHandle nh;
ROS_INFO("main:instantiating an objecy of type ExampleRosClass");
ExampleRosClass exampleRosClass(&nh);
ROS_INFO("main: going into spin");
ros::spin();
return 0;
}
刚开始我还以为是要单独拿出头文件来编译,结果发现根本就不需要,只要在同一个目录下,然后直接调用就行了。
运行结果
代码结构就不多讲了,就是一个很简单的订阅-发布通信方式,好吧还掺杂了一个服务客户端通信方式。
|