Bootstrap

ROS1入门教程4:服务请求和响应

一、新建项目

# 创建工作空间
mkdir -p demo4/src

# 打开工作空间
cd demo4

# 初始化工作空间
catkin_make

# 打卡src目录
cd src

# 创建功能包
catkin_create_pkg demo roscpp message_generation

二、新建服务

# 创建服务目录
mkdir srv

# 创建服务文件
vim Login.srv

三、修改编译配置

# 添加服务文件
add_service_files(
  FILES
  Login.srv
)

# 生成消息
generate_messages(
  DEPENDENCIES
  std_msgs
)

# 添加源文件
add_executable(server src/server.cpp)
add_executable(client src/client.cpp)

# 添加依赖
add_dependencies(server ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS} ${PROJECT_NAME}_generate_messages_cpp)
add_dependencies(client ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS} ${PROJECT_NAME}_generate_messages_cpp)

# 链接catkin库
target_link_libraries(server ${catkin_LIBRARIES})
target_link_libraries(client ${catkin_LIBRARIES})

四、创建服务端

#include <iostream>

#include "ros/ros.h"
#include "demo/Login.h"

bool ServiceCallback(demo::Login::Request &request, demo::Login::Response &response) {
    if (request.username == "admin" && request.password == "admin") {
        response.result = "Login success";
        ROS_INFO("%s", response.result.c_str());
        return true;
    }
    response.result = "Login failed";
    ROS_ERROR("%s", response.result.c_str());
    return true;
}

int main(int argc, char* argv[]) {
    std::string nodeName = "Server";
    ros::init(argc, argv, nodeName);
    ros::NodeHandle nodeHandle;
    std::string serviceName = "demo4";
    const ros::ServiceServer &serviceServer = nodeHandle.advertiseService(serviceName, ServiceCallback); // 创建服务端
    ros::spin();

    return EXIT_SUCCESS;
}

五、创建客户端

#include <iostream>

#include "ros/ros.h"
#include "demo/Login.h"

int main(int argc, char* argv[]) {
    std::string nodeName = "Client";
    ros::init(argc, argv, nodeName);
    ros::NodeHandle nodeHandle;
    std::string serviceName = "demo4";
    ros::ServiceClient serviceClient = nodeHandle.serviceClient<demo::Login>(serviceName); // 创建客户端
    demo::Login service; // 创建服务
    service.request.username = "admin";
    service.request.password = "admin";
    serviceClient.call(service); // 请求服务
    ROS_INFO("Response: %s", service.response.result.c_str());

    return EXIT_SUCCESS;
}

;