使用像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)
如何获取合适的数据?
谢谢!
发布于 2019-05-06 21:31:42
从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);
});发布于 2017-06-30 09:32:31
解决了!
我编写了自己的解析器:
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
复制相似问题