forked from rnilssoncx/homebridge-pico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
caseta.js
executable file
·89 lines (78 loc) · 2.53 KB
/
caseta.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'use strict';
const net = require('net');
const lutronLogin = {
username: "lutron",
password: "integration",
}
class CasetaPro {
constructor(log, host, port, eventHandler, quiet) {
this._log = log;
this.log(`Caseta Pro Initializing`);
this.host = host;
this.port = port;
this.loggedIn = false;
this.socket = new net.Socket();
this.quiet = quiet;
this.eventHandler = eventHandler;
this.socket.on('connect', () => {
this.log(`Caseta Pro Connected`);
});
this.socket.on('data', this.receiveData.bind(this));
this.socket.on('end', () => {
});
this.socket.on('error', (error) => {
this.log(error);
});
this.socket.destroy();
this.manageSocket();
this.timer = setInterval(this.manageSocket.bind(this), 60000);
}
receiveData(data) {
// TODO: do we need to worry about partial strings?
const lines = data.toString().split("\r\n").filter(l => l != "");
for (let line of lines) {
if (!this.quiet) {
this.log(`Bus Data: ${line}`);
}
if (this.loggedIn) {
const args = line.split(",");
if (args[0] === "~DEVICE") {
this.eventHandler({
"host": this.host,
"device": args[1],
"button": args[2],
"action": args[3]
});
}
} else {
if (/^login:\s*/.test(line)) {
this.socket.write(`${lutronLogin.username}\r\n`);
} else if (/^password:\s*/.test(line)) {
this.socket.write(`${lutronLogin.password}\r\n`);
} else if (/^GNET>\s*/.test(line)) {
this.loggedIn = true;
this.log('Logged in');
} else {
}
}
}
}
manageSocket() {
if (this.socket.destroyed) {
this.loggedIn = false;
this.log('Attempting connection');
this.socket.connect(this.port, this.host);
} else if (!this.socket.connecting) {
if (!this.quiet) {
this.log(`Writing Keep Alive`)
}
this.socket.write('\r\n');
} else {
this.log('Waiting for connection');
}
}
log(message) {
this._log(`[${this.host}] ${message}`);
}
}
module.exports = CasetaPro;