やりたいこと
サービス通信で,クライアントがトリガーを投げたら,それを受け取ったサーバが処理を実行し終わるまで待ちたい
方法
spin_until_future_complete を使う
サービスタイプはTrigerで実装した
service_server.py
import rclpy
from rclpy.node import Node
from std_srvs.srv import Trigger #service type
import time
class ServiceServer(Node):
def __init__(self):
super().__init__('service_server')
self.srv = self.create_service(Trigger, 'service_name', self.handle_request)
self.get_logger().info('server is ready')
def handle_request(self, request, response):
self.get_logger().info('executing hundle_request')
'''
実行したい処理
例
time.sleep(10)
'''
response.success = True
response.message = "finished"
self.get_logger().info('finished hundle_request')
return response
def main(args=None):
rclpy.init(args=args)
server = ServiceServer()
rclpy.spin(server)
server.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()
service_client.py
from std_srvs.srv import Trigger #service type
import rclpy
from rclpy.node import Node
class ServiceClient(Node):
def __init__(self):
super().__init__('service_client')
self.cli = self.create_client(Trigger, 'service_name')
while not self.cli.wait_for_service(timeout_sec=1.0):
self.get_logger().info('service not available, waiting again...')
self.req = Trigger.Request()
def send_request(self):
self.get_logger().info('send a request')
self.future = self.cli.call_async(self.req)
rclpy.spin_until_future_complete(self, self.future)
return self.future.result()
def main(args=None):
rclpy.init(args=args)
client = ServiceClient()
response = client.send_request()
#サーバの処理が終わるまで待機
client.get_logger().info(response.message)
client.destroy_node()
rclpy.shutdown()
if __name__ == '__main__':
main()