forked from homebridge/HAP-NodeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTLV-Handler.js
55 lines (42 loc) · 1.23 KB
/
TLV-Handler.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
exports.encodeTLV = function (type,data) {
var encodedTLVBuffer = Buffer(0);
if (data.length <= 255) {
encodedTLVBuffer = Buffer.concat([Buffer([type,data.length]),data]);
} else {
var leftLength = data.length;
var tempBuffer = Buffer(0);
var currentStart = 0;
for (; leftLength > 0;) {
if (leftLength >= 255) {
tempBuffer = Buffer.concat([tempBuffer,Buffer([type,0xFF]),data.slice(currentStart, currentStart + 255)]);
leftLength -= 255;
currentStart = currentStart + 255;
} else {
tempBuffer = Buffer.concat([tempBuffer,Buffer([type,leftLength]),data.slice(currentStart, currentStart + leftLength)]);
leftLength -= leftLength;
}
};
encodedTLVBuffer = tempBuffer;
}
return encodedTLVBuffer;
}
exports.decodeTLV = function (data) {
var objects = {};
var leftLength = data.length;
var currentIndex = 0;
for (; leftLength > 0;) {
var type = data[currentIndex]
var length = data[currentIndex+1]
currentIndex += 2;
leftLength -= 2;
var newData = data.slice(currentIndex, currentIndex+length);
if (objects[type]) {
objects[type] = Buffer.concat([objects[type],newData]);
} else {
objects[type] = newData;
}
currentIndex += length;
leftLength -= length;
};
return objects;
}