< >
Home » ROS2与Python入门教程 » ros2与Python入门教程-使用服务

ros2与Python入门教程-使用服务

**ros2与Python入门教程-使用服务 **

说明:

  • 介绍如何python来测试服务
  • 实现3个数字相加的

步骤:

cd ~/dev_ws/src/py_srvcli/py_srvcli
vim  service_member_function_num.py
  • 内容如下
from tutorial_interfaces.srv import AddThreeInts     # CHANGE

import rclpy
from rclpy.node import Node


class MinimalService(Node):

    def __init__(self):
        super().__init__('minimal_service')
        self.srv = self.create_service(AddThreeInts, 'add_three_ints', self.add_three_ints_callback)        # CHANGE

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

        return response

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

    minimal_service = MinimalService()

    rclpy.spin(minimal_service)

    rclpy.shutdown()

if __name__ == '__main__':
    main()
  • 新建文件
cd ~/dev_ws/src/py_srvcli/py_srvcli
vim client_member_function_num.py
  • 内容如下:
from tutorial_interfaces.srv import AddThreeInts       # CHANGE
import sys
import rclpy
from rclpy.node import Node


class MinimalClientAsync(Node):

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

    def send_request(self):
        self.req.a = int(sys.argv[1])
        self.req.b = int(sys.argv[2])
        self.req.c = int(sys.argv[3])                  # CHANGE
        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_three_ints: for %d + %d + %d = %d' %                               # CHANGE
                    (minimal_client.req.a, minimal_client.req.b, minimal_client.req.c, response.sum)) # CHANGE
            break

    minimal_client.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()
  • 变更package.xml,增加
<exec_depend>tutorial_interfaces</exec_depend>
  • 变更setup.py,增加入口
entry_points={
        'console_scripts': [
                'service_num = py_srvcli.service_member_function:main',
                'listener_num = py_pubsub.subscriber_member_function_num:main',
        ],
},
  • 安装依赖
rosdep install -i --from-path src --rosdistro foxy -y
  • 编译
colcon build --packages-select py_srvcli
  • 新开终端,运行
. install/setup.bash
ros2 run py_srvcli service_num
  • 新开终端,运行

    . install/setup.bash
    ros2 run py_srvcli client_num 2 3 4

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

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


标签: ros2与python入门教程