/* 20190529-1 * * FS-rw * STA und AP Mode * * SimpleAuthentifikation * ESP8266WebServer * Beispiele für Generik ESP8266 Module * * 2.6 esptool.py v2.6 Serial port /dev/ttyUSB1 Connecting.... Chip is ESP8266EX Features: WiFi MAC: 84:0d:8e:b1:1f:1a * Board: "NodeMCU 1.0 (ESP-12E Module) * * */ #include #include // Include the Wi-Fi library #include #include // Include the Wi-Fi-Multi library #include // Include the mDNS library #include #include // Stationsmode (STA mode) #ifndef STASSID #define STASSID "Router" #define STAPSK "your-password" #endif // Accesspoint mode (AP mode) #ifndef AP1SSID #define AP1SSID "ESP-Access1" #define AP1PSK "your-password" #define AP1HOST "robisys1" #endif #ifndef AP2SSID #define AP2SSID "ESP-Access2" #define AP2PSK "your-password" #define AP2HOST "robisys2" #endif #ifndef AP3SSID #define AP3SSID "ESP-Access3" #define AP3PSK "your-password" #define AP3HOST "robisys3" #endif int incomingByte = 0; //for incoming serial data // static const uint8_t D4 = 2; //D4 Pin für den WPS Taster const char* filename1 = "/upload.html"; const char* filename2 = "/editor.html"; const char* filename3 = "/logfile.html"; const char* ssid = STASSID; const char* password = STAPSK; const char* ap1ssid = AP1SSID; const char* ap1password = AP1PSK; const char* ap2ssid = AP2SSID; const char* ap2password = AP2PSK; const char* ap3ssid = AP3SSID; const char* ap3password = AP3PSK; // STA Mode const bool stamode = true ; // AP mode if stamode=false //const bool stamode = false ; const char* LED1status= "Off"; String teststring = "1"; const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 0; const int daylightOffset_sec = 3600; char buffer[80]; //ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti' ESP8266WebServer server(80); File fsUploadFile; // a File object to temporarily store the received file String getContentType(String filename); // convert the file extension to the MIME type bool handleFileRead(String path); // send the right file to the client (if it exists) void handleFileUpload(); // upload a new file to the SPIFFS bool freeSpace(uint16_t const& printsize) { // Funktion um beim speichern in Logdateien zu prüfen ob noch genügend freier Platz verfügbar ist. FSInfo fs_info; SPIFFS.info(fs_info); // Füllt FSInfo Struktur mit Informationen über das Dateisystem //printf("Funktion: %s meldet in Zeile: %d FreeSpace: %s\n",__PRETTY_FUNCTION__,__LINE__,formatBytes(fs_info.totalBytes - (fs_info.usedBytes * 1.05)).c_str()); return (fs_info.totalBytes - (fs_info.usedBytes * 1.05) > printsize) ? true : false; } //Check if header is present and correct bool is_authenticated() { Serial.println("Enter is_authenticated"); if (server.hasHeader("Cookie")) { Serial.print("Found cookie: "); String cookie = server.header("Cookie"); Serial.println(cookie); if (cookie.indexOf("ESPSESSIONID=1") != -1) { Serial.println("Authentication Successful"); return true; } } Serial.println("Authentication Failed"); return false; } /* // File an Browser senden bool handleFileRead(String path){ Serial.println("handleFileRead: " + path); if(path.endsWith("/")) path += "index.html"; String contentType = StaticRequestHandler::getContentType(path); if(SPIFFS.exists(path)){ File file = SPIFFS.open(path, "r"); size_t sent = webserver.streamFile(file, contentType); file.close(); return true; } return false; } */ void printLocalTime() { //Serial.println("printLocalTime"); //String Printloctime ; time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,80," %d %B %Y %H:%M:%S ",timeinfo); //struct tm timeinfo; //time_t now = time(nullptr); Serial.println(buffer); //Serial.print(ctime(&now)); //Serial.print(&timeinfo, " %d %B %Y %H:%M:%S "); //Printloctime = buffer ; //return Printloctime; delay(1000); } String loglTime() { //Serial.println("printLocalTime"); String strbuffer; time_t rawtime; struct tm * timeinfo; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,80," %d %B %Y %H:%M:%S ",timeinfo); //struct tm timeinfo; //time_t now = time(nullptr); strbuffer = buffer; return strbuffer ; } void handle_testus() { if (!is_authenticated()) { server.sendHeader("Location", "/login"); server.sendHeader("Cache-Control", "no-cache"); server.send(301); return; } Serial.println("handle_testus: " ); // server.sendHeader("Location","/success.html"); // Redirect the client to the success page server.send(200,"text/html",SendHTML1(true) ); } String SendHTMLon (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" "; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode) {ptr += password;} {ptr +="

LED1 Status: On

LED1 Off\n";} {ptr +="

Weiter

testus \n";} ptr +="\n"; ptr +="\n"; return ptr; } String SendHTMLoff (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" "; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode) {ptr += password;} {ptr +="

LED1 Status: Off

LED1 On\n";} {ptr +="

Weiter

testus \n";} ptr +="\n"; ptr +="\n"; return ptr; } String SendHTMLwps (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" "; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode){ptr += password;} {ptr +="

WPS:

login \n";} {ptr +="

Weiter

testus \n";} ptr +="\n"; ptr +="\n"; return ptr; } String SendHTMLmoni (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" " ; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr += teststring; {ptr +="

Serieller Monitor Eingabe:

Semoni \n";} {ptr +="

Weiter

testus \n";} ptr +="\n"; ptr +="\n"; return ptr; } String SendHLP (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" " ; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode) {ptr += password;} {ptr +="

Weiter

testus \n";} {ptr +="

robisys

robisys \n";} // {ptr +="

Weiter robisys

\n";} {ptr +="

studi50m.de studi

\n";} {ptr +="

dl bsp FS-rw.ino dl

\n";} {ptr +="

Weiter

\n";} ptr +="\n"; ptr +="\n"; return ptr; } String Sendmod (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=" "; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode) {ptr += password;} {ptr +="

robisys

robisys \n";} {ptr +="

Weiter

testus \n";} {ptr +="

Weiter robisys

\n";} {ptr +="

Weiter studi50m.de

\n";} {ptr +="

Weiter dl bsp FS-rw.ino

\n";} {ptr +="

Weiter

\n";} ptr +="\n"; ptr +="\n"; return ptr; } String SendHTML1 (uint8_t){ String ptr = " \n"; ptr +="\n"; ptr +=""; ptr +="LED Control\n"; ptr +="\n"; ptr +="\n"; ptr +="\n"; ptr +="

ESP8266 Web Server

\n"; if(stamode) {ptr +="

Using Access Station (STA) Mode

\n";} else {ptr +="

Using Access Point (AP) Mode

\n";} ptr +="WiFi: "; ptr += ssid ; ptr += " "; if(!stamode) {ptr += password;} {ptr +="

Hilfeinformation

Help Me\n";} {ptr +="

LED Steuerung

LED1\n";} {ptr +="

editor

editor\n";} {ptr +="

upload

upload\n";} {ptr +="

runwps

runwps\n";} {ptr +="

Weiter

testus \n";} {ptr +="

Inhalt

spwrite \n";} {ptr +="

Anzeige /index.htm

read \n";} {ptr +="

logfile schreiben

logfile \n";} {ptr +="

logfile eintrag schreiben

logfile \n";} {ptr +="

logfile lesen

logfiler \n";} {ptr +="

Semonitor

semoni\n";} {ptr +="

WiFiReset

wifireset\n";} // {ptr +="

startwps

WPS \n";} {ptr +="

changemode

mode\n";} {ptr +="

Speicher formatieren

spform\n";} ptr +="\n"; ptr +="\n"; return ptr; } String getContentType(String filename) { // convert the file extension to the MIME type if (filename.endsWith(".html")) return "text/html"; else if (filename.endsWith(".css")) return "text/css"; else if (filename.endsWith(".js")) return "application/javascript"; else if (filename.endsWith(".ico")) return "image/x-icon"; else if (filename.endsWith(".gz")) return "application/x-gzip"; return "text/plain"; } bool handleFileRead(String path) { // send the right file to the client (if it exists) Serial.println("handleFileRead: " + path); if (path.endsWith("/")) path += "index.html"; // If a folder is requested, send the index file String contentType = getContentType(path); // Get the MIME type String pathWithGz = path + ".gz"; if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal if (SPIFFS.exists(pathWithGz)) // If there's a compressed version available path = pathWithGz; // Use the compressed verion File file = SPIFFS.open(path, "r"); // Open the file size_t sent = server.streamFile(file, contentType); // Send it to the client file.close(); // Close the file again Serial.println(String("\tSent file: ") + path); return true; } Serial.println(String("\tFile Not Found: ") + path); // If the file doesn't exist, return false return false; } void handleFileUpload(){ // upload a new file to the SPIFFS HTTPUpload& upload = server.upload(); if(upload.status == UPLOAD_FILE_START){ String filename = upload.filename; if(!filename.startsWith("/")) filename = "/"+filename; Serial.print("handleFileUpload Name: "); Serial.println(filename); fsUploadFile = SPIFFS.open(filename, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist) } else if(upload.status == UPLOAD_FILE_WRITE){ if(fsUploadFile) fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file } else if(upload.status == UPLOAD_FILE_END){ if(fsUploadFile) { // If the file was successfully created fsUploadFile.close(); // Close the file again Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize); server.sendHeader("Location","/success.html"); // Redirect the client to the success page server.send(303); } else { Serial.println("File upload failed"); server.send(500, "text/html; charset=utf-8", "500: couldn't create file"); } } } //login page, also called for disconnect void handleWiFIReset() { Serial.println("WiFi Reset"); Serial.println("failed to connect, we should reset as see if it connects"); // hardwareReset(); //WiFi.disconnect(); // WiFiManager.resetSettings(); // ESP.eraseConfig(); // ESP.reset(); // ESP.restart(); // ssid =WiFi.SSID().c_str(); // password = WiFi.psk().c_str(); Serial.print("WiFi.SSID: "); Serial.println(ssid ); Serial.print("WiFi.PSK: "); Serial.println(password); //WiFi.disconnect(); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); server.send(200, "text/html", SendHTML1(true)); } //login page, also called for disconnect void handleLogin() { String msg; if (server.hasHeader("Cookie")) { Serial.print("Found cookie: "); String cookie = server.header("Cookie"); Serial.println(cookie); } if (server.hasArg("DISCONNECT")) { Serial.println("Disconnection"); server.sendHeader("Location", "/login"); server.sendHeader("Cache-Control", "no-cache"); server.sendHeader("Set-Cookie", "ESPSESSIONID=0"); server.send(301); return; } if (server.hasArg("USERNAME") && server.hasArg("PASSWORD")) { if (server.arg("USERNAME") == "admin" && server.arg("PASSWORD") == "admin") { server.sendHeader("Location", "/"); server.sendHeader("Cache-Control", "no-cache"); server.sendHeader("Set-Cookie", "ESPSESSIONID=1"); server.send(301); Serial.println("Log in Successful"); return; } msg = "Wrong username/password! try again."; Serial.println("Log in Failed"); } String content = " "; content += " "; content += "
To log in, please use : admin/admin
"; content += "User:
"; content += "Password:
"; content += "
" + msg + "
"; content += "You also can go here"; server.send(200, "text/html", content); } //root page can be accessed only if authentication is ok void handleRoot() { Serial.println("Enter handleRoot"); String header; if (!is_authenticated()) { server.sendHeader("Location", "/login"); server.sendHeader("Cache-Control", "no-cache"); server.send(301); return; } String content = ""; content += " "; content+= "

hello, you successfully connected to esp8266!


"; if (server.hasHeader("User-Agent")) { content += "the user agent used is : " + server.header("User-Agent") + "

"; } content += "You can access this page until you disconnect"; {content +="

Weiter

testus \n";} server.send(200, "text/html", content); } //no need authentication void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } // server.send(404, "text/plain", message); server.send(404, "text/html; charset=utf-8", message); } //Startet die WPS Konfiguration bool startWPS() { Serial.println("WPS Konfiguration gestartet"); bool wpsSuccess = WiFi.beginWPSConfig(); if(wpsSuccess) { // Muss nicht immer erfolgreich heißen! Nach einem Timeout bist die SSID leer String newSSID = WiFi.SSID(); if(newSSID.length() > 0) { // Nur wenn eine SSID gefunden wurde waren wir erfolgreich Serial.printf("WPS fertig. Erfolgreich angemeldet an SSID '%s'\n", newSSID.c_str()); } else { wpsSuccess = false; } } return wpsSuccess; } //Startet die WPS Konfiguration void semonitor() { server.send(200, "text/html", SendHTMLmoni(true)); teststring=semoni(); String Logeintrag = loglTime(); Logeintrag +="Monitoreingabe: "; Logeintrag += teststring; if (!logfile(Logeintrag)) Serial.println(" no logfile Monitor"); } //Startet die WPS Konfiguration void runWPS() { Serial.println("runWPS"); Serial.println("Connected!"); Serial.println(WiFi.localIP()); Serial.println(WiFi.SSID()); Serial.println(WiFi.macAddress()); server.send(200, "text/html", SendHTMLwps(true)); String Logeintrag = loglTime(); Logeintrag +="runwps: "; if (!logfile(Logeintrag)) Serial.println(" no logfile runwps"); } void spiff_init() { //Initialize File System if(SPIFFS.begin()) { Serial.println("SPIFFS Initialisierung....OK"); } else { Serial.println("SPIFFS Initialisierung...Fehler!"); } } void spi_format() { Serial.println("spi_format"); if (!is_authenticated()) { server.sendHeader("Location", "/login"); server.sendHeader("Cache-Control", "no-cache"); server.send(301); return; } //Format File System if(SPIFFS.format()) { Serial.println("Datei-System formatiert"); } else { Serial.println("Datei-System formatiert Error"); } server.send(200, "text/html", SendHTML1(true)); } void spi_write() { Serial.println("spi_write"); //Erstellung einer neuen Datei und Beispielhaftes füllen der Datei //w=Öffnen mit Schreibzugtriff auf die Datei File f = SPIFFS.open(filename1, "w"); if (!f) { Serial.println("Oeffnen der Datei fehlgeschlagen"); } else { //Write data to file Serial.println("Schreibe Daten in die Datei"); //f.print("Dies ist Beispielinhalt...."); f.print(" ESP8266 SPIFFS File Upload "); f.print(" "); f.print(""); f.print("

ESP8266 SPIFFS File Upload

"); f.print("

Select a new file to upload to the ESP8266. Existing files will be replaced.

"); f.print("
"); f.print("
"); f.print(""); // f.print("...weiterer Text."); f.close(); //Schließen der Datei } server.send(200, "text/html", SendHTML1(true)); } void spi_weditor() { Serial.println("spi_weditor"); //Erstellung einer neuen Datei und Beispielhaftes füllen der Datei //w=Öffnen mit Schreibzugtriff auf die Datei File f = SPIFFS.open(filename2, "w"); if (!f) { Serial.println("Oeffnen der Datei fehlgeschlagen"); } else { //Write data to file Serial.println("Schreibe Daten in die Datei"); //f.print("Dies ist Beispielinhalt...."); // f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print("
Inhalt kann gedruckt werden
\n "); f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print(" \n "); f.print("
Text to Save:
Filename to Save As:
Select a File to Load:
\n "); f.print("
\n "); f.print(" \n "); f.close(); //Schließen der Datei } server.send(200, "text/html", SendHTML1(true)); } void spwrite() { spi_write(); spi_weditor(); // https://www.w3.org/International/questions/qa-html-encoding-declarations.de String Logeintrag = " "; if (!logfile(Logeintrag)) Serial.println(" no logfile "); } // */ void spi_read( ) { Serial.println("spi_read"); int i; //Lesen des Dateiinhaltes File f = SPIFFS.open(filename1, "r"); if (!f) { Serial.println("Oeffnen der Datei fehlgeschlagen"); } else { Serial.println("Lesen des Dateiinhaltes:"); //Data from file for(i=0;i 0) { // read the incoming byte: incomingByte = Serial.read(); // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); } if ( incomingByte == 10 ) { Serial.println("WPS mit Seriellem Monitor gestartet"); if(startWPS()) { Serial.println("Verbindung über WPS erfolgreich "); } else { Serial.println("*** Keine Verbindung über WPS herstellbar *** "); } } } */ configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); } else { //AP-Mode Serial.println("*** AP -Modus *** "); ssid =ap1ssid; password =ap1password; // AP mode WiFi.mode(WIFI_AP); WiFi.softAP (ssid,password); // Eingabe vom Seriellen Monitor abfragen //Serial.println("Eingabe vom Seriellem Monitor gestartet"); if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); // say what you got: Serial.print("I received: "); Serial.println(incomingByte, DEC); } if ( incomingByte == 10 ) { Serial.println("Eingabe vom Seriellem Monitor "); } } // AP-mode ende /* * WiFiMulti */ /* wifiMulti.addAP(ap1ssid, ap1password); // add Wi-Fi networks you want to connect to wifiMulti.addAP(ap2ssid, ap2password); wifiMulti.addAP(ap3ssid, ap3password); Serial.println("Connecting ..."); int i = 0; while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above delay(1000); Serial.print(++i); Serial.print(' '); } Serial.println('\n'); Serial.print("Connected to "); Serial.println(WiFi.SSID()); // Tell us what network we're connected to Serial.print("IP address:\t"); Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer if (!MDNS.begin("esp8266")) { // Start the mDNS responder for esp8266.local Serial.println("Error setting up MDNS responder!"); } */ // Server Anfragen abarbeiten server.on("/", handleRoot); server.on("/login", handleLogin); server.on("/inline", []() { server.send(200, "text/plain", "this works without need of authentication"); }); server.on("/upload", HTTP_GET, []() { // if the client requests the upload page if (!handleFileRead("/upload.html")) // send it if it exists server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error }); server.on("/upload", HTTP_POST, // if the client posts to the upload page [](){}, handleFileUpload // Receive and save the file ); server.on("/fsread", spi_read ); server.on("/wifireset", handleWiFIReset); server.on("/runwps", runWPS); server.on("/startwps", startWPS); server.on("/success.html", handle_success); server.on("/contact", handle_Contact ); server.on("/favicon.ico", handleFileR ); server.on("/contact", HTTP_GET, []() { // if the client requests the upload page if (!handleFileRead("/contact.html")) // send it if it exists server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error }); server.on("/testus", handle_testus ); // if the client requests the testus page server.on("/read", filelesen ); server.on("/logfile", logfileEintrag ); server.on("/logfile1", logfileEintrag1 ); server.on("/logfiler", logfiler); server.on("/semoni", semonitor); server.on("/spform", spi_format); server.on("/spwrite", spwrite ); server.on("/led1off",LED1Off ); server.on("/led1on", LED1On ); server.on("/help", HelpMe ); server.on("/editor",myeditor); server.on("/mode", changemode ); server.onNotFound(handleNotFound); //here the list of headers to be recorded const char * headerkeys[] = {"User-Agent", "Cookie"} ; size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); //ask server to track these headers server.collectHeaders(headerkeys, headerkeyssize); server.begin(); Serial.println("HTTP server started"); } /* * Loop * */ void loop(void) { server.handleClient(); }