-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqttclient.js
44 lines (37 loc) · 1.3 KB
/
mqttclient.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
const mqtt = require('mqtt');
const assetBuilder = require('./assetbuilder');
const os = require('os');
const chalk = require('chalk');
function startStream(streamConfig) {
const connectionOptions = {
username: os.hostname() + '-' + os.platform() + '-' + os.arch(),
password: streamConfig.apikey
}
const broker = assetBuilder.makeURL(streamConfig.env);
const streamTopic = assetBuilder.makeTopic(streamConfig.type, streamConfig.source);
const client = mqtt.connect(broker, connectionOptions);
client.on('connect', function(connack) {
console.log(connack);
client.subscribe(streamTopic, function (error, granted) {
if (!error) {
console.log(granted);
if (granted[0].qos > 100)
client.emit('error', chalk.red(`✘ Invalid MQTT topic`))
} else {
console.error(error);
}
});
});
client.on('error', function(error) {
console.error(error);
process.exit(1);
});
client.on('message', function(topic, message, packet) {
const jsonString = message.toString();
const json = JSON.parse(jsonString);
console.log(json);
});
}
module.exports = {
startStream: startStream
};