forked from doublerobotics/d3-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDRDoubleSDK.js
More file actions
94 lines (84 loc) · 1.78 KB
/
DRDoubleSDK.js
File metadata and controls
94 lines (84 loc) · 1.78 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 net = require("net");
const EventEmitter = require("events");
class DRDoubleSDK extends EventEmitter {
constructor() {
super();
this.path = '/tmp/doubleapi';
this.client = null;
this.clientConnected = false;
}
isConnected() {
return this.clientConnected;
}
connect() {
if (this.clientConnected) {
return;
}
this.client = net.createConnection(this.path);
this.client.on("connect", () => {
this.clientConnected = true;
this.emit("connect");
});
this.client.on('data', (data) => {
this.processBuffer(data.toString());
});
this.client.on('close', () => {
this.clientConnected = false;
this.emit("disconnect");
setTimeout( () => {
console.log("Attempting reconnect");
this.connect();
}, 1000);
});
this.client.on('error', (err) => {
console.log("error", err);
this.emit("error", err);
});
}
processBuffer(str) {
var packets = null;
var lines = str.split("\n");
for (var i = 0; i < lines.length; i++) {
try {
packets = [JSON.parse(line[i])];
} catch (err) {
// maybe it's multiple packets?
try {
str = "["+ str.replace(/\n/g, "").replace(/}{/g, "},{") +"]";
packets = JSON.parse(str);
} catch (err) {
// bail out
console.log("JSON.parse error: ", err, str);
return;
}
}
if (packets) {
this.processMessage(packets);
}
}
}
processMessage(packets) {
var arr = null;
if (Array.isArray(packets)) {
arr = packets;
} else {
arr = [packets];
}
for (var i = 0; i < arr.length; i++) {
this.emit("event", arr[i]);
}
}
sendCommand(c, d) {
var packet = {
c: c
};
if (d) {
packet.d = d;
}
this.client.write(JSON.stringify(packet) +"\n");
}
resetWatchdog() {
this.sendCommand("gui.watchdog.reset");
}
}
module.exports = DRDoubleSDK;