This repository has been archived by the owner on May 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
647 lines (559 loc) · 21.7 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
var fetch = require("node-fetch");
var Accessory, Service, Characteristic, UUIDGen;
var skippedDevices = [];
var addedDevices = [];
module.exports = function (homebridge) {
Accessory = homebridge.platformAccessory;
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
homebridge.registerPlatform("homebridge-liftmaster2", "LiftMaster2", LiftMasterPlatform, true);
}
// This seems to be the "id" of the official LiftMaster iOS app
var APP_ID = "JVM/G9Nwih5BwKgNCjLxiFUQxQijAebyyg8QUHr7JOrP+tuPb8iHfRHKwTmDzHOu";
// Headers needed for validation
var HEADERS = {
"Content-Type": "application/json",
"User-Agent": "Chamberlain/3.73",
"BrandID": "2",
"ApiVersion": "4.1",
"Culture": "en",
"MyQApplicationID": APP_ID
};
function LiftMasterPlatform(log, config, api) {
this.log = log;
this.config = config || {"platform": "LiftMaster2"};
this.username = this.config.username;
this.password = this.config.password;
this.gateways = Array.isArray(this.config.gateways) ? this.config.gateways : [];
this.openDuration = parseInt(this.config.openDuration, 10) || 15;
this.closeDuration = parseInt(this.config.closeDuration, 10) || 25;
this.polling = this.config.polling === true;
this.longPoll = parseInt(this.config.longPoll, 10) || 300;
this.shortPoll = parseInt(this.config.shortPoll, 10) || 5;
this.shortPollDuration = parseInt(this.config.shortPollDuration, 10) || 120;
this.maxCount = this.shortPollDuration / this.shortPoll;
this.count = this.maxCount;
this.validData = false;
// Gateways convenience
if (this.config.gateway) this.gateways.push(this.config.gateway);
if (this.config.hub) this.gateways.push(this.config.hub);
if (this.config.hubs && Array.isArray(this.config.hubs)) this.gateways = this.gateways.concat(this.config.hubs);
this.accessories = {};
if (api) {
this.api = api;
this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this));
}
// Definition Mapping
this.doorState = ["open.", "closed.", "opening.", "closing.", "stopped."];
}
// Method to restore accessories from cache
LiftMasterPlatform.prototype.configureAccessory = function (accessory) {
this.setService(accessory);
this.accessories[accessory.context.deviceID] = accessory;
}
// Method to setup accesories from config.json
LiftMasterPlatform.prototype.didFinishLaunching = function () {
if (this.username && this.password) {
// Add or update accessory in HomeKit
this.addAccessory();
// Start polling
if (this.polling) this.statePolling(0);
} else {
this.log("Please setup MyQ login information!");
for (var deviceID in this.accessories) {
var accessory = this.accessories[deviceID];
this.removeAccessory(accessory);
}
}
}
// Method to add or update HomeKit accessories
LiftMasterPlatform.prototype.addAccessory = function () {
var self = this;
this.login(function (error){
if (!error) {
for (var deviceID in self.accessories) {
var accessory = self.accessories[deviceID];
if (!accessory.reachable) {
// Remove extra accessories in cache
self.removeAccessory(accessory);
} else {
// Update inital state
self.log("Initializing platform accessory '" + accessory.context.name + " (ID: " + deviceID + ")'...");
self.updateDoorStates(accessory);
}
}
}
});
}
// Method to remove accessories from HomeKit
LiftMasterPlatform.prototype.removeAccessory = function (accessory) {
if (accessory) {
var deviceID = accessory.context.deviceID;
this.log(accessory.context.name + " is removed from HomeBridge.");
this.api.unregisterPlatformAccessories("homebridge-liftmaster2", "LiftMaster2", [accessory]);
delete this.accessories[deviceID];
}
}
// Method to setup listeners for different events
LiftMasterPlatform.prototype.setService = function (accessory) {
accessory.getService(Service.GarageDoorOpener)
.getCharacteristic(Characteristic.CurrentDoorState)
.on('get', this.getCurrentState.bind(this, accessory.context));
accessory.getService(Service.GarageDoorOpener)
.getCharacteristic(Characteristic.TargetDoorState)
.on('get', this.getTargetState.bind(this, accessory.context))
.on('set', this.setTargetState.bind(this, accessory.context));
accessory.on('identify', this.identify.bind(this, accessory));
}
// Method to setup HomeKit accessory information
LiftMasterPlatform.prototype.setAccessoryInfo = function (accessory, model, serial) {
accessory.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, model)
.setCharacteristic(Characteristic.SerialNumber, serial);
}
// Method to update door state in HomeKit
LiftMasterPlatform.prototype.updateDoorStates = function (accessory) {
accessory.getService(Service.GarageDoorOpener)
.setCharacteristic(Characteristic.CurrentDoorState, accessory.context.currentState);
accessory.getService(Service.GarageDoorOpener)
.getCharacteristic(Characteristic.TargetDoorState)
.getValue();
}
// Method to retrieve door state from the server
LiftMasterPlatform.prototype.updateState = function (callback) {
if (this.validData && this.polling) {
// Refresh data directly from sever if current data is valid
this.getDevice(callback);
} else {
// Re-login if current data is not valid
this.login(callback);
}
}
// Method for state periodic update
LiftMasterPlatform.prototype.statePolling = function (delay) {
var self = this;
var refresh = this.longPoll + delay;
// Clear polling
clearTimeout(this.tout);
// Determine polling interval
if (this.count < this.maxCount) {
this.count++;
refresh = this.shortPoll + delay;
}
// Setup periodic update with polling interval
this.tout = setTimeout(function () {
self.updateState(function (error) {
if (!error) {
// Update states for all HomeKit accessories
for (var deviceID in self.accessories) {
var accessory = self.accessories[deviceID];
self.updateDoorStates(accessory);
}
} else {
// Re-login after short polling interval if error occurs
self.count = self.maxCount - 1;
}
// Setup next polling
self.statePolling(0);
});
}, refresh * 1000);
}
// Login to MyQ server
LiftMasterPlatform.prototype.login = function (callback) {
var self = this;
// Body stream for validation
var body = {
username: this.username,
password: this.password
};
// login to liftmaster
fetch("https://myqexternal.myqdevice.com/api/v4/User/Validate", {
method: "POST",
headers: HEADERS,
body: JSON.stringify(body)
}).then(function (res) {
return res.json();
}).then(function (data) {
// Check for MyQ Error Codes
if (data.ReturnCode === "0") {
self.securityToken = data.SecurityToken;
self.manufacturer = "Chamberlain";
self.getDevice(callback);
} else {
self.log(data.ErrorMessage);
callback(data.ErrorMessage);
}
});
}
// Find your garage door ID
LiftMasterPlatform.prototype.getDevice = function (callback) {
var self = this;
// Reset validData hint until we retrived data from the server
this.validData = false;
// Querystring params
var query = {
filterOn: "true"
};
// Adding security token to headers
var getHeaders = JSON.parse(JSON.stringify(HEADERS));
getHeaders.SecurityToken = this.securityToken;
// Request details of all your devices
fetch("https://myqexternal.myqdevice.com/api/v4/UserDeviceDetails/Get", {
method: "GET",
headers: getHeaders,
query: query
}).then(function (res) {
return res.json();
}).then(function (data) {
if (data && data.ReturnCode === "0" && data.Devices) {
var devices = data.Devices;
// Look through the array of devices for all the gateways
var allowedGateways = [];
var gatewaysKeyed = {};
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
var deviceType = device.MyQDeviceTypeId;
var deviceDesc = "Unknown";
// Search for specific device type
if (deviceType != 1) continue;
for (var j = 0; j < device.Attributes.length; j ++) {
var thisAttributeSet = device.Attributes[j];
// Search for device name
if (thisAttributeSet.AttributeDisplayName === "desc") {
deviceDesc = thisAttributeSet.Value;
}
}
// Is this gateway one of the specified gateways in the config
gatewaysKeyed[device.MyQDeviceId] = deviceDesc;
if (self.gateways.indexOf(deviceDesc) > -1 || self.gateways.indexOf(device.MyQDeviceId) > -1) allowedGateways.push(device.MyQDeviceId);
}
// Look through the array of devices for all the openers
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
var deviceType = device.MyQDeviceTypeName;
// Search for specific device type
if (deviceType === "Garage Door Opener WGDO" || deviceType === "GarageDoorOpener" || deviceType === "VGDO" || deviceType === "Gate") {
var thisDeviceID = device.MyQDeviceId.toString();
var thisSerial = device.SerialNumber.toString();
var thisModel = deviceType.toString();
var thisDoorName = "Unknown";
var thisDoorState = "2";
var thisDoorMonitor = "0";
for (var j = 0; j < device.Attributes.length; j ++) {
var thisAttributeSet = device.Attributes[j];
// Search for device name
if (thisAttributeSet.AttributeDisplayName === "desc") {
thisDoorName = thisAttributeSet.Value;
}
// Search for device state
if (thisAttributeSet.AttributeDisplayName === "doorstate") {
thisDoorState = thisAttributeSet.Value;
}
// Search for device monitor mode
if (thisAttributeSet.AttributeDisplayName === "myqmonitormode") {
thisDoorMonitor = thisAttributeSet.Value;
}
}
// Does this device fall under the specified gateways
if (self.gateways.length > 0 && allowedGateways.indexOf(device.ParentMyQDeviceId) == -1) {
if (skippedDevices.indexOf(thisDeviceID) == -1) {
skippedDevices.push(thisDeviceID);
self.log('Skipping Device: "'+thisDoorName+'" - Device ID: '+thisDeviceID+' (Gateway: "'+gatewaysKeyed[device.ParentMyQDeviceId]+"\"",'-', "Gateway ID:",device.ParentMyQDeviceId+")");
}
continue;
}
if (thisDoorMonitor === "0") {
// Should this accessory be registered
var registerAccessory = false;
// Retrieve accessory from cache
var accessory = self.accessories[thisDeviceID];
// Initialization for new accessory
if (accessory === undefined) {
// Ensure accessory is registered
registerAccessory = true;
// Setup accessory as GARAGE_DOOR_OPENER (4) category.
var uuid = UUIDGen.generate(thisDeviceID);
accessory = new Accessory("MyQ " + thisDoorName, uuid, 4);
// Setup HomeKit security system service
accessory.addService(Service.GarageDoorOpener, thisDoorName);
// New accessory is always reachable
accessory.reachable = true;
// Setup HomeKit accessory information
self.setAccessoryInfo(accessory, thisModel, thisSerial);
// Setup listeners for different security system events
self.setService(accessory);
// Store accessory in cache
self.accessories[thisDeviceID] = accessory;
}
if (addedDevices.indexOf(thisDeviceID) == -1) {
addedDevices.push(thisDeviceID);
if (device.ParentMyQDeviceId) {
self.log('Adding Device: "'+thisDoorName+'" - Device ID: '+thisDeviceID+' (Gateway: "'+gatewaysKeyed[device.ParentMyQDeviceId]+"\"",'-', "Gateway ID:",device.ParentMyQDeviceId+")");
} else {
self.log('Adding Device: "'+thisDoorName+'"');
}
}
// Accessory is reachable after it's found in the server
accessory.updateReachability(true);
// Store and initialize variables into context
var cache = accessory.context;
cache.name = thisDoorName;
cache.deviceID = thisDeviceID;
if (cache.currentState === undefined) cache.currentState = Characteristic.CurrentDoorState.CLOSED;
// Determine the current door state
var newState;
if (thisDoorState === "1") {
newState = Characteristic.CurrentDoorState.OPEN;
} else if (thisDoorState === "2") {
newState = Characteristic.CurrentDoorState.CLOSED;
} else if (thisDoorState === "3") {
newState = Characteristic.CurrentDoorState.STOPPED;
} else if (thisDoorState === "4") {
newState = Characteristic.CurrentDoorState.OPENING;
} else if (thisDoorState === "5") {
newState = Characteristic.CurrentDoorState.CLOSING;
} else {
// Not sure about this...
accessory.updateReachability(false);
}
// Detect for state changes
if (newState !== cache.currentState) {
self.count = 0;
cache.currentState = newState;
}
// Set validData hint after we found an opener
self.validData = true;
// Register accessory
if (registerAccessory) {
try {
self.api.registerPlatformAccessories("homebridge-liftmaster2", "LiftMaster2", [accessory]);
} catch (e) {
self.log('Unable to Add Device: "'+thisDoorName+'"');
self.removeAccessory(accessory);
}
}
}
}
}
// Did we have valid data?
if (self.validData) {
// Set short polling interval when state changes
if (self.polling) self.statePolling(0);
callback();
} else {
var parseErr = "Error: Couldn't find a MyQ door device."
self.log(parseErr);
callback(parseErr);
}
} else {
self.log("Error getting MyQ devices: " + data.ErrorMessage);
callback(data.ErrorMessage);
}
});
}
// Send opener target state to the server
LiftMasterPlatform.prototype.setState = function (thisOpener, state, callback) {
var self = this;
var thisAccessory = this.accessories[thisOpener.deviceID];
var liftmasterState = state === 1 ? "0" : "1";
var updateDelay = state === 1 ? this.closeDuration : this.openDuration;
// Adding security token to headers
var putHeaders = JSON.parse(JSON.stringify(HEADERS));
putHeaders.SecurityToken = this.securityToken;
// PUT request body
var body = {
AttributeName: "desireddoorstate",
AttributeValue: liftmasterState,
MyQDeviceId: thisOpener.deviceID
};
// Send the state request to liftmaster
fetch("https://myqexternal.myqdevice.com/api/v4/DeviceAttribute/PutDeviceAttribute", {
method: "PUT",
headers: putHeaders,
body: JSON.stringify(body)
}).then(function(res) {
return res.json();
}).then(function (data) {
if (data.ReturnCode === "0") {
self.log(thisOpener.name + " is set to " + self.doorState[state]);
if (self.polling) {
// Set short polling interval
self.count = 0;
self.statePolling(updateDelay - self.shortPoll);
} else {
// Update door state after updateDelay
setTimeout(function () {
self.updateState(function (error) {
if (!error) self.updateDoorStates(thisAccessory);
});
}, updateDelay * 1000);
}
callback();
} else {
self.log("Error setting " + thisOpener.name + " state: " + JSON.stringify(data));
callback(data.ErrorMessage);
}
});
}
// Method to set target door state
LiftMasterPlatform.prototype.setTargetState = function (thisOpener, state, callback) {
var self = this;
// Always re-login for setting the state
this.login(function (loginError) {
if (!loginError) {
self.setState(thisOpener, state, callback);
} else {
callback(loginError);
}
});
}
// Method to get target door state
LiftMasterPlatform.prototype.getTargetState = function (thisOpener, callback) {
// Get target state directly from cache
callback(null, thisOpener.currentState % 2);
}
// Method to get current door state
LiftMasterPlatform.prototype.getCurrentState = function (thisOpener, callback) {
var self = this;
// Retrieve latest state from server
this.updateState(function (error) {
if (!error) {
self.log(thisOpener.name + " is " + self.doorState[thisOpener.currentState]);
callback(null, thisOpener.currentState);
} else {
callback(error);
}
});
}
// Method to handle identify request
LiftMasterPlatform.prototype.identify = function (thisOpener, paired, callback) {
this.log(thisOpener.name + " identify requested!");
callback();
}
// Method to handle plugin configuration in HomeKit app
LiftMasterPlatform.prototype.configurationRequestHandler = function (context, request, callback) {
if (request && request.type === "Terminate") {
return;
}
// Instruction
if (!context.step) {
var instructionResp = {
"type": "Interface",
"interface": "instruction",
"title": "Before You Start...",
"detail": "Please make sure homebridge is running with elevated privileges.",
"showNextButton": true
}
context.step = 1;
callback(instructionResp);
} else {
switch (context.step) {
// Operation choices
case 1:
var respDict = {
"type": "Interface",
"interface": "input",
"title": "Configuration",
"items": [{
"id": "username",
"title": "Login Username (Required)",
"placeholder": this.username ? "Leave blank if unchanged" : "email"
}, {
"id": "password",
"title": "Login Password (Required)",
"placeholder": this.password ? "Leave blank if unchanged" : "password",
"secure": true
}, {
"id": "openDuration",
"title": "Time to Open Garage Door Completely",
"placeholder": this.openDuration.toString(),
}, {
"id": "closeDuration",
"title": "Time to Close Garage Door Completely",
"placeholder": this.closeDuration.toString(),
}, {
"id": "polling",
"title": "Enable Polling (true/false)",
"placeholder": this.polling.toString(),
}, {
"id": "longPoll",
"title": "Long Polling Interval",
"placeholder": this.longPoll.toString(),
}, {
"id": "shortPoll",
"title": "Short Polling Interval",
"placeholder": this.shortPoll.toString(),
}, {
"id": "shortPollDuration",
"title": "Short Polling Duration",
"placeholder": this.shortPollDuration.toString(),
}]
}
context.step = 2;
callback(respDict);
break;
case 2:
var userInputs = request.response.inputs;
// Setup info for adding or updating accessory
this.username = userInputs.username || this.username;
this.password = userInputs.password || this.password;
this.openDuration = parseInt(userInputs.openDuration, 10) || this.openDuration;
this.closeDuration = parseInt(userInputs.closeDuration, 10) || this.closeDuration;
if (userInputs.polling.toUpperCase() === "TRUE") {
this.polling = true;
} else if (userInputs.polling.toUpperCase() === "FALSE") {
this.polling = false;
}
this.longPoll = parseInt(userInputs.longPoll, 10) || this.longPoll;
this.shortPoll = parseInt(userInputs.shortPoll, 10) || this.shortPoll;
this.shortPollDuration = parseInt(userInputs.shortPollDuration, 10) || this.shortPollDuration;
// Check for required info
if (this.username && this.password) {
// Add or update accessory in HomeKit
this.addAccessory();
// Reset polling
if (this.polling) {
this.maxCount = this.shortPollDuration / this.shortPoll;
this.count = this.maxCount;
this.statePolling(0);
}
var respDict = {
"type": "Interface",
"interface": "instruction",
"title": "Success",
"detail": "The configuration is now updated.",
"showNextButton": true
};
context.step = 3;
} else {
// Error if required info is missing
var respDict = {
"type": "Interface",
"interface": "instruction",
"title": "Error",
"detail": "Some required information is missing.",
"showNextButton": true
};
context.step = 1;
}
callback(respDict);
break;
case 3:
// Update config.json accordingly
delete context.step;
var newConfig = this.config;
newConfig.username = this.username;
newConfig.password = this.password;
newConfig.openDuration = this.openDuration;
newConfig.closeDuration = this.closeDuration;
newConfig.polling = this.polling;
newConfig.longPoll = this.longPoll;
newConfig.shortPoll = this.shortPoll;
newConfig.shortPollDuration = this.shortPollDuration;
callback(null, "platform", true, newConfig);
break;
}
}
}