Here's a detailed guide on creating a ROS2 service for calculating Fibonacci numbers, including defining a custom service interface, implementing a service server, and writing a service client.
First, ensure you have a ROS2 workspace set up. If not, create one:
mkdir -p ros2_ws/src
cd ros2_ws
Create a new package for your custom interfaces:
ros2 pkg create my_robot_interfaces --dependencies rclpy rosidl_default_generators
Navigate into the package:
cd src/my_robot_interfaces
Create a Service Interface File:
Navigate to the srv
directory of your package. If it doesn't exist, create it:
mkdir srv
cd srv
Create a new file named Fibonacci.srv
:
touch Fibonacci.srv
Open Fibonacci.srv
and define the service interface:
int32 number
---
int32 fibonacci_number
Update CMakeLists.txt
:
Open the CMakeLists.txt
file in the root of your package.
Add the following lines to include your service interface in the build process:
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(${PROJECT_NAME}
"srv/Fibonacci.srv"
)
ament_export_dependencies(rosidl_default_runtime)
Navigate Back to Your Workspace:
cd ../../..
Build Your Workspace:
colcon build --packages-select my_robot_interfaces
Source the Environment:
source install/setup.bash
Create a New Package for the Server: If you haven't already, create a new package for your server node:
ros2 pkg create my_pkg --dependencies rclpy my_robot_interfaces
Implement the Service Server:
Navigate to the src
directory of your new package:
cd src/my_pkg
Create a new Python file named fibonacci_server.py
:
touch fibonacci_server.py
Open fibonacci_server.py
and implement the server:
import rclpy
from rclpy.node import Node
from my_robot_interfaces.srv import Fibonacci
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()
Update setup.py
:
Open the setup.py
file in the root of your package.
Add the following line to include your server node in the package's entry points:
entry_points={
'console_scripts': [
"fibonacci_server = my_pkg.fibonacci_server:main"
],
},