Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make registering as a subscriber or publisher an option for the streaming API #148

Merged
merged 1 commit into from
Dec 15, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 23 additions & 8 deletions src/node/TopicStream.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
};
Expand Down