From 9d0841df998a601e95aa442f764af88f07ec4d9a Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Thu, 23 Dec 2021 22:42:19 +0100 Subject: [PATCH] =?UTF-8?q?=D1=82=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20=D0=BC?= =?UTF-8?q?=D0=BE=D0=B6=D0=BD=D0=BE=20=D0=B2=D1=8B=D0=B1=D0=B8=D1=80=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B8=D0=B7=20=D0=B4=D0=B2=D1=83=D1=85:=20?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BD=D0=B4=D0=B0=D1=80=D1=82=D0=BD=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B8=D0=BB=D0=B8=20=D0=B0=D1=81=D0=B8=D0=BD=D1=85?= =?UTF-8?q?=D1=80=D0=BE=D0=BD=D0=BD=D1=8B=D0=B9=20=D0=B2=D0=B5=D0=B1=20?= =?UTF-8?q?=D1=81=D0=B5=D1=80=D0=B2=D0=B5=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/{WebServer.h => AsyncWebServer.h} | 6 +- include/Const.h | 2 +- include/Global.h | 15 +- include/StandWebServer.h | 16 ++ include/main.h | 3 +- src/{WebServer.cpp => AsyncWebServer.cpp} | 8 +- src/Global.cpp | 7 +- src/StandWebServer.cpp | 183 ++++++++++++++++++++++ src/main.cpp | 16 +- 9 files changed, 241 insertions(+), 15 deletions(-) rename include/{WebServer.h => AsyncWebServer.h} (74%) create mode 100644 include/StandWebServer.h rename src/{WebServer.cpp => AsyncWebServer.cpp} (98%) create mode 100644 src/StandWebServer.cpp diff --git a/include/WebServer.h b/include/AsyncWebServer.h similarity index 74% rename from include/WebServer.h rename to include/AsyncWebServer.h index 87629cea..f6d31635 100644 --- a/include/WebServer.h +++ b/include/AsyncWebServer.h @@ -1,10 +1,10 @@ #pragma once #include "Global.h" -#ifdef ACYNC_WEB_SERVER +#ifdef ASYNC_WEB_SERVER extern AsyncWebSocket ws; extern AsyncEventSource events; -void webServerInit(); -void webSocketsInit(); +void asyncWebServerInit(); +void asyncWebSocketsInit(); void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len); #endif diff --git a/include/Const.h b/include/Const.h index 64313658..0c5b660b 100644 --- a/include/Const.h +++ b/include/Const.h @@ -4,7 +4,7 @@ #define JSON_BUFFER_SIZE 4096 -#define ACYNC_WEB_SERVER +//#define ASYNC_WEB_SERVER #define STANDARD_WEB_SERVER #ifdef esp8266_4mb diff --git a/include/Global.h b/include/Global.h index 563784d9..af561423 100644 --- a/include/Global.h +++ b/include/Global.h @@ -14,13 +14,19 @@ #endif #ifdef ESP8266 +#include #include #endif -#ifdef ACYNC_WEB_SERVER +#ifdef ASYNC_WEB_SERVER #include #endif +#ifdef STANDARD_WEB_SERVER +#include +#include +#endif + #include //внутренние глобальные директории проекта @@ -30,10 +36,15 @@ //глобальные объекты классов extern TickerScheduler ts; -#ifdef ACYNC_WEB_SERVER +#ifdef ASYNC_WEB_SERVER extern AsyncWebServer server; #endif +#ifdef STANDARD_WEB_SERVER +extern ESP8266WebServer HTTP; +extern ESP8266HTTPUpdateServer httpUpdater; +#endif + //глобальные переменные extern String settingsFlashJson; extern String paramsFlashJson; diff --git a/include/StandWebServer.h b/include/StandWebServer.h new file mode 100644 index 00000000..7d933446 --- /dev/null +++ b/include/StandWebServer.h @@ -0,0 +1,16 @@ +#pragma once +#include "Global.h" +#ifdef STANDARD_WEB_SERVER +extern void standWebServerInit(); + +extern void standWebServerFiles(); +extern bool handleFileRead(String path); +extern String getContentType(String filename); + +#ifdef RSET_FILE_OPERATIONS +extern void handleFileUpload(); +extern void handleFileDelete(); +extern void handleFileCreate(); +extern void handleFileList(); +#endif +#endif \ No newline at end of file diff --git a/include/main.h b/include/main.h index 5d31b3e9..14eccd4f 100644 --- a/include/main.h +++ b/include/main.h @@ -3,4 +3,5 @@ #include "Global.h" #include "Utils/Pretty.h" #include "Utils/WiFiUtils.h" -#include "WebServer.h" +#include "AsyncWebServer.h" +#include "StandWebServer.h" diff --git a/src/WebServer.cpp b/src/AsyncWebServer.cpp similarity index 98% rename from src/WebServer.cpp rename to src/AsyncWebServer.cpp index 9c86f775..48b77c60 100644 --- a/src/WebServer.cpp +++ b/src/AsyncWebServer.cpp @@ -1,9 +1,9 @@ -#include "WebServer.h" -#ifdef ACYNC_WEB_SERVER +#include "AsyncWebServer.h" +#ifdef ASYNC_WEB_SERVER AsyncWebSocket ws("/ws"); AsyncEventSource events("/events"); -void webServerInit() { +void asyncWebServerInit() { String login = jsonReadStr(settingsFlashJson, "weblogin"); String pass = jsonReadStr(settingsFlashJson, "webpass"); #ifdef ESP32 @@ -71,7 +71,7 @@ void webServerInit() { SerialPrint("i", F("WEB"), F("WebServer Init")); } -void webSocketsInit() { +void asyncWebSocketsInit() { ws.onEvent(onWsEvent); server.addHandler(&ws); events.onConnect([](AsyncEventSourceClient *client) { diff --git a/src/Global.cpp b/src/Global.cpp index faea78d3..59564de5 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -2,10 +2,15 @@ //глобальные объекты классов TickerScheduler ts(MYTEST + 1); -#ifdef ACYNC_WEB_SERVER +#ifdef ASYNC_WEB_SERVER AsyncWebServer server(80); #endif +#ifdef STANDARD_WEB_SERVER +ESP8266HTTPUpdateServer httpUpdater; +ESP8266WebServer HTTP(80); +#endif + //глобальные переменные String settingsFlashJson = "{}"; //переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью String paramsFlashJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти и синхронизированна с flash памятью diff --git a/src/StandWebServer.cpp b/src/StandWebServer.cpp new file mode 100644 index 00000000..3682eb38 --- /dev/null +++ b/src/StandWebServer.cpp @@ -0,0 +1,183 @@ +#include "StandWebServer.h" +#ifdef STANDARD_WEB_SERVER +void standWebServerInit() { + // Кэшировать файлы для быстрой работы + HTTP.serveStatic("/css/", FileFS, "/css/", "max-age=31536000"); // кеширование на 1 год + HTTP.serveStatic("/js/", FileFS, "/js/", "max-age=31536000"); // кеширование на 1 год + HTTP.serveStatic("/png/", FileFS, "/png/", "max-age=31536000"); // кеширование на 1 год + + HTTP.on("/settings.json", HTTP_GET, []() { + HTTP.send(200, "application/json", settingsFlashJson); + }); + + HTTP.on("/restart", HTTP_GET, []() { + // ESP.restart(); + HTTP.send(200, "text/plain", "ok"); + }); + + // Добавляем функцию Update для перезаписи прошивки по WiFi при 1М(256K FileFS) и выше + // httpUpdater.setup(&HTTP); + // Запускаем HTTP сервер + HTTP.begin(); +} + +File fsUploadFile; + +void standWebServerFiles() { +#ifdef RSET_FILE_OPERATIONS + SPIFFS.begin(); + { + Dir dir = SPIFFS.openDir("/"); + while (dir.next()) { + String fileName = dir.fileName(); + size_t fileSize = dir.fileSize(); + } + } + // HTTP страницы для работы с FFS + // list directory + HTTP.on("/list", HTTP_GET, handleFileList); + //загрузка редактора editor + HTTP.on("/edit", HTTP_GET, []() { + if (!handleFileRead("/edit.htm")) HTTP.send(404, "text/plain", "FileNotFound"); + }); + //Создание файла + HTTP.on("/edit", HTTP_PUT, handleFileCreate); + //Удаление файла + HTTP.on("/edit", HTTP_DELETE, handleFileDelete); + // first callback is called after the request has ended with all parsed arguments + // second callback handles file uploads at that location + HTTP.on( + "/edit", HTTP_POST, []() { + HTTP.send(200, "text/plain", ""); + }, + handleFileUpload); +#endif + // called when the url is not defined here + // use it to load content from SPIFFS + HTTP.onNotFound([]() { + if (!handleFileRead(HTTP.uri())) + HTTP.send(404, "text/plain", "FileNotFound"); + }); +} + +bool handleFileRead(String path) { + if (path.endsWith("/")) path += "index.html"; + String contentType = getContentType(path); + String pathWithGz = path + ".gz"; + if (FileFS.exists(pathWithGz) || FileFS.exists(path)) { + if (FileFS.exists(pathWithGz)) + path += ".gz"; + File file = FileFS.open(path, "r"); + size_t sent = HTTP.streamFile(file, contentType); + file.close(); + return true; + } + return false; +} + +String getContentType(String filename) { + if (HTTP.hasArg("download")) + return "application/octet-stream"; + else if (filename.endsWith(".htm")) + return "text/html"; + else if (filename.endsWith(".html")) + return "text/html"; + else if (filename.endsWith(".json")) + return "application/json"; + else if (filename.endsWith(".css")) + return "text/css"; + else if (filename.endsWith(".js")) + return "application/javascript"; + else if (filename.endsWith(".png")) + return "image/png"; + else if (filename.endsWith(".gif")) + return "image/gif"; + else if (filename.endsWith(".jpg")) + return "image/jpeg"; + else if (filename.endsWith(".ico")) + return "image/x-icon"; + else if (filename.endsWith(".xml")) + return "text/xml"; + else if (filename.endsWith(".pdf")) + return "application/x-pdf"; + else if (filename.endsWith(".zip")) + return "application/x-zip"; + else if (filename.endsWith(".gz")) + return "application/x-gzip"; + return "text/plain"; +} + +#ifdef RSET_FILE_OPERATIONS +// Здесь функции для работы с файловой системой +void handleFileUpload() { + if (HTTP.uri() != "/edit") return; + HTTPUpload& upload = HTTP.upload(); + if (upload.status == UPLOAD_FILE_START) { + String filename = upload.filename; + if (!filename.startsWith("/")) filename = "/" + filename; + fsUploadFile = FileFS.open(filename, "w"); + filename = String(); + } else if (upload.status == UPLOAD_FILE_WRITE) { + // Serial.print("handleFileUpload Data: "); Serial.println(upload.currentSize); + if (fsUploadFile) + fsUploadFile.write(upload.buf, upload.currentSize); + } else if (upload.status == UPLOAD_FILE_END) { + if (fsUploadFile) + fsUploadFile.close(); + } +} + +void handleFileDelete() { + if (HTTP.args() == 0) return HTTP.send(500, "text/plain", "BAD ARGS"); + String path = HTTP.arg(0); + if (path == "/") + return HTTP.send(500, "text/plain", "BAD PATH"); + if (!FileFS.exists(path)) + return HTTP.send(404, "text/plain", "FileNotFound"); + FileFS.remove(path); + HTTP.send(200, "text/plain", ""); + path = String(); +} + +void handleFileCreate() { + if (HTTP.args() == 0) + return HTTP.send(500, "text/plain", "BAD ARGS"); + String path = HTTP.arg(0); + if (path == "/") + return HTTP.send(500, "text/plain", "BAD PATH"); + if (FileFS.exists(path)) + return HTTP.send(500, "text/plain", "FILE EXISTS"); + File file = FileFS.open(path, "w"); + if (file) + file.close(); + else + return HTTP.send(500, "text/plain", "CREATE FAILED"); + HTTP.send(200, "text/plain", ""); + path = String(); +} + +void handleFileList() { + if (!HTTP.hasArg("dir")) { + HTTP.send(500, "text/plain", "BAD ARGS"); + return; + } + String path = HTTP.arg("dir"); + Dir dir = FileFS.openDir(path); + path = String(); + String output = "["; + while (dir.next()) { + File entry = dir.openFile("r"); + if (output != "[") output += ','; + bool isDir = false; + output += "{\"type\":\""; + output += (isDir) ? "dir" : "file"; + output += "\",\"name\":\""; + output += String(entry.name()).substring(1); + output += "\"}"; + entry.close(); + } + output += "]"; + HTTP.send(200, "text/json", output); +} +#endif +#endif diff --git a/src/main.cpp b/src/main.cpp index 63111c10..cea0af43 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -13,9 +13,15 @@ void setup() { globalVarsSync(); //инициализация асинхронного веб сервера и веб сокетов -#ifdef ACYNC_WEB_SERVER - webServerInit(); - webSocketsInit(); +#ifdef ASYNC_WEB_SERVER + asyncWebServerInit(); + asyncWebSocketsInit(); +#endif + +//инициализация стандартного веб сервера +#ifdef STANDARD_WEB_SERVER + standWebServerInit(); + standWebServerFiles(); #endif //подключаемся к роутеру @@ -38,4 +44,8 @@ void setup() { void loop() { //обновление задач таскера ts.update(); + +#ifdef STANDARD_WEB_SERVER + HTTP.handleClient(); +#endif }