forked from tasict/homebridge-http-accessory
-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.js
417 lines (366 loc) · 12.6 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
var Service, Characteristic;
var request = require("request");
var pollingtoevent = require("polling-to-event");
var mappers = require("./mappers.js");
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-http-advanced-accessory", "HttpAdvancedAccessory", HttpAdvancedAccessory);
};
function HttpAdvancedAccessory(log, config) {
this.log = log;
this.name = config.name;
this.service = config.service;
this.optionCharacteristic = config.optionCharacteristic || [];
this.props = config.props || {};
this.forceRefreshDelay = config.forceRefreshDelay || 0;
this.setterDelay = config.setterDelay || 0;
this.enableSet = true;
this.statusEmitters = [];
this.state = {};
this.uriCalls=0;
this.uriCallsDelay = config.uriCallsDelay || 0;
// process the mappers
var self = this;
self.debug = config.debug;
/**
* self.urls ={
* getStatus : {
* url:"http://",
* httpMethod:"",
* mappers : [],
* inconclusive : {
* url:
* httpMethods:"",
* mappers[]
* }
* },
* getTemp : {
* url:"http://",
* httpMethod:"",
* mappers : []
* },
* setTemp : {
* url:"http://{value}",
* httpMethod:"",
* body:"{value}",
* mappers : []
* }
*}
*/
function createAction(action, actionDescription){
action.url = actionDescription.url;
action.httpMethod = actionDescription.httpMethod || "GET";
action.body = actionDescription.body || "";
action.resultOnError = actionDescription.resultOnError;
if (actionDescription.mappers) {
action.mappers = [];
actionDescription.mappers.forEach(function(matches) {
switch (matches.type) {
case "regex":
action.mappers.push(new mappers.RegexMapper(matches.parameters));
break;
case "static":
action.mappers.push(new mappers.StaticMapper(matches.parameters));
break;
case "xpath":
action.mappers.push(new mappers.XPathMapper(matches.parameters));
break;
case "jpath":
action.mappers.push(new mappers.JPathMapper(matches.parameters));
break;
case "eval":
var mapper = new mappers.EvalMapper(matches.parameters);
mapper.state = self.state;
action.mappers.push(mapper);
break;
}
});
}
if(actionDescription.inconclusive){
action.inconclusive = {};
createAction(action.inconclusive, actionDescription.inconclusive);
}
};
self.urls ={};
if(config.urls){
for (var actionName in config.urls){
if(!config.urls.hasOwnProperty(actionName)) continue;
self.urls[actionName] = {};
createAction(self.urls[actionName],config.urls[actionName]);
}
}
self.auth = {
username: config.username || "",
password: config.password || "",
immediately: true
};
if ("immediately" in config) {
self.auth.immediately = config.immediately;
}
}
HttpAdvancedAccessory.prototype = {
/**
* Logs a message to the HomeBridge log
*
* Only logs the message if the debug flag is on.
*/
debugLog : function () {
if (this.debug) {
this.log.apply(this, arguments);
}
},
/**
* Method that performs a HTTP request
*
* @param url The URL to hit
* @param body The body of the request
* @param callback Callback method to call with the result or error (error, response, body)
*/
httpRequest : function(url, body, httpMethod, callback) {
setTimeout(
function(){request({
url: url,
body: body,
method: httpMethod,
auth: {
user: this.auth.username,
pass: this.auth.password,
sendImmediately: this.auth.immediately
},
headers: {
Authorization: "Basic " + new Buffer(this.auth.username + ":" + this.auth.password).toString("base64")
}
},
function(error, response, body) {
this.uriCalls--;
this.debugLog("httpRequest ended, current uriCalls is " + this.uriCalls);
callback(error, response, body)
}.bind(this))}.bind(this), this.uriCalls * this.uriCallsDelay);
this.uriCalls++;
this.debugLog("httpRequest called, current uriCalls is " + this.uriCalls);
},
/**
* 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
*/
applyMappers : function(mappers, string) {
var self = this;
if (mappers && mappers.length > 0) {
self.debugLog("Applying mappers on " + string);
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;
},
stringInject : function(str, data) {
if (typeof str === 'string' && (data instanceof Array)) {
return str.replace(/({\d})/g, function(i) {
return data[i.replace(/{/, '').replace(/}/, '')];
});
} else if (typeof str === 'string' && (data instanceof Object)) {
for (let key in data) {
return str.replace(/({([^}]+)})/g, function(i) {
let key = i.replace(/{/, '').replace(/}/, '');
if (!data[key]) {
return i;
}
return data[key];
});
}
} else {
return false;
}
},
//Start
identify: function (callback) {
this.log("Identify requested!");
callback(null);
},
getName: function (callback) {
this.log("getName :", this.name);
var error = null;
callback(error, this.name);
},
getServices: function () {
var getDispatch = function (callback, action) {
if (typeof action == "undefined") {
callback(null);
return;
}
this.debugLog("getDispatch function called for url: %s", action.url);
this.httpRequest(action.url, action.body, action.httpMethod, function(error, response, responseBody) {
if (error && action.resultOnError != null) {
this.debugLog("GetState function failed BUT using resultOnError=%s: %s", action.resultOnError, error.message);
callback(null, action.resultOnError);
} else if (error) {
this.log("GetState function failed: %s", error.message);
callback(error);
} else {
this.debugLog("received response from action: %s", action.url);
var state = responseBody;
state = this.applyMappers(action.mappers,state);
if (state == "inconclusive") {
this.log(`Inconclusive mapping of response "${responseBody}"`);
if (action.inconclusive){
this.debugLog("Response inconclusive and trying the action specified for this condition.");
getDispatch(callback,action.inconclusive);
} else {
this.debugLog("Response inconclusive with no further action specified for this condition.");
}
} else {
this.debugLog("We have a value: %s, int: %d", state, parseInt(state));
callback(null, state);
}
}
}.bind(this));
}.bind(this);
var setDispatch = function (value, callback, characteristic) {
if (this.enableSet == false) { callback() }
else {
var actionName = "set" + characteristic.displayName.replace(/\s/g, '')
this.debugLog("setDispatch:actionName:value: ", actionName, value);
var action = this.urls[actionName];
if (!action || !action.url) {
callback(null);
return;
}
var state = this.state;
var body = action.body;
var mappedValue = this.applyMappers(action.mappers, value);
var url = eval('`'+action.url+'`').replace(/{value}/gi, mappedValue);
if (body) {
body = eval('`'+body+'`').replace(/{value}/gi, mappedValue);
}
this.httpRequest(url, body, action.httpMethod, function(error, response, responseBody) {
if (error) {
this.log("SetState function failed: %s", error.message);
}
if (callback) {
if (error) {
callback(error);
} else {
// https://github.com/KhaosT/HAP-NodeJS/blob/master/lib/Characteristic.js#L34 setter callback takes only error as arg
callback();
}
}
}.bind(this));
}
}.bind(this);
// you can OPTIONALLY create an information service if you wish to override / the default values for things like serial number, model, etc.
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "Custom Manufacturer")
.setCharacteristic(Characteristic.Model, "HTTP Accessory Model")
.setCharacteristic(Characteristic.SerialNumber, "HTTP Accessory Serial Number");
var newService = new Service[this.service](this.name);
var counters = [];
var optionCounters = [];
for (var characteristicIndex in newService.characteristics)
{
var characteristic = newService.characteristics[characteristicIndex];
var compactName = characteristic.displayName.replace(/\s/g, '');
if (compactName in this.props) {
characteristic.setProps(this.props[compactName]);
}
counters[characteristicIndex] = makeHelper(characteristic);
characteristic.on('get', counters[characteristicIndex].getter.bind(this))
characteristic.on('set', counters[characteristicIndex].setter.bind(this));
}
for (var characteristicIndex in newService.optionalCharacteristics)
{
var characteristic = newService.optionalCharacteristics[characteristicIndex];
var compactName = characteristic.displayName.replace(/\s/g, '');
if (compactName in this.props) {
characteristic.setProps(this.props[compactName]);
}
if(this.optionCharacteristic.indexOf(compactName) == -1)
{
continue;
}
optionCounters[characteristicIndex] = makeHelper(characteristic);
characteristic.on('get', optionCounters[characteristicIndex].getter.bind(this))
characteristic.on('set', optionCounters[characteristicIndex].setter.bind(this));
newService.addCharacteristic(characteristic);
}
function makeHelper(characteristic) {
var timeoutID = null;
return {
getter: function (callback) {
var actionName = "get" + characteristic.displayName.replace(/\s/g, '');
if(actionName == "getName"){
callback (null, this.name);
return;
}
var action = this.urls[actionName];
if (this.forceRefreshDelay == 0 ) {
getDispatch(function(error,data){
this.debugLog(actionName + " getter function returned with data: " + data);
this.enableSet = false;
this.state[actionName] = data;
characteristic.setValue(data);
this.enableSet = true;
callback(error,data);
}.bind(this), action);
}
else {
callback(null,this.state[actionName] || characteristic.value);
if (typeof this.statusEmitters[actionName] != "undefined"){
this.debugLog(actionName + " returning cached data: " + this.state[actionName]);
return;
}
this.debugLog("creating new emitter for " + actionName);
this.statusEmitters[actionName] = pollingtoevent(function (done) {
this.debugLog("requested update for action " + actionName);
getDispatch(done,action);
}.bind(this), {
longpolling: true,
interval: this.forceRefreshDelay * 1000,
longpollEventName: actionName
});
this.statusEmitters[actionName].on(actionName, function (data)
{
this.debugLog(actionName + " emitter returned data: " + data);
this.enableSet = false;
if (['int', 'uint16', 'uint8', 'uint32', 'uint64'].includes(characteristic.props.format))
data = parseInt(data);
if ('float' == characteristic.props.format)
data = parseFloat(data);
this.state[actionName] = data;
characteristic.setValue(data);
this.enableSet = true;
}.bind(this));
this.statusEmitters[actionName].on("error", function(err, data) {
this.log("Emitter errored: %s. with data %j", err, data);
}.bind(this));
}
},
setter: function (value, callback) {
if (this.enableSet == false || this.setterDelay === 0) {
// no setter delay or internal set - do it immediately
this.debugLog("updating " + characteristic.displayName.replace(/\s/g, '') + " with value " + value);
setDispatch(value, callback, characteristic);
} else {
// making a request and setter delay is set
// optimistic callback calling if we have a delay
// this also means we won't be getting back any errors in homekit
callback();
this.debugLog("updating " + characteristic.displayName.replace(/\s/g, '') + " with value " + value + " in " + this.setterDelay + "ms");
if(timeoutID != null) {
clearTimeout(timeoutID);
this.debugLog("clearing timeout for setter " + characteristic.displayName.replace(/\s/g, ''));
}
timeoutID = setTimeout(function(){setDispatch(value, null, characteristic);timeoutID=null;}.bind(this), this.setterDelay);
}
}
};
}
return [informationService, newService];
}
};