2

随着传入的数据,如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)

如何获得合适的数据?

谢谢!

4

2 回答 2

1

从 node-serialport 版本 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);
});
于 2019-05-06T13:31:42.317 回答
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);
});
于 2017-06-30T01:32:30.937 回答