Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 444
htown0724082 Avatar asked Jul 22 '26 07:07

htown0724082


1 Answers

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) {
  // ...
});
like image 80
Linus Thiel Avatar answered Jul 24 '26 22:07

Linus Thiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!