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

  1. 首先咱们将导入 WiFiPubSubClient 库,ESP8266WiFi 库可能将 ESP32 连贯到 Wi-Fi 网络,PubSubClient 库能使 ESP32 连贯到 MQTT 服务器公布音讯及订阅主题。

    #include <WiFi.h>#include <PubSubClient.h>
  2. 设置 Wi-Fi 名称和明码,以及 MQTT 服务器连贯地址和端口,并这是 topic 为 "esp32/test"

    // WiFiconst char *ssid = "mousse"; // Enter your WiFi nameconst char *password = "qweqweqwe";  // Enter WiFi password// MQTT Brokerconst 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;
  3. 关上一个串行连贯,以便于输入程序的后果并且连贯到 Wi-Fi 网络

    // Set software serial baud to 115200;Serial.begin(115200);// connecting to a WiFi networkWiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.println("Connecting to WiFi..");}
  4. 应用 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);    }}
  5. MQTT 服务器连贯胜利后,ESP32 将向 MQTT 服务器 esp/test 公布音讯和订阅 esp/test 主题音讯。

    // publish and subscribeclient.publish(topic, "Hi EMQ X I'm ESP32 ^^");client.subscribe(topic);
  6. 设置回调函数将主题名称打印到串行端口并打印从 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>// WiFiconst char *ssid = "mousse"; // Enter your WiFi nameconst char *password = "qweqweqwe";  // Enter WiFi password// MQTT Brokerconst 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();}

运行和测试

  1. 应用 Arduino 上传残缺代码,并将 esp32 上电
  2. 关上串口监视器,抉择 115200 波特率,查看 ESP32 连贯状况

  3. 应用 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