-
Notifications
You must be signed in to change notification settings - Fork 52
/
index.js
executable file
·333 lines (293 loc) · 12 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
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 Service, Characteristic, HomebridgeAPI;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
HomebridgeAPI = homebridge;
homebridge.registerPlatform("homebridge-people", "People", PeoplePlatform);
homebridge.registerAccessory("homebridge-people", "PeopleAccessory", PeopleAccessory);
homebridge.registerAccessory("homebridge-people", "PeopleAllAccessory", PeopleAllAccessory);
}
// #######################
// PeoplePlatform
// #######################
function PeoplePlatform(log, config){
this.log = log;
this.threshold = config['threshold'] || 15;
this.anyoneSensor = config['anyoneSensor'] || true;
this.nooneSensor = config['nooneSensor'] || false;
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;
this.service = new Service.OccupancySensor(this.name);
this.service
.getCharacteristic(Characteristic.OccupancyDetected)
.on('get', this.getState.bind(this));
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.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.OccupancyDetected).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.log('Changed occupancy state for %s to %s. Last successful ping %s , last webhook %s .', this.target, newState, lastSuccessfulPingMoment, lastWebhookMoment);
}
}
PeopleAccessory.prototype.getServices = function() {
return [this.service];
}
// #######################
// 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));
}
PeopleAllAccessory.prototype.getState = function(callback) {
callback(null, PeopleAccessory.encodeState(this.getStateFromCache()));
}
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];
}