In ROS, messages which are used to communicate with ROS Services are defined in srv/*.srv files. Each service requires 2 messages: Request, Response (see ROS documentation for defining services in ROS2 or ROS1.
In order to work with ROS Services from jrosservices users need to:
To simplify this process users are encouraged to use msgmonster application.
ROS "add_two_ints" service definition file looks like this:
int64 a int64 b --- int64 sum
In ROS2 this file is called "AddTwoInts.srv" and in ROS1 as "TwoInts.srv"
We need to map it to the corresponding service definition Java class. Use final results of these definitions for ROS2 or ROS1.
For ROS1 we additionally need to obtain md5 sum for request/response messages which in both cases should match service definition. Such md5 sum can be found with "rossrv" command:
Once Java service definition is created, it can be used to run ROS services, as well as to call them.
In this example we are going to:
How to create and run "add_two_ints" service can be found in:
Required Java dependencies:
Code:
var clientFactory = new JRos2ClientFactory(); var serviceClientFactory = new JRos2ServicesFactory(); try (var client = clientFactory.createClient(); var serviceClient = serviceClientFactory .createClient(client, new AddTwoIntsServiceDefinition(), "add_two_ints")) { var request = new AddTwoIntsRequestMessage(3, 2); var response = serviceClient.sendRequestAsync(request).get(); System.out.println(response); }
Required Java dependencies:
Code:
var clientFactory = new JRos1ClientFactory(); var serviceClientFactory = new JRos1ServiceClientFactory(); try (var client = clientFactory.createClient(); var serviceClient = serviceClientFactory .createClient(client, new AddTwoIntsServiceDefinition(), "add_two_ints")) { var request = new AddTwoIntsRequestMessage(3, 2); var response = serviceClient.sendRequestAsync(request).get(); System.out.println(response); }
In this example we are going to:
Code:
var clientFactory = new JRos2ClientFactory(); var serviceClientFactory = new JRos2ServicesFactory(); ServiceHandler<AddTwoIntsRequestMessage, AddTwoIntsResponseMessage> proc = request -> { System.out.println("Received new request " + request); var response = new AddTwoIntsResponseMessage(request.a + request.b); System.out.println("Result " + response); return response; }; try (var client = clientFactory.createClient(); var service = serviceClientFactory.createService( client, new AddTwoIntsServiceDefinition(), "jros_add_two_ints", proc)) { service.start(); System.out.println("Press Enter to stop ROS service..."); System.in.read(); }
In terminal, use "ros2" command to send requests to "jros_add_two_ints" Java service:
waiting for service to become available... requester: making request: example_interfaces.srv.AddTwoInts_Request(a=10, b=1) response: example_interfaces.srv.AddTwoInts_Response(sum=11)