Step 1: Create a Custom Service Interface

  1. Create a Package for Interfaces: If you haven't already, create a package for your custom interfaces. For example, my_robot_interfaces.

  2. Create a Service Interface:

  3. Verify the CMakeLists.txt Configuration Make sure that your CMakeLists.txt file in the my_robot_interfaces package correctly includes the service interface.


rosidl_generate_interfaces(${PROJECT_NAME}
"msg/YourOtherMessages.msg"
"srv/Fibonacci.srv"
)

Step 2: Implement the Service Server

  1. Create a Server Node:

  2. Import Necessary Modules:

    import rclpy
    from rclpy.node import Node
    from my_robot_interfaces.srv import Fibonacci  # Import your custom service interface
    
    
  3. Define the Service Server:

    def fibonacci(n):
        if n <= 0:
            return 0
        elif n == 1:
            return 1
        else:
            return fibonacci(n-1) + fibonacci(n-2)
    
    class FibonacciServer(Node):
        def __init__(self):
            super().__init__("fibonacci_server")
            self.fibonacci_service = self.create_service(
                Fibonacci,  # Service interface
                "fibonacci",  # Service name
                self.fibonacci_callback  # Callback function
            )
            self.get_logger().info("Fibonacci Service started")
    
        def fibonacci_callback(self, request, response):
            response.fibonacci_number = fibonacci(request.number)
            self.get_logger().info(f"Fibonacci of {request.number} is {response.fibonacci_number}")
            return response
    
    def main(args=None):
        rclpy.init(args=args)
        node = FibonacciServer()
        rclpy.spin(node)
        rclpy.shutdown()
    
    if __name__ == "__main__":
        main()
    
    
  4. Install the Node: Add the following line to your package's setup.py file under entry_points:

    entry_points={
        'console_scripts': [
            # Other scripts...
            "fibonacci_server = my_pkg.fibonacci_server:main"
        ],
    },
    
    

Step 3: Implement the Service Client

  1. Create a Client Node:

  2. Import Necessary Modules:

    import rclpy
    from rclpy.node import Node
    from my_robot_interfaces.srv import Fibonacci  # Import your custom service interface
    
    
  3. Define the Service Client:

    class FibonacciClient(Node):
        def __init__(self):
            super().__init__("fibonacci_client")
            self.client = self.create_client(Fibonacci, "fibonacci")  # Service name
            while not self.client.wait_for_service(timeout_sec=1.0):
                self.get_logger().info("Fibonacci Service not available, waiting...")
            self.get_logger().info("Fibonacci Service available")
    
        def send_request(self, number):
            req = Fibonacci.Request()
            req.number = number
            future = self.client.call_async(req)
            while rclpy.ok():
                rclpy.spin_once(self)
                if future.done():
                    try:
                        response = future.result()
                    except Exception as e:
                        self.get_logger().info(f"Service call failed {e}")
                    else:
                        self.get_logger().info(f"Fibonacci of {number} is {response.fibonacci_number}")
                    break
    
    def main(args=None):
        rclpy.init(args=args)
        node = FibonacciClient()
        node.send_request(10)  # Calculate Fibonacci of 10
        rclpy.spin(node)
        rclpy.shutdown()
    
    if __name__ == "__main__":
        main()
    
    
  4. Install the Node: Add the following line to your package's setup.py file under entry_points:

    entry_points={
        'console_scripts': [
            # Other scripts...
            "fibonacci_client = my_pkg.fibonacci_client:main"
        ],
    },