Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9393095
  • 博文数量: 1747
  • 博客积分: 12961
  • 博客等级: 上将
  • 技术积分: 20060
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-09 11:25
个人简介

偷得浮生半桶水(半日闲), 好记性不如抄下来(烂笔头). 信息爆炸的时代, 学习是一项持续的工作.

文章分类

全部博文(1747)

文章存档

2024年(23)

2023年(26)

2022年(112)

2021年(217)

2020年(157)

2019年(192)

2018年(81)

2017年(78)

2016年(70)

2015年(52)

2014年(40)

2013年(51)

2012年(85)

2011年(45)

2010年(231)

2009年(287)

分类: 其他平台

2020-06-17 17:50:38

CPP部分

点击(此处)折叠或打开

  1. ros2 pkg create --build-type ament_cmake cpp_srvcli --dependencies rclcpp example_interfaces

  2. --dependencies 会自动把必要的依赖加入到 package.xml 和 CMakeLists.txt 中.

  3. example_interfaces 这个依赖包存在一个 .srv 文件. 我们需要这个包的 .srv 文件.

  4. cat example_interfaces/srv/AddTwoInts.srv
  5. int64 a
  6. int64 b
  7. ---
  8. int64 sum

点击(此处)折叠或打开  --  add_two_ints_server.cpp

  1. #include "rclcpp/rclcpp.hpp"
  2. #include "example_interfaces/srv/add_two_ints.hpp"

  3. #include <memory>

  4. void add(const std::shared_ptr<example_interfaces::srv::AddTwoInts::Request> request,
  5.           std::shared_ptr<example_interfaces::srv::AddTwoInts::Response> response)
  6. {
  7.   response->sum = request->a + request->b;
  8.   RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Incoming request\na: %ld" " b: %ld",
  9.                 request->a, request->b);
  10.   RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "sending back response: [%ld]", (long int)response->sum);
  11. }

  12. int main(int argc, char **argv)
  13. {
  14.   rclcpp::init(argc, argv);

  15.   std::shared_ptr<rclcpp::Node> node = rclcpp::Node::make_shared("add_two_ints_server");

  16.   rclcpp::Service<example_interfaces::srv::AddTwoInts>::SharedPtr service =
  17.     node->create_service<example_interfaces::srv::AddTwoInts>("add_two_ints", &add);

  18.   RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Ready to add two ints.");

  19.   rclcpp::spin(node);
  20.   rclcpp::shutdown();
  21. }

点击(此处)折叠或打开

  1. 修改 CMakeLists.txt 增加

  2. add_executable(server src/add_two_ints_server.cpp)
  3. ament_target_dependencies(server rclcpp example_interfaces)
  4. add_executable(client src/add_two_ints_client.cpp) 
  5. ament_target_dependencies(client rclcpp example_interfaces)

  6. install(TARGETS
  7.   server
  8.   client
  9.   DESTINATION lib/${PROJECT_NAME})

点击(此处)折叠或打开  --  add_two_ints_client.cpp

  1. #include "rclcpp/rclcpp.hpp"
  2. #include "example_interfaces/srv/add_two_ints.hpp"

  3. #include <chrono>
  4. #include <cstdlib>
  5. #include <memory>

  6. using namespace std::chrono_literals;

  7. int main(int argc, char **argv)
  8. {
  9.   rclcpp::init(argc, argv);

  10.   if (argc != 3) {
  11.       RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "usage: add_two_ints_client X Y");
  12.       return 1;
  13.   }

  14.   std::shared_ptr<rclcpp::Node> node = rclcpp::Node::make_shared("add_two_ints_client");
  15.   rclcpp::Client<example_interfaces::srv::AddTwoInts>::SharedPtr client =
  16.     node->create_client<example_interfaces::srv::AddTwoInts>("add_two_ints");

  17.   auto request = std::make_shared<example_interfaces::srv::AddTwoInts::Request>();
  18.   request->a = atoll(argv[1]);
  19.   request->b = atoll(argv[2]);

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

  27.   auto result = client->async_send_request(request);
  28.   // Wait for the result.
  29.   if (rclcpp::spin_until_future_complete(node, result) ==
  30.     rclcpp::FutureReturnCode::SUCCESS)
  31.   {
  32.     RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Sum: %ld", result.get()->sum);
  33.   } else {
  34.     RCLCPP_ERROR(rclcpp::get_logger("rclcpp"), "Failed to call service add_two_ints");
  35.   }

  36.   rclcpp::shutdown();
  37.   return 0;
  38. }

点击(此处)折叠或打开

  1. rosdep install -i --from-path src --rosdistro foxy -y
  2. colcon build --packages-select cpp_srvcli
  3. . install/setup.bash

  4. ros2 run cpp_srvcli server
  5. ros2 run cpp_srvcli client 2 3
######################################################
Python 部分

点击(此处)折叠或打开

  1. ros2 pkg create --build-type ament_python py_srvcli --dependencies rclpy example_interfaces
  2. 修改 package.xml 和 setup.py 的 maintainer, maintainer_email, description, license 部分

  3. ##################### service_member_function.py 代码 #####################
  4. from example_interfaces.srv import AddTwoInts
  5. import rclpy
  6. from rclpy.node import Node

  7. class MinimalService(Node):

  8.     def __init__(self):
  9.         super().__init__('minimal_service')
  10.         self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_two_ints_callback)

  11.     def add_two_ints_callback(self, request, response):
  12.         response.sum = request.a + request.b
  13.         self.get_logger().info('Incoming request\na: %d b: %d' % (request.a, request.b))

  14.         return response


  15. def main(args=None):
  16.     rclpy.init(args=args)

  17.     minimal_service = MinimalService()

  18.     rclpy.spin(minimal_service)

  19.     rclpy.shutdown()


  20. if __name__ == '__main__':
  21.     main()

  22. ##################### client_member_function.py 代码 #####################
  23. import sys

  24. from example_interfaces.srv import AddTwoInts
  25. import rclpy
  26. from rclpy.node import Node


  27. class MinimalClientAsync(Node):

  28.     def __init__(self):
  29.         super().__init__('minimal_client_async')
  30.         self.cli = self.create_client(AddTwoInts, 'add_two_ints')
  31.         while not self.cli.wait_for_service(timeout_sec=1.0):
  32.             self.get_logger().info('service not available, waiting again...')
  33.         self.req = AddTwoInts.Request()

  34.     def send_request(self):
  35.         self.req.a = int(sys.argv[1])
  36.         self.req.b = int(sys.argv[2])
  37.         self.future = self.cli.call_async(self.req)


  38. def main(args=None):
  39.     rclpy.init(args=args)

  40.     minimal_client = MinimalClientAsync()
  41.     minimal_client.send_request()

  42.     while rclpy.ok():
  43.         rclpy.spin_once(minimal_client)
  44.         if minimal_client.future.done():
  45.             try:
  46.                 response = minimal_client.future.result()
  47.             except Exception as e:
  48.                 minimal_client.get_logger().info(
  49.                     'Service call failed %r' % (e,))
  50.             else:
  51.                 minimal_client.get_logger().info(
  52.                     'Result of add_two_ints: for %d + %d = %d' %
  53.                     (minimal_client.req.a, minimal_client.req.b, response.sum))
  54.             break

  55.     minimal_client.destroy_node()
  56.     rclpy.shutdown()


  57. if __name__ == '__main__':
  58.     main()


  59. 修改 setup.py
  60. entry_points={
  61.     'console_scripts': [
  62.         'service = py_srvcli.service_member_function:main',
  63.         'client = py_srvcli.client_member_function:main',
  64.     ],
  65. },

  66. 编译执行
  67. rosdep install -i --from-path src --rosdistro foxy -y
  68. colcon build --packages-select py_srvcli
  69. . install/setup.bash
  70. ros2 run py_srvcli service
  71. ros2 run py_srvcli client 2 3





阅读(1651) | 评论(0) | 转发(0) |
0

上一篇:ROS2 just do it

下一篇:ROS2 之 自定义消息

给主人留下些什么吧!~~