Writing a Service Server (Python)

Create a package

First of all, you will have to create a new package, where you will place the code for your Publisher node. For this, you need to be in your ROS2 workspace src folder.

cd ~/ros2_ws/src

Now, execute the following command to create the package:

ros2 pkg create --build-type ament_python service_server_py --dependencies rclpy example_interfaces

You will get an output similar to this one:

This will automatically generate your package and all its necessary files and folders. Now, navigate to the ~/ros2_ws/src folder in order to create your file.

Write the code

Inside the ros2_ws/src folder, create a new file named service_server.py. Into this file, you will copy the following code

from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node

class ServiceServer(Node):

    def __init__(self):
        super().__init__('service_server_node')
        self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_two_ints_callback)

    def add_two_ints_callback(self, request, response):
        response.sum = request.a + request.b
        self.get_logger().info('Incoming request\na: %d b: %d' % (request.a, request.b))
        return response

def main(args=None):
    rclpy.init(args=args)
    service_server = ServiceServer()
    rclpy.spin(service_server)
    rclpy.shutdown()

if __name__ == '__main__':
    main()

Review the code

The first import we have is importing the AddTwoInts message, from the example_interfaces package. We will use this message for our Service Server.

from example_interfaces.srv import AddTwoInts

Next we define our class, which inherits from the Node class.

class ServiceServer(Node):

Within the constructor, we are initializing our node by calling to the constructor of the superclass Node.

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

Also within the constructor, we create the service server and define its type, name, and callback function .

self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_two_ints_callback)

The add_two_ints_callback function receives the request data, sums it, and returns the sum as a response. .

def add_two_ints_callback(self, request, response):
        response.sum = request.a + request.b
        self.get_logger().info('Incoming request\na: %d b: %d' % (request.a, request.b))
        return response

Finally, the main class initializes the ROS 2 Python client library, instantiates the SimpleService class to create the service node and spins the node to handle callbacks.

def main(args=None):
    rclpy.init(args=args)
    service_server = ServiceServer()
    rclpy.spin(service_server)
    rclpy.shutdown()

Modify the setup.py file

In the entry_points section of your setup.py file, add the following lines:

entry_points={
    'console_scripts': [
        'service_server_node = service_server_py.service_server:main'
    ],
},

This will generate an executable, which points to the main function from the service_server.py file, which is inside the service_server_py folder.

Compile the package

First of all, let's go the ros2_ws folder in order to be able to compile.

cd ~/ros2_ws;

Let's now execute the colcon command in order to build our node.

colcon build --symlink-install

You will get an output like the following one:

Finally, let's source the workspace.

source ~/ros2_ws/install/setup.bash

Testing the Service Server

Let's run our service server with the following command:

ros2 run service_server_cpp service_server_node

Now, in order to call the service server, let's execute in a different shell the following command:

ros2 service call /add_two_ints example_interfaces/AddTwoInts '{a: 2, b: 3}'

From the Shell where you executed the Server, you will get the following:

And from the Shell where you called the Server, you wll get the following:

Practice Online

Also, you can test this tutorial in ROSDS, using a ROSject which already contains all the code described in it. You can get the ROSject by clicking on the button below:

Above: Get ROSDS ROSject

The link above will take yo a page like the below one:

Now, you just need to Sign In (or Sign Up if you don't have an account yet) to ROSDS in order to launch the ROSject.