-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
60 lines (53 loc) · 1.64 KB
/
index.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
const removeSpaces = (str) => str.replace(/\s{1,}/g, '');
const toHex = (num) => num.toString(16).toUpperCase();
const leftPad = (str, len = '2', char = '0') => {
while (str.length < len) {
str = char + str;
}
return str;
};
const extractMainData = (input) => {
let mainData = '';
try {
// Remove spaces
let output = removeSpaces(input);
// Uppercase
output = output.toUpperCase();
// Extract data between prefix (AAB1) and suffix (55)
const re = /(^AAB1)([0-9A-F]*)(55$)/;
const result = re.exec(output);
if (result && result.length === 4) {
mainData = result[2];
}
} catch (err) {
} finally {
return mainData;
}
};
const convertB1toB0 = (input, repeatVal = 8) => {
const inputStr = extractMainData(input);
if (inputStr === '') {
throw new Error('invalid input');
}
const bucketLength = 4;
const hexNbrOfBuckets = inputStr.substr(0, 2);
const intNbrOfBuckets = parseInt(hexNbrOfBuckets, 16);
const bucketsArr = [];
for (let i = 0; i < intNbrOfBuckets; i++) {
const bucket = inputStr.substr(2 + (i * bucketLength), bucketLength);
bucketsArr.push(bucket);
}
const data = inputStr.substring(2 + (intNbrOfBuckets * bucketLength), inputStr.length);
const hexLength = leftPad(toHex((2 + 2 + (intNbrOfBuckets * bucketLength) + data.length)/2));
const hexRepVal = leftPad(toHex(repeatVal));
// 0xAA: sync start
// 0xB0: command
// 0x??: length
// 0x??: number of buckets
// 0x??: repeats
// buckets
// data
// 0x55: sync end
return `AA B0 ${hexLength} ${hexNbrOfBuckets} ${hexRepVal} ${bucketsArr.join(' ')} ${data} 55`;
};
module.exports = convertB1toB0;