【问题标题】:Custom parser for node-serialport?节点串行端口的自定义解析器?
【发布时间】:2017-06-29 08:30:30
【问题描述】:

传入数据如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)

如何获取合适的数据?

谢谢!

【问题讨论】:

    标签: node.js serial-port node-serialport


    【解决方案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);
    });
    

    【讨论】:

    • 获取:TypeError [ERR_INVALID_ARG_TYPE]: The "emitter" argument must be an instance of EventEmitter. Received type string ('unpipe') 查看我自己的问题
    【解决方案2】:

    解决了!

    我自己写解析器:

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

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      相关资源
      最近更新 更多