< >
Home » ROS2与Python入门教程 » ros2与Python入门教程-创建服务端好客户端

ros2与Python入门教程-创建服务端好客户端

ros2与Python入门教程-创建服务端好客户端

说明:

  • 介绍如何创建服务端好客户端

步骤:

  • 新建包py_srvcli
cd ~/dev_ws/
ros2 pkg create --build-type ament_python py_srvcli --dependencies rclpy example_interfaces
  • 更改package.xml
  • 因为使用了--dependencies rclpy example_interfaces添加的依赖已经增加
  • 可以更改如下相应的
<description>Python client server tutorial</description>
<maintainer email="you@email.com">Your Name</maintainer>
<license>Apache License 2.0</license>
  • 更改setup.py
  • maintainer, maintainer_email, description and license都更改与package.xml对应的
  • 在目录dev_ws/src/py_srvcli/py_srvcli下,新增service_member_function.py
  • 内容如下:
from example_interfaces.srv import AddTwoInts

import rclpy
from rclpy.node import Node


class MinimalService(Node):

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

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

        return response


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

    minimal_service = MinimalService()

    rclpy.spin(minimal_service)

    rclpy.shutdown()


if __name__ == '__main__':
    main()
  • 更改setup.py,增加入口点,在console_scripts中添加:
entry_points={
    'console_scripts': [
        'service = py_srvcli.service_member_function:main',
    ],
},
  • 在目录dev_ws/src/py_srvcli/py_srvcli下新增client_member_function.py
  • 内容如下:
import sys

from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node


class MinimalClientAsync(Node):

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

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


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

    minimal_client = MinimalClientAsync()
    minimal_client.send_request()

    while rclpy.ok():
        rclpy.spin_once(minimal_client)
        if minimal_client.future.done():
            try:
                response = minimal_client.future.result()
            except Exception as e:
                minimal_client.get_logger().info(
                    'Service call failed %r' % (e,))
            else:
                minimal_client.get_logger().info(
                    'Result of add_two_ints: for %d + %d = %d' %
                    (minimal_client.req.a, minimal_client.req.b, response.sum))
            break

    minimal_client.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()
  • 更改setup.py,增加入口点,在console_scripts中添加:
entry_points={
    'console_scripts': [
        'service = py_srvcli.service_member_function:main',
        'client = py_srvcli.client_member_function:main',
    ],
},
  • 安装依赖
rosdep install -i --from-path src --rosdistro foxy -y
  • 编译
colcon build --packages-select py_srvcli
  • 新开终端,运行
. install/setup.bash
ros2 run py_srvcli service
  • 效果如下:
[INFO] [minimal_client_async]: Result of add_two_ints: for 2 + 3 = 5
  • 新开终端,运行
. install/setup.bash
ros2 run py_srvcli client 2 3
  • 效果如下:
[INFO] [minimal_service]: Incoming request
a: 2 b: 3

纠错,疑问,交流: 请进入讨论区点击加入Q群

获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号


标签: ros2与python入门教程