-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
93 lines (77 loc) · 3.47 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
const http = require('http');
var Service, Characteristic, ContactState;
module.exports = function (homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
ContactState = homebridge.hap.Characteristic.ContactSensorState;
homebridge.registerAccessory("homebridge-http-contact-sensor", "ContactSensor", ContactSensorAccessory);
};
function ContactSensorAccessory(log, config) {
this.log = log;
this.name = config.name;
this.pollInterval = config.pollInterval;
this.statusUrl = config.statusUrl || null;
if (this.statusUrl == null) {
this.log("statusUrl is required");
process.exit(1);
}
this.isClosed = true;
this.wasClosed = true;
this.service = new Service.ContactSensor(this.name);
setTimeout(this.monitorContactState.bind(this), this.pollInterval);
};
ContactSensorAccessory.prototype = {
identify: function (callback) {
callback(null);
},
monitorContactState: function () {
this.isDoorClosed((state) => {
this.isClosed = state;
if (this.isClosed != this.wasClosed) {
this.wasClosed = this.isClosed;
this.service.getCharacteristic(Characteristic.ContactSensorState).setValue(this.isClosed);
}
setTimeout(this.monitorContactState.bind(this), this.pollInterval);
})
},
isDoorClosed: function (callback) {
if (this.statusUrl != null) {
http.get(this.statusUrl, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
callback(parseInt(data));
});
}).on("error", (err) => {
console.error("Error: " + err.message);
callback();
});
}
},
getContactSensorState: function (callback) {
this.isDoorClosed((state) => {
this.isClosed = state;
this.log("getContactSensorState: ", this.isClosed);
callback(null, this.isClosed);
});
},
getName: function (callback) {
callback(null, this.name);
},
getServices: function () {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, "ContactSensor")
.setCharacteristic(Characteristic.Model, "FrontDoor")
.setCharacteristic(Characteristic.SerialNumber, "Version 1.0.3");
this.service
.getCharacteristic(Characteristic.ContactSensorState)
.on('get', this.getContactSensorState.bind(this));
this.service
.getCharacteristic(Characteristic.Name)
.on('get', this.getName.bind(this));
return [informationService, this.service];
}
};