From 875f5009c2f3d260c5c823e52daee7ba0fda5994 Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Fri, 24 Dec 2021 22:49:06 +0100 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D1=8B=D0=B5=20json=20=D1=83=D1=82=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D1=82=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/AsyncWebServer.h | 5 ++++- include/Const.h | 10 +++------ include/Global.h | 7 +++++-- include/StandWebServer.h | 4 +--- include/utils/JsonUtils.h | 31 ++++++++++++++------------- src/AsyncWebServer.cpp | 8 +++++-- src/Global.cpp | 6 +++++- src/StandWebServer.cpp | 10 ++++----- src/main.cpp | 13 ++++++------ src/utils/JsonUtils.cpp | 44 ++++++++++++++++++++++++--------------- 10 files changed, 79 insertions(+), 59 deletions(-) diff --git a/include/AsyncWebServer.h b/include/AsyncWebServer.h index f3fcb8f3..e85599d5 100644 --- a/include/AsyncWebServer.h +++ b/include/AsyncWebServer.h @@ -1,9 +1,12 @@ #pragma once #include "Global.h" #ifdef ASYNC_WEB_SERVER +void asyncWebServerInit(); +#endif + +#ifdef ASYNC_WEB_SOCKETS extern AsyncWebSocket ws; extern AsyncEventSource events; -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 2a106df1..a328f30b 100644 --- a/include/Const.h +++ b/include/Const.h @@ -4,17 +4,13 @@ #define FIRMWARE_VERSION 400 //Размер буфера json -#define JSON_BUFFER_SIZE 4096 +#define JSON_BUFFER_SIZE 1024 -//выбор сервера (или асинхронный, или обычный) +//выбор сервера //#define ASYNC_WEB_SERVER +//#define ASYNC_WEB_SOCKETS #define STANDARD_WEB_SERVER - -//если мы используем стандартный веб сервер то нужна библиотека веб сокетов -//если асинхронный то плагин сокетов включен в него -#ifdef STANDARD_WEB_SERVER #define STANDARD_WEB_SOCKETS -#endif #ifdef esp8266_4mb #define USE_LITTLEFS true diff --git a/include/Global.h b/include/Global.h index cc6e5fc3..c051cdba 100644 --- a/include/Global.h +++ b/include/Global.h @@ -11,7 +11,6 @@ #include "WiFi.h" #include #include - #endif #ifdef ESP8266 @@ -76,4 +75,8 @@ extern WebSocketsServer standWebSocket; **********************************************************************************************************************/ extern String settingsFlashJson; extern String paramsFlashJson; -extern String paramsHeapJson; \ No newline at end of file +extern String paramsHeapJson; + +extern DynamicJsonDocument settingsFlashJsonDoc; +extern DynamicJsonDocument paramsFlashJsonDoc; +extern DynamicJsonDocument paramsHeapJsonDoc; \ No newline at end of file diff --git a/include/StandWebServer.h b/include/StandWebServer.h index 9ff24627..917a19ae 100644 --- a/include/StandWebServer.h +++ b/include/StandWebServer.h @@ -1,13 +1,11 @@ #pragma once #include "Global.h" #include "Web.h" + #ifdef STANDARD_WEB_SERVER extern void standWebServerInit(); - -extern void standWebServerFiles(); extern bool handleFileRead(String path); extern String getContentType(String filename); - #ifdef REST_FILE_OPERATIONS extern void handleFileUpload(); extern void handleFileDelete(); diff --git a/include/utils/JsonUtils.h b/include/utils/JsonUtils.h index 0f78276e..9053ab41 100644 --- a/include/utils/JsonUtils.h +++ b/include/utils/JsonUtils.h @@ -2,20 +2,23 @@ #include "Global.h" -String jsonReadStr(String& json, String name); -int jsonReadInt(String& json, String name); -boolean jsonReadBool(String& json, String name); +extern String jsonReadStrDoc(DynamicJsonDocument& doc, String name); +extern void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String value); -String jsonWriteStr(String& json, String name, String value); -String jsonWriteInt(String& json, String name, int value); -String jsonWriteFloat(String& json, String name, float value); -String jsonWriteBool(String& json, String name, boolean value); +extern String jsonWriteStr(String& json, String name, String value); +extern String jsonWriteInt(String& json, String name, int value); +extern String jsonWriteFloat(String& json, String name, float value); +extern String jsonWriteBool(String& json, String name, boolean value); -bool jsonRead(String& json, String key, String& value); -bool jsonRead(String& json, String key, bool& value); -bool jsonRead(String& json, String key, int& value); +extern bool jsonRead(String& json, String key, String& value); +extern bool jsonRead(String& json, String key, bool& value); +extern bool jsonRead(String& json, String key, int& value); -bool jsonWriteStr_(String& json, String name, String value); -bool jsonWriteBool_(String& json, String name, bool value); -bool jsonWriteInt_(String& json, String name, int value); -bool jsonWriteFloat_(String& json, String name, float value); +extern String jsonReadStr(String& json, String name); +extern int jsonReadInt(String& json, String name); +extern boolean jsonReadBool(String& json, String name); + +extern bool jsonWriteStr_(String& json, String name, String value); +extern bool jsonWriteBool_(String& json, String name, bool value); +extern bool jsonWriteInt_(String& json, String name, int value); +extern bool jsonWriteFloat_(String& json, String name, float value); diff --git a/src/AsyncWebServer.cpp b/src/AsyncWebServer.cpp index 48b77c60..6e4522c4 100644 --- a/src/AsyncWebServer.cpp +++ b/src/AsyncWebServer.cpp @@ -1,7 +1,5 @@ #include "AsyncWebServer.h" #ifdef ASYNC_WEB_SERVER -AsyncWebSocket ws("/ws"); -AsyncEventSource events("/events"); void asyncWebServerInit() { String login = jsonReadStr(settingsFlashJson, "weblogin"); @@ -70,6 +68,12 @@ void asyncWebServerInit() { SerialPrint("i", F("WEB"), F("WebServer Init")); } +#endif + +#ifdef ASYNC_WEB_SOCKETS + +AsyncWebSocket ws("/ws"); +AsyncEventSource events("/events"); void asyncWebSocketsInit() { ws.onEvent(onWsEvent); diff --git a/src/Global.cpp b/src/Global.cpp index b43c1978..c92b9564 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -30,4 +30,8 @@ WebSocketsServer standWebSocket = WebSocketsServer(81); String settingsFlashJson = "{}"; //переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью String paramsFlashJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти и синхронизированна с flash памятью -String paramsHeapJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти только \ No newline at end of file +String paramsHeapJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти только + +DynamicJsonDocument settingsFlashJsonDoc(JSON_BUFFER_SIZE); +DynamicJsonDocument paramsFlashJsonDoc(JSON_BUFFER_SIZE); +DynamicJsonDocument paramsHeapJsonDoc(JSON_BUFFER_SIZE); \ No newline at end of file diff --git a/src/StandWebServer.cpp b/src/StandWebServer.cpp index 7e1906c5..0a3b28e1 100644 --- a/src/StandWebServer.cpp +++ b/src/StandWebServer.cpp @@ -1,5 +1,8 @@ #include "StandWebServer.h" #ifdef STANDARD_WEB_SERVER + +File fsUploadFile; + void standWebServerInit() { // Кэшировать файлы для быстрой работы HTTP.serveStatic("/css/", FileFS, "/css/", "max-age=31536000"); // кеширование на 1 год @@ -19,11 +22,7 @@ void standWebServerInit() { // httpUpdater.setup(&HTTP); // Запускаем HTTP сервер HTTP.begin(); -} -File fsUploadFile; - -void standWebServerFiles() { #ifdef REST_FILE_OPERATIONS SPIFFS.begin(); { @@ -224,7 +223,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) case WStype_BIN: { Serial.printf("[%u] get binary length: %u\n", num, length); - //hexdump(payload, length); + // hexdump(payload, length); // send message to client // standWebSocket.sendBIN(num, payload, length); @@ -246,5 +245,4 @@ void hexdump(const void* mem, uint32_t len, uint8_t cols = 16) { Serial.printf("\n"); } #endif - #endif diff --git a/src/main.cpp b/src/main.cpp index 2b70598a..4db51cad 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,25 +12,26 @@ void setup() { //синхронизация глобальных переменных с flash globalVarsSync(); + //подключаемся к роутеру + routerConnect(); + //инициализация асинхронного веб сервера и веб сокетов #ifdef ASYNC_WEB_SERVER asyncWebServerInit(); +#endif +#ifdef ASYNC_WEB_SOCKETS asyncWebSocketsInit(); #endif -//инициализация стандартного веб сервера +//инициализация стандартного веб сервера и веб сокетов #ifdef STANDARD_WEB_SERVER standWebServerInit(); - standWebServerFiles(); #endif - #ifdef STANDARD_WEB_SOCKETS standWebSocketsInit(); #endif - //подключаемся к роутеру - routerConnect(); - + //создаем объект класса выгружающего json массив из файла myStreamJsonArray = new StreamJsonArray; //выводим остаток оперативной памяти после старта diff --git a/src/utils/JsonUtils.cpp b/src/utils/JsonUtils.cpp index 8306a4b9..fad4e814 100644 --- a/src/utils/JsonUtils.cpp +++ b/src/utils/JsonUtils.cpp @@ -2,26 +2,13 @@ #include "Utils/FileUtils.h" -// depricated====================================================================== -String jsonReadStr(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); +//================================================================================ +String jsonReadStrDoc(DynamicJsonDocument& doc, String name) { return doc[name].as(); } -boolean jsonReadBool(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); - return doc[name].as(); -} - -int jsonReadInt(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); - return doc[name].as(); +void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String value) { + doc[name] = value; } // new============================================================================== @@ -69,6 +56,29 @@ bool jsonRead(String& json, String key, int& value) { value = doc[key].as(); return ret; } + +// depricated====================================================================== +String jsonReadStr(String& json, String name) { + DynamicJsonDocument doc(JSON_BUFFER_SIZE); + DeserializationError error = deserializeJson(doc, json); + if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); + return doc[name].as(); +} + +boolean jsonReadBool(String& json, String name) { + DynamicJsonDocument doc(JSON_BUFFER_SIZE); + DeserializationError error = deserializeJson(doc, json); + if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); + return doc[name].as(); +} + +int jsonReadInt(String& json, String name) { + DynamicJsonDocument doc(JSON_BUFFER_SIZE); + DeserializationError error = deserializeJson(doc, json); + if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); + return doc[name].as(); +} + // depricated======================================================================== String jsonWriteStr(String& json, String name, String value) { DynamicJsonDocument doc(JSON_BUFFER_SIZE);