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.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 handleJS() {
  52. String message = F(JS_FILE);
  53. server.send(200, "text/javascript", message);
  54. }
  55. void handleNotFound() {
  56. String message = "File Not Found\n\n";
  57. message += "URI: ";
  58. message += server.uri();
  59. message += "\nMethod: ";
  60. message += (server.method() == HTTP_GET)?"GET":"POST";
  61. message += "\nArguments: ";
  62. message += server.args();
  63. message += "\n";
  64. for (uint8_t i = 0; i < server.args(); i++){
  65. message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  66. }
  67. server.send(404, "text/plain", message);
  68. }
  69. void setup(void) {
  70. // Debugging
  71. Serial.begin(115200);
  72. Serial.println();
  73. Serial.println("ESP-Weather init...");
  74. //sensor.begin();
  75. // The SHT library is simpy calling Wire.begin(), but the default
  76. // config does not match the pins i'm using (sda - 2; scl - 0)
  77. Wire.begin(2, 0);
  78. // Here you can override the WiFiManager configuration. Leave
  79. // the default autoConnect in use for the default behaviour.
  80. // To force the config portal, even though the module was connected before,
  81. // comment-out autoConnect and use startConfigPortal instead.
  82. WiFiManager wifiManager;
  83. wifiManager.autoConnect(DEFAULT_SSID, DEFAULT_PASS);
  84. //wifiManager.startConfigPortal(DEFAULT_SSID, DEFAULT_PASS);
  85. initMemory();
  86. storage = readMemory();
  87. // Wait for connection
  88. if (WiFi.status() != WL_CONNECTED) {
  89. while (WiFi.status() != WL_CONNECTED) {
  90. delay(500);
  91. Serial.print(".");
  92. }
  93. Serial.println("");
  94. }
  95. Serial.print("IP address: ");
  96. Serial.println(WiFi.localIP());
  97. broadcastIP = ~WiFi.subnetMask() | WiFi.gatewayIP();
  98. server.on("/", handleRoot);
  99. server.on("/index.html", handleRoot);
  100. server.on("/view.js", handleJS);
  101. server.onNotFound(handleNotFound);
  102. server.begin();
  103. serverSocket.begin();
  104. ntpInit();
  105. udp.begin(BROADCAST_PORT);
  106. Serial.println("ESP-Weather ready!");
  107. }
  108. void loop(void) {
  109. ntpRun();
  110. server.handleClient();
  111. // Websocket fuer Browser
  112. WiFiClient client = serverSocket.available();
  113. if (client.connected() && webSocketServer.handshake(client)) {
  114. Serial.println("Building WebSocket Response...");
  115. String json = "{\"H\":";
  116. json += String(sensor.getHumidity());
  117. json += ",";
  118. json += "\"T\":";
  119. json += String(sensor.getTemperature());
  120. json += ", \"EEPROM\" : [";
  121. for (int i = 0; i < storage.header.count; i++) {
  122. json += "{\"H\":";
  123. json += String(storage.data[i].humidity);
  124. json += ",";
  125. json += "\"T\":";
  126. json += String(storage.data[i].temperature);
  127. json += "}";
  128. if (i < storage.header.count - 1) {
  129. json += ",";
  130. }
  131. }
  132. json += "]}";
  133. Serial.println("WebSocket Response:");
  134. Serial.println(json);
  135. webSocketServer.sendData(json);
  136. client.flush();
  137. client.stop();
  138. }
  139. // EEPROM-Schreiben jede Stunde
  140. if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
  141. && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
  142. Serial.println("Storing new data packet...");
  143. lastStorageTime = millis();
  144. storeAtBoot = 0;
  145. if (storage.header.count < MAX_STORAGE) {
  146. storage.header.count++;
  147. } else {
  148. for(int i = 0; i < MAX_STORAGE - 1; i++) {
  149. storage.data[i] = storage.data[i+1];
  150. }
  151. }
  152. storage.data[storage.header.count - 1].temperature = sensor.getTemperature();
  153. storage.data[storage.header.count - 1].humidity = sensor.getHumidity();
  154. writeMemory(storage);
  155. }
  156. // UDP
  157. int packetSize = udp.parsePacket();
  158. if (packetSize) {
  159. IPAddress remoteIp = udp.remoteIP();
  160. // read the packet into packetBufffer
  161. int len = udp.read(packetBuffer, UDP_PACKET_BUFFER_SIZE);
  162. if (len > 0) {
  163. packetBuffer[len] = 0;
  164. }
  165. Serial.print("Got UDP packet: ");
  166. Serial.println(packetBuffer);
  167. if (strcmp(packetBuffer, UDP_PING_CONTENTS) == 0) {
  168. Serial.println("Broadcast");
  169. udp.beginPacket(udp.remoteIP(), udp.remotePort());
  170. udp.print(UDP_ECHO_CONTENTS);
  171. udp.endPacket();
  172. } else if((strcmp(packetBuffer, UDP_ECHO_CONTENTS) == 0) && (waitingForReplies == true)) {
  173. vecClients.push_back(udp.remoteIP());
  174. }
  175. }
  176. if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
  177. Serial.println("Timeout, sending response...");
  178. waitingForReplies = false;
  179. String message = F(HTML_BEGIN);
  180. message += "var clients = Array(";
  181. message += "\"" + WiFi.localIP().toString() + "\"";
  182. if (vecClients.size() > 0) {
  183. message += ", ";
  184. }
  185. for (int i = 0; i < vecClients.size(); i++) {
  186. message += "\"" + vecClients[i].toString() + "\"";
  187. if (i < (vecClients.size() - 1)) {
  188. message += ", ";
  189. }
  190. }
  191. message += ");";
  192. message += F(HTML_END);
  193. vecClients.clear();
  194. server.send(200, "text/html", message);
  195. }
  196. }