forked from timroemisch/mqtt-s7-connector
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmqtt_handler.js
45 lines (36 loc) · 886 Bytes
/
mqtt_handler.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
const mqtt = require('mqtt');
let connected = false;
const isConnected = function () {
return connected;
};
const setup = function (config, onMessage, initDevices) {
// connect to mqtt
const client = mqtt.connect(config["host"], {
username: config["user"],
password: config["password"],
rejectUnauthorized: config["rejectUnauthorized"]
});
// successful connected :)
client.on('connect', function () {
console.log('MQTT Connected');
connected = true;
initDevices();
});
client.on('disconnect', function () {
console.log('MQTT Disconnected');
connected = false;
});
client.on('close', function () {
console.log('MQTT Closed');
connected = false;
});
// handle incoming messages
client.on('message', function (topic, msg) {
onMessage(topic, msg.toString());
});
return client;
};
module.exports = {
setup: setup,
isConnected: isConnected
}