박권수

feat. mqtt logic going dev

1 const mqtt = require('mqtt'); 1 const mqtt = require('mqtt');
2 +const clientList = [];
2 3
3 -exports.mqttOn = (hosting) => { 4 +exports.mqttOn = async (hosting) => {
5 + const filterIndex = clientList.findIndex(client => {
6 + return (client.options.clientId === hosting.clientId
7 + && client.options.host === hosting.host
8 + && client.options.port === hosting.port)
9 + });
10 +
11 + if(filterIndex === -1) {
4 const client = mqtt.connect(hosting); 12 const client = mqtt.connect(hosting);
13 + clientList.push(client);
5 client.on('connect', () => { 14 client.on('connect', () => {
6 - console.log('Connected : ', client.connected) 15 + console.log('Client connected: ', client.connected);
7 }); 16 });
8 17
9 return client; 18 return client;
10 -} 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
......