-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenServer.js
102 lines (89 loc) · 2.43 KB
/
openServer.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
94
95
96
97
98
99
100
101
102
var http = require('http'), express = require('express');
var methodOverride = require('method-override');
var querystring = require('querystring');
var mqtt = require('mqtt'), url = require('url');
/* Global Params. */
var connectedToBroker = false;
var connectedToClient = false;
var genericTimer = null;
var ConnectionCheckInterval = 5000;
var httpPort = 80;
var mqttUser = 'USER';
var mqttPass = 'PASS';
var mqttTopic = 'TOPIC';
var mqttAddress = 'mqtt://vestelmqtt.xyz:1883';
var latestDisconnection = "N/A";
var port = process.env.PORT || httpPort;
var app = express();
app.use(methodOverride());
/* Start HTTP Server */
var server = http.createServer(app).listen(port, function() {
console.log("HTTP Server listening to %d within %s environment",
port, app.get('env'));
});
/* Configuring MQTT client. */
var options = {username: mqttUser, password: mqttPass};
var mqtt_client = mqtt.connect(mqttAddress, options);
/* MQTT events. */
mqtt_client.on('connect', function() {
console.log("MQTT connected.");
connectedToBroker = true;
mqtt_client.subscribe(mqttTopic);
});
mqtt_client.on('error', function(err) {
connectedToBroker = false;
console.log("MQTT Connection error!! " + err);
});
mqtt_client.on('offline', function() {
connectedToBroker = false;
console.log("MQTT Client is offline!");
});
mqtt_client.on('message', function(topic, message, packet) {
if(topic == mqttTopic)
{
connectedToClient = true;
setTimer();
}
});
/* HTTP handling. */
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/', function(req, res){
if(connectedToBroker == true)
{
if(connectedToClient == true)
{
res.send("Geldi:) <br/><br/> Son kesinti : " + latestDisconnection);
}
else
{
res.send("Gelmedi:( <br/><br/> Son kesinti : " + latestDisconnection);
}
}
else
{
res.send("System status : DOWN!");
}
});
/* Timeout functions. */
function connectionDroppedCb()
{
connectedToClient = false;
latestDisconnection = new Date();
}
function clearTimer()
{
clearInterval(genericTimer);
genericTimer = null;
}
function setTimer()
{
if(genericTimer != null)
{
clearTimer();
}
genericTimer = setInterval(connectionDroppedCb, ConnectionCheckInterval);
}