Main Content

Create ROS 2 Service Server in Simulink

This example shows how to set up a ROS 2 service server in Simulink® which provides the vector cross product as response for any two input vectors. You then create a service client, connect to the service server and send a service request with two input vectors.

Inspect Service Server Model

Open the setupROS2ServiceServer model.

modelName = "setupROS2ServiceServer";

The Receive Service Request block processes an incoming service request from the client and outputs the service request message. To execute the service request only when a new request is received, use the IsNew output as the enable signal to an Enabled Subsystem. In this model, the Enabled Subsytem takes in the service request message which contains the two input vectors, and the default response message as inputs. Then, it calculates the cross product of the two input vectors, assigns the cross product result vector to the appropriate field in the default response message and outputs the response message. To calculate the cross product, the model uses the vectors present in the float64_values and float32_values fields of the incoming service request message. The Send Service Response block then sends the response message to the service client.

This model implements the service with name /cross_product_service, and type test_msgs/Arrays. You can configure the name, service type and any quality of service (QoS) parameters of the service server in the Receive Service Request block mask.

Run the model to start the service server.


Create Service Client and Send Service Request

Create a ROS 2 node.

node1 = ros2node('service_client_node');

Use the ros2svcclient object to create a ROS 2 service client of the service type test_msgs/Arrays and attach it to the node.

[client,reqMsg] = ros2svcclient(node1,'/cross_product_service','test_msgs/Arrays');

Wait for the service client to connect to the server. Specify a timeout of 3 seconds.

[connectionStatus,connectionStatustext] = waitForServer(client,Timeout=3)
connectionStatus = logical

connectionStatustext = 

Create the service request message by assigning the first and second input vectors to the float64_values and float32_values fields, respectively. This example uses the X- and Y- axes basis vectors as the two input vectors.

reqMsg.float64_values = [1 0 0]';
reqMsg.float32_values = single([0 1 0]');

Check whether the service server is available. If it is, send the service request and wait for a response. Specify a wait time of 3 seconds for a response.

    respMsg = call(client,reqMsg,Timeout=3);

Output the response value. Note that the server returns the correct cross product value as the Z- axis basis vector.

ans = 3×1


Stop the service server.


See Also