Welcome to RDK S600 Developer Kit repository
8.ROS2 service communication
8. ROS2 Service Communication
Note: The accompanying reference video uses the ROS Humble version, for reference only
1. Service Communication Overview
Service communication is a request-response communication model. In communication, the client sends request data to the server, and the server responds with results to the client.
Client/Server model:

From the perspective of service implementation mechanism, this ask-and-answer form is called the Client/Server model, abbreviated as CS model. When the client needs certain data, it sends a request message for a specific service. After the server receives the request, it processes and sends back a response message.
This communication mechanism is also common in real life, such as the web pages we browse. At this time, your computer browser is the client. Through domain names or various operations, it sends requests to the website server. After the server receives the request, it returns the page data to be displayed.
2. Create New Package
In the workspace src directory:
ros2 pkg create pkg_service --build-type ament_python --dependencies rclpy --node-name server_demo
After executing the above command, the pkg_service package will be created, along with a server_demo node, and the related configuration files will already be set up.

3. Service Server Implementation
3.1 Create Service Server
Next, edit [server_demo.py] to implement the service server functionality. Add the following code:
x# Import related library filesimport rclpyfrom rclpy.node import Nodefrom example_interfaces.srv import AddTwoInts
class Service_Server(Node): def __init__(self,name): super().__init__(name) # Create a service server using create_service function with parameters: # service data type, service name, service callback function (the service content) self.srv = self.create_service(AddTwoInts, '/add_two_ints', self.Add2Ints_callback) # The service callback function adds two integers and returns the result def Add2Ints_callback(self,request,response): response.sum = request.a + request.b print("response.sum = ",response.sum) return responsedef main(): rclpy.init() server_demo = Service_Server("publisher_node") rclpy.spin(server_demo) server_demo.destroy_node() # Destroy node object rclpy.shutdown() # Shutdown ROS2 Python interfaceKey point: Look at the service callback function Add2Ints_callback. Besides self, the parameters are request and response. The request contains the parameters needed for the service, and the response contains the service feedback result. request.a and request.b are the content of the request part, and response.sum is the content of the response part. First, let's look at what the AddTwoInts data type looks like.
You can use the following command to view:
xxxxxxxxxxros2 interface show example_interfaces/srv/AddTwoInts
"---" divides the data type into two parts. The upper part represents the request, and the lower part represents the response. Each part has its own variables, such as int64 a and int64 b. Therefore, when passing parameters, you need to specify the values for a and b. Similarly, for the feedback result, you need to specify the value for sum.
3.2 Edit Configuration File
Open setup.py and add to the console_scripts list:
xxxxxxxxxx'server_demo = pkg_service.server_demo:main',
3.3 Build Package
Build the package:
xxxxxxxxxxcolcon build --packages-select pkg_service
3.4 Run Program
Refresh environment variables and run the node:
xxxxxxxxxxros2 run pkg_service server_demo

After running, since the service is not called, there is no feedback data. You can call the service via command line. First, query what services are currently available. Enter in another terminal:
xxxxxxxxxxros2 service list
/add_two_ints is the service we need to call. Use the following command to call it:
xxxxxxxxxxros2 service call /add_two_ints example_interfaces/srv/AddTwoInts "{a: 1,b: 4}"
Here we set a to 1 and b to 4, which means calling the service to calculate the sum of 1 and 4:

As shown in the image, after calling the service, the returned result is 5. The terminal running the service server also prints the returned value.
4. Client Implementation
4.1 Create Client
Create a new file [client_demo.py] in the same directory as [server_demo.py]:

Next, edit [client_demo.py] to implement the client functionality. Add the following code:
xxxxxxxxxx# Import related librariesimport rclpyfrom rclpy.node import Nodefrom example_interfaces.srv import AddTwoInts
class Service_Client(Node): def __init__(self,name): super().__init__(name) # Create client using create_client function with parameters: # service data type, service topic name self.client = self.create_client(AddTwoInts,'/add_two_ints') # Loop waiting for server to start successfully while not self.client.wait_for_service(timeout_sec=1.0): print("service not available, waiting again...") # Create service request data object self.request = AddTwoInts.Request()
def send_request(self): self.request.a = 10 self.request.b = 90 # Send service request self.future = self.client.call_async(self.request)
def main(): rclpy.init() # Node initialization service_client = Service_Client("client_node") # Create object service_client.send_request() # Send service request while rclpy.ok(): rclpy.spin_once(service_client) # Check if data processing is complete if service_client.future.done(): try: # Get and print service feedback information response = service_client.future.result() print("service_client.request.a = ",service_client.request.a) print("service_client.request.b = ",service_client.request.b) print("Result = ",response.sum) except Exception as e: service_client.get_logger().info('Service call failed %r' % (e,)) break service_client.destroy_node() rclpy.shutdown()
4.2 Edit Configuration File
Open setup.py and add to the console_scripts list:
xxxxxxxxxx'client_demo = pkg_service.client_demo:main'
4.3 Build Package
xxxxxxxxxxcolcon build --packages-select pkg_service
4.4 Run Program
Refresh environment variables and run the node:
xxxxxxxxxx# Start service server noderos2 run pkg_service server_demo# Start client noderos2 run pkg_service client_demo
Run the service server first, then run the client. The client provides a=10, b=90. The service server calculates the sum, and the result is 100. The result is printed in both terminals.