ESP8266 SHT21 sensor
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ESP-Weather.ino 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /*
  2. * ESP-Weather.ino
  3. *
  4. * This is the main program for our distributed temperature and humidity logger
  5. * with WiFi interface, based on the ESP8266 ESP-01 module and an SHT21 sensor.
  6. *
  7. * ----------------------------------------------------------------------------
  8. * "THE BEER-WARE LICENSE" (Revision 42):
  9. * <xythobuz@xythobuz.de> & <ghost-ghost@web.de> wrote this file. As long as
  10. * you retain this notice you can do whatever you want with this stuff. If we
  11. * meet some day, and you think this stuff is worth it, you can buy us a beer
  12. * in return. Thomas Buck & Christian Högerle
  13. * ----------------------------------------------------------------------------
  14. */
  15. #include <ESP8266WiFi.h>
  16. #include <WiFiClient.h>
  17. #include <ESP8266WebServer.h>
  18. #include <WiFiUdp.h>
  19. #include <SHT21.h>
  20. #include <vector>
  21. #include <WebSocketServer.h>
  22. #include <WiFiServer.h>
  23. #include <DNSServer.h>
  24. #include <WiFiManager.h>
  25. #include "config.h"
  26. #include "ntp.h"
  27. #include "storage.h"
  28. SHT21 sensor;
  29. ESP8266WebServer server(WEB_PORT);
  30. WiFiServer serverSocket(WEBSOCKET_PORT);
  31. WebSocketServer webSocketServer;
  32. IPAddress broadcastIP;
  33. WiFiUDP udp;
  34. PersistentStorage storage;
  35. std::vector<IPAddress> vecClients;
  36. char packetBuffer[UDP_PACKET_BUFFER_SIZE];
  37. unsigned long lastStorageTime = 0;
  38. byte storeAtBoot = 1;
  39. unsigned long lastTime = 0;
  40. bool waitingForReplies = false;
  41. void handleRoot() {
  42. Serial.println("Sending UDP Broadcast...");
  43. // Send UDP broadcast to other modules
  44. udp.beginPacket(broadcastIP, BROADCAST_PORT);
  45. udp.write(UDP_PING_CONTENTS);
  46. udp.endPacket();
  47. // Start reply wait timer
  48. lastTime = millis();
  49. waitingForReplies = true;
  50. }
  51. void handleNotFound() {
  52. String message = "File Not Found\n\n";
  53. message += "URI: ";
  54. message += server.uri();
  55. message += "\nMethod: ";
  56. message += (server.method() == HTTP_GET)?"GET":"POST";
  57. message += "\nArguments: ";
  58. message += server.args();
  59. message += "\n";
  60. for (uint8_t i = 0; i < server.args(); i++){
  61. message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  62. }
  63. server.send(404, "text/plain", message);
  64. }
  65. void setup(void) {
  66. // Debugging
  67. Serial.begin(115200);
  68. Serial.println();
  69. Serial.println("ESP-Weather init...");
  70. //sensor.begin();
  71. // The SHT library is simpy calling Wire.begin(), but the default
  72. // config does not match the pins i'm using (sda - 2; scl - 0)
  73. Wire.begin(2, 0);
  74. // Here you can override the WiFiManager configuration. Leave
  75. // the default autoConnect in use for the default behaviour.
  76. // To force the config portal, even though the module was connected before,
  77. // comment-out autoConnect and use startConfigPortal instead.
  78. WiFiManager wifiManager;
  79. wifiManager.autoConnect(DEFAULT_SSID, DEFAULT_PASS);
  80. //wifiManager.startConfigPortal(DEFAULT_SSID, DEFAULT_PASS);
  81. initMemory();
  82. storage = readMemory();
  83. // Wait for connection
  84. if (WiFi.status() != WL_CONNECTED) {
  85. while (WiFi.status() != WL_CONNECTED) {
  86. delay(500);
  87. Serial.print(".");
  88. }
  89. Serial.println("");
  90. }
  91. Serial.print("IP address: ");
  92. Serial.println(WiFi.localIP());
  93. broadcastIP = ~WiFi.subnetMask() | WiFi.gatewayIP();
  94. server.on("/", handleRoot);
  95. server.onNotFound(handleNotFound);
  96. server.begin();
  97. serverSocket.begin();
  98. ntpInit();
  99. udp.begin(BROADCAST_PORT);
  100. Serial.println("ESP-Weather ready!");
  101. }
  102. void loop(void) {
  103. ntpRun();
  104. server.handleClient();
  105. // Websocket fuer Browser
  106. WiFiClient client = serverSocket.available();
  107. if (client.connected() && webSocketServer.handshake(client)) {
  108. Serial.println("Building WebSocket Response...");
  109. String json = "{\"H\":";
  110. json += String(sensor.getHumidity());
  111. json += ",";
  112. json += "\"T\":";
  113. json += String(sensor.getTemperature());
  114. json += ", \"EEPROM\" : [";
  115. for (int i = 0; i < storage.header.count; i++) {
  116. json += "{\"H\":";
  117. json += String(storage.data[i].humidity);
  118. json += ",";
  119. json += "\"T\":";
  120. json += String(storage.data[i].temperature);
  121. json += "}";
  122. if (i < storage.header.count - 1) {
  123. json += ",";
  124. }
  125. }
  126. json += "]}";
  127. Serial.println("WebSocket Response:");
  128. Serial.println(json);
  129. webSocketServer.sendData(json);
  130. client.flush();
  131. client.stop();
  132. }
  133. // EEPROM-Schreiben jede Stunde
  134. if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
  135. && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
  136. Serial.println("Storing new data packet...");
  137. lastStorageTime = millis();
  138. storeAtBoot = 0;
  139. if (storage.header.count < MAX_STORAGE) {
  140. storage.header.count++;
  141. } else {
  142. for(int i = 0; i < MAX_STORAGE - 1; i++) {
  143. storage.data[i] = storage.data[i+1];
  144. }
  145. }
  146. storage.data[storage.header.count - 1].temperature = sensor.getTemperature();
  147. storage.data[storage.header.count - 1].humidity = sensor.getHumidity();
  148. writeMemory(storage);
  149. }
  150. // UDP
  151. int packetSize = udp.parsePacket();
  152. if (packetSize) {
  153. IPAddress remoteIp = udp.remoteIP();
  154. // read the packet into packetBufffer
  155. int len = udp.read(packetBuffer, UDP_PACKET_BUFFER_SIZE);
  156. if (len > 0) {
  157. packetBuffer[len] = 0;
  158. }
  159. Serial.print("Got UDP packet: ");
  160. Serial.println(packetBuffer);
  161. if (strcmp(packetBuffer, UDP_PING_CONTENTS) == 0) {
  162. Serial.println("Broadcast");
  163. udp.beginPacket(udp.remoteIP(), udp.remotePort());
  164. udp.print(UDP_ECHO_CONTENTS);
  165. udp.endPacket();
  166. } else if((strcmp(packetBuffer, UDP_ECHO_CONTENTS) == 0) && (waitingForReplies == true)) {
  167. vecClients.push_back(udp.remoteIP());
  168. }
  169. }
  170. if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
  171. Serial.println("Timeout, sending response...");
  172. waitingForReplies = false;
  173. String message = HTML_BEGIN;
  174. message += "var clients = Array(";
  175. message += "\"" + WiFi.localIP().toString() + "\"";
  176. if (vecClients.size() > 0) {
  177. message += ", ";
  178. }
  179. for (int i = 0; i < vecClients.size(); i++) {
  180. message += "\"" + vecClients[i].toString() + "\"";
  181. if (i < (vecClients.size() - 1)) {
  182. message += ", ";
  183. }
  184. }
  185. message += ");";
  186. message += HTML_END;
  187. vecClients.clear();
  188. server.send(200, "text/html", message);
  189. }
  190. }