Main Content

ros2svcserver

Create ROS 2 service server

Since R2021b

Description

Use ros2svcserver to create a ROS 2 service server that can receive requests from, and send responses to, a ROS 2 service client.

When you create the service server, it registers itself with the ROS 2 network. When you create a service client, it establishes a connection to the server. The connection persists while both client and server exist and can reach each other. To get a list of services, or to get information about a particular service that is available on the current ROS 2 network, use the ros2 function.

The service has an associated message type that contains a pair of messages: one for the request and one for the response. The service server receives a request, constructs an appropriate response based on a callback function, and returns it to the client. The behavior of the service server is inherently asynchronous because it becomes active only when a service client connects to the ROS 2 network and issues a call. For more information, see Call and Provide ROS 2 Services.

Creation

Description

server = ros2svcserver(node,servicename,servicetype,callback) creates a service server of the specified servicetype available in the ROS 2 network under the name servicename. It attaches the server to the ROS 2 node specified by the ros2node object, node. It also specifies the callback function, which is set to the NewRequestFcn property. The input arguments servicename and servicetype, are set to the ServiceType and ServiceName properties, respectively.

example

server = ros2svcserver(___,Name=Value) sets the rest of the properties based on the additional options specified by one or more Name=Value pair arguments, using the arguments from the previous syntax.

example

Properties

expand all

This property is read-only.

Name of the service, specified as a string scalar or character vector.

Example: "/gazebo/get_model_state"

This property is read-only.

Type of service, specified as a string scalar or character vector.

Example: "gazebo_msgs/GetModelState"

Callback property, specified as a function handle or cell array. In the first element of the cell array, specify either a function handle, string scalar, or character vector representing a function name. In subsequent elements, specify user data.

The service callback function requires at least two input arguments with one output. The first argument, reqMsg, is the request message object sent by the service client. The second argument is the default response message object, defaultRespMsg. The callback returns a response message, response, based on the input request message and sends it back to the service client. Use the default response message as a starting point for constructing the request message. The function header for the callback is:

function response = serviceCallback(reqMsg,defaultRespMsg)

Specify the NewRequestFcn property as:

server.NewRequestFcn = @serviceCallback;

When setting the callback, you pass additional parameters to the callback function by including both the callback function and the parameters as elements of a cell array. The function header for the callback is:

function response = serviceCallback(reqMsg,defaultRespMsg,userData)

Specify the NewRequestFcn property as:

server.NewRequestFcn = {@serviceCallback,userData};

This property is read-only.

Mode of storing requests in the queue, specified as a string or character vector. If the queue fills with requests waiting to be processed, then old requests will be dropped to make room for new. When set to "keeplast", the queue stores the number of requests set by the Depth property. Otherwise, when set to "keepall", the queue stores all requests up to the MATLAB® resource limits.

Example: "keeplast"

Data Types: char | string

This property is read-only.

Size of the request queue in number of requests stored in the queue, specified as a non-negative scalar integer. This only applies when History is set to "keeplast".

Example: 42

Data Types: double

This property is read-only.

Requirement on delivery guarantee of request and response, specified as a string or character vector. If "reliable", then delivery is guaranteed, but may retry multiple times. If "besteffort", then attempt delivery and do not retry. "reliable" setting is recommended for services.

Note

The quality of service settings must be compatible between service servers and clients for a connection to be made.

Example: "reliable"

Data Types: char | string

This property is read-only.

Requirement on persistence of the client, specified as a string or character vector. If "volatile", then requests are not required to persist. If "transientlocal", then the server will require clients to persist and receive responses for the number of previous requests specified by Depth. "volatile" setting is recommended to prevent servers from receiving out of date requests in the event of a server restart.

Note

The quality of service settings must be compatible between service servers and clients for a connection to be made.

Example: "volatile"

Data Types: char | string

Maximum amount of time allowed between receiving a service request and sending a response, specified as a positive scalar. The Deadline QoS parameter of service clients sending requests to the server must be greater than or equal to the value of this parameter.

The default value is Inf which implies that after the service server receives a service request, it can wait for an infinite period of time before sending response to that request.

Length of time a service request is considered valid, specified as a positive scalar. The server does not process service requests persisting longer than the specified lifespan in the queue.

The default value is Inf which implies that a service request received by service server is considered valid for infinite period of time.

Liveliness check of service client by service server, specified as automatic. This parameter is a measure of whether the client is still alive.

Liveliness set to automatic implies that once the action server gets a service request from an action client, it will treat that client as active for an additional Lease Duration.

Maximum amount of time before which a connected service client has to assert liveliness, specified as a positive scalar.

The default value is Inf which implies that the service client connected to the server can assert liveliness for infinite period of time.

Object Functions

ros2messageCreate ROS 2 message structures

Examples

collapse all

Create a sample ROS 2 network with two nodes.

node_1 = ros2node('node_1_service_client');
node_2 = ros2node('node_2_service_client');

Set up a service server and attach it to a ROS 2 node. Specify the callback function flipstring, which flips the input string. The callback function is defined at the end of this example.

server = ros2svcserver(node_1,'/test','test_msgs/BasicTypes',@flipString);

Set up a service client of the same service type and attach it to a different node.

client = ros2svcclient(node_2,'/test','test_msgs/BasicTypes');

Wait for the service client to connect to the server.

[connectionStatus,connectionStatustext] = waitForServer(client)
connectionStatus = logical
   1

connectionStatustext = 
'success'

Create a request message based on the client. Assign the string to the corresponding field in the message, string_value.

request = ros2message(client);
request.string_value = 'hello world';

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

if(isServerAvailable(client))
    response = call(client,request,'Timeout',3);
end

The response is a flipped string from the request message which you see in the string_value field.

response.string_value
ans = 
'dlrow olleh'

If the call function above fails, it results in an error. Instead of an error, if you would prefer to react to a call failure using conditionals, return the status and statustext outputs from the call function. The status output indicates if the call succeeded, while statustext provides additional information.

numCallFailures = 0;
[response,status,statustext] = call(client,request,"Timeout",3);
if ~status
    numCallFailures = numCallFailues + 1;
    fprintf("Call failure number %d. Error cause: %s\n",numCallFailures,statustext)
else
    disp(response.string_value)
end
dlrow olleh

The callback function used to flip the string is defined below.

function resp = flipString(req,resp)
% FLIPSTRING Reverses the order of a string in REQ and returns it in RESP.
resp.string_value = fliplr(req.string_value);
end

Tips

  • ROS 2 service servers cannot communicate errors in callback execution directly to clients. In such situations, the servers only return the default response without any indication of failure. Hence, it is recommended to use try-catch blocks within the callback function, and set specific fields in the response message to communicate the success/failure of the callback execution on the server side.

Extended Capabilities

Version History

Introduced in R2021b