/********* 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 #else #include #include #include #include #endif #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 password[] = "12345678901"; //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; void notFound(AsyncWebServerRequest *request) { request->send(404); } String readFile(fs::FS &fs, const char * path){ Serial.printf("Reading file: %s\r\n", path); File file = fs.open(path, "r"); if(!file || file.isDirectory()){ Serial.println("- empty file or failed to open file"); return String(); } Serial.print("- read from file:"); String fileContent; while(file.available()){ fileContent+=String((char)file.read()); } file.close(); Serial.println(fileContent); return fileContent; } void writeFile(fs::FS &fs, const char * path, const char * message){ Serial.printf("Writing file: %s\r\n", path); File file = fs.open(path, "w"); if(!file){ Serial.println("- failed to open file for writing"); return; } if(file.print(message)){ Serial.println("- file written"); } else { Serial.println("- write failed"); } file.close(); } // Replaces placeholder with stored values String processor(const String& var){ //Serial.println(var); Serial.print("Processor "); Serial.print(var); if(var == "inputString"){ return readFile(SPIFFS, "/inputString.txt"); } else if(var == "inputInt"){ return readFile(SPIFFS, "/inputInt.txt"); } else if(var == "inputFloat"){ return readFile(SPIFFS, "/inputFloat.txt"); } else 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(); } 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 time[9]; strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); strftime(time, 9, "%H:%M:%S", &timeinfo); //Serial.println(&timeinfo); //Serial.println(datetime); testdoc["pin36"]=242; testdoc["pin39"]=datetime; testdoc["time"]=time; // testdoc["datetime"]=datetime; testdoc["pin5"]=millis(); testdoc["curtime"]=time; 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"]=time; testdoc["time2"]=time; 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 time[9]; strftime(datetime, 21, "%d %b %Y %H:%M:%S", &timeinfo); strftime(time, 9, "%H:%M:%S", &timeinfo); //Serial.println(&timeinfo); //Serial.println(datetime); // testdoc["datetime"]=datetime; testdoc["curtime"]=time; 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; } 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){ for(byte i=0;iremoteIP()); client->text(getPin()); } else if(type == WS_EVT_DISCONNECT){ Serial.println("Client disconnected"); 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 ledstatus=doc["LED1"]; if (ledstatus=="null"){Serial.println("led1 is null");} Serial.print("LED1=");Serial.println(ledstatus); } } void onWsEvent2(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){ if(type == WS_EVT_CONNECT){ Serial.println("wscal Websocket client connection received"); Serial.print("IPAdd client:"); Serial.println(client->remoteIP()); client->text(getCalib()); } else if(type == WS_EVT_DISCONNECT){ Serial.println("wscal Client disconnected"); 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 setdis=doc["setdis"]; String setcal=doc["setcal"]; String calstart=doc["calstart"]; Serial.print("setdis=");Serial.println(setdis); Serial.print("setcal=");Serial.println(setcal); Serial.print("calstart=");Serial.println(calstart); if (setdis!="null"){ if (isDecimal(setdis)){ Serial.print("setdis=");Serial.println(setdis.toInt()); } } if (setcal!="null"){ if (isDecimal(setcal)){ Serial.print("setcal=");Serial.println(setcal.toInt()); } } if (calstart="null"){ if (isDecimal(calstart)){ if(calstart=="1"){ Serial.print("calstart=");Serial.println("START"); } else if(calstart=="0"){ } Serial.print("calstart=");Serial.println("STOP"); } } } } // void configModeCallback (WiFiManager *myWiFiManager) { // Serial.println("Entered config mode"); // Serial.println(WiFi.softAPIP()); // Serial.println(myWiFiManager->getConfigPortalSSID()); // } void setup() { 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); 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); } 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); } 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()); // 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; Serial.println("ini masuk /setwifi"); // GET inputString value on /get?inputString= //List all parameters int params = request->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()); } } if (request->hasParam(PARAM_SSID,true)) { Serial.println("hasparam ssid"); inputMessage = request->getParam(PARAM_SSID,true)->value(); //add true for POST method. no true for GET method 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,true)) { // add true for POST, no true for GET method Serial.println("hasparam pwd"); inputMessage = request->getParam(PARAM_PWD,true)->value(); // add true for POST 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); 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) { //PAGE.replace("%serveripaddress%", WiFi.localIP().toString()); request->send_P(200, "text/html", HTML_CALIBRATION, processor); }); ws.onEvent(onWsEvent); //add ws event wscal.onEvent(onWsEvent2); //add ws event server.addHandler(&ws); server.addHandler(&wscal); server.onNotFound(notFound); server.begin(); } void loop() { // // To access your stored values on inputString, inputInt, inputFloat // String yourInputString = readFile(SPIFFS, "/inputString.txt"); // Serial.print("*** Your inputString: "); // Serial.println(yourInputString); // int yourInputInt = readFile(SPIFFS, "/inputInt.txt").toInt(); // Serial.print("*** Your inputInt: "); // Serial.println(yourInputInt); // float yourInputFloat = readFile(SPIFFS, "/inputFloat.txt").toFloat(); // Serial.print("*** Your inputFloat: "); // Serial.println(yourInputFloat); // String yourSSIDString = readFile(SPIFFS, "/ssidString.txt"); // Serial.print("*** Your ssidString: "); // Serial.println(yourSSIDString); // String yourInputPwd = readFile(SPIFFS, "/inputPwd.txt"); // Serial.print("*** Your inputPwd: "); // Serial.println(yourInputPwd); // delay(10000); delay(10330); ws.textAll(getPin()); wscal.textAll(getCalib()); //printLocalTime(); }