MqttModule.js
1.37 KB
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
const mqtt = require('mqtt');
const clientList = [];
exports.mqttOn = async (hosting) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
if(filterIndex === -1) {
const client = mqtt.connect(hosting);
clientList.push(client);
client.on('connect', () => {
console.log('Client connected: ', client.connected);
});
return client;
} else {
return clientList[filterIndex];
};
};
exports.mqttSubscribe = (client, topic, func) => {
client.subscribe(topic);
client.on('message', async (topic, message, packet) => {
const result = await func(topic, message.toString());
this.mqttPublishMessage(client, result);
});
};
exports.mqttPublishMessage = (client, { topic, message }) => {
client.publish(topic, message, () => {});
};
exports.mqttOff = (hosting) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
if(filterIndex !== -1) {
clientList[filterIndex].end();
clientList.splice(filterIndex, 1);
}
}