Пользовательский парсер для node-serialport?

С входящими данными типа STX(0x02)..Data..ETX(0x03)

Я могу обрабатывать данные 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);
});

Но мои фактические входящие данные STX(0x02)..Data..ETX(0x03)..XX(plus 2 characters to validate data)

Как я могу получить соответствующие данные?

Спасибо!


person 13thang08    schedule 29.06.2017    source источник


Ответы (2)


Начиная с версии 2 или 3 node-serialport, синтаксические анализаторы должны наследовать класс Stream.Tansform. В вашем примере это станет новым классом.

Создайте файл 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;

Они используют ваш парсер следующим образом:

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);
});
person Sam    schedule 06.05.2019
comment
Получение: TypeError [ERR_INVALID_ARG_TYPE]: The "emitter" argument must be an instance of EventEmitter. Received type string ('unpipe') см. мой собственный вопрос - person Nathan; 19.01.2021

Решено!

Я пишу свой собственный парсер:

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);
});
person 13thang08    schedule 30.06.2017