/** * Power Regler DTZ * Version 0.09 * 07.10.2022 P. Rebesky * author Creator P.Rebesky * Copyright (©): 2020-2022 by Peter Rebesky * This code can use in private cases only. Every business or companies using of this codes or codes parts is required an approval of us (me) * Every private using can exchange some parts of code or modify some code-lines. This code is allowed change for private use only. * This software is basicly owned by Peter Rebesky and any comercial using is forbidden without approval of us (me). **/ //#define DEBUG_PAYLOAD //#define DEBUG_VALUE #define OTA_on #include //ESP8266 Core WiFi Library #include //ESP8266 Core WiFi Library #include #include //Local WebServer #include "configPWR.h" #include "strings.h" #include // LittleFS is declared #include #include #include // https://github.com/tzapu/WiFiManager #include #include #ifdef OTA_on #include #include #endif //ADC_MODE(ADC_VCC); #define BoardTaster 1 #define LEDred 13 #define RELAIS 14 #define RFinput 12 #define ON 1 #define OFF 0 #define FLASHTIME 300 #define MESZ 0 // summer-time = 1 else winter-time = 0 #define TimeOf2021 1640998800 const long utcOffsetInSeconds = 3600; unsigned int year = 0; byte month = 0; int day = 0; int years=0; byte hour = 0; byte minute =0; byte second =0; uint32_t timestamp = 0; uint32_t timeDummy = 0; uint32_t SecOfYear =0; unsigned int waitTimeCount =0; uint32_t previousMillis = 0; uint32_t secondMillis =0; uint32_t ErrorCounter = 0; int x=0; int actualConsumption=0; int flashCounter = 0; bool receivedOK = false; String act_time; String act_date; String TransmitResult; WiFiManager wm; // global wm instance //WiFiManagerParameter custom_field; // global param ( for non blocking w params ) WiFiServer server(80); ESP8266WiFiMulti WiFiMulti; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds); configPWR cPWR; //*********************** use WIFI manager by Tzapu https://github.com/tzapu/WiFiManager ************************************ bool setupWIFI() { WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP pinMode(LEDred, OUTPUT); // set as output digitalWrite(LEDred,ON); // show setup-mode on LED delay(1000); // Serial.println("\n Starting"); std::vector menu = {"wifi","info","sep","restart","exit"}; wm.setMenu(menu); // set dark theme wm.setClass("invert"); //set static ip // wm.setSTAStaticIPConfig(IPAddress(192,168,0,10),IPAddress(192,168,0,1),IPAddress(255,255,255,0),IPAddress(8,8,8,8)); // set static ip,gw,sn,dns // wm.setShowStaticFields(true); // force show static ip fields // wm.setShowDnsFields(true); // force show dns field always wm.setConfigPortalTimeout(500); // auto close configportal after n seconds // checkButton(); // if pressed then reset WIFI config to start new change ssid bool res; res = wm.autoConnect("PWR_Setup"); // anonymous ap, first parameter is name of access point if(!res) { return false; } else { return true; } } //************************* press button for set a new SSID ********************************** void checkButton(){ // check for button press if ( digitalRead(BoardTaster) == LOW ) { // poor mans debounce/press-hold delay(50); if( digitalRead(BoardTaster) == LOW ){ digitalWrite(LEDred,OFF); // LED OFF delay(5000); // reset delay hold if( digitalRead(BoardTaster) == LOW ){ digitalWrite(LEDred,ON); // show button pressed on LED wm.resetSettings(); delay(100); wm.resetSettings(); for(int i=0;i<50;i++){ if(i%2)digitalWrite(LEDred,ON); else digitalWrite(LEDred,OFF); delay(50); } ESP.restart(); } } } } //*************************** function by WIFI manager ******************************** String getParam(String name){ //read parameter from server, for customhmtl input String value; if(wm.server->hasArg(name)) { value = wm.server->arg(name); } return value; } //*************************** function by WIFI manager ******************************** void saveParamCallback(){ #ifdef DEBUG_VALUE Serial.println("[CALLBACK] saveParamCallback fired"); Serial.println("PARAM customfieldid = " + getParam("customfieldid")); #endif } //*************************** function for get time & date as timestamp ******************************** bool syncron_NTP_Time() { timeClient.begin(); if(timeClient.update()) { timeDummy = timeClient.getEpochTime(); if(timeDummy !=0){ timestamp = timeDummy + (MESZ * 3600); // 3600 means add 1 hour return true; } } return false; } //*************************** create a string from values for data and time ******************************** void getTimeDate2String(){ act_time = ""; act_date = ""; if(hour < 10) act_time += "0"; // if value < 10 then show a zero before act_time += String(hour); //combine string for time act_time += ":"; if(minute < 10) act_time += "0"; act_time += String(minute); act_time += ":"; if(second < 10) act_time += "0"; act_time += String(second); if (day < 10) act_date += "0"; // if value < 10 then show a zero before act_date += String(day); //combine string for time act_date += "."; if(month < 10) act_date += "0"; act_date += String(month); act_date += "."; if(year < 10) act_date += "0"; act_date += String(year); } //**************************** intern clock ******************************* bool internClock(uint32_t currentMillis) { if (currentMillis < secondMillis) secondMillis = 0; // handle if currentMillis are overflows, max 32 bits if (currentMillis - secondMillis >=1000){ secondMillis = currentMillis; second++; timestamp++; if (second >=60){ second=0, minute++;} if (minute >=60){ minute=0, hour++;} if (hour >=24){ hour=0; day++;} return true; } else return false; } //***************************** show Data on WEB-Browser ****************************** void check4Client() { // Check if a client has connected String argument; String PostValues; if (WiFi.status() == WL_CONNECTED) { WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data unsigned long timeout = millis() + 3000; while (!client.available() && millis() < timeout) { delay(1); } if (millis() > timeout) { // Serial.println("timeout"); client.flush(); client.stop(); return; } // Read the first line of the reply from server and copy it into variable "argument" if(client.available()){ String methode; String line; methode = client.readStringUntil(' '); if (methode == "GET") line = client.readStringUntil('\n'); else { line = client.readString(); int postBegin = line.indexOf("\r\n\r\n"); PostValues = line.substring(postBegin+4, line.length()); } int argEnd = line.indexOf("HTTP"); argument = line.substring(0, argEnd-1); argEnd = line.indexOf("?"); if(argEnd>0 && methode == "GET"){ argument = line.substring(0, argEnd); // cut the values after ? } // Serial.println(argument); // debug // Serial.println(PostValues); // debug // Match the request client.flush(); String s; if (argument == "/save") { cPWR.savePostValues(PostValues); s = HTTP_ANSWER; s += HTTP_HEAD_PWR; s += ""; s += cPWR.getPName(); s += ""; s += HTTP_BODYSTYLE_PWR; s += ""; s += HTTP_DIV_FIELD; s += "

Ihre Eingaben wurden gespeichert.

"; s += "

"; s += HTTP_TEXT_END; } else if (argument == "/setup") { s = HTTP_ANSWER; s += HTTP_HEAD_PWR; s += ""; s += cPWR.getPName(); s += ""; s += HTTP_BODYSTYLE_PWR; s += ""; s += HTTP_DIV_FIELD; s += "

Einstellungen

"; s += "
"; // s += "


"; s += "


"; s += "


"; s += "


"; s += "


"; s += "


"; s += "


"; s += "Automatik:

"; s += "

"; s += "

"; s += "
Regler-Version: "; s += PWRVersion; s += "
Check for update firmware"; s += "

Hilfe & Impressum

"; s += HTTP_TEXT_END; } else if (argument == "/favicon.ico") { s = HTTP_ANSWER; s += "none"; } else if (argument == "/searchLogger") { s = HTTP_ANSWER; int argBegin = line.indexOf("?"); s += "{\"DTZLOGGER\":\"" + PWRVersion + "\"}"; } else if (argument == "/" || argument == "/back") { // Prepare the response s = HTTP_ANSWER; s += HTTP_HEAD_PWR_REFRESH; s += ""; s += cPWR.getPName(); s += ""; s += HTTP_BODYSTYLE_PWR; s += ""; s += HTTP_DIV_FIELD; s += "

PW-Switch-Status

"; s += "

Zeit: 🔄
"; s += "
"; s += "Datum:

"; s += "PW-Switch-IP:

"; s += "

"; s += TransmitResult; s += "
"; s += "

"; s += cPWR.getPName(); s += " aktiv: "; if(cPWR.getActionOn()) s+="✅"; else s += "😞"; s +="

"; s += "Verbunden mit Zähler: "; if(receivedOK == true)s += "✅"; // show a red bubble when StromLog not connect on server at the first time else s += "😞"; s += "
Aktion Relais: "; if(digitalRead(RELAIS))s += "👍"; // show status of relais else s += "👎"; s += "
"; s += "

Aktuelle Leistung: "; s+=actualConsumption; s += " W
"; s += "Relais
AN < "; s+=cPWR.getValueON(); s+=" W
AUS > "; s+=cPWR.getValueOFF(); s+="W"; s += "

"; s += "Protokoll Errors: "; s+= ErrorCounter; s+="
"; s += "Wartezeit: "; s+= cPWR.getWaitAction()-waitTimeCount; s+=" s
"; s += HTTP_SETUP_BUTTON; s += "

Hilfe & Impressum

"; s += HTTP_TEXT_END; } else if (argument == "/memory") { s = HTTP_ANSWER; s += "Free space: "; s += cPWR.FREESPACE; s += "
"; s += HTTP_TEXT_END; } #ifdef OTA_on else if (argument == "/firmware"){ s = HTTP_ANSWER; s += "Your PWRegler versions number: "+Version+"
"; s += "Check for new firmware now.
"; s += getFilesFromServer(WiFi.localIP()); s += HTTP_TEXT_END; } else if (argument == "/upDate"){ int valueBegin = line.indexOf("?"); s = HTTP_ANSWER; if(valueBegin > 0){ int valueEnd = line.indexOf("HTTP"); String argumentValue = line.substring(valueBegin+1,valueEnd-1); if(argumentValue.indexOf("R1M")>0){ // check if the right firmware and memory of esp (1M,2M,4M....) s += "Update will be start now.
"; s += "Update-file: "+argumentValue+"
"; s += "Don't turn off power during update!

"; s += "After update, the reconnection only via IP, without arguments behind it!

"; s += "Click here for reconnect after update
"; } else{ s += "Wrong firmware for this IoT.
Update canceled.
"; argument =""; } } else { s += "Error: Missing name of update file!
"; s += "Update canceled.
"; argument =""; } s += HTTP_TEXT_END; } #endif else if(argument == "/setTime"){ s = HTTP_ANSWER; s += HTTP_BODYSTYLE_PWR; s += ""; s += HTTP_DIV_FIELD; s += "

Die Uhr wird jetzt neu synchronisiert.

"; s += "

Zeit:

"; if (syncron_NTP_Time() == true){ Timestamp2DateTime(); s += "Neue Zeit:

"; } else { s += "Serverfehler! Aktuallisierung nicht erfolgt.
Bitte eine Wartezeit von 2 Minuten,
bis zur wiederholten, manuellen Aktuallisierung einhalten.
"; } s += "


"; s += HTTP_TEXT_END; } else s = "HTTP/1.1 403 OK\r\nContent-Type: text/html\r\n\r\n"; // Send the response to the client client.print(s); delay(1); #ifdef OTA_on if(argument == "/upDate"){ turnAllOff(); int valueBegin = line.indexOf("?"); if(valueBegin > 0){ int valueEnd = line.indexOf("HTTP"); argument = line.substring(valueBegin+1,valueEnd-1); delay(1000); //wait one second updateStromLog(argument); // start update now } } #endif } } } //*********** update new software for StromLog ***************************/ //*********** get available files ****************************************/ #ifdef OTA_on String getFilesFromServer(IPAddress ip){ String files = ""; if (WiFiMulti.run() == WL_CONNECTED) { WiFiClient client; HTTPClient http; String target = "http://"; target+=cPWR.getUpdateServer(); target+="/fwpwr/getFiles.php"; if (http.begin(client,target)){ http.addHeader("Content-Type","application/json;charset=utf-8"); int httpCode = http.POST("{\"userIP\":\""+ip.toString()+"\",\"build\":\""+Version+"\"}"); if(httpCode >= 100){ files = http.getString(); } else files = "Error: no connection."; } http.end(); } return files; } //********** update, input file-name ************************************/ String updateStromLog(String file){ String result = "ERROR: Update failed!"; ESPhttpUpdate.rebootOnUpdate(false); // remove automatic update digitalWrite(LEDred,ON); WiFiClient client; t_httpUpdate_return ret = ESPhttpUpdate.update(client, cPWR.getUpdateServer(), 80, "/fwpwr/"+file); switch (ret) { case HTTP_UPDATE_FAILED: break; case HTTP_UPDATE_NO_UPDATES: break; case HTTP_UPDATE_OK: String result = "Update successful."; delay(1000); // Wait a second and restart ESP.restart(); break; } return result; } #endif //*********** update end *************************************************/ //*********** get json data from meter *******************/ bool getConsumptionMeter(){ bool r=false; if (WiFiMulti.run() == WL_CONNECTED) { WiFiClient client; HTTPClient http; String target = "http://"; target += cPWR.getTargetMeter(); target+="/consumption"; int httpCode = 0; if (http.begin(client,target)){ httpCode = http.GET(); if (httpCode >= 0) { if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_NO_CONTENT){ TransmitResult = http.getString(); r=true; #ifdef DEBUG_PAYLOAD Serial.println(httpCode); Serial.println(TransmitResult); #endif } else {TransmitResult = "[HTTP] Unable to connect! "; TransmitResult +=httpCode;} } else {TransmitResult ="[http] missing return-code";} } else {TransmitResult ="[HTTP] Service not found!";} http.end(); } return r; } /*********************************************************** * convert a unix-timestamp into single bytes as value * function works up to 1972 until 19.01.2038 ***********************************************************/ void Timestamp2DateTime(){ int dummy = 0; bool leapYear = false; // default: don't be a leap-year timeDummy = timestamp - 31536000 *2; // sub two years (1970 and 1971) add the years later years= (timeDummy / 126230400) *4; // get the periodes of four years cycle; 3Y+leapY = 126230400 seconds timeDummy = timeDummy % 126230400; // get the rest of timestamp without the cycles like above this line if (timeDummy >= 31622400) { timeDummy -= 31622400; // sub the first leap-year if it's over years++; // add the leapyear years += timeDummy / 31536000; // get the rest of years between 0 until 2 years } year = years + 1972; // add start-year +2: now, we know the actual year and can figure out if is a leap-year // if (year % 4 == 0) leapYear = true; // if year divison by four without some rest, then is a leap-year...yeeeh -> it works until 2036 only if ( bitRead(year,0)==0 && bitRead(year,1)==0) { // it's very faster than %-arithmetic leapYear = true; SecOfYear = 31622400; // set the counts of seconds leap-year // Serial.print("LeapYear "); } else SecOfYear = 31536000; // or don't be a leap-year -> regulary seconds day = (timeDummy % SecOfYear) / 86400; // get the days of actual year month = 0; // set zero for (int i=0; day>=0; i++ ) { // do it until the day(s) are negativ, this loop has be exicute one time -> to set month at ones dummy = day; // store the value befor result is negativ for break, because the last one was the day of actual month day = day - DaysPerMonth[i]; // sub the days of month until it's negativ, according byte-array if (i == 1 && leapYear == true) {day -= 1;} // sub the 29. of february on leapyears ;-) month++; // add one month on every loop if (i > 11) return; // if this function wild ;-) then break (max. months are 0 - 11) } day = dummy+1; // add one, because the start was on 1. january (start of timstamp = 01.01.1970 and we have to add it) /****** get time ******/ hour = (timeDummy % 86400) / 3600; // the value of timeDummy contents the rest of hours, minutes and seconds only minute = (timeDummy % 3600) / 60; // it's shorter to take reduced timeDummy than the whole timestamp second = timeDummy % 60; } //****************************** show received a protocol on red LED *************************** void showProtocolOnLED(){ } //*********************** error-handling ********************************* void decodeValue(){ receivedOK=true; int valueBegin = TransmitResult.indexOf("value"); if(valueBegin >= 0){ int valueEnd = TransmitResult.indexOf(",",valueBegin); if (valueEnd != -1){ String value = TransmitResult.substring(valueBegin+7, valueEnd); #ifdef DEBUG_VALUE Serial.println(value); #endif actualConsumption=value.toInt(); } } else actualConsumption=0; } //************************ void errorConnect(){ ErrorCounter++; turnAllOff(); } void turnAllOff(){ receivedOK=false; TransmitResult=""; actualConsumption=0; digitalWrite(RELAIS, OFF); waitTimeCount=0; } //****************** time counter until switch on ************************ bool ifWaitTimeOver(){ waitTimeCount += cPWR.getScanTime(); if(waitTimeCount >= cPWR.getWaitAction()){ waitTimeCount = cPWR.getWaitAction(); return true; } else return false; } //*********************** handle turn on off relais ********************** void switchRelais(){ if(cPWR.getActionOn()){ if(actualConsumption < cPWR.getValueON()){if(ifWaitTimeOver())digitalWrite(RELAIS, ON);}else waitTimeCount=0; if(actualConsumption > cPWR.getValueOFF()){digitalWrite(RELAIS, OFF); waitTimeCount=0;} }else turnAllOff(); } //*********************** setup esp on start ***************************** void setup() { pinMode(LEDred, OUTPUT); // set as output digitalWrite(LEDred,OFF); pinMode(RELAIS, OUTPUT); // pinMode(2, INPUT); // because the TX pin is used for input by circuit digitalWrite(RELAIS, OFF); // set relais off flashCounter = 30; // time to show flash on LED for infos #ifdef DEBUG_VALUE Serial.begin(115200); #else pinMode(BoardTaster, INPUT_PULLUP); // set as input #endif delay(200); wifi_station_set_hostname("PWR_StromLog"); // set hostname into WLAN network bool result = setupWIFI(); if (result) { cPWR.begin(); // start filesystem and properties of user server.begin(); syncron_NTP_Time(); Timestamp2DateTime(); delay(200); } else { for (int i=0 ; i<20;i++){ if (digitalRead(LEDred) == HIGH)digitalWrite(LEDred,OFF); else digitalWrite(LEDred,ON); delay(200); } ESP.restart(); } } //************************* esp loop function *************************** void loop() { yield(); checkButton(); // check if user pressed button for set new SSID uint32_t currentMillis = millis(); if(internClock(currentMillis)== true) { // every second will run this component if (flashCounter > 0){ // Flash LED when errors occurs or for information if (digitalRead(LEDred) == HIGH)digitalWrite(LEDred,OFF); else digitalWrite(LEDred,ON); flashCounter --; } else digitalWrite(LEDred,OFF); // if flashtime over turn off LED if (hour == 23 && minute==1 && second==3){ // update timestamp if (syncron_NTP_Time() == true) Timestamp2DateTime(); else if(!WiFi.isConnected()) ESP.restart(); // check if connected yet } if (timestamp < TimeOf2021 && second == 50) { if (syncron_NTP_Time() == true) Timestamp2DateTime(); // get timestamp again if sync was failure, perhaps after power down } if(second % cPWR.getScanTime() == 0){ // handle get data from meter and switch relais if(cPWR.getActionOn()){ // is automatic on if(getConsumptionMeter()){ // get value of consumption from meter decodeValue(); // decode value of consumption switchRelais(); // handle turn on of relais } else errorConnect(); // if connection lost turn off relais } else turnAllOff(); } } check4Client(); // thats it's if with the browser show data on port 80 by html }