%% Use ROS Service Server with ServiceServer and ServiceClient Objects
% 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;
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.

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

%
% 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. Create a request message based on the client.

client = ros.ServiceClient(node,'/data/string');
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)

% 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

% Copyright 2019 The MathWorks, Inc.