diff --git a/backup/wmain2.dcpx b/backup/wmain2.dcpx new file mode 100644 index 0000000..14ad293 --- /dev/null +++ b/backup/wmain2.dcpx @@ -0,0 +1,3743 @@ +/********* + Rui Santos + Complete project details at https://RandomNerdTutorials.com/esp32-esp8266-input-data-html-form/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files. + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. +*********/ + +#include +#ifdef ESP32 + #include + #include + #include + #include +#else + #include + #include + #include + #include +#endif +#include +// #include +//#include +#include +#include +#include +#include +#include +//#include + +AsyncWebServer server(80); +AsyncWebSocket ws("/ws"); +AsyncWebSocket wscal("/wscal"); +//WiFiManager wifiManager; + +// REPLACE WITH YOUR NETWORK CREDENTIALS +// char ssid[] = "WiFi_SuGi"; +char ssid[] = "123456789012345678901234567890"; +char password[] = "123456789012345678901234567890"; + +//strcpy(ssid,"WiFi_SuGi"); + +//password = "1234567890"; + +const char *soft_ap_ssid = "MyESP32AP"; +const char *soft_ap_password = "testpassword"; + +const char* PARAM_STRING = "inputString"; +const char* PARAM_INT = "inputInt"; +const char* PARAM_FLOAT = "inputFloat"; + +const char* PARAM_SSID = "ssidString"; +const char* PARAM_PWD = "inputPwd"; + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 7*3600; +const int daylightOffset_sec = 0; + +uint8_t STATE, dircount1, dircount2; //The current state machine state + +//volatile DynamicJsonDocument getRally(200); +String getRallyJson="{\"counter\":0}"; +String getCalibJson="{\"counter\":0}"; +int globalClientRally=0; +int globalClientCalib=0; + +#define REQUESTCOUNT 3 +AsyncWebServerRequest *gRequest[REQUESTCOUNT]; +JsonVariant gJson[REQUESTCOUNT]; +uint8_t gReqCount=0; +bool gGotRequest[REQUESTCOUNT]; + + + +AsyncWebServerRequest *gRequestConstHTML[REQUESTCOUNT]; +uint8_t gReqCountConstHTML=0; +bool gGotRequestConstHTML[REQUESTCOUNT]; +//////// +// +// +// +// +// + +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#include +#include +// #include +#include +#include + +//#define BUFF_MAX 128 + +//****************************************Define I2C LCD Display ********************************* +#define I2C_ADDR 0x27 // Define I2C Address for the PCF8574T +//---(Following are the PCF8574 pin assignments to LCD connections )---- +// This are different than earlier/different I2C LCD displays + +#define Rs_pin 0 +#define Rw_pin 1 +#define En_pin 2 +#define BACKLIGHT_PIN 3 +#define D4_pin 4 +#define D5_pin 5 +#define D6_pin 6 +#define D7_pin 7 + + +#define ATMEGA328 //comment out this line if it is not ATMEGA328 +//#define DEBUG //comment out this line to disable for Production(No Serial print) + +#define RRcountSIZE 20 +#define count1Address 0 +#define count1count2diffAddress 40 //only one address which is 40*32 +//int count1Address = 0; +//int count1count2diffAddress = 40; +long count1count2diff = 0; + +#define TRIPSIZE 16 //so thestartaddress is 50*32 until (50+12)*32 +#define TRIPADDRESS 50 + +const byte interruptPin = 32; //2; +#define simulatorPWMPin 19 +bool simstate = false; +volatile bool isloadingConst = false; +bool iscalculatingRally = false; +//const byte ledPin = 13; + +// #ifndef ATMEGA328 + volatile byte ledstate = LOW; +// #endif + +#define LED_OFF 0 +#define LED_ON 1 + +// set the LCD number of columns and rows +const int lcdColumns = 20; +const int lcdRows = 4; + +///lolin esp32 lite i2c pin +#define I2C_SDA 15 +#define I2C_SCL 13 +#define LED_BUILTIN 22 // LED built in pada ESP32 Lolin32 Lite +// set LCD address, number of columns and rows +// if you don't know your display address, run an I2C scanner sketch +// LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // marcoschwartz. ujungnya jelek ->remark +LiquidCrystal_PCF8574 lcd(0.27); + +/*-----( Declare objects )-----*/ +//LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); +// LiquidCrystal_I2C lcd(I2C_ADDR); +AT24CX mem; +boolean cursorON=true; +boolean blinkON=true; +//************************************ END LCD DISPLAY ******************************************* + +uint8_t thistime[8]; +//char recv[BUFF_MAX]; +unsigned int recv_size = 0; +unsigned long prevsettime, intervalsettime = 250; +unsigned long prevtempint, tempinterval=60000; +unsigned long prevtemprally, tempintervalrally=333; +unsigned long prevcalibrationtime, calibrationtimeinterval = 200; +unsigned long updatecounttime=0; +float temperature; +byte x; +byte y; +// #ifndef y++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define y++ y+1 +// #endif +// #ifndef x++ +// //#define min(a,b) (((a) < (b)) ? (a) : (b)) +// #define x++ x+1 +// #endif + +unsigned long startmillis, startVSSCount; +unsigned long startsavemillis; +unsigned long broadcastwebsocket; +unsigned long broadcastwebsocketcalib; +volatile unsigned long howLongInMillis; + +//#include //https://github.com/JChristensen/Button //from change to +#include + +#define UP_pin 25 //4 +#define DOWN_pin 26 //5 +#define LEFT_pin 27 //6 +#define RIGHT_pin 14 //7 +#define OK_pin 12 //8 + +#define UP_PIN 25 //4 //Connect two tactile button switches (or something similar) +#define DN_PIN 26 //5 //from Arduino pin 2 to ground and from pin 3 to ground. +#define LF_PIN 27 //6 +#define RF_PIN 14 //7 +#define OK_PIN 12 //8 +#define ESC_PIN 33 //10 +#define PULLUPRES true //To keep things simple, we use the Arduino's internal PULLUPRES resistor. +#define INVERT true //Since the pullup resistor will keep the pin high unless the + //switch is closed, this is negative logic, i.e. a high state + //means the button is NOT pressed. (Assuming a normally open switch.) +#define DEBOUNCE_MS 40 //A debounce time of 20 milliseconds usually works well for tactile button switches. + +#define REPEAT_FIRST 1000 //ms required before repeating on long press +#define REPEAT_INCR 75 //repeat interval for long press +#define MIN_COUNT 0 +#define MAX_ROW 3 +#define MAX_COL 19 +#define MS_IN_HOUR 3600000 //Number of ms in an hour +#define MS_IN_MIN 60000 //Number of ms in a minute +// Button btnUP(UP_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnDN(DN_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +// Button btnLF(LF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); +// Button btnRF(RF_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnOK(OK_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons +// Button btnESC(ESC_PIN, PULLUPRES, INVERT, DEBOUNCE_MS); //Declare the buttons + +Button btnUP(UP_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnDN(DN_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); +Button btnLF(LF_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); +Button btnRF(RF_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnOK(OK_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons +Button btnESC(ESC_PIN, DEBOUNCE_MS, PULLUPRES, INVERT); //Declare the buttons + +enum {WAIT, UP, DOWN, LEFT, RIGHT, OKAY, RALLYEDIT, ESC}; //The possible states for the STATE machine +enum {MAIN, CALIBRATION, SETTIME, INPUTSUBTRAYEK, RALLY, CONSTANTA}; //The possible states for the MENU +enum {FORWARD, FREEZE, BACKWARD}; +char const *dircount[] = {"Fw", "Zz", "Bw"}; //CHANGE 2022 +//String dircount[] = {"Fw", "Zz", "Bw"}; + +uint8_t MENU, PREVMENU; +///uint8_t STATE, dircount1, dircount2; ///move to top //The current state machine state +byte hour24, min60, sec60; +unsigned long rpt = REPEAT_FIRST; //A variable time that is used to drive the repeats for long presses +uint8_t prevsec; +float constanta=3.275; +float distance1, distance2; +volatile float prevdistance1, prevdistance2; +volatile long prevcount1, prevcount2; +boolean showTIME = true; + +float tempval; +struct ts t; +byte calibrationDistance=1; +byte tempcalibdist=1; +boolean calibrationON=false; + +float oneMeter=0; +unsigned long startCalibration=0; +unsigned long Calibration=110400; //for CR-V 2012 +unsigned long Calibrationcount; +unsigned long Calibrationcountbackup; +unsigned long Calibrationtime; +int digit1, digit2, digit3, digit4, digit5, digit6; +byte calibdigit1, calibdigit2, calibdigit3; +int dist1digit1, dist1digit2; +int dist2digit1, dist2digit2; +byte starttractsec, starttractmin, starttracthour; +boolean rallyON=false; + +volatile unsigned long VSSCount =0; + +long count1 = 0; //must be signed as technically distance can go negative +long count2 = 0; +long backcount1 = 0; +long backcount2 = 0; + +//The two time variables are used to store reset times in ms +unsigned long time1 = 1; +unsigned long time2 = 1; +int CURSOR_POS = 1; + +unsigned long count1Seq = 0; +boolean editDist1 = false; + +//to save trayek data +struct RallyData { + char sub; + float speed; + byte startHour; + byte startMin; + byte startSec; + float distance; + unsigned int subTime; +}; + //RallyData Trip={"b",23.342, 11,0,0,12.13}; + RallyData Trip[TRIPSIZE]; +//RallyData currentTrip; + +byte curTrip=0; +byte prevTrip=0; + + + +// +// +// +// +// + +void notFound(AsyncWebServerRequest *request) { + request->send(404); +} + +String readFile(fs::FS &fs, const char * path){ + // Serial.printf("Reading file: %s\r\n", path); + // if (fs.exists(path)){ + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + // Serial.print("filesize:");Serial.println(file.size()); + if (!file.size()){ + Serial.println("File is empty"); + file.close(); + return String(); + } + Serial.print("- read from file:"); + String fileContent; + + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; + // } else {return String();} +} + +boolean writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.println(message); + Serial.println(sizeof(message)); + if ((message != NULL) && (message[0] == '\0')) { + Serial.println("message is empty\n"); + return false; + } + if (sizeof(message)==0){ + return false; + } + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + file.close(); + return false; + } + if(file.print(message)){ + Serial.println("- file written"); + file.close(); + return true; + } else { + Serial.println("- write failed"); + file.close(); + return false; + } + file.close(); + return false; +} + +// Replaces placeholder with stored values +String processor(const String& var){ + //Serial.println(var); + Serial.print("Processor "); + Serial.print(var); + if(var == "ssidString"){ + return readFile(SPIFFS, "/ssidString.txt"); + } + else if(var == "localip"){ + return WiFi.localIP().toString(); + } + else if(var == "serveripaddress"){ + if (WiFi.localIP().toString()!="0.0.0.0"){ + Serial.println(WiFi.localIP()); + return WiFi.localIP().toString(); + } else { + Serial.println(WiFi.softAPIP()); + return WiFi.softAPIP().toString(); + } + } + // else if(var == "inputPwd"){ + // return readFile(SPIFFS, "/inputPwd.txt"); + // } + return String(); +} +String procConst(const String& var){ + Serial.print("proConst->"); + Serial.print(var); + return String(); +} + + + + +void OnWiFiEvent(WiFiEvent_t event) +{ + switch (event) { + + case SYSTEM_EVENT_STA_CONNECTED: + Serial.println("ESP32 Connected to WiFi Network"); + break; + case SYSTEM_EVENT_AP_START: + Serial.println("ESP32 soft AP started"); + break; + case SYSTEM_EVENT_AP_STACONNECTED: + Serial.println("Station connected to ESP32 soft AP"); + break; + case SYSTEM_EVENT_AP_STADISCONNECTED: + Serial.println("Station disconnected from ESP32 soft AP"); + break; + default: break; + } +} +String getPin(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + // StaticJsonBuffer<200> jsonBuffer; + // JsonObject& root = JsonBuffer.createObject(); + DynamicJsonDocument testdoc(512); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + testdoc["pin36"]=242; + testdoc["pin39"]=datetime; + testdoc["time"]=curtime; + // testdoc["datetime"]=datetime; + testdoc["pin5"]=millis(); + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + String dir[]={"FW","STOP","BACK"}; + testdoc["dir1"]=dir[random(3)]; + testdoc["dir2"]=dir[random(3)]; + testdoc["time1"]=curtime; + testdoc["time2"]=curtime; + float odo1=float(millis())/10000; + float odo2=float(millis())/20000; + //Serial.println(odo1,3); + testdoc["odo1"]=String(odo1,3); + testdoc["odo2"]=String(odo2,3); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} +String getCalib(){ + struct tm timeinfo; + String hasil; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return hasil; + } + DynamicJsonDocument testdoc(200); + //String datetime = &timeinfo; + char datetime[21]; + char curtime[9]; + strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); + strftime(curtime, 9, "%H:%M:%S", &timeinfo); + //Serial.println(&timeinfo); + //Serial.println(datetime); + // testdoc["datetime"]=datetime; + testdoc["curtime"]=curtime; + testdoc["speed"]=String(float(random(1,20000))/100,1); + testdoc["counter"]=random(0,50000); + String bb[]={"A","B","C","D","E","F","G","H","I","J","K","L"}; + testdoc["curtrack"]=bb[random(12)]; + float calkm=float(millis())/100000; + float calmeter=float(millis())/100; + testdoc["caldist"]=random(9); + testdoc["calman"]=random(100000, 150000); + testdoc["calkm"]=String(calkm,3); + testdoc["calmeter"]=String(calmeter,3); + //Serial.println(odo1,3); + testdoc["calval"]=String(calmeter*1000); // if disabled, the web will get undefined value + //serializeJson(testdoc,Serial); + serializeJson(testdoc,hasil); + //testdoc.printTo(hasil); + // testdoc.clear(); + return hasil; +} + +void printLocalTime(){ + struct tm timeinfo; + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + t.hour=timeinfo.tm_hour; + t.min=timeinfo.tm_min; + t.sec=timeinfo.tm_sec; + t.mday=timeinfo.tm_mday; + t.mon=timeinfo.tm_mon; + t.year=timeinfo.tm_year; + DS3231_set(t); + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); + Serial.print("Day of week: "); + Serial.println(&timeinfo, "%A"); + Serial.print("Month: "); + Serial.println(&timeinfo, "%B"); + Serial.print("Day of Month: "); + Serial.println(&timeinfo, "%d"); + Serial.print("Year: "); + Serial.println(&timeinfo, "%Y"); + Serial.print("Hour: "); + Serial.println(&timeinfo, "%H"); + Serial.print("Hour (12 hour format): "); + Serial.println(&timeinfo, "%I"); + Serial.print("Minute: "); + Serial.println(&timeinfo, "%M"); + Serial.print("Second: "); + Serial.println(&timeinfo, "%S"); + + Serial.println("Time variables"); + char timeHour[3]; + strftime(timeHour,3, "%H", &timeinfo); + Serial.println(timeHour); + char timeWeekDay[10]; + strftime(timeWeekDay,10, "%A", &timeinfo); + Serial.println(timeWeekDay); + Serial.println(); +} + +boolean isDecimal(String str){ + // boolean digit=true; + for(byte i=0;i '9') return false; + } + return true; +} + +boolean isShortTime(const char* st){ + Serial.println(sizeof(st)); //ini size pointer saja longint(4) + Serial.println(strlen(st)); //ini yg benar + Serial.println(st); + + if(strlen(st)!=5) return false; + for (int i=0; iindex ? data.substring(strIndex[0], strIndex[1]) : ""; +} +unsigned long getValueSetTime(const char* st){ + Serial.print("getValueSetTime=");Serial.println(st); + if (!isShortTime(st)) { + Serial.println("getValueSetTime=-1"); + return -1; + } + String x = getSplitValue(st, ':', 0); + int xval=x.toInt(); + String y = getSplitValue(st, ':', 1); + int yval=y.toInt(); + + return ((xval*256)+yval)*256+0; +} + +unsigned long getMemStime(uint8_t getmemsTimecurTrip); + +String getsTime(uint8_t getsTimecurtrip){ + unsigned long sTimeinconstanta; + int sTimeHour; + int sTimeMin; + for(int i=0; i<4; i++){ + sTimeinconstanta = getMemStime(getsTimecurtrip); + sTimeHour = sTimeinconstanta/65536; + sTimeMin = (sTimeinconstanta/256)-sTimeHour*256; + if (sTimeHour<=24 && sTimeMin<=60){ + break; + } + delayMicroseconds(20); + } + // String sTime; + char sTime[6]; + // if (sTimeHour<10){ + sprintf(sTime, "%02d:%02d", sTimeHour, sTimeMin); + Serial.print(getsTimecurtrip);Serial.print("getsTime:");Serial.print(sTimeHour);Serial.print(":");Serial.print(sTimeMin);Serial.print(";");Serial.println(sTime); + // } + return sTime; +} + +void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ + + if(type == WS_EVT_CONNECT){ + globalClientRally++; + Serial.println("Websocket client connection received"); + Serial.print("Rally Client=");Serial.println(globalClientRally); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + client->text(getRallyJson); + } else if(type == WS_EVT_DISCONNECT){ + globalClientRally--; + Serial.println("Client disconnected"); + Serial.print("Rally Client=");Serial.println(globalClientRally); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(256); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String resetodo=doc["resetodo"]; + String copytoodo=doc["copytoodo"]; + String direction1=doc["dir1"]; + String direction2=doc["dir2"]; + String toggle=doc["toggle"]; + String ctotrip=doc["ctotrip"]; + if (resetodo!="null"){ + if (isDecimal(resetodo)){ + if(resetodo=="1"){ + Serial.print("resetodo=");Serial.println(resetodo); + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + } else if(resetodo=="2"){ + Serial.print("resetodo=");Serial.println(resetodo); + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + } + } + } + if (copytoodo!="null"){ + if (isDecimal(copytoodo)){ + if(copytoodo=="2"){ + Serial.print("copytoodo=");Serial.println(copytoodo); + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + } else if(copytoodo=="1"){ + Serial.print("copytoodo=");Serial.println(copytoodo); + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + } + } + } + if (direction1!="null"){ + if (isDecimal(direction1)){ + if(direction1.toInt()>=0 && direction1.toInt()<=3){ + Serial.print("direction1=");Serial.println(direction1); + dircount1=direction1.toInt(); + } + } + } + if (direction2!="null"){ + if (isDecimal(direction2)){ + if(direction2.toInt()>=0 && direction2.toInt()<=3){ + Serial.print("direction2=");Serial.println(direction2); + dircount2=direction2.toInt(); + } + } + } + if (toggle!="null"){ + if (isDecimal(toggle)){ + if(toggle=="1"){ + Serial.print("toggle=");Serial.println(toggle); + showTIME = !showTIME; + } else if(toggle=="2"){ + Serial.print("toggle=");Serial.println(toggle); + showTIME = !showTIME; + } + } + } + if (ctotrip!="null"){ + int temptrip; + temptrip = (int)ctotrip.charAt(0); + if (temptrip>=65 && temptripremoteIP()); + client->text(getCalibJson); + } else if(type == WS_EVT_DISCONNECT){ + globalClientCalib--; + Serial.println("wscal Client disconnected"); + Serial.print("Calib Client=");Serial.println(globalClientCalib); + Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); + } else if(type == WS_EVT_DATA){ + Serial.print("wscal IPAdd client:"); Serial.println(client->remoteIP()); + Serial.printf("[%u] get Text: %s\n", len, data); + String message = String((char*)( data)); + Serial.println(message); + + DynamicJsonDocument doc(200); + // Deserialize the data + DeserializationError error = deserializeJson(doc, message); + // parse the parameters we expect to receive (TO-DO: error handling) + // test if parsing succeeds + if (error){ + Serial.print("wscal deserialiseJson() failed: "); + Serial.println(error.c_str()); + client->text(error.c_str()); + return; + } + String setcaldis=doc["setcaldis"]; + String setcaldisman=doc["setcaldisman"]; //set calibation distance manual + String calstart=doc["calstart"]; + Serial.print("setcaldis=");Serial.println(setcaldis); + Serial.print("setcaldisman=");Serial.println(setcaldisman); + Serial.print("calstart=");Serial.println(calstart); + if (setcaldis!="null"){ + if (isFloat(setcaldis)){ + Serial.print("setcaldis=");Serial.println(setcaldis.toInt()); + calibrationDistance=setcaldis.toInt(); + } + } + if (setcaldisman!="null"){ + if (isDecimal(setcaldisman)){ + Serial.print("setcaldisman=");Serial.println(setcaldisman.toInt()); + Calibration = setcaldisman.toInt(); + mem.writeLong(896, Calibration); + } + } + if (calstart!="null"){ + if (isDecimal(calstart)){ + if(calstart=="1"){ + Serial.print("calstart=");Serial.println("START"); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + calibrationON=true; + } else if(calstart=="0"){ + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + calibrationON=false; + } + Serial.print("calstart=");Serial.println("STOP"); + } + } + } +} + +// void configModeCallback (WiFiManager *myWiFiManager) { +// Serial.println("Entered config mode"); +// Serial.println(WiFi.softAPIP()); + +// Serial.println(myWiFiManager->getConfigPortalSSID()); +// } + + + +////// VSSRALLYMODULE +// +// +// +// +// +// +// +// +// + +void printUPchar() +{ + byte thumb1[8] = {B00100,B01110,B11111,B00100,B00100,B00100,B00100,B00100}; + lcd.createChar(1, thumb1); + //lcd.write(1); +} +void printDOWNchar() +{ + byte thumb1[8] = {B00100,B00100,B00100,B00100,B00100,B11111,B01110,B00100}; + lcd.createChar(2, thumb1); + //lcd.write(2); +} +unsigned long memretrieveLong(int startaddress, byte rrpointersize, unsigned long &seq ) +{ + //Serial.print(seq);Serial.print(";R ");Serial.print(rrpointer[0]);Serial.print("; SizeofArr=");Serial.println(rrpointersize); + unsigned long largestcountpointer=0; + int lastpointer = 0; + unsigned long seqnumber = 0; + int pointeradd = 0; + for (int i = 0; i");Serial.println(mem.readLong(pointer+(i*32))); + } +} +*/ + +void memretrieveTrip(int pointer, int startaddress) +{ + //Serial.print (pointer); Serial.println(startaddress); + int pointeradd; + Trip[pointer].speed = mem.readFloat(startaddress); + pointeradd = (startaddress + 6); + Trip[pointer].startHour = mem.read(pointeradd); + pointeradd = (startaddress + 5); + Trip[pointer].startMin = mem.read(pointeradd); + pointeradd = (startaddress + 4); + Trip[pointer].startSec = mem.read(pointeradd); + if (Trip[pointer].startHour >= 24) Trip[pointer].startHour = 23; + if (Trip[pointer].startMin >= 60) Trip[pointer].startMin = 59; + if (Trip[pointer].startSec >= 60) Trip[pointer].startSec = 59; +} + +void constantatodigit() +{ + digit1=(int)(constanta/10); + digit2=(int)constanta%10; + digit3=(int)((constanta - (int)constanta)*10); + digit4=(int)((constanta*10 - (int)(constanta*10))*10); + digit5=(int)((constanta*100 - (int)(constanta*100))*10); + digit6=(int)((constanta*1000 - (int)(constanta*1000))*10); + //digit6=(int)((constanta*10000 - (int)(constanta*10000))*10); +} + +void setMemSpeedInConstanta(float constanta, uint8_t setmemcurTrip){ + int pointeradd = ((TRIPADDRESS+setmemcurTrip)*32); + mem.writeFloat(pointeradd, constanta); + Trip[setmemcurTrip].speed = constanta; +} +float getMemSpeedInConstanta(uint8_t getmemSpeedcurTrip){ + int pointeradd = ((TRIPADDRESS+getmemSpeedcurTrip)*32); + float x=mem.readFloat(pointeradd); + if(isnan(x)) { + delayMicroseconds(10); + x=mem.readFloat(pointeradd); + } + return x; +} +void setMemStime(unsigned long valuesettime, uint8_t setmemssTimecurTrip){ + int pointeradd = ((TRIPADDRESS+setmemssTimecurTrip)*32+4); + mem.writeLong(pointeradd, valuesettime); + Trip[setmemssTimecurTrip].startHour = (valuesettime/65536); //starttracthour; + Trip[setmemssTimecurTrip].startMin = (valuesettime/256)-Trip[setmemssTimecurTrip].startHour*256; // starttractmin; + Trip[setmemssTimecurTrip].startSec = valuesettime-((Trip[setmemssTimecurTrip].startHour*256 + Trip[curTrip].startMin)*256);//starttractsec; + Serial.print(Trip[setmemssTimecurTrip].startHour);Serial.print(";"); + Serial.print(Trip[setmemssTimecurTrip].startMin);Serial.print(";"); + Serial.println(Trip[setmemssTimecurTrip].startSec); +} +unsigned long getMemStime(uint8_t getmemsTimecurTrip){ + int pointeradd = ((TRIPADDRESS+getmemsTimecurTrip)*32+4); + return mem.readLong(pointeradd); +} + +void blink() { +// #ifndef ATMEGA328 + ledstate = !ledstate; +// #else +// PORTB ^= B00100000; +// #endif + VSSCount++; +} + + + + +#ifdef DEBUG +long prevtimemicros=micros(); //************************************************************************** +#endif +unsigned long rallyEditTime=micros(); +byte rallyEditRpt = 0; +boolean rallyEdit =false; +boolean savedCount = true; +unsigned long intervalsavemillis = 3000; + + +void printMOVEchar() +{ + byte Movechar3[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B00000,B11111}; + lcd.createChar(3, Movechar3); + byte Movechar4[8] = {B00000,B00000,B00000,B00000,B00000,B00000,B11111,B11111}; + lcd.createChar(4, Movechar4); + byte Movechar5[8] = {B00000,B00000,B00000,B00000,B00000,B11111,B11111,B11111}; + lcd.createChar(5, Movechar5); +} + + +void lcdprint2digit(byte val) +{ + if (val<10) lcd.print("0"); + lcd.print(val); +} +void setTheTime(char *cmd) +{ + // ssmmhhWDDMMYYYY set time + + t.sec = inp2toi(cmd, 0); + t.min = inp2toi(cmd, 2); + t.hour = inp2toi(cmd, 4); + t.wday = inp2toi(cmd, 6); + t.mday = inp2toi(cmd, 7); + t.mon = inp2toi(cmd, 9); + t.year = inp2toi(cmd, 11) * 100 + inp2toi(cmd, 13); + DS3231_set(t); +#ifdef DEBUG + Serial.println("OK setTheTime()"); +#endif +} + +void printMonth(int month) +{ + switch(month) + { + case 1: lcd.print(" January ");break; + case 2: lcd.print(" February ");break; + case 3: lcd.print(" March ");break; + case 4: lcd.print(" April ");break; + case 5: lcd.print(" May ");break; + case 6: lcd.print(" June ");break; + case 7: lcd.print(" July ");break; + case 8: lcd.print(" August ");break; + case 9: lcd.print(" September ");break; + case 10: lcd.print(" October ");break; + case 11: lcd.print(" November ");break; + case 12: lcd.print(" December ");break; + default: lcd.print(" Error ");break; + } +} + +void mainMenu() +{ + MENU = MAIN; + lcd.clear(); + lcd.print("1. Rally TSD"); + lcd.setCursor(0,1); + lcd.print("2. Set Main Time"); + lcd.setCursor(0,2); + lcd.print("3. Input Constanta"); + lcd.setCursor(0,3); + lcd.print("4. Calibration ODO"); + //lcd.home(); + x=2; + y=0; + lcd.cursor(); + lcd.setCursor(x,y); + PREVMENU = MENU; +} + +void runningtime(byte x1,byte y1) +{ + lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + lcd.print("0"); + } + lcd.print(t.hour); + lcd.print(":"); + if(t.min<10) + { + lcd.print("0"); + } + lcd.print(t.min); + lcd.print(":"); + if(t.sec<10) + { + lcd.print("0"); + } + lcd.print(t.sec); +} + +String runningtimeforESP32(byte x1,byte y1) +{ + String runningTIME; + // lcd.setCursor(x1,y1); //Go to second line of the LCD Screen + if(t.hour<10) + { + // lcd.print("0"); + runningTIME="0"; + } + // lcd.print(t.hour); + // lcd.print(":"); + runningTIME+=t.hour; + runningTIME+=":"; + if(t.min<10) + { + // lcd.print("0"); + runningTIME+="0"; + } + // lcd.print(t.min); + // lcd.print(":"); + runningTIME+=t.min; + runningTIME+=":"; + if(t.sec<10) + { + // lcd.print("0"); + runningTIME+="0"; + } + // lcd.print(t.sec); + runningTIME+=t.sec; + // Serial.print("t.hour:");Serial.println(t.hour); + // Serial.print("runningtimeforesp:");Serial.println(runningTIME); + return runningTIME; +} + +void settimeMenu() +{ + lcd.setCursor(0,0); + lcd.print(t.mday); + printMonth(t.mon); + lcd.print(t.year); + + runningtime(0,1); + + lcd.setCursor(x,y); + prevsec = t.sec; + PREVMENU = MENU; +} + + +void calibrationMenu() +{ + MENU = CALIBRATION; + lcd.clear(); + lcd.setCursor(0,0); + lcd.print("Calibration Back"); + lcd.setCursor(0,1); + lcd.print("Set Distance(Km): "); + lcd.print(calibrationDistance); + lcd.setCursor(0,2); + lcd.print("Start 00.000Km"); + lcd.setCursor(0,3); + lcd.print("1m="); + lcd.print(((float)Calibration/1000),3); + char Calibrationstr[6]; + sprintf(Calibrationstr, "%06lu", Calibration); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(0,0); + lcd.print("Calibration Back"); + //lcd.setCursor(0,0); + //lcd.print(Calibration); + //lcd.home(); + x=18; + y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + Serial.print(Calibrationstr);Serial.println("end"); +} + +void constantaMenu() +{ + MENU = CONSTANTA; + lcd.clear(); + lcd.print("Constanta Back"); + lcd.setCursor(0,1); + lcd.print("Sub Trip:"); + lcd.setCursor(14,1); + lcd.print(Trip[curTrip].sub); + lcd.setCursor(0,2); + lcd.print("Set Speed:"); + lcd.setCursor(13,2); + if (constanta<10) lcd.print("0"); + lcd.print(constanta,4); + //lcd.print( + lcd.setCursor(0,3); + lcd.print("Start Time:"); + //DS3231_get(&t); //Get time + lcd.setCursor(12,3); //Go to second line of the LCD Screen + if(starttracthour<10) + { + lcd.print("0"); + } + lcd.print(starttracthour); + lcd.print(":"); + if(starttractmin<10) + { + lcd.print("0"); + } + lcd.print(starttractmin); + lcd.print(":"); + if(starttractsec<10) + { + lcd.print("0"); + } + lcd.print(starttractsec); + lcd.print(""); + //x=14; + //y=0; + lcd.setCursor(x,y); + lcd.cursor(); + //lcd.blink(); + //blinkON=true; + PREVMENU = MENU; + +} +void updateCount() +{ + if (dircount1 == FORWARD) { + count1 = count1 + (VSSCount-time1); + } + else if (dircount1 == BACKWARD) { + count1 = count1 - (VSSCount-time1); + } + + if (dircount2 == FORWARD) { + count2 = count2 + (VSSCount-time2); + } + else if (dircount2 == BACKWARD) { + count2 = count2 - (VSSCount-time2); + } + time1 = VSSCount; + time2 = VSSCount; +} +void saveCount() +{ + if (count1 != prevcount1) { + count1Seq++; + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + prevcount1 = count1; + } + + if ((count1-count2) != count1count2diff) { +#ifdef DEBUG + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); +#endif + count1count2diff = count1-count2; + int pointer = count1count2diffAddress*32; + mem.writeLong(pointer,count1count2diff); +#ifdef DEBUG + Serial.println("save count1count2diff"); +#endif + } +} + + +void secondrallyMenu() +{ + + char heading2[6]; + char heading4[6]; + lcd.setCursor(9,1); + //sprintf(heading2, "%s", (dirfwdcount1?"Fw":"Bw")); + sprintf(heading2, "%s", dircount[dircount1]); + lcd.print(heading2); + + lcd.setCursor(9,3); + //sprintf(heading4, "%s", (dirfwdcount2?"Fw":"Bw")); + sprintf(heading4, "%s", dircount[dircount2]); + lcd.print(heading4); + +#ifdef DEBUG + Serial.println("secondrallyMenu"); +#endif +} + +void rallyMenu() +{ + MENU = RALLY; + + //lcd.clear(); + lcd.setCursor(15,0); + if (showTIME) lcd.print("Time "); + else lcd.print("TDiff"); + + secondrallyMenu(); + PREVMENU = MENU; +// #ifdef DEBUG + Serial.println("rallyMenu"); +// #endif +} + +unsigned long startspeed=0; +float startdistance=0; + +void redrawcalibrationMenu() +{ +// bool test=false; + + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + char cur_distance_str[9]; + byte xtemp=13; + if (distance<100) { + sprintf(cur_distance_str, "%02d.%03dKm", (int)distance, (int)((distance - (int)distance)*1000)); + xtemp = 12; + } + else if (distance<1000) { + sprintf(cur_distance_str, "%02d.%02dKm", (int)distance, (int)((distance - (int)distance)*100)); + } + else { + sprintf(cur_distance_str, "%03d.%01dKm", (int)distance, (int)((distance - (int)distance)*10)); + } +// if(test){ + Calibrationtime = VSSCount; + lcd.setCursor(xtemp,2); + lcd.print(cur_distance_str); +// } +} + +void redrawcalibrationMenuForESP32() +{ + DynamicJsonDocument getCalib(512); + deserializeJson(getCalib, getCalibJson); + float distance; + Calibrationcount = Calibrationcount + (VSSCount-Calibrationtime); + distance = (float)Calibrationcount/((float)Calibration); + // char cur_distance_str[8]; + + Calibrationtime = VSSCount; + // lcd.setCursor(xtemp,2); + // lcd.print(cur_distance_str); + getCalib["counter"]=VSSCount; ///// + getCalib["curTrip"]=String(Trip[curTrip].sub); ///// + getCalib["curTripSpeed"]=String(Trip[curTrip].speed); ///// + String curTime = runningtimeforESP32(6,0); + getCalib["curTime"]=curTime; + + getCalib["caldist"]=calibrationDistance; + getCalib["calman"]= Calibration; + // Serial.println(cur_distance_str); + if (calibrationON){ + getCalib["calkm"]= String(distance,3); + Calibrationcountbackup=Calibrationcount; + } else { + distance = (float)Calibrationcountbackup/((float)Calibration); + getCalib["calkm"]= String(distance, 3); + } + getCalib["calmeter"]=String(float(Calibration)/1000,3); + getCalib["calval"]= Calibration; + + getCalibJson = ""; + serializeJson(getCalib, getCalibJson); +} + + +// char digitClock(int v){ +// if (v < 10) +// return '0' + v; +// else +// return 'A' + (v-10); +// } +void digitClock(int v){ + // lcd.setCursor(x,y); + if (v < 10){ + lcd.print("0"); + lcd.print(v); + // return '0' + v; + } + else lcd.print(v); +} +void digitClock(int v, byte x, byte y){ + lcd.setCursor(x,y); + if (v < 10){ + lcd.print("0"); + lcd.print(v); + // return '0' + v; + } + else lcd.print(v); +} + +void redrawrallyMenu() +{ + // Serial.println("redrawRM"); + DS3231_get(&t); //Get time + //runningtime(6,0); + //float distance, distance1, distance2; + + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + updateCount(); + + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 +// Serial.println("redrawRM 1"); + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + //Serial.print(tempcount1);Serial.print(";"); Serial.print(time1);Serial.print("; ");Serial.print(Calibration); Serial.print(";"); Serial.println(count1); + + //Serial.print(millis());Serial.print(";");Serial.println(distance1,3); + //Serial.print(starttracthour); Serial.print(":"); Serial.print(starttractmin); Serial.print(":"); Serial.println(starttractsec); + //Serial.println(distance2,3); + + // lcd.setCursor(4,0); + // lcd.print(Trip[curTrip].sub); + // lcd.setCursor(0,2); + + // lcd.print(Trip[curTrip].speed); + // lcd.print("Km/H"); + + runningtime(6,0); + + // lcd.setCursor(11,2); + char cur_speed_str[9]; + int speedtemp=(int)speed1; + int speedtemp2=(int)((speed1 - (int)speed1)*10); + + sprintf(cur_speed_str, "%3d.%01dKm/h", speedtemp , speedtemp2 ); +// Serial.print(count1); Serial.print(";");Serial.print(Calibration); Serial.print(";");Serial.print(speed1); Serial.print(";");Serial.println(cur_speed_str); +// Serial.print(distance1); Serial.print(";");Serial.print(startdistance); Serial.print(";");Serial.print(startspeed); Serial.println(";"); + // lcd.print(cur_speed_str); + char cur_distance1_str[8]; + char cur_distance2_str[8]; + // lcd.setCursor(0,1); +// Serial.print(";redrawRM 2;"); + if (distance1<100) { + sprintf(cur_distance1_str, "%02d.%03dKm", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_str, "%02d.%02dKm", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_str, "%03d.%01dKm", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + // lcd.print(cur_distance1_str); + + // lcd.setCursor(0,3); + if (distance2<100) { + sprintf(cur_distance2_str, "%02d.%03dKm", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_str, "%02d.%02dKm", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_str, "%03d.%01dKm", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + // lcd.print(cur_distance2_str); + + // Serial.print(";redrawRM 3;"); + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + // lcd.setCursor(9,1); + uint8_t secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; +// Serial.print(";redrawRM 4;"); +//Serial.print((long)starttracthour*3600); Serial.print(";"); Serial.print(starttractmin*60); Serial.println(";"); +//Serial.print(totsecs1); Serial.print(";"); Serial.print(totstarttractsecs); Serial.print(";"); +//Serial.print(tottime1);Serial.print(";");Serial.println(totcurrentsecs); + if (totcurrentsecs= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + char cur_time1_str[12]; + if (showTIME) { + // lcd.setCursor(9,1); + // lcd.print(dircount[dircount1]); + // lcd.print(" "); + // digitClock(hours1); + // lcd.print(":"); + // digitClock(mins1); + // lcd.print(":"); + // digitClock(secs1); + + sprintf(cur_time1_str, "%s %02d:%02d:%02d", dircount[dircount1], hours1, mins1, secs1); + } + else { + if (hours1 < 10) sprintf(cur_time1_str, "%s %s%01d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_str, "%s%s%02d:%02d:%02d", dircount[dircount1], (negatifsign?"-":" "), hours1, mins1, secs1); + + } + // lcd.print(cur_time1_str); +// Serial.print(";redrawRM 5;"); +// Print Second TIME + // lcd.setCursor(9,3); + uint8_t secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } +// Serial.print(";redrawRM 6;"); + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[11]; + if (showTIME) { + lcd.setCursor(9,3); + lcd.print(dircount[dircount2]); + lcd.print(" "); + digitClock(hours2); + lcd.print(":"); + digitClock(mins2); + lcd.print(":"); + digitClock(secs2); + + // sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + + // lcd.setCursor(4,0); + // lcd.print(Trip[curTrip].sub); + // lcd.setCursor(0,2); + // lcd.print(Trip[curTrip].speed); + // lcd.print("Km/H"); + + // lcd.setCursor(11,2); + + // lcd.print(cur_speed_str); + + // lcd.setCursor(0,1); + + // lcd.print(cur_distance1_str); + + + // lcd.setCursor(0,3); + + // lcd.print(cur_distance2_str); + + // lcd.setCursor(9,1); + // lcd.print(dircount[dircount1]); + // // lcd.print(cur_time1_str); + // digitClock(hours1,12,1); + // lcd.print(":"); + // // lcd.print(digitClock(mins1)); + // digitClock(mins1); + // lcd.print(":"); + // // lcd.print(digitClock(secs1)); + // digitClock(secs1); + // // Serial.print(digitClock(hours1));Serial.print(":");Serial.print(digitClock(mins1));Serial.print(":");Serial.println(digitClock(secs1)); + + // // lcd.setCursor(9,3); + + + // // lcd.print(cur_time2_str); + + + lcd.setCursor(x,y); + // Serial.println("END redrawRM"); +} + +void calculationRally() //calculation only ESP32 +{ + DynamicJsonDocument getRally(1024); + deserializeJson(getRally, getRallyJson); + DS3231_get(&t); //Get time + // Serial.println("startCRal"); + updateCount(); + + distance1 = (float)count1/((float)Calibration); // * 1); + distance2 = (float)count2/((float)Calibration); + float speed1=0; + + if ((distance1 - startdistance) > 0) { + speed1 = (distance1-startdistance)/(millis()-startspeed)*3600000; + } + + startdistance = distance1; + startspeed = millis(); //startspeed is only one no startspeed2 + + if ((millis()-startsavemillis)>0) { + + if (distance1 != prevdistance1) { + mem.writeFloat(832,distance1); + prevdistance1 = distance1; + } + if (distance2 != prevdistance2) { + mem.writeFloat(864,distance2); + prevdistance2 = distance2; + } + saveCount(); + startsavemillis=millis()+2500; + } + + // lcd.setCursor(4,0); + // lcd.print(Trip[curTrip].sub); + // lcd.setCursor(0,2); + + // lcd.print(Trip[curTrip].speed); + // lcd.print("Km/H"); + getRally["Trip"]=String(Trip[curTrip].sub); ///// + getRally["TSpeed"]=String(Trip[curTrip].speed); ///// + char sTime[9]; + sprintf(sTime, "%02u:%02u:%02u", Trip[curTrip].startHour, Trip[curTrip].startMin, Trip[curTrip].startSec); + getRally["TsTime"]=sTime; ///// + getRally["TTime"]=String(Trip[curTrip].subTime); ///// + getRally["TDist"]=String(Trip[curTrip].distance); ///// + + // Serial.print(Trip[curTrip].sub);Serial.print(Trip[curTrip].speed);Serial.print(";");Serial.println(Trip[curTrip].startHour); + + String curTime = runningtimeforESP32(6,0); + getRally["Time"]=curTime; + // lcd.setCursor(11,2); + char cur_speed_str[7]; + sprintf(cur_speed_str, "%3d.%01d", (int)speed1, (int)((speed1 - (int)speed1)*10)); + // lcd.print(cur_speed_str); + getRally["curSpeed"]=cur_speed_str; ///// + // char cur_distance1_str[8]; + // char cur_distance2_str[8]; + char cur_distance1_plain[7]; + char cur_distance2_plain[7]; + // lcd.setCursor(0,1); + + if (distance1<100) { + sprintf(cur_distance1_plain, "%02d.%03d", (int)distance1, (int)((distance1 - (int)distance1)*1000)); + } + else if (distance1<1000) { + sprintf(cur_distance1_plain, "%02d.%02d", (int)distance1, (int)((distance1 - (int)distance1)*100)); + } + else { + sprintf(cur_distance1_plain, "%03d.%01d", (int)distance1, (int)((distance1 - (int)distance1)*10)); + } + + // lcd.print(cur_distance1_str); + getRally["curDist1"]=String(cur_distance1_plain); + // lcd.setCursor(0,3); + + if (distance2<100) { + sprintf(cur_distance2_plain, "%02d.%03d", (int)distance2, (int)((distance2 - (int)distance2)*1000)); + } + else if (distance2<1000) { + sprintf(cur_distance2_plain, "%02d.%02d", (int)distance2, (int)((distance2 - (int)distance2)*100)); + } + else { + sprintf(cur_distance2_plain, "%03d.%01d", (int)distance2, (int)((distance2 - (int)distance2)*10)); + } + + // lcd.print(cur_distance2_str); + getRally["curDist2"]=cur_distance2_plain; + + float distancetime1 = distance1 * 60 / constanta; + float distancetime2 = distance2 * 60 / constanta; + +//Calculating all about TIME,TDiff(including passing 23:59:59) + // lcd.setCursor(9,1); + int secs1, mins1, hours1; + + secs1 = (distancetime1-(int)distancetime1)*60; + mins1 = (int)distancetime1 % 60; + hours1 = (int)distancetime1 / 60; + unsigned long totcurrentsecs = t.sec + (t.min*60) + ((long)t.hour*3600); + unsigned long totsecs1 = secs1 + (mins1*60) + ((long)hours1*3600); + unsigned long totstarttractsecs = starttractsec + (starttractmin*60) + ((long)starttracthour*3600); + unsigned long tottime1 = totsecs1 + totstarttractsecs; + boolean negatifsign = false; + + if (totcurrentsecs=0) { //positif means we are too fast, slow down please. + if (tottime1 >= totcurrentsecs) { //positif means we are too fast, slow down please. + // Serial.println("pos"); + negatifsign = false; + tottime1 = tottime1 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + // Serial.println("neg"); + negatifsign = true; + tottime1 = totcurrentsecs - tottime1; + } + } + //Serial.print(negatifsign);Serial.print(";"); Serial.println(tottime1); + hours1 = ((int)(tottime1 / 3600))%24; + mins1 = (int)((tottime1 % 3600)/60); + secs1 = (tottime1 % 60); + + // char cur_time1_str[12]; + char cur_time1_plain[10]; + + if (showTIME) { + sprintf(cur_time1_plain, "%02d:%02d:%02d", hours1, mins1, secs1); + } + else { + if (hours1<10) sprintf(cur_time1_plain, "%s%01d:%02d:%02d", (negatifsign?"-":" "), hours1, mins1, secs1); + else sprintf(cur_time1_plain, "%s%02d:%02d:%02d", (negatifsign?"-":" "), hours1, mins1, secs1); + } + // lcd.print(cur_time1_str); + getRally["time1"]=cur_time1_plain; + getRally["dir1"]=dircount[dircount1]; + +// Print Second TIME + // lcd.setCursor(9,3); + int secs2, mins2, hours2; + + secs2 = (distancetime2-(int)distancetime2)*60; + mins2 = (int)distancetime2 % 60; + hours2 = (int)distancetime2 / 60; + + unsigned long totsecs2 = secs2 + (mins2*60) + ((long)hours2*3600); + unsigned long tottime2 = totsecs2 + totstarttractsecs; +//Serial.println(tottime2); + + if (!showTIME) { + if (tottime2 >= totcurrentsecs) { //positif means we are too fast, slow down please. + negatifsign = false; + tottime2 = tottime2 - totcurrentsecs; + } + else { //negatif means we need to hurry, its late + negatifsign = true; + tottime2 = totcurrentsecs - tottime2 ; + } + } + + // Serial.println("MidCRal"); + + hours2 = ((int)(tottime2 / 3600))%24; + mins2 = (int)((tottime2 % 3600)/60); + secs2 = (tottime2 % 60); + char cur_time2_str[12]; + char cur_time2_plain[9]; + if (showTIME) { + sprintf(cur_time2_str, "%s %02d:%02d:%02d", dircount[dircount2], hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_str, "%s %s%01d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_str, "%s%s%02d:%02d:%02d", dircount[dircount2], (negatifsign?"-":" "), hours2, mins2, secs2); + } + + if (showTIME) { + sprintf(cur_time2_plain, "%02d:%02d:%02d", hours2, mins2, secs2); + } + else { + if (hours2<10) sprintf(cur_time2_plain, "%s%01d:%02d:%02d", (negatifsign?"-":" "), hours2, mins2, secs2); + else sprintf(cur_time2_plain, "%s%02d:%02d:%02d", (negatifsign?"-":" "), hours2, mins2, secs2); + } + + // lcd.print(cur_time2_str); + getRally["time2"]=cur_time2_plain; + getRally["dir2"]=dircount[dircount2]; + + // lcd.setCursor(x,y); + getRally["counter"]=VSSCount; + getRallyJson=""; + serializeJson(getRally, getRallyJson); + // Serial.println("ENDCRal"); +} ///// calculation only for esp32 + +void set_cursor_pos(int new_pos) +{ + /* + Cursor Positon map: + ---------------------- + |Count1 TIME AvgSp| + |1 35 |7 9 | + |Count2 KmH| + |2 46 |8 10| + ---------------------- + */ + + //Need to clear the previous cursor position + //int x, y; + switch(CURSOR_POS) + { + case 1: + x = 0; + y = 1; + break; + case 2: + x = 0; + y = 3; + break; + case 3: + x = 8; //Km is 7,1 + y = 1; + break; + case 4: + x = 8; //Km is 7,3 + y = 3; + break; + case 5: + x = 9; + y = 1; + break; + case 6: + x = 9; + y = 3; + break; + case 7: + x = 13; + y = 1; + break; + case 8: + x = 13; + y = 3; + break; + case 9: + x = 18; + y = 1; + break; + case 10: + x = 18; + y = 3; + break; + } + lcd.print(" "); + lcd.blink(); + lcd.setCursor(8,3); + lcd.write(1); //UP Arrow + + lcd.setCursor(8,1); + lcd.write(2); //DOWN Arrow + + lcd.setCursor(x,y); + +/* + switch(new_pos) + { + case 1: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 2: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_RIGHT); + break; + case 3: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 4: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 5: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 6: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_DOWN); + break; + case 7: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + case 8: + lcd.setCursor(6,1); + //lcd.print(LCD_ARROW_LEFT); + break; + } +*/ + + CURSOR_POS = new_pos; +#ifdef DEBUG + Serial.print("SetCursorPosition:"); + Serial.println(CURSOR_POS); +#endif +} + + +void IRAM_ATTR isr() { //esp32 only + VSSCount++; + ledstate=!ledstate; +} + +void convertJsonTripToTripStruct(uint8_t iTrip, const char* strJson){ + // Serial.print(iTrip); Serial.print(";");Serial.println(strJson); + DynamicJsonDocument doc(256); + deserializeJson(doc, strJson); + Trip[iTrip].distance = doc["dist"]; + Trip[iTrip].subTime = doc["time"]; +} +void fillTripArray(){ + char tempTrip[7]="/tripZ"; + // Serial.println(tempTrip); + String tempReadFile; + tempReadFile.reserve(100); + for (uint8_t i=0; isend_P(200, "text/html", HTML_CALIBRATION, processor); + // isloadingConst=true; + howLongInMillis=millis(); + int pageZise; + int pageZiseConstRow; + pageZise=strlen_P(HTML_CONSTHEADER) + strlen_P(HTML_CONSTROW)*TRIPSIZE + strlen_P(HTML_CONSTEND); + String PAGE; + PAGE.reserve(pageZise); + pageZiseConstRow = strlen_P(HTML_CONSTROW); + String PAGEROW; + PAGEROW.reserve(pageZiseConstRow); + + PAGE = FPSTR(HTML_CONSTHEADER); + for (uint8_t i=65; i<(TRIPSIZE+65); i++){ + PAGEROW = FPSTR(HTML_CONSTROW); + PAGEROW.replace("%A%", String(char(i))); + PAGEROW.replace("%speed%", "speed"+String(char(i))); + PAGEROW.replace("%dist%", "dist"+String(char(i))); + PAGEROW.replace("%time%", "time"+String(char(i))); + PAGEROW.replace("%stime%", "stime"+String(char(i))); + // Serial.println(PAGEROW); + PAGE += PAGEROW; + } + PAGE += FPSTR(HTML_CONSTEND); + // Serial.println(PAGE); + Serial.print(pageZise); + Serial.print("PAGE Size:"); + Serial.println(PAGE.length()); + request->send(200, "text/html", PAGE); + // request->send(SPIFFS, "/constanta.html", String(), false, procConst); // read from spiif straight away + // isloadingConst=false; +} +void handlesetConst(AsyncWebServerRequest *request, JsonVariant &json){ + isloadingConst=true; + // JsonObject& jsonObj = json.as(); + if (not json.is()) { + Serial.println("Not JSONG object"); + request->send(400, "text/plain", "Not an object"); + return; + } + auto&& data = json.as(); + String hasil; + hasil.reserve(100); + boolean canSave = true; + const char* datatrip = data["trip"]; + char trip = datatrip[0]; + int iTrip = ((int) trip)-65; + uint8_t constCurTrip= (int)trip; + Serial.println(trip);Serial.println(iTrip);Serial.println(constCurTrip); + if (constCurTrip >= 65 && constCurTrip < (TRIPSIZE+65)){ + constCurTrip = constCurTrip-65; + } else { + canSave = false; + } + + // const char* speed = data["speed"].as(); + float speed = data["speed"].as(); + float dist = data["dist"].as(); + const char* time = data["time"].as();//.as(); + // if (!isNumeric(speed)){ + // canSave = false; + // } + float constconstanta = speed; //.toFloat(); + // String constdist = data["dist"].as(); + // String consttime = data["time"].as(); + const char* stime = data["stime"].as();//.as(); + unsigned long constvaluesettime; + if(!isShortTime(stime)){ + canSave = false; + } + constvaluesettime = getValueSetTime(stime); + Serial.println(dist); + if (constvaluesettime==-1){ + canSave = false; + } + + Serial.print(constconstanta,3); Serial.print(";"); Serial.println(constCurTrip); + Serial.print(constvaluesettime); Serial.print(";"); Serial.println(speed); + AsyncResponseStream *response = request->beginResponseStream("application/json"); + if (canSave){ + // String filename = String("/trip"+trip); + char filename[7] = "/tripZ"; + // Serial.println(filename); + // Serial.println(filename); + filename[5]=trip; + Serial.println(filename); + // if (speed != "" && speed !="null" && stime!= "" && stime !="null") { + // if (stime!= "" && stime !="null") { + bool wfile; + serializeJson(data, hasil); + wfile = writeFile(SPIFFS, filename, hasil.c_str()); + if (wfile){ + setMemSpeedInConstanta(constconstanta, constCurTrip); + setMemStime(constvaluesettime, constCurTrip); + convertJsonTripToTripStruct(iTrip, hasil.c_str()); + data["ok"]=1; + } + // } + + Serial.println(hasil); + // Serial.print("isi ");Serial.print(filename);Serial.println(readFile(SPIFFS, filename)); + } + // request->send(200, "text/plain", hasil); // handle data and respond + serializeJson(data, *response); + request->send(response); + + // request->send(200, "text/plain", hasil); + isloadingConst=false; +} + + +void handleloadConst(AsyncWebServerRequest *request, JsonVariant &json) { + isloadingConst=true; + // while(iscalculatingRally) { + // yield(); + // } + String constTrip; + String tempTrip; + tempTrip.reserve(100); + String tripload; + + tripload = "{\"alltrip\":"; + tripload+="["; + uint8_t maxI=81; + DynamicJsonDocument doc(256); + float speedinconstanta; + // unsigned long sTimeinconstanta; + String tempSpeed; + tempSpeed.reserve(10); + String tempsTime; + tempsTime.reserve(10); + for(uint8_t i=65; ibeginResponseStream("application/json"); + // DynamicJsonDocument doc(1024); + // deserializeJson(doc, tripload); + // doc["ok"]=1; + // serializeJson(doc, *response); + request->send(200, "text/plain", tripload); // handle data and respond + // request->send(tripload); + isloadingConst=false; + Serial.print("constLoadTime=");Serial.println(millis()-howLongInMillis); + } + +void setup() { +getCalibJson.reserve(512); +getRallyJson.reserve(512); +// +// +// +// +//#ifdef DEBUG + Serial.begin(115200); + Serial.println("Starting Rally"); +//#endif + // pinMode(ledPin, OUTPUT); + pinMode(simulatorPWMPin,OUTPUT); + pinMode(LED_BUILTIN, OUTPUT); + pinMode(interruptPin, INPUT); //Pull down using resistor to ground + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + // attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); + // attachInterrupt(interruptPin, isr, FALLING); + Wire.begin(I2C_SDA, I2C_SCL); //for lolin32lite sda=15; scl=13 + // pinMode(UP_pin, INPUT_PULLUP); /// + // pinMode(DOWN_pin, INPUT_PULLUP); /// + // pinMode(LEFT_pin, INPUT_PULLUP); /// + // pinMode(RIGHT_pin, INPUT_PULLUP); /// + // pinMode(OK_pin, INPUT_PULLUP); /// + + btnUP.begin(); /// using JC_BUTTON harus ada begin + btnDN.begin(); + btnLF.begin(); + btnRF.begin(); + btnOK.begin(); + btnESC.begin(); + //DS3231_init(DS3231_INTCN); + DS3231_init(DS3231_CONTROL_INTCN); + //memset(recv, 0, BUFF_MAX); +#ifdef DEBUG + Serial.println("GET time"); +#endif +/* +Trip[0].sub = "A"; +Trip[0].speed = 24.275; +Trip[0].startHour = 25; +//Trip[0].distance = 12.898; +Trip[9].sub = "A"; +Trip[9].speed = 90.2751; +Trip[9].startHour = 22; +Trip[9].startMin = 59; +Trip[9].startSec = 58; +*/ +//Trip[9].distance = 12.898; +//Serial.println(Trip[0].sub);Serial.println(Trip[0].speed);Serial.println(Trip[0].startHour);Serial.println(Trip[0].startMin);Serial.println(Trip[0].startSec); +//Serial.println(Trip[0].distance); +//Serial.println(Trip[0].subTime); + + +// lcd.init(); +// lcd.backlight(); + + lcd.begin(20, 4); + // if(lcd.begin(20, 4)) + // { + // // begin() failed so blink the onboard LED if possible + // return; // this never returns + // } + lcd.setBacklight(0xff); + // Wire.setClock(100000L); // set i2c clock bit rate, if asked + + lcd.print("i2c clock:"); + lcd.setCursor(0,1); + lcd.print(Wire.getClock()); + lcd.print(" Hz"); + delay(3000); + + + + + + //**************************LCD Setup******************************** + +// // lcd.begin (20,4); // initialize the lcd +// // lcd.init(); +// lcd.begin(); +// // Switch on the backlight +// /// lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); +// lcd.backlight(); +// /// lcd.setBacklight(LED_ON); + + //***************************END LCD Setup******************************** +#ifdef DEBUG + Serial.println("Setting time"); +#endif + //char a[]="304022129022016"; + + DS3231_get(&t); //Get time + + blinkON=false; + sec60=t.sec; + min60=t.min; + hour24=t.hour; + + delay(100); // delay for reading mem.read + //mainMenu(); + printUPchar(); + printDOWNchar(); + count1 = memretrieveLong(count1Address, RRcountSIZE, count1Seq); //(int startaddress, byte RRsize, unsigned long seq) + Serial.println(count1Seq); + int countaddresspointer = count1count2diffAddress*32; + Serial.print(countaddresspointer); + count1count2diff = mem.readLong(countaddresspointer); + //count1count2diff = mem.readLong((count1count2diffAddress*32)); + count2 = count1 - count1count2diff; + //printmemLong(0,20); //startaddress, size + Serial.print("count1=");Serial.print(count1);Serial.print(";count2=");Serial.print(count2);Serial.print("countdiff=");Serial.println(count1count2diff); + +//TESTING MEM AT24cx EEPROM check the address in the library #define ..... 0x57 + // Serial.println("Write 42 to address 12"); + // mem.write(12, 42); + // Serial.println("Read byte from address 12 ..."); + // byte b = mem.read(12); + // Serial.print("... read: "); + // Serial.println(b, DEC); + // Serial.println(); + + //count1Seq = 4294967290; +/* + for (int i=0; i<25 ; i++){ + count1Seq++; + //Serial.println(count1Seq); + //memwritingLong(rrcountpointer1, count1Seq, count1+1, RRcountSIZE ); + memwritingLong(count1Address, RRcountSIZE, count1Seq, count1);//(int startaddress, byte RRsize, unsigned long seq, unsigned long Data) + } + */ + //mem.writeLong(896, 110025); to reset CALIBRATION value to CRV + /* + starttracthour=mem.read(770); + starttractmin=mem.read(769); + starttractsec=mem.read(768); + */ +// for (int i = 0; i23) starttracthour = 23; + if (starttractmin>59) starttractmin = 59; + if (starttractsec>59) starttractsec = 59; + //constanta=mem.readFloat(800); + constanta = Trip[curTrip].speed; + if ((constanta > 150) || (constanta < 0)) constanta = 60; /// aslinya if ((constanta > 150) || (constanta < 0)) constanta = 60; + long m = mem.readLong(896); //read calibration value; + if (m > 0) { + Calibration = m; + } else Calibration = 110025; + // Calibration = 100000; + +//#ifdef DEBUG + Serial.println("calibration and constanta"); + Serial.println(m); + Serial.println(Calibration); + Serial.println(constanta); +//#endif + constantatodigit(); + +// Serial.print(digit1);Serial.print(digit2); Serial.print(digit3); Serial.print(digit4);Serial.print(digit5);Serial.println(digit6); +// Serial.println(constanta,5); + //Serial.print(digitalRead(UP_pin));Serial.print(digitalRead(DOWN_pin));Serial.print(digitalRead(LEFT_pin));Serial.print(digitalRead(RIGHT_pin));Serial.println(digitalRead(OK_pin)); + + prevcount1 = count1; + prevcount2 = count2; + + prevcalibrationtime+=calibrationtimeinterval; + prevtempint+=tempinterval; + prevtemprally+=tempintervalrally; + prevsettime += intervalsettime; + startmillis+=1000; + + + mainMenu(); + + +// +// +// +// + + + //Serial.begin(115200); + //DynamicJsonDocument doc(512); + // Initialize SPIFFS + #ifdef ESP32 + if(!SPIFFS.begin(true)){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #else + if(!SPIFFS.begin()){ + Serial.println("An Error has occurred while mounting SPIFFS"); + return; + } + #endif + // wifiManager.setAPCallback(configModeCallback); + // wifiManager.autoConnect(soft_ap_ssid); + fillTripArray(); + WiFi.onEvent(OnWiFiEvent); + //WiFi.mode(WIFI_STA); + WiFi.mode(WIFI_MODE_APSTA); + + WiFi.softAP(soft_ap_ssid, soft_ap_password); + + String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); + Serial.print("*** Your ssidString: "); + Serial.println(yourSSIDString); + Serial.println(ssid); + if (yourSSIDString != ""){ + strncpy(ssid, yourSSIDString.c_str() , (sizeof ssid)-1); + // strncpy(ssid, yourSSIDString.c_str() , (sizeof yourSSIDString)-1); + } + + Serial.println(ssid); + String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); + Serial.print("*** Your inputPwd: "); + Serial.println(yourInputPwd); + if (yourInputPwd != ""){ + strncpy(password, yourInputPwd.c_str() , (sizeof password)-1); + // strncpy(password, yourInputPwd.c_str() , (sizeof yourInputPwd)-1); + } +Serial.print("try to connect to ssid:");Serial.print(ssid);Serial.print("; with pwd:");Serial.println(password); + WiFi.begin(ssid, password); + if (WiFi.waitForConnectResult() != WL_CONNECTED) { + Serial.println("WiFi Failed!"); + //return; + } + + Serial.print("ESP32 IP as soft AP: "); + Serial.println(WiFi.softAPIP()); + + Serial.println(); + Serial.print("IP Address: "); + Serial.println(WiFi.localIP()); + +// //settingup MDNS +// if(!MDNS.begin("esp32")) { +// Serial.println("Error starting mDNS"); +// return; +// } +// Serial.println(“MDNS started.”); +// MDNS.addService(“http”, “tcp”, 80); +// // Init and get the time + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printLocalTime(); + + // Send web page with input fields to client + server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", main_menu, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + }); + + server.on("/wifi", HTTP_GET, [](AsyncWebServerRequest * request) { + + if (ON_STA_FILTER(request)) { + //request->send(200, "text/plain", "Hello from STA"); + request->send_P(200, "text/html", wifi_html, processor); + return; + + } else if (ON_AP_FILTER(request)) { + //request->send(200, "text/plain", "Hello from AP"); + Serial.println("on apfilter /wifi"); + request->send_P(200, "text/html", wifi_html, processor); + return; + } + + request->send(200, "text/plain", "Hello from undefined"); +}); + + + + // Send a GET request to /get?inputString= + server.on("/setwifi", HTTP_POST, [] (AsyncWebServerRequest *request) { + String inputMessage; + boolean bolrestart=false; + boolean POST=true; + Serial.println("ini masuk /setwifi"); + // GET inputString value on /get?inputString= + if (request->hasParam(PARAM_SSID, POST)) { + inputMessage = request->getParam(PARAM_SSID, POST )->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + // GET inputPwd value on /wifi/get?inputPwd= + if (request->hasParam(PARAM_PWD, POST)) { + inputMessage = request->getParam(PARAM_PWD, POST)->value(); + if (inputMessage!=""){ + writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + delay(50); + bolrestart=true; + //ESP.restart(); + } + } + else { + inputMessage = "No message sent"; + } + if (bolrestart) { + ESP.restart(); + } + Serial.println("ini /setwifi aja");Serial.println(inputMessage); + request->send(200, "text/text", inputMessage); + }); + + // // Send a GET request to /wifi/get?ssidString= + // server.on("/wifi/get", HTTP_GET, [] (AsyncWebServerRequest *request) { + // String inputMessage; + // // GET ssidString value on /wifi/get?ssidString= + // Serial.println("ini masuk wifi get"); + // Serial.println(request->params()); + // if (request->hasParam(PARAM_SSID)) { + // inputMessage = request->getParam(PARAM_SSID)->value(); + // writeFile(SPIFFS, "/ssidString.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // // GET inputPwd value on /wifi/get?inputPwd= + // else if (request->hasParam(PARAM_PWD)) { + // inputMessage = request->getParam(PARAM_PWD)->value(); + // writeFile(SPIFFS, "/inputPwd.txt", inputMessage.c_str()); + // delay(100); + // ESP.restart(); + // } + // else { + // inputMessage = "No message sent"; + // } + // Serial.println("/wifi/get value:"); Serial.println(inputMessage); + // request->send(200, "text/text", inputMessage); + // }); + + server.on("/menu", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + request->send_P(200, "text/html", main_menu); + }); + + server.on("/startrally", HTTP_GET, [] (AsyncWebServerRequest *request) { + //String s = MAIN_page; //Read HTML contents + //request->send_P(200, "text/html", s); //Send web page + String PAGE; + PAGE += FPSTR(HTML_PAGEHEADER); + PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + PAGE += FPSTR(HTML_DIVSTARTRALLY); + //PAGE += FPSTR(HTML_SCRIPTSETINTERVAL); + //PAGE += FPSTR(HTML_SCRIPTGETDATA); + PAGE += FPSTR(HTML_END); + //Serial.println(PAGE); + Serial.print("PAGE Size:"); + Serial.println(PAGE.length()); + request->send(200, "text/html", PAGE); + }); + + server.on("/startrally1", HTTP_GET, [] (AsyncWebServerRequest *request) { + request->send_P(200, "text/html", HTML_startrally1, processor); + }); + + server.on("/resetodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 1"); + request->redirect("/startrally1"); + }); + + server.on("/resetodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("ODORESET 22222"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 1 to 2"); + request->redirect("/startrally1"); + }); + + server.on("/copytoodo1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("COPY ODO 2 to 1"); + request->redirect("/startrally1"); + }); + server.on("/DIR", HTTP_GET, [] (AsyncWebServerRequest *request) { + String inputMessage; + String inputParam; + if (request->hasParam("DIR1")){ + inputMessage=request->getParam("DIR1")->value(); + Serial.print("DIR 1->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW1"); + break; + case 'S': + Serial.println("ST1"); + break; + case 'B': + Serial.println("BACK1"); + break; + default: + Serial.println("Default VAL1"); + } + } + else if (request->hasParam("DIR2")){ + inputMessage=request->getParam("DIR2")->value(); + Serial.print("DIR 2->");Serial.println(inputMessage); + switch(inputMessage[0]){ + case 'F': + Serial.println("FW2"); + break; + case 'S': + Serial.println("ST2"); + break; + case 'B': + Serial.println("BACK2"); + break; + default: + Serial.println("Default VAL2"); + } + } + request->redirect("/startrally1"); + }); + + + server.on("/TG1", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 1"); + request->redirect("/startrally1"); + }); + + server.on("/TG2", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("TOGGLE 2"); + request->redirect("/startrally1"); + }); +// //server.on("/adc", HTTP_GET); //This is display page +// server.on("/readADC", HTTP_GET, [] (AsyncWebServerRequest *request) { +// // int a = analogRead(A0); +// // String adcValue = String(millis()); +// String adcValue = getPin(); +// Serial.println(adcValue); +// request->send_P(200, "text/plain", adcValue.c_str()); //Send ADC value only to client ajax request +// }); + + server.on("/calibration", HTTP_GET, [] (AsyncWebServerRequest *request) { + int params = request->params(); //showing all params + for(int i=0;igetParam(i); + if(p->isFile()){ //p->isPost() is also true + Serial.printf("FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size()); + } else if(p->isPost()){ + Serial.printf("POST[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } else { + Serial.printf("GET[%s]: %s\n", p->name().c_str(), p->value().c_str()); + } + } + //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); + request->send_P(200, "text/html", HTML_CALIBRATION, processor); + }); + server.on("/constanta", HTTP_GET, [] (AsyncWebServerRequest *request) { + Serial.println("start /const"); + for (uint8_t i=0; i(); + + }); + server.addHandler(setconst); + server.addHandler(loadconst); + +Serial.println("before onevent"); + ws.onEvent(onWsEvent); //add ws event + wscal.onEvent(onWsEvent2); //add ws event + server.addHandler(&ws); + server.addHandler(&wscal); +Serial.println("after onevent"); + server.onNotFound(notFound); + Serial.println("onnotfound"); + + server.begin(); + Serial.println("server begin"); +} + +unsigned long testLoadTime; + +void loop() //loop from VSS RALLY V2 +{ +#ifdef DEBUG + prevtimemicros = micros(); +#endif +// #ifndef ATMEGA328 + //digitalWrite(ledPin, ledstate); + digitalWrite(LED_BUILTIN, ledstate); +// #endif + +// Serial.print("start loop; "); + char tempF[6]; + unsigned long now1 = millis(); + + btnUP.read(); //read the buttons + btnDN.read(); + btnLF.read(); //read the buttons + btnRF.read(); + btnOK.read(); + btnESC.read(); +// Serial.print("read button; "); + if (millis()-rallyEditTime >1500) rallyEditRpt = 0; + switch (STATE) { + case WAIT: //wait for a button event + if (btnUP.wasPressed()) + STATE = UP; + else if (btnDN.wasPressed()) + STATE = DOWN; + else if (btnLF.wasPressed()) + STATE = LEFT; + else if (btnRF.wasPressed()) + STATE = RIGHT; + else if (btnUP.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnDN.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnLF.wasReleased()) //reset the long press interval + rpt = REPEAT_FIRST; + else if (btnRF.wasReleased()) + rpt = REPEAT_FIRST; + else if (btnUP.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = UP; + } + else if (btnDN.pressedFor(rpt)) { + rpt += REPEAT_INCR; + STATE = DOWN; + } + else if (btnLF.pressedFor(rpt)) { //check for long press + rpt += REPEAT_INCR; //increment the long press interval + STATE = LEFT; + } + else if (btnRF.pressedFor(1000)) { + rpt += REPEAT_INCR; + STATE = RIGHT; + } + else if (btnOK.wasPressed() && (MENU != RALLY)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS > 4)) { + STATE = OKAY; + } + else if (btnOK.wasPressed() && (CURSOR_POS <= 2)) { + //STATE = OKAY; + if (!rallyEditRpt) { + rallyEditTime = millis(); + rallyEditRpt++; + //Serial.println("!rallyEditRpt"); + //Serial.println(rallyEditRpt); + } + else if (millis()-rallyEditTime > 1500) { + rallyEditRpt = 0; + //Serial.println("rallyEditRpt = 0"); + //Serial.println(rallyEditRpt); + } + else if (rallyEditRpt == 2) { + //Serial.println("rallyEditRpt = ");Serial.println(rallyEditRpt); + STATE = RALLYEDIT; + rallyEditRpt = 0; + } + else { + rallyEditRpt++; + //Serial.println("rallyEditRpt++"); + //Serial.println(rallyEditRpt); + } + } + else if (btnOK.pressedFor(rpt) && (CURSOR_POS <= 4)) { + STATE = OKAY; + } + else if (btnESC.wasPressed()){ + STATE = ESC; + //Serial.println("ESC pressed"); + } + break; + + case DOWN: //increment the counter + switch (MENU) { + case MAIN: + y = min(y+1, MAX_ROW); //but not more than the specified maximum + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = max(dist1digit1-1, 0); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = max(dist1digit2-1, 0); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y ==3) { + if (x == 0 || x == 1) { + dist2digit1 = max(dist2digit1-1, 0); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = max(dist2digit2-1, 0); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + + } + + } + else { + CURSOR_POS=min(CURSOR_POS+1,10); + set_cursor_pos(CURSOR_POS); + } + + break; + + case CALIBRATION: + if (!blinkON) y = min(y+1, MAX_ROW ); //but not more than the specified maximum + else if (blinkON && y==1) { + //calibrationDistance=max(calibrationDistance-1, 1); + tempcalibdist=max(tempcalibdist-1, 1); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = max(calibdigit3-1,0); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = max(calibdigit2-1,0); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = max(calibdigit1-1,0); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = min(y+1, 3); //but not less than the specified minimum + if (y==1) x=15; + } + else if (y==1) { + prevTrip = min(prevTrip+1,TRIPSIZE-1); + //curTrip = min(curTrip+1,TRIPSIZE-1); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1 = max(digit1-1, MIN_COUNT); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2 = max(digit2-1, MIN_COUNT); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3 = max(digit3-1, MIN_COUNT); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4 = max(digit4-1, MIN_COUNT); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5 = max(digit5-1, MIN_COUNT); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6 = max(digit6-1, MIN_COUNT); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = min(y+1, MAX_ROW); //but not more than the specified maximum + lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=max(hour24-1, MIN_COUNT); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=max(min60-1, MIN_COUNT); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=max(sec60-1, MIN_COUNT); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case UP: //decrement the counter + switch(MENU) { + case MAIN: + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + break; + + case CALIBRATION: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + x = 18; + } + else if (blinkON && y==1) { + //calibrationDistance=min(calibrationDistance+1, 9); + tempcalibdist=min(tempcalibdist+1, 9); + lcd.print(tempcalibdist); + } + else if (blinkON && y==3 && (x==18||x==19)) { + calibdigit3 = min(calibdigit3+1,99); + lcd.setCursor(18,3); + if (calibdigit3<10) lcd.print("0"); + lcd.print(calibdigit3); + } + else if (blinkON && y==3 && (x==16||x==17)) { + calibdigit2 = min(calibdigit2+1,99); + lcd.setCursor(16,3); + if (calibdigit2<10) lcd.print("0"); + lcd.print(calibdigit2); + } + else if (blinkON && y==3 && (x==14||x==15)) { + calibdigit1 = min(calibdigit1+1,50); + lcd.setCursor(14,3); + if (calibdigit1<10) lcd.print("0"); + lcd.print(calibdigit1); + } + break; + + case RALLY: + if (blinkON) { + if (y == 1) { + if (x == 0 || x == 1) { + dist1digit1 = min(dist1digit1+1, 999); + lcd.setCursor(0,y); + if (dist1digit1 <10) lcd.print("0"); + lcd.print(dist1digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist1digit2 = min(dist1digit2+1, 999); + lcd.setCursor(3,y); + if (dist1digit2 <10) { + lcd.print("00"); + }else if (dist1digit2 <100) lcd.print("0"); + lcd.print(dist1digit2); + } + } + else if (y == 3) { + if (x == 0 || x == 1) { + dist2digit1 = min(dist2digit1+1, 99); + lcd.setCursor(0,y); + if (dist2digit1 <10) lcd.print("0"); + lcd.print(dist2digit1); + } + else if (x == 3 || x == 4 || x == 5) { + dist2digit2 = min(dist2digit2+1, 999); + lcd.setCursor(3,y); + if (dist2digit2 <10) { + lcd.print("00"); + }else if (dist2digit2 <100) lcd.print("0"); + lcd.print(dist2digit2); + } + } + + } + else { + CURSOR_POS=max(CURSOR_POS-1,1); + set_cursor_pos(CURSOR_POS); + } + break; + + case CONSTANTA: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + if (y==0) x=16; + else if (y==1) x=15; + } + else if (y==1) { + prevTrip = max(prevTrip-1, MIN_COUNT); + //curTrip = max(curTrip-1, MIN_COUNT); + lcd.setCursor(14,y); + lcd.print(Trip[prevTrip].sub); + } + else if (x==13 && y==2) { + digit1=min(digit1+1, 9); + lcd.print(digit1); + } + else if (x==14 && y==2) { + digit2=min(digit2+1, 9); + lcd.print(digit2); + } + else if (x==16 && y==2) { + digit3=min(digit3+1, 9); + lcd.print(digit3); + } + else if (x==17 && y==2) { + digit4=min(digit4+1, 9); + lcd.print(digit4); + } + else if (x==18 && y==2) { + digit5=min(digit5+1, 9); + lcd.print(digit5); + } + else if (x==19 && y==2) { + digit6=min(digit6+1, 9); + lcd.print(digit6); + } + else if ((x==12 || x==13) && y==3) { //******SET CONSTANTA TIME ******* + hour24=min(hour24+1, 23); + lcd.setCursor(12,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==15 || x==16) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(15,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==18 || x==19) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(18,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + + case SETTIME: + if (!blinkON) { + y = max(y-1, MIN_COUNT); //but not less than the specified minimum + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + } + else if ((x==0 || x==1) && y==3) { + hour24=min(hour24+1, 23); + lcd.setCursor(0,y); + if (hour24<10) lcd.print("0"); + lcd.print(hour24); + } + else if ((x==3 || x==4) && y==3) { + min60=min(min60+1, 59); + lcd.setCursor(3,y); + if (min60<10) lcd.print("0"); + lcd.print(min60); + } + else if ((x==6 || x==7) && y==3) { + sec60=min(sec60+1, 59); + lcd.setCursor(6,y); + if (sec60<10) lcd.print("0"); + lcd.print(sec60); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RIGHT: //increment the counter + switch (MENU) { + case SETTIME: + x = min(x+1, MAX_COL); //MAX_COUNT); //but not more than the specified maximum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + + x = min(x+1, 5); + //Serial.println(x); + } + else if (CURSOR_POS % 2 ==0) CURSOR_POS=min(CURSOR_POS+2,10); + else CURSOR_POS=min(CURSOR_POS+2,9); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3) { + x = min(x+1, MAX_COL); //MAX_COUNT); + } + break; + + case CALIBRATION: + if (y==3) { + x = min(x+1,MAX_COL); + } + else x = 18; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case LEFT: //decrement the counter + switch (MENU) { + case SETTIME: + x = max(x-1, MIN_COUNT); //but not less than the specified minimum + //STATE = WAIT; + //Serial.print(x); Serial.print(","); Serial.println(y); + //lcd.setCursor(x,y); + break; + + case RALLY: + if (blinkON) { + x = max(x-1, MIN_COUNT); + } + else if (CURSOR_POS % 2 == 0) CURSOR_POS=max(CURSOR_POS-2,2); + else CURSOR_POS=max(CURSOR_POS-2,1); + if (!blinkON) set_cursor_pos(CURSOR_POS); + break; + + case CONSTANTA: + if (y==2 || y==3){ + x = max(x-1, 12); + } + break; + + case CALIBRATION: + if (y==3) { + x = max(x-1, 14); + } + else x = 18; + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case OKAY: + switch (MENU) { + case MAIN: + if (y==1) { + MENU = SETTIME; + //prevsettime += millis(); + //prevtempint+=millis(); + } + else if (y==0) { + MENU = RALLY; + //prevtemprally=millis(); + } + else if (y==2) MENU = CONSTANTA; + else if (y==3) { + MENU = CALIBRATION; + //prevcalibrationtime+=millis(); + } + break; + + case CONSTANTA: + if (y==0) MENU = MAIN; + //else if (!blinkON && y==1) { + + // } + else if (!blinkON && y==2) { + constantatodigit(); + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==3) { + sec60 = starttractsec; + min60 = starttractmin; + hour24 = starttracthour; + lcd.blink(); + blinkON=!blinkON; + } + else if (!blinkON && y==1) { + prevTrip = curTrip; + lcd.blink(); + blinkON = !blinkON; + } + else if (blinkON && y==1) { + curTrip = prevTrip; + constanta = Trip[curTrip].speed; + starttractsec = Trip[curTrip].startSec; + starttractmin = Trip[curTrip].startMin; + starttracthour = Trip[curTrip].startHour; + lcd.noBlink(); + blinkON=!blinkON; + constantaMenu(); + } + else if (blinkON && y==2) { + lcd.noBlink(); + blinkON=!blinkON; + constanta = (digit1*10)+digit2+(float)digit3/10+(float)digit4/100+(float)digit5/1000+(float)digit6/10000; //+(float)digit6/100000; + //mem.writeFloat(800, constanta); + + setMemSpeedInConstanta(constanta, curTrip); + // int pointeradd = ((TRIPADDRESS+curTrip)*32); + // mem.writeFloat(pointeradd, constanta); + // Trip[curTrip].speed = constanta; +#ifdef DEBUG + Serial.println(pointeradd); Serial.print(";");Serial.println(constanta,5); +#endif + } + else if (blinkON && y==3) { + starttractsec=sec60; + starttractmin=min60; + starttracthour=hour24; + unsigned long valuesettime = starttracthour; + valuesettime = valuesettime * 256 + starttractmin; // effectively shift the first byte 8 bit positions + valuesettime = valuesettime * 256 + starttractsec; + //mem.writeLong(768,valuesettime); + + setMemStime(valuesettime, curTrip); ///added for esp32 + // int pointeradd = ((TRIPADDRESS+curTrip)*32+4); + // mem.writeLong(pointeradd, valuesettime); + // Trip[curTrip].startHour = starttracthour; + // Trip[curTrip].startMin = starttractmin; + // Trip[curTrip].startSec = starttractsec; + lcd.noBlink(); + blinkON=!blinkON; +#ifdef DEBUG + Serial.println(pointeradd); Serial.println(valuesettime); +#endif + } + else {// if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + break; + + case RALLY: +#ifdef DEBUG + Serial.println("OKRALLY"); +#endif + switch(CURSOR_POS) + { + case 1: + count1 = 0; + backcount1 = 0; + time1 = VSSCount; + //Serial.println("case 1"); + break; + case 2: + count2 = 0; + backcount2 = 0; + time2 = VSSCount; + //Serial.println("case 2"); + break; + case 3: + count2 = count1; //no yet UNDO next update can UNDO + backcount2 = 0; + //time2 = VSSCount; + //Serial.println("case 3"); + break; + case 4: + count1 = count2; //no yet UNDO next update can UNDO + backcount1 = 0; + //time1 = VSSCount; + //Serial.println("case 4"); + break; + case 5: + //dirfwdcount1 = !dirfwdcount1; + switch (dircount1) + { + case FORWARD: + dircount1 = FREEZE; + break; + case FREEZE: + dircount1 = BACKWARD; + break; + case BACKWARD: + dircount1 = FORWARD; + break; + default: + dircount1 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 5"); + break; + case 6: + //dirfwdcount2 = !dirfwdcount2; + switch (dircount2) + { + case FORWARD: + dircount2 = FREEZE; + break; + case FREEZE: + dircount2 = BACKWARD; + break; + case BACKWARD: + dircount2 = FORWARD; + break; + default: + dircount2 = FORWARD; + break; + } + secondrallyMenu(); + //Serial.println("case 6"); + break; + case 7: + showTIME = !showTIME; + rallyMenu(); + break; + case 8: + showTIME = !showTIME; + rallyMenu(); + break; + case 9: + //Serial.println("case 9"); + MENU = MAIN; + lcd.noBlink(); + break; + case 10: + //Serial.println("case 10"); + MENU = MAIN; + lcd.noBlink(); + break; + + } + break; + + case CALIBRATION: + if (blinkON && y==1) { + lcd.noBlink(); + blinkON=!blinkON; + calibrationDistance = tempcalibdist; + } + else if (!blinkON && y==1) { + lcd.blink(); + blinkON=!blinkON; + tempcalibdist = calibrationDistance; + } + else if (!blinkON && y==2) { + //startCalibration = millis(); + Calibrationcount = 0; + startCalibration = VSSCount; + Calibrationtime = startCalibration; + blinkON=!blinkON; + lcd.blink(); + calibrationON=true; + lcd.setCursor(0,2); + lcd.print("Calibrating 00.000Km"); + } + else if (blinkON && y==2) { + Calibration = (VSSCount-startCalibration)/(float)calibrationDistance; + mem.writeLong(896, Calibration); //Save Calibration to memory + oneMeter=(millis()-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=((float)VSSCount-startCalibration)/(1000*(float)calibrationDistance);//*calibrationDistance); + oneMeter=(float)(Calibration)/1000*(float)calibrationDistance; + blinkON=!blinkON; + lcd.noBlink(); + calibrationON=false; + lcd.setCursor(0,2); + lcd.print("Start "); + lcd.setCursor(0,3); + lcd.print("1m="); + //Serial.print(startCalibration);Serial.print(";");Serial.print((millis()-startCalibration)/1000);Serial.print(";"); +#ifdef DEBUG + Serial.println(oneMeter,5); +#endif + lcd.print(oneMeter,3); + lcd.print(";"); + } + else if (!blinkON && y==3) { //not yet implemented + lcd.blink(); + blinkON=!blinkON; + calibdigit1 = (byte)(Calibration/10000); + calibdigit2 = (byte)((Calibration % 10000)/100); + calibdigit3 = Calibration % 100; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + } + else if (blinkON && y==3) { + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println(calibdigit1);Serial.println(calibdigit2);Serial.println(calibdigit3); + Calibration = ((long)calibdigit1*10000) + ((long)calibdigit2*100) + (calibdigit3); + //Serial.println(Calibration); + mem.writeLong(896, Calibration); + } + else if (y==0) MENU = MAIN; + break; + + case SETTIME: + if (blinkON && y==3) { + t.sec=sec60; + t.min=min60; + t.hour=hour24; + DS3231_set(t); + lcd.noBlink(); + blinkON=!blinkON; + //Serial.println("OKAY"); + } + else if (y==3) { + lcd.blink(); + blinkON=!blinkON; + } + else {//(blinkON) { + MENU = MAIN; + lcd.noBlink(); + } + break; + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case RALLYEDIT: + if ((CURSOR_POS == 1 || CURSOR_POS == 2) && !blinkON) { + rallyEdit = true; + blinkON = true; + lcd.blink(); + //if (distance<100) { + dist1digit1=((int)distance1%1000); + dist1digit2=(int)((distance1 - (int)distance1)*1000); + dist2digit1=((int)distance2%1000); + dist2digit2=(int)((distance2 - (int)distance2)*1000); + //} + /* + Serial.print(dist1digit1);Serial.println(dist1digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance1,3); + Serial.print(dist2digit1);Serial.println(dist2digit2); //Serial.print(dist1digit3); Serial.print(dist1digit4);Serial.println(dist1digit5);//Serial.println(digit6); + Serial.println(distance2,3); + */ + } + else if (blinkON) { //set the new distance to count + blinkON = false; + rallyEdit = false; + /* + Serial.println(count1); + Serial.println(distance1,5); + Serial.println(""); + */ + if (CURSOR_POS == 1) { + distance1 = dist1digit1 + (float)dist1digit2/1000; + count1 = (unsigned long)(distance1 * Calibration) + 5; + //distance1 = (float)count1/((float)Calibration); + }else if (CURSOR_POS == 2) { + distance2 = dist2digit1 + (float)dist2digit2/1000; + count2 = (unsigned long)(distance2 * Calibration) + 5; + //distance2 = (float)count2/((float)Calibration); + } + /* + Serial.println(count1); + Serial.println(distance1,3); + */ + set_cursor_pos(CURSOR_POS); + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + + case ESC: + switch (MENU) + { + case RALLY: + lcd.noBlink(); + MENU=MAIN; + if (rallyEdit) { + rallyEdit = false; + lcd.blink(); + MENU = RALLY; + set_cursor_pos(CURSOR_POS); + } + blinkON=false; + + break; + case SETTIME: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + //MENU=MAIN; + break; + case CONSTANTA: + //MENU=MAIN; + if (!blinkON) MENU = MAIN; + else constantaMenu(); + lcd.noBlink(); + blinkON=false; + break; + case CALIBRATION: + lcd.noBlink(); + if (!blinkON) MENU = MAIN; + blinkON=false; + calibrationON=false; + //MENU=MAIN; + break; + + } + STATE = WAIT; + lcd.setCursor(x,y); + break; + } + +//***************************************************************** +//*************************************** M E N U ***************** +// +// +// +//*************************************** M E N U ***************** +//***************************************************************** + + if (PREVMENU!=MENU) + { + switch (MENU) + { + case (MAIN): + mainMenu(); + break; + + case (RALLY): + lcd.clear(); + rallyMenu(); + rallyON=true; + //lcd.blink(); + CURSOR_POS=10; + set_cursor_pos(CURSOR_POS); + break; + + case (SETTIME): + lcd.clear(); + settimeMenu(); + sec60=t.sec; + min60=t.min; + hour24=t.hour; + lcd.setCursor(0,3); + lcdprint2digit(hour24); + lcd.print(":"); + lcdprint2digit(min60); + lcd.print(":"); + lcdprint2digit(sec60); + x=0; + y=2; + lcd.setCursor(x,y); + break; + + case (CALIBRATION): + calibrationMenu(); + break; + + case CONSTANTA: + sec60=starttractsec; + min60=starttractmin; + hour24=starttracthour; + x = 16; + y = 0; + constantaMenu(); + break; + + case (INPUTSUBTRAYEK): + break; + } + } + + if (MENU==RALLY) { + if (((now1 - prevtemprally) >= tempintervalrally) && !isloadingConst) { + //if ((long)(now1 - prevtemprally) >= 0) { + testLoadTime=millis(); + //rallyMenu(); + if (!rallyEdit) { + iscalculatingRally=true; + redrawrallyMenu(); //Distance is edited? + iscalculatingRally=false; + } + Serial.println(millis()-testLoadTime); + prevtemprally=now1; + //prevtemprally+=tempintervalrally; + } + } + + if (MENU==SETTIME) { + //if ((long)(now1 - prevtempint) >=0 ){ + if ((now1 - prevtempint) >=tempinterval ){ + temperature = DS3231_get_treg(); //Get temperature + dtostrf(temperature, 5, 1, tempF); + lcd.setCursor(9,1); + lcd.print(tempF); + lcd.print((char)223); + lcd.print("C "); + //prevtempint+=tempinterval; + prevtempint=now1; + lcd.setCursor(x,y); + //lcd.setCursor(15,0); + //lcd.print(now); + } + //if ((long)(now1- prevsettime) >=0 ){ //show SET TIME MENU + if ((now1 - prevsettime) >=intervalsettime ){ //show SET TIME MENU + DS3231_get(&t); //Get time + if (prevsec!=t.sec) { //will update the LCD every sec(as long as the t.sec is different) eventhough intervalseetime is 250ms + settimeMenu(); + prevsettime = now1; + //prevsettime += intervalsettime; + } + } + } + + if (MENU==CALIBRATION) { + if (calibrationON) { + if ((now1 - prevcalibrationtime) >= calibrationtimeinterval ) { + //if ((long)(now1 - prevcalibrationtime) >=0 ) { + redrawcalibrationMenu(); + char Calibrationstr[6]; + unsigned long calibtemp = VSSCount - startCalibration; + sprintf(Calibrationstr, "%06lu", calibtemp); + lcd.setCursor(14,3); + lcd.print(Calibrationstr); + lcd.setCursor(x,y); + prevcalibrationtime=now1; + //prevcalibrationtime+=calibrationtimeinterval; + } + } + } + + //if (((long)(millis()-startmillis)>=0) && MENU!=CALIBRATION) { + if ((now1-startmillis)>=500) { //&& MENU!=CALIBRATION && MENU!=MAIN) { + unsigned long VSSCountDiff = VSSCount - startVSSCount; + startVSSCount=VSSCount; + if ((VSSCountDiff == 0) && savedCount) { + intervalsavemillis = 4000000; + } + else if ((VSSCountDiff == 0) && !savedCount) { + saveCount(); + savedCount = !savedCount; + intervalsavemillis = 2000000; + } + else if (VSSCountDiff < 15) intervalsavemillis = 3000; + else if (VSSCountDiff < 70) intervalsavemillis = 60000; + else intervalsavemillis = 4000000; + if (VSSCountDiff > 0) savedCount = false; + if (MENU!=CALIBRATION && MENU!=MAIN && MENU!=CONSTANTA) { + lcd.setCursor(0,0); + if (VSSCountDiff==0) lcd.print("0"); + else if (VSSCountDiff <= 10) lcd.print("1"); + else if (VSSCountDiff <= 50) lcd.print("2"); + else if (VSSCountDiff <= 150) lcd.print("3"); + else if (VSSCountDiff <= 250) lcd.print("4"); + else if (VSSCountDiff <= 400) lcd.print("5"); + else if (VSSCountDiff <= 600) lcd.print("6"); + else if (VSSCountDiff <= 900) lcd.print("7"); + else if (VSSCountDiff <= 1200) lcd.print("8"); + else if (VSSCountDiff > 1200) lcd.print("9"); + + //lcd.print(VSSCountDiff); + //lcd.print(" "); + lcd.setCursor(x,y); + } + //startmillis+=400; + startmillis=now1; + + } + +/* + if (((millis() % 100)==0) && MENU!=CALIBRATION) { + lcd.setCursor(0,2); + lcd.print(VSSCount); + lcd.print(" "); + lcd.setCursor(x,y); + } +*/ + if ((millis()-updatecounttime)>=250) { + // if ((millis()-updatecounttime)>=250) { + updateCount(); + updatecounttime = millis(); + digitalWrite(simulatorPWMPin, !simstate); + simstate = !simstate; + // Serial.print(ledstate); Serial.print(";");Serial.println(simstate); + } + + if ((millis()-startsavemillis) > intervalsavemillis) { + saveCount(); + //startsavemillis += 3000; + startsavemillis = millis(); + } + + if ((millis()-broadcastwebsocket) > 333 && !isloadingConst && globalClientRally) { + broadcastwebsocket = millis(); + iscalculatingRally=true; + calculationRally(); + iscalculatingRally=false; + // Serial.println(getRallyJson); + // Serial.println(millis()-broadcastwebsocket); + ws.textAll(getRallyJson); + // char pingPong[] = "{\"ping\":1}"; + // ws.textAll(pingPong); + } + + if ((millis()-broadcastwebsocketcalib) > 499 && !isloadingConst && globalClientCalib) { + broadcastwebsocketcalib = millis(); + //calculationRally(); + redrawcalibrationMenuForESP32(); + // Serial.println(getCalibJson); + + wscal.textAll(getCalibJson); + + + // Serial.print("VSSCount="); Serial.println(VSSCount); + // Serial.print(ledstate); Serial.print(";");Serial.println(simstate); + } + if(!isloadingConst){ + for (int i=(REQUESTCOUNT-1); i>=0; i--){ + // for (int i=0; i #include #include -#else - #include - #include - #include - #include + +// #else +// #include +// #include +// #include +// #include #endif #include // #include @@ -92,9 +93,10 @@ bool gGotRequestConstHTML[REQUESTCOUNT]; #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif -#include +// #include #include #include +// #include #include //#define BUFF_MAX 128 @@ -151,8 +153,9 @@ const int lcdRows = 4; #define LED_BUILTIN 22 // LED built in pada ESP32 Lolin32 Lite // set LCD address, number of columns and rows // if you don't know your display address, run an I2C scanner sketch -LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows); // marcoschwartz. ujungnya jelek ->remark - +LiquidCrystal_I2C lcd(0x28, lcdColumns, lcdRows); // marcoschwartz. ujungnya jelek ->remark +LiquidCrystal_I2C lcd2(I2C_ADDR, lcdColumns, lcdRows); // marcoschwartz. ujungnya jelek ->remark +// LiquidCrystal_PCF8574 lcd(0.27); /*-----( Declare objects )-----*/ //LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin); @@ -2137,8 +2140,7 @@ void handleloadConst(AsyncWebServerRequest *request, JsonVariant &json) { } void setup() { -getCalibJson.reserve(512); -getRallyJson.reserve(512); + // // // @@ -2148,13 +2150,16 @@ getRallyJson.reserve(512); Serial.println("Starting Rally"); //#endif // pinMode(ledPin, OUTPUT); + uint32_t freqhx=100000; + // Wire.begin(15, 13, freqhx); //for lolin32lite sda=15; scl=13 pinMode(simulatorPWMPin,OUTPUT); pinMode(LED_BUILTIN, OUTPUT); pinMode(interruptPin, INPUT); //Pull down using resistor to ground attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); // attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING); // attachInterrupt(interruptPin, isr, FALLING); - Wire.begin(I2C_SDA, I2C_SCL); //for lolin32lite sda=15; scl=13 + // Wire.begin(I2C_SDA, I2C_SCL); //for lolin32lite sda=15; scl=13 + // Wire.begin(15, 13); //for lolin32lite sda=15; scl=13 // pinMode(UP_pin, INPUT_PULLUP); /// // pinMode(DOWN_pin, INPUT_PULLUP); /// // pinMode(LEFT_pin, INPUT_PULLUP); /// @@ -2168,7 +2173,7 @@ getRallyJson.reserve(512); btnOK.begin(); btnESC.begin(); //DS3231_init(DS3231_INTCN); - DS3231_init(DS3231_CONTROL_INTCN); + //memset(recv, 0, BUFF_MAX); #ifdef DEBUG Serial.println("GET time"); @@ -2193,36 +2198,47 @@ Trip[9].startSec = 58; // lcd.init(); // lcd.backlight(); -// lcd.begin(LCD_COLS, LCD_ROWS); -// lcd.setBacklight(0xff); -// Wire.setClock(400000L); // set i2c clock bit rate, if asked + // lcd.begin(20, 4); + // // if(lcd.begin(20, 4)) + // // { + // // // begin() failed so blink the onboard LED if possible + // // return; // this never returns + // // } + // lcd.setBacklight(0xff); + // // Wire.setClock(100000L); // set i2c clock bit rate, if asked -// lcd.print("i2c clock:"); -// lcd.setCursor(0,1); -// lcd.print(Wire.getClock()); -// lcd.print(" Hz"); -// delay(3000); + // lcd.print("i2c clock:"); + // lcd.setCursor(0,1); + // lcd.print(Wire.getClock()); + // lcd.print(" Hz"); + // delay(3000); //**************************LCD Setup******************************** - + delay(100); // lcd.begin (20,4); // initialize the lcd // lcd.init(); lcd.begin(); + lcd2.begin(); // Switch on the backlight /// lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE); lcd.backlight(); + lcd2.backlight(); /// lcd.setBacklight(LED_ON); + lcd2.print("hello rally"); + delay(3000); //***************************END LCD Setup******************************** + getCalibJson.reserve(512); +getRallyJson.reserve(512); #ifdef DEBUG Serial.println("Setting time"); #endif //char a[]="304022129022016"; - +DS3231_init(DS3231_CONTROL_INTCN); DS3231_get(&t); //Get time blinkON=false;