From 14a53099870207e785fef5088aa66da19bb64df3 Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Mon, 15 Dec 2014 10:09:10 -0500 Subject: [PATCH] Make registering as a subscriber or publisher an option for the streaming API --- src/node/TopicStream.js | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/src/node/TopicStream.js b/src/node/TopicStream.js index 759f108ed..f492e72e7 100644 --- a/src/node/TopicStream.js +++ b/src/node/TopicStream.js @@ -5,10 +5,19 @@ var DuplexStream = require('stream').Duplex; * Publish a connected ROS topic to a duplex * stream. This stream can be piped to, which will * publish to the topic + * + * @options + * * subscribe: whether to subscribe to the topic and start emitting + * Data + * * publish: whether to register the stream as a publisher to the topic + * * transform: a function to change the data to be published + * or filter it if false is returned */ -Topic.prototype.toStream = function(transform) { +Topic.prototype.toStream = function(options) { + options = options || {subscribe: true, publish: true}; + var topic = this; - var hasTransform = typeof transform === 'function'; + var hasTransform = typeof options.transform === 'function'; var stream = new DuplexStream({ objectMode: true @@ -18,18 +27,24 @@ Topic.prototype.toStream = function(transform) { // Publish to the topic if someone pipes to stream stream._write = function(chunk, encoding, callback) { if (hasTransform) { - chunk = transform(chunk); + chunk = options.transform(chunk); } - if (chunk) { + if (chunk === false) { topic.publish(chunk); } callback(); }; - this.subscribe(function(message) { - stream.push(message); - }); - this.on('unsubscribe', stream.push.bind(stream, null)); + if (options.subscribe) { + this.subscribe(function(message) { + stream.push(message); + }); + this.on('unsubscribe', stream.push.bind(stream, null)); + } + + if (options.publish) { + this.advertise(); + } return stream; };