MqttModule.js
1.67 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
48
49
50
51
52
53
54
55
56
57
58
const mqtt = require('mqtt')
const clientList = []
exports.mqttOn = async (hosting, func) => {
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('Hub connected: ', client.connected)
})
client.on('message', async (topic, message) => {
const result = await func(topic, message.toString())
console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m')
this.mqttPublishMessage(client, result)
})
return client
}
return clientList[filterIndex]
}
exports.mqttSubscribe = (client, topic) => {
client.subscribe(topic)
}
exports.mqttPublishMessage = (client, { topic, message }) => {
client.publish(topic, message, () => {
console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m')
})
}
exports.mqttUnsubscribe = (client, topic) => {
client.unsubscribe(topic, () => {
console.log('unsubscribe', topic)
})
}
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)
}
}