forked from codetwice/homebridge-http-securitysystem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
423 lines (366 loc) · 10.5 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
var Service, Characteristic;
var request = require("request");
var xpath = require("xpath");
var dom = require("xmldom").DOMParser;
var pollingtoevent = require("polling-to-event");
var _ = require("lodash");
module.exports = function(homebridge){
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-http-securitysystem", "Http-SecuritySystem", HttpSecuritySystemAccessory);
};
/**
* Mapper class that can be used as a dictionary for mapping one value to another
*
* @param {Object} parameters The parameters of the mapper
* @constructor
*/
function StaticMapper(parameters) {
var self = this;
self.mapping = parameters.mapping;
self.map = function(value) {
return self.mapping[value] || value;
};
}
/**
* Mapper class that can extract a part of the string using a regex
*
* @param {Object} parameters The parameters of the mapper
* @constructor
*/
function RegexMapper(parameters) {
var self = this;
self.regexp = new RegExp(parameters.regexp);
self.capture = parameters.capture || "1";
self.map = function(value) {
var matches = self.regexp.exec(value);
if (matches !== null && self.capture in matches) {
return matches[self.capture];
}
return value;
};
}
/**
* Mapper class that uses XPath to select the text of a node or the value of an attribute
*
* @param {Object} parameters The parameters of the mapper
* @constructor
*/
function XPathMapper(parameters) {
var self = this;
self.xpath = parameters.xpath;
self.index = parameters.index || 0;
self.map = function(value) {
var document = new dom().parseFromString(value);
var result = xpath.select(this.xpath, document);
if (typeof result == "string") {
return result;
} else if (result instanceof Array && result.length > self.index) {
return result[self.index].data;
}
return value;
};
}
/**
* The main class acting as the Security System Accessory
*
* @param log The logger to use
* @param config The config received from HomeBridge
* @constructor
*/
function HttpSecuritySystemAccessory(log, config) {
var self = this;
self.log = log;
self.name = config["name"];
// the service
self.securityService = null;
// debug flag
self.debug = config.debug;
// polling settings
self.polling = config.polling;
self.pollInterval = config.pollInterval || 30000;
// cached values
self.previousCurrentState = null;
self.previousTargetState = null;
// process the mappers
self.mappers = [];
if (config.mappers) {
config.mappers.forEach(function(matches) {
switch (matches.type) {
case "regex":
self.mappers.push(new RegexMapper(matches.parameters));
break;
case "static":
self.mappers.push(new StaticMapper(matches.parameters));
break;
case "xpath":
self.mappers.push(new XPathMapper(matches.parameters));
break;
}
});
}
// url info
self.urls = {
stay: { url: '', body: '' },
away: { url: '', body: '' },
night: { url: '', body: '' },
disarm: { url: '', body: '' },
readCurrentState: { url: '', body: '' },
readTargetState: { url: '', body: '' }
};
_.merge(self.urls, config.urls);
self.httpMethod = config["http_method"] || "GET";
self.auth = {
username: config.username || "",
password: config.password || "",
immediately: true
};
if ("immediately" in config) {
self.auth.immediately = config.immediately;
}
// initialize
self.init();
}
/**
* Initializer method, fired after the config has been applied
*/
HttpSecuritySystemAccessory.prototype.init = function() {
var self = this;
// set up polling if requested
if (self.polling) {
self.log("Starting polling with an interval of %s ms", self.pollInterval);
var emitterConfig = [
{
method: self.getCurrentState.bind(this),
property: 'current state',
characteristic: Characteristic.SecuritySystemCurrentState
},
{
method: self.getTargetState.bind(this),
property: 'target state',
characteristic: Characteristic.SecuritySystemTargetState
}
];
emitterConfig.forEach(config => {
var emitter = pollingtoevent(function(done) {
config.method(function (err, result) {
done(err, result);
});
}, { longpolling: true, interval: self.pollInterval });
emitter.on("longpoll", function(state) {
self.log('Polling noticed %s change to %s, notifying devices', config.property, state);
self.securityService
.getCharacteristic(config.characteristic)
.setValue(state);
});
emitter.on("error", function(err) {
self.log("Polling of %s failed, error was %s", config.property, err);
});
});
}
};
/**
* Method that performs a HTTP request
*
* @param {String} url The URL to hit
* @param {String} body The body of the request
* @param {Object} headers The HTTP headers to pass along the request
* @param {Function} callback Callback method to call with the result or error (error, response, body)
*/
HttpSecuritySystemAccessory.prototype.httpRequest = function(url, body, headers, callback) {
var params = {
url: url,
body: body,
method: this.httpMethod,
auth: {
user: this.auth.username,
pass: this.auth.password,
sendImmediately: this.auth.immediately
},
headers: {}
};
if (this.auth.username) {
_.merge(params.headers, {
'Authorization': 'Basic ' + new Buffer(this.auth.username + ':' + this.auth.password).toString('base64')
});
}
if (headers != null) {
_.merge(params.headers, headers);
}
request(params, function(error, response, body) {
callback(error, response, body)
});
};
/**
* Logs a message to the HomeBridge log
*
* Only logs the message if the debug flag is on.
*/
HttpSecuritySystemAccessory.prototype.debugLog = function () {
if (this.debug) {
this.log.apply(this, arguments);
}
};
/**
* Sets the target state of the security device to a given state
*
* @param state The state to set
* @param callback Callback to call with the result
*/
HttpSecuritySystemAccessory.prototype.setTargetState = function(state, callback) {
this.log("Setting state to %s", state);
var cfg = null;
switch (state) {
case Characteristic.SecuritySystemTargetState.STAY_ARM:
cfg = this.urls.stay;
break;
case Characteristic.SecuritySystemTargetState.AWAY_ARM :
cfg = this.urls.away;
break;
case Characteristic.SecuritySystemTargetState.NIGHT_ARM:
cfg = this.urls.night;
break;
case Characteristic.SecuritySystemTargetState.DISARM:
cfg = this.urls.disarm;
break;
}
// if the URL is not configured, do not do anything
if (cfg == null) {
callback(null);
}
// if the config is not an array, convert it to one
if (!(cfg instanceof Array)) {
cfg = [ cfg ];
}
// call all urls and fire the callbacks when all URLs have returned something
var errorToReport = null;
var responses = 0;
cfg.forEach(c => {
var url = c.url;
var body = c.body || '';
var headers = c.headers || {}
this.httpRequest(url, body, headers, function(error, response) {
responses++;
if (error) {
this.log("SetState function failed (%s returned %s)", url, error.message);
errorToReport = error;
callback(error);
} else {
this.log("SetState function succeeded (%s)", url);
}
if (responses == cfg.length) {
callback(errorToReport, response, state);
}
}.bind(this));
});
};
/**
* Applies the mappers to the state string received
*
* @param {string} string The string to apply the mappers to
* @returns {string} The modified string after all mappers have been applied
*/
HttpSecuritySystemAccessory.prototype.applyMappers = function(string) {
var self = this;
if (self.mappers.length > 0) {
self.debugLog("Applying mappers on " + string);
self.mappers.forEach(function (mapper, index) {
var newString = mapper.map(string);
self.debugLog("Mapper " + index + " mapped " + string + " to " + newString);
string = newString;
});
self.debugLog("Mapping result is " + string);
}
return string;
};
/**
* Gets the state of the security system from a given URL
*
* @param {Object} requestConfig The HTTP request configuration
* @param {Function} callback The method to call with the results
*/
HttpSecuritySystemAccessory.prototype.getState = function(requestConfig, callback) {
// if the URL is not configured, do not do anything
if (requestConfig == null) {
callback(null);
}
var url = requestConfig.url;
var body = requestConfig.body || '';
var headers = requestConfig.headers || {}
if (!url) {
callback(null);
}
this.httpRequest(url, body, headers, function(error, response, responseBody) {
if (error) {
this.log("getState function failed: %s", error.message);
callback(error);
} else {
var state = responseBody;
state = this.applyMappers(state);
callback(null, parseInt(state));
}
}.bind(this));
};
/**
* Gets the current state of the security system
*
* @param {Function} callback The method to call with the results
*/
HttpSecuritySystemAccessory.prototype.getCurrentState = function(callback) {
var self = this;
self.debugLog("Getting current state");
this.getState(this.urls.readCurrentState, function(err, state) {
if (!err) {
self.debugLog("Current state is %s", state);
if (self.previousCurrentState !== state) {
self.previousCurrentState = state;
self.log("Current state changed to %s", state);
}
}
callback(err, state);
});
};
/**
* Gets the target state of the security system
*
* @param {Function} callback The method to call with the results
*/
HttpSecuritySystemAccessory.prototype.getTargetState = function(callback) {
var self = this;
self.debugLog("Getting target state");
this.getState(this.urls.readTargetState, function(err, state) {
if (!err) {
self.debugLog("Target state is %s", state);
if (self.previousTargetState !== state) {
self.previousTargetState = state;
self.log("Target state changed to %s", state);
}
}
callback(err, state);
});
};
/**
* Identifies the security device (?)
*
* @param {Function} callback The method to call with the results
*/
HttpSecuritySystemAccessory.prototype.identify = function(callback) {
this.log("Identify requested!");
callback();
};
/**
* Returns the services offered by this security device
*
* @returns {Array} The services offered
*/
HttpSecuritySystemAccessory.prototype.getServices = function() {
this.securityService = new Service.SecuritySystem(this.name);
this.securityService
.getCharacteristic(Characteristic.SecuritySystemCurrentState)
.on("get", this.getCurrentState.bind(this));
this.securityService
.getCharacteristic(Characteristic.SecuritySystemTargetState)
.on("get", this.getTargetState.bind(this))
.on("set", this.setTargetState.bind(this));
return [ this.securityService ];
};