๐Ÿ“/cloudIOT

AWS EC2 - MQTT ์ด์šฉํ•˜๊ธฐ

sssbin 2022. 5. 17. 01:33

 

โ˜… MQTT Message Broker ๋งŒ๋“ค๊ธฐ

 

1. EC2 ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ (์šฐ๋ถ„ํˆฌ๋กœ ํ•จ) ํ›„ ์ ‘์†

 -  ์ธ๋ฐ”์šด๋“œ ๊ทœ์น™ ์ถ”๊ฐ€: ์‚ฌ์šฉ์ž์ง€์ • TCP, TCP, 1883, 0.0.0.0/0

 

2. mosquitto ์„ค์น˜

$ sudo apt install mosquitto
$ sudo apt install mosquitto-clients

 

3. mosquitto ์‹คํ–‰

$ sudo systemctl start mosquitto
$ sudo systemctl enable mosquitto

 

4. pub & sub 

$ mosquitto_sub -d -t ํ† ํ”ฝ์ด๋ฆ„
$ mosquitto_pub -d -t ํ† ํ”ฝ์ด๋ฆ„ -m "๋ฉ”์‹œ์ง€"

-> ์ฐฝ ๋‘๊ฐœ ๋„์›Œ์„œ ํ•œ์ชฝ์—์„œ sub ๋จผ์ € ํ•˜๊ณ  ๋‹ค๋ฅธ์ชฝ์—์„œ pub

 

 


โ˜… MQTT ์‚ฌ์šฉํ•ด์„œ File Copy Program ๊ตฌํ˜„ํ•˜๊ธฐ

 

1. nodejs ์„ค์น˜

$ sudo apt-get install -y curl
$ sudo apt update
$ sudo apt install nodejs
$ sudo apt install npm

 

2. nodejs ๋ชจ๋“ˆ์— mqtt ์„ค์น˜

$ npm install mqtt -save

 

3. ์ฝ”๋“œ ์ž‘์„ฑ

/* FileSender.js */

// mqtt
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost:1883');

// topic
var topic = 'myTopic';

// file read
var fs = require('fs');
var fileName = 'file.txt';
var fileData = fs.readFileSync(fileName, 'utf-8');

// send
client.on('connect', function() {
        client.subscribe(topic);
        client.publish(topic, fileData);
});

client.on('message', function() {
        console.log(topic+" send!");
        client.end();
});
/* FileReceiver.js */

// mqtt
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://localhost:1883');

// topic
var topic = 'myTopic';

// saved filename
var fileName = 'fileRecv.txt';

// file system
var fs = require('fs');

// receive
client.on('connect', function () {
        client.subscribe(topic);
        console.log(topic+" receive!");
});

client.on('message', function (topic, message) {
        fs.writeFileSync(fileName, message);
        client.end();
});

 

4. ์‹คํ–‰

- ์ดˆ๊ธฐ ์ƒํƒœ

- ์ฐฝ ๋‘๊ฐœ ๋„์›Œ์„œ FileReceiver.js ์‹คํ–‰ -> FileSender.js ์‹คํ–‰

- ์‹คํ–‰ ํ›„

- ํŒŒ์ผ ์ž˜ ๋ณต์‚ฌ๋จ