服务通信:自定义srv文件以及服务端的编写

首先新建功能包,可利用VS Code或者 catkin_create_pkg server_client roscpp rospy std_msgs

 

在其下建立srv文件夹,再建立Addints.srv文件(---用于区分请求和响应)

int32 num1

int32 num2

---

int32 sum

再在package.xml中修改如下:

message_generation

message_runtime

再在CMakeList.txt修改如下:

find_package(catkin REQUIRED COMPONENTS

roscpp

rospy

std_msgs

message_generation

)

add_service_files(

FILES

Addints.srv

)

generate_messages(

DEPENDENCIES

std_msgs

catkin_package(

CATKIN_DEPENDS roscpp rospy std_msg message_runtime

)

在c_cppc_properies.json文件中的includePath加入:

"/home/jhx/demo03_ws/devel/include/server_client/**"

对srv的初步编译完成

现在编写server.cpp文件:

#include "ros/ros.h"

#include

#include "server_client/Addints.h"

bool doNums(server_client::Addints::Request &request, server_client::Addints::Response &response){

int num1=request.num1;

int num2=request.num2;

ROS_INFO("Received data: num1 = %d, num2 = %d",num1,num2);

int sum=num1+num2;

response.sum=sum;

ROS_INFO("calculated data: sum = %d",sum);

return true;

}

int main(int argc,char *argv[]){

setlocale(LC_ALL,"");

ros::init(argc,argv,"server");

ros::NodeHandle n;

ros::ServiceServer server=n.advertiseService("Addints",doNums);

ros::spin();

return 0;

}

再对CMakeList.txt进行修改:

add_executable(server src/server.cpp)

add_dependencies(server ${PROJECT_NAME}_gencpp)

target_link_libraries(server

${catkin_LIBRARIES}

)

然后roscore,source ./devel/setup.bash,进行rosrun操作

再开启一个终端,输入rosservice call Addints,敲击空格再使用tab键,再直接修改num1和num2的值,敲击回车,就能得到结果。

效果如下:

服务通信:自定义srv文件以及服务端的编写_第1张图片

你可能感兴趣的:(ros,学习方法,机器人)