1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ROS2 サービス通信でサーバの処理が終わるまで待機したい

Last updated at Posted at 2024-11-19

やりたいこと

サービス通信で,クライアントがトリガーを投げたら,それを受け取ったサーバが処理を実行し終わるまで待ちたい

方法

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()
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?