service通信client-python
service通信client¶
service通信分为server和client端
实现¶
1. 创建package(如果创建过可省略)¶
ros2 pkg create --build-type ament_python py_srvcli --dependencies rclpy example_interfaces
可以修改
package.xml
文件如下信息<description>C++ client server tutorial</description> <maintainer email="you@email.com">Your Name</maintainer> <license>Apache License 2.0</license>
2. 编写client节点代码¶
2.1 编写代码¶
- 在package的
py_srvcli
下创建client.py
文件,代码如下
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts
import time
class MyNode(Node):
def __init__(self):
super(MyNode, self).__init__('py_client')
self.cli = self.create_client(AddTwoInts,'py_service')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger().info('service not available,waiting again...')
self.req = AddTwoInts.Request()
time.sleep(3)
self.send_request(10,20)
def send_request(self,a,b):
self.req.a = int(a)
self.req.b = int(b)
self.future = self.cli.call_async(self.req)
self.future.add_done_callback(self.call_back)
def call_back(self,future):
self.get_logger().info(f'receive response {future.result().sum}')
def main():
rclpy.init()
node = MyNode()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
2.2 添加配置¶
- 打开
setup.py
文件,在console_scripts
节点下添加配置
'client = py_srvcli.client:main',
3. 编译工程¶
colcon build
4. 运行节点¶
ros2 run py_srvcli client