Main Content

call

Call ROS or ROS 2 service server and receive a response

Description

response = call(serviceclient) sends a default service request message and waits for a service response. The default service request message is an empty message of type serviceclient.ServiceType.

example

response = call(serviceclient,requestmsg) specifies a service request message, requestmsg, to be sent to the service.

example

[response,status,statustext] = call(___) returns a status indicating whether a response has been received successfully, and a statustext that captures additional information about the status, using any of the arguments from the previous syntaxes. If the call fails, the status will be false with an empty default response message, and this function will not display an error.

example

response = call(___,Name,Value) provides additional options specified by one or more Name,Value pair arguments, using any of the arguments from the previous syntaxes.

example

Examples

collapse all

Connect to a ROS network.

rosinit
Launching ROS Core...
Done in 0.45482 seconds.
Initializing ROS master on http://172.20.147.47:55175.
Initializing global node /matlab_global_node_34277 with NodeURI http://dcc300956glnxa64:41953/ and MasterURI http://localhost:55175.

Set up a service server. Use structures for the ROS message data format.

server = rossvcserver('/test', 'std_srvs/Empty', @exampleHelperROSEmptyCallback,...
                      'DataFormat','struct');
client = rossvcclient('/test','DataFormat','struct');

Check whether the service server is available. If it is, wait for the service client to connect to the server.

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

connectionStatustext = 
'success'

Call service server with default message.

response = call(client)
response = struct with fields:
    MessageType: 'std_srvs/EmptyResponse'

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,"Timeout",3);
if ~status
    numCallFailures = numCallFailues + 1;
    fprintf("Call failure number %d. Error cause: %s\n",numCallFailures,statustext)
else
    disp(response)
end
    MessageType: 'std_srvs/EmptyResponse'

Shut down the ROS network.

rosshutdown
Shutting down global node /matlab_global_node_34277 with NodeURI http://dcc300956glnxa64:41953/ and MasterURI http://localhost:55175.
Shutting down ROS master on http://172.20.147.47:55175.

Connect to a ROS network.

rosinit
Launching ROS Core...
Done in 0.43746 seconds.
Initializing ROS master on http://172.20.147.47:56947.
Initializing global node /matlab_global_node_99620 with NodeURI http://dcc300956glnxa64:36433/ and MasterURI http://localhost:56947.

Set up a service server and client. This server calculates the sum of two integers and is based on a ROS service tutorial.

sumserver = rossvcserver('/sum','roscpp_tutorials/TwoInts',@exampleHelperROSSumCallback);
sumclient = rossvcclient('/sum');

Get the request message for the client and modify the parameters.

reqMsg = rosmessage(sumclient);
reqMsg.A = 2;
reqMsg.B = 1;

Call service and get a response. The response should be the sum of the two integers given in the request message. Wait 5 seconds for the service to time out.

response = call(sumclient,reqMsg,'Timeout',5)
response = 
  ROS TwoIntsResponse message with properties:

    MessageType: 'roscpp_tutorials/TwoIntsResponse'
            Sum: 3

  Use showdetails to show the contents of the message

Shut down the ROS network.

rosshutdown
Shutting down global node /matlab_global_node_99620 with NodeURI http://dcc300956glnxa64:36433/ and MasterURI http://localhost:56947.
Shutting down ROS master on http://172.20.147.47:56947.

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

Input Arguments

collapse all

ROS or ROS 2 service client, specified as a ros.ServiceClient or ros2serviceclient object handle, respectively.

Request message, specified as a Message object handle or structure. The default message type is serviceclient.ServiceType.

Note

In a future release, ROS Toolbox will use message structures instead of objects for ROS messages.

To use message structures now, set the "DataFormat" name-value argument to "struct". For more information, see ROS Message Structures.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: "TimeOut",5

Timeout for service response in seconds, specified as a comma-separated pair consisting of "Timeout" and a scalar. If the service client does not receive a service response and the timeout period elapses, call displays an error message and lets MATLAB® continue running the current program. The default value of inf prevents MATLAB from running the current program until the service client receives a service response.

Message format for ROS service clients, specified as "object" or "struct". Set this property on creation of the service client using the name-value input. For more information, see ROS Message Structures. This argument applies to ROS service clients only.

Output Arguments

collapse all

Response message sent by the service server, returned as a Message object handle or structure.

Status of the service call, returned as a logical scalar. If the call fails, status will be false.

Note

Use the status output argument when you use call for code generation. This will avoid runtime errors and outputs the status instead, which can be reacted to in the calling code.

Status text associated with the service call status, returned as one of the following:

  • 'success' — The service response was successfully received.

  • 'input' — The input to the function is invalid.

  • 'timeout' — The service response was not received within the specified timeout.

  • 'unknown' — The service response was not received due to unknown errors.

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 R2019b

expand all