forked from nfarina/homebridge-kevo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
327 lines (270 loc) · 9.5 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
var request = require('request').defaults({jar: true/*, proxy:"http://localhost:8888", strictSSL:false*/}); // use cookies
var cheerio = require('cheerio');
var Service, Characteristic;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-kevo", "Kevo", KevoAccessory);
}
var lockOrder = 0;
var lockEventSpacing = 15000;
var lockEventsOccurring = 0;
function KevoAccessory(log, config) {
this.log = log;
this.name = config["name"];
this.username = config["username"];
this.password = config["password"];
this.lockId = config["lock_id"];
this.lockOrder = lockOrder++;
this.serialNumber = config["serialNumber"];
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, 'Homebridge')
.setCharacteristic(Characteristic.Model, 'Kevo')
.setCharacteristic(Characteristic.SerialNumber, this.serialNumber);
this.service = new Service.LockMechanism(this.name);
this.service
.getCharacteristic(Characteristic.LockCurrentState)
.on('get', this.getState.bind(this));
this.service
.getCharacteristic(Characteristic.LockTargetState)
.on('get', this.getState.bind(this));
this.service
.getCharacteristic(Characteristic.LockTargetState)
.on('set', this.setState.bind(this));
this._setup();
}
KevoAccessory.prototype.getServices = function() {
return [this.informationService, this.service];
}
KevoAccessory.prototype._setup = function() {
this._login(function(err) {
if (err) {
this.log("There was a problem logging into Kevo. Check your username and password.");
return;
}
else {
this._checkLockExists(function(err) {});
}
}.bind(this));
}
KevoAccessory.prototype._login = function(callback) {
var url = "https://www.mykevo.com/login";
var followRedirect = function(response) {
if ((response.headers.location === "https://www.mykevo.com/user/locks") || (response.headers.location === "https://mykevo.com/user/locks")) {
this.log("Already logged in.");
callback(null);
return false; // don't follow this redirect, we're done
}
return true; // ok redirect, sure
}.bind(this);
request(url, {followRedirect:followRedirect}, function (err, response, body) {
if (response.statusCode == 302) return; // we cancelled a redirect above
if (!err && response.statusCode == 200 && response.headers['content-type'].indexOf("text/html") == 0) {
var form = {
"user[username]": this.username,
"user[password]": this.password,
"commit": "Sign In"
};
// the response is an HTML login page. Suck out the hidden input fields so we can simulate a form submit
var $ = cheerio.load(body);
var action = $('form').attr('action');
$('input[type=hidden]').each(function(i, input) {
var name = $(input).attr('name');
var value = $(input).val();
form[name] = value;
});
if (!action) {
this.log("Couldn't find form action.");
this.log(body);
callback(err);
return;
}
// Submit the login page
request.post(action, {form:form}, function(err, response, body) {
// we expect a redirect response
if (!err) {
if (response.statusCode == 302) { // expect a redirect to the locks page
this.log("Login successful.");
callback(null);
} else if (response.statusCode == 200) { // check for failed login
if (body.indexOf("Username or password is incorrect") >= 0) {
err = err || new Error("Login failure - incorrect username or password");
this.log(err);
callback(err);
} else {
this.log("Login successful."); // session login was successful but redirect blocked by reCAPTCHA
callback(null);
}
} else { // unexpected response code
err = err || new Error("Unexpected status code " + response.statusCode);
this.log("Error submitting login page: %s", err);
callback(err);
}
}
else {
err = err || new Error("Bad status code " + response.statusCode);
this.log("Error submitting login page: %s", err);
callback(err);
}
}.bind(this));
}
else {
err = err || new Error("Invalid response code " + response.statusCode)
this.log("Error requesting login page: %s", err);
callback(err);
}
}.bind(this));
}
KevoAccessory.prototype._checkLockExists = function(callback) {
var url = "https://www.mykevo.com/user/locks";
request(url, function(err, response, body) {
if (!err && response.statusCode == 200) {
var $ = cheerio.load(body);
var seenLockIds = [];
// pull out all elements with "data-lock-id" defined
$('*[data-lock-id]').each(function(i, elem) {
var lockId = $(elem).attr('data-lock-id');
if (this.lockId == null && seenLockIds.indexOf(lockId) < 0) {
seenLockIds.push(lockId);
}
else if (lockId == this.lockId) {
callback(null);
return;
}
}.bind(this));
if (this.lockId == null) {
this.log("No lock ID specified, list of possible lock IDs: ");
this.log(seenLockIds);
}
else {
err = new Error("Could not locate lock with ID: %s", this.lockId);
callback(err);
}
}
else {
err = err || new Error("Invalid status code " + response.statusCode);
this.log("Error fetching lock: %s", err);
callback(err);
}
}.bind(this));
}
KevoAccessory.prototype._getLockStatus = function(callback) {
var url = "https://www.mykevo.com/user/remote_locks/command/lock.json";
var qs = {
arguments: this.lockId
};
request(url, {qs:qs}, function(err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
var state = json.bolt_state; // "Unlocked" or "Locked" or maybe "Processing" or "Confirming"
callback(null, state);
}
else {
err = err || new Error("Invalid status code " + response.statusCode);
this.log("Error getting lock status: %s", err);
callback(err);
}
}.bind(this));
}
KevoAccessory.prototype._setLockStatus = function(status, callback) {
var url;
if (status === "Locked") {
url = "https://www.mykevo.com/user/remote_locks/command/remote_lock.json";
}
else if (status === "Unlocked") {
url = "https://www.mykevo.com/user/remote_locks/command/remote_unlock.json";
}
else {
this.log("Invalid lock status %s", status);
callback(new Error("Invalid lock status"));
return;
}
var qs = {
arguments: this.lockId
};
request(url, {qs:qs}, function(err, response, body) {
if (!err && response.statusCode == 200) {
var json = JSON.parse(body);
if (json.status_code !== 201) {
callback(new Error("Unexpected status_code " + json.status_code));
return;
}
// success!
callback(null);
}
else {
err = err || new Error("Invalid status code " + response.statusCode);
this.log("Error setting lock status: %s", err);
callback(err);
}
}.bind(this));
}
KevoAccessory.prototype.getState = function(callback, state) {
if (!this.lockId) {
this.log("Lock has no ID assigned; can't get current state.");
return;
}
this.log("Getting current state...");
this._login(function(err) {
if (err) {
callback(err);
return;
}
this._getLockStatus(function(err, status) {
this.log("Lock status is %s", status);
if (status === "Locked") {
callback(null, true); // success, locked
}
else if (status === "Unlocked") {
callback(null, false); // success, unlocked
}
else {
err = new Error("Invalid lock status '"+status+"'");
this.log("Error getting state: %s", err);
callback(err);
}
}.bind(this));
}.bind(this));
}
KevoAccessory.prototype.setState = function(state, callback) {
if (!this.lockId) {
this.log("Lock has no ID assigned; can't set current state");
return;
}
var kevoStatus = (state == Characteristic.LockTargetState.SECURED) ? "Locked" : "Unlocked";
this._login(function(err) {
if (err) {
callback(err);
return;
}
var lockStatusCallback = function(err) {
if (err) {
this.log("Error setting state: %s", err);
callback(err);
lockEventsOccurring--;
return;
}
// we succeeded, so update the "current" state as well
var currentState = (state == Characteristic.LockTargetState.SECURED) ?
Characteristic.LockCurrentState.SECURED : Characteristic.LockCurrentState.UNSECURED;
this.service
.setCharacteristic(Characteristic.LockCurrentState, currentState);
// success
lockEventsOccurring--;
callback(null);
}.bind(this);
if (lockEventsOccurring > 0) {
lockEventsOccurring++;
setTimeout(function() {
this.log("Setting status to %s", kevoStatus);
this._setLockStatus(kevoStatus, lockStatusCallback);
}.bind(this), lockEventsOccurring * lockEventSpacing);
}
else {
lockEventsOccurring++;
this.log("Setting status to %s", kevoStatus);
this._setLockStatus(kevoStatus, lockStatusCallback);
}
}.bind(this));
}