-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-mode-parser.js
More file actions
94 lines (70 loc) · 2.67 KB
/
Copy pathapi-mode-parser.js
File metadata and controls
94 lines (70 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const Transform = require('stream').Transform
const constants = require('./components/constants.js');
const frameHandler = require('./components/frame-handler.js')
class ApiModeParser extends Transform {
constructor(options = {}) {
super(options)
// if (options.delimiter === undefined) {
// throw new TypeError('"delimiter" is not a bufferable object')
// }
// if (options.delimiter.length === 0) {
// throw new TypeError('"delimiter" has a 0 or undefined length')
// }
// this.includeDelimiter = options.includeDelimiter !== undefined ? options.includeDelimiter : false
// this.delimiter = Buffer.from(options.delimiter)
this.buffer = Buffer.alloc(0)
this.processingMessage = false;
}
_transform(chunk, encoding, cb) {
let data = Buffer.concat([this.buffer, chunk])
let position = 0;
if (!this.processingMessage) {
while (position < data.length-1 && !(this.processingMessage = (data[position] === 0x7E))) {
position++;
}
data = data.slice(position);
position = 0;
}
if (this.processingMessage) {
while(true) {
if (position == null)
break;
data = data.slice(position);
position = 0;
if (data[position] !== 0x7E) {
this.processingMessage = false;
break;
}
//se acabar as mensagens ou se chegar uma mensagem muito pequena (corrompida)
if (data.length < 5)
break;
const len = (data[1]<<8) + data[2];
if (data.length < len + 3)
break;
// if ((data.length) <= 18) {
// break;
// }
const frame = frameHandler.parseFrame(data);
if (frame.secure) {
this.push(data);
} else {
//deu erro no checksum, procure o byte de inicio novamente
if (frame.position == null) {
frame.position = 1
}
this.processingMessage = false;
}
//readiciona os 3 bytes q foram dados offset no começo para cria o newData
position = frame.position;
}
}
this.buffer = data;
cb();
}
_flush(cb) {
this.push(this.buffer)
this.buffer = Buffer.alloc(0)
cb()
}
}
module.exports = ApiModeParser