MQTT 是輕量級的、靈活的物聯網消息交換和數據傳遞協議,致力於爲 IoT 開發人員實現靈活性與硬件/網絡資源的平衡。
ESP32 是 ESP8266 的升級版本,除了Wi-Fi模塊,該模塊還包含藍牙4.0模塊。雙核CPU工作頻率爲80至240 MHz,包含兩個Wi-Fi和藍牙模塊以及各種輸入和輸出引腳, ESP32 是物聯網項目的理想選擇。
在此項目中我們將實現 ESP32 連接到 EMQ X MQTT Cloud 運營和維護的 免費公共 MQTT 服務器,並使用 Arduino IDE 來對 ESP32 進行編程。 EMQ X Cloud 是由 EMQ 推出的安全的 MQTT 物聯網雲服務平臺,它提供一站式運維代管、獨有隔離環境的 MQTT 5.0 接入服務。
所需物聯網組件
- ESP32
- Arduino IDE
- MQTT 5.0 客戶端工具 - MQTT X
- 部署在 EMQ X Cloud 上的免費的公共 MQTT 服務器
- Broker: broker-cn.emqx.io
- TCP Port: 1883
- Websocket Port: 8083
Arduino 配置
安裝 ESP32 開發板
點擊 工具 -> 開發板 -> 開發板管理 -> 搜索 ESP32 -> 點擊安裝
安裝 PubSub client
項目 -> 加載庫 -> 管理庫... -> 搜索 PubSubClient -> 安裝 PubSubClient by Nick O’Leary
ESP32 Pub/Sub 示意圖
ESP32 代碼編寫
分步驟連接 MQTT
-
首先我們將導入 WiFi 和 PubSubClient 庫,ESP8266WiFi 庫能夠將 ESP32 連接到 Wi-Fi 網絡,PubSubClient 庫能使 ESP32 連接到 MQTT 服務器發佈消息及訂閱主題。
#include <WiFi.h> #include <PubSubClient.h>
-
設置 Wi-Fi 名稱和密碼,以及 MQTT 服務器連接地址和端口,並這是 topic 爲 "esp32/test"
// WiFi const char *ssid = "mousse"; // Enter your WiFi name const char *password = "qweqweqwe"; // Enter WiFi password // MQTT Broker const char *mqtt_broker = "broker.emqx.io"; const char *topic = "esp32/test"; const char *mqtt_username = "emqx"; const char *mqtt_password = "public"; const int mqtt_port = 1883;
-
打開一個串行連接,以便於輸出程序的結果並且連接到 Wi-Fi 網絡
// Set software serial baud to 115200; Serial.begin(115200); // connecting to a WiFi network WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); }
-
使用 PubSubClient 連接到公共 MQTT Broker。
client.setServer(mqtt_broker, mqtt_port); client.setCallback(callback); while (!client.connected()) { String client_id = "esp32-client-"; client_id += String(WiFi.macAddress()); Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str()); if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) { Serial.println("Public emqx mqtt broker connected"); } else { Serial.print("failed with state "); Serial.print(client.state()); delay(2000); } }
-
MQTT 服務器連接成功後,ESP32 將向 MQTT 服務器
esp/test
發佈消息和訂閱esp/test
主題消息。// publish and subscribe client.publish(topic, "Hi EMQ X I'm ESP32 ^^"); client.subscribe(topic);
-
設置回調函數將主題名稱打印到串行端口並打印從
esp32/test
主題接收的消息。void callback(char *topic, byte *payload, unsigned int length) { Serial.print("Message arrived in topic: "); Serial.println(topic); Serial.print("Message:"); for (int i = 0; i < length; i++) { Serial.print((char) payload[i]); } Serial.println(); Serial.println("-----------------------"); }
完整代碼
#include <WiFi.h>
#include <PubSubClient.h>
// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp32/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "Hi EMQ X I'm ESP32 ^^");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
運行和測試
-
使用 Arduino 上傳完整代碼,並將 esp32 上電
-
打開串口監視器,選擇 115200 波特率,查看 ESP32 連接情況
-
使用 MQTT X 客戶端 連接到公共 MQTT 服務器, 並向 ESP32 發送消息
總結
至此,我們已成功使 ESP32 連接到 EMQ X Cloud 提供的公共 MQTT 服務器。 在本項目中我們簡單的將 ESP32 連接到 MQTT 服務器,這只是 ESP32 較爲基礎的能力之一,ESP32 其實還能與各類物聯網傳感器相連,並將傳感器數據上報至 MQTT 服務器。
接下來我們將會陸續發佈更多關於物聯網開發及 ESP32 的相關文章,敬請關注。
版權聲明: 本文爲 EMQ 原創,轉載請註明出處。
原文鏈接:https://www.emqx.com/zh/blog/esp32-connects-to-the-free-public-mqtt-broker