Main Content

call

Call ROS or ROS 2 service server and receive a response

Since R2019b

Description

example

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

example

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

example

[response,status,statustext] = call(___)返回一个statusindicating whether aresponsehas been received successfully, and astatustext捕获abo血型的额外信息ut thestatus, using any of the arguments from the previous syntaxes. If the call fails, thestatuswill befalsewith an empty defaultresponsemessage, and this function will not display an error.

example

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

Examples

collapse all

Connect to a ROS network.

rosinit
Launching ROS Core... Done in 0.37844 seconds. Initializing ROS master on http://172.29.205.71:57759. Initializing global node /matlab_global_node_62458 with NodeURI http://dcc066343glnxa64:37831/ and MasterURI http://localhost:57759.

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 =logical1
connectionStatustext = 'success'

Call service server with default message.

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

If thecallfunction above fails, it results in an error. Instead of an error, if you would prefer to react to a call failure using conditionals, return thestatusandstatustextoutputs from the call function. Thestatusoutput indicates if the call succeeded, whilestatustextprovides 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)elsedisp(response)end
MessageType: 'std_srvs/EmptyResponse'

Shut down the ROS network.

rosshutdown
Shutting down global node /matlab_global_node_62458 with NodeURI http://dcc066343glnxa64:37831/ and MasterURI http://localhost:57759. Shutting down ROS master on http://172.29.205.71:57759.

Connect to a ROS network.

rosinit
Launching ROS Core... Done in 0.45266 seconds. Initializing ROS master on http://172.29.205.71:58376. Initializing global node /matlab_global_node_59388 with NodeURI http://dcc066343glnxa64:44193/ and MasterURI http://localhost:58376.

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_59388 with NodeURI http://dcc066343glnxa64:44193/ and MasterURI http://localhost:58376. Shutting down ROS master on http://172.29.205.71:58376.

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 functionflipstring, 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 =logical1
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 thestring_valuefield.

response.string_value
ans = 'dlrow olleh'

If thecallfunction above fails, it results in an error. Instead of an error, if you would prefer to react to a call failure using conditionals, return thestatusandstatustextoutputs from the call function. Thestatusoutput indicates if the call succeeded, whilestatustextprovides 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)elsedisp(response.string_value)end
dlrow olleh

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

functionresp = 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 aros.ServiceClientorros2serviceclientobject handle, respectively.

Request message, specified as aMessageobject handle or structure. The default message type isserviceclient.ServiceType.

Note

In a future release,ROS Toolboxwill 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, seeROS Message Structures.

Name-Value Arguments

Specify optional pairs of arguments asName1=Value1,...,NameN=ValueN, whereNameis the argument name andValueis 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 encloseNamein 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显示一个错误消息并让MATLAB®continue running the current program. The default value ofinfprevents 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, seeROS Message Structures. This argument applies to ROS service clients only.

Output Arguments

collapse all

Response message sent by the service server, returned as aMessageobject handle or structure.

Status of the service call, returned as alogicalscalar. If the call fails, status will befalse.

Note

Use thestatusoutput 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