ros2 服务接口实例

目录

一. 创建服务接口

1. 创建功能包

2.编写服务接口

3. 输入文件内容,输入参数是cmd,输出参数是success,result

4. 修改

5.编译查看接口

二. 编写代码使用srv接口

1.创建功能包

2.编写代码

3.修改CmakeList.txt 和 package.xml

4.运行


一. 创建服务接口

1. 创建功能包

ros2 pkg create --build-type ament_cmake robot_interfaces

2.编写服务接口

cd robot_interfaces
rm include src -r
mkdir action srv msg
cd srv
gedit TargetLocate.srv #文件名字采用首字母大写拼接方式

3. 输入文件内容,输入参数是cmd,输出参数是success,result

TargetLocate.srv

string cmd    # get_fenda_position
---
bool success   # indicate successful run of robot_analyse service
string result  # result

4. 修改

编辑CmakeList.txt,添加如下内容:

find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(${PROJECT_NAME}
          "srv/TargetLocate.srv"

)

    编辑package.xml,增加如下行:

rosidl_default_generators
rosidl_default_runtime
rosidl_interface_packages

5.编译查看接口

colcon build

ros2 interface show robot_interfaces/srv/TargetLocate
string cmd    # get_fenda_position
---
bool success   # indicate successful run of robot_analyse service
string result  # result

二. 编写代码使用srv接口

1.创建功能包

ros2 pkg create --build-type ament_cmake robot_sercli

2.编写代码

服务端代码

 gedit robot_image_analyse.cpp  #server
#include "rclcpp/rclcpp.hpp"
#include "robot_interfaces/srv/target_locate.hpp"     // 添加头文件 find -name target_locate.*
#include 

void analyseImage(const std::shared_ptr request,     //客户端传递的参数,也就是请求参数
          std::shared_ptr       response)  // 返回请求的结果
{
    RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Incoming request\n: cmd %s", request->cmd.c_str());      
    response->result = "[1,2,3,4,5,6,7,9,0,1,2,3,4,5,6]";                                       // 构造结果
                                      
}

int main(int argc, char **argv)
{
  rclcpp::init(argc, argv);

  auto node = rclcpp::Node::make_shared("robot_image_analyse");  // 节点名字

  auto service = node->create_service("get_target_position",  &analyseImage);     // 服务的名字


  rclcpp::spin(node);
  rclcpp::shutdown();
}

客户端代码:

gedit robot_request_result.cpp 
#include "rclcpp/rclcpp.hpp"
#include "robot_interfaces/srv/target_locate.hpp"        //  添加头文件 find -name target_locate.*

#include 
#include 
#include 

using namespace std::chrono_literals;

int main(int argc, char **argv)
{
    rclcpp::init(argc, argv);


    auto node = rclcpp::Node::make_shared("robot_request_result");        //
    auto client =  node->create_client("get_target_position");                  

    auto request = std::make_shared();               
               
    request->cmd = "get_fenda_position";  //获取fenda位姿

    while (!client->wait_for_service(1s)) {
        if (!rclcpp::ok()) {
          	RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Interrupted while waiting for the service. Exiting.");
          	return 0;
        }
        RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "service not available, waiting again...");
  	}

  	auto result = client->async_send_request(request);
	// Wait for the result.
	if(rclcpp::spin_until_future_complete(node, result) == rclcpp::executor::FutureReturnCode::SUCCESS)
	{
		RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "result: %s", result.get()->result.c_str());
	} 
	else{
		RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service add_three_ints");    // CHANGE
	}

  	rclcpp::shutdown();
  	return 0;
}

3.修改CmakeList.txt 和 package.xml


find_package(ament_cmake REQUIRED)
find_package(rclcpp REQUIRED)
find_package(robot_interfaces REQUIRED)      #srv接口功能包  



# uncomment the following section in order to fill in
# further dependencies manually.
# find_package( REQUIRED)

if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)
  # the following line skips the linter which checks for copyrights
  # uncomment the line when a copyright and license is not present in all source files
  #set(ament_cmake_copyright_FOUND TRUE)
  # the following line skips cpplint (only works in a git repo)
  # uncomment the line when this package is not in a git repo
  #set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

add_executable(robot_ser src/robot_image_analyse.cpp)
ament_target_dependencies(robot_ser
  rclcpp robot_interfaces)                      

add_executable(robot_cli src/robot_request_result.cpp)
ament_target_dependencies(robot_cli 
rclcpp robot_interfaces)                     

install(TARGETS
  robot_ser
  robot_cli
  DESTINATION lib/${PROJECT_NAME})

在package.xml添加如下行

robot_interfaces

4.运行

终端1:

mfj@ros:~/health_robot$ ros2 run robot_sercli robot_ser
[INFO] [1666839991.371300205] [rclcpp]: Incoming request
: cmd get_fenda_position

终端2:

mfj@ros:~/health_robot$ ros2 run robot_sercli robot_cli
[INFO] [1666839991.371983716] [rclcpp]: result: [1,2,3,4,5,6,7,9,0,1,2,3,4,5,6]

你可能感兴趣的:(ros2,c++,ubuntu)