2
votes

With incomming data like STX(0x02)..Data..ETX(0x03)

I can process data by byte sequence parser:

var SerialPort = require('serialport');

var port = new SerialPort('/dev/tty-usbserial1', {
  parser: SerialPort.parsers.byteDelimiter([3])
});

port.on('data', function (data) {
  console.log('Data: ' + data);
});

But my actual incomming data is STX(0x02)..Data..ETX(0x03)..XX(plus 2 characters to validate data)

How can I get appropriate data?

Thanks!

2

2 Answers

1
votes

Since version 2 or 3 of node-serialport, parsers have to inherit the Stream.Tansform class. In your example, that would become a new class.

Create a file called CustomParser.js :

class CustomParser extends Transform {
  constructor() {
    super();

    this.incommingData = Buffer.alloc(0);
  }

  _transform(chunk, encoding, cb) {
    // chunk is the incoming buffer here
    this.incommingData = Buffer.concat([this.incommingData, chunk]);
    if (this.incommingData.length > 3 && this.incommingData[this.incommingData.length - 3] == 3) {
        this.push(this.incommingData); // this replaces emitter.emit("data", incomingData);
        this.incommingData = Buffer.alloc(0);
    }
    cb();
  }

  _flush(cb) {
    this.push(this.incommingData);
    this.incommingData = Buffer.alloc(0);
    cb();
  }
}

module.exports = CustomParser;

Them use your parser like this:

var SerialPort = require('serialport');
var CustomParser = require('./CustomParser ');

var port = new SerialPort('COM1');
var customParser = new CustomParser();
port.pipe(customParser);

customParser.on('data', function(data) {
  console.log(data);
});
1
votes

Solved!

I write my own parser:

var SerialPort = require('serialport');
var incommingData = new Buffer(0);
var myParser = function(emitter, buffer) {
    incommingData = Buffer.concat([incommingData, buffer]);
    if (incommingData.length > 3 && incommingData[incommingData.length - 3] == 3) {
        emitter.emit("data", incommingData);
        incommingData = new Buffer(0);
    }
};
var port = new SerialPort('COM1', {parser: myParser});

port.on('data', function(data) {
    console.log(data);
});