This repository has been archived by the owner on Apr 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
740 lines (644 loc) · 24 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
var foscam = require("foscam-client");
var fs = require("fs");
var mkdirp = require("mkdirp");
var inherits = require('util').inherits;
var Accessory, Service, Characteristic, UUIDGen;
module.exports = function(homebridge) {
Accessory = homebridge.platformAccessory;
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
// Characteristic "Snapshot"
Snapshot = function () {
Characteristic.call(this, 'Snapshot', 'B895211C-0587-11E6-8CEC-00089BDF8CC3');
this.setProps({
format: Characteristic.Formats.BOOL,
perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY]
});
this.value = this.getDefaultValue();
};
inherits(Snapshot, Characteristic);
Snapshot.UUID = 'B895211C-0587-11E6-8CEC-00089BDF8CC3';
homebridge.registerPlatform("homebridge-foscam2", "Foscam2", FoscamPlatform, true);
}
function FoscamPlatform(log, config, api) {
this.log = log;
this.config = config || {"platform": "Foscam2"};
this.cameras = this.config.cameras || [];
this.accessories = {};
this.foscamAPI = {};
this.cameraInfo = {};
if (api) {
this.api = api;
this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this));
}
// HomeKit Current State: 0 (STAY_ARM), 1 (AWAY_ARM), 2 (NIGHT_ARM), 3 (DISARMED), 4 (ALARM_TRIGGERED)
this.armState = ["Armed (Stay).", "Armed (Away).", "Armed (Night).", "Disarmed.", "Alarm Triggered."]
}
// Method to restore accessories from cache
FoscamPlatform.prototype.configureAccessory = function(accessory) {
this.setService(accessory);
var accessoryMAC = accessory.context.mac;
this.accessories[accessoryMAC] = accessory;
}
// Method to setup accesories from config.json
FoscamPlatform.prototype.didFinishLaunching = function() {
var self = this;
// Add or update accessory in HomeKit
for (var i in this.cameras) {
this.addAccessory(this.cameras[i]);
}
}
// Method to add or update HomeKit accessories
FoscamPlatform.prototype.addAccessory = function(camera) {
var self = this;
this.getInfo(camera, function(camera, mac, error){
if (!error) {
self.configureCamera(camera, mac);
} else {
self.log(error);
}
});
}
// Method to detect Foscam API version and camera info
FoscamPlatform.prototype.getInfo = function(camera, callback) {
var self = this;
// Setup for foscam-client
var thisFoscamAPI = new foscam({
username: camera.username,
password: camera.password,
host: camera.host,
port: camera.port,
protocol: 'http',
rejectUnauthorizedCerts: true
});
// Retrieve camera info
thisFoscamAPI.getDevInfo().then(function(info) {
if (info.result == 0) {
self.foscamAPI[info.mac] = thisFoscamAPI;
self.cameraInfo[info.mac] = {};
self.cameraInfo[info.mac].name = info.devName;
self.cameraInfo[info.mac].model = info.productName.toString();
self.cameraInfo[info.mac].serial = info.serialNo.toString();
self.cameraInfo[info.mac].fw = info.firmwareVer.toString();
self.cameraInfo[info.mac].hw = info.hardwareVer.toString();
self.detectAPI(camera, info.mac, callback);
} else {
callback(null, null, "Failed to retrieve camera information!");
}
})
.catch(function(error) {
callback(null, null, "Failed to retrieve camera information!");
});
}
// Method to detect Foscam API version and camera info
FoscamPlatform.prototype.detectAPI = function(camera, mac, callback) {
var self = this;
// Detect API
this.foscamAPI[mac].getMotionDetectConfig().then(function(config) {
if (config.result == 0) {
self.cameraInfo[mac].ver = 0;
} else {
self.cameraInfo[mac].ver = 1;
}
callback(camera, mac);
})
.catch(function(error) {
self.log(error);
callback(null, null, "Failed to detect API version!");
});
}
// Method to configure camera info for HomeKit
FoscamPlatform.prototype.configureCamera = function(camera, mac) {
var conversion = [camera.stay, camera.away, camera.night];
if (this.cameraInfo[mac].ver == 0) {
// Older models only support 4-bit linkage
conversion = conversion.map(function(k) {return (k & 0x0f)});
} else {
// Newer models support push notification bit
conversion = conversion.map(function(k) {return (k & 0x8f)});
}
if (!this.accessories[mac]) {
var uuid = UUIDGen.generate(mac);
// Setup accessory as ALARM_SYSTEM (11) category.
var newAccessory = new Accessory("Foscam " + this.cameraInfo[mac].name, uuid, 11);
// New accessory is always reachable
newAccessory.reachable = true;
// Store and initialize variables into context
newAccessory.context.mac = mac;
newAccessory.context.username = camera.username;
newAccessory.context.password = camera.password;
newAccessory.context.host = camera.host;
newAccessory.context.port = camera.port;
newAccessory.context.path = camera.path;
newAccessory.context.conversion = conversion;
newAccessory.context.currentState = Characteristic.SecuritySystemCurrentState.DISARMED;
newAccessory.context.statusFault = 0;
// Setup HomeKit security system service
newAccessory.addService(Service.SecuritySystem, this.cameraInfo[mac].name);
// Add custom snapshot switch
newAccessory.getService(Service.SecuritySystem).addCharacteristic(Snapshot);
// Setup HomeKit accessory information
this.setAccessoryInfo(newAccessory);
// Setup listeners for different security system events
this.setService(newAccessory);
// Register accessory in HomeKit
this.api.registerPlatformAccessories("homebridge-foscam2", "Foscam2", [newAccessory]);
} else {
// Retrieve accessory from cache
var newAccessory = this.accessories[mac];
// Accessory is reachable after it's found in config.json
newAccessory.updateReachability(true);
// Update variables in context
newAccessory.context.username = camera.username;
newAccessory.context.password = camera.password;
newAccessory.context.host = camera.host;
newAccessory.context.port = camera.port;
newAccessory.context.path = camera.path;
newAccessory.context.conversion = conversion;
}
// Retrieve initial state
this.getInitState(newAccessory);
// Store accessory in cache
this.accessories[mac] = newAccessory;
}
// Method to remove accessories from HomeKit
FoscamPlatform.prototype.removeAccessory = function(accessory) {
if (accessory) {
var mac = accessory.context.mac;
this.log("[" + accessory.displayName + "] Removed from HomeBridge.");
this.api.unregisterPlatformAccessories("homebridge-foscam2", "Foscam2", [accessory]);
delete this.accessories[mac];
delete this.foscamAPI[mac];
delete this.cameraInfo[mac];
}
}
// Method to setup listeners for different events
FoscamPlatform.prototype.setService = function(accessory) {
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Characteristic.SecuritySystemCurrentState)
.on('get', this.getCurrentState.bind(this, accessory));
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Characteristic.SecuritySystemTargetState)
.on('get', this.getTargetState.bind(this, accessory))
.on('set', this.setTargetState.bind(this, accessory));
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Characteristic.StatusFault)
.on('get', this.getStatusFault.bind(this, accessory));
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Snapshot)
.on('get', this.resetSwitch.bind(this))
.on('set', this.takeSnapshot.bind(this, accessory));
accessory
.on('identify', this.identify.bind(this, accessory));
}
// Method to setup HomeKit accessory information
FoscamPlatform.prototype.setAccessoryInfo = function(accessory) {
var mac = accessory.context.mac;
accessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, "Foscam Digital Technology LLC");
if (this.cameraInfo[mac]) {
accessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Model, this.cameraInfo[mac].model)
.setCharacteristic(Characteristic.SerialNumber, this.cameraInfo[mac].serial);
}
}
// Method to retrieve initial state
FoscamPlatform.prototype.getInitState = function(accessory) {
var mac = accessory.context.mac;
if (this.cameraInfo[mac]) {
accessory
.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.FirmwareRevision, this.cameraInfo[mac].fw)
.setCharacteristic(Characteristic.HardwareRevision, this.cameraInfo[mac].hw);
}
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Characteristic.SecuritySystemCurrentState)
.getValue();
accessory
.getService(Service.SecuritySystem)
.getCharacteristic(Characteristic.SecuritySystemTargetState)
.getValue();
accessory
.getService(Service.SecuritySystem)
.setCharacteristic(Snapshot, 0);
}
// Method to get the current state
FoscamPlatform.prototype.getCurrentState = function(accessory, callback) {
var self = this;
var thisCamera = accessory.context;
var name = accessory.displayName;
// Setup the correct promise to use
if (this.cameraInfo[thisCamera.mac].ver == 0) {
var getConfig = this.foscamAPI[thisCamera.mac].getMotionDetectConfig();
} else {
var getConfig = this.foscamAPI[thisCamera.mac].getMotionDetectConfig1();
}
getConfig.then(function(config) {
if (config.result == 0) {
// Compute current state and target state
if (config.isEnable == 0) {
thisCamera.currentState = Characteristic.SecuritySystemCurrentState.DISARMED;
} else {
if (thisCamera.conversion.indexOf(config.linkage) >= 0) {
thisCamera.currentState = thisCamera.conversion.indexOf(config.linkage);
} else {
thisCamera.currentState = Characteristic.SecuritySystemCurrentState.STAY_ARM;
}
}
// Set status fault
thisCamera.statusFault = 0;
self.log("[" + name + "] Current state: " + self.armState[thisCamera.currentState]);
callback(null, thisCamera.currentState);
} else {
// Set status fault to 1 in case of error
thisCamera.statusFault = 1;
callback(new Error("Failed to retrieve current state!"));
}
})
.catch(function(error) {
// Set status fault to 1 in case of error
thisCamera.statusFault = 1;
callback(error);
});
}
// Method to get the target state
FoscamPlatform.prototype.getTargetState = function(accessory, callback) {
setTimeout(function() {
callback(null, accessory.context.currentState);
}, 500);
}
// Method to set the target state
FoscamPlatform.prototype.setTargetState = function(accessory, state, callback) {
var self = this;
var thisCamera = accessory.context;
var name = accessory.displayName;
// Setup the correct promise and function to use
if (this.cameraInfo[thisCamera.mac].ver == 0) {
var getConfig = this.foscamAPI[thisCamera.mac].getMotionDetectConfig();
var setConfig = function(config) {self.foscamAPI[thisCamera.mac].setMotionDetectConfig(config);};
} else {
var getConfig = this.foscamAPI[thisCamera.mac].getMotionDetectConfig1();
var setConfig = function(config) {self.foscamAPI[thisCamera.mac].setMotionDetectConfig1(config);};
}
// Convert target state to isEnable
var enable = state < 3 ? 1 : 0;
// Get current config
getConfig.then(function(config) {
if (config.result == 0) {
// Change isEnable and linkage to requested state
config.isEnable = enable;
if (enable) config.linkage = thisCamera.conversion[state];
// Update config with requested state
setConfig(config);
// Set status fault
thisCamera.statusFault = 0;
// Set current state
accessory
.getService(Service.SecuritySystem)
.setCharacteristic(Characteristic.SecuritySystemCurrentState, state);
self.log("[" + name + "] " + self.armState[state]);
callback(null);
} else {
// Set status fault to 1 in case of error
thisCamera.statusFault = 1;
callback(new Error("Failed to set target state!"));
}
})
.catch(function(error) {
// Set status fault to 1 in case of error
thisCamera.statusFault = 1;
callback(error);
});
}
// Method to get the status fault
FoscamPlatform.prototype.getStatusFault = function(accessory, callback) {
setTimeout(function() {
callback(null, accessory.context.statusFault);
}, 500);
}
// Method to take snapshots
FoscamPlatform.prototype.takeSnapshot = function(accessory, snapshot, callback) {
if (snapshot) {
var self = this;
var thisCamera = accessory.context;
var name = accessory.displayName;
this.foscamAPI[thisCamera.mac].snapPicture2().then(function(jpeg) {
// Create directory for snapshots
mkdirp(thisCamera.path, function(error) {
if (!error) {
var timeStamp = new Date();
// Write data as jpeg file to predefined directory
fs.writeFile(thisCamera.path + "/snap_" + timeStamp.valueOf() + ".jpeg", jpeg, function(error) {
if (!error) {
self.log("[" + name + "] Took a snapshot.");
} else {
self.log("[" + name + "] Snapshot cannot be saved.");
}
});
} else {
self.log("[" + name + "] Snapshot directory cannot be created.");
}
});
})
.catch(function(error){
self.log("[" + name + "] Snapshot cannot be created");
});
// Set switch back to off after 1s
setTimeout(function(accessory) {
accessory
.getService(Service.SecuritySystem)
.setCharacteristic(Snapshot, 0);
}.bind(this, accessory), 1000);
}
callback(null);
}
// Method to reset snapshot switch
FoscamPlatform.prototype.resetSwitch = function(callback) {
callback(null, 0);
}
// Method to handle identify request
FoscamPlatform.prototype.identify = function(accessory, paired, callback) {
this.log("[" + accessory.displayName + "] Identify requested!");
callback();
}
// Method to compute linkage for different states
FoscamPlatform.prototype.computeLinkage = function(selections) {
var linkage = 0;
// Compute linkage according to Foscam CGI manual
selections.sort();
for (var i in selections) {
if (selections[i] == 4) {
linkage += 128;
} else {
linkage += Math.pow(2, selections[i]);
}
}
return linkage;
}
// Method to handle plugin configuration in HomeKit app
FoscamPlatform.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": "list",
"title": "What do you want to do?",
"items": [
"Add New IP Camera",
"Modify Existing IP Camera",
"Remove Existing IP Camera"
]
}
context.step = 2;
callback(respDict);
break;
case 2:
var selection = request.response.selections[0];
if (selection === 0) {
// Info for new accessory
var respDict = {
"type": "Interface",
"interface": "input",
"title": "New IP Camera",
"items": [{
"id": "username",
"title": "Login Username (Default admin)",
"placeholder": "admin"
}, {
"id": "password",
"title": "Login Password (Required)",
"placeholder": "password",
"secure": true
}, {
"id": "host",
"title": "IP Camera Address (Required)",
"placeholder": "192.168.1.10"
}, {
"id": "port",
"title": "IP Camera Port (Default 88)",
"placeholder": "88"
}, {
"id": "path",
"title": "Local Path for Snapshots (Required)",
"placeholder": "/home/pi/Foscam"
}]
};
context.stateConfig = 0;
context.step = 3;
callback(respDict);
} else {
var self = this;
var cameras = Object.keys(this.accessories).map(function(k) {return self.accessories[k]});
var names = cameras.map(function(k) {return k.displayName});
if (names.length > 0) {
// Select existing accessory for modification or removal
if (selection === 1) {
var title = "Witch IP camera do you want to modify?";
context.modify = 1;
} else {
var title = "Witch IP camera do you want to remove?";
context.modify = 0;
}
var respDict = {
"type": "Interface",
"interface": "list",
"title": title,
"items": names
};
context.cameras = cameras;
context.step = 5;
} else {
// Error if no accessory is configured
var respDict = {
"type": "Interface",
"interface": "instruction",
"title": "Unavailable",
"detail": "No IP camera is configured.",
"showNextButton": true
};
context.step = 1;
}
callback(respDict);
}
break;
case 3:
// Configure Stay, Away, Night arm
if (context.stateConfig == 0) {
var title = "Configure Stay Arm";
context.inputs = request.response.inputs;
context.stateConfig = 1;
context.step = 3;
} else if (context.stateConfig == 1) {
var title = "Configure Away Arm";
context.inputs.stay = this.computeLinkage(request.response.selections);
context.stateConfig = 2;
context.step = 3;
} else {
var title = "Configure Night Arm";
context.inputs.away = this.computeLinkage(request.response.selections);
delete context.stateConfig;
context.step = 4;
}
var respDict = {
"type": "Interface",
"interface": "list",
"title": title,
"allowMultipleSelection": true,
"items": [
"Ring",
"Send Email",
"Snap Picture",
"Record",
"Push Notification (Only on newer models)"
]
};
callback(respDict);
break;
case 4:
context.inputs.night = this.computeLinkage(request.response.selections);
var userInputs = context.inputs;
var newCamera = {};
// Setup info for adding or updating accessory
if (context.selected) {
var accessory = this.accessories[context.selected];
newCamera.username = userInputs.username || accessory.context.username;
newCamera.password = userInputs.password || accessory.context.password;
newCamera.host = userInputs.host || accessory.context.host;
newCamera.port = userInputs.port || accessory.context.port;
newCamera.path = userInputs.path || accessory.context.path;
newCamera.stay = userInputs.stay || accessory.context.conversion[0];
newCamera.away = userInputs.away || accessory.context.conversion[1];
newCamera.night = userInputs.night || accessory.context.conversion[2];
} else {
newCamera.username = userInputs.username || "admin";
newCamera.password = userInputs.password;
newCamera.host = userInputs.host;
newCamera.port = userInputs.port || 88;
newCamera.path = userInputs.path;
newCamera.stay = userInputs.stay;
newCamera.away = userInputs.away;
newCamera.night = userInputs.night;
}
// Check for required info
if (newCamera.password && newCamera.host && newCamera.path) {
// Add or update accessory in HomeKit
this.addAccessory(newCamera);
var respDict = {
"type": "Interface",
"interface": "instruction",
"title": "Success",
"detail": "The new IP camera is now updated.",
"showNextButton": true
};
context.step = 6;
} 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 5:
var selection = request.response.selections[0];
var accessory = context.cameras[selection];
if (context.modify) {
// Modify info of selected accessory
var respDict = {
"type": "Interface",
"interface": "input",
"title": accessory.displayName.toString(),
"items": [{
"id": "username",
"title": "Login Username",
"placeholder": "Leave blank if unchanged"
}, {
"id": "password",
"title": "Login Password",
"placeholder": "Leave blank if unchanged",
"secure": true
}, {
"id": "host",
"title": "IP Camera Address",
"placeholder": "Leave blank if unchanged"
}, {
"id": "port",
"title": "IP Camera Port",
"placeholder": "Leave blank if unchanged"
}, {
"id": "path",
"title": "Local Path for Snapshots",
"placeholder": "Leave blank if unchanged"
}]
};
context.selected = accessory.context.mac;
context.stateConfig = 0;
context.step = 3;
} else {
// Remove selected accessory from HomeKit
this.removeAccessory(accessory);
var respDict = {
"type": "Interface",
"interface": "instruction",
"title": "Success",
"detail": "The switch is now removed.",
"showNextButton": true
};
context.step = 6;
}
callback(respDict);
break;
case 6:
// Update config.json accordingly
var self = this;
delete context.step;
var newConfig = this.config;
var newCameras = Object.keys(this.accessories).map(function(k) {
var accessory = self.accessories[k];
var data = {
'username': accessory.context.username,
'password': accessory.context.password,
'host': accessory.context.host,
'port': accessory.context.port,
'stay': accessory.context.conversion[0],
'away': accessory.context.conversion[1],
'night': accessory.context.conversion[2],
'path': accessory.context.path
};
return data;
});
newConfig.cameras = newCameras;
callback(null, "platform", true, newConfig);
break;
}
}
}