call
Syntax
Description
sends a default service request message and waits for a serviceresponse
= call(serviceclient
)response
. The default service request message is an empty message of typeserviceclient.ServiceType
.
specifies a service request message,response
= call(serviceclient
,requestmsg
)requestmsg
, to be sent to the service.
[
返回一个response
,status
,statustext
] = call(___)status
indicating whether aresponse
has been received successfully, and astatustext
捕获abo血型的额外信息ut thestatus
, using any of the arguments from the previous syntaxes. If the call fails, thestatus
will befalse
with an empty defaultresponse
message, and this function will not display an error.
Examples
Call Service Client with Default Message
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 thecall
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 thestatus
andstatustext
outputs from the call function. Thestatus
output indicates if the call succeeded, whilestatustext
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)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.
Call for Response Using Specific Request Message
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.
Call ROS 2 Service Client With a Custom Callback Function
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_value
field.
response.string_value
ans = 'dlrow olleh'
If thecall
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 thestatus
andstatustext
outputs from the call function. Thestatus
output indicates if the call succeeded, whilestatustext
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)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
serviceclient
—Service client
ros.ServiceClient
object handle|ros2serviclient
object handle
ROS or ROS 2 service client, specified as aros.ServiceClient
orros2serviceclient
object handle, respectively.
requestmsg
—Request message
Message
object handle|structure
Request message, specified as aMessage
object 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
, whereName
is the argument name andValue
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 encloseName
in quotes.
Example:"TimeOut",5
TimeOut
—Timeout for service response in seconds
inf(default) |scalar
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 ofinf
prevents MATLAB from running the current program until the service client receives a service response.
DataFormat
—Message format for ROS service clients
"object"
(default) |"struct"
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
response
— Response message
Message
object handle | structure
Response message sent by the service server, returned as aMessage
object handle or structure.
status
— Status of the service call
logical
scalar
Status of the service call, returned as alogical
scalar. If the call fails, status will befalse
.
Note
Use thestatus
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.
statustext
— Status text associated with the service call status
character vector
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
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Supported only for the Build Type,
Executable
.Usage inMATLAB Functionblock is not supported.
Version History
Introduced in R2019bR2021a:ROS Message Structures
You can now create messages as structures with fields matching the message object properties. Using structures typically improves performance of creating, updating, and using ROS messages, but message fields are no longer validated when set. Message types and corresponding field values from the structures are validated when sent across the network.
To use ROS messages as structures, use the"DataFormat"
name-value argument when creating your publishers, subscribers, or other ROS objects. Any messages generated from these objects will utilize structures.
pub = rospublisher("/scan","sensor_msgs/LaserScan","DataFormat","struct") msg = rosmessage(pub)
You can also create messages as structures directly, but make sure to specify the data format as"struct"
for the publisher, subscriber, or other ROS objects as well. ROS objects still use message objects by default.
msg = rosmessage("/scan","sensor_msgs/LaserScan","DataFormat","struct")...pub = rospublisher("/scan","sensor_msgs/LaserScan","DataFormat","struct")
In a future release, ROS messages will use structures by default and ROS message objects will be removed.
For more information, seeImprove Performance of ROS Using Message Structures.
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select:.
你也可以从下面选择一个网站list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina(Español)
- Canada(English)
- United States(English)
Europe
- Belgium(English)
- Denmark(English)
- Deutschland(Deutsch)
- España(Español)
- Finland(English)
- France(Français)
- Ireland(English)
- Italia(Italiano)
- Luxembourg(English)
- Netherlands(English)
- Norway(English)
- Österreich(Deutsch)
- Portugal(English)
- Sweden(English)
- Switzerland
- United Kingdom(English)