Writing a Simple Service in Matlab

Writing matlab function

The Matlab functions are searching in packages which were specified at interface starting. Only folders package_name/matlab/* are visible from matlab.
Even that Matlab functions are (for now) finding across the whole $ROS_WORKSPACE directory it will be nice to place all functions to folder matlab in appropriate package. While creating matlab function be 'respectful' to other ros users and named your functions uniquely.

roscd clopema_matlab_tutorials/
mkdir matlab
cd matlab

To create a matlab function there is a possibility to use our template generator, it will create function with sample input/output variables set in it. Sample variables are set to default value and depend on srv type.

rosrun clopema_matlab gen_matlab_function_service.py AddTwoInts clopema_matlab_tutorials/AddTwoInts

The command create AddTwoInts.m file in current directory. File should contains following code:
function ros_out = AddTwoInts(ros_in)
%Automatically generated function for ROS (Robot Operating System) implementation in matlab
% in ros_out variable the default values of output message fields are set
% in commented variable ros_in (overlaying input) the default values for input message are set 
    ros_out = struct('Sum', 0);
    %ros_in = struct('A', 0,'B', 0);

end

ros_in variable is commented because it will be set automatically when service is called. All variables from srv type are stored in struct and ros arrays are transformed to cell.

Adding the following command at the end of the function body will complete our Matlab function:

ros_out.Sum = ros_in.A + ros_in.B;

Mapping function to service

The next step in service creation process is to run node which will remap service to Matlab function we have created.

Node parameters are:
- Type of the srv file (srv type)
- Name of the service that node will provide (how ROS will see our service)
- Name of the matlab function

After following command will be executed the service add_two_ints will be remaped to AddTwoInts function in matlab.

rosrun clopema_matlab map_srv_to_mtlb.py clopema_matlab_tutorials/AddTwoInts add_two_ints AddTwoInts

Calling (testing) our service

rosservice call /add_two_ints 5 98

If service will not print result, check if at least one matlab instance is running from ros.

rosrun clopema_matlab call_matlab