当前位置:网站首页>ROS series (IV): ROS communication mechanism series (2): Service Communication
ROS series (IV): ROS communication mechanism series (2): Service Communication
2022-04-23 03:37:00 【Yi Lanjun】
Service communication is based on Request response pattern Of , It's a response mechanism . That is to say : A node A To another node B Send a request ,B Receive and process the request and generate a response. The result is returned to A.
For example, the following scenes : During the robot patrol , The control system analyzes the sensor data and finds suspicious objects or people , At this time, you need to take photos and keep them .
In the above scenario , Service communication is used . Service communication is more suitable for those who require timeliness 、 Application scenarios with certain logical processing .
1 Theoretical model of service communication
Service communication is simpler than topic communication , The theoretical model is shown in the figure below , There are three roles involved in the model :
- ROS master( managers )
- Server( Server side )
- Clien( client )
ROS Master Responsible for keeping Server and Client Registered information , And match the same topic Server And Client , help Server And Client Establishing a connection , After the connection is established ,Client Send request information ,Server Return response information .
The whole process is realized by the following steps :
1.1 Server register
Server After starting , Will pass RPC stay ROS Master Register your own information in , It contains the name of the service provided .ROS Master The registration information of the node will be added to the registry .
1.2 Client register
Client After starting , Also through RPC stay ROS Master Register your own information in , Contains the name of the service that needs to be requested .ROS Master The registration information of the node will be added to the registry .
1.3 ROS Master Realize information matching
ROS Master Will match according to the information in the registry Server and Client, And pass RPC towards Client send out Server Of TCP Address information .
1.4 Client Send a request
Client Follow the steps 2 Response information , Use TCP And Server Set up a network connection , And send request data .
1.5 Server Send a response
Server receive 、 Parse the requested data , And generate a response result and return it to Client.
2 Service communication customization srv( Customize communication with topics msg similar )
demand : Service communication , The client submits two integers to the server , The server sums and responds to the result to the client , Please create a data carrier for the communication between the server and the client .
technological process :srv The types of data available in the file are the same as msg The documents are consistent , And define srv Implementation process and customization msg The implementation process is similar to :
- Create in a fixed format srv file
- Edit profile
- Compile and generate intermediate files
2.1 Definition srv file
Service communication , The data is divided into two parts: request and response , stay srv Requests and responses in files use — To segment , The specific implementation is as follows :
New under function pack srv Catalog , add to xxx.srv file , Content :
# Two numbers sent when the client requests
int32 num1
int32 num2
---
# The server responds to the data sent
int32 sum
2.2 Edit profile
package.xml Add compilation dependency and execution dependency
<build_depend>message_generation</build_depend>
<exec_depend>message_runtime</exec_depend>
CMakeLists.txt edit srv Related configuration
find_package(catkin REQUIRED COMPONENTS
roscpp
rospy
std_msgs
message_generation
)
# Need to add message_generation, There has to be std_msgs
add_service_files(
FILES
AddInts.srv
)
generate_messages(
DEPENDENCIES
std_msgs
)
2.3 compile
View the compiled intermediate file :C++ Intermediate file to be called (…/ working space /devel/include/ Package name /xxx.h)
Subsequent calls related to srv when , Is called from these intermediate files .
3 Service communication customization srv call (C++)
demand : Write service communication , The client submits two integers to the server , The server sums and responds to the result to the client .
analysis : In model implementation ,ROS master There is no need to achieve , The establishment of the connection has also been encapsulated , There are three key points to pay attention to :
- Server side
- client
- data
technological process : - Write server implementation ;
- Write client implementation ;
- Edit profile ;
- Compile and execute .
3.1 vscode To configure
Need to customize as before msg Achieve the same configuration c_cpp_properies.json file , If the workspace has been configured before and has not been changed , You can ignore , If you need to configure , The configuration method is the same as before :
{
"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
}
3.2 Server side
/* demand : Write two nodes to realize service communication , The client node needs to submit two integers to the server The server needs to parse the data submitted by the client , Add up , Respond the results back to the client , The client parses again Server implementation : 1. Include header file 2. initialization ROS node 3. establish ROS Handle 4. establish service object 5. The callback function processes the request and generates a response 6. Because there are multiple requests , Need to call ros::spin() */
#include "ros/ros.h"
#include "demo03_server_client/AddInts.h"
// bool The return value depends on whether the flag is processed successfully
bool doReq(demo03_server_client::AddInts::Request& req,
demo03_server_client::AddInts::Response& resp){
int num1 = req.num1;
int num2 = req.num2;
ROS_INFO(" The request data received by the server is :num1 = %d, num2 = %d",num1, num2);
// Logical processing
if (num1 < 0 || num2 < 0)
{
ROS_ERROR(" The submitted data is abnormal : Data cannot be negative ");
return false;
}
// If there is no abnormality , Then add and assign the result to resp
resp.sum = num1 + num2;
return true;
}
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
// 2. initialization ROS node
ros::init(argc,argv,"AddInts_Server");
// 3. establish ROS Handle
ros::NodeHandle nh;
// 4. establish service object
ros::ServiceServer server = nh.advertiseService("AddInts",doReq);
ROS_INFO(" Service started ....");
// 5. The callback function processes the request and generates a response
// 6. Because there are multiple requests , Need to call ros::spin()
ros::spin();
return 0;
}
3.3 client
/* demand : Write two nodes to realize service communication , The client node needs to submit two integers to the server The server needs to parse the data submitted by the client , Add up , Respond the results back to the client , The client parses again Server implementation : 1. Include header file 2. initialization ROS node 3. establish ROS Handle 4. establish client object 5. Request service , Receiving response */
// 1. Include header file
#include "ros/ros.h"
#include "demo03_server_client/AddInts.h"
int main(int argc, char *argv[])
{
setlocale(LC_ALL,"");
// Dynamic value transfer when calling , If you pass launch Of args The ginseng , Number of parameters to be passed +3
if (argc != 3)
// if (argc != 5)//launch The ginseng (0- File path 1 Incoming parameter 2 Incoming parameter 3 The name of the node 4 Log path )
{
ROS_ERROR(" Please submit two integers ");
return 1;
}
// 2. initialization ROS node
ros::init(argc,argv,"AddInts_Client");
// 3. establish ROS Handle
ros::NodeHandle nh;
// 4. establish client object
ros::ServiceClient client = nh.serviceClient<demo03_server_client::AddInts>("AddInts");
// Wait for the service to start successfully
// The way 1
ros::service::waitForService("AddInts");
// The way 2
// client.waitForExistence();
// 5. Organization request data
demo03_server_client::AddInts ai;
ai.request.num1 = atoi(argv[1]);
ai.request.num2 = atoi(argv[2]);
// 6. Send a request , return bool value , Whether the marking is successful
bool flag = client.call(ai);
// 7. Process response
if (flag)
{
ROS_INFO(" Requests are processed normally , In response to the results :%d",ai.response.sum);
}
else
{
ROS_ERROR(" Request processing failed ....");
return 1;
}
return 0;
}
3.4 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}
)
3.5 perform
technological process :
- You need to start the service first :rosrun Package name service
- Then call the client :rosrun Package name client Parameters 1 Parameters 2
result : The results will be added according to the submitted data responses .
Be careful : If you start the client first , Then it will cause the operation to fail
Optimize : Add... Before the client sends the request :client.waitForExistence(); or :ros::service::waitForService(“AddInts”); This is a blocking function , The execution will not continue until the service is started successfully , You can use launch File optimization , But we need to pay attention args Transmission characteristics .
版权声明
本文为[Yi Lanjun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220602231818.html
边栏推荐
- Supersocket is Used in net5 - command
- Several common methods of multithreading
- File upload vulnerability summary and upload labs shooting range documentary
- Application and definition of interface
- STM32 advanced timer com event
- Design and implementation of redis (3): persistence strategy RDB, AOF
- Translation of l1-7 matrix columns in 2022 group programming ladder Simulation Competition (20 points)
- String input problem
- Design and implementation of redis (4): what is the event driver of redis
- The art of concurrent programming (3): an in-depth understanding of the principle of synchronized
猜你喜欢
PyMOL usage
Unity Basics
【微服务】(十)—— 统一网关Gateway
Instructions for fastmock
. net 5 Web custom middleware implementation returns the default picture
2022 团体程序设计天梯赛 模拟赛 L2-1 盲盒包装流水线 (25 分)
Supersocket is Use in net5 - startup
Visual programming -- how to customize the mouse cursor
C abstract class
Wechat applet cloud database value assignment to array error
随机推荐
If statement format flow
Several common methods of multithreading
Romantic silhouette of L2-3 of 2022 group programming ladder Simulation Competition (25 points)
打卡:4.22 C语言篇 -(1)初识C语言 - (11)指针
A sword is a sword. There is no difference between a wooden sword and a copper sword
Flink customizes the application of sink side sinkfunction
(valid for personal testing) compilation guide of paddedetection on Jetson
抽象类、接口、常用关键字
Unity knowledge points (ugui 2)
MySQL is completely uninstalled and MySQL service is cleaned up
将编译安装的mysql加入PATH环境变量
7-2 Tushare
JS changes the words separated by dashes into camel style
淺學一下I/O流和File類文件操作
Three types of cyclic structure
浅学一下I/O流和File类文件操作
Punch in: 4.22 C language chapter - (1) first knowledge of C language - (11) pointer
Problem B: small challenge
L3-011 直捣黄龙 (30 分)
深度学习笔记(二)——激活函数原理与实现