写点什么

【古月 21 讲】ROS 入门系列(3)——客户端 Client、服务器 Server 的编程实现 + 自定义服务数据编程实现

作者:秃头小苏
  • 2022 年 7 月 16 日
  • 本文字数:5872 字

    阅读完需:约 19 分钟

7、客户端 Client 的编程实现

  1. 创建功能包


cd ~/catkin_ws/srccatkin_create_pkg learning_service roscpp rospy std_msgs geometry_msgsturtlesim
复制代码


  1. 创建客户端代码(C++) ——文件名为 turtle_spawn.cpp


/***********************************************************************Copyright 2020 GuYueHome (www.guyuehome.com).***********************************************************************//*** 该例程将请求/spawn服务,服务数据类型turtlesim::Spawn*/#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的serviceros::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 spwan 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("Spwan turtle successfully [name:%s]",srv.response.name.c_str());return 0;};
复制代码


总结上面的代码,实现一个客户端的步骤为:初始化 ROS 节点创建一个 Client 实例发布服务请求数据等待 Server 处理后的应答结果 python 代码如下:


#!/usr/bin/env python# -*- coding: utf-8 -*-############################################################################Copyright 2020 GuYueHome (www.guyuehome.com).############################################################################ 该例程将请求/spawn服务,服务数据类型turtlesim::Spawnimport sysimport rospyfrom turtlesim.srv import Spawndef turtle_spawn():# ROS节点初始化rospy.init_node('turtle_spawn')# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的service

rospy.wait_for_service('/spawn')try:add_turtle = rospy.ServiceProxy('/spawn', Spawn)

# 请求服务调用,输入请求数据response = add_turtle(2.0, 2.0, 0.0, "turtle2")return response.nameexcept rospy.ServiceException, e:print "Service call failed: %s"%eif __name__ == "__main__":#服务调用并显示调用结果print "Spwan turtle successfully [name:%s]" %(turtle_spawn())
复制代码


  1. 配置客户端代码编译规则设置需要的编译的代码和生成的可执行文件


add_executable(turtle_spawn src/turtle_spawn.cpp)
复制代码


设置链接库


target_link_libraries(turtle_spawn ${catkin_LIBRARIES})
复制代码


  1. 编译并运行客户端


cd ~/catkin_wscatkin_makeroscorerosrun turtlesim turtlesim_noderosrun learning_service turtle_spawn
复制代码


运行结果如下,在坐标(2,2)处产生了一只新的乌龟。


8、服务端 Server 的编程实现

  1. 创建服务器代码(C++) ——文件名为 turtle_command_server.cpp


/***********************************************************************Copyright 2020 GuYueHome (www.guyuehome.com).***********************************************************************//*** 该例程将执行/turtle_command服务,服务数据类型std_srvs/Trigger*/#include <ros/ros.h>#include <geometry_msgs/Twist.h>#include <std_srvs/Trigger.h>ros::Publisher turtle_vel_pub;bool pubCommand = false;// service回调函数,输入参数req,输出参数resbool 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,注册回调函数commandCallbackros::ServiceServer command_service =n.advertiseService("/turtle_command", commandCallback);// 创建一个Publisher,发布名为/turtle1/cmd_vel的topic,消息类型为geometry_msgs::Twist,队列长度10turtle_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;}
复制代码


总结上面的代码,实现一个服务器的步骤为:初始化 ROS 节点创建 Serveer 实例循环等待服务请求,进入回调函数在回调函数中完成服务功能的处理,并反馈应答数据 python 代码如下:


#!/usr/bin/env python# -*- coding: utf-8 -*-############################################################################Copyright 2020 GuYueHome (www.guyuehome.com).############################################################################ 该例程将执行/turtle_command服务,服务数据类型std_srvs/Triggerimport rospyimport thread,timefrom geometry_msgs.msg import Twistfrom std_srvs.srv import Trigger, TriggerResponsepubCommand = False;turtle_vel_pub = rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10)def command_thread():while True:if pubCommand:vel_msg = Twist()vel_msg.linear.x = 0.5vel_msg.angular.z = 0.2turtle_vel_pub.publish(vel_msg)time.sleep(0.1)def commandCallback(req):global pubCommandpubCommand = bool(1-pubCommand)# 显示请求数据rospy.loginfo("Publish turtle velocity command![%d]", pubCommand)# 反馈数据return TriggerResponse(1, "Change turtle command state!")def turtle_command_server():# ROS节点初始化rospy.init_node('turtle_command_server')# 创建一个名为/turtle_command的server,注册回调函数commandCallbacks = rospy.Service('/turtle_command', Trigger, commandCallback)# 循环等待回调函数print "Ready to receive turtle command."thread.start_new_thread(command_thread, ())rospy.spin()if __name__ == "__main__":turtle_command_server()
复制代码


  1. 配置服务器代码编译规则设置需要编译的代码和生成可执行文件


add_executable(turtle_command_server src/turtle_command_server.cpp)
复制代码


设置链接库


target_link_libraries(turtle_command_server ${catkin_LIBRARIES})
复制代码


  1. 编译并运行服务器


cd ~/catkin_wscatkin_makeroscorerosrun turtlesim turtlesim_noderosrun learning_service turtle_command_serverrosservice call /turtle_command "{}"
复制代码


运行结果如下,可以发现可以通过客户端发送请求,然后达到控制海龟的运动和停止。


9、自定义服务数据

  1. 自定义服务数据


定义 srv 文件


//在learning_service目录下创建srv文件夹cd ~/catkin_ws/src/learning_topicmkdir srv//创建Penson.srv文件touch Person.srv
复制代码


创建好 Person.srv 文件后,在文件中写入以下内容:


string nameuint8 sexuint8 ageuint8 unknown = 0uint8 male = 1uint8 female = 2---string result
复制代码


在 package.xml 中添加功能包依赖


<build_depend>message_generation</build_depend><exec_depend>message_runtime</exec_depend>
复制代码


在 CMakeLists.txt 中添加编译选项


find_package( ...... message_generation)add_service_files(FILES Person.srv)generate_messages(DEPENDENCIES std_msgs)catkin_package(...... message_runtime)
复制代码



add_service_files(FILES Person.srv)generate_messages(DEPENDENCIES std_msgs)
复制代码



catkin_package(…… message_runtime)
复制代码



编译生成语言相关文件


cd ~/catkin_wscatkin_make
复制代码


  1. 创建服务器代码(C++)——文件名为 person_server.cpp


/***********************************************************************Copyright 2020 GuYueHome (www.guyuehome.com).***********************************************************************//*** 该例程将执行/show_person服务,服务数据类型learning_service::Person*/#include <ros/ros.h>#include "learning_service/Person.h"// service回调函数,输入参数req,输出参数resbool personCallback(learning_service::Person::Request&req,learning_service::Person::Response &res){// 显示请求数据ROS_INFO("Person: name:%sage:%dsex:%d", req.name.c_str(), req.age,req.sex);// 设置反馈数据res.result = "OK";return true;}int main(int argc, char **argv){// ROS节点初始化ros::init(argc, argv, "person_server");// 创建节点句柄ros::NodeHandle n;// 创建一个名为/show_person的server,注册回调函数personCallbackros::ServiceServer person_service = n.advertiseService("/show_person",personCallback);// 循环等待回调函数ROS_INFO("Ready to show person informtion.");ros::spin();return 0;}
复制代码


该部分和之前的步骤基本一致,这里不再进行总结。python 代码如下:


#!/usr/bin/env python# -*- coding: utf-8 -*-############################################################################Copyright 2020 GuYueHome (www.guyuehome.com).############################################################################ 该例程将执行/show_person服务,服务数据类型learning_service::Personimport rospyfrom learning_service.srv import Person, PersonResponsedef personCallback(req):# 显示请求数据rospy.loginfo("Person: name:%sreq.sex)# 反馈数据return PersonResponse("OK")def person_server():age:%dsex:%d", req.name, req.age,# ROS节点初始化rospy.init_node('person_server')# 创建一个名为/show_person的server,注册回调函数personCallbacks = rospy.Service('/show_person', Person, personCallback)# 循环等待回调函数print "Ready to show person informtion."rospy.spin()if __name__ == "__main__":person_server()
复制代码


  1. 创建客户端代码(C++)——文件名为 person_client.cpp


/***********************************************************************Copyright 2020 GuYueHome (www.guyuehome.com).***********************************************************************//*** 该例程将请求/show_person服务,服务数据类型learning_service::Person*/#include <ros/ros.h>#include "learning_service/Person.h"int main(int argc, char** argv){// 初始化ROS节点ros::init(argc, argv, "person_client");// 创建节点句柄ros::NodeHandle node;// 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的serviceros::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());return 0;};
复制代码


python 代码如下:


#!/usr/bin/env python# -*- coding: utf-8 -*-############################################################################Copyright 2020 GuYueHome (www.guyuehome.com).############################################################################ 该例程将请求/show_person服务,服务数据类型learning_service::Personimport sysimport rospyfrom learning_service.srv import Person, PersonRequestdef person_client():# ROS节点初始化rospy.init_node('person_client')# 发现/spawn服务后,创建一个服务客户端,连接名为/spawn的servicerospy.wait_for_service('/show_person')try:person_client = rospy.ServiceProxy('/show_person', Person)# 请求服务调用,输入请求数据response = person_client("Tom", 20, PersonRequest.male)return response.resultexcept rospy.ServiceException, e:print "Service call failed: %s"%eif __name__ == "__main__":#服务调用并显示调用结果print "Show person result : %s" %(person_client())
复制代码


  1. 配置服务器/客户端代码编译规则设置需要编译的代码和可执行文件设置链接库添加依赖项


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)
复制代码


  1. 编译并运行客户端和服务器


cd ~/catkin_wscatkin_makeroscorerosrun learning_service person_serverrosrun learning_service person_client
复制代码


运行结果如下,可以发现每次客户端发送请求后,服务器做出响应。



咻咻咻咻~~duang~~点个赞呗


上一篇:【古月21讲】ROS入门系列(2)——发布者Publisher、订阅者Subscriber的编程实现+自定义话题消息编程实现下一篇:【古月21讲】ROS入门系列(4)——参数使用与编程方法、坐标管理系统、tf坐标系广播与监听的编程实现、launch启动文件的使用方法

发布于: 刚刚阅读数: 3
用户头像

秃头小苏

关注

还未添加个人签名 2022.07.01 加入

还未添加个人简介

评论

发布
暂无评论
【古月21讲】ROS入门系列(3)——客户端Client、服务器Server的编程实现+自定义服务数据编程实现_ROS_秃头小苏_InfoQ写作社区