当前位置:   article > 正文

ESP8266入门教程13:项目实战_esp8266实战

esp8266实战

一、安装第三方库

  1. // WIFI自动配网
  2. git clone https://github.com/tzapu/WiFiManager.git
  3. // Json解析
  4. git clone https://github.com/bblanchon/ArduinoJson.git
  5. // MQTT连接
  6. git clone https://github.com/knolleary/pubsubclient.git
  7. // WebSocket连接
  8. git clone https://github.com/Links2004/arduinoWebSockets.git

二、测试效果

  

三、完整代码

  1. // AutoConnectAP.h
  2. #ifndef AUTO_CONNECT_AP_H
  3. #define AUTO_CONNECT_AP_H
  4. #include "../lib/WiFiManager/WiFiManager.h"
  5. bool autoConnectAP() {
  6. // 创建WIFI管理器
  7. WiFiManager wifiManager;
  8. // 开始自动配网
  9. if (wifiManager.autoConnect("ESP8266-Auto")) {
  10. return true;
  11. } else {
  12. return false;
  13. }
  14. }
  15. #endif // AUTO_CONNECT_AP_H
  1. // ConnectMQTT.h
  2. #ifndef CONNECT_MQTT_H
  3. #define CONNECT_MQTT_H
  4. #include <ESP8266WiFi.h>
  5. #include <ESP8266WebServer.h>
  6. #include <LittleFS.h>
  7. #include "../lib/pubsubclient/src/PubSubClient.h"
  8. #include "../lib/arduinoWebSockets/src/WebSocketsServer.h"
  9. #define MQTT_HOST ""
  10. #define MQTT_PORT 1883
  11. #define MQTT_CLIENT_ID ""
  12. #define MQTT_USER ""
  13. #define MQTT_PASS ""
  14. #define HTTP_PORT 80
  15. // 创建WIFI客户端
  16. WiFiClient wifiClient;
  17. // 创建MQTT客户端
  18. PubSubClient mqttClient(wifiClient);
  19. // 创建HTTP服务器
  20. ESP8266WebServer webServer(HTTP_PORT);
  21. // 创建WS服务器
  22. WebSocketsServer webSocketServer(81);
  23. uint8_t clientId = 0;
  24. // 主页源码
  25. String homeContent = R"(
  26. <html>
  27. <head>
  28. <meta charset="UTF-8"/>
  29. <title>消息列表</title>
  30. <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  31. </head>
  32. <body>
  33. <div>
  34. <input id="msg"/>
  35. <button id="send">发送消息</button>
  36. </div>
  37. <div>消息列表:</div>
  38. <div id="log"></div>
  39. <script>
  40. $(function(){
  41. let ws = new WebSocket("ws://192.168.10.5:81");
  42. ws.onpen = function(res) {
  43. console.log("onpen", res);
  44. }
  45. ws.onclose = function(res) {
  46. console.log("onclose", res);
  47. }
  48. ws.onmessage = function(res) {
  49. console.log("onmessage", res.data);
  50. $("#log").append("<div>" + res.data + "</div>");
  51. }
  52. ws.onerror = function(res) {
  53. console.log("onerror", res);
  54. }
  55. $("#send").click(function(){
  56. let msg = $("#msg").val();
  57. console.log("发送消息: ", msg);
  58. ws.send(msg);
  59. });
  60. })
  61. </script>
  62. </body>
  63. </html>)";
  64. void sendMQTT(const String &payload)
  65. {
  66. // 判断MQTT服务器是否已连接
  67. if (!mqttClient.connected())
  68. {
  69. Serial.println("MQTT服务器未连接");
  70. return;
  71. }
  72. // 定义MQTT主题
  73. String topic = "/a1aeNGS45Gg/";
  74. topic += "ESP8266";
  75. topic += "/user/info";
  76. if (mqttClient.publish(topic.c_str(), payload.c_str()))
  77. {
  78. Serial.println("MQTT消息发送成功");
  79. }
  80. else
  81. {
  82. Serial.println("MQTT消息发送失败");
  83. }
  84. }
  85. void onWebSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length)
  86. {
  87. clientId = num;
  88. String message = String((char *)payload).substring(0, length);
  89. switch ((int)type)
  90. {
  91. case WStype_CONNECTED:
  92. Serial.println("WebSocket连接成功");
  93. break;
  94. case WStype_DISCONNECTED:
  95. Serial.println("WebSocket断开连接");
  96. break;
  97. case WStype_TEXT:
  98. Serial.println("WebSocket收到消息: " + message);
  99. Serial.println("length: " + String(length));
  100. // 发送消息到MQTT服务器
  101. sendMQTT(message);
  102. break;
  103. }
  104. }
  105. void handleRoot()
  106. {
  107. // 打开页面文件
  108. File file = LittleFS.open("/index.html", "r");
  109. String content = file.readString();
  110. // 响应HTTP请求
  111. webServer.send(200, "text/html", content);
  112. }
  113. void handleNotFound()
  114. {
  115. webServer.send(404, "text/html", "<h1>Not found</h1>");
  116. }
  117. void recvMQTT(char *topic, uint8_t *payload, unsigned int length)
  118. {
  119. String message = String((char *)payload).substring(0, length);
  120. Serial.println("topic: " + String(topic));
  121. Serial.println("payload: " + message);
  122. Serial.println("length: " + String(length));
  123. // 回复WebSocket消息
  124. webSocketServer.sendTXT(clientId, message);
  125. }
  126. void initMQTT()
  127. {
  128. // 配置MQTT服务器
  129. mqttClient.setServer(MQTT_HOST, MQTT_PORT);
  130. // 设置MQTT消息回调函数
  131. mqttClient.setCallback(recvMQTT);
  132. // 启动HTTP服务器
  133. webServer.begin();
  134. // 设置HTTP请求处理函数
  135. webServer.on("/", handleRoot);
  136. webServer.onNotFound(handleNotFound);
  137. // 启动WebSocket服务器
  138. webSocketServer.begin();
  139. webSocketServer.onEvent(onWebSocketEvent);
  140. // 加载文件系统
  141. if (!LittleFS.begin())
  142. {
  143. Serial.println("文件系统加载失败");
  144. return;
  145. }
  146. // 写入页面文件
  147. File file = LittleFS.open("/index.html", "w");
  148. file.print(homeContent);
  149. file.close();
  150. }
  151. void connectMQTT()
  152. {
  153. // 连接MQTT服务器
  154. if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS))
  155. {
  156. Serial.println("MQTT服务器连接成功");
  157. // 定义MQTT主题
  158. String topic = "/a1aeNGS45Gg/";
  159. topic += "ESP8266";
  160. topic += "/user/info";
  161. // 订阅MQTT主题
  162. if (mqttClient.subscribe(topic.c_str()))
  163. {
  164. Serial.println("MQTT主题订阅成功");
  165. }
  166. else
  167. {
  168. Serial.println("MQTT主题订阅失败");
  169. }
  170. }
  171. else
  172. {
  173. Serial.println("MQTT服务器连接失败");
  174. delay(3000);
  175. }
  176. }
  177. void loopMQTT()
  178. {
  179. // 判断MQTT是否已连接
  180. if (mqttClient.connected())
  181. {
  182. // 保持MQTT连接心跳
  183. mqttClient.loop();
  184. }
  185. else
  186. {
  187. // 重新连接MQTT服务器
  188. connectMQTT();
  189. }
  190. // 处理HTTP客户端请求
  191. webServer.handleClient();
  192. // 保持WebSocket服务器心跳
  193. webSocketServer.loop();
  194. }
  195. #endif // CONNECT_MQTT_H
  1. // main.cpp
  2. #include <Arduino.h>
  3. #include "AutoConnectAP.h"
  4. #include "ConnectMQTT.h"
  5. void setup()
  6. {
  7. // put your setup code here, to run once:
  8. // 设置波特率
  9. Serial.begin(9600);
  10. Serial.println();
  11. // 自动配网
  12. if (!autoConnectAP())
  13. {
  14. Serial.println("自动配网失败");
  15. return;
  16. }
  17. Serial.println("自动配网成功");
  18. Serial.println("WIFI名称: " + WiFi.SSID());
  19. Serial.println("IP地址: " + WiFi.localIP().toString());
  20. // 初始化MQTT服务器
  21. initMQTT();
  22. // 连接MQTT服务器
  23. connectMQTT();
  24. }
  25. void loop()
  26. {
  27. // put your main code here, to run repeatedly:
  28. // 保持MQTT连接心跳
  29. loopMQTT();
  30. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/684645
推荐阅读
相关标签
  

闽ICP备14008679号