htown0724082
htown0724082

Reputation: 33

node.js serialport module event types

Is it possible to declare an event type when transmitting data in the way that socket.io allows. Currently writing with serialport is as:

serialPort.write("OMG IT WORKS\r");

which is received as:

serialPort.on("data", function (data) {
    foo(data);
});

i would like to transmit a number of different events e.g. "positionUpdate", "data", "timeSync" ..etc

e.g serialPort.emit("positionUpdate", slavePosition);

Thanks

Upvotes: 3

Views: 4351

Answers (1)

Linus Thiel
Linus Thiel

Reputation: 39233

Edit: It seems that serialport accepts an optional parser, which takes an EventEmitter and a raw buffer:

var myParser = function(emitter, buffer) {
  // Inspect buffer, emit on emitter:
  if(buffer.toString("utf8", 0, 3) === "foo")
    emitter.emit("foo", buffer);
  else
    emitter.emit("data", buffer);
};

var serialport = new SerialPort("/dev/foo", { parser: myParser });

serialport.on("foo", function(data) {
  // Do stuff
});

Update: Obviously, you will need to buffer the data that comes in, massage it in some way etc, but only you know what data to expect. You could take a look at serialport's readline parser as an introduction.

Without testing it, I think this is the better way, but I leave my initial solution below.

You could do this with a proxy:

var events = require('events');
var util = require('util');

var SerialProxy = function(serialport){
  events.EventEmitter.call(this);
  var self = this;
  serialport.on("data", function(data) {
    // Inspect data to see which event to emit
    // data is a Buffer object
    var prefix = data.toString("utf8", 0, 3);
    if(prefix === "foo")
      self.emit("foo", data.toString("utf8", 3));
    else if(prefix === "bar")
      self.emit("bar", data.toString("utf8", 3));
    else
      self.emit("data", data.toString("utf8"));
  });
};

util.inherits(SerialProxy, events.EventEmitter);

Usage:

var serialProxy = new SerialProxy(serialport);

serialProxy.on("foo", function(data) {
  // ...
});

serialProxy.on("bar", function(data) {
  // ...
});

serialProxy.on("data", function(data) {
  // ...
});

Upvotes: 3

Related Questions