当前位置:网站首页>4、 Service communication principle, code implementation
4、 Service communication principle, code implementation
2022-07-26 17:53:00 【Rock magnon】
List of articles
1、 Principle of service communication

- Server register
Server After starting , Will pass RPC The agreement Master Register your address and services in ( topic of conversation ) - Client register
Client After starting , Will be in Master Register the services you need in ( topic of conversation ) - matching
Master Match topics according to the registry , And will Server Of TCP Address through RPC The agreement is sent to Client - Client Send a request
Client received TCP After the address , adopt TCP Deal with the Server Establishing a connection , Send request data - Server Send corresponding
Server On request , Send results
Be careful :
In topic communication , Because it adopts subscription , There is no requirement for the sequence before and after the start of both parties . however , In service communication , Due to the way of request response , So start it first Server, Restart Client
2、 Service communication customization srv
- In service communication ,srv The document is divided into two parts : Client and server , In topic communication ,msg Only part of the document , Create... Under the function pack srv Catalog , Add... Below it xxx.srv file :
Be careful : Between the client and the server — Division# client int32 num1 int32 num2 --- # Server side int32 sum - Edit profile
- package.xml
<build_depend>message_generation</build_depend> <exec_depend>message_runtime</exec_depend> <!-- exce_depend It used to correspond to run_depend Now illegal --> - CmakeLists.txt
find_package(catkin REQUIRED COMPONENTS roscpp rospy std_msgs message_generation ) # Need to add message_generation, There has to be std_msgsadd_service_files( FILES AddInts.srv )generate_messages( DEPENDENCIES std_msgs ) - compile
The corresponding middleware will be generated after compilation , Include C++ Medium .h Document and Python Medium .py file
- package.xml
3、 Code implementation
1.C++ Realization
- vscode To configure , stay C++ in , Need configuration c_cpp_properies.json file , Mainly "includePath" Path settings , If not set , The generated .h file , In the process of typing code , There is no corresponding prompt
{ "configurations": [ { "browse": { "databaseFilename": "", "limitSymbolsToIncludedHeaders": true }, "includePath": [ "/opt/ros/noetic/include/**", "/usr/include/**", "/xxx/yyy working space /devel/include/**" // To configure head Path to file ], "name": "ROS", "intelliSenseMode": "gcc-x64", "compilerPath": "/usr/bin/gcc", "cStandard": "c11", "cppStandard": "c++17" } ], "version": 4 } - Server side
Test after service startup ://1. Include header file #include"ros/ros.h" // Path is : Function pack / The header file #include"server_client/add.h" // Callback function , Perform relevant service operations , The return value is of Bohr type bool doReq(server_client::add::Request &req, server_client::add::Response &resp){ int num1 = req.num1; int num2 = req.num2; ROS_INFO(" The data received by the server is :num1 = %d,num2 = %d",num1,num2); if(num1 < 0 || num2 < 0){ ROS_ERROR(" Data error !"); return false; } resp.sum = num1 + num2; return true; } int main(int argc, char *argv[]){ setlocale(LC_ALL,""); //2. initialization ROS node ros::init(argc,argv,"server");//server Name the node //3. establish ROS Handle ros::NodeHandle nh; //4. Create service object ,add_int For the topic ros::ServiceServer server = nh.advertiseService("add_int",doReq);//add_int Name the topic ROS_INFO(" Service startup "); //5. The callback function processes the request and generates a response //6.spin function , Without this function , The node will stop immediately after starting ros::spin(); return 0; }rosservice call Topic name+ Space + Tab Key to complete the parameters , Then modify the corresponding parameters . Be careful , During the test , Confirm that the server has started , And hang , Otherwise, there will be no corresponding topic - client
//1. Include header file #include"ros/ros.h" #include"server_client/add.h" int main(int argc, char *argv[]){ setlocale(LC_ALL,""); // stay launch In file , Parameter is 5 individual //argc Represents the number of parameters passed //argv Store the corresponding parameters : 0: The node name 1: The first parameter 2: The second parameter if(argc != 3){ ROS_ERROR(" Please submit two integers !"); return 1; } //2. initialization ros node ros::init(argc,argv,"client"); //3. establish ROS Handle ros::NodeHandle nh; //4. Create client objects , Submit the desired service ros::ServiceClient client = nh.serviceClient<server_client::add>("add_int"); /* In service communication , You need to start the server first , Have you got anything to do , For the convenience of the project , You can use the wait function , In this way, you can start the client first , Wait for the server to start */ // The way 1 ros::service::waitForService("add_int"); // The way 2 // client.waitForExistence(); //5. Organization request data server_client::add ai; ai.request.num1 = atoi(argv[1]); ai.request.num2 = atoi(argv[2]); //6. Send a request , return bool value , Success is true bool flag = client.call(ai); if (flag){ ROS_INFO(" Request OK , The result is :%d, %s, %s, %s",ai.response.sum,argv[0],argv[1],argv[2]); } else{ ROS_INFO(" request was aborted !"); return 1; } return 0; } - To configure CMakeLists.txt
add_executable(AddInts_Server src/AddInts_Server.cpp) add_executable(AddInts_Client src/AddInts_Client.cpp) add_dependencies(AddInts_Server ${ PROJECT_NAME}_gencpp) add_dependencies(AddInts_Client ${ PROJECT_NAME}_gencpp) target_link_libraries(AddInts_Server ${ catkin_LIBRARIES} ) target_link_libraries(AddInts_Client ${ catkin_LIBRARIES} ) - perform
- Start the service
rosrun Package name service name - Start the customer
rosrun Package name Customer name Parameters 1 Parameters 2
- Start the service
2.Python Realization
- vscode To configure , stay Python in , Need configuration setting.json file , Supplement of parameters
{ "python.autoComplete.extraPaths": [ "/opt/ros/noetic/lib/python3/dist-packages", ] } - Server side
#! /usr/bin/env python #1. Guide pack import rospy # From the function pack srv File import the corresponding data type from server_client.srv import add, addRequest, addResponse #req Parameters can be named casually , It's a class , But its element must be srv Parameters in def doReq(req): #num1 num2 by srv Data types defined in sum = req.num1 + req.num2 rospy.loginfo(" result :%d",sum) resp = addResponse(sum) # The callback function returns the response result return resp if __name__ == "__main__": #2. initialization ROS node Note that the node name is unique rospy.init_node("server_p") #3. Create service object # add_int_p Name the topic add Is the data type # doReq Is the callback function , Its data type is srv Data types in server = rospy.Service("add_int_p",add,doReq) #4. The callback function processes the request and generates a response #5.spin function rospy.spin() - client
#! /usr/bin/env python #1. Guide pack import rospy from server_client.srv import * import sys if __name__ == "__main__": if len(sys.argv) != 3: rospy.logerr(" Please enter the correct parameters !") sys.exit #2. initialization ROS node rospy.init_node("client_p") #3. Create request object # add_int_p For the topic , The same as the server # add Is the data type client = rospy.ServiceProxy("add_int_p",add) rospy.wait_for_service("add_int_p") # client.wait_for_service() #4. Send a request , Accept and deal with the corresponding # The way 1 #resp = client(3,4) # The way 2 #resp = client(addRequest(1,2)) # The way 3 req = addRequest() req.num1 = int(sys.argv[1]) req.num2 = int(sys.argv[2]) resp = client.call(req) rospy.loginfo(" The result is :%d",resp.sum) - Add executable rights
stay scripts Under the folder , perform :chmod +x *.py - To configure CMakeLists.txt file
catkin_install_python(PROGRAMS scripts/AddInts_Server_p.py scripts/AddInts_Client_p.py DESTINATION ${ CATKIN_PACKAGE_BIN_DESTINATION} ) - perform
- Server side :
rosrun Package name service - client :
rosrun Package name Customer Parameters 1 Parameters 2
Be careful : Service and customers are .py file
- Server side :
边栏推荐
- Spark data format unsafe row
- 【集训Day1】 Dwarves line up
- [300 opencv routines] 240. Shi Tomas corner detection in opencv
- Is it really safe and reliable to exempt five in case of opening an account in a stock company
- uni-app
- 浅谈数据技术人员的成长之路
- [Day2] cinema ticket
- [cloud native kubernetes actual combat] kubeopertor installation tutorial
- Asemi rectifier bridge kbpc2510, kbpc2510 parameters, kbpc2510 specifications
- 就这一次!详细聊聊分布式系统的那些技术方案
猜你喜欢

我们被一个 kong 的性能 bug 折腾了一个通宵
![[300 opencv routines] 240. Shi Tomas corner detection in opencv](/img/3a/0b81fb06e91e681ccc928e67297188.png)
[300 opencv routines] 240. Shi Tomas corner detection in opencv

【集训Day2】Sculpture

得不偿失!博士骗领210万元、硕士骗领3万元人才补贴,全被判刑了!

Spark unified memory partition

Summer Challenge openharmony greedy snake based on JS

# MySQL 七种连接方式图解

RedisDesktopManager去除升级提示
![Leetcode:1206. design jump table [jump table board]](/img/4f/2b6df8e2151b8bce70c8227c69d8bc.png)
Leetcode:1206. design jump table [jump table board]

跨站点请求伪造(CSRF)
随机推荐
AI遮天传 DL-回归与分类
#夏日挑战赛# OpenHarmony基于JS实现的贪吃蛇
Open source kaggle cat and dog data set -- used in classic CNN classification practice
The chess robot broke the finger of a 7-year-old boy because "the chess player violated safety rules"?
Gan (generative adversarial network, GaN) generative countermeasure network
图扑 3D 可视化国风设计 | 科技与文化碰撞炫酷”火花“
Hardware development and market industry
Common super easy to use regular expressions!
[training Day2] torchbearer
AI遮天传 ML-无监督学习
PIP installation module, error
ACL实验演示(Huawei路由器设备配置)
徽商期货网上开户安全吗?开户办理流程是怎样的?
【集训Day3】section
Brief introduction to CUDA image construction
【元宇宙欧米说】剖析 Web3 风险挑战,构筑 Web3 生态安全
Mondriaans‘s Dream(状态压缩DP)
国际大咖 VS 本土开源新星 | ApacheCon Asia 主题演讲议程全览
Summer Challenge openharmony greedy snake based on JS
一文详解吞吐量、QPS、TPS、并发数等高并发指标