Main Content

rossvcclient

Connect to ROS service server

Description

Use rossvcclient or ros.ServiceClient to create a service client object over ROS network. This service client uses a persistent connection to send requests to, and receive responses from, a ROS service server. The connection persists until the service client is deleted or the service server becomes unavailable.

Use the ros.ServiceClient syntax when connecting to a specific ROS node.

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.

Creation

Description

client = rossvcclient(servicename,servicetype) creates a service client with the given ServiceName that connects to a service serve of type ServiceType. This command syntax prevents the current MATLAB® program from running until it can connect to the service server.

example

client = rossvcclient(servicename,servicetype,Name,Value) provides additional options specified by one or more Name,Value pair arguments.

[client,reqmsg] = rossvcclient(___) returns a new service request message in reqmsg, using any of the arguments from previous syntaxes. The message type of reqmsg is determined by the service that client is connected to. The message is initialized with default values. You can also create the request message using rosmessage.

[___] = rossvcclient(___,"DataFormat","struct") uses message structures instead of objects. For more information, see ROS Message Structures.

[___] = rossvcclient(___,"IsPersistent","true") determines that the service client is persistent.

client = ros.ServiceClient(node,name) creates a service client that connects to a service server. The client gets its service type from the server. The service client attaches to the ros.Node object handle, node.

example

client = ros.ServiceClient(node,name,type) creates a service client that connects to a service server with the given service name name, and type, type. The service client attaches to the ros.Node object handle, node.

client = ros.ServiceClient(node, name,"Timeout",timeout) specifies a timeout period in seconds for the client to connect the service server.

[___] = ros.ServiceClient(___,"DataFormat","struct") uses message structures instead of objects. For more information, see ROS Message Structures.

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"

Message format, specified as "object" or "struct". You must set this property on creation using the name-value input. For more information, see ROS Message Structures.

Option to determine if the service connection is persistent, specified as a numeric or logical 1(true) or 0(false).

With a persistent connection, a client always stays connected to a service. The connection persists until the service client gets deleted or the service server becomes unavailable. Persistent connections significantly improve performance for repeated requests, however, they also make the client more fragile to service failures when the connection is lost.

In case of non-persistent connection, a client normally does a lookup and reconnects to a service each time. This connection is slower but potentially allows a client to connect to a different node each time it does a service call, assuming that the lookup return a different node.

Data Types: logical

Object Functions

rosmessageCreate ROS messages
callCall ROS or ROS 2 service server and receive a response
isServerAvailableDetermine if ROS or ROS 2 service server is available
waitForServerWait for ROS or ROS 2 service server to start

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.

Create a ROS service serve by creating a ServiceServer object and use ServiceClient objects to request information over the network. The callback function used by the server takes a string, reverses it, and returns the reversed string.

Start the ROS master and node.

master = ros.Core;
Launching ROS Core...
Done in 0.52505 seconds.
node = ros.Node('/test');

Create a service server. This server expects a string as a request and responds with a string based on the callback. Use structures for the ROS message data format.

server = ros.ServiceServer(node,'/data/string',...
                            'roseus/StringString','DataFormat','struct');

Create a callback function. This function takes an input string as the Str property of req and returns it as the Str property of resp. The function definition is shown here, but is defined below the example. req is a ROS message you create using rosmessage.

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

Assign the callback function for incoming service calls.

server.NewRequestFcn = @flipString;

Create a service client and connect to the service server. Use structures for the ROS message data format.

Create a request message based on the client.

client = ros.ServiceClient(node,'/data/string','DataFormat','struct');
request = rosmessage(client);
request.Str = 'hello world';

Send a service request and wait for a response. Specify that the service waits 3 seconds for a response.

response = call(client,request,'Timeout',3)
response = struct with fields:
    MessageType: 'roseus/StringStringResponse'
            Str: 'dlrow olleh'

The response is a flipped string from the request message.

Clear the service client, service server, and ROS node. Shut down the ROS master.

clear('client', 'server', 'node')
clear('master')
function [resp] = flipString(~,req,resp)
% FLIPSTRING Reverses the order of a string in REQ and returns it in RESP.
resp.Str = fliplr(req.Str);
end

Extended Capabilities

Version History

Introduced in R2019b

expand all