Custom parser for node-serialport?

我怕爱的太早我们不能终老 提交于 2021-01-27 20:05:36

问题


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!


回答1:


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);
});



回答2:


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);
});


来源:https://stackoverflow.com/questions/44820013/custom-parser-for-node-serialport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!