-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (35 loc) · 956 Bytes
/
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
'use strict';
const mqtt = require('mqtt'),
url = require('url'),
Topics = require('./subscriptions/topics-aggregator.js');
const topics = Topics.getTopicsToBeSubscribed(),
mqtt_url = url.parse(process.env.CLOUDMQTT_URL || 'mqtt://localhost:1883'),
auth = (mqtt_url.auth || ':').split(':'),
mqtt_broker_url = `mqtts://${mqtt_url.host}`;
const options = {
port: mqtt_url.port,
clientId: `mqttjs_${
Math
.random()
.toString(16)
.substr(2, 8)
}`,
username: auth[0],
password: auth[1]
};
const client = mqtt.connect(mqtt_broker_url, options);
client.on('connect', () => {
//subscribe to the aggregated topics
for (let topic in topics) {
client.subscribe(topic);
console.log(`subscribed to ${topic}`);
}
client.publish('/all', 'mqtt-processor is up.');
});
client.on('message', (topicName, message) => {
//call respective callbacks
topics[topicName](message);
});
client.on('error', (err) => {
console.error(err);
});