forked from PeteLawrence/homebridge-people
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
executable file
·467 lines (409 loc) · 16.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
var ping = require('ping');
var moment = require('moment');
var request = require("request");
var http = require('http');
var url = require('url');
var DEFAULT_REQUEST_TIMEOUT = 10000;
var SENSOR_ANYONE = 'Anyone';
var SENSOR_NOONE = 'No One';
var FakeGatoHistoryService;
const EPOCH_OFFSET = 978307200;
var Service, Characteristic, HomebridgeAPI;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
FakeGatoHistoryService = require('fakegato-history')(homebridge);
homebridge.registerPlatform("homebridge-people-x", "PeopleX", PeoplePlatform);
homebridge.registerAccessory("homebridge-people-x", "PeopleAccessory", PeopleAccessory);
homebridge.registerAccessory("homebridge-people-x", "PeopleAllAccessory", PeopleAllAccessory);
}
// #######################
// PeoplePlatform
// #######################
function PeoplePlatform(log, config){
this.log = log;
this.threshold = config['threshold'] || 15;
this.anyoneSensor = ((typeof(config['anyoneSensor']) != "undefined" && config['anyoneSensor'] !== null)?config['anyoneSensor']:true);
this.nooneSensor = ((typeof(config['nooneSensor']) != "undefined" && config['nooneSensor'] !== null)?config['nooneSensor']:true);
this.webhookPort = config["webhookPort"] || 51828;
this.cacheDirectory = config["cacheDirectory"] || HomebridgeAPI.user.persistPath();
this.pingInterval = config["pingInterval"] || 10000;
this.ignoreReEnterExitSeconds = config["ignoreReEnterExitSeconds"] || 0;
this.people = config['people'];
this.storage = require('node-persist');
this.storage.initSync({dir:this.cacheDirectory});
this.webhookQueue = [];
}
PeoplePlatform.prototype = {
accessories: function(callback) {
this.accessories = [];
this.peopleAccessories = [];
for(var i = 0; i < this.people.length; i++){
var peopleAccessory = new PeopleAccessory(this.log, this.people[i], this);
this.accessories.push(peopleAccessory);
this.peopleAccessories.push(peopleAccessory);
}
if(this.anyoneSensor) {
this.peopleAnyOneAccessory = new PeopleAllAccessory(this.log, SENSOR_ANYONE, this);
this.accessories.push(this.peopleAnyOneAccessory);
}
if(this.nooneSensor) {
this.peopleNoOneAccessory = new PeopleAllAccessory(this.log, SENSOR_NOONE, this);
this.accessories.push(this.peopleNoOneAccessory);
}
callback(this.accessories);
this.startServer();
},
startServer: function() {
//
// HTTP webserver code influenced by benzman81's great
// homebridge-http-webhooks homebridge plugin.
// https://github.com/benzman81/homebridge-http-webhooks
//
// Start the HTTP webserver
http.createServer((function(request, response) {
var theUrl = request.url;
var theUrlParts = url.parse(theUrl, true);
var theUrlParams = theUrlParts.query;
var body = [];
request.on('error', (function(err) {
this.log("WebHook error: %s.", err);
}).bind(this)).on('data', function(chunk) {
body.push(chunk);
}).on('end', (function() {
body = Buffer.concat(body).toString();
response.on('error', function(err) {
this.log("WebHook error: %s.", err);
});
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
if(!theUrlParams.sensor || !theUrlParams.state) {
response.statusCode = 404;
response.setHeader("Content-Type", "text/plain");
var errorText = "WebHook error: No sensor or state specified in request.";
this.log(errorText);
response.write(errorText);
response.end();
}
else {
var sensor = theUrlParams.sensor.toLowerCase();
var newState = (theUrlParams.state == "true");
this.log('Received hook for ' + sensor + ' -> ' + newState);
var responseBody = {
success: true
};
for(var i = 0; i < this.peopleAccessories.length; i++){
var peopleAccessory = this.peopleAccessories[i];
var target = peopleAccessory.target
if(peopleAccessory.name.toLowerCase() === sensor) {
this.clearWebhookQueueForTarget(target);
this.webhookQueue.push({"target": target, "newState": newState, "timeoutvar": setTimeout((function(){
this.runWebhookFromQueueForTarget(target);
}).bind(this), peopleAccessory.ignoreReEnterExitSeconds * 1000)});
break;
}
}
response.write(JSON.stringify(responseBody));
response.end();
}
}).bind(this));
}).bind(this)).listen(this.webhookPort);
this.log("WebHook: Started server on port '%s'.", this.webhookPort);
},
clearWebhookQueueForTarget: function(target) {
for (var i = 0; i < this.webhookQueue.length; i++) {
var webhookQueueEntry = this.webhookQueue[i];
if(webhookQueueEntry.target == target) {
clearTimeout(webhookQueueEntry.timeoutvar);
this.webhookQueue.splice(i, 1);
break;
}
}
},
runWebhookFromQueueForTarget: function(target) {
for (var i = 0; i < this.webhookQueue.length; i++) {
var webhookQueueEntry = this.webhookQueue[i];
if(webhookQueueEntry.target == target) {
this.log('Running hook for ' + target + ' -> ' + webhookQueueEntry.newState);
this.webhookQueue.splice(i, 1);
this.storage.setItemSync('lastWebhook_' + target, Date.now());
this.getPeopleAccessoryForTarget(target).setNewState(webhookQueueEntry.newState);
break;
}
}
},
getPeopleAccessoryForTarget: function(target) {
for(var i = 0; i < this.peopleAccessories.length; i++){
var peopleAccessory = this.peopleAccessories[i];
if(peopleAccessory.target === target) {
return peopleAccessory;
}
}
return null;
}
}
// #######################
// PeopleAccessory
// #######################
function PeopleAccessory(log, config, platform) {
this.log = log;
this.name = config['name'];
this.target = config['target'];
this.platform = platform;
this.threshold = config['threshold'] || this.platform.threshold;
this.pingInterval = config['pingInterval'] || this.platform.pingInterval;
this.ignoreReEnterExitSeconds = config['ignoreReEnterExitSeconds'] || this.platform.ignoreReEnterExitSeconds;
this.stateCache = false;
class LastActivationCharacteristic extends Characteristic {
constructor(accessory) {
super('LastActivation', 'E863F11A-079E-48FF-8F27-9C2605A29F52');
this.setProps({
format: Characteristic.Formats.UINT32,
unit: Characteristic.Units.SECONDS,
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.NOTIFY
]
});
}
}
class SensitivityCharacteristic extends Characteristic {
constructor(accessory) {
super('Sensitivity', 'E863F120-079E-48FF-8F27-9C2605A29F52');
this.setProps({
format: Characteristic.Formats.UINT8,
minValue: 0,
maxValue: 7,
validValues: [0, 4, 7],
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.NOTIFY,
Characteristic.Perms.WRITE
]
});
}
}
class DurationCharacteristic extends Characteristic {
constructor(accessory) {
super('Duration', 'E863F12D-079E-48FF-8F27-9C2605A29F52');
this.setProps({
format: Characteristic.Formats.UINT16,
unit: Characteristic.Units.SECONDS,
minValue: 5,
maxValue: 15 * 3600,
validValues: [
5, 10, 20, 30,
1 * 60, 2 * 60, 3 * 60, 5 * 60, 10 * 60, 20 * 60, 30 * 60,
1 * 3600, 2 * 3600, 3 * 3600, 5 * 3600, 10 * 3600, 12 * 3600, 15 * 3600
],
perms: [
Characteristic.Perms.READ,
Characteristic.Perms.NOTIFY,
Characteristic.Perms.WRITE
]
});
}
}
this.service = new Service.MotionSensor(this.name);
this.service
.getCharacteristic(Characteristic.MotionDetected)
.on('get', this.getState.bind(this));
this.service.addCharacteristic(LastActivationCharacteristic);
this.service
.getCharacteristic(LastActivationCharacteristic)
.on('get', this.getLastActivation.bind(this));
this.service.addCharacteristic(SensitivityCharacteristic);
this.service
.getCharacteristic(SensitivityCharacteristic)
.on('get', function(callback){
callback(null, 4);
}.bind(this));
this.service.addCharacteristic(DurationCharacteristic);
this.service
.getCharacteristic(DurationCharacteristic)
.on('get', function(callback){
callback(null, 5);
}.bind(this));
this.accessoryService = new Service.AccessoryInformation;
this.accessoryService
.setCharacteristic(Characteristic.Name, this.name)
.setCharacteristic(Characteristic.SerialNumber, "hps-"+this.name.toLowerCase())
.setCharacteristic(Characteristic.Manufacturer, "Elgato");
this.historyService = new FakeGatoHistoryService("motion", {
displayName: this.name,
log: this.log
},
{
storage: 'fs',
disableTimer: true
});
this.initStateCache();
if(this.pingInterval > -1) {
this.ping();
}
}
PeopleAccessory.encodeState = function(state) {
if (state)
return Characteristic.OccupancyDetected.OCCUPANCY_DETECTED;
else
return Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED;
}
PeopleAccessory.prototype.getState = function(callback) {
callback(null, PeopleAccessory.encodeState(this.stateCache));
}
PeopleAccessory.prototype.getLastActivation = function(callback) {
var lastSeenUnix = this.platform.storage.getItemSync('lastSuccessfulPing_' + this.target);
if (lastSeenUnix) {
var lastSeenMoment = moment(lastSeenUnix).unix();
callback(null, lastSeenMoment - this.historyService.getInitialTime());
} else {
callback(null, 0);
}
}
PeopleAccessory.prototype.identify = function(callback) {
this.log("Identify: "+this.name);
callback();
}
PeopleAccessory.prototype.initStateCache = function() {
var isActive = this.isActive();
this.stateCache = isActive;
}
PeopleAccessory.prototype.isActive = function() {
var lastSeenUnix = this.platform.storage.getItemSync('lastSuccessfulPing_' + this.target);
if (lastSeenUnix) {
var lastSeenMoment = moment(lastSeenUnix);
var activeThreshold = moment().subtract(this.threshold, 'm');
return lastSeenMoment.isAfter(activeThreshold);
}
return false;
}
PeopleAccessory.prototype.ping = function() {
if(this.webhookIsOutdated()) {
ping.sys.probe(this.target, function(state){
if(this.webhookIsOutdated()) {
if (state) {
this.platform.storage.setItemSync('lastSuccessfulPing_' + this.target, Date.now());
}
if(this.successfulPingOccurredAfterWebhook()) {
var newState = this.isActive();
this.setNewState(newState);
}
}
setTimeout(PeopleAccessory.prototype.ping.bind(this), this.pingInterval);
}.bind(this));
}
else {
setTimeout(PeopleAccessory.prototype.ping.bind(this), this.pingInterval);
}
}
PeopleAccessory.prototype.webhookIsOutdated = function() {
var lastWebhookUnix = this.platform.storage.getItemSync('lastWebhook_' + this.target);
if (lastWebhookUnix) {
var lastWebhookMoment = moment(lastWebhookUnix);
var activeThreshold = moment().subtract(this.threshold, 'm');
return lastWebhookMoment.isBefore(activeThreshold);
}
return true;
}
PeopleAccessory.prototype.successfulPingOccurredAfterWebhook = function() {
var lastSuccessfulPing = this.platform.storage.getItemSync('lastSuccessfulPing_' + this.target);
if(!lastSuccessfulPing) {
return false;
}
var lastWebhook = this.platform.storage.getItemSync('lastWebhook_' + this.target);
if(!lastWebhook) {
return true;
}
var lastSuccessfulPingMoment = moment(lastSuccessfulPing);
var lastWebhookMoment = moment(lastWebhook);
return lastSuccessfulPingMoment.isAfter(lastWebhookMoment);
}
PeopleAccessory.prototype.setNewState = function(newState) {
var oldState = this.stateCache;
if (oldState != newState) {
this.stateCache = newState;
this.service.getCharacteristic(Characteristic.MotionDetected).updateValue(PeopleAccessory.encodeState(newState));
if(this.platform.peopleAnyOneAccessory) {
this.platform.peopleAnyOneAccessory.refreshState();
}
if(this.platform.peopleNoOneAccessory) {
this.platform.peopleNoOneAccessory.refreshState();
}
var lastSuccessfulPingMoment = "none";
var lastWebhookMoment = "none";
var lastSuccessfulPing = this.platform.storage.getItemSync('lastSuccessfulPing_' + this.target);
if(lastSuccessfulPing) {
lastSuccessfulPingMoment = moment(lastSuccessfulPing).format();
}
var lastWebhook = this.platform.storage.getItemSync('lastWebhook_' + this.target);
if(lastWebhook) {
lastWebhookMoment = moment(lastWebhook).format();
}
this.historyService.addEntry(
{
time: moment().unix(),
status: (newState) ? 1 : 0
});
this.log('Changed occupancy state for %s to %s. Last successful ping %s , last webhook %s .', this.target, newState, lastSuccessfulPingMoment, lastWebhookMoment);
}
}
PeopleAccessory.prototype.getServices = function() {
var servicesList = [this.service];
if(this.historyService) {
servicesList.push(this.historyService)
}
if(this.accessoryService) {
servicesList.push(this.accessoryService)
}
return servicesList;
}
// #######################
// PeopleAllAccessory
// #######################
function PeopleAllAccessory(log, name, platform) {
this.log = log;
this.name = name;
this.platform = platform;
this.service = new Service.OccupancySensor(this.name);
this.service
.getCharacteristic(Characteristic.OccupancyDetected)
.on('get', this.getState.bind(this));
this.accessoryService = new Service.AccessoryInformation;
this.accessoryService
.setCharacteristic(Characteristic.Name, this.name)
.setCharacteristic(Characteristic.SerialNumber, (this.name === SENSOR_NOONE)?"hps-noone":"hps-all")
.setCharacteristic(Characteristic.Manufacturer, "Elgato");
}
PeopleAllAccessory.prototype.getState = function(callback) {
callback(null, PeopleAccessory.encodeState(this.getStateFromCache()));
}
PeopleAllAccessory.prototype.identify = function(callback) {
this.log("Identify: "+this.name);
callback();
}
PeopleAllAccessory.prototype.getStateFromCache = function() {
var isAnyoneActive = this.getAnyoneStateFromCache();
if(this.name === SENSOR_NOONE) {
return !isAnyoneActive;
}
else {
return isAnyoneActive;
}
}
PeopleAllAccessory.prototype.getAnyoneStateFromCache = function() {
for(var i = 0; i < this.platform.peopleAccessories.length; i++){
var peopleAccessory = this.platform.peopleAccessories[i];
var isActive = peopleAccessory.stateCache;
if(isActive) {
return true;
}
}
return false;
}
PeopleAllAccessory.prototype.refreshState = function() {
this.service.getCharacteristic(Characteristic.OccupancyDetected).updateValue(PeopleAccessory.encodeState(this.getStateFromCache()));
}
PeopleAllAccessory.prototype.getServices = function() {
return [this.service, this.accessoryService];
}