(五)ROS服务
服务消息
我还是先新建了一个程序包example_ros_service,然后新建了一个子目录srv,具体操作就不写了。
编写服务消息文件
修改程序包下的package.xml文件
修改程序包下的CMakeLists.txt文件
服务节点
#include <ros/ros.h>
#include <example_ros_service/ExampleServiceMsg.h>
#include <iostream>
#include <string>
using namespace std;
bool callback(example_ros_service::ExampleServiceMsgRequest& request,example_ros_service::ExampleServiceMsgResponse& response)
{
ROS_INFO("callback activated");
string in_name(request.name);
response.on_the_list=false;
if(in_name.compare("Bob")==0)
{
ROS_INFO("ask about Bob");
response.on_the_list=true;
response.good_guy=false;
response.age=32;
response.nickname="BobTheTerrible";
}
if(in_name.compare("Ted")==0)
{
ROS_INFO("ask about Ted");
response.on_the_list=true;
response.good_guy=true;
response.age=21;
response.nickname="Ted the Benevolent";
}
return true;
}
int main(int argc,char **argv)
{
ros::init(argc,argv,"example_ros_service");
ros::NodeHandle n;
ros::ServiceServer service=n.advertiseService("lookup_by_name",callback);
ROS_INFO("Ready to look up names.");
ros::spin();
return 0;
}
服务端就是由客户端触发,当客户端的call函数调用调用成功的时候,那么服务端就会在回调函数中处理话题的内容。
客户端节点
#include <ros/ros.h>
#include <example_ros_service/ExampleServiceMsg.h>
#include <iostream>
#include <string>
using namespace std;
int main(int argc,char **argv)
{
ros::init(argc,argv,"example_ros_client");
ros::NodeHandle n;
ros::ServiceClient client=n.serviceClient<example_ros_service::ExampleServiceMsg>("lookup_by_name");
example_ros_service::ExampleServiceMsg srv;
bool found_on_list;
string in_name;
while(ros::ok())
{
cout<<endl;
cout<<"enter a name (x to quit): ";
cin>>in_name;
if(in_name.compare("x")==0)
return 0;
srv.request.name=in_name;
if(client.call(srv))
{
if(srv.response.on_the_list)
{
if(srv.response.good_guy)
{
cout<<"He is a good guy"<<endl;
}
else
{
cout<<"He is not a good guy"<<endl;
}
}
else
{
cout<<srv.request.name<<" is not in the database"<<endl;
}
}
else
{
ROS_INFO("Failed to call service lookup_BY_name");
return 1;
}
}
return 0;
}
客户端节点就是用户用来操作的,当利用call()函数调用服务端成功后,就可以尽情享受服务结果了。(所以说,核心就在call()函数了)
服务端与客户端的交互
在上面的运行截图可以看到,当在客户端输入一个名字的时候,服务端就会判断是否合法.如果合法的话,那么就填充信息,客户端就会输出填充的信息;如果不合法,那么就凉菜了呗。