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.
In this example we are going to send requests to ROS add_two_ints service from Java.
How to create and run add_two_ints service can be found in:
ROS add_two_ints service file AddTwoInts.srv looks like this:
int64 a int64 b --- int64 sum
We need to map it to the corresponding service definition Java class. Use final results of these definitions for ROS2 or ROS1.
Once we have service definition ready we can use it to send requests to add_two_ints service.
Required Java dependencies:
Code:
var clientFactory = new JRos2ClientFactory(); var serviceClientFactory = new JRos2ServiceClientFactory(); 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); }