Showing
1 changed file
with
25 additions
and
9 deletions
1 | const mqtt = require('mqtt'); | 1 | const mqtt = require('mqtt'); |
2 | +const clientList = []; | ||
2 | 3 | ||
3 | -exports.mqttOn = (hosting) => { | 4 | +exports.mqttOn = async (hosting) => { |
4 | - const client = mqtt.connect(hosting); | 5 | + const filterIndex = clientList.findIndex(client => { |
5 | - client.on('connect', () => { | 6 | + return (client.options.clientId === hosting.clientId |
6 | - console.log('Connected : ', client.connected) | 7 | + && client.options.host === hosting.host |
8 | + && client.options.port === hosting.port) | ||
7 | }); | 9 | }); |
8 | 10 | ||
9 | - return client; | 11 | + if(filterIndex === -1) { |
10 | -} | 12 | + const client = mqtt.connect(hosting); |
13 | + clientList.push(client); | ||
14 | + client.on('connect', () => { | ||
15 | + console.log('Client connected: ', client.connected); | ||
16 | + }); | ||
17 | + | ||
18 | + return client; | ||
19 | + } else { | ||
20 | + return clientList[filterIndex]; | ||
21 | + }; | ||
22 | +}; | ||
11 | 23 | ||
12 | exports.mqttSubscribe = (client, topic) => { | 24 | exports.mqttSubscribe = (client, topic) => { |
13 | client.subscribe(topic); | 25 | client.subscribe(topic); |
14 | client.on('message', (topic, message, packet) => { | 26 | client.on('message', (topic, message, packet) => { |
15 | - console.log('topic : ', topic); | 27 | + console.log('\x1b[1;37mtopic : ', topic, '\x1b[0m'); |
16 | - console.log('message : ', message.toString()); | 28 | + console.log('\x1b[1;37mmessage : ', message.toString(), '\x1b[0m', '\n'); |
17 | }); | 29 | }); |
18 | -} | ||
... | \ No newline at end of file | ... | \ No newline at end of file |
30 | +}; | ||
31 | + | ||
32 | +exports.mqttPublishMessage = (client, topic, message) => { | ||
33 | + client.publish(topic, message, () => {}); | ||
34 | +}; | ||
... | \ No newline at end of file | ... | \ No newline at end of file | ... | ... |
-
Please register or login to post a comment