-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
79 lines (71 loc) · 2.81 KB
/
worker.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
//initialize http server
var http = require('http');
var url = require('url');
//initialize mqtt server
var mqtt = require('mqtt')
var client = mqtt.connect(require('./creds.json'))
//list of registered topics
var topics = require('./topics.json')
//import device names
var devname = require('./devname.json')
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
//get parameters
var queryData = url.parse(request.url, true).query;
response.writeHead(200, { "Content-Type": "text/plain" });
if (queryData.devID) {
response.end(queryData.action);
}
//in case of an available query set to something like this
switch (queryData.devID) {
case devname.dev1:
if (queryData.action == 'on' || queryData.action == '1') {
client.publish(topics.dev1, '1', { retain: true })
} else if (queryData.action == 'off' || queryData.action == '0') {
client.publish(topics.dev1, '0', { retain: true })
} else {
//do nothing
}
break;
case devname.dev2:
if (queryData.action == 'on' || queryData.action == '1') {
client.publish(topics.dev2, '1', { retain: true })
} else if (queryData.action == 'off' || queryData.action == '0') {
client.publish(topics.dev2, '0', { retain: true })
} else {
//do nothing
}
break;
case devname.dev3:
if (queryData.action == 'on' || queryData.action == '1') {
client.publish(topics.dev3, '1', { retain: true })
} else if (queryData.action == 'off' || queryData.action == '0') {
client.publish(topics.dev3, '0', { retain: true })
} else {
//do nothing
}
break;
case devname.dev4:
if (queryData.action == 'on' || queryData.action == '1') {
client.publish(topics.dev4, '1', { retain: true })
} else if (queryData.action == 'off' || queryData.action == '0') {
client.publish(topics.dev4, '0', { retain: true })
} else {
//do nothing
}
break;
case devname.dev5:
if (queryData.action == 'on' || queryData.action == '1') {
client.publish(topics.dev5, '1', { retain: true })
} else if (queryData.action == 'off' || queryData.action == '0') {
client.publish(topics.dev5, '0', { retain: true })
} else {
//do nothing
}
break;
}
});
//finally start http server and accept commands
server.listen(8000, () => {
console.log("Server Started at localhost port 8000")
});