———————- Untitled11.txt ———————-
1 #include “esp_sleep.h” 2 #include “FS.h” 3 #include “SPIFFS.h” 4 #include <time.h> 5 #include <WiFi.h> 6 #include <WiFiUdp.h> //For NTP Server 7 #include <DHT_U.h> 8 //#include “DHT.h” 9 #include <NTPClient.h> 10 #include <stdlib.h> /* atoi */ 11 #include <stdio.h> /* printf, fgets */ 12 #include <String.h> 13 #line 15 “DHT_Ruis_SantosV1.9″// (this ligne number +1) __LINE__ “DHT_Ruis_SantosV1.9” 14 // Define NTP Client to get time 15 WiFiUDP ntpUDP; 16 NTPClient timeClient(ntpUDP); 17 WiFiClient client; 18 WiFiServer server(80); 19 20 #define Threshold 40 /* Greater the value, more the touch sensitivity */ 21 #define DHTTYPE DHT11 // DHT 11 22 #define uS_TO_S_FACTOR 1000000ULL //for sleep only 23 #define HOURS 60 //(7200 = 120 minutes) 43200 secondes , soit 12 heures 24 #define TIME_TO_SLEEP_MAX 80ULL // MAX Time to sleep in case of repeatable unsuccessfull connection attempts 25 #define TIME_TO_SLEEP_CASE1 3600ULL //(15min = 900s) (1h = 3600s) in if the time is 11:00 – 12:00 26 #define TIME_TO_SLEEP_CASE2 72000ULL //3h (4h = 14400) (20h = 72000s)if time isn’t 11:00 – 12:00 27 #define DAY_PERIOD_START 480 //(8h =480min)(12h =720min )in minutes the morning 28 #define DAY_PERIOD_END 960 //(17h =1020 )(20h =1200min) in minutes later 29 #define VM_DEBUG 1 //0 = false 30 RTC_DATA_ATTR unsigned long timeDiff, timeDiff2; 31 RTC_DATA_ATTR int TIME_TO_SLEEP_WiFi = 10; // Time to sleep in case of unavailable WiFi (This is the first sleep) 32 String newLinesArray[40]; 33 RTC_DATA_ATTR uint8_t newLinesCnt = 0; 34 RTC_DATA_ATTR long calcul5 = 0.0; 35 // Replace with your network credentials 36 const char* ssid = “Network_1”; 37 const char* password = “xxxxxxxxxxx”; 38 39 //wroom mac address 24:6f:28:17:f9:50 40 // Variables to save date and time 41 long timezone = -5; 42 uint8_t daysavetime = 1; 43 struct tm tmstruct ; 44 unsigned long currentMillis; 45 const unsigned long period = 10000; //period that esp32 will try to connect with WIFI in ms 46 String formattedDate; 47 String timeStamp; 48 // DHT Sensor 49 const int DHTPin = 16; 50 RTC_DATA_ATTR const int relay = 26; //pin dixième piton relais 51 RTC_DATA_ATTR uint8_t dryRedAlarm = 55; 52 uint8_t pinToRead = 36, newLinesCnt2; 53 // Initialize DHT sensor. 54 DHT dht(DHTPin, DHTTYPE); 55 static char celsiusTemp[7]; 56 static char fahrenheitTemp[7]; 57 static char humidityTemp[7]; 58 char dayBuff[130]; 59 char lineBuff[130]; 60 char atoiBuff1[3]; 61 char atoiBuff2[3]; 62 int datCnt, maxCount = 100; 63 int decCnt = ( maxCount – 1); 64 RTC_DATA_ATTR uint8_t flag = 0; 65 RTC_DATA_ATTR uint8_t usedFlagNum[100]; 66 RTC_DATA_ATTR int minut1Cp = -1; 67 RTC_DATA_ATTR int minut2Cp = 0; 68 int charcount = 0; 69 int val; 70 int bootCount = 0; 71 int heureNormal = 3600; //-3600 pour l’heure avancée 72 RTC_DATA_ATTR int add_Delays = 0; 73 float hic; 74 String aNewLine = “”;// previousNewline; 75 String datArray[150]; // our data array holding 30 elements 76 void myDebug(String what, int lineNumb) { 77 #if defined VM_DEBUG 78 printf(“\n——:line__%d__ “, lineNumb); 79 Serial.print(what); 80 #endif 81 } 82 void timerFunction(long long delays) { 83 unsigned long long previousMillis; 84 previousMillis = millis(); 85 while ((millis() – previousMillis) < delays) { 86 analogRead(pinToRead); 87 } 88 } 89 int whileFunction(uint8_t readings, long delays, uint8_t foroncer) { 90 unsigned long long previousMillis; 91 int totVal = 0, val = 0; 92 uint8_t oncer = foroncer; 93 uint8_t turns = 0; 94 while (turns < readings) { 95 if (oncer < 1) { 96 //lets the device warm up 5 minutes 97 analogRead(pinToRead); 98 previousMillis = millis(); 99 while ((millis() – previousMillis) < 300000) {//5 min 100 ; 101 } 102 //Serial.println(“dummy reading end”); 103 oncer = 1; 104 } 105 val = analogRead(pinToRead); //connect sensor to Analog 11 or else 106 previousMillis = millis(); 107 while ((millis() – previousMillis) < delays) { 108 ; 109 } 110 if (isnan(val)) { 111 Serial.println(“Failed to read from probe.”); 112 return 0; 113 } 114 //printf(“_%d val brute avant map= %d\n”, __LINE__, val); 115 // % = (val- map low value)/(map top value- map low value) 116 //0,100 => 1/% 117 //map(value, fromLow, fromHigh, toLow, toHigh) 118 val = map(val, 2450, 1615, 0, 100); 119 totVal += val; 120 //printf(“%d %d\n”, val, totVal); 121 turns++; 122 } 123 printf(“dryRedAlarm %d <–> %d (totVal/readings)\n”, dryRedAlarm, (totVal / readings)); 124 return (totVal / readings); 125 } 126 void ampoule(int probe) { 127 if (probe < dryRedAlarm) { 128 digitalWrite(relay, HIGH); 129 printf(“Ampoule allumée.\n”); 130 //while Function tant que val < dryRedAlarm 131 //whileFunction(1, 120.0, 1)// 6E7 = 1000 min = 16.6 heures 132 while (probe < dryRedAlarm) { 133 // 1= nombre de fois, 36E2=1 heure, 0=avec réchauffement 134 probe = whileFunction(5, 2000.0, 1); //1 = pas de réchauffement 135 } 136 } 137 digitalWrite(relay, LOW); 138 printf(“Ampoule éteinte.\n”); 139 //printf(“ligne_%d humidité du sol: %d\n”, __LINE__, w); 140 } 141 void print_wakeup_reason() { 142 esp_sleep_wakeup_cause_t wakeup_reason; 143 wakeup_reason = esp_sleep_get_wakeup_cause(); 144 switch (wakeup_reason) 145 { 146 case ESP_SLEEP_WAKEUP_EXT0 : Serial.println(“Wakeup caused by external signal using RTC_IO”); break; 147 case ESP_SLEEP_WAKEUP_EXT1 : Serial.println(“Wakeup caused by external signal using RTC_CNTL”); break; 148 case ESP_SLEEP_WAKEUP_TIMER : Serial.println(“Wakeup caused by timer”); break; 149 case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println(“Wakeup caused by touchpad”); break; 150 case ESP_SLEEP_WAKEUP_ULP : Serial.println(“Wakeup caused by ULP program”); break; 151 default : printf(“Wakeup was not caused by deep sleep: %d\n”, wakeup_reason); break; 152 } 153 } 154 long longMinutStamp() { 155 // Variables to save date and time 156 String formattedDate; 157 String dayStamp; 158 String timeStamp, timeStamp1, timeStamp2, timeStamp3; 159 long longMinutStamp; 160 while (!timeClient.update()) { 161 timeClient.forceUpdate(); 162 } 163 timeClient.setTimeOffset(-18000 + heureNormal); 164 formattedDate = timeClient.getFormattedDate(); 165 int splitT = formattedDate.indexOf(“T”); 166 dayStamp = formattedDate.substring(0, splitT); 167 //timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() – 1); 168 timeStamp1 = formattedDate.substring(splitT + 3, formattedDate.length() – 9); 169 timeStamp2 = formattedDate.substring(splitT + 4, formattedDate.length() – 4); 170 timeStamp3 = formattedDate.substring(splitT + 7, formattedDate.length() – 1); 171 longMinutStamp = atoi(timeStamp1.c_str()) * 60; 172 longMinutStamp += atoi(timeStamp2.c_str()); 173 longMinutStamp += atoi(timeStamp3.c_str()) / 60; 174 //returns minutes 175 return longMinutStamp; 176 } 177 long timeDiffData(long minut) 178 { //returns minutes difference 179 RTC_DATA_ATTR static long previous; 180 Serial.println(“_116 – previous = ” + (String)previous); 181 if (previous != 0) 182 { 183 return (minut – previous); 184 } else { 185 previous = minut; 186 return (minut – longMinutStamp()); 187 } 188 } 189 String myDate() { 190 // Variables to save date and time 191 String formattedDate; 192 String dayStamp; 193 String timeStamp; 194 String myDate; 195 while (!timeClient.update()) { 196 timeClient.forceUpdate(); 197 } 198 timeClient.setTimeOffset(-18000 + heureNormal); 199 formattedDate = timeClient.getFormattedDate(); 200 int splitT = formattedDate.indexOf(“T”); 201 dayStamp = formattedDate.substring(0, splitT); 202 timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() – 1); // 203 myDate = dayStamp + ” ” + timeStamp; 204 //Serial.println(myDate); 205 return myDate; 206 } 207 void readData() { 208 int datCnt = 0; 209 File f = SPIFFS.open(“/gardenTemp.txt”, “r”); 210 if (!f) { 211 Serial.println(“====== Reading from SPIFFS file FAILED =======”); 212 } else 213 Serial.println(“====== Reading from SPIFFS file =======”); 214 while (f.available()) { 215 //Lets read line by line from the file 216 String line = f.readStringUntil(‘\n’); 217 Serial.print(datCnt); 218 Serial.print(” “); 219 Serial.println(line); 220 datCnt ++; 221 } 222 f.close(); 223 Serial.println(“====== End reading from SPIFFS file =======”); 224 } 225 //============ appendFile Start ================ 226 void appendFile(fs::FS &fs, const char * path, const char * message) { 227 File file = fs.open(path, FILE_APPEND); 228 if (!file) { 229 Serial.println(“Failed to open file for appending”); 230 return; 231 } 232 if (file.print(message)) { 233 printf(“\n%s\n”, message); 234 printf(“->|__Appended to file: %s\n”, path); 235 } else { 236 printf(“\nAppend failed: %s\n”, message); 237 } 238 file.close(); 239 } 240 double dewPoint(double celsius, double humidity) 241 { 242 // (1) Saturation Vapor Pressure = ESGG(T) 243 double RATIO = 373.15 / (273.15 + celsius); 244 double RHS = -7.90298 * (RATIO – 1); 245 RHS += 5.02808 * log10(RATIO); 246 RHS += -1.3816e-7 * (pow(10, (11.344 * (1 – 1 / RATIO ))) – 1) ; 247 RHS += 8.1328e-3 * (pow(10, (-3.49149 * (RATIO – 1))) – 1) ; 248 RHS += log10(1013.246); 249 // factor -3 is to adjust units – Vapor Pressure SVP * humidity 250 double VP = pow(10, RHS – 3) * humidity; 251 // (2) DEWPOINT = F(Vapor Pressure) 252 double T = log(VP / 0.61078); // temp var 253 return (241.88 * T) / (17.558 – T); 254 } 255 //=================== Listing SPIFFS Files ======= 256 void listDir(fs::FS &fs, const char * dirname, uint8_t levels) { 257 Serial.println(“====== Listing DIR SPIFFS files =======”); 258 printf(“Listing directory: %s\n”, dirname); 259 File root = fs.open(dirname); 260 if (!root) { 261 Serial.println(“Failed to open directory”); 262 return; 263 } 264 if (!root.isDirectory()) { 265 Serial.println(“Not a directory”); 266 return; 267 } 268 File file = root.openNextFile(); 269 while (file) { 270 if (file.isDirectory()) { 271 Serial.print(” DIR : “); 272 Serial.print (file.name()); 273 time_t t = file.getLastWrite(); 274 struct tm * tmstruct = localtime(&t); 275 printf(” LAST WRITE: %d-%02d-%02d\n”, (tmstruct->tm_year) + 1900, ( tmstruct->tm_mon) + 1, tmstruct->tm_mday); //,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec 276 if (levels) { 277 listDir(fs, file.name(), levels – 1); 278 } 279 } else { 280 Serial.print(” FILE: “); 281 Serial.print(file.name()); 282 Serial.print(” SIZE: “); 283 Serial.print(file.size()); 284 time_t t = file.getLastWrite(); 285 struct tm * tmstruct = localtime(&t); 286 printf(” LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n”, (tmstruct->tm_year) + 1900, ( tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); 287 } 288 file = root.openNextFile(); 289 } 290 Serial.println(“====== End listing DIR SPIFFS files =======”); 291 } 292 void writeFile(const char * path, const char * message) { 293 File file = SPIFFS.open(path, “w”); 294 if (!file) { 295 Serial.println(“Failed to open file for writing” + *path); 296 file.close(); 297 return; 298 } 299 if (file.print(message)) { 300 printf(“\nErasing or writing file: %s OK\n”, path); 301 } else { 302 Serial.println(“Write or erasing failed\n” + *path); 303 } 304 file.close(); 305 } 306 void callback() { 307 Serial.println(); 308 Serial.println(“Awaken by pin GPIO(4 fourth pin) touch …”); 309 Serial.println(“On the boot button side of the card.”); 310 Serial.println(); 311 ESP.restart(); 312 } 313 //========================== minuteSort ====================================== 314 int minuteSort(String theMinuts) { 315 //Serial.println(“inString.toInt()%d inString.toInt()/%d•\n”, inString.toInt(),inString.toInt()/2); 316 char atoiBuff[3]; 317 Serial.println(“theMinuts•” + theMinuts + “•”); 318 printf(“_%d 0=%c\n”, __LINE__, theMinuts.charAt(0)); 319 printf(“_%d 1=%c\n”, __LINE__, theMinuts.charAt(1)); 320 printf(“_%d 2=%c\n”, __LINE__, theMinuts.charAt(2)); 321 if (theMinuts.charAt(0) == 48) { 322 atoiBuff [0] = theMinuts.charAt(1); 323 atoiBuff [1] = ‘\0’; 324 atoiBuff [2] = ‘\0’; 325 } else { 326 atoiBuff [0] = theMinuts.charAt(0); 327 atoiBuff [1] = theMinuts.charAt(1); 328 atoiBuff [2] = ‘\0’; 329 } 330 int minutCp5 = atoi(atoiBuff); 331 printf(“0= %c\n”, atoiBuff [0] ); 332 printf(“1= %c\n”, atoiBuff [1] ); 333 printf(“2= %c\n”, atoiBuff [2] ); 334 //printf(“_%d- atoiBuff [0], atoiBuff [1], atoiBuff [2], atoiBuff)\n•%c•%c•%c•%c\n”, __LINE__, atoiBuff [0], atoiBuff [1], atoiBuff [2], *atoiBuff); 335 return minutCp5; 336 } 337 //========================== END ====================================== 338 //==================== SETUP BEGIN ==================================== 339 void setup() { 340 Serial.begin(115200); 341 while (!Serial) { 342 ; // wait for serial port to connect. Needed for native USB port only 343 } 344 //Setup interrupt on Touch Pad 3 (GPIO15) 345 touchAttachInterrupt(T3, callback, Threshold); 346 esp_sleep_enable_touchpad_wakeup();//Configure Touchpad as wakeup source 347 // initialize the DHT sensor 348 dht.begin(); 349 /*——————————————————————————————————*/ 350 //Print the wakeup reason for ESP32 351 print_wakeup_reason(); 352 WiFi.begin(ssid, password); 353 while (WiFi.status() != WL_CONNECTED) { 354 currentMillis = millis(); //Assign the ms have been passed since ESP32 code start running 355 Serial.println(“Boot number: ” + String(++bootCount)); 356 if (currentMillis > period) { 357 WiFi.disconnect(); 358 esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_WiFi * uS_TO_S_FACTOR); 359 Serial.println(“Wifi to sleep now for ” + String(TIME_TO_SLEEP_WiFi) + ” Seconds” + ” Due to WiFi unavailability”); 360 while (TIME_TO_SLEEP_WiFi < TIME_TO_SLEEP_MAX) { // While the sleep time is less than the predefined limit keep double the sleep time. When the sleep time exceeds the limit then keep a constant sleep time equal to the limit. 361 TIME_TO_SLEEP_WiFi = TIME_TO_SLEEP_WiFi * 2; // Double the sleep time 362 esp_deep_sleep_start(); 363 } 364 TIME_TO_SLEEP_WiFi = TIME_TO_SLEEP_MAX; // Set the sleep time equal to the limit 365 esp_deep_sleep_start(); 366 } 367 delay(1000); 368 } 369 /*—————————————————————————————————–*/ 370 server.begin(); 371 Serial.print(“Connected to “); 372 Serial.print(ssid); 373 Serial.println(” network”); 374 Serial.println(WiFi.macAddress()); 375 Serial.println(WiFi.RSSI()); 376 Serial.print(“IP address: “); 377 Serial.println(WiFi.localIP()); 378 //if a temp file has already been in use, open it and load it’s data to array. 379 SPIFFS.begin(); 380 if (!SPIFFS.begin()) { 381 Serial.println(” Not SPIFFS.begin()”); 382 } 383 //listDir(SPIFFS, “/”, 0); 384 //erase file 385 if (flag == 0)writeFile(“/gardenTemp.txt”, ‘\0’); 386 File f = SPIFFS.open(“/gardenTemp.txt”, “r”); 387 if (!f) { 388 Serial.println(“file open failed”); 389 } 390 Serial.println(“====== Setup Start reading from SPIFFS file =======”); 391 while (f.available() && datCnt < maxCount) { 392 //Lets read line by line from the file 393 String line = f.readStringUntil(‘\n’); 394 if (line != 0) { 395 if (datCnt > 9) { 396 Serial.print(datCnt); 397 Serial.print(” “); 398 Serial.println(line); 399 datArray[datCnt] = line; 400 } else { 401 Serial.print(0); 402 Serial.print(datCnt); 403 Serial.print(” “); 404 Serial.println(line); 405 //line = “0” + line; 406 datArray[datCnt] = line; 407 } 408 datCnt ++; 409 } 410 } 411 f.close(); 412 Serial.println(“====== Setup End reading from SPIFFS file =======\n”); 413 /*—————————————————————————————————–*/ 414 timeClient.begin(); // Initialize a NTPClient to get time 415 // Set offset time in seconds to adjust for your timezone, for example: 416 timeClient.setTimeOffset(-18000 + heureNormal); //Cyprus Time Zone GMT -5 = -18000 417 pinMode(relay, OUTPUT); 418 /*—————————————————————————————————–*/ 419 // 1= nombre de fois, 36E2=1 heure, 0=avec réchauffement 420 Serial.println(myDate()); 421 Serial.print(“NTP • “);//Client initialized 422 int a = whileFunction(3, 120000.0, 0);//0=réchauffe, 5min + 6 min 423 ampoule(a); 424 Serial.println(“setup end” + myDate()); 425 } 426 //======================= SETUP END ==================================== 427 void loop() { 428 // ———————— BEGIN if replaced 429 if ((flag != 0) ) { //&& (flag % 3) == 0, && (flag < 2) 430 while (!timeClient.update()) { 431 timeClient.forceUpdate(); 432 } 433 // The formattedDate comes with the following format: 434 long long _Entre_Deux = longMinutStamp(); 435 long long calcul3 = _Entre_Deux; 436 long long calcul4 = 0.0; 437 printf(” Between START & END %04lld \n”, _Entre_Deux); 438 _Entre_Deux = _Entre_Deux – DAY_PERIOD_START; 439 printf(“-%d DAY_PERIOD_START %04lld \n” , DAY_PERIOD_START, _Entre_Deux); 440 calcul4 = calcul3 – DAY_PERIOD_END; 441 printf(“-%d DAY_PERIOD_START_END %04lld\n”, DAY_PERIOD_END, calcul4); 442 /*———————————————-*/ 443 printf(“________ 0 to _________ line_%d\n”, __LINE__); 444 Serial.println(“0 ” + newLinesArray[0]); 445 Serial.println(“1 ” + newLinesArray[1]); 446 Serial.println(“2 ” + newLinesArray[2]); 447 Serial.println(“3 ” + newLinesArray[3]); 448 Serial.println(“________3_________”); 449 /*———————————————-*/ 450 printf(“newLinesCnt#%d flag#_%d Line_%d\n”, newLinesCnt, flag, __LINE__); 451 Serial.println(“newLinesCnt#1 ” + newLinesArray[(newLinesCnt – 1)]); 452 // printf(“\nIn for (newLinesArray[i])┐\n”); 453 // for (int i = newLinesCnt ; i >= 0 ; i–) { 454 // Serial.print(newLinesArray[i]); 455 // } 456 // printf(“\nOut for (newLinesArray[i])┘ \n”); 457 Serial.println(myDate()); 458 /*———————————————-*/ 459 if ((calcul3 >= DAY_PERIOD_START) && (calcul3 <= DAY_PERIOD_END)) { 460 esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_CASE1 * uS_TO_S_FACTOR); 461 printf(“\n->CASE1-> Going to sleep for %3.00f minutes\n” , (TIME_TO_SLEEP_CASE1 / 60.0)); 462 esp_light_sleep_start(); //esp_deep_sleep_start();// 463 } else { 464 esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_CASE2 * uS_TO_S_FACTOR); 465 newLinesArray[newLinesCnt2].toCharArray(dayBuff, 130); 466 const char *result2 = dayBuff; 467 printf(“result2 %s\n”, result2); 468 appendFile(SPIFFS, “/gardenTemp.txt”, result2); 469 printf(“_%d ->CASE2-> Going to sleep for %6.0f minutes\n”, __LINE__, (TIME_TO_SLEEP_CASE2 / 60.0)); 470 flag = 0; //deep sleep reset variables to 0 471 newLinesCnt = 0; 472 esp_deep_sleep_start(); 473 } 474 /*———————————————-*/ 475 } 476 // listen for incoming clients 477 WiFiClient client = server.available(); 478 if (client ) { 479 memset(lineBuff, 0, sizeof(lineBuff)); 480 charcount = 0; 481 // an http request ends with a blank line 482 boolean currentLineIsBlank = true; 483 while (client.connected()) { 484 if (client.available()) { 485 char c = client.read(); 486 Serial.write(c); 487 //read char by char HTTP request 488 lineBuff[charcount] = c; 489 if (charcount < sizeof(lineBuff) – 1) charcount++; 490 // if you’ve gotten to the end of the line (received a newline 491 // character) and the line is blank, the http request has ended, 492 // so you can send a reply 493 //================================================================ 494 if (c == ‘\n’ && currentLineIsBlank) { 495 // Sensor readings may also be up to 2 seconds ‘old’ (its a very slow sensor) 496 float h = dht.readHumidity(); 497 // Read temperature as Celsius (the default) 498 float t = dht.readTemperature(); 499 double dew = dewPoint(t, h); 500 // Read temperature as Fahrenheit (isFahrenheit = true) 501 float f = dht.readTemperature(true); 502 // Check if any reads failed and exit early (to try again). 503 if (isnan(h) || isnan(t) || isnan(f)) { 504 Serial.println(“Failed to read from DHT sensor!”); 505 strcpy(celsiusTemp, “Failed”); 506 strcpy(fahrenheitTemp, “Failed”); 507 strcpy(humidityTemp, “Failed”); 508 } 509 else 510 { 511 // Computes temperature values in Celsius + Fahrenheit and Humidity 512 hic = dht.computeHeatIndex(t, h, false); 513 dtostrf(hic, 6, 2, celsiusTemp); 514 float hif = dht.computeHeatIndex(f, h); 515 dtostrf(hif, 6, 2, fahrenheitTemp); 516 dtostrf(h, 6, 2, humidityTemp); 517 val = whileFunction(3, 60000, 0);//8 minutes 518 aNewLine += “\n”; 519 aNewLine += myDate(); 520 aNewLine += “–> ” + (String)val + “% Soil Moisture Temperature: ” ; 521 aNewLine += (String)t + ” °C Humidity: ” + (String)h; 522 aNewLine += “% Heat index: ” + (String)hic + ” °C Dew ” + (String)dew + “%” ; 523 } 524 //myDebug(aNewLine, __LINE__); 525 printf(“-aNewLine size %d->¬\n”, aNewLine.length()); 526 Serial.println(aNewLine); 527 int firstNum = 1 + aNewLine.indexOf(‘:’); 528 int secondNum = 2 + firstNum; 529 //Serial.println(“firstNum ” + (String)firstNum + ” secondNum ” + (String)secondNum); 530 String minutSubstr = aNewLine.substring(firstNum, secondNum); 531 minut2Cp = minuteSort(minutSubstr); 532 printf(“line_%d -newLinesCnt %d minut1Cp•%d != minut2Cp•%d ?\n”, __LINE__, newLinesCnt, minut1Cp, minut2Cp); 533 timerFunction(60000); //1 minute 534 if (minut1Cp != minut2Cp) { 535 const char *result = aNewLine.c_str(); 536 newLinesArray[newLinesCnt] = result; 537 minut1Cp = minut2Cp; 538 usedFlagNum[newLinesCnt] = flag; 539 newLinesCnt++; 540 printf(“newLinesCnt #%d Line_%d\n”, newLinesCnt, __LINE__); 541 } 542 printf(“\n%s Line_%d\n”, “—— end newLinesArray ————-“, __LINE__); 543 for (int i = newLinesCnt ; i >= 0 ; i–) { 544 printf(“%d• “, i); 545 Serial.print(newLinesArray[i]); 546 Serial.println(); 547 } 548 Serial.println(“————- begin newLinesArray ————-“); 549 Serial.println(“\n————- end spiffDatas ————“); 550 for (int spiffDatas = decCnt; spiffDatas >= 0; spiffDatas–) 551 { 552 if (datArray[spiffDatas] != 0) 553 { 554 Serial.println(datArray[spiffDatas]); 555 } 556 } 557 Serial.println(“————- begin spiffDatas ————“); 558 // send a standard http response header 559 client.println(“HTTP/1.1 200 OK”); 560 client.println(“Content-Type: text/html”); 561 //client.println(“Content-Type: image/gif”); 562 client.println(“Connection: close”); // the connection will be closed after completion of the response 563 client.println(); 564 client.println(“<!DOCTYPE HTML><html lang=\”fr\”><head><meta charset=\”UTF-8\”><meta name=\”viewport\” content=\”width=device-width, initial-scale=1\”>”); 565 client.println(“<meta http-equiv=\”refresh\” content=\”30\”></head>”); 566 client.println(“<body style=\”color:#f3d6e1;\”><div style=\”font-size: 3.5rem;color:green;\”><p style=\”text-align:center;\”>Météo</p>”); 567 if (atoi(celsiusTemp) >= 25) { 568 client.println(“<div style=\”color: #930000;\”><p style=\”text-align:center;\”>”); 569 } 570 else if (atoi(celsiusTemp) < 25 && atoi(celsiusTemp) >= 5) { 571 client.println(“<div style=\”color: #006601;\”><p style=\”text-align:center;\”>”); 572 } 573 else if (atoi(celsiusTemp) < 5) { 574 client.println(“<div style=\”color: #009191;\”>”); 575 } 576 client.println(“<p style=\”text-align:center;font-size:14pt;\”>”); 577 client.println(myDate()); 578 client.println(“</p><p></p><p style=\”text-align:center;\”>”); 579 client.print(celsiusTemp); 580 client.print(“°C ”); 581 client.print(fahrenheitTemp); 582 client.println(” °F</p><p style=\”text-align:center;\”>”); 583 client.print(humidityTemp); 584 client.print(“ %H ”); 585 client.print(dew); 586 client.println(“ ° Rosé</p><p style=\”text-align:center;\”>”); 587 client.print(hic); 588 client.print(“ °Ressenti ”); 589 client.print(val); 590 client.print(“ %Soil Moisture</p><p style=\”text-align:center;font-size:12pt;\”>”); 591 for (int i = newLinesCnt ; i >= 0 ; i–) { 592 client.print(newLinesArray[i] + “<br>”); 593 } 594 client.print(“<br>——————————————-<br>”); 595 for (int spiffDatas = decCnt; spiffDatas >= 0; spiffDatas–) { 596 if (datArray[spiffDatas] != 0) { 597 client.print(“<br>” + datArray[spiffDatas] + “<br>”); 598 } 599 } 600 client.print(“</p></div>”); 601 client.print(“</body></html>”); 602 break; 603 } 604 if (c == ‘\n’) { 605 // you’re starting a new line 606 currentLineIsBlank = true; 607 memset(lineBuff, 0, sizeof(lineBuff)); 608 charcount = 0; 609 } else if (c != ‘\r’) { 610 // you’ve gotten a character on the current line 611 currentLineIsBlank = false; 612 } 613 } 614 } 615 Serial.println(myDate()); 616 printf(“\n 2 minutes for browser.\n”); 617 timerFunction(120000); 618 // close the connection: 619 client.stop(); 620 } 621 flag += 1; 622 timeDiff = longMinutStamp(); 623 printf(“+10 minutes before flag #%d preceding if\n”, flag); 624 timerFunction(600000);//10 min * 3 flags 625 Serial.println(myDate()); 626 }
Hi,
It is a variation of a Ruis Santos code.
I dont know why the
—-
525 printf(“-aNewLine size %d->¬\n”, aNewLine.length());
526 Serial.println(aNewLine);
——-
Print or dont print on the console is aleatory. Some time it does sometime it does not. When it prints to the console the aNewLine is registered in the newLinesArray .
It seem to be related to the opening of an already opened browser at the url (I know that does not make sense.
I dont know either why the flag 1 is registered to the newLinesArray but not the other flags number ( read loop runs)
________ 0 to _________ line_504
0
1
2
3
________3_________
The code compile and run.
JP Daviau
Output
ets Jun 8 2016 00:22:57
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac
Wakeup was not caused by deep sleep: 0
Boot number: 1
Connected to 23JANVIER-2012_Network_1 network
24:6F:28:17:F9:50
-43
IP address: 189.143.0.107
sleep now for
====== Setup Start reading from SPIFFS file =======
====== Setup End reading from SPIFFS file =======2020-06-06 15:42:16
NTP • dryRedAlarm 55 <–> 55 (totVal/readings)
Ampoule éteinte.
setup end2020-06-06 15:53:16
+10 minutes before flag #1 preceding if
2020-06-06 16:03:17
Between START & END 0963
-480 DAY_PERIOD_START 0483
-1020 DAY_PERIOD_START_END -057
________ 0 to _________ line_504
0
1
2
3
________3_________
newLinesCnt#0 flag#_1 Line_5122020-06-06 16:03:17
->CASE1-> Going to sleep for 60 minutes
+10 minutes before flag #2 preceding if2020-06-06 17:13:04
Between START & END 1033
-480 DAY_PERIOD_START 0553
-1020 DAY_PERIOD_START_END 0013
________ 0 to _________ line_504
0
1
2
3
________3_________
newLinesCnt#0 flag#_2 Line_5122020-06-06 17:13:04
result2Append failed:
_533 ->CASE2-> Going to sleep for 1200 minutes
Hi.
Can you tell me the original code that this is based on?
A common issue that happens when building a web server using client.print() is that Google Chrome makes an extra connection – it creates a new client and lefts the connection opened.
That’s possible the reason for you to say that “It seem to be related to the opening of an already opened browser at the url”.
This is somehow problematic because it doesn’t allow any client to connect until that random connection is closed. To solve that issue, we create a timer that closes all the connections after a predetermined number of seconds.
I’m not really sure if this is related with your issue.
Regards,
Sara
DHT11-DHT22 Sensor with Arduino – Random Nerd Tutorials.zip
Rui Santos
https://randomnerdtutorials.com/esp32-dht11-dht22-temperature-humidity-web-server-arduino-ide/
Hi.
That doesn’t seem the code your project is based on.
I think you’re using an old version of that project.
Now, we use the AsyncWebServer library to build the wen server and that problem with the extra connection doesn’t happen anymore.
Regards,
Sara
I dont think this is the problem.
Because the Serial print lines are done before the client.print lines and the connection is closed (619) before a new loop run is done.
Maybe it has to do with the dht11 or capacitive probe (517) readings .
JPD
Another possible project is based on.
https://github.com/RuiSantosdotme/ESP32-Course/blob/master/code/WiFi_Web_Server_Outputs/WiFi_Web_Server_Outputs.ino
Can the esp32 serve two browsers? Two browsers where opened:
———————- Untitled1.txt ———————-
1 GET / HTTP/1.1
2 Host: 189.143.0.107
3 Connection: keep-alive
4 Cache-Control: max-age=0
5 Upgrade-Insecure-Requests: 1
6 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36
7 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
8 Accept-Encoding: gzip, deflate
9 Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
10
11
———————- END/FIN ———————-
JP Daviau
—— code corrected ———
/**[SOLVED] ESP32/ESP8266 Web Server Drops Connection/Crashes* */ #include "esp_sleep.h" #include "esp_deep_sleep.h"//obsolete #include "FS.h" #include "SPIFFS.h" #include #include #include //For NTP Server //#include #include "DHT.h" #include #include /* atoi */ #include /* printf, fgets */ #include #line 15 "DHT_Ruis_SantosV1.9"// (this ligne number +1) __LINE__ "DHT_Ruis_SantosV1.9" // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); WiFiServer server(80); //#define MY_DEBUG 1 //#if defined MY_DEBUG // printf("\n------:line__%d__ ", lineNumb); // Serial.print(what); //#endif #define Threshold 40 /* Greater the value, more the touch sensitivity */ #define DHTTYPE DHT11 // DHT 11 #define uS_TO_S_FACTOR 1000000ULL //for sleep only #define HOURS 60 //(7200 = 120 minutes) 43200 secondes , soit 12 heures #define TIME_TO_SLEEP_MAX 80ULL // MAX Time to sleep in case of repeatable unsuccessfull connection attempts #define TIME_TO_SLEEP_CASE1 5400ULL //(15min = 900s) (1.5h = 5400s) in if the time is 11:00 - 12:00 #define TIME_TO_SLEEP_CASE2 70200ULL //3h (4h = 14400) (20h = 72000s)if time isn't 11:00 - 12:00 #define DAY_PERIOD_START 360 //(6h =360min)(12h =720min)in minutes the morning #define DAY_PERIOD_END 660 //(11h =660min)(17h =1020 )(20h =1200min) in minutes later unsigned long timeDiff, timeDiff2;//RTC_DATA_ATTR int TIME_TO_SLEEP_WiFi = 10; ////RTC_DATA_ATTR Time to sleep in case of unavailable WiFi (This is the first sleep) long calcul5 = 0.0; // Replace with your network credentials const char* ssid = "your"; const char* password = "your"; //wroom mac address 24:6f:28:17:f9:50 // Variables to save date and time long timezone = -5; uint8_t daysavetime = 1; struct tm tmstruct ; unsigned long currentMillis; const unsigned long period = 10000; //period that esp32 will try to connect with WIFI in ms String formattedDate; String timeStamp; // DHT Sensor const int DHTPin = 16; RTC_DATA_ATTR const int relay = 26; //pin dixième piton relais RTC_DATA_ATTR uint8_t dryRedAlarm = 55; // arrosage 2hrs + pluie 70 uint8_t pinToRead = 36; // Initialize DHT sensor. DHT dht(DHTPin, DHTTYPE); static char celsiusTemp[7]; static char fahrenheitTemp[7]; static char humidityTemp[7]; char dayBuff[160]; char clientReadBuff[160]; char atoiBuff1[3]; char atoiBuff2[3]; int datCnt, maxCount = 100; int decCnt = ( maxCount - 1); RTC_DATA_ATTR uint8_t flag = 0, lastFlag = 0; RTC_DATA_ATTR uint8_t usedFlagNum[100]; RTC_DATA_ATTR int minut1Cp = -1; RTC_DATA_ATTR int minut2Cp = 0; int charcount = 0; int val; int bootCount = 0; int heureNormal = 3600; //-3600 pour l'heure avancée double totalDelay = 0, webPageTime = 0; RTC_DATA_ATTR uint8_t newLinesCnt = 0; uint8_t newLinesCnt2, newLinesCnt3; float hic; String aNewLine;// previousNewline; String datArray[150]; // our data array holding 30 elements String newLinesArray[40]; String newLinesArray2[40]; //=== // Current time unsigned long currentTime = millis(); // Previous time unsigned long previousTime = 0; // Define timeout time in milliseconds (example: 2000ms = 2s) const long timeoutTime = 2000; //=== void delayFunction(long long secondes) { unsigned long long previousMillis; secondes = secondes * 1000000; previousMillis = micros(); while ((micros() - previousMillis) < secondes) { analogRead(pinToRead); } } int capacitiveProbe(uint8_t readings, long delays, uint8_t foroncer) { unsigned long long previousMillis; int totVal = 0, val = 0; uint8_t oncer = foroncer; uint8_t turns = 0; while (turns < readings) { if (oncer < 1) { //lets the device warm up 5 minutes analogRead(pinToRead); previousMillis = millis(); while ((millis() - previousMillis) < 300000) {//5 min ; } //Serial.println("dummy reading end"); oncer = 1; } val = analogRead(pinToRead); //connect sensor to Analog 11 or else previousMillis = millis(); while ((millis() - previousMillis) < delays) { ; } if (isnan(val)) { Serial.println("Failed to read from probe."); return 0; } val = map(val, 2450, 1615, 0, 100); totVal += val; //printf("%d %d\n", val, totVal); turns++; } printf("dryRedAlarm %d %d (totVal/readings)\n", dryRedAlarm, (totVal / readings)); return (totVal / readings); } void ampoule(int probe) { if (probe < dryRedAlarm) { digitalWrite(relay, HIGH); printf("Ampoule allumée.\n"); //while Function tant que val < dryRedAlarm //capacitiveProbe(1, 120.0, 1)// 6E7 = 1000 min = 16.6 heures while (probe |__Appended to file: %s\n", path); } else { printf("\nAppend failed: %s\n", message); } file.close(); } double dewPoint(double celsius, double humidity) { // (1) Saturation Vapor Pressure = ESGG(T) double RATIO = 373.15 / (273.15 + celsius); double RHS = -7.90298 * (RATIO - 1); RHS += 5.02808 * log10(RATIO); RHS += -1.3816e-7 * (pow(10, (11.344 * (1 - 1 / RATIO ))) - 1) ; RHS += 8.1328e-3 * (pow(10, (-3.49149 * (RATIO - 1))) - 1) ; RHS += log10(1013.246); // factor -3 is to adjust units - Vapor Pressure SVP * humidity double VP = pow(10, RHS - 3) * humidity; // (2) DEWPOINT = F(Vapor Pressure) double T = log(VP / 0.61078); // temp var return (241.88 * T) / (17.558 - T); } //=================== Listing SPIFFS Files ======= void listDir(fs::FS &fs, const char * dirname, uint8_t levels) { Serial.println("====== Listing DIR SPIFFS files ======="); printf("Listing directory: %s\n", dirname); File root = fs.open(dirname); if (!root) { Serial.println("Failed to open directory"); return; } if (!root.isDirectory()) { Serial.println("Not a directory"); return; } File file = root.openNextFile(); while (file) { if (file.isDirectory()) { Serial.print(" DIR : "); Serial.print (file.name()); time_t t = file.getLastWrite(); struct tm * tmstruct = localtime(&t); printf(" LAST WRITE: %d-%02d-%02d\n", (tmstruct->tm_year) + 1900, ( tmstruct->tm_mon) + 1, tmstruct->tm_mday); //,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec if (levels) { listDir(fs, file.name(), levels - 1); } } else { Serial.print(" FILE: "); Serial.print(file.name()); Serial.print(" SIZE: "); Serial.print(file.size()); time_t t = file.getLastWrite(); struct tm * tmstruct = localtime(&t); printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n", (tmstruct->tm_year) + 1900, ( tmstruct->tm_mon) + 1, tmstruct->tm_mday, tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); } file = root.openNextFile(); } Serial.println("====== End listing DIR SPIFFS files ======="); } void writeFile(const char * path, const char * message) { File file = SPIFFS.open(path, "w"); if (!file) { Serial.println("Failed to open file for writing" + *path); file.close(); return; } if (file.print(message)) { printf("\nErasing or writing file: %s OK\n", path); } else { Serial.println("Write or erasing failed\n" + *path); } file.close(); } void callback() { Serial.println(); Serial.println("Awaken by pin GPIO(4 fourth pin) touch ..."); Serial.println("On the boot button side of the card."); Serial.println(); ESP.restart(); } //========================== minuteSort ====================================== int minuteSort(String theMinuts) { //Serial.println("inString.toInt()%d inString.toInt()/%d•\n", inString.toInt(),inString.toInt()/2); char atoiBuff[3]; Serial.println("theMinuts•" + theMinuts + "•"); printf("_%d 0=%c\n", __LINE__, theMinuts.charAt(0)); printf("_%d 1=%c\n", __LINE__, theMinuts.charAt(1)); printf("_%d 2=%c\n", __LINE__, theMinuts.charAt(2)); if (theMinuts.charAt(0) == 48) { atoiBuff [0] = theMinuts.charAt(1); atoiBuff [1] = '\0'; atoiBuff [2] = '\0'; } else { atoiBuff [0] = theMinuts.charAt(0); atoiBuff [1] = theMinuts.charAt(1); atoiBuff [2] = '\0'; } int minutCp5 = atoi(atoiBuff); printf("0= %c\n", atoiBuff [0] ); printf("1= %c\n", atoiBuff [1] ); printf("2= %c\n", atoiBuff [2] ); //printf("_%d- atoiBuff [0], atoiBuff [1], atoiBuff [2], atoiBuff)\n•%c•%c•%c•%c\n", __LINE__, atoiBuff [0], atoiBuff [1], atoiBuff [2], *atoiBuff); return minutCp5; } void soundAlert() { digitalWrite(relay, HIGH); printf("Ampoule allumée.\n"); delayFunction(.5); digitalWrite(relay, LOW); printf("Ampoule éteinte.\n"); } //========================== END ====================================== //==================== SETUP BEGIN ==================================== void setup() { Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } //Setup interrupt on Touch Pad 3 (GPIO15) touchAttachInterrupt(T3, callback, Threshold); esp_sleep_enable_touchpad_wakeup();//Configure Touchpad as wakeup source // initialize the DHT sensor dht.begin(); /*------------------------------------------------------------------------------------------------------*/ //Print the wakeup reason for ESP32 print_wakeup_reason(); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { currentMillis = millis(); //Assign the ms have been passed since ESP32 code start running Serial.println("Boot number: " + String(++bootCount)); if (currentMillis > period) { WiFi.disconnect(); esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_WiFi * uS_TO_S_FACTOR); Serial.println("Wifi to sleep now for " + String(TIME_TO_SLEEP_WiFi) + " Seconds" + " Due to WiFi unavailability"); while (TIME_TO_SLEEP_WiFi < TIME_TO_SLEEP_MAX) { // While the sleep time is less than the predefined limit keep double the sleep time. When the sleep time exceeds the limit then keep a constant sleep time equal to the limit. TIME_TO_SLEEP_WiFi = TIME_TO_SLEEP_WiFi * 2; // Double the sleep time esp_deep_sleep_start(); } TIME_TO_SLEEP_WiFi = TIME_TO_SLEEP_MAX; // Set the sleep time equal to the limit esp_deep_sleep_start(); } delayFunction(1); } /*-----------------------------------------------------------------------------------------------------*/ server.begin(); Serial.print("Connected to "); Serial.print(ssid); Serial.println(" network"); Serial.println(WiFi.macAddress()); Serial.println(WiFi.RSSI()); Serial.print("IP address: "); Serial.println(WiFi.localIP()); //if a temp file has already been in use, open it and load it's data to array. SPIFFS.begin(); if (!SPIFFS.begin()) { Serial.println(" Not SPIFFS.begin()"); } //listDir(SPIFFS, "/", 0); //erase file //if (flag == 0)writeFile("/gardenTemp.txt", '\0'); File f = SPIFFS.open("/gardenTemp.txt", "r"); if (!f) { Serial.println("file open failed"); } Serial.println("====== Setup Start reading from SPIFFS file ======="); while (f.available() && datCnt 9) { Serial.print(datCnt); Serial.print(" "); Serial.println(line); datArray[datCnt] = line; } else { Serial.print(0); Serial.print(datCnt); Serial.print(" "); Serial.println(line); //line = "0" + line; datArray[datCnt] = line; } datCnt ++; } } f.close(); Serial.println("====== Setup End reading from SPIFFS file =======\n"); /*-----------------------------------------------------------------------------------------------------*/ timeClient.begin(); // Initialize a NTPClient to get time // Set offset time in seconds to adjust for your timezone, for example: timeClient.setTimeOffset(-18000 + heureNormal); //Cyprus Time Zone GMT -5 = -18000 pinMode(relay, OUTPUT); /*-----------------------------------------------------------------------------------------------------*/ // 1= nombre de fois, 36E2=1 heure, 0=avec réchauffement Serial.println(myDate()); Serial.print("NTP • ");//Client initialized printf("+11 minutes for probing.\n"); int a = capacitiveProbe(3, 120000.0, 0);//0=réchauffe, 5min + 6 min totalDelay += 11; ampoule(a); Serial.println("setup end " + myDate()); soundAlert(); Serial.println("page web should be open in 19 minutes."); } //======================= SETUP END ==================================== void loop() { printf(" webPageTime = %4.1f\n", webPageTime); printf(" totalDelay = %4.1f\n", totalDelay); printf("loop()=>IF newLinesCnt#%d\n", newLinesCnt); printf(" flag#%d at Line_%d\n", flag, __LINE__); /*----------------------------------------------*/ if (flag != 0) { //flag > lastFlag && (flag % 3) == 0, && (flag = 0 ;) { Serial.print((String)i + " "); Serial.println(newLinesArray[i]); } printf("Out for (newLinesArray[i])┘ \n"); printf("newLinesCnt#%d flag#_%d Line_%d", newLinesCnt, flag, __LINE__); webPageTime = 0; totalDelay = 0; if ((calcul3 >= DAY_PERIOD_START) && (calcul3 CASE1-> Going to sleep for %3.0f minutes\n" , (TIME_TO_SLEEP_CASE1 / 60.0)); //client.stop(); esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_CASE1 * uS_TO_S_FACTOR); esp_light_sleep_start(); //esp_deep_sleep_start();// } else { newLinesCnt2 = (newLinesCnt - 1); newLinesArray[newLinesCnt2].toCharArray(dayBuff, 130); const char *result = dayBuff; printf("result %s\n", result); appendFile(SPIFFS, "/gardenTemp.txt", result); Serial.println(myDate()); printf("_%d ->CASE2-> Going to sleep for %6.0f minutes\n", __LINE__, (TIME_TO_SLEEP_CASE2 / 60.0)); flag = 0; //deep sleep reset variables to 0 totalDelay = (TIME_TO_SLEEP_CASE2 / 60.0); newLinesCnt = 0; //client.stop(); esp_deep_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_OFF); esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_CASE2 * uS_TO_S_FACTOR); //Serial.flush(); esp_deep_sleep_start(); } } printf("flag#%d before WiFiClient client at line#%d\n", flag, __LINE__); Serial.println(myDate()); /*----------------------------------------------*/ soundAlert(); // listen for incoming clients WiFiClient client = server.available(); delayFunction(12); totalDelay += 0.2; if (client ) { //currentTime = millis();//=== //previousTime = currentTime;//=== memset(clientReadBuff, 0, sizeof(clientReadBuff)); charcount = 0; // an http request ends with a blank line boolean currentLineIsBlank = true; Serial.println("------ char c start---------"); //while (client.connected() && currentTime - previousTime <= timeoutTime) {//=== //currentTime = millis();//=== while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); //read char by char HTTP request clientReadBuff[charcount] = c; if (charcount " + (String)val + "% Eau dans le sol Température: " ; aNewLine += (String)t + " °C Humidité: " + (String)h; aNewLine += "% Ressentie: " + (String)hic + " °C Rosé " + (String)dew + "%" ; } printf("-aNewLine size %d->¬\n", aNewLine.length()); Serial.println(aNewLine); int firstNum = 1 + aNewLine.indexOf(':'); int secondNum = 2 + firstNum; //Serial.println("firstNum " + (String)firstNum + " secondNum " + (String)secondNum); String minutSubstr = aNewLine.substring(firstNum, secondNum); minut2Cp = minuteSort(minutSubstr); //printf("line_%d -newLinesCnt %d minut1Cp•%d != minut2Cp•%d ?\n", __LINE__, newLinesCnt, minut1Cp, minut2Cp); //delayFunction(60); //1 minute if (minut1Cp != minut2Cp) { newLinesArray[newLinesCnt] = aNewLine; minut1Cp = minut2Cp; usedFlagNum[newLinesCnt] = flag; newLinesCnt++; printf("newLinesCnt #%d Line_%d\n", newLinesCnt, __LINE__); } Serial.println("\n------ end newLinesArray -------------"); for (int i = (newLinesCnt - 1) ; i >= 0 ; i--) { printf("%d• ", i); Serial.print(newLinesArray[i]); } Serial.println("------------- begin newLinesArray -------------"); Serial.println("\n------------- end spiffDatas ------------"); for (int spiffDatas = decCnt; spiffDatas >= 0; spiffDatas--) { if (datArray[spiffDatas] != 0) { Serial.println(datArray[spiffDatas]); } } Serial.println("------------- begin spiffDatas ------------"); // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); //client.println("Content-Type: image/gif"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println(); client.println(""); client.println(""); client.println("Météo"); if (atoi(celsiusTemp) >= 25) { client.println(""); } else if (atoi(celsiusTemp) = 5) { client.println(""); } else if (atoi(celsiusTemp) < 5) { client.println(""); } client.println(""); client.println(myDate()); client.println(""); client.println("Page en ligne pour "); client.println((webPageTime+ 21)); client.println(" minutes."); client.println(""); client.print(celsiusTemp); client.print("°C "); //client.print(fahrenheitTemp); //client.println(" °F"); client.println(""); client.print(humidityTemp); client.print("° % Humidité "); client.print(dew); client.println("° Rosé"); client.print(hic); client.print("° Ressenti "); client.print(val); client.print("%° Humidité du sol"); for (int i = newLinesCnt ; i >= 0 ; i--) { client.print(newLinesArray[i] + " "); } client.print(" ------------------------------------------- "); for (int spiffDatas = decCnt; spiffDatas >= 0; spiffDatas--) { if (datArray[spiffDatas] != 0) { client.print(" " + datArray[spiffDatas] + " "); } } client.print(""); client.print(""); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; memset(clientReadBuff, 0, sizeof(clientReadBuff)); charcount = 0; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } flag += 1; //------------------- Serial.print("page web opened at "); Serial.println(myDate()); webPageTime += 0.5;//1/2min for browser webPageTime += 20; printf("for %3.0f minutes.\n", webPageTime); delayFunction(30); totalDelay += 0.5; // close the connection: client.stop(); totalDelay += 20; delayFunction(1200);// in seconds //timeDiff = longMinutStamp(); //------------------- } else { Serial.println("no client"); Serial.println("The browser is stopped?"); // close the connection: client.stop(); } }
/*
This is somehow problematic because it doesn’t
allow any client to connect until that random
connection is closed. To solve that issue, we
create a timer that closes all the connections
after a predetermined number of seconds.
*/