-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
53 lines (42 loc) · 1.31 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
'use strict'
const restify = require('restify')
const mqtt = require('mqtt')
const brokerUrl = process.env.BROKER_URL || 'mqtt://test.mosquitto.org'
const topicBase = process.env.TOPIC_BASE || ''
const httpPort = process.env.HTTP_PORT || 9001
const mqttUsername = process.env.MQTT_USERNAME
const mqttPassword = process.env.MQTT_PASSWORD
const server = restify.createServer();
server.use(restify.plugins.bodyParser({
requestBodyOnGet: true
}));
server.get('*', controller);
server.post('*', controller);
function startHttpServer() {
server.listen(httpPort, function() {
console.log('%s listening at %s', server.name, server.url);
});
}
console.log(`connect mqtt client to ${brokerUrl}`)
const mqttClient = mqtt.connect(brokerUrl, {
username: mqttUsername,
password: mqttPassword
})
mqttClient.once('connect', () => {
startHttpServer()
})
mqttClient.once('close', () => {
process.exit(1) // restart docker container then
})
function controller(req, res, next) {
const topic = `${topicBase}${req.path().substring(1)}`
let message = req.body || null
if (typeof message === 'object') {
message = JSON.stringify(message)
}
mqttClient.publish(topic, message, () => {
console.log(new Date(), `published: ${topic}`)
res.send(req.body);
next();
})
}