-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
95 lines (78 loc) · 1.75 KB
/
main.js
File metadata and controls
95 lines (78 loc) · 1.75 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict'
const Axios = require('axios');
const Hue = require("node-hue-api");
const config = require('./config.json');
if (!config) {
console.error("Expecting config file");
return;
}
const { routerURI, watchDevice, username, request } = config;
let previousCurl = {};
let api = null;
let bridges = [];
const Status = {
ON: true,
OFF: false
}
const getBridges = () => {
Hue.upnpSearch().then((res) => {
bridges = res;
main();
}).done();
}
const light = (status) => {
if (api == null)
return;
api.setLightState(4, {"on": status})
.then(() => {
})
.fail((err) => {
console.error(err);
})
.done();
}
const doCurl = () => {
Axios.post(routerURI, request)
.then((response) => {
const data = response.data.result.status;
// watch on wifi
const connectedWIFI = data.wifi;
if (!connectedWIFI)
return {};
const wasHere = previousCurl.hasOwnProperty(watchDevice);
let devicePresent = false;
previousCurl = {};
for (var i = 0; i < connectedWIFI.length; ++i) {
if (connectedWIFI[i].Key === watchDevice) {
devicePresent = true;
previousCurl[watchDevice] = true;
break;
}
}
if (wasHere && !devicePresent) {
// Left, do not do anything
light(Status.OFF);
} else if (!wasHere && devicePresent) {
// Device connected
light(Status.ON);
} else {
// Nothing changed
}
})
.catch((error) => {
console.error(error);
})
;
}
const regularCurl = () => {
setInterval(() => {
doCurl();
}, 10000);
}
const main = () => {
if (bridges.length) {
api = new Hue.HueApi(bridges[0].ipaddress, username);
}
regularCurl();
};
getBridges();