野火电子论坛

标题: ESP8266 连接到免费的公共 MQTT 服务器 [打印本页]

作者: edwardx    时间: 2020-7-6 15:16
标题: ESP8266 连接到免费的公共 MQTT 服务器
MQTT 是轻量级的、灵活的物联网消息交换和数据传递协议,致力于为 IoT 开发人员实现灵活性与硬件/网络资源的平衡。
ESP8266 提供了⼀套⾼度集成的 Wi-Fi SoC 解决⽅案,其低功耗、 紧凑设计和⾼稳定性可以满⾜⽤户的需求。ESP8266 拥有完整的且⾃成体系的 Wi-Fi ⽹络功能,既能够独⽴应⽤,也可以作为从机搭载于其他主机 MCU 运⾏。
在此项目中我们将实现 ESP8266 连接到免费公共 MQTT 服务器,并使用 Arduino IDE 来对 ESP8266 进行编程。
EMQ X MQTT 物联网云服务 提供了一个在线的公共 MQTT 5.0 服务器,不需要任何安装您就可以快速开始 MQTT 协议的学习、测试或原型制作。该 MQTT 服务器的详细接入信息请见 EMQ 官网页面:免费的在线 MQTT 服务器。本教程我们将使用该免费的在线 MQTT 服务器。
准备工作
ESP8266 Pub/Sub 示意图
(, 下载次数: 1)

ESP8266 代码编写
MQTT 服务器的连接和测试
完整代码
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>

  3. const char *ssid = "name"; // Enter your WiFi name
  4. const char *password = "pass";  // Enter WiFi password
  5. const char *mqtt_broker = "broker.emqx.io";
  6. const int mqtt_port = 1883;

  7. WiFiClient espClient;
  8. PubSubClient client(espClient);

  9. void setup() {
  10.     // Set software serial baud to 115200;
  11.     Serial.begin(115200);
  12.     // connecting to a WiFi network
  13.     WiFi.begin(ssid, password);
  14.     while (WiFi.status() != WL_CONNECTED) {
  15.         delay(500);
  16.         Serial.println("Connecting to WiFi..");
  17.     }
  18.     Serial.println("Connected to the WiFi network");
  19.     //connecting to a mqtt broker
  20.     client.setServer(mqtt_broker, mqtt_port);
  21.     client.setCallback(callback);
  22.     while (!client.connected()) {
  23.         Serial.println("Connecting to public emqx mqtt broker.....");
  24.         if (client.connect("esp8266-client")) {
  25.             Serial.println("Public emqx mqtt broker connected");
  26.         } else {
  27.             Serial.print("failed with state ");
  28.             Serial.print(client.state());
  29.             delay(2000);
  30.         }
  31.     }
  32.     // publish and subscribe
  33.     client.publish("esp8266/test", "hello emqx");
  34.     client.subscribe("esp8266/test");
  35. }

  36. void callback(char *topic, byte *payload, unsigned int length) {
  37.     Serial.print("Message arrived in topic: ");
  38.     Serial.println(topic);
  39.     Serial.print("Message:");
  40.     for (int i = 0; i < length; i++) {
  41.         Serial.print((char) payload[i]);
  42.     }
  43.     Serial.println();
  44.     Serial.println("-----------------------");
  45. }

  46. void loop() {
  47.     client.loop();
  48. }
复制代码

总结
在本项目中我们简单的将 ESP8266 连接到 MQTT 服务器,这只是 ESP8266 较为基础的能力之一,ESP8266 其实还能与各类物联网传感器相连,并将传感器数据上报至 MQTT 服务器。


作者: icode    时间: 2020-8-23 09:40
这个不错,感谢分享,手上正好有之前项目剩余的ESP8266,用Ardunio来玩玩





欢迎光临 野火电子论坛 (https://www.firebbs.cn/) Powered by Discuz! X3.4