-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
executable file
·87 lines (68 loc) · 2.91 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
/* eslint-env node, es6 */
var HomebridgeAPI;
module.exports = function(homebridge) {
HomebridgeAPI = homebridge;
homebridge.registerPlatform("homebridge-info", "Info", InfoPlatform);
}
function InfoPlatform(log, config) {
// Set defaults, if not defined in config.json.
if (!config.updateCheckFrequency) {
config.updateCheckFrequency = 10000;
}
if (!config.updateFrequency) {
config.updateFrequency = 5000;
}
function handleRequest(req, res) {
log("handleAPIRequest: " + req.url);
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
var path = require('url').parse(req.url).pathname;
switch (path) {
case '/api/info':
infoOut(req, res);
break;
default:
res.statusCode = 404;
res.end();
}
}
var path = require('path');
var BridgeInfoEmitter = require(path.resolve(require.resolve('./lib/HomebridgeInfoEmitter/BridgeInfoEmitter.js')));
var infoEmitter = BridgeInfoEmitter(config, HomebridgeAPI);
infoEmitter.start();
function infoOut(req, res) {
res.setHeader("Content-Type", "text/event-stream");
// Send the current data to the client so he doesn't have to
// wait for the next update before he get's something.
res.write("data: " + JSON.stringify({'type': 'bridgeInfo', 'data': infoEmitter.initialInfo()}) + "\n\n");
res.write("data: " + JSON.stringify({'type': 'bridgeUpdateAvailable', 'data': infoEmitter.lastUpdateCheck()}) + "\n\n");
// From here we'll write whenever the emitter has something to say...
infoEmitter.on('bridgeInfo', function(data) {
res.write("data: " + JSON.stringify({'type': 'bridgeInfo', 'data': data}) + "\n\n");
});
infoEmitter.on('bridgeUpdateAvailable', function(data) {
res.write("data: " + JSON.stringify({'type': 'bridgeUpdateAvailable', 'data': data}) + "\n\n");
});
}
// Launches the webserver and transmits the website by concatenating the precreated markup
var http = require('http');
var server = http.createServer(handleRequest);
server.listen(config.port, function() {
var os = require('os');
var ifaces = os.networkInterfaces();
Object.keys(ifaces).forEach(function (ifname) {
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
return;
}
log("is listening on: http://%s:%s", iface.address, config.port);
});
});
});
}
InfoPlatform.prototype.accessories = function(callback) {
this.accessories = [];
callback(this.accessories);
}