forked from petkov/http_to_mqtt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
173 lines (142 loc) · 4.28 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
var settings = {
mqtt: {
host: process.env.MQTT_HOST || '',
user: process.env.MQTT_USER || '',
password: process.env.MQTT_PASS || '',
clientId: process.env.MQTT_CLIENT_ID || null
},
keepalive: {
topic: process.env.KEEP_ALIVE_TOPIC || 'keep_alive',
message: process.env.KEEP_ALIVE_MESSAGE || 'keep_alive'
},
debug: process.env.DEBUG_MODE || false,
auth_key: process.env.AUTH_KEY || '',
http_port: process.env.PORT || 5000
}
var mqtt = require('mqtt');
var express = require('express');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
function getMqttClient() {
var options = {
username: settings.mqtt.user,
password: settings.mqtt.password
};
if (settings.mqtt.clientId) {
options.clientId = settings.mqtt.clientId
}
return mqtt.connect(settings.mqtt.host, options);
}
var mqttClient = getMqttClient();
app.set('port', settings.http_port);
app.use(bodyParser.json());
function logRequest(req, res, next) {
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress;
var message = 'Received request [' + req.originalUrl +
'] from [' + ip + ']';
if (settings.debug) {
message += ' with payload [' + JSON.stringify(req.body) + ']';
} else {
message += '.';
}
console.log(message);
next();
}
function authorizeUser(req, res, next) {
if (settings.auth_key && req.body['key'] != settings.auth_key) {
console.log('Request is not authorized.');
res.sendStatus(401);
}
else {
next();
}
}
function checkSingleFileUpload(req, res, next) {
if (req.query.single) {
var upload = multer().single(req.query.single);
upload(req, res, next);
}
else {
next();
}
}
function checkMessagePathQueryParameter(req, res, next) {
if (req.query.path) {
req.body.message = req.body[req.query.path];
}
next();
}
function checkTopicQueryParameter(req, res, next) {
if (req.query.topic) {
req.body.topic = req.query.topic;
}
next();
}
function ensureTopicSpecified(req, res, next) {
if (!req.body.topic) {
res.status(500).send('Topic not specified');
}
else {
next();
}
}
app.get('/keep_alive/', logRequest, function (req, res) {
mqttClient.publish(settings.keepalive.topic, settings.keepalive.message);
res.sendStatus(200);
});
app.post('/post/', logRequest, authorizeUser, checkSingleFileUpload, checkMessagePathQueryParameter, checkTopicQueryParameter, ensureTopicSpecified, function (req, res) {
mqttClient.publish(req.body['topic'], req.body['message']);
res.sendStatus(200);
});
app.get('/subscribe/', logRequest, authorizeUser, function (req, res) {
var topic = req.query.topic;
if (!topic) {
res.status(500).send('topic not specified');
}
else {
// get a new mqttClient
// so we dont constantly add listeners on the 'global' mqttClient
var mqttClient = getMqttClient();
mqttClient.on('connect', function () {
mqttClient.subscribe(topic);
});
mqttClient.on('message', function (t, m) {
if (t === topic) {
res.write(m);
}
});
req.on("close", function () {
mqttClient.end();
});
req.on("end", function () {
mqttClient.end();
});
}
});
const server = app.listen(app.get('port'), function () {
console.log('Node app is running on port', app.get('port'));
});
// The signals we want to handle
// NOTE: although it is tempting, the SIGKILL signal (9) cannot be intercepted and handled
var signals = {
'SIGHUP': 1,
'SIGINT': 2,
'SIGTERM': 15
};
// Do any necessary shutdown logic for our application here
const shutdown = (signal, value) => {
console.log("shutdown!");
server.close(() => {
console.log(`server stopped by ${signal} with value ${value}`);
process.exit(128 + value);
});
};
// Create a listener for each of the signals that we want to handle
Object.keys(signals).forEach((signal) => {
process.on(signal, () => {
console.log(`process received a ${signal} signal`);
shutdown(signal, signals[signal]);
});
});