Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

rclpyでROS2のトピックを扱う その3:service

実際のところ

実践例として、xArm の ROS2 humble用パッケージのサービスをコールしてロボットアームを動かしてみます。

$ cd ~/dev_ws/
$ source install/setup.bash

スクリプト

import rclpy
from rclpy.node import Node
from xarm_msgs.srv import SetInt16, SetInt16ById, MoveCartesian

class ServiceClient(Node):

    def __init__(self):
        super().__init__('xarm_service_client')

        # サービスクライアントの定義
        self.motion_enable_client = self.create_client(SetInt16ById, '/ufactory/motion_enable')
        self.set_mode_client = self.create_client(SetInt16, '/ufactory/set_mode')
        self.set_state_client = self.create_client(SetInt16, '/ufactory/set_state')
        self.set_position_client = self.create_client(MoveCartesian, '/ufactory/set_position')

    def send_requests(self):
        # motion_enableサービスの呼び出し
        req = SetInt16ById.Request()
        req.id = 8
        req.data = 1
        future = self.motion_enable_client.call_async(req)
        rclpy.spin_until_future_complete(self, future)

        # set_modeサービスの呼び出し
        req = SetInt16.Request()
        req.data = 0
        future = self.set_mode_client.call_async(req)
        rclpy.spin_until_future_complete(self, future)

        # set_stateサービスの呼び出し
        req = SetInt16.Request()
        req.data = 0
        future = self.set_state_client.call_async(req)
        rclpy.spin_until_future_complete(self, future)

        # set_positionサービスの呼び出し
        req = MoveCartesian.Request()
        req.pose = [250.0, 0.0, 250.0, 3.14, 0.0, 0.0]
        req.speed = 50.0
        req.acc = 500.0
        req.mvtime = 0.0
        future = self.set_position_client.call_async(req)
        rclpy.spin_until_future_complete(self, future)

        self.get_logger().info('All services called successfully.')

def main(args=None):
    rclpy.init(args=args)
    service_client = ServiceClient()
    service_client.send_requests()
    service_client.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()