Service Definitions

Code generated by gennodejs for ROS Services contain both a request and a response.

  • my_package/srv/Foo.srv → my_package.srv.Foo
    my_package/srv/Foo.srv → my_package.srv.Foo.Request
    my_package/srv/Foo.srv → my_package.srv.Foo.Response

Providing Services

Services are advertised through the NodeHandle.

const AddTwoInts = rosnodejs.require('ros_tutorials/AddTwoInts');

rosnodejs.initNode('/test_node')
.then((nh) => {
  const addTwoInts = (req, resp) => {
    resp.sum = req.a + req.b;
    return true;
  };

  let service = nh.advertiseService('/add_two_ints', AddTwoInts, addTwoInts);
});

Calling Services

ServiceClients can be created through the NodeHandle.

let serviceClient = nh.serviceClient('/add_two_ints', AddTwoInts);

When calling the service, simply provide your request message and a callback to handle the response.

let req = new AddTwoInts.Request();
req.a = 1;
req.b = 2;
serviceClient.call(req)
.then((resp) => { console.log(resp); });

Wait for Service

The NodeHandle also provides an interface to wait for a service.

nh.waitForService('/add_two_ints')
.then(() => {
  // call it, presumably
});

When waiting for a service, you can provide an optional timeout argument that specifies a maximum amount of time (in milliseconds) to wait for. To help handle this case, the returned promise resolves with whether or not the service was available.

nh.waitForService('/add_two_ints', 1000)
.then((available) => {
  if (available) {
    // as you were
  }
});

Wiki: rosnodejs/overview/services (last edited 2017-10-30 13:42:30 by chris-smith)