사양
OS : Windows 10 x64
MQTT
MQTT는 ISO 표준 발행-구독 기반의 메시징 프로토콜이다. TCP/IP 프로토콜 위에서 동작한다. "작은 코드 공간"이 필요하거나 네트워크 대역폭이 제한되는 원격 위치와의 연결을 위해 설계되어 있다. 발행-구독 메시징 패턴은 메시지 브로커가 필요하다.
MQTT 사용을 위해 대표적인 메시지 브로커인 모스키토(Mosquitto) 브로커를 설치 합니다.
모스키토 홈페이지에서 설치 파일을 다운로드
https://mosquitto.org/download/
Download
Source mosquitto-2.0.8.tar.gz (319kB) (GPG signature) Git source code repository (github.com) Older downloads are available at https://mosquitto.org/files/ Binary Installation The binary packages li
mosquitto.org
[ Windows Binary ]
이전 버전들에서는 OpenSSL 등 의존성 프로그램들을 따로 설치해야 했지만 지금은 모스키토 바이너리만 설치하면 작동 한다.
Mosquitto 실행 테스트
모스키토 설치 경로에서 명령 창을 열고 아래 명령을 실행 합니다.
"NAME" 따옴표 안에 이름으로 토픽을 구독(Subscribe)하겠다는 명령어 입니다.
[명령 프롬프트 1]
mosquitto_sub -t "MY_TOPIC"
새로운 명령창을 열어 해당 토픽에 메시지를 발행(Publish) 합니다.
[명령 프롬프트 2]
mosquitto_pub -t "MY_TOPIC" -m HELLO
[명령 프롬프트 1]
C:\Program Files\mosquitto>mosquitto_sub.exe -t MY_TOPIC
HELLO
구독하고 있는 명령창에 HELLO가 표시되면 정상적으로 메시지가 전송된 것으로 보시면 됩니다.
아두이노에서 MQTT 연결 하기전 설정 사항
1) mosquitto.conf 메모장으로 열고 아래와 같이 수정하세요
listener 1883
allow_anonymous true
2) 서비스 -> mosquitto Broker 재시작
* 실행 -> firewall.cpl
* 고급설정
3) 인바운드 : 1883 포트 추가
* cmd 창 관리자모드로 실행후 : mosquitto -c mosquitto.conf -v
브로커 서버 동작유무를 확인해 볼수 있어요.
모스키토 첫 설치 후 서비스 시작 문제
C:\Program Files\mosquitto>mosquitto_sub.exe -t MY_TOPIC
"Error: 대상 컴퓨터에서 연결을 거부했으므로 연결하지 못했습니다."
설치가 완료되면 모스키토가 윈도우 서비스로 등록이 되지만 실행 상태는 아니기 때문에 작업 관리자를 통하여 서비스를 실행 시켜 줘야 한다.
ESP8266 DHT11 MQTT(Mosquitto) 연결테스트
//DHT11 연결포트 : D5
//DHT_HUMIDITY
#include "DHTesp.h"
DHTesp dht;
String packet;
unsigned long lastSend = 0;
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
// MQTT 설정
const char* ssid = "SSID"; //WIFI 공유기 이름
const char* password = "PW"; //WIFI 패스워드
const char* mqtt_server = "19.169.0.6"; //내컴퓨터 IP주소 CMD에서 ipconfig로 확인할수 있어요
const char* mqtt_topic = "MY"; //subscribe 할 기본 TOPIC
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
////////////////////////////////////
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
String msg = "";
for (int i = 0; i < length; i++) {
msg +=(char)payload[i];
}
Serial.println(msg);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("outTopic", "hello world");
// ... and resubscribe
client.subscribe(mqtt_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
dht.setup(D5, DHTesp::DHT22); // D5
//SERIAL BAUDRATE
/*
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
#if ESP8266
Serial.begin(115200, SERIAL_8N1, SERIAL_TX_ONLY);
#else // ESP8266
Serial.begin(115200, SERIAL_8N1);
#endif // ESP8266
*/
Serial.begin(115200);
// MQTT SETUP
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void Get_th(){
delay(dht.getMinimumSamplingPeriod());
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
packet = "TEMP: " + String(temperature) + "*C \n" + "HUMIDITY: " + String(humidity) + "%" ;
client.publish("sensor/th", (char*) packet.c_str());
client.publish("sensor/t", (char*) String(temperature).c_str());
client.publish("sensor/h", (char*) String(humidity).c_str());
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if ( millis() - lastSend > 1000 ) { // Update and send only after 1 seconds
Get_th();
lastSend = millis();
}
}
MQTT subscribe 확인 (온도 / 습도값 확인방법)
mosquitto_sub -t "sensor/th" -t "sensor/t" -t "sensor/h"
cmd 에서 위와같이 입력 하세요
온도 / 습도값이 잘들어 오고 있습니다.
끝.