本文介绍了用于节点串行端口的自定义解析器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
输入数据如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);
});
但我实际传入的数据是STX(0x02)..Data..ETX(0x03)..XX(加2个字符来验证数据)
如何获取合适的数据?
谢谢!
推荐答案
从 node-serialport 的版本 2 或 3 开始,解析器必须继承 Stream.Tansform 类.在您的示例中,这将成为一个新类.
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.
创建一个名为 CustomParser.js 的文件:
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);
});
这篇关于用于节点串行端口的自定义解析器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!