node-serialport的自定义解析器?

时间:2017-06-29 08:30:31

标签: node.js serial-port 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)

我如何获得适当的数据?

谢谢!

2 个答案:

答案 0 :(得分:1)

解决!

我编写自己的解析器:

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

答案 1 :(得分:1)

由于版本2或3的节点串行端口,解析器必须继承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);
});