Clion的部分详细操作可以看小弟的第一篇文章https://blog.csdn.net/EliGold/article/details/100122095。
本文是以柴长坤老师的《机器人操作系统》6.4节进行编程。也参考了这篇文章https://blog.csdn.net/EliminatedAcmer/article/details/80628121
1.Greeting.srv的编写与对应的头文件生成
在service_try目录下创建srv文件夹,在该文件夹内创建Greeting.srv。
Greeting.srv内容如下
string name
int32 age
---
string feedback
保存后,更改CMakeLists.txt和package.xml文件
CMakeLists.txt修改内容
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)
add_service_files(
FILES
Greeting.srv
)
generate_messages(
DEPENDENCIES
std_msgs
)
package.xml修改内容
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
修改完毕后就catkin_make操作下,生成的头文件会出现在ros_ws/devel/include/service_try内。
这次主要会用到Greeting.h
2.server.cpp和client.cpp的创建与编译
老办法,创建了这两个cpp文件后,在CMakeLists.txt进行如下修改操作:
include_directories(
# include
${catkin_INCLUDE_DIRS}
"~/code/ros_ws/devel/include"
)
add_executable(server src/server.cpp)
add_dependencies(server ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(server
${catkin_LIBRARIES})
add_executable(client src/client.cpp)
add_dependencies(client ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
target_link_libraries(client
${catkin_LIBRARIES})
然后就开始编写这两个cpp程序了
server.cpp
#include <ros/ros.h>
#include <service_try/Greeting.h>
bool handle_function(service_try::GreetingRequest &req, service_try::Greeting::Response &res)
{
//显示请求信息
ROS_INFO("Request from %s with age %d", req.name.c_str(),req.age);
//处理请求,结果写入response
res.feedback="Hi "+req.name+"! I am server!";
//返回true,正确处理请求
return true;
}
int main(int argc, char **argv)
{
ros::init(argc,argv,"greetings_server");//解析参数,命名节点
ros::NodeHandle nh; //创建句柄,实例化node
ros::ServiceServer service =nh.advertiseService("greetings", handle_function);//写明服务的处理函数
ros::spin();
return 0;
}
client.cpp
#include <ros/ros.h>
#include <service_try/Greeting.h>
int main(int argc, char **argv)
{
ros::init(argc,argv,"greetings_clint");//初始化,节点命名为“greetings_client”
ros::NodeHandle nh;
ros::ServiceClient client=nh.serviceClient<service_try::Greeting>("greetings");
//定义service客户端,service名字为“greetings”,service 的类型为Service_try
//实例化srv,设置其request消息的内容,这里request包括两个变量,name和age,见Greeting.srv
service_try::Greeting srv;
srv.request.name="HAN";
srv.request.age=20;
if(client.call(srv))
{
//注意我们的response部分中的内容只包含一个变量response,另,注意将其转化为字符串
ROS_INFO("Response from server: %s",srv.response.feedback.c_str());
}
else
{
ROS_ERROR("Fail to call service Service_try");
return 1;
}
return 0;
}
分别编译后,在新建terminal输入roscore。然后就能进行service操作了。
client显示的信息
server显示的信息