[Documentation] [TitleIndex] [WordIndex

Publishers

You can create publishers on a given topic using a NodeHandle from rosnodejs.

const nh = rosnodejs.nh;
const pub = nh.advertise('/topic', 'std_msgs/String');

When creating publishers, you can specify the type of message to publish with either a string, as above, or using the class itself.

const std_msgs = rosnodejs.require('std_msgs');

const nh = rosnodejs.nh;
const pub = nh.advertise('/topic', std_msgs.msg.String);

Initialization

rosnodejs Publishers also provide a number of options to allow you to customize their behavior for your use case. These are provided through an optional object after specifying the message type.

const options = {...};
nh.advertise('/topic', std_msgs.msg.String, options);

The additional options are

Publishing

Calls to publish should be passed an instance of the desired message object. So, if you have advertised a publisher with a type std_msgs/String, you would publish a message like so.

const pub = nh.advertise('/my_topic', 'std_msgs/String');
...
const msg = new std_msgs.msg.String();
msg.data = 'Hello!';
pub.publish(msg)

You can also pass a generic object with the required fields filled in.

pub.publish({ data: 'Hello!' });

When publishing, it is possible to specify a one-time override to the throttleMs setting on the publisher. For example, if in a specific instance you want to skip the event loop, you could do the following

pub.publish(msg, -1);

Events

rosnodejs Publishers are also event emitters. If desired, you can add handlers for the following events

Complete Example

const std_msgs = rosnodejs.require('std_msgs');

rosnodejs.initNode('my_node')
.then((nh) => {
  const pub = nh.advertise('/my_topic', std_msgs.msg.String);
  const msg = new std_msgs.msg.String();
  msg.data = 'Hello, World';
  setInterval(() => {
    pub.publish(msg);
  }, 1000);
});

Subscribers

You also create subscribers on a given topic using a NodeHandle from rosnodejs.

const callback = function(msg) {
  console.log(msg.data);
}

const nh = rosnodejs.nh;
const sub = nh.subscribe('/topic', 'std_msgs/String', callback);

As with publishers, when creating subscribers you can specify the type of message to subscribe to with either a string or using the class itself.

const std_msgs = rosnodejs.require('std_msgs');

const nh = rosnodejs.nh;
const sub = nh.subscribe('/topic', std_msgs.msg.String, () => {});

Initialization

rosnodejs Subscribers also provide a few options during initialization. These are provided via an optional object after specifying the callback function.

const options = {...};
const sub = nh.subscribe('/topic', std_msgs.msg.String, () => {}, options);

The possible options are

Events

rosnodejs Subscribers are also event emitters. If desired, you can add handlers for two events


2023-10-28 13:00