Tech Arcanist
Get in touch

52Chapter 52 of 74

Service Server in Python: AddTwoInts

Introduction

The previous chapter explained what a service is: one node asks with a request, another node does the work and answers with a response. This chapter builds a real one in Python: a service server that adds two whole numbers.

A service needs a description of what goes in and what comes out. ROS 2 has ready-made ones, but here we write our own, called AddTwoInts. It goes in a new package, bumperbot_msgs, that holds only message and service definitions.

The plan:

  1. Create the package bumperbot_msgs.
  2. Describe the service in srv/AddTwoInts.srv: two numbers in, one number out.
  3. Tell CMakeLists.txt and package.xml to turn that file into code, then build.
  4. Write the server node simple_service_server.py and register it in setup.py and package.xml.
  5. Run it and call it from the terminal: 7 and 5 come back as 12.

Why a separate package? As far as I know, ROS 2 generates message and service code with CMake tools (rosidl), so interface files live in an ament_cmake package. A Python package like bumperbot_py_examples then simply uses them.

Create the interface package

Go to the src folder of the workspace and create an ament_cmake package named bumperbot_msgs:

cd ~/bumperbot_ws/src
ros2 pkg create --build-type ament_cmake bumperbot_msgs
Creating the bumperbot_msgs package with ros2 pkg create
Creating the bumperbot_msgs package with ros2 pkg create

Describe the service: AddTwoInts.srv

Inside bumperbot_msgs, make a folder called srv, and in it a file called AddTwoInts.srv.

The new srv folder with AddTwoInts.srv inside bumperbot_msgs
The new srv folder with AddTwoInts.srv inside bumperbot_msgs

Write this in the file:

# Request
int64 a
int64 b
---
# Response
int64 sum
AddTwoInts.srv open in the editor
AddTwoInts.srv open in the editor

How to read it

  • Everything above the line --- is the request: what the caller sends. Here two fields, a and b.
  • Everything below --- is the response: what the server sends back. Here one field, sum.
  • Each field is a type and a name. int64 is a whole number that can be very large, positive or negative.
  • Lines starting with # are comments for people; the build ignores them.

When the package is built, this small file becomes real Python classes: AddTwoInts.Request with a and b, and AddTwoInts.Response with sum. The picture below shows that step.

Tell the build about it

CMakeLists.txt

Open CMakeLists.txt of bumperbot_msgs.

CMakeLists.txt of bumperbot_msgs before the change
CMakeLists.txt of bumperbot_msgs before the change

Make it look like this:

cmake_minimum_required(VERSION 3.8)
project(bumperbot_msgs)

if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
  add_compile_options(-Wall -Wextra -Wpedantic)
endif()


find_package(ament_cmake REQUIRED)
find_package(std_msgs REQUIRED)
find_package(rosidl_default_generators REQUIRED)

rosidl_generate_interfaces(${PROJECT_NAME}
  "srv/AddTwoInts.srv"
)


if(BUILD_TESTING)
  find_package(ament_lint_auto REQUIRED)

  set(ament_cmake_copyright_FOUND TRUE)
  set(ament_cmake_cpplint_FOUND TRUE)
  ament_lint_auto_find_test_dependencies()
endif()

ament_package()

The new parts:

  • find_package(rosidl_default_generators REQUIRED) loads the tools that turn interface files into code.
  • rosidl_generate_interfaces(${PROJECT_NAME} "srv/AddTwoInts.srv") names the file to convert. ${PROJECT_NAME} is bumperbot_msgs, set by project() on line 2.
  • find_package(std_msgs REQUIRED) is not used by this service (it only uses int64), but it does no harm and is handy when later messages use standard types.

package.xml

Open package.xml of bumperbot_msgs.

package.xml of bumperbot_msgs before the change
package.xml of bumperbot_msgs before the change

Make it look like this:

<?xml version="1.0"?>
<?xml-model href="http://download.ros.org/schema/package_format3.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="3">
  <name>bumperbot_msgs</name>
  <version>0.0.0</version>
  <description>TODO: Package description</description>
  <maintainer email="techarcanist@todo.todo">techarcanist</maintainer>
  <license>TODO: License declaration</license>

  <buildtool_depend>ament_cmake</buildtool_depend>

  <depend>std_msgs</depend>
  <build_depend>rosidl_default_generators</build_depend>

  <exec_depend>rosidl_default_runtime</exec_depend>

  <member_of_group>rosidl_interface_packages</member_of_group>
  <test_depend>ament_lint_auto</test_depend>
  <test_depend>ament_lint_common</test_depend>

  <export>
    <build_type>ament_cmake</build_type>
  </export>
</package>

The new parts:

  • <build_depend>rosidl_default_generators</build_depend>: the generators are needed while building.
  • <exec_depend>rosidl_default_runtime</exec_depend>: the generated code needs these libraries when it runs.
  • <member_of_group>rosidl_interface_packages</member_of_group>: marks this package as one that holds interfaces. As far as I know, the build refuses to generate interfaces without it.

Build

Go back to the workspace and build, so the Python code can use the new service type:

cd ~/bumperbot_ws
colcon build
colcon build finishing with bumperbot_msgs built
colcon build finishing with bumperbot_msgs built

Check that the new type exists. Source the workspace, then show the interface:

. install/setup.bash
ros2 interface show bumperbot_msgs/srv/AddTwoInts

What you should see (newer versions also print the # comment lines)

int64 a
int64 b
---
int64 sum

Write the service server

Create simple_service_server.py inside bumperbot_py_examples/bumperbot_py_examples, next to the other example nodes.

simple_service_server.py next to the other example nodes in bumperbot_py_examples
simple_service_server.py next to the other example nodes in bumperbot_py_examples

Write this code:

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


class SimpleServiceServer(Node):

    def __init__(self):
        super().__init__("simple_service_server")
        self.service_ = self.create_service(AddTwoInts, "add_two_ints", self.serviceCallback)
        self.get_logger().info("Service add_two_ints Ready")


    def serviceCallback(self, req, res):
        self.get_logger().info("New Request Received a: %d, b: %d" % (req.a, req.b))
        res.sum = req.a + req.b
        self.get_logger().info("Returning sum: %d" % res.sum)
        return res


def main():
    rclpy.init()

    simple_service_server = SimpleServiceServer()
    rclpy.spin(simple_service_server)

    simple_service_server.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()

What it does, in short

  • Line 3 imports the service type generated from AddTwoInts.srv.
  • Line 10 creates the server: type AddTwoInts, name add_two_ints, and the function to call for every request, serviceCallback.
  • Lines 14 to 18: for each request, ROS 2 passes the request (req) and an empty response (res). The callback logs the numbers, fills res.sum and returns res, which ROS 2 sends back to the caller.
  • main() starts ROS 2, creates the node and keeps it waiting for requests with rclpy.spin.

How the code works, line by line

The visualizer below covers this file and the four files around it: AddTwoInts.srv, CMakeLists.txt, package.xml and the two lines added in setup.py and package.xml. Pick a level, click any line, follow a request through the code, or break something on purpose.

Register the node

In setup.py of bumperbot_py_examples, add the new executable to console_scripts:

The simple_service_server entry point added on line 32 of setup.py
The simple_service_server entry point added on line 32 of setup.py
entry_points={
    'console_scripts': [
        # ... the executables you added earlier stay here ...
        'simple_service_server = bumperbot_py_examples.simple_service_server:main',
    ],
},

The part before = is the name used with ros2 run. The part after is the module (simple_service_server.py) and the function to start (main).

In package.xml of bumperbot_py_examples, add the new package as a dependency, because the node imports from it:

bumperbot_msgs added as an exec_depend in package.xml of bumperbot_py_examples
bumperbot_msgs added as an exec_depend in package.xml of bumperbot_py_examples
<exec_depend>bumperbot_msgs</exec_depend>

Build, run and test

Start the server

Build again, because setup.py and package.xml changed:

cd ~/bumperbot_ws
colcon build
Building the workspace again after adding the node
Building the workspace again after adding the node

Open a new terminal (terminal 1). Source the workspace and start the node:

cd ~/bumperbot_ws
. install/setup.bash
ros2 run bumperbot_py_examples simple_service_server

What you should see (the number in the first brackets is the time, so yours differs)

[INFO] [1794209330.489125457] [simple_service_server]: Service add_two_ints Ready
The server running and printing Service add_two_ints Ready
The server running and printing Service add_two_ints Ready

Leave this terminal running. The server waits here for requests.

See the service

Open another terminal (terminal 2). Source the workspace and list the services:

cd ~/bumperbot_ws
. install/setup.bash
ros2 service list

What you should see

/add_two_ints
/simple_service_server/describe_parameters
/simple_service_server/get_parameter_types
/simple_service_server/get_parameters
/simple_service_server/get_type_description
/simple_service_server/list_parameters
/simple_service_server/set_parameters
/simple_service_server/set_parameters_atomically
ros2 service list showing /add_two_ints
ros2 service list showing /add_two_ints

/add_two_ints is ours. The other seven are parameter services that, as far as I know, every rclpy node creates for itself.

Call it from the terminal

In terminal 2 (already sourced), send one request with a = 7 and b = 5. This one line is ready to copy:

ros2 service call /add_two_ints bumperbot_msgs/srv/AddTwoInts "{a: 7, b: 5}"

What you should see

waiting for service to become available...
requester: making request: bumperbot_msgs.srv.AddTwoInts_Request(a=7, b=5)

response:
bumperbot_msgs.srv.AddTwoInts_Response(sum=12)

Typing it yourself? Let Tab fill in the long parts:

  1. Type ros2 service call /add_two_ints and press Tab twice: the type bumperbot_msgs/srv/AddTwoInts is added.
  2. Type a space and "a, then press Tab twice: a request template appears, "a: 0 and b: 0".
  3. Change the numbers to 7 and 5 and press Enter.
Tab completion filling in the service type and the request template
Tab completion filling in the service type and the request template

Tab completion builds the same request over two lines. That form works too, and can also be copied:

ros2 service call /add_two_ints bumperbot_msgs/srv/AddTwoInts "a: 7
b: 5"
The call with a: 7 and b: 5 returning sum=12
The call with a: 7 and b: 5 returning sum=12

The terminal acts as the client: it waits for the service, sends the request with a = 7 and b = 5, and prints the response sum=12.

What the server printed

The server terminal logging the request and the returned sum
The server terminal logging the request and the returned sum

What terminal 1 (the server) now shows

[INFO] [1794209330.489125457] [simple_service_server]: Service add_two_ints Ready
[INFO] [1794209761.812979091] [simple_service_server]: New Request Received a: 7, b: 5
[INFO] [1794209761.813279298] [simple_service_server]: Returning sum: 12

The first line appeared when the node started. The other two appeared only when the request arrived: the callback runs once per request, not in a loop.

Remember

  • A .srv file has a request part and a response part, separated by ---.
  • Interfaces live in an ament_cmake package and need rosidl_generate_interfaces, the generator and runtime dependencies, and member_of_group.
  • A server is created with create_service(type, name, callback). The callback gets the request and an empty response, fills the response and must return it.
  • A node that imports a service type needs that package as a dependency in its own package.xml.
  • ros2 service list shows the service; ros2 service call acts as a client for testing.