ESP32 mit WIFI und MQTT rx und tx
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

268 lignes
9.5KB

  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3. //#include "struct.h"
  4. #include "eepromsettings.h"
  5. // Update these with values suitable for your network.
  6. const char* ssid = "Andreas-Grabner.NET";
  7. const char* password = "born2win";
  8. const char* mqtt_server = "192.168.11.35";
  9. #define mqtt_port 1883
  10. #define MQTT_USER "loxberry"
  11. #define MQTT_PASSWORD "OSVL0AMqISFXgr5g"
  12. #define MQTT_SERIAL_PUBLISH_CH "ESP32/Heizung/status"
  13. #define MQTT_SERIAL_RECEIVER_CH "ESP32/Heizung/stufe"
  14. WiFiClient wifiClient;
  15. PubSubClient client(wifiClient);
  16. // Webserver
  17. WiFiServer server(80);
  18. String header;
  19. // Auxiliar variables to store the current output state
  20. String output26State = "off";
  21. String output27State = "off";
  22. // Assign output variables to GPIO pins
  23. const int output26 = 26;
  24. const int output27 = 27;
  25. /* Store all string in the FLASH storage to free SRAM.
  26. The P() is a function from Webduino.
  27. */
  28. P(Page_start) = "<html><head><title>Web_EEPROM_Setup</title></head><body>\n";
  29. P(Page_end) = "</body></html>";
  30. P(Http400) = "HTTP 400 - BAD REQUEST";
  31. P(Index) = "<h1>index.html</h1><br>This is your main site!<br>The code is found in the indexHTML() function.<br>You can add more sites if you need. Please see the well documented source code.<br><br>Use the following link to setup the network.<br><a href=\"setupNet.html\">NETWORK SETUP</a>";
  32. P(Form_eth_start) = "<FORM action=\"setupNet.html\" method=\"get\">";
  33. P(Form_end) = "<FORM>";
  34. P(Form_input_send) = "<INPUT type=\"submit\" value=\"Set config\">";
  35. P(Form_input_text_start) = "<input type=\"text\" name=\"";
  36. P(Form_input_value) = "\" value=\"";
  37. P(Form_input_size2) = "\" maxlength=\"2\" size=\"2";
  38. P(Form_input_size3) = "\" maxlength=\"3\" size=\"3";
  39. P(Form_input_end) = "\">\n";
  40. P(MAC) = "MAC address: ";
  41. P(IP) = "IP address: ";
  42. P(SUBNET) = "Subnet: ";
  43. P(GW) = "GW address: ";
  44. P(DNS_SERVER) = "DNS server: ";
  45. P(WEB_PORT) = "Webserver port (1-65535): ";
  46. P(DHCP_ACTIVE) = "Use DHCP: ";
  47. P(DHCP_REFRESH) = "Renew interval for DHCP in minutes (1 - 255): ";
  48. P(MQTT_SERVER) = "MQTT server: ";
  49. P(MQTT_PORT) = "MQTTserver port (1-65535): ";
  50. P(Form_cb) = "<input type=\"radio\" name=\"23\" value=\"";
  51. P(Form_cb_checked) = " checked ";
  52. P(Form_cb_on) = ">On";
  53. P(Form_cb_off) = ">Off";
  54. P(br) = "<br>\n";
  55. P(table_start) = "<table>";
  56. P(table_tr_start) = "<tr>";
  57. P(table_tr_end) = "</tr>";
  58. P(table_td_start) = "<td>";
  59. P(table_td_end) = "</td>";
  60. P(table_end) = "</table>";
  61. P(Config_set) = "<font size=\"6\" color=\"red\">New configuration stored! <br>Please turn off and on your Arduino or use the reset button!</font><br>";
  62. P(DHCP_STATE_TIME) = "DHCP last renew timestamp (sec)";
  63. P(DHCP_STATE) = "DHCP renew return code (sec)";
  64. P(UPTIME) = "Uptime: ";
  65. #ifdef USE_SYSTEM_LIBRARY
  66. P(RAM_1) = "RAM (byte): ";
  67. P(RAM_2) = " free of ";
  68. #endif
  69. void setup_wifi() {
  70. delay(10);
  71. // We start by connecting to a WiFi network
  72. Serial.println();
  73. Serial.print("Connecting to ");
  74. Serial.println(ssid);
  75. WiFi.begin(ssid, password);
  76. while (WiFi.status() != WL_CONNECTED) {
  77. delay(500);
  78. Serial.print(".");
  79. }
  80. randomSeed(micros());
  81. Serial.println("");
  82. Serial.println("WiFi connected");
  83. Serial.println("IP address: ");
  84. Serial.println(WiFi.localIP());
  85. }
  86. void setup_webserver() {
  87. server.begin();
  88. }
  89. void reconnect() {
  90. // Loop until we're reconnected
  91. while (!client.connected()) {
  92. Serial.print("Attempting MQTT connection...");
  93. // Create a random client ID
  94. String clientId = "ESP32Client-";
  95. clientId += String(random(0xffff), HEX);
  96. // Attempt to connect
  97. if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
  98. Serial.println("connected");
  99. //Once connected, publish an announcement...
  100. client.publish("ESP32/Heizung/Status/restart", "done");
  101. // ... and resubscribe
  102. client.subscribe(MQTT_SERIAL_RECEIVER_CH);
  103. } else {
  104. Serial.print("failed, rc=");
  105. Serial.print(client.state());
  106. Serial.println(" try again in 5 seconds");
  107. // Wait 5 seconds before retrying
  108. delay(5000);
  109. }
  110. }
  111. }
  112. void callback(char* topic, byte *payload, unsigned int length) {
  113. Serial.println("-------new message from broker-----");
  114. Serial.print("channel:");
  115. Serial.println(topic);
  116. Serial.print("data:");
  117. Serial.write(payload, length);
  118. Serial.println();
  119. }
  120. void setup() {
  121. Serial.begin(115200);
  122. Serial.setTimeout(500);// Set time out for
  123. setup_wifi();
  124. setup_webserver();
  125. client.setServer(mqtt_server, mqtt_port);
  126. client.setCallback(callback);
  127. reconnect();
  128. }
  129. void publishSerialData(char *serialData){
  130. if (!client.connected()) {
  131. reconnect();
  132. }
  133. client.publish(MQTT_SERIAL_PUBLISH_CH, serialData);
  134. }
  135. void loop_webserver() {
  136. WiFiClient client = server.available(); // Listen for incoming clients
  137. if (client) { // If a new client connects,
  138. Serial.println("New Client."); // print a message out in the serial port
  139. String currentLine = ""; // make a String to hold incoming data from the client
  140. while (client.connected()) { // loop while the client's connected
  141. if (client.available()) { // if there's bytes to read from the client,
  142. char c = client.read(); // read a byte, then
  143. Serial.write(c); // print it out the serial monitor
  144. header += c;
  145. if (c == '\n') { // if the byte is a newline character
  146. // if the current line is blank, you got two newline characters in a row.
  147. // that's the end of the client HTTP request, so send a response:
  148. if (currentLine.length() == 0) {
  149. // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  150. // and a content-type so the client knows what's coming, then a blank line:
  151. client.println("HTTP/1.1 200 OK");
  152. client.println("Content-type:text/html");
  153. client.println("Connection: close");
  154. client.println();
  155. // turns the GPIOs on and off
  156. if (header.indexOf("GET /26/on") >= 0) {
  157. Serial.println("GPIO 26 on");
  158. output26State = "on";
  159. digitalWrite(output26, HIGH);
  160. } else if (header.indexOf("GET /26/off") >= 0) {
  161. Serial.println("GPIO 26 off");
  162. output26State = "off";
  163. digitalWrite(output26, LOW);
  164. } else if (header.indexOf("GET /27/on") >= 0) {
  165. Serial.println("GPIO 27 on");
  166. output27State = "on";
  167. digitalWrite(output27, HIGH);
  168. } else if (header.indexOf("GET /27/off") >= 0) {
  169. Serial.println("GPIO 27 off");
  170. output27State = "off";
  171. digitalWrite(output27, LOW);
  172. }
  173. // Display the HTML web page
  174. client.println("<!DOCTYPE html><html>");
  175. client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
  176. client.println("<link rel=\"icon\" href=\"data:,\">");
  177. // CSS to style the on/off buttons
  178. // Feel free to change the background-color and font-size attributes to fit your preferences
  179. client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
  180. client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
  181. client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
  182. client.println(".button2 {background-color: #555555;}</style></head>");
  183. // Web Page Heading
  184. client.println("<body><h1>ESP32 Web Server</h1>");
  185. // Display current state, and ON/OFF buttons for GPIO 26
  186. client.println("<p>GPIO 26 - State " + output26State + "</p>");
  187. // If the output26State is off, it displays the ON button
  188. if (output26State=="off") {
  189. client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
  190. } else {
  191. client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
  192. }
  193. // Display current state, and ON/OFF buttons for GPIO 27
  194. client.println("<p>GPIO 27 - State " + output27State + "</p>");
  195. // If the output27State is off, it displays the ON button
  196. if (output27State=="off") {
  197. client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
  198. } else {
  199. client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
  200. }
  201. client.println("</body></html>");
  202. // The HTTP response ends with another blank line
  203. client.println();
  204. // Break out of the while loop
  205. break;
  206. } else { // if you got a newline, then clear currentLine
  207. currentLine = "";
  208. }
  209. } else if (c != '\r') { // if you got anything else but a carriage return character,
  210. currentLine += c; // add it to the end of the currentLine
  211. }
  212. }
  213. }
  214. // Clear the header variable
  215. header = "";
  216. // Close the connection
  217. client.stop();
  218. Serial.println("Client disconnected.");
  219. Serial.println("");
  220. }
  221. }
  222. void loop() {
  223. client.loop();
  224. loop_webserver();
  225. if (Serial.available() > 0) {
  226. char mun[501];
  227. memset(mun,0, 501);
  228. Serial.readBytesUntil( '\n',mun,500);
  229. publishSerialData(mun);
  230. }
  231. }