-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
692 lines (594 loc) · 22.1 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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
var Service, Characteristic, Accessory, UUIDGen;
var GogogateAPI = require('./gogogateAPI.js').GogogateAPI;
const GogogateTools = require('./gogogateTools.js');
String.prototype.isEmpty = function () {
return this.length === 0 || !this.trim();
};
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
Accessory = homebridge.platformAccessory;
UUIDGen = homebridge.hap.uuid;
HomebridgeAPI = homebridge;
homebridge.registerPlatform('homebridge-gogogate2', 'GogoGate2', Gogogate2Platform, true);
};
function Gogogate2Platform(log, config, api) {
if (!config) {
log('No configuration found for homebridge-gogogate2');
return;
}
this.log = log;
this.gogogateIP = config['gogogateIP'];
this.name = config['name'];
this.devMode = config['DEVMODE'];
this.username = config['username'];
this.password = config['password'];
this.refreshTimer = GogogateTools.checkTimer(config['refreshTimer']);
this.refreshTimerDuringOperation = GogogateTools.checkParemeter(
config['refreshTimerDuringOperation'],
2,
15,
10
);
this.maxWaitTimeForOperation = GogogateTools.checkParemeter(
config['maxWaitTimeForOperation'],
30,
90,
45
);
this.cleanCache = config['cleanCache'];
this.foundAccessories = [];
this._confirmedAccessories = [];
this._confirmedServices = [];
this.gogogateAPI = new GogogateAPI(log, this);
if (api) {
// Save the API object as plugin needs to register new accessory via this object
this.api = api;
// Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories.
// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
// Or start discover new accessories.
this.api
.on(
'shutdown',
function () {
this.end();
}.bind(this)
)
.on(
'didFinishLaunching',
function () {
this.log('DidFinishLaunching');
if (this.cleanCache) {
this.log('WARNING - Removing Accessories');
this.api.unregisterPlatformAccessories(
'homebridge-gogogate2',
'GogoGate2',
this.foundAccessories
);
this.foundAccessories = [];
}
this.discoverDoors();
}.bind(this)
);
}
}
Gogogate2Platform.prototype = {
configureAccessory: function (accessory) {
this.log.debug(
accessory.displayName,
'Got cached Accessory ' + accessory.UUID + ' for ' + this.name
);
this.foundAccessories.push(accessory);
},
end() {
this.log('INFO - shutdown');
if (this.timerID) {
clearInterval(this.timerID);
this.timerID = undefined;
}
this.gogogateAPI.logout(() => {});
},
//Cleaning methods
cleanPlatform: function () {
this.cleanAccessories();
this.cleanServices();
},
cleanAccessories: function () {
//cleaning accessories
let accstoRemove = [];
for (let acc of this.foundAccessories) {
if (!this._confirmedAccessories.find((x) => x.UUID == acc.UUID)) {
accstoRemove.push(acc);
this.log('WARNING - Accessory will be Removed ' + acc.UUID + '/' + acc.displayName);
}
}
if (accstoRemove.length > 0)
this.api.unregisterPlatformAccessories('homebridge-gogogate2', 'GogoGate2', accstoRemove);
},
cleanServices: function () {
//cleaning services
for (let acc of this.foundAccessories) {
let servicestoRemove = [];
for (let serv of acc.services) {
if (
serv.subtype !== undefined &&
!this._confirmedServices.find((x) => x.UUID == serv.UUID && x.subtype == serv.subtype)
) {
servicestoRemove.push(serv);
}
}
for (let servToDel of servicestoRemove) {
this.log(
'WARNING - Service Removed' +
servToDel.UUID +
'/' +
servToDel.subtype +
'/' +
servToDel.displayName
);
acc.removeService(servToDel);
}
}
},
discoverDoors: function () {
this.gogogateAPI.on('doorsRetrieveError', () => {
if (this.timerID == undefined) {
this.log('ERROR - discoverDoors - will retry in 1 minute');
setTimeout(() => {
this.gogogateAPI.getDoors();
}, 60000);
}
});
this.gogogateAPI.on('doorsRetrieved', () => {
this.log.debug('INFO - doorsRetrieved event');
this.loadDoors();
});
this.gogogateAPI.on('doorRefreshError', (gateId) => {
this.log.debug('INFO - doorRefreshError event -' + gateId);
if (this.timerID == undefined) {
this.log('ERROR - doorRefreshError - will retry in 1 minute');
setTimeout(() => {
this.gogogateAPI.refreshDoor(gateId);
}, 60000);
}
});
this.gogogateAPI.on('doorRefreshed', (gateId, result) => {
this.log.debug('INFO - doorRefreshed event -' + gateId + '-' + result);
this.handleRefreshDoor(result, gateId);
});
this.gogogateAPI.on('sensorRefreshError', (gateId) => {
this.log.debug('INFO - sensorRefreshError event -' + gateId);
if (this.timerID == undefined) {
this.log('ERROR - sensorRefreshError - will retry in 1 minute');
setTimeout(() => {
this.gogogateAPI.refreshSensor(gateId);
}, 60000);
}
});
this.gogogateAPI.on('sensorRefreshed', (gateId, result) => {
this.log.debug('INFO - sensorRefreshed event -' + gateId + '-' + result);
this.handleRefreshSensor(result, gateId);
});
this.gogogateAPI.getDoors();
},
loadDoors() {
let doors = this.gogogateAPI.discoverdDoors;
let sensors = this.gogogateAPI.discoverdSensors;
if (doors && doors instanceof Array && doors.length > 0) {
for (let i = 0, len = doors.length; i < len; i++) {
let doorName = doors[i];
if (doorName && !doorName.isEmpty()) {
if (this.devMode) {
doorName = 'DEV' + doorName;
}
this.log('INFO - Discovered door : ' + doorName);
let uuid = UUIDGen.generate(doorName);
let myGogogateDoorAccessory = this.foundAccessories.find((x) => x.UUID == uuid);
if (!myGogogateDoorAccessory) {
myGogogateDoorAccessory = new Accessory(doorName, uuid);
myGogogateDoorAccessory.name = doorName;
myGogogateDoorAccessory.model = 'Gogogate2';
myGogogateDoorAccessory.manufacturer = 'Gogogate';
myGogogateDoorAccessory.serialNumber = doorName + '-' + this.gogogateIP;
myGogogateDoorAccessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, myGogogateDoorAccessory.manufacturer)
.setCharacteristic(Characteristic.Model, myGogogateDoorAccessory.model)
.setCharacteristic(Characteristic.SerialNumber, myGogogateDoorAccessory.serialNumber);
this.api.registerPlatformAccessories('homebridge-gogogate2', 'GogoGate2', [
myGogogateDoorAccessory,
]);
this.foundAccessories.push(myGogogateDoorAccessory);
}
myGogogateDoorAccessory.gateId = i + 1;
myGogogateDoorAccessory.name = doorName;
let HKService = myGogogateDoorAccessory.getServiceByUUIDAndSubType(
doorName,
'GarageDoorOpener' + doorName
);
if (!HKService) {
this.log('INFO - Creating Main Service ' + doorName);
HKService = new Service.GarageDoorOpener(doorName, 'GarageDoorOpener' + doorName);
HKService.subtype = 'GarageDoorOpener' + doorName;
myGogogateDoorAccessory.addService(HKService);
}
HKService.gateId = i + 1;
this.bindCurrentDoorStateCharacteristic(HKService);
this.bindTargetDoorStateCharacteristic(HKService);
this.bindObstructionDetectedCharacteristic(HKService);
this._confirmedAccessories.push(myGogogateDoorAccessory);
this._confirmedServices.push(HKService);
if (sensors[i] && !sensors[i].isEmpty()) {
this.log('INFO - Discovered sensor : ' + sensors[i]);
let HKService1 = myGogogateDoorAccessory.getServiceByUUIDAndSubType(
doorName,
'BatteryService' + sensors[i]
);
if (!HKService1) {
this.log(
'INFO - Creating Service ' + doorName + '/' + 'BatteryService' + sensors[i]
);
HKService1 = new Service.BatteryService(doorName, 'BatteryService' + sensors[i]);
HKService1.subtype = 'BatteryService' + sensors[i];
myGogogateDoorAccessory.addService(HKService1);
}
HKService1.gateId = i + 1;
this.bindBatteryLevelCharacteristic(HKService1);
this.bindChargingStateCharacteristic(HKService1);
this.bindStatusLowBatteryCharacteristic(HKService1);
let HKService2 = myGogogateDoorAccessory.getServiceByUUIDAndSubType(
doorName,
'Temp' + sensors[i]
);
if (!HKService2) {
this.log('INFO - Creating Service ' + doorName + '/' + 'Temp' + sensors[i]);
HKService2 = new Service.TemperatureSensor(doorName, 'Temp' + sensors[i]);
HKService2.subtype = 'Temp' + sensors[i];
myGogogateDoorAccessory.addService(HKService2);
}
HKService2.gateId = i + 1;
this.bindCurrentTemperatureLevelCharacteristic(HKService2);
this._confirmedServices.push(HKService1);
this._confirmedServices.push(HKService2);
}
}
}
this.cleanPlatform();
this.refreshAllDoors();
//timer for background refresh
this.refreshBackground();
} else {
this.log('ERROR - discoverDoors - no door found, will retry in 1 minute - ' + doors);
setTimeout(() => {
this.gogogateAPI.getDoors();
}, 60000);
}
},
endOperation(service, statusbody) {
if (statusbody != 'OK' && statusbody != 'FAIL') return true;
//timeout
if (
service.TargetDoorState !== undefined &&
service.TargetDoorStateOperationStart !== undefined
) {
let elapsedTime = Date.now() - service.TargetDoorStateOperationStart;
this.log.debug(
'INFO - CheckTimeout / statusbody : ' + statusbody + ' - elapsedTime : ' + elapsedTime
);
if (elapsedTime > this.maxWaitTimeForOperation * 1000) {
return true;
}
}
return false;
},
handleRefreshDoor(statusbody, gateId) {
//retrieve service
var service;
let myGogogateDoorAccessory = this.foundAccessories.find((x) => x.gateId == gateId);
if (myGogogateDoorAccessory) {
service = myGogogateDoorAccessory.getServiceByUUIDAndSubType(
myGogogateDoorAccessory.name,
'GarageDoorOpener' + myGogogateDoorAccessory.name
);
}
if (!service) {
this.log('Error - handleRefreshDoor - ' + gateId + ' - no service found');
return;
}
let currentDoorState =
statusbody == 'OK'
? Characteristic.CurrentDoorState.OPEN
: Characteristic.CurrentDoorState.CLOSED;
let operationInProgress = service.TargetDoorStateOperationStart !== undefined;
let operationInProgressIsFinished =
operationInProgress && service.TargetDoorState == currentDoorState;
let oldDoorState = service.getCharacteristic(Characteristic.CurrentDoorState).value;
let oldTargetState = service.getCharacteristic(Characteristic.TargetDoorState).value;
this.log.debug(
'INFO - refreshDoor - Got Status for : ' +
service.subtype +
' - (currentDoorState/operationInProgress/operationInProgressIsFinished/oldDoorState) : (' +
currentDoorState +
'/' +
operationInProgress +
'/' +
operationInProgressIsFinished +
'/' +
oldDoorState +
')'
);
var newDoorState = oldDoorState;
var newTargetState = oldTargetState;
//operation has finished or timed out
if (operationInProgressIsFinished || this.endOperation(service, statusbody)) {
this.endDoorOperation(service);
if (!operationInProgressIsFinished) {
this.log(
'WARNING - refreshDoor - ' +
service.subtype +
' - operation was in progress and has timedout or no status retrieval'
);
}
newDoorState = currentDoorState;
newTargetState = currentDoorState;
} else if (!operationInProgress && currentDoorState != oldDoorState) {
newDoorState = currentDoorState;
newTargetState = currentDoorState;
}
if (newTargetState != oldTargetState) {
this.log.debug(
'INFO - refreshDoor - ' +
service.subtype +
' updating TargetDoorState to : ' +
this.gogogateAPI.getStateString(newTargetState)
);
//TargetDoorState before CurrentDoorState
setImmediate(() => {
service.getCharacteristic(Characteristic.TargetDoorState).updateValue(newTargetState);
});
}
if (newDoorState != oldDoorState) {
this.log.debug(
'INFO - refreshDoor - ' +
service.subtype +
' updating CurrentDoorState to : ' +
this.gogogateAPI.getStateString(newDoorState)
);
setImmediate(() => {
service.getCharacteristic(Characteristic.CurrentDoorState).updateValue(newDoorState);
});
}
},
handleRefreshSensor(statusbody, gateId) {
this.log.debug('INFO - refreshSensor with body : ' + statusbody);
let res = JSON.parse(statusbody);
var newVal;
//retrieve service
var batteryService;
var tempService;
let myGogogateDoorAccessory = this.foundAccessories.find((x) => x.gateId == gateId);
if (myGogogateDoorAccessory) {
for (let s = 0; s < myGogogateDoorAccessory.services.length; s++) {
let service = myGogogateDoorAccessory.services[s];
if (service.UUID == Service.TemperatureSensor.UUID) {
tempService = service;
} else if (service.UUID == Service.BatteryService.UUID) {
batteryService = service;
}
}
}
if (!batteryService) {
this.log('Error - handleRefreshSensor - ' + batteryService.subtype + ' - service not found');
} else {
newVal = GogogateTools.normalizeBattery(res[1]);
this.log.debug('INFO - refreshBattery with value : ' + newVal);
batteryService.getCharacteristic(Characteristic.BatteryLevel).updateValue(newVal);
}
if (!tempService) {
this.log('Error - handleRefreshSensor - ' + batteryService.subtype + ' - service not found');
} else {
newVal = res[0] / 1000;
this.log.debug('INFO - refreshTemp with value : ' + newVal);
tempService.getCharacteristic(Characteristic.CurrentTemperature).updateValue(newVal);
}
},
getCurrentDoorStateCharacteristic: function (service, callback) {
callback(undefined, service.getCharacteristic(Characteristic.CurrentDoorState).value);
//no operationInProgress, refresh current state
if (service.TargetDoorStateOperationStart == undefined) {
this.gogogateAPI.refreshDoor(service.gateId);
}
},
getTargetDoorStateCharacteristic: function (service, callback) {
callback(undefined, service.getCharacteristic(Characteristic.TargetDoorState).value);
//Target is updated through event
},
setTargetDoorStateCharacteristic: function (service, value, callback) {
var currentValue = service.getCharacteristic(Characteristic.TargetDoorState).value;
var currentState = service.getCharacteristic(Characteristic.CurrentDoorState).value;
callback();
var that = this;
if (
currentState != value &&
(currentState == Characteristic.CurrentDoorState.OPEN ||
currentState == Characteristic.CurrentDoorState.CLOSED)
) {
this.log.debug(
'INFO - SET Characteristic.TargetDoorState - ' +
service.subtype +
' - CurrentDoorState is ' +
this.gogogateAPI.getStateString(currentState)
);
this.gogogateAPI.activateDoor(service.gateId, function (error) {
if (error) {
that.endDoorOperation(service);
setTimeout(() => {
service.getCharacteristic(Characteristic.TargetDoorState).updateValue(currentValue);
service.getCharacteristic(Characteristic.CurrentDoorState).updateValue(currentState);
}, 500);
that.log.debug(
'ERROR - SET Characteristic.TargetDoorState - ' + service.subtype + ' error activating '
);
} else {
that.beginDoorOperation(service, value);
that.log.debug(
'INFO - SET Characteristic.TargetDoorState - ' +
service.subtype +
' success activating '
);
}
});
}
},
bindCurrentDoorStateCharacteristic: function (service) {
service.getCharacteristic(Characteristic.CurrentDoorState).on(
'get',
function (callback) {
this.getCurrentDoorStateCharacteristic(service, callback);
}.bind(this)
);
},
bindTargetDoorStateCharacteristic: function (service) {
//at startup, set to currentstate to reset
service
.getCharacteristic(Characteristic.TargetDoorState)
.updateValue(service.getCharacteristic(Characteristic.CurrentDoorState).value);
service
.getCharacteristic(Characteristic.TargetDoorState)
.on(
'get',
function (callback) {
this.getTargetDoorStateCharacteristic(service, callback);
}.bind(this)
)
.on(
'set',
function (value, callback) {
this.setTargetDoorStateCharacteristic(service, value, callback);
}.bind(this)
);
},
bindObstructionDetectedCharacteristic: function (service) {
service.getCharacteristic(Characteristic.ObstructionDetected).on(
'get',
function (callback) {
callback(undefined, false);
}.bind(this)
);
},
bindBatteryLevelCharacteristic: function (service) {
service.getCharacteristic(Characteristic.BatteryLevel).on(
'get',
function (callback) {
var percent = service.getCharacteristic(Characteristic.BatteryLevel).value;
callback(undefined, percent);
this.gogogateAPI.refreshSensor(service.gateId);
}.bind(this)
);
},
bindCurrentTemperatureLevelCharacteristic: function (service) {
service
.getCharacteristic(Characteristic.CurrentTemperature)
//to handle negative temps
.setProps({
minValue: -50,
maxValue: 50,
})
.on(
'get',
function (callback) {
var temp = service.getCharacteristic(Characteristic.CurrentTemperature).value;
callback(undefined, temp);
this.gogogateAPI.refreshSensor(service.gateId);
}.bind(this)
);
},
bindChargingStateCharacteristic: function (service) {
service.getCharacteristic(Characteristic.ChargingState).on(
'get',
function (callback) {
callback(undefined, false);
}.bind(this)
);
},
bindStatusLowBatteryCharacteristic: function (service) {
service.getCharacteristic(Characteristic.StatusLowBattery).on(
'get',
function (callback) {
callback(undefined, service.getCharacteristic(Characteristic.BatteryLevel) == 0);
}.bind(this)
);
},
beginDoorOperation(service, state) {
//stop timer if one exists.
if (this.timerID !== undefined) {
clearInterval(this.timerID);
this.timerID = undefined;
}
service.TargetDoorState = state;
service.TargetDoorStateOperationStart = Date.now();
//start operating timer
this.log.debug(
'INFO - beginDoorOperation - ' + service.subtype + ' - Setting Timer for operation'
);
this.timerID = setInterval(() => {
this.refreshAllDoors();
}, this.refreshTimerDuringOperation * 1000);
},
endDoorOperation(service) {
//stop timer for this operation
this.log.debug('INFO - endDoorOperation - ' + service.subtype + ' - Stopping operation');
service.TargetDoorState = undefined;
service.TargetDoorStateOperationStart = undefined;
this.checkEndOperation();
},
checkEndOperation() {
//clear timer and set background again if no other operation in progress
if (this.timerID !== undefined) {
let operationInProgress = false;
for (let a = 0; a < this.foundAccessories.length; a++) {
let myGogogateAccessory = this.foundAccessories[a];
for (let s = 0; s < myGogogateAccessory.services.length; s++) {
let service = myGogogateAccessory.services[s];
if (service.TargetDoorStateOperationStart !== undefined) {
operationInProgress = true;
break;
}
}
if (operationInProgress) break;
}
if (!operationInProgress) {
this.log.debug('Stopping Operation Timer ');
clearInterval(this.timerID);
this.timerID = undefined;
this.refreshBackground();
}
}
},
refreshBackground() {
//timer for background refresh
if (this.refreshTimer !== undefined && this.refreshTimer > 0) {
this.log.debug(
'INFO - Setting Timer for background refresh every : ' + this.refreshTimer + 's'
);
this.timerID = setInterval(() => this.refreshAllDoors(), this.refreshTimer * 1000);
}
},
refreshAllDoors: function () {
for (let a = 0; a < this.foundAccessories.length; a++) {
this.log.debug('INFO - refreshing - ' + this.foundAccessories[a].name);
let myGogogateAccessory = this.foundAccessories[a];
for (let s = 0; s < myGogogateAccessory.services.length; s++) {
let service = myGogogateAccessory.services[s];
if (service.UUID == Service.GarageDoorOpener.UUID) {
this.log.debug('INFO - refreshAllDoors - Door : ' + service.subtype);
this.gogogateAPI.refreshDoor(service.gateId);
} else if (service.UUID == Service.TemperatureSensor.UUID) {
this.log.debug('INFO - refreshAllDoors - Temp / Battery : ' + service.subtype);
this.gogogateAPI.refreshSensor(service.gateId);
//battery will be done with temp
}
}
}
},
};