When nodes communicate using services, the node that sends a request for data is called the client node, and the one that responds to the request is the service node. The structure of the request and response is determined by a .srv
file.
In this simple example, you will create a simple integer addition system; one node requests the sum of two integers, and the other responds with the result.
Inside the humble_ws/src/ros_basics/ros_basics
directory, create a new file called service_member_function.py
and paste the following code within:
from example_interfaces.srv import AddTwoInts
import rclpy
from rclpy.node import Node
class MinimalService(Node):
def __init__(self):
super().__init__('minimal_service')
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():
rclpy.init()
minimal_service = MinimalService()
rclpy.spin(minimal_service)
rclpy.shutdown()
if __name__ == '__main__':
main()
The first import
statement imports the AddTwoInts
service type from the example_interfaces
package. The following import
statement imports the ROS 2 Python client library, specifically the Node
class.
def __init__(self):
super().__init__('minimal_service')
self.srv = self.create_service(AddTwoInts, 'add_two_ints', self.add_two_ints_callback)
The definition of the service callback 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 MinimalService
class to create the service node, and spins the node to handle callbacks.
Navigate one level back to the main package directory humble_ws/src/ros_basics
, where the setup.py
, setup.cfg
, and package.xml
files have been created for you.
Open package.xml
with your text editor.
Add the following dependencies corresponding to your node’s import statements:
<exec_depend>example_interfaces</exec_depend>
Open the setup.py
file. Add the following lines within the console_scripts
brackets of the entry_points
field:
entry_points={
'console_scripts': [
[...]
'service = ros_basics.service_member_function:main',
],
},