ROS service通信机制中,客户端编程实例
时间: 2024-10-16 07:15:41 浏览: 32
ROS (Robot Operating System) 中的服务(service)是一种异步的消息传递模式,用于处理特定任务并返回结果。服务通信由客户端和服务端两部分组成。下面是一个简单的ROS服务客户端编程实例,假设我们有一个名为`add_two_numbers`的服务,它接受两个整数并返回它们的和。
**服务定义** (通常在`server.py`文件):
```python
import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32
class AddNumbersService(Node):
def __init__(self):
super().__init__('add_two_numbers_service')
self.service = self.create_service(Int32, 'add_two_numbers', self.add_two_numbers_callback)
def add_two_numbers_callback(self, request, response):
result = request.data1 + request.data2
response.sum = result
return response
def main(args=None):
rclpy.init(args=args)
node = AddNumbersService()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
```
**客户端编程** (通常在`client.py`文件):
```python
import rclpy
from rclpy.node import Node
from add_two_numbers_service.srv import AddTwoNumbers
class ClientNode(Node):
def __init__(self):
super().__init__('client_node')
self.add_service = self.create_client(AddTwoNumbers, 'add_two_numbers')
def call_add_service(self, num1, num2):
future = self.add_service.call_async({'data1': num1, 'data2': num2})
while rclpy.ok() and not future.done():
self.get_logger().info('Waiting for server...')
rclpy.spin_once(self, timeout_sec=0.1)
if not future.done():
self.get_logger().error('Service call failed!')
return None
else:
result = future.result()
return result.sum
def main(args=None):
rclpy.init(args=args)
client = ClientNode()
sum_result = client.call_add_service(4, 5)
if sum_result is not None:
client.get_logger().info(f'The sum of {num1} and {num2} is: {sum_result}')
rclpy.shutdown()
if __name__ == '__main__':
main()
```
当你运行`client.py`时,它会连接到`server.py`中定义的服务,并发送请求计算两个数字之和。如果服务正常运行,它将返回响应。
阅读全文