PubSubClient 라이브러리를 설치한다. ( 라이브러리 관리에서 검색하면 나온다)
MQTT사용을 위한 기본 베이스( 라이브러리 예제에 있음) | |
#include <ESP8266WiFi.h> // Wemos 사용 #include <PubSubClient.h> // MQTT const char* ssid = "........"; // WIFI 이름 const char* password = "..........."; // WIFI 비밀번호 const char* mqtt_server = "broker.mqtt-dashboard.com"; //무료 broker 서버중 하나 WiFiClient espClient; PubSubClient client(espClient); unsigned long lastMsg = 0; #define MSG_BUFFER_SIZE (50) char msg[MSG_BUFFER_SIZE]; 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("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); if ((char)payload[0] == '1') digitalWrite(BUILTIN_LED, LOW); // 전달 받은 메세지 처리 else digitalWrite(BUILTIN_LED, HIGH); } void reconnect() { 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"); client.subscribe("inTopic"); // 구독 설정 inTopic은 원하는 것으로 설정 } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void setup() { pinMode(BUILTIN_LED, OUTPUT); Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } int value = 0; void loop() { if (!client.connected()) { reconnect(); } client.loop(); unsigned long now = millis(); // delay함수를 사용하지 말자 if (now - lastMsg > 2000) { lastMsg = now; ++value; snprintf (msg, MSG_BUFFER_SIZE, "# %d", value); Serial.print("Publish message: "); Serial.println(msg); client.publish("outTopic", msg); // 발행하기 outTopic은 실제 사용할 것으로 변경 } } |
실제 사용한 소스 - 1번 2번 3번으로 변경하여 3개의 wemos 에 업로드 했음 | |
#include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "-----------------------"; const char* password = "------------------"; const char* mqtt_server = "broker.mqtt-dashboard.com"; WiFiClient espClient; PubSubClient client(espClient); unsigned long lastMsg = 0; #define MSG_BUFFER_SIZE (50) char msg[MSG_BUFFER_SIZE]; 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("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); if ((char)payload[0] == '1') digitalWrite(BUILTIN_LED, LOW); else digitalWrite(BUILTIN_LED, HIGH); } void reconnect() { 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"); client.publish("토픽이름1", "Wemos mini 1번"); client.subscribe("토픽이름/bt01"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void setup() { pinMode(BUILTIN_LED, OUTPUT); Serial.begin(115200); setup_wifi(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } int value = 0; void loop() { if (!client.connected()) { reconnect(); } client.loop(); unsigned long now = millis(); if (now - lastMsg > 2000) { lastMsg = now; ++value; snprintf (msg, MSG_BUFFER_SIZE, "Wemos mini 1번 :%d", value); Serial.print("Publish message: "); Serial.println(msg); client.publish("토픽이름1", msg); } } |
'프로젝트 > MQTT 다중연결' 카테고리의 다른 글
C#에서 MQTT프로그램 만들기 (0) | 2022.09.14 |
---|---|
MQTT 다중 연결 (0) | 2022.09.13 |