一、客户端和服务器的编程实现
1. 环境准备
- 切换到工作目录:
cd ~/catkin_ws/src
- 创建功能包:
catkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgs turtlesim
- 通讯模型图示如下:
2. 客户端Client代码
/**
* @file turtle_spawn.cpp
* @author zhaoxu (1852109@tongji.edu.cn)
* @brief 该例程将请求/spawn服务,服务数据类型turtlesim::Spawn
* @version 0.1
* @date 2022-04-23
*
* @copyright Copyright (c) 2022
*
*/
#include <ros/ros.h>
#include <turtlesim/Spawn.h>
int main(int argc, char **argv)
{
// 初始化ROS节点
ros::init(argc, argv, "turtle_spawn");
// 创建节点句柄
ros::NodeHandle node;
// 发现/Spawn服务后,创建一个服务客户端,连接名为/spawn的service
// 阻塞型等待存在spawn服务后再进行
ros::service::waitForService("/spawn");
ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("/spawn");
// 初始化turtlesim::Spawn的请求数据
turtlesim::Spawn srv;
srv.request.x = 2.0;
srv.request.y = 2.0;
srv.request.name = "turtle2";
// 请求服务调用
ROS_INFO("Call service to spawn turtle[x:%0.6f, y:%0.6f, name:%s]",
srv.request.x, srv.request.y, srv.request.name.c_str());
add_turtle.call(srv);
//显示服务调用结果
ROS_INFO("Spawn turtle successfully [name:%s]", srv.response.name.c_str());
return 0;
}
3. 服务端Server代码
/**
* @file turtle_command_server.cpp
* @author zhaoxu (1852109@tongji.edu.cn)
* @brief 该例程将执行/turtle_command服务,服务数据类型std_srvs/Trigger
* @version 0.1
* @date 2022-04-23
*
* @copyright Copyright (c) 2022
*
*/
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <std_srvs/Trigger.h>
ros::Publisher turtle_vel_pub;
bool pubCommand = false;
// service回调函数,输入参数req,输出参数res
bool commandCallback(std_srvs::Trigger::Request &req,
std_srvs::Trigger::Response &res)
{
pubCommand = !pubCommand;
// 显示请求数据
ROS_INFO("Publish turtle velocity command [%s]",
pubCommand == true?"Yes":"No");
// 设置反馈数据
res.success = true;
res.message = "Change turtle command state!";
return true;
}
int main(int argc, char **argv)
{
// 初始化ROS节点
ros::init(argc, argv, "turtle_command_server");
// 创建节点句柄
ros::NodeHandle n;
// 创建一个名为/turtle_command的server,注册回调函数commandCallback
ros::ServiceServer command_service = n.advertiseService("/turtle_command", commandCallback);
// 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型
// 为geometry_msgs::Twist,队列长度为10
turtle_vel_pub = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 10);
// 循环等待回调函数
ROS_INFO("Ready to receive turtle command.");
// 设置循环的频率
ros::Rate loop_rate(10);
while (ros::ok())
{
// 查看一次回调函数队列
ros::spinOnce();
// 如果标志为true,则发布速度指令
if (pubCommand)
{
geometry_msgs::Twist vel_msg;
vel_msg.linear.x = 0.5;
vel_msg.angular.z = 0.2;
turtle_vel_pub.publish(vel_msg);
}
// 按照循环频率延时
loop_rate.sleep();
}
return 0;
}
4. 编译并运行
添加编译规则
- 客户端代码编译规则:
在install部分之前添加如下指令:
add_executable(turtle_spawn src/turtle_spawn.cpp) #设置需要编译的代码和生成的可执行文件 target_link_libraries(turtle_spawn ${catkin_LIBRARIES}) #设置链接库
- 订阅者代码编译规则:
在install部分之前添加如下指令:
add_executable(turtle_command_server src/turtle_command_server.cpp) #设置需要编译的代码和生成的可执行文件 target_link_libraries(turtle_command_server ${catkin_LIBRARIES}) #设置链接库
编译并运行
- 在工作空间目录下编译:
cd ~/catkin_ws
catkin_make
- ROS命令:
roscore
rosrun turtlesim turtlesim_node
rosrun learning_service turtle_spawn
rosrun learning_service turtle_command_server
发送一次开始运动,再次停止
rosservice call /turtle_command "{}"
二、自定义服务
1. 自定义服务数据
- 创建srv文件夹:
- 内部创建Person.srv文件: 横线上为request,下为response
string name
uint8 age
uint8 sex
uint8 unknown = 0
uint8 male = 1
uint8 female = 2
---
string result
2. 添加功能包依赖和编译规则
- 修改XML文件:
添加如下指令
<build_depend>message_generation</build_depend> <exec_depend>message_runtime</exec_depend>
- 修改CMakelist文件:
在最初添加:
find_package(...... message_generation)
在Declare ROS之前添加:add_message_files(FILES Person.srv) generate_messages(DEPENDENCIES std_msgs)
在build之前添加
catkin_package(...... message_runtime)
- 编译:在编译后可以在devel下的include中找到learning_service的person头文件
3. 创建编译代码
客户端
- 头文件:
#include "learning_service/Person.h"
- 创建并连接服务,初始化数据、服务调用及显示:
// 发现/Spawn服务后,创建一个服务客户端,连接名为/spawn的service
// 阻塞型等待存在spawn服务后再进行
ros::service::waitForService("/show_person");
ros::ServiceClient person_client = node.serviceClient<learning_service::Person>("/show_person");
// 初始化learning_service::Person的请求数据
learning_service::Person srv;
srv.request.name = "Tom";
srv.request.age = 20;
srv.request.sex = learning_service::Person::Request::male;
// 请求服务调用
ROS_INFO("Call service to show person[name:%s, age:%d, sex:%d]",
srv.request.name.c_str(), srv.request.age, srv.request.sex);
person_client.call(srv);
//显示服务调用结果
ROS_INFO("Show person result: %s", srv.response.result.c_str());
服务端
- 头文件:
#include "learning_service/Person.h"
- 消息回调打印:
// 显示请求数据
ROS_INFO("Person: name:%s age:%d sex:%d", req.name.c_str(),
req.age, req.sex);
- 创建服务端:
// 创建一个名为/show_person的server,注册回调函数personCallback
ros::ServiceServer person_service = n.advertiseService("/show_person", personCallback);
4. 编译并运行
- 修改CMake文件
在install之前添加:
add_executable(person_server src/person_server.cpp) target_link_libraries(person_server ${catkin_LIBRARIES}) add_dependencies(person_server ${PROJECT_NAME}_gencpp) add_executable(person_client src/person_client.cpp) target_link_libraries(person_client ${catkin_LIBRARIES}) add_dependencies(person_client ${PROJECT_NAME}_gencpp)
- 编译并运行
cd ~/catkin_ws
catkin_make
roscore
rosrun learning_service person_server
rosrun learning_service person_client
请求一次回复一次,谁先都可以,因为存在等待,在运行程序之前,习惯重新打开roscore,放置存在变量/参数冲突
总结
本节博客主要对基于服务通信机制完成的C++编程实现,总体框架与上一节类似,后续入门课程还将推出三到四节内容,包含参数的使用,launch文件的具体解析,坐标变换与最终的总结展望,以十节博客完成基本的入门课程,敬请期待。