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 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #include <ESP8266WiFi.h>
  2. #include <WiFiClient.h>
  3. #include <ESP8266WebServer.h>
  4. #include <WiFiUdp.h>
  5. #include <SHT21.h>
  6. #include <vector>
  7. #include <WebSocketServer.h>
  8. #include <WiFiServer.h>
  9. #include <DNSServer.h>
  10. #include <WiFiManager.h>
  11. #include "storage.h"
  12. #define WEB_PORT 80
  13. #define BROADCAST_PORT 2390
  14. #define WEBSOCKET_PORT 2391
  15. #define NTP_PORT_FROM 2392
  16. #define NTP_PORT_TO 123
  17. #define DEFAULT_SSID "ESP-Weather"
  18. #define DEFAULT_PASS "testtest"
  19. #define MAX_BROADCAST_WAIT_TIME 550
  20. #define NTP_RETRY_TIMEOUT 2000
  21. // NTP-Client
  22. IPAddress timeServerIP;
  23. const char* ntpServerName = "time.nist.gov";
  24. const int NTP_PACKET_SIZE = 48;
  25. byte ntpPacketBuffer[NTP_PACKET_SIZE];
  26. WiFiUDP ntp;
  27. unsigned long timestamp = 0;
  28. unsigned long timeReceived = 0;
  29. unsigned long lastStorageTime = 0;
  30. byte storeAtBoot = 1;
  31. unsigned long lastNTP = 0;
  32. SHT21 SHT21;
  33. ESP8266WebServer server(WEB_PORT);
  34. WiFiServer serverSocket(WEBSOCKET_PORT);
  35. WebSocketServer webSocketServer;
  36. IPAddress broadcastIP;
  37. PersistentStorage storage;
  38. std::vector<IPAddress> vecClients;
  39. // UDP-Config
  40. #define UDP_PACKET_BUFFER_SIZE 255
  41. char packetBuffer[UDP_PACKET_BUFFER_SIZE];
  42. const char pingBuffer[] = "pingESP8266v0.1";
  43. const char echoBuffer[] = "echoESP8266v0.1";
  44. WiFiUDP udp;
  45. unsigned long lastTime;
  46. bool waitingForReplies = false;
  47. // Using the RawGit.com service to serve the scripts directly from GitHub.
  48. // Consider using cdn.rawgit.com to reduce their server load.
  49. const char* htmlBegin = "<html><head>\
  50. <title>Sysadmin</title>\
  51. <script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/jquery-3.1.1.min.js\"></script>\
  52. <script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/bootstrap.min.js\"></script>\
  53. <script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/Chart.bundle.min.js\"></script>\
  54. <script src=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/script.js\"></script>\
  55. <link rel=\"stylesheet\" href=\"https://rawgit.com/xythobuz/ESP-Weather/master/static/bootstrap.min.css\" />\
  56. </head><body>\
  57. <script type=\"text/javascript\">";
  58. const char* htmlEnd = "</script></body></html>";
  59. void handleRoot() {
  60. Serial.println("Sending UDP Broadcast...");
  61. // Send UDP broadcast to other modules
  62. udp.beginPacket(broadcastIP, BROADCAST_PORT);
  63. udp.write(pingBuffer);
  64. udp.endPacket();
  65. // Start reply wait timer
  66. lastTime = millis();
  67. waitingForReplies = true;
  68. }
  69. void handleNotFound(){
  70. String message = "File Not Found\n\n";
  71. message += "URI: ";
  72. message += server.uri();
  73. message += "\nMethod: ";
  74. message += (server.method() == HTTP_GET)?"GET":"POST";
  75. message += "\nArguments: ";
  76. message += server.args();
  77. message += "\n";
  78. for (uint8_t i = 0; i < server.args(); i++){
  79. message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  80. }
  81. server.send(404, "text/plain", message);
  82. }
  83. void setup(void) {
  84. // Debugging
  85. Serial.begin(115200);
  86. Serial.println();
  87. Serial.println("ESP-Weather init...");
  88. //SHT21.begin();
  89. // The SHT library is simpy calling Wire.begin(), but the default
  90. // config does not match the pins i'm using (sda - 2; scl - 0)
  91. Wire.begin(2, 0);
  92. // Here you can override the WiFiManager configuration. Leave
  93. // the default autoConnect in use for the default behaviour.
  94. // To force the config portal, even though the module was connected before,
  95. // comment-out autoConnect and use startConfigPortal instead.
  96. WiFiManager wifiManager;
  97. wifiManager.autoConnect(DEFAULT_SSID, DEFAULT_PASS);
  98. //wifiManager.startConfigPortal(DEFAULT_SSID, DEFAULT_PASS);
  99. initMemory();
  100. storage = readMemory();
  101. // Wait for connection
  102. if (WiFi.status() != WL_CONNECTED) {
  103. while (WiFi.status() != WL_CONNECTED) {
  104. delay(500);
  105. Serial.print(".");
  106. }
  107. Serial.println("");
  108. }
  109. Serial.print("IP address: ");
  110. Serial.println(WiFi.localIP());
  111. broadcastIP = ~WiFi.subnetMask() | WiFi.gatewayIP();
  112. server.on("/", handleRoot);
  113. server.onNotFound(handleNotFound);
  114. server.begin();
  115. serverSocket.begin();
  116. // NTP-Client
  117. ntp.begin(NTP_PORT_FROM);
  118. WiFi.hostByName(ntpServerName, timeServerIP);
  119. lastNTP = millis();
  120. sendNTPpacket(timeServerIP);
  121. udp.begin(BROADCAST_PORT);
  122. Serial.println("ESP-Weather ready!");
  123. }
  124. void loop(void){
  125. server.handleClient();
  126. // Websocket fuer Browser
  127. WiFiClient client = serverSocket.available();
  128. if (client.connected() && webSocketServer.handshake(client)) {
  129. Serial.println("Building WebSocket Response...");
  130. String json = "{\"H\":";
  131. json += String(SHT21.getHumidity());
  132. json += ",";
  133. json += "\"T\":";
  134. json += String(SHT21.getTemperature());
  135. json += ", \"EEPROM\" : [";
  136. for (int i = 0; i < storage.header.count; i++) {
  137. json += "{\"H\":";
  138. json += String(storage.data[i].humidity);
  139. json += ",";
  140. json += "\"T\":";
  141. json += String(storage.data[i].temperature);
  142. json += "}";
  143. if (i < storage.header.count - 1) {
  144. json += ",";
  145. }
  146. }
  147. json += "]}";
  148. Serial.println("WebSocket Response:");
  149. Serial.println(json);
  150. webSocketServer.sendData(json);
  151. client.flush();
  152. client.stop();
  153. }
  154. // NTP wiederholen falls keine Antwort
  155. if ((timestamp == 0) && ((millis() - lastNTP) > NTP_RETRY_TIMEOUT)) {
  156. Serial.println("NTP packet retry...");
  157. WiFi.hostByName(ntpServerName, timeServerIP);
  158. lastNTP = millis();
  159. sendNTPpacket(timeServerIP);
  160. }
  161. // NTP Paket vom Server erhalten
  162. if (ntp.parsePacket() >= NTP_PACKET_SIZE) {
  163. ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);
  164. unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
  165. unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
  166. unsigned long secsSince1900 = highWord << 16 | lowWord;
  167. const unsigned long seventyYears = 2208988800UL;
  168. unsigned long epoch = secsSince1900 - seventyYears;
  169. timestamp = epoch;
  170. timeReceived = millis();
  171. Serial.print("Got NTP time: ");
  172. Serial.println(epoch);
  173. }
  174. // EEPROM-Schreiben jede Stunde
  175. if ((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0)
  176. && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
  177. Serial.println("Storing new data packet...");
  178. lastStorageTime = millis();
  179. storeAtBoot = 0;
  180. if (storage.header.count < MAX_STORAGE) {
  181. storage.header.count++;
  182. } else {
  183. for(int i = 0; i < MAX_STORAGE - 1; i++) {
  184. storage.data[i] = storage.data[i+1];
  185. }
  186. }
  187. storage.data[storage.header.count - 1].temperature = SHT21.getTemperature();
  188. storage.data[storage.header.count - 1].humidity = SHT21.getHumidity();
  189. writeMemory(storage);
  190. }
  191. // UDP
  192. int packetSize = udp.parsePacket();
  193. if (packetSize) {
  194. IPAddress remoteIp = udp.remoteIP();
  195. // read the packet into packetBufffer
  196. int len = udp.read(packetBuffer, UDP_PACKET_BUFFER_SIZE);
  197. if (len > 0) {
  198. packetBuffer[len] = 0;
  199. }
  200. Serial.print("Got UDP packet: ");
  201. Serial.println(packetBuffer);
  202. if (strcmp(packetBuffer, pingBuffer) == 0) {
  203. Serial.println("Broadcast");
  204. udp.beginPacket(udp.remoteIP(), udp.remotePort());
  205. udp.print(echoBuffer);
  206. udp.endPacket();
  207. } else if((strcmp(packetBuffer, echoBuffer) == 0) && (waitingForReplies == true)) {
  208. vecClients.push_back(udp.remoteIP());
  209. }
  210. }
  211. if (((millis() - lastTime) >= MAX_BROADCAST_WAIT_TIME) && (waitingForReplies == true)) {
  212. Serial.println("Timeout, sending response...");
  213. waitingForReplies = false;
  214. String message = htmlBegin;
  215. message += "var clients = Array(";
  216. message += "\"" + WiFi.localIP().toString() + "\"";
  217. if (vecClients.size() > 0) {
  218. message += ", ";
  219. }
  220. for (int i = 0; i < vecClients.size(); i++) {
  221. message += "\"" + vecClients[i].toString() + "\"";
  222. if (i < (vecClients.size() - 1)) {
  223. message += ", ";
  224. }
  225. }
  226. message += ");";
  227. message += htmlEnd;
  228. vecClients.clear();
  229. server.send(200, "text/html", message);
  230. }
  231. }
  232. void sendNTPpacket(IPAddress& address) {
  233. Serial.println("Sending NTP packet...");
  234. memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
  235. ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
  236. ntpPacketBuffer[1] = 0;
  237. ntpPacketBuffer[2] = 6;
  238. ntpPacketBuffer[3] = 0xEC;
  239. ntpPacketBuffer[12] = 49;
  240. ntpPacketBuffer[13] = 0x4E;
  241. ntpPacketBuffer[14] = 49;
  242. ntpPacketBuffer[15] = 52;
  243. ntp.beginPacket(address, NTP_PORT_TO);
  244. ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
  245. ntp.endPacket();
  246. }