说明:本文基于ubuntu22.04和ros2 humble版本
三、服务之RCLPY实现
1.创建功能包和节点
创建功能包其实还可以加上一些参数,让这个过程变得更简单
cd chapt3_ws/src
ros2 pkg create example_service_rclpy --build-type ament_python --dependencies rclpy example_interfaces --node-name service_server_02
--node-name service_server_02
会帮助创建好节点文件和在setup.py中添加执行文件。
但是也有一些限制,比如只支持一个节点文件,所以还需要手动创建一个。
cd example_service_rclpy/example_service_rclpy/
touch service_client_02.py
修改setup.py文件
entry_points={
'console_scripts': [
"service_client_02 = example_service_rclpy.service_client_02:main",
"service_server_02 = example_service_rclpy.service_server_02:main"
],
},
2.服务端实现
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
# 导入接口
from example_interfaces.srv import AddTwoInts
class ServiceServer02(Node):
def __init__(self,name):
super().__init__(name)
self.get_logger().info("节点已启动:%s!" % name)
self.add_ints_server_ = self.create_service(AddTwoInts,"add_two_ints_srv",
self.handle_add_two_ints)
def handle_add_two_ints(self,request, response):
self.get_logger().info(f"收到请求,计算{request.a} + {request.b}")
response.sum = request.a + request.b
return response
def main(args=None):
rclpy.init(args=args) # 初始化rclpy
node = ServiceServer02("service_server_02") # 新建一个节点
rclpy.spin(node) # 保持节点运行,检测是否收到退出指令(Ctrl+C)
rclpy.shutdown() # 关闭rclpy
3.客户端实现
#!/usr/bin/env python3
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts
class ServiceClient02(Node):
def __init__(self,name):
super().__init__(name)
self.get_logger().info("节点已启动:%s!" % name)
self.client_ = self.create_client(AddTwoInts,"add_two_ints_srv")
def result_callback_(self, result_future):
response = result_future.result()
self.get_logger().info(f"收到返回结果:{response.sum}")
def send_request(self, a, b):
while rclpy.ok() and self.client_.wait_for_service(1)==False:
self.get_logger().info(f"等待服务端上线....")
request = AddTwoInts.Request()
request.a = a
request.b = b
self.client_.call_async(request).add_done_callback(self.result_callback_)
def main(args=None):
rclpy.init(args=args) # 初始化rclpy
node = ServiceClient02("service_client_02") # 新建一个节点
# 调用函数发送请求
node.send_request(3,4)
rclpy.spin(node) # 保持节点运行,检测是否收到退出指令(Ctrl+C)
rclpy.shutdown() # 关闭rclpy
同样是异步请求,rclpy客户端库定义的是call_async
并且使用add_done_callback
添加回调函数。
4.服务测试
工作空间目录下,开启客户端
colcon build --packages-select example_service_rclpy
source install/setup.bash
ros2 run example_service_rclpy service_client_02
#打开新的终端运行
source install/setup.bash
ros2 run example_service_rclpy service_server_02