forked from crashtestoz/homebridge-http-lux
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
78 lines (68 loc) · 2.53 KB
/
index.js
File metadata and controls
78 lines (68 loc) · 2.53 KB
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
var Service, Characteristic;
var request = require('request');
const DEF_MIN_LUX = 0,
DEF_MAX_LUX = 800,
DEF_TIMEOUT = 5000;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-http-lux2", "HttpLux2", HttpLux2);
}
function HttpLux2(log, config) {
this.log = log;
// url info
this.url = config["url"];
this.http_method = config["http_method"] || "GET";
this.name = config["name"];
this.manufacturer = config["manufacturer"] || "@crashtestoz";
this.model = config["model"] || "nodeMCU multi sensor DIY";
this.serial = config["serial"] || "20181011";
this.timeout = config["timeout"] || DEF_TIMEOUT;
this.minLux = config["min_lux"] || DEF_MIN_LUX;
this.maxLux = config["max_lux"] || DEF_MAX_LUX;
}
HttpLux2.prototype = {
getState: function (callback) {
var ops = {
uri: this.url,
method: this.http_method,
timeout: this.timeout
};
//Parse the request sent via http
this.log('Requesting light level on "' + ops.uri + '", method ' + ops.method);
request(ops, (error, res, body) => {
var value = null;
if (error) {
this.log('HTTP bad response (' + ops.uri + '): ' + error.message);
} else {
try {
value = JSON.parse(body).lightlevel;
if (value < this.minLux || value > this.maxLux || isNaN(value)) {
throw "Invalid value received";
}
this.log('HTTP successful response: ' + body);
} catch (parseErr) {
this.log('Error processing received information: ' + parseErr.message);
error = parseErr;
}
}
callback(error, value);
});
},
getServices: function () {
this.informationService = new Service.AccessoryInformation();
this.informationService
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, this.model)
.setCharacteristic(Characteristic.SerialNumber, this.serial);
this.lightLevelService = new Service.LightSensor(this.name);
this.lightLevelService
.getCharacteristic(Characteristic.CurrentAmbientLightLevel)
.on('get', this.getState.bind(this))
.setProps({
minValue: this.minLux,
maxValue: this.maxLux
});
return [this.informationService, this.lightLevelService];
}
};