/* ################################################ Based on VertiCircNT_Pulse_SyncThing.ino 44 ################################################ clear thingspeak channel * * ChannelID = YOUR_CHANNEL_NUMBER; UserAPIKey = 'YOUR_USER_API_KEY'; % This is available from https://thingspeak.com/account/profile url = sprintf('https://api.thingspeak.com/channels/%s/feeds.json?api_key=%s',num2str(ChannelID),UserAPIKey) response = webwrite(url, weboptions('RequestMethod','delete')) https://api.thingspeak.com/channels/2058475/feeds.json?api_key=2YNZU0PKI98G5LNA http://api.thingspeak.com/channels/2058475/feeds.html * https://RandomNerdTutorials.com/esp32-thingspeak-publish-arduino/ PWM using pin D5 https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output https://randomnerdtutorials.com/esp8266-pwm-arduino-ide/ https://arduino-esp8266.readthedocs.io/en/latest/reference.html#analog-output analogWrite(pin, value); // set pwm analogWriteRange(new_range); analogWriteFreq(new_frequency); //default, ESP8266 PWM frequency is 1kHz. // countdown TLDR ////////////////////////////////////////////////// #include //https://github.com/RobTillaart/CountDown /see exemple: countdown_demo2 //timer matrix #define CD_SENSOR 0 #define CD_OPEN 1 #define CD_CLOSE 2 #define CD_WINCLOSED 3 #define CD_SNDDETECTED 4 CountDown CD[4]; // set timersarray MyCountDownTime = 10000UL ; CD[MyCountDown].start( MyCountDownTime ); //start Serial.print(CD[MyCountDown].remaining()); //show Serial.print(CD[MyCountDown].isRunning()); //bool CD[MyCountDown].stop(); // // countdown TLDR ////////////////////////////////////////////////// removed all OTA handle relay removed changof FanSTATUS = 1; //https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html //https://links2004.github.io/Arduino/d2/ddc/md_esp8266_doc_filesystem.html https://www.aliexpress.com/item/33053690164.html https://www.hackster.io/javagoza/nodemcu-amica-v2-road-test-2e8bff // // version nodemcu 2020 01 12 // https://randomnerdtutorials.com/esp8266-ds18b20-temperature-sensor-web-server-with-arduino-ide/ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !! my nodeMCU use ESP8266 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // https://www.vultr.com/docs/using-screen-on-ubuntu-14-04 ctrl-A \ screen /dev/ttyUSB0 115200 ADDED /home/luc/arduino-1.8.9/hardware/tools/avr/avr/include/avr/pgmspace.h /home/luc/Dropbox/arduino_ino/libraries/OneWire/OneWire.h warning: 'bool HTTPClient::begin(String)' is deprecated (declared at /home/luc/.arduino15/packages/esp8266/hardware/esp8266/2.6.3/libraries/ ESP8266HTTPClient/src/ESP8266HTTPClient.h:155) [-Wdeprecated-declarations] https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#enable-wi-fi-diagnostic https://makeradvisor.com/esp32-vs-esp8266/ Récupérer automatiquement des redémarrages en boucle du ESP8266 https://www.sigmdel.ca/michel/program/esp8266/arduino/watchdogs2_fr.html * * PinName function GPIO nbr D5 14 Relay ON D1 05 Push button D2 04 DS18B20 one wire bus D8 15 DHT22 https://iotbyhvm.ooo/gpio-pins-esp8266/ ESP8266 has 17 GPIO pins (0-16), however, you can only use 11 of them, because 6 pins (GPIO 6 – 11) are used to connect the flash memory chip. This is the small 8-pin IC right next to the ESP8266. If you try to use one of these pins, you might crash your program. set point TempREF mesure delay def idelayMeasures 5 minutes : 5*60*1000 ms thingspeak send data idelaySendData 20 mins 20*60*1000 regulation delay idelayRelays 2 mins 2*60*1000 */ //______________________________________________________________________ char FileName[] = __FILE__; // //Serial.print (__DATE__) ; //Serial.print (" ") ; //Serial.println (__TIME__) ; const char compile_date[] = __DATE__ " " __TIME__; //______________________________________________________________________ int ENABLE_PrtDataToThingSpeak = true ; //#include #include #include #include #include "time.h" // **LB 20210106 #include ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti' //#include // // official arduino //https://randomnerdtutorials.com/esp32-esp8266-input-data-html-form/#more-88796 // // is Jonas Ekstrand. /////////////////////////////////////////////////////////// // ThingSpeak stuff #include "ThingSpeak.h" unsigned long myChannelNumber = 2058475 ; const char * myWriteAPIKey = "YOUR API " ; /////////////////////////////////////////////////////////// WiFiClient client; #ifdef ESP32 #include #include //#include #include #else // ESP8266 my nodemcu with ESP8266 #include // #include #include //#include #include #endif #include // my nodemcu with ESP8266 //https://techtutorialsx.com/2017/12/01/esp32-arduino-asynchronous-http-webserver/ #include //#include //https://www.bakke.online/index.php/2017/06/02/self-updating-ota-firmware-for-esp8266/ // OTA // https://www.fais-le-toi-meme.fr/fr/electronique/tutoriel/esp8266-arduinoota-mise-a-jour-logiciel-esp8266-wifi #include #include //OTA #include // ? https://randomnerdtutorials.com/esp8266-nodemcu-ota-over-the-air-arduino/ // #include // /home/jacqueline/.arduino15/packages/esp8266/tools/python3/3.7.2-post1/python3 -I /home/jacqueline/.arduino15/packages/esp8266/hardware/esp8266/3.1.2/tools/espota.py -i 192.168.1.53 -p 8266 --auth= -f /tmp/arduino_build_906795/SerreLoubna_Humi_OTA.ino.bin //ntp datetime //https://randomnerdtutorials.com/esp8266-nodemcu-date-time-ntp-client-server-arduino/ #include //////////////////////////// DHT sensor //https://lastminuteengineers.com/esp8266-dht11-dht22-web-server-tutorial/ #include "DHT.h" #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 float TempDHT22; float HumiDHT22; uint8_t DHTPin = D7 ; // D7 OK, D8 Fail ! https://arduino.stackexchange.com/questions/55940/input-pullup-not-work-for-d8-in-my-nodemcu-v3/55942 // Initialize DHT sensor. DHT dht(DHTPin, DHTTYPE); String currentDate; // "2020-99-99 hh:mm:ss" String formattedTime; // Define NTP Client to get time WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org"); //Week Days //String weekDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; //Month names //String months[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // check timeClient.setTimeOffset ! unsigned long previousCPdelayMeasures = 0; // to avoid millis rollover unsigned long previousCPdelayRelays = 0; // to avoid millis rollover unsigned long previousCPdelaySendData = 0; // to avoid millis rollover unsigned long previousCPdelayResetMaxDelta = 0; // to avoid millis rollover /////////////////////////////////////////////////////////// //set relay output wire #define RELAY_CONTROL D5 // PWM // 14 // D5 GPIO14 relayboard in1 //#define RELAY_FAST D6 // 12 // D6 GPIO12 relayboard in2 #define ENABLE LOW //relay is reverse logic: active on low (sinking) #define DISABLE HIGH // array to hold last temp TempDelta const int arRecDeltaMax = 9 ; int iRecDeltaCnt = 0; // cnt record, lifo float arRecDelta [arRecDeltaMax] ; String RecDeltaHistory ; /////////////////////////////////////////////////////////// // led // ! ! MUST SET in Arduino IDE // 'Tools' 'BuitlinLED at 16 (not the default 2) // large nodeMCU is only ESP12LED , must set LED_BUILTIN at 2 =ESP12LED // Amica nodemcu has both led #define LED_ON 0 #define LED_OFF 1 //status led : ON if auto mode // #define pinled LED_BUILTIN // D0 ; // GPIO16 ; #define LEDESP12_2 2 // always present: ide i/f LED_BUILTIN set to 2 #define LEDBOARD_16 16 // only amica nodemcu /////////////////////////////////////////////////////////// // button // https://www.baldengineer.com/detect-short-long-button-press.html #define PRESSED LOW #define NOT_PRESSED HIGH const unsigned long shortPress = 50; const unsigned long longPress = 500; typedef struct Buttons { const byte pin = D1; // D1 =GPIO5 const int debounce = 20; unsigned long counter = 0; bool prevState = NOT_PRESSED; bool currentState; } Button; Button button; // // https://randomnerdtutorials.com/esp32-esp8266-input-data-html-form/#more-88796 // #if defined(ESP8266) // my NodeMCU use this //ESP8266WebServer server(80); AsyncWebServer server(80); #endif #if defined(ESP32) WebServer server(80); #endif // Set the amount of debugging detail // https://www.instructables.com/Read-Electricity-and-Gas-Meter-BelgianDutch-and-Up/ #define DEBUG_LEVEL 0 // 3 Et max verbosity // #define DEBUG_OFF 0 //**LB #define DEBUG_ERROR 1 #define DEBUG_MIN_INFO 2 #define DEBUG_MAX_INFO 3 #define DEBUG_OUT(level, fmt, ...) \ if (DEBUG_LEVEL >= level) Serial.printf_P((PGM_P)PSTR(fmt), ##__VA_ARGS__) /////////////////////////////////////////////////////////// // temperature sensors #define TEMPERATURE_PRECISION 12 // 9..12 #define ONE_WIRE_BUS D2 //4 // D2 = GPIO4 Data wire ONE_WIRE_BUS // arrays to hold device addresses #define iMaxCntDev 3 //max devs expected. limit mem used real count will be in byte iCntDev; //physical dev count DeviceAddress probes[iMaxCntDev]; // table holding dev adress float probeTemp[iMaxCntDev]; // table holding measures OneWire myOneWireDev(ONE_WIRE_BUS); // Setup a myOneWireDev instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) DallasTemperature mySensors(&myOneWireDev); // Pass our myOneWireDev reference to Dallas Temperature. const char* PARAM_idelayMeasures = "idelayMeasures"; const char* PARAM_idelayRelays = "idelayRelays"; const char* PARAM_idelaySendData = "idelaySendData"; //const char* PARAM_idelayRstDelta = "idelayRstDelta"; // NOW LOW (PWM value) // delay before reset max value const char* PARAM_TempREF = "TempREF"; //const char* PARAM_TempFanFAST = "TempFanFAST"; const char* PARAM_mode = "mode"; const char* PARAM_state = "state"; int Pct_PWR ; //pct heat power String GETdata; //will contains line send to server ////////////////////////////////////////////////////////////////////////////////////// // server template html ////////////////////////////////////////////////////////////////////////////////////// const char index_html[] PROGMEM = R"rawliteral( Loubna's Greenhouse %FileName%
Temp 1 Temp 2 Delta
%temp01% %temp02% %TempDelta%
%humidity%

%state%

Graphiques des temperatures

Temperature demandee (Now %TempREF% deg):
Set default (%TempREF_def%) Set value


%idelayMeasures%
Set default (%idelayMeasures_def%) Set value

%idelayRelays%
Set default (%idelayRelays_def%) Set value

%idelaySendData%
Set default (%idelaySendData_def%) Set value

)rawliteral"; //______________________________________________________________________ float TempDelta; float maxDelta = 0; float meanTemp = 0.0 ; // set in Gettemp() //______________________________________________________________________ //parameters .. //______________________________________________________________________ float TempREF_def = 20.23 ; //limit start TempDelta fan normal (capacitor limited) speed float TempREF = TempREF_def ; // set point long int idelayMeasures_def = 5 * 60 * 1000; // def val long int idelayRelays_def = 2 * 60 * 1000; // 120000 //relays cntrl long int idelaySendData_def = 20 * 60 * 1000; // send data 10 sec //long int idelayRstDelta_def = 600; // used as pulse FanSlowPulse ms on for slow speed control every idelayRstDelta ms int FanSLOWPulse = 100 ; // ms pulse lenght (is a delay in loop()) long int idelayMeasures; long int idelayRelays; long int idelaySendData; //long int idelayRstDelta; // bool MAN_def = true; // auto: true , man: false // 0 (nu), 1 FanSLOW, 2 FanFast, 3 FanOFF byte STATUS_def = 0; // 0 (nu), 1 FanSLOW, 2 FanFast, 3 FanOFF //========================== //______________________________________________________________________ void notFound(AsyncWebServerRequest* request) { request->send(404, "text/plain", "Not found"); } //______________________________________________________________________ void LedBlink(int cc = 1, int msec = 100, int pinled = LED_BUILTIN) { int i = 1; for (i; i <= cc; i++) { digitalWrite(pinled, !digitalRead(pinled)); delay(msec); digitalWrite(pinled, !digitalRead(pinled)); delay(msec); } } //______________________________________________________________________ void setup(void) { byte i; Serial.begin(115200); // start serial port delay(500); Serial.println(""); Serial.println(""); Serial.println("_____________________________"); Serial.println(__FILE__); Serial.println("_____________________________"); Serial.println(String(", compiled ")+ String(compile_date) ) ; Serial.println(F(">>>Set pins..")); pinMode(LEDESP12_2, OUTPUT); pinMode(LEDBOARD_16, OUTPUT); pinMode(DHTPin, INPUT_PULLUP); // check if ok w/o R pullup dht22 mode: INPUT, OUTPUT, or INPUT_PULLUP. Se pinMode(button.pin, INPUT_PULLUP); pinMode(RELAY_CONTROL, OUTPUT); // set relays out digitalWrite(RELAY_CONTROL, DISABLE); // relay to off Serial.println(F(">>>Start LittleFS..")); #ifdef ESP32 // Initialize LittleFS // https://arduino-esp8266.readthedocs.io/en/latest/filesystem.html if (!LittleFS.begin(true)) { Serial.println("An Error has occurred while mounting LittleFS"); return; } #else // ESP8266 if (!LittleFS.begin()) { Serial.println("An Error has occurred while mounting LittleFS"); return; } #endif //ndp datetime //https://randomnerdtutorials.com/esp8266-nodemcu-date-time-ntp-client-server-arduino/ timeClient.begin(); timeClient.setTimeOffset(3600); // offset to GMT in sec 2x60x60 Serial.println(">>>InitWifiCx"); InitWifiCx(); Serial.println(">>>InitParams"); InitParams(); Serial.println(">>>MonParams"); MonParams(); Serial.println(">>>Init RecDelta"); Serial.printf("There is %i values", arRecDeltaMax + 1 ) ; for (int i = 0; i <= arRecDeltaMax - 1; i++) { arRecDelta[i] = 0 ; //Serial.print(i) ; } printRecDelta() ; Serial.println(">>>mySensor.begin and DHT22.begin"); mySensors.begin(); // Start up the sensor library dht.begin(); StatusTempSensor () ; // will call GetTemps() // Serial.println(">>>GetRealTime , SyncLocalClock.."); GetRealTime(); //SyncLocalClock (1) ; //call GetRealTime , set local rt clock //Serial.print("Local RT "); Serial.println(LocalRTepoch); Serial.println(">>>ThingSpeak.begin"); ThingSpeak.begin(client); // Initialize ThingSpeak Serial.println(">>>Call temp, regulate, PrtDataToThingSpeak .."); //GetTemps(); Regulate(); PrtDataToMon(); PrtDataToThingSpeak() ; Serial.println(">>>Blink default ESP LED.."); LedBlink(3, 200, LEDESP12_2 ) ; Serial.println(">>>Blink board LED.."); LedBlink(3, 200, LEDBOARD_16 ) ; Serial.println(">>>LED Off.."); digitalWrite(LEDESP12_2, LED_OFF) ; digitalWrite(LEDBOARD_16, LED_OFF) ; Serial.println(">>>Init OTA .."); ArduinoOTA.setHostname(__FILE__); ArduinoOTA.begin(); Serial.println("============ End setup()"); } //end setup(void) //______________________________________________________________________ void StatusTempSensor () { iCntDev = mySensors.getDeviceCount(); // locate devices on the bus Serial.print(F(">>>Locating sensors devices...")); Serial.print(F("Found ")); Serial.print(iCntDev, DEC); Serial.println(" devices."); Serial.print(F("Set to maximum ")); Serial.print(iMaxCntDev, DEC); Serial.println(" devices ! (See iMaxCntDev)"); Serial.print(F("ONE_WIRE_BUS bus on pin ")); Serial.print(ONE_WIRE_BUS, DEC); Serial.println(""); Serial.print(F("Parasite power is: ")); // report parasite power requirements if (mySensors.isParasitePowerMode()) Serial.println("ON"); else Serial.println("OFF"); for (int i = 0; i < iCntDev; i++) { // print infos for each device if (!mySensors.getAddress(probes[i], i)) Serial.println("Unable to find address for Device "); Serial.print(F("Device ")); Serial.print(i); Serial.print(F(", address: ")); printAddress(probes[i]); // set the resolution to 12 bit per device mySensors.setResolution(probes[i], TEMPERATURE_PRECISION); Serial.print(F(", resolution: ")); int res = mySensors.getResolution(probes[i]); Serial.print(res, DEC); Serial.print(F(", temp: ")); //mySensors.requestTemperatures(probes[i]); probeTemp[i] = printTemperature(probes[i]); Serial.println(probeTemp[i]); //Serial.println(); } GetTemps () ; } //______________________________________________________________________ void loop(void) { unsigned long CPdelayMeasures = millis(); unsigned long CPdelayRelays = millis(); unsigned long CPdelaySendData = millis(); //unsigned long CPdelayResetMaxDelta = millis(); ArduinoOTA.handle(); time_t epochTime = timeClient.getEpochTime(); // was unsigned long keysacn(); // will activate handle.Press who call ButtonPressed() //Serial.println("Waiting delays actions.."); ///////////////////////////////////////////////// // ==== idelayMeasures PrtDataToMon if ((unsigned long)(CPdelayMeasures - previousCPdelayMeasures) >= idelayMeasures) { Serial.print(F("== ==1.idelayMeasures: ")); Serial.println(idelayMeasures / 1000); GetTemps(); //get t° and fill PrtDataToMon(); //MonParams(); previousCPdelayMeasures = CPdelayMeasures; } ///////////////////////////////////////////////// // ==== idelayRelays if ((unsigned long)(CPdelayRelays - previousCPdelayRelays) >= idelayRelays) { Serial.print(F("== ==2.idelayRelays: ")); Serial.println(idelayRelays / 1000); GetRealTime() ; //GetTemps(); Regulate() ; previousCPdelayRelays = CPdelayRelays; } ///////////////////////////////////////////////// // ==== idelaySendData if ((unsigned long)(CPdelaySendData - previousCPdelaySendData) >= idelaySendData) { Serial.print(F("3.idelaySendData: ")); Serial.println(idelaySendData / 1000); GetTemps(); //get t° and fill maxDelta, TempDelta PrtDataToMon() ; PrtDataToThingSpeak() ; previousCPdelaySendData = CPdelaySendData; } } ///home/jacqueline/.local/share/icons/hicolor/48x48/apps/arduino-arduinoide.png //_________________________________________________________________ void ButtonPressed() { Regulate(); Serial.print("ButtonPressed end"); } //______________________________________________________________________ void PrtDataToThingSpeak() { if(ENABLE_PrtDataToThingSpeak) { // ! Field or Fields ! // ThingSpeak.writeField // ThingSpeak.writeFields // multiple fields ! // // Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store up to 8 different // pieces of information in a channel. Here, we write to field 1. //int x = ThingSpeak.writeField(myChannelNumber, 1, temperatureC0,temperatureC1, myWriteAPIKey); //ThingSpeak.setStatus(String()); Serial.print("PrtDataToThingSpeak:"); // exit if any value is 0 // tmp action ?.. if ( probeTemp[0]==0 || probeTemp[0]==0 || probeTemp[1]==0 || HumiDHT22 ==0 || isnan(probeTemp[0]) || isnan(probeTemp[1]) || isnan(HumiDHT22) ){ //webwrite('http://api.thingspeak.com/update','api_key',writeApiKey,'status','good'); //status const char * String status = String(currentDate)+String(" ") + String(formattedTime) + String(", compiled ")+ String(compile_date) + String(":Aborted, some invalid values."); Serial.println(status) ; int x = ThingSpeak.setStatus (status) ; if (x == 200) { Serial.print(myChannelNumber); Serial.println(" status written successfuly, "); } return ; } ThingSpeak.setField(1, probeTemp[0]); ThingSpeak.setField(2, probeTemp[1]); //ThingSpeak.setField(3, TempDelta ); ThingSpeak.setField(3, HumiDHT22 ); ThingSpeak.setField(4, Pct_PWR ); int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); Serial.print("Updating channel "); if (x == 200) { Serial.print(myChannelNumber); Serial.println(" successfuly !"); } else { Serial.println("with HTTP error code: " + String(x)); } //lastTime = millis(); // not used because deepsleep // Timer variables //unsigned long lastTime = 0; //unsigned long timerDelay = 30000; //if ((millis() - lastTime) > timerDelay) { } else { Serial.println("PrtDataToThingSpeak() inhibited by ENABLE_PrtDataToThingSpeak") ; } } //_________________________________________________________________ int Regulate() { //return int 0..100 for heat // get all temp, make mean and regulate on it // this on gettemps ?? GetTemps(); Serial.printf("Set point: %f, Mean: %f -> ",TempREF, meanTemp ); if (meanTemp < TempREF) { Serial.println("Heat ON"); Pct_PWR=100; digitalWrite(RELAY_CONTROL, ENABLE); digitalWrite(LEDESP12_2,LED_ON ) ; return 100; } else { Serial.println("Heat OFF"); Pct_PWR=0; digitalWrite(RELAY_CONTROL, DISABLE); digitalWrite(LEDESP12_2,LED_OFF ) ; return 0 ; } } //_________________________________________________________________ void ShoStatus(int status) { //Serial.print("FanSTATUS="); //Serial.printf("DriveRelays handle mode man= %i, FanSTATUS=%i", MAN, FanSTATUS); Serial.printf("TempRef: %2.2f, TempDelta: %2.2f, Max: %2.2f\n", TempREF, TempDelta , maxDelta ); //Serial.printf("SLOW: Pulse len is %i ms every %i ms\n", FanSLOWPulse, idelayRstDelta ) ; //if (MAN) {Serial.print("MANUAL, "); } else {Serial.print("AUTO, ") ;} // Serial.print(status); /* switch (status) { case 0: Serial.println(F("OFF")); break; case 1: Serial.println(F("SLOW")); break; case 2: Serial.println(F("FAST")); break; } */ } //_________________________________________________________________ void PrtLine(int len) { // for (byte i = 0; i < iCntDev; i++) { //The loop that goes through the sensors Serial.println("") ; for ( int i = 0; i <= len; i++) { Serial.print("-") ; } //Serial.println("-") ; } //_________________________________________________________________ void GetTemps() { //get t° and fill probeTemp[], maxDelta, TempDelta yield(); meanTemp =0.0 ; DEBUG_OUT(DEBUG_MAX_INFO, "DEBUG:>>>GetTemps\n"); LedBlink(2, 150, LEDBOARD_16 ) ; mySensors.requestTemperatures(); TempDHT22 = dht.readTemperature(); HumiDHT22 = dht.readHumidity(); for (byte i = 0; i < iCntDev; i++) { //The loop that goes through the sensors probeTemp[i] = printTemperature(probes[i]); //Serial.print(" == meanTemp: ") ;Serial.println(meanTemp) ; //Serial.print(i) ; Serial.print(" ") ; Serial.println(probeTemp[i]) ; meanTemp= meanTemp + probeTemp[i] ; } meanTemp= meanTemp / iCntDev ; if (probeTemp[0] > probeTemp[1]) { TempDelta = (probeTemp[0] - probeTemp[1]); } else { TempDelta = (probeTemp[1] - probeTemp[0]); } if (TempDelta > maxDelta) { maxDelta = TempDelta; } Serial.print("TempDHT22: ") ;Serial.println(TempDHT22) ; Serial.print("HumiDHT22: ") ;Serial.println(HumiDHT22) ; Serial.print("TempDelta: ") ;Serial.println(TempDelta) ; Serial.print(", maxDelta: ") ;Serial.println(maxDelta) ; Serial.print(", meanTemp: ") ;Serial.println(meanTemp) ; //DEBUG_OUT(DEBUG_MAX_INFO, "DEBUG:<<= 1 ; i-- ) { //arRecDelta [i+1] = arRecDelta [i] ; arRecDelta [i] = arRecDelta [i - 1] ; //RecDeltaHistory = RecDeltaHistory + String(arRecDelta [i]) + " "; } arRecDelta [0] = TempDelta ; } //______________________________________________________________________ void SendData() { //send data via index.php float fMes0, fMes1; String Link; // WiFiClient client; // now global HTTPClient http; //Declare object of class HTTPClient // build a HTTP request if (WiFi.status() == WL_CONNECTED) { fMes0 = probeTemp[0]; fMes1 = probeTemp[1]; // String GETdata="GET /esp8266/index.php/?t0=" + String(fMes0) GETdata = "?t0=" + String(fMes0) + "&t1=" + fMes1 + "&TD=" + String(TempDelta) + "&mTD=" + String(maxDelta) //+ "&Md=" + String(FanSTATUS) //+ "&St="+ sState //+ "&St=" + String(MAN) + "&ti=" + millis(); +" HTTP/1.1"; //echo to sermon Link = "http://192.168.0.11/esp8266/index.php" + GETdata; Serial.print(F("===> GETdata: ")); Serial.println(Link); http.begin(client, Link); //Specify request destination int httpCode = http.GET(); //Send the request Serial.println("=response"); String payload = http.getString(); //Get the response payload Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload Serial.println("=end response"); http.end(); //Close connection } else { Serial.println("WiFiStatus != WL_CONNECTED"); } } //______________________________________________________________________ void PrtDataToMon() { Serial.println(""); Serial.print(">>>PrtDataToMon: "); //Serial.print(String(currentDate) + String(" ") + String(formattedTime) + String(":")); Serial.printf("%s %s", String(currentDate), String(formattedTime) ) ; Serial.println(""); for (byte i = 0; i < iCntDev; i++) { Serial.print(F("Device ")); Serial.print(i); Serial.print(F("( ")); printAddress(probes[i]); Serial.print(F("): ")); Serial.print(probeTemp[i]); Serial.println(" °C "); } //Serial.printf(">>(Limits: SLOW>%f, FAST>%f) Delta: %f, Max=%f\n", TempREF, TempFanFAST ,TempDelta ,maxDelta ); //ShoStatus(FanSTATUS) ; Serial.print("TempDHT22: ") ;Serial.println(TempDHT22) ; Serial.print("HumiDHT22: ") ;Serial.println(HumiDHT22) ; //Serial.print("TempDelta: ") ;Serial.print(TempDelta) ; //Serial.print(", maxDelta: ") ;Serial.print(maxDelta) ; //Serial.print(", meanTemp: ") ;Serial.println(meanTemp) ; Serial.println("<<= shortPress) && !(currentMillis - button.counter >= longPress)) { // short press detected. handleShortPress(); } if ((currentMillis - button.counter >= longPress)) { // the long press was detected handleLongPress(); } } // used to detect when state changes button.prevState = button.currentState; } } //______________________________________________________________________ void handleShortPress() { //Serial.print(F("# beg ShortPress entry")); ButtonPressed(); DriveRelays(); //Serial.print(MAN); //Serial.print("/ FanSTATUS"); //Serial.println(FanSTATUS); //Serial.print(F("# end ShortPress entry")); } //______________________________________________________________________ void handleLongPress() { //set to auto, slow Serial.println(" handleLongPress"); handleShortPress(); } //______________________________________________________________________ void printWifiStatus() { // print the SSID of the network you're attached to Serial.print(F("Connected to WiFi SSID: ")); long rssi = WiFi.RSSI(); Serial.print(WiFi.SSID()); Serial.print(F(", ip: ")); Serial.print(WiFi.localIP()); Serial.println(" MAC: "); Serial.print(WiFi.macAddress()); Serial.print(F(", signal (RSSI): ")); Serial.print(rssi); Serial.print(F(" dBm")); } //______________________________________________________________________ void InitWifiCx() { ///////////////////////////////////////////////////////////////////// // Add list of wifi networks // set web srvr processing int i = 0; wifiMulti.addAP("BRG-FLOOR0-5G", "0499185306"); wifiMulti.addAP("BRG-FLOOR0-2G", "0499185306"); wifiMulti.addAP("BRG-FLOOR2-5G", "0499185306"); wifiMulti.addAP("BRG-FLOOR2-2G", "0499185306"); wifiMulti.addAP("BRG-FLOOR0-TPLINK", "0499185306"); wifiMulti.addAP("Les Carlines_2,4 GHz", "carlines74310"); wifiMulti.addAP("WiFi-2.4-C9C0-JH", "0485626211"); Serial.println("Connecting ..."); while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above } printWifiStatus(); Serial.println(); // set server to response //code based on // https://techtutorialsx.com/2017/12/01/esp32-arduino-asynchronous-http-webserver/ // https://github.com/me-no-dev/ESPAsyncWebServer/blob/master/src/StringArray.h // // Send web page with input fields to client start server initialisation // ################################################################################# server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) { // page when requested, no dat apassed via GET //String inputMessage = "inputMessage nd1"; //Serial.println("AsyncWebServerRequest request /"); request->send_P(200, "text/html", index_html, processor); //Serial.println(inputMessage); }); // ################################################################################# // Send a GET request to /get?inputString= // https://www.w3schools.com/get?TempREF=&Def_TempREF=_TempREF // ################################################################################# server.on("/get", HTTP_GET, [](AsyncWebServerRequest * request) { // handlinf the GET requests String inputMessage = ""; int paramsNr = request->params(); //Serial.print("paramsNr="); Serial.println(paramsNr); if (request->hasParam(PARAM_idelayMeasures)) { int paramsNr = request->params(); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); if (p->name() == "Def_idelayMeasures") { // search for &Def_idelayMeasures= //Serial.println("==line 993"); if (p->value() == "setdef_idelayMeasures") { // if set, use def value, ignore other option: handled by else part //Serial.println("==line 995"); FileWrite(LittleFS, "/idelayMeasures.txt", (String(idelayMeasures_def)).c_str()); idelayMeasures = idelayMeasures_def; } else { // p->value() == "setval_idelayMeasures" //Serial.println("==line 1000"); inputMessage = request->getParam(0)->value(); if (1) { //Serial.print("==line 1010 "); //Serial.println(String(inputMessage)); FileWrite(LittleFS, "/idelayMeasures.txt", inputMessage.c_str()); idelayMeasures = inputMessage.toInt() * 1000;// int(inputMessage.c_str()); //Serial.print("2. inputmsg : ") ; Serial.println(inputMessage); } } } // if (p->name() == "Def_idelayMeasures" ) } // end for(int i=0;ihasParam(PARAM_idelayRelays)) { /* inputMessage = request->getParam(PARAM_idelayRelays)->value(); inputMessage=(inputMessage.toInt())*1000; FileWrite(SPIFFS, "/idelayRelays.txt", inputMessage.c_str()); idelayRelays = atol(inputMessage.c_str()); */ int paramsNr = request->params(); //DEBUG_OUT(DEBUG_MAX_INFO, "request->hasParam(PARAM_idelayRelays)\n", p->name() ); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); if (p->name() == "Def_idelayRelays") { if (p->value() == "setdef_idelayRelays") { FileWrite(LittleFS, "/idelayRelays.txt", (String(idelayRelays_def)).c_str()); idelayRelays = idelayRelays_def; } else { //inputMessage=(request->getParam(0)->value()) *1000 ; inputMessage = request->getParam(0)->value(); inputMessage = (atoi(inputMessage.c_str())) * 1000; if (inputMessage.toInt() > 0) { FileWrite(LittleFS, "/idelayRelays.txt", inputMessage.c_str()); idelayRelays = atol(inputMessage.c_str()); // inputMessage.toInt() //idelayRelays = (float)atof(inputMessage.c_str()); } } } } // end for(int i=0;ihasParam(PARAM_idelaySendData)) { /* inputMessage = request->getParam(PARAM_idelaySendData)->value(); inputMessage=(inputMessage.toInt())*1000; FileWrite(SPIFFS, "/idelaySendData.txt", inputMessage.c_str()); idelaySendData = atol(inputMessage.c_str()); */ int paramsNr = request->params(); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); if (p->name() == "Def_idelaySendData") { if (p->value() == "setdef_idelaySendData") { FileWrite(LittleFS, "/idelaySendData.txt", (String(idelaySendData_def)).c_str()); idelaySendData = idelaySendData_def; } else { //inputMessage=(request->getParam(0)->value()) *1000 ; inputMessage = request->getParam(0)->value(); inputMessage = (atoi(inputMessage.c_str())) * 1000; if (inputMessage.toInt() > 0) { FileWrite(LittleFS, "/idelaySendData.txt", inputMessage.c_str()); //idelaySendData = (float)atof(inputMessage.c_str()); // inputMessage.toInt() idelaySendData = inputMessage.toInt() ; //atol(inputMessage.c_str()); } } } } // end for(int i=0;ihasParam(PARAM_idelayRstDelta)) { int paramsNr = request->params(); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); if (p->name() == "Def_idelayRstDelta") { if (p->value() == "setdef_idelayRstDelta") { FileWrite(LittleFS, "/idelayRstDelta.txt", (String(idelayRstDelta_def)).c_str()); idelayRstDelta = idelayRstDelta_def; } else { //inputMessage=(request->getParam(0)->value()) *1000 ; inputMessage = request->getParam(0)->value(); //inputMessage = (atoi(inputMessage.c_str())) * 1000; inputMessage = (atoi(inputMessage.c_str())) ; // now LOW PWM ! if (inputMessage.toInt() > 0) { Serial.print("store idelayRstDelta=") ; Serial.println( inputMessage.toInt() ) ; FileWrite(LittleFS, "/idelayRstDelta.txt", inputMessage.c_str()); //idelayRstDelta = (float)atof(inputMessage.c_str()); idelayRstDelta = inputMessage.toInt() ; //atol(inputMessage.c_str()); DriveRelays() ; } } } } // end for(int i=0;ihasParam(PARAM_TempREF)) { // has received TempREF=12.34 &Def_TempREF=setval_TempREF /* https://www.w3schools.com/get?TempREF=00&Def_TempREF=setdef_TempREF Set def Set val // https://forum.arduino.cc/index.php?topic=590802.0 int paramsNr = request->params(); Serial.println(paramsNr); int paramsNr = request->params(); for(int i=0;igetParam(i); Serial.print("Param name: "); Serial.println(p->name()); Serial.print("Param value: "); Serial.println(p->value()); Serial.println("------"); } */ /* TempREF=12.34 &Def_TempREF=setval_TempREF TempREF=78.91 &Def_TempREF=setdef_TempREF */ int paramsNr = request->params(); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); /* Serial.print("Param name: "); Serial.println(p->name()); Serial.print("Param value: "); Serial.println(p->value()); Serial.println("------"); */ if (p->name() == "Def_TempREF") { //if set def if (p->value() == "setdef_TempREF") { FileWrite(LittleFS, "/TempREF.txt", (String(TempREF_def)).c_str()); TempREF = TempREF_def; } else { inputMessage = request->getParam(0)->value(); if (inputMessage != 0) { //inputMessage = request->getParam(PARAM_TempREF)->value(); FileWrite(LittleFS, "/TempREF.txt", inputMessage.c_str()); TempREF = (float)atof(inputMessage.c_str()); } else { //man step if (TempREF==0) handleShortPress(); } } } } // end for(int i=0;ihasParam(PARAM_TempFanFAST)) { int paramsNr = request->params(); for (int i = 0; i < paramsNr; i++) { AsyncWebParameter* p = request->getParam(i); if (p->name() == "Def_TempFanFAST") { if (p->value() == "setdef_TempFanFAST") { FileWrite(LittleFS, "/TempFanFAST.txt", (String(TempFanFAST_def)).c_str()); TempFanFAST = TempFanFAST_def; } else { inputMessage = request->getParam(0)->value(); if (inputMessage != 0) { FileWrite(LittleFS, "/TempFanFAST.txt", inputMessage.c_str()); TempFanFAST = (float)atof(inputMessage.c_str()); } } } } // end for(int i=0;ihasParam(PARAM_mode)) { Serial.print(F(" >>> ShortPress call ")); handleShortPress(); //inputMessage = request->getParam(PARAM_mode)->value(); //inputMessage = String(FanSTATUS); //FileWrite(LittleFS, "/mode.txt", inputMessage.c_str()); //FanSTATUS=atol( inputMessage.c_str() ); } else { inputMessage = "No message sent"; //Serial.print(F(" >>> No message sent")); //manual action ? //DriveRelays() ; } //Serial.println(inputMessage); request->send(200, "text/text", inputMessage); Serial.println(inputMessage); }); // server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) // ################################################################################# server.onNotFound(notFound); server.begin(); } //InitWifiCx(){ //______________________________________________________________________ String FileRead(fs::FS& fs, const char* path) { //Serial.printf("FileRead(): Reading file: %s\r\n", path); //Serial.printf("FileRead(): Reading file: %s ", path); File file = fs.open(path, "r"); if (!file || file.isDirectory()) { //Serial.println("- empty file or failed to open file"); return String(); } //Serial.print("- read from file:"); String fileContent; while (file.available()) { fileContent += String((char)file.read()); } //Serial.println(fileContent); return fileContent; } //______________________________________________________________________ void FileWrite(fs::FS& fs, const char* path, const char* message) { Serial.printf("Writing file: %s", path); File file = fs.open(path, "w"); if (!file) { Serial.print(F("- failed to open file for writing")); return; } if (file.print(message)) { Serial.print(F("- file written")); } else { Serial.print(F("- write failed")); } Serial.println(F("")); } //______________________________________________________________________ String processor(const String& var) { // Replaces placeholder with stored values //pass param 'id' return value or null (?) // NO OTHER CODE ALLOWED HERE WILL PROBABLY MAKE CRASH if (var == "idelayMeasures") { return String("idelayMeasures (Now ") + String(idelayMeasures / 1000) + String(" s = ") + String(idelayMeasures / 60000) + String(" min):"); } else if (var == "idelayMeasures_def") { return String(idelayMeasures_def); } else if (var == "idelayRelays") { return String("idelayRelays (Now ") + String(idelayRelays / 1000) + String(" s = ") + String(idelayRelays / 60000) + String(" min):"); } else if (var == "idelayRelays_def") { return String((idelayRelays_def)); } else if (var == "idelaySendData") { return String("idelaySendData (Now ") + String(idelaySendData / 1000) + String(" s = ") + String(idelaySendData / 60000) + String(" min):"); } else if (var == "idelaySendData_def") { return String((idelaySendData_def)); } // / TEMPERATURES else if (var == "TempREF") { return FileRead(LittleFS, "/TempREF.txt"); } else if (var == "TempREF_def") { return String((TempREF_def)); } else if (var == "temp01") { return String((probeTemp[0])); } else if (var == "temp02") { return String((probeTemp[1])); } else if (var == "state") { //return FileRead(LittleFS, "/state.txt"); //return String("Pwr % :")+ String(Pct_PWR) ; return (String("Puissance de chauffe: ")+String(Pct_PWR)+String(" %%")) ; } else if (var == "humidity") { //return FileRead(LittleFS, "/state.txt"); //return String("Pwr % :")+ String(Pct_PWR) ; //return (String("Humidite: ")+String(HumiDHT22)+String(" %%")) ; return (String("Humidite: ")+String(HumiDHT22)+String(" %%") + String(", ")+String(TempDHT22)+String(" deg") ) ; } /* else if (var == "mode") { //return String(FanSTATUS); switch (FanSTATUS) { case 0: return String("OFF"); break; case 1: return String("SLOW"); break; case 2: return String("FAST"); break; } } */ else if (var == "TempDelta") { return String(TempDelta) + " (max " + String(maxDelta) + ")"; } else if (var == "FileName") { //GetRealTime() ; return String(FileName) + "
MAC:"+String(WiFi.macAddress()) + "
"+String(currentDate)+String(" ")+String(formattedTime) + String(", compiled ")+ String(compile_date) ; //+ "
"+RecDeltaHistory ; } // Serial.println(" return processor()") ; return ""; } //______________________________________________________________________ void InitParams() { String inputMessage; char fi[20]; // 4 /* strcpy(fi, "/idelayRstDelta.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { idelayRstDelta = idelayRstDelta_def; Serial.println(" not found set def"); inputMessage = String(idelayRstDelta); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { idelayRstDelta = FileRead(LittleFS, fi).toInt(); Serial.print(" set by read FS ");Serial.println(idelayRstDelta); } */ // 5 strcpy(fi, "/TempREF.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { Serial.println(" not found set def"); TempREF = TempREF_def; inputMessage = String(TempREF); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { TempREF = FileRead(LittleFS, fi).toFloat(); Serial.print(" set by read FS: "); Serial.println(TempREF); } // 6 /* strcpy(fi, "/TempFanFAST.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { Serial.println(" not found set def"); TempFanFAST = TempFanFAST_def; inputMessage = String(TempFanFAST); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { TempFanFAST = FileRead(LittleFS, fi).toFloat(); Serial.print(" set by read FS ");Serial.println(TempFanFAST); } */ // 1 strcpy(fi, "/idelayMeasures.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { idelayMeasures = idelayMeasures_def; Serial.println(" not found set def"); inputMessage = String(idelayMeasures); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { idelayMeasures = FileRead(LittleFS, fi).toInt(); Serial.print(" set by read FS: "); Serial.println(idelayMeasures); } strcpy(fi, "/idelayRelays.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { idelayRelays = idelayRelays_def; Serial.println(" not found set def"); inputMessage = String(idelayRelays); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { idelayRelays = FileRead(LittleFS, fi).toInt(); Serial.print(" set by read FS: "); Serial.println(idelayRelays); } // 3 strcpy(fi, "/idelaySendData.txt"); Serial.print(fi); if (!LittleFS.exists(fi)) { idelaySendData = idelaySendData_def; Serial.println(" not found set def"); inputMessage = String(idelaySendData); FileWrite(LittleFS, fi, inputMessage.c_str()); } else { idelaySendData = FileRead(LittleFS, fi).toInt(); Serial.print(" set by read FS: "); Serial.println(idelaySendData); } } //______________________________________________________________________ void MonParams() { Serial.println(" PARAMETERS :"); Serial.print(F("idelayMeasures =")); Serial.println(idelayMeasures / 1000); Serial.print(F("idelayRelays =")); Serial.println(idelayRelays / 1000); Serial.print(F("idelaySendData =")); Serial.println(idelaySendData / 1000); //Serial.print(F("Slow PWM =")); //Serial.println(idelayRstDelta / 1000); //Serial.println(idelayRstDelta ); // pulse delay Serial.print(F("TempREF =")); Serial.println(TempREF); //limit start TempDelta fan normal (capacitor limited) speed //Serial.print(F("TempFanFAST =")); //Serial.println(TempFanFAST); //limit start fan fast } //______________________________________________________________________ void GetRealTime() { ///////////////////////////////////////////////////////////////////////// // show real time from ntp server // https://randomnerdtutorials.com/esp8266-nodemcu-date-time-ntp-client-server-arduino/ timeClient.update(); //unsigned long epochTime = timeClient.getEpochTime(); time_t epochTime = timeClient.getEpochTime(); // was unsigned long //Serial.println(">>>GetRealTime"); formattedTime = timeClient.getFormattedTime(); struct tm* ptm = gmtime((time_t*)&epochTime); int monthDay = ptm->tm_mday; int currentMonth = ptm->tm_mon + 1; int currentYear = ptm->tm_year + 1900; //Print complete date currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay); /* Serial.print("Current date: "); Serial.print(currentDate); Serial.print(" "); Serial.println(formattedTime); Serial.println(""); */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /* void checkForUpdates() { //https://www.bakke.online/index.php/2017/06/02/self-updating-ota-firmware-for-esp8266/ //String mac = getMAC(); // 3C:71:BF:29:AB:59 // http://192.168.0.11//home/luc/Dropbox/arduino_ino/DHT22_SRV_OTA/ota/3C:71:BF:29:AB:59 String mac = WiFi.macAddress(); //3C:71:BF:29:AB:59 String fwURL = String( fwUrlBase ); //http://192.168.0.11//home/luc/Dropbox/arduino_ino/DHT22_SRV_OTA/ota/ fwURL.concat( mac );//http://192.168.0.11//home/luc/Dropbox/arduino_ino/DHT22_SRV_OTA/ota/3C:71:BF:29:AB:59 String fwVersionURL = fwURL; fwVersionURL.concat( ".version" );//http://192.168.0.11//home/luc/Dropbox/arduino_ino/DHT22_SRV_OTA/ota/3C:71:BF:29:AB:59.version Serial.println( "Checking for firmware updates." ); Serial.print( "MAC address: " ); Serial.println( mac ); Serial.print( "Firmware version URL: " ); Serial.println( fwVersionURL ); HTTPClient httpClient; httpClient.begin( fwVersionURL ); int httpCode = httpClient.GET(); if( httpCode == 200 ) { String newFWVersion = httpClient.getString(); Serial.print( "Current firmware version: " ); Serial.println( SW_VERSION ); Serial.print( "Available firmware version: " ); Serial.println( newFWVersion ); int newVersion = newFWVersion.toInt(); if( newVersion > SW_VERSION ) { Serial.println( "Preparing to update" ); String fwImageURL = fwURL; fwImageURL.concat( ".bin" ); t_httpUpdate_return ret = ESPhttpUpdate.update( fwImageURL ); switch(ret) { case HTTP_UPDATE_FAILED: Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break; case HTTP_UPDATE_NO_UPDATES: Serial.println("HTTP_UPDATE_NO_UPDATES"); break; default: Serial.print("unknow return "); Serial.println(ret); } } else { Serial.println( "Already on latest version" ); } } else { Serial.print( "Firmware version check failed, got HTTP response code " ); Serial.println( httpCode ); } httpClient.end(); } */