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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 <EEPROM.h>
  10. #include <DNSServer.h>
  11. #include <WiFiManager.h>
  12. #define NTP_PORT 2392
  13. #define MAX_WAIT_TIME 550
  14. #define EEPROM_SIZE 512
  15. // NTP-Client
  16. IPAddress timeServerIP;
  17. const char* ntpServerName = "time.nist.gov";
  18. const int NTP_PACKET_SIZE = 48;
  19. byte ntpPacketBuffer[NTP_PACKET_SIZE];
  20. WiFiUDP ntp;
  21. unsigned long timestamp = 0;
  22. unsigned long timeReceived = 0;
  23. unsigned long lastStorageTime = 0;
  24. byte storeAtBoot = 1;
  25. unsigned long lastNTP = 0;
  26. SHT21 SHT21;
  27. ESP8266WebServer server(80);
  28. WiFiServer serverSocket(2391);
  29. WebSocketServer webSocketServer;
  30. #define DEFAULT_SSID "ESP-Weather"
  31. #define DEFAULT_PASS "testtest"
  32. IPAddress broadcastIP;
  33. struct __attribute__((__packed__)) Measurement {
  34. float temperature;
  35. float humidity;
  36. };
  37. struct __attribute__((__packed__)) Header {
  38. uint8_t count;
  39. uint16_t checksum;
  40. };
  41. #define MAX_STORAGE (EEPROM_SIZE - sizeof(Header)) / sizeof(Measurement)
  42. struct __attribute__((__packed__)) PersistentStorage {
  43. Measurement data[MAX_STORAGE];
  44. Header header;
  45. };
  46. PersistentStorage storage;
  47. void writeMemory(PersistentStorage &s) {
  48. Serial.println("write Memory");
  49. unsigned char* r = (unsigned char*) &s;
  50. uint16_t a = 0, b = 0;
  51. for(int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
  52. a = (a + r[i]) % 255;
  53. b = (b + a) % 255;
  54. }
  55. s.header.checksum = (b << 8) | a;
  56. for(int i = 0; i < sizeof(PersistentStorage); i++) {
  57. EEPROM.write(i, r[i]);
  58. }
  59. EEPROM.commit();
  60. }
  61. PersistentStorage readMemory() {
  62. PersistentStorage s;
  63. unsigned char* r = (unsigned char*) &s;
  64. for(int i = 0; i < sizeof(PersistentStorage); i++) {
  65. r[i] = EEPROM.read(i);
  66. }
  67. uint16_t a = 0, b = 0;
  68. for(int i = 0; i < sizeof(PersistentStorage) - 2; i++) {
  69. a = (a + r[i]) % 255;
  70. b = (b + a) % 255;
  71. }
  72. if(s.header.checksum != ((b << 8) | a)) {
  73. Serial.print("Checksum error ");
  74. Serial.print(s.header.checksum);
  75. Serial.print(" ");
  76. Serial.println((b << 8) | a);
  77. s.header.count = 0;
  78. } else {
  79. Serial.println("Checksum ok");
  80. }
  81. return s;
  82. }
  83. std::vector<IPAddress> vecClients;
  84. // UDP-Config
  85. unsigned int localPort = 2390;
  86. char packetBuffer[255];
  87. char pingBuffer[] = "pingESP8266v0.1";
  88. char echoBuffer[] = "echoESP8266v0.1";
  89. WiFiUDP Udp;
  90. unsigned long lastTime;
  91. bool waitingForReplies = false;
  92. const char* htmlBegin = "<html>\
  93. <head>\
  94. <title>Sysadmin</title>\
  95. <script src=\"http://hoegerle-home.de/sysAdmin/js/jquery-3.1.1.min.js\"></script>\
  96. <script src=\"http://hoegerle-home.de/sysAdmin/js/bootstrap.min.js\"></script>\
  97. <script src=\"http://hoegerle-home.de/sysAdmin/js/Chart.bundle.min.js\"></script>\
  98. <script src=\"http://hoegerle-home.de/sysAdmin/js/script.js\"></script>\
  99. <link rel=\"stylesheet\" href=\"http://hoegerle-home.de/sysAdmin/css/bootstrap.min.css\" />\
  100. </head>\
  101. <body>\
  102. <script type=\"text/javascript\">";
  103. const char* htmlEnd = "</script>\
  104. </body>\
  105. </html>";
  106. // root-URL
  107. void handleRoot() {
  108. // send a reply, to the IP address and port that sent us the packet we received
  109. Udp.beginPacket(broadcastIP, 2390);
  110. Udp.write(pingBuffer);
  111. Udp.endPacket();
  112. // Timer starten
  113. lastTime = millis();
  114. waitingForReplies = true;
  115. Serial.println("broadcast send");
  116. }
  117. // URL nicht vorhanden
  118. void handleNotFound(){
  119. String message = "File Not Found\n\n";
  120. message += "URI: ";
  121. message += server.uri();
  122. message += "\nMethod: ";
  123. message += (server.method() == HTTP_GET)?"GET":"POST";
  124. message += "\nArguments: ";
  125. message += server.args();
  126. message += "\n";
  127. for (uint8_t i=0; i<server.args(); i++){
  128. message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  129. }
  130. server.send(404, "text/plain", message);
  131. }
  132. void setup(void) {
  133. EEPROM.begin(512);
  134. // Debugging
  135. Serial.begin(115200);
  136. Serial.println("");
  137. SHT21.begin();
  138. WiFiManager wifiManager;
  139. // use one or the other, never both!
  140. wifiManager.autoConnect(DEFAULT_SSID, DEFAULT_PASS);
  141. //wifiManager.startConfigPortal(DEFAULT_SSID, DEFAULT_PASS);
  142. storage = readMemory();
  143. // Wait for connection
  144. while (WiFi.status() != WL_CONNECTED) {
  145. delay(500);
  146. Serial.print(".");
  147. }
  148. Serial.println("");
  149. Serial.print("IP address: ");
  150. Serial.println(WiFi.localIP());
  151. broadcastIP = ~WiFi.subnetMask() | WiFi.gatewayIP();
  152. server.on("/", handleRoot);
  153. server.onNotFound(handleNotFound);
  154. server.begin();
  155. serverSocket.begin();
  156. // NTP-Client
  157. ntp.begin(NTP_PORT);
  158. WiFi.hostByName(ntpServerName, timeServerIP);
  159. lastNTP = millis();
  160. sendNTPpacket(timeServerIP);
  161. Udp.begin(localPort);
  162. Serial.println("HTTP server and UDP started");
  163. }
  164. void loop(void){
  165. server.handleClient();
  166. // Websocket fuer Browser
  167. WiFiClient client = serverSocket.available();
  168. if(client.connected() && webSocketServer.handshake(client)) {
  169. String json = "{\"H\":";
  170. json += String(SHT21.getHumidity());
  171. json += ",";
  172. json += "\"T\":";
  173. json += String(SHT21.getTemperature());
  174. json += ", \"EEPROM\" : [";
  175. for(int i = 0; i < storage.header.count; i++) {
  176. json += "{\"H\":";
  177. json += String(storage.data[i].humidity);
  178. json += ",";
  179. json += "\"T\":";
  180. json += String(storage.data[i].temperature);
  181. json += "}";
  182. if(i < storage.header.count - 1) {
  183. json += ",";
  184. }
  185. }
  186. json += "]}";
  187. Serial.println(json);
  188. webSocketServer.sendData(json);
  189. client.flush();
  190. client.stop();
  191. }
  192. // NTP wiederholen falls keine Antwort
  193. if((timestamp == 0) && ((millis() - lastNTP) > 2000)) {
  194. WiFi.hostByName(ntpServerName, timeServerIP);
  195. lastNTP = millis();
  196. sendNTPpacket(timeServerIP);
  197. }
  198. // NTP Paket vom Server erhalten
  199. if(ntp.parsePacket() >= NTP_PACKET_SIZE) {
  200. ntp.read(ntpPacketBuffer, NTP_PACKET_SIZE);
  201. unsigned long highWord = word(ntpPacketBuffer[40], ntpPacketBuffer[41]);
  202. unsigned long lowWord = word(ntpPacketBuffer[42], ntpPacketBuffer[43]);
  203. unsigned long secsSince1900 = highWord << 16 | lowWord;
  204. const unsigned long seventyYears = 2208988800UL;
  205. unsigned long epoch = secsSince1900 - seventyYears;
  206. timestamp = epoch;
  207. timeReceived = millis();
  208. Serial.println(epoch);
  209. }
  210. // EEPROM-Schreiben jede Stunde
  211. if((((((millis() - timeReceived) / 1000) + timestamp) % 3600) == 0) && (timestamp != 0) && (((millis() - lastStorageTime) > 100000) || storeAtBoot) ) {
  212. lastStorageTime = millis();
  213. storeAtBoot = 0;
  214. if(storage.header.count < MAX_STORAGE) {
  215. storage.header.count++;
  216. } else {
  217. for(int i = 0; i < MAX_STORAGE - 1; i++) {
  218. storage.data[i] = storage.data[i+1];
  219. }
  220. }
  221. storage.data[storage.header.count-1].temperature = SHT21.getTemperature();
  222. storage.data[storage.header.count-1].humidity = SHT21.getHumidity();
  223. writeMemory(storage);
  224. }
  225. // UDP
  226. int packetSize = Udp.parsePacket();
  227. if(packetSize) {
  228. IPAddress remoteIp = Udp.remoteIP();
  229. // read the packet into packetBufffer
  230. int len = Udp.read(packetBuffer, 255);
  231. if (len > 0) {
  232. packetBuffer[len] = 0;
  233. }
  234. Serial.println(packetBuffer);
  235. if(strcmp(packetBuffer, pingBuffer) == 0) {
  236. Serial.println("Broadcast");
  237. Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
  238. Udp.print(echoBuffer);
  239. Udp.endPacket();
  240. } else if((strcmp(packetBuffer, echoBuffer) == 0) && (waitingForReplies == true)) {
  241. vecClients.push_back(Udp.remoteIP());
  242. }
  243. }
  244. if(((millis() - lastTime) >= MAX_WAIT_TIME) && (waitingForReplies == true)) {
  245. Serial.println("waiting done");
  246. waitingForReplies = false;
  247. String message = htmlBegin;
  248. message += "var clients = Array(";
  249. message += "\"" + WiFi.localIP().toString() + "\"";
  250. if(vecClients.size() > 0) {
  251. message += ", ";
  252. }
  253. for(int i = 0; i < vecClients.size(); i++) {
  254. message += "\"" + vecClients[i].toString() + "\"";
  255. if(i < (vecClients.size() - 1)) {
  256. message += ", ";
  257. }
  258. }
  259. message += ");";
  260. message += htmlEnd;
  261. vecClients.clear();
  262. server.send(200, "text/html", message);
  263. }
  264. }
  265. void sendNTPpacket(IPAddress& address) {
  266. Serial.println("sending NTP packet...");
  267. memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE);
  268. ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode
  269. ntpPacketBuffer[1] = 0;
  270. ntpPacketBuffer[2] = 6;
  271. ntpPacketBuffer[3] = 0xEC;
  272. ntpPacketBuffer[12] = 49;
  273. ntpPacketBuffer[13] = 0x4E;
  274. ntpPacketBuffer[14] = 49;
  275. ntpPacketBuffer[15] = 52;
  276. ntp.beginPacket(address, 123);
  277. ntp.write(ntpPacketBuffer, NTP_PACKET_SIZE);
  278. ntp.endPacket();
  279. }