-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.js
66 lines (56 loc) · 1.89 KB
/
Parser.js
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
const { Transform } = require('stream');
function ParseChannels(str) {
const fdatLine = str.match(/FDAT: (.*)/);
const bvalLine = str.match(/BVAL: (.*)/);
const diffLine = str.match(/DIFF: (.*)/);
const touchLine = str.match(/TOUCH: (.*)/);
const valuesRegex = /(-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+) (-?\d+)/;
const fdatValues = fdatLine[0].match(valuesRegex);
const bvalValues = bvalLine[0].match(valuesRegex);
const diffValues = diffLine[0].match(valuesRegex);
const touchValues = touchLine[0].match(valuesRegex);
const channels = [];
for (let i = 0; i < fdatValues.length - 1; i += 1) {
const obj = {
fdat: fdatValues[i + 1],
bval: bvalValues[i + 1],
diff: diffValues[i + 1],
touch: touchValues[i + 1],
};
// console.log(obj);
channels.push(obj);
}
return channels;
}
const frameRegex = /RTHS:[\s\S]*?TTHS:/gm;
class ElectrodeParser extends Transform {
constructor() {
super({ objectMode: true });
this.buffer = Buffer.alloc(0);
}
static EatFrame(buf) {
const str = buf.toString();
const match = str.match(frameRegex);
if (match == null) {
// no frame detected, leave buffer unmodified
return [null, buf];
}
// strip buffer up to and including the packet
if (match.index === undefined) match.index = 0;
const strippedBuf = buf.slice(match.index + match[0].length);
const channels = ParseChannels(match[0]);
return [channels, strippedBuf];
}
_transform(chunk, encoding, cb) { // eslint-disable-line no-underscore-dangle
let data = Buffer.concat([this.buffer, chunk]);
let channels;
[channels, data] = ElectrodeParser.EatFrame(data);
while (channels != null) {
this.push(channels);
[channels, data] = ElectrodeParser.EatFrame(data);
}
this.buffer = data;
cb();
}
}
module.exports = ElectrodeParser;