编写一个 ROS2 service程序,包含2个节点: 客户端调用一个名为把两个整数相乘的服务,该服务接受两个整数并返回它们的乘积。
时间: 2024-09-27 21:09:54 浏览: 85
ROS复习笔记之——创建和运行动作服务器与客户端节点
编写ROS2 (Robot Operating System version 2) 的 service 程序涉及到几个关键步骤,这里是一个简化的示例,演示如何创建一个服务提供者和服务消费者。在这个例子中,我们将创建一个名为 `multiply_numbers` 的服务,它接收两个整数并返回它们的乘积。
首先,你需要安装 ROS2,并了解其包管理工具 `ros2 pkg` 和 `ros2 run`。
**1. 创建服务提供者(server_node.py)**
```python
# server_node.py
import rclpy
from rclpy.node import Node
from rclpy.service import Service, ServiceException
from std_msgs.msg import Int32
class MultiplyNumbersService(Node):
def __init__(self):
super().__init__('multiply_numbers_server')
self.service = self.create_service(
Int32, 'multiply_numbers', self.multiply_callback)
def multiply_callback(self, request, response):
try:
if not isinstance(request.a, int) or not isinstance(request.b, int):
raise ServiceException('Both inputs must be integers.')
result = request.a * request.b
response.result = result
return response
except Exception as e:
self.get_logger().error(f'Mulitply failed: {e}')
return response
def main(args=None):
rclpy.init(args=args)
multiply_numbers_server = MultiplyNumbersService()
rclpy.spin(multiply_numbers_server)
rclpy.shutdown()
if __name__ == '__main__':
main()
```
**2. 客户端调用(client_node.py)**
```python
# client_node.py
import rclpy
from rclpy.node import Node
from rclpy.client import Client
from std_msgs.msg import Int32
from std_srvs.srv import Empty, MultiplyRequest, MultiplyResponse
class MultiplyNumbersClient(Node):
def __init__(self):
super().__init__('multiply_numbers_client')
self.client = self.create_client(MultiplyRequest, 'multiply_numbers')
def call_multiply_service(self, a, b):
while not self.wait_for_service(timeout_sec=5.0):
self.get_logger().info('Waiting for multiply_numbers service...')
request = MultiplyRequest()
request.a = a
request.b = b
future = self.call_async(request)
rclpy.spin_until_future_complete(self, future)
if future.result() is not None:
response = future.result()
print(f'Result of multiplication: {response.result}')
else:
self.get_logger().err('Service call failed.')
def main(args=None):
rclpy.init(args=args)
multiply_numbers_client = MultiplyNumbersClient()
try:
multiply_numbers_client.call_multiply_service(4, 5)
except KeyboardInterrupt:
pass
finally:
rclpy.shutdown()
if __name__ == '__main__':
main()
```
运行这两个节点,客户端会向服务器发送请求,服务器接收到请求后计算两个数字的乘积并返回结果。
阅读全文