diff --git a/.gitignore b/.gitignore index 65bd8853..41f063ef 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,6 @@ .vscode/c_cpp_properties.json .vscode/launch.json .vscode/ipch +/myProfile_wm.json +/myProfile.json data_svelte/settings.json diff --git a/data_svelte/build/bundle.css.gz b/data_svelte/build/bundle.css.gz index 55b3f3ce..d1b51f45 100644 Binary files a/data_svelte/build/bundle.css.gz and b/data_svelte/build/bundle.css.gz differ diff --git a/data_svelte/build/bundle.js.gz b/data_svelte/build/bundle.js.gz index fe45ea11..982ec426 100644 Binary files a/data_svelte/build/bundle.js.gz and b/data_svelte/build/bundle.js.gz differ diff --git a/data_svelte/settings.json b/data_svelte/settings.json index f83115c2..affb351a 100644 --- a/data_svelte/settings.json +++ b/data_svelte/settings.json @@ -19,5 +19,6 @@ "pinSCL": 0, "pinSDA": 0, "i2cFreq": 100000, + "wg": "group1", "settings_": "" } \ No newline at end of file diff --git a/include/Const.h b/include/Const.h index 94a3a87d..a4e065b4 100644 --- a/include/Const.h +++ b/include/Const.h @@ -23,6 +23,8 @@ #define JSON_BUFFER_SIZE 2048 #define WEB_SOCKETS_FRAME_SIZE 2048 +//#define LOOP_DEBUG + //выбор сервера //#define ASYNC_WEB_SERVER //#define ASYNC_WEB_SOCKETS diff --git a/include/Global.h b/include/Global.h index 558ace8f..3f036530 100644 --- a/include/Global.h +++ b/include/Global.h @@ -137,6 +137,8 @@ extern Time_t _time_local; extern Time_t _time_utc; extern bool _time_isTrust; +extern unsigned long loopPeriod; + // extern DynamicJsonDocument settingsFlashJsonDoc; // extern DynamicJsonDocument paramsFlashJsonDoc; // extern DynamicJsonDocument paramsHeapJsonDoc; diff --git a/include/PeriodicTasks.h b/include/PeriodicTasks.h index eee9d1d5..c9a27a9e 100644 --- a/include/PeriodicTasks.h +++ b/include/PeriodicTasks.h @@ -10,8 +10,5 @@ extern void periodicTasksInit(); extern void printGlobalVarSize(); -extern void handleError(String errorId, String errorValue); -extern void handleError(String errorId, int errorValue); - extern String ESP_getResetReason(void); extern String ESP32GetResetReason(uint32_t cpu_no); \ No newline at end of file diff --git a/include/WsServer.h b/include/WsServer.h index ff08d671..89955c13 100644 --- a/include/WsServer.h +++ b/include/WsServer.h @@ -17,5 +17,5 @@ void publishStatusWs(const String& topic, const String& data); void publishChartWs(int num, String& path); void periodicWsSend(); -void sendFileToWsByFrames(const String& filename, const String& header, const String& json, uint8_t client_id, size_t frameSize); +void sendFileToWsByFrames(const String& filename, const String& header, const String& json, int client_id, size_t frameSize); void sendStringToWs(const String& header, String& payload, int client_id); \ No newline at end of file diff --git a/myProfile.json b/myProfile.json index b122eff2..f6656391 100644 --- a/myProfile.json +++ b/myProfile.json @@ -22,6 +22,7 @@ "pinSDA": 0, "i2cFreq": 100000, "settings_": "" + "wg": "group1" }, "projectProp": { "platformio": { diff --git a/platformio.ini b/platformio.ini index 40bf409e..4660c6a7 100644 --- a/platformio.ini +++ b/platformio.ini @@ -191,7 +191,7 @@ build_src_filter = [env:esp32_4mb_fromitems] lib_deps = - Adafruit AHTX0 + https://github.com/enjoyneering/AHTxx.git adafruit/Adafruit BME280 Library adafruit/Adafruit BMP280 Library beegee-tokyo/DHT sensor library for ESPx @@ -199,7 +199,6 @@ lib_deps = https://github.com/JonasGMorsch/GY-21.git ClosedCube HDC1080 adafruit/MAX6675 library - mandulaj/PZEM-004T-v30 rc-switch @ ^2.6.4 robtillaart/SHT2x@^0.1.1 WEMOS SHT3x@1.0.0 @@ -208,35 +207,37 @@ lib_deps = adafruit/Adafruit MCP23017 Arduino Library@^2.1.0 adafruit/Adafruit BusIO @ ^1.13.2 dfrobot/DFRobotDFPlayerMini @ ^1.0.5 + adafruit/Adafruit BusIO @ ^1.13.2 marcoschwartz/LiquidCrystal_I2C@^1.1.4 build_src_filter = - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/DeviceList.cpp b/src/DeviceList.cpp index d2f97724..9e5d99c2 100644 --- a/src/DeviceList.cpp +++ b/src/DeviceList.cpp @@ -2,7 +2,8 @@ const String getThisDevice() { String thisDevice = "{}"; - jsonWriteStr_(thisDevice, F("devicelist_"), ""); //метка для парсинга нужна для udp валидации может быть рабочей группой в последствии + jsonWriteStr_(thisDevice, F("devicelist_"), ""); //метка для парсинга + jsonWriteStr_(thisDevice, F("wg"), jsonReadStr(settingsFlashJson, F("wg"))); //рабочая группа jsonWriteStr_(thisDevice, F("ip"), jsonReadStr(settingsFlashJson, F("ip"))); jsonWriteStr_(thisDevice, F("id"), jsonReadStr(settingsFlashJson, F("id"))); jsonWriteStr_(thisDevice, F("name"), jsonReadStr(settingsFlashJson, F("name"))); @@ -52,7 +53,7 @@ void asyncUdpInit() { }); } - //будем отправлять каждые 30 секунд презентацию данного устройства + //будем отправлять каждые 60 секунд презентацию данного устройства ts.add( UDP, 60000, [&](void*) { // UDPP if (isNetworkActive()) { @@ -68,7 +69,9 @@ void asyncUdpInit() { } bool udpPacketValidation(String& data) { - if (data.indexOf("devicelist_") != -1) { + // SerialPrint("i", F("UDP"), data); + String workgroup = jsonReadStr(settingsFlashJson, "wg"); + if (workgroup != "" && data.indexOf(workgroup) != -1) { return true; } else { return false; diff --git a/src/EventsAndOrders.cpp b/src/EventsAndOrders.cpp index bb6db4a9..2af00a66 100644 --- a/src/EventsAndOrders.cpp +++ b/src/EventsAndOrders.cpp @@ -27,10 +27,6 @@ void handleOrder() { String id = selectToMarker(order, " "); - //это модификатор для даты графика - // if (id.endsWith("-date")) { - //} - //здесь нужно перебрать все методы execute всех векторов и выполнить те id которых совпали с id события IoTItem* item = findIoTItem(id); if (item) { diff --git a/src/Global.cpp b/src/Global.cpp index 5aa28dea..b05c868e 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -68,6 +68,8 @@ String mqttRootDevice = ""; unsigned long unixTime = 0; unsigned long unixTimeShort = 0; +unsigned long loopPeriod; + bool isTimeSynch = false; Time_t _time_local; Time_t _time_utc; diff --git a/src/Main.cpp b/src/Main.cpp index 16448d34..dce96513 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -116,38 +116,22 @@ void setup() { } void loop() { - // if(millis()%2000==0){ - // //watch->settimeUnix(time(&iotTimeNow)); - // Serial.println(watch->gettime("d-m-Y, H:i:s, M")); - // delay(1); - // } - - //обновление задач таскера - ts.update(); - -//отправка json -#ifdef QUEUE_FROM_STR - if (sendJsonFiles) sendJsonFiles->loop(); +#ifdef LOOP_DEBUG + unsigned long st = millis(); #endif + ts.update(); + #ifdef STANDARD_WEB_SERVER - //обработка web сервера 1 HTTP.handleClient(); #endif #ifdef STANDARD_WEB_SOCKETS - //обработка web сокетов standWebSocket.loop(); #endif - //обновление mqtt mqttLoop(); -#ifdef STANDARD_WEB_SERVER - //обработка web сервера 2 - // HTTP.handleClient(); -#endif - // передаем управление каждому элементу конфигурации для выполнения своих функций for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { (*it)->loop(); @@ -159,33 +143,43 @@ void loop() { } handleOrder(); - handleEvent(); -#ifdef STANDARD_WEB_SERVER - //обработка web сервера 3 - // HTTP.handleClient(); +#ifdef LOOP_DEBUG + loopPeriod = millis() - st; + if (loopPeriod > 2) Serial.println(loopPeriod); #endif - - // сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение) - // currentMillis = millis(); - // if (currentMillis - prevMillis >= 1000) { - // prevMillis = millis(); - // volStrForSave = ""; - // for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { - // if ((*it)->needSave) { - // (*it)->needSave = false; - // volStrForSave = volStrForSave + (*it)->getID() + "=" + (*it)->getValue() + ";"; - // } - // } - // - // if (volStrForSave != "") { - // Serial.print("volStrForSave: "); - // Serial.println(volStrForSave.c_str()); - // } - //} } +//отправка json +//#ifdef QUEUE_FROM_STR +// if (sendJsonFiles) sendJsonFiles->loop(); +//#endif + +// if(millis()%2000==0){ +// //watch->settimeUnix(time(&iotTimeNow)); +// Serial.println(watch->gettime("d-m-Y, H:i:s, M")); +// delay(1); +// } + +// сохраняем значения IoTItems в файл каждую секунду, если были изменения (установлены маркеры на сохранение) +// currentMillis = millis(); +// if (currentMillis - prevMillis >= 1000) { +// prevMillis = millis(); +// volStrForSave = ""; +// for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { +// if ((*it)->needSave) { +// (*it)->needSave = false; +// volStrForSave = volStrForSave + (*it)->getID() + "=" + (*it)->getValue() + ";"; +// } +// } +// +// if (volStrForSave != "") { +// Serial.print("volStrForSave: "); +// Serial.println(volStrForSave.c_str()); +// } +//} + // File dir = FileFS.open("/", "r"); // String out; // printDirectory(dir, out); diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp index 7fa2c7ef..90691b43 100644 --- a/src/MqttClient.cpp +++ b/src/MqttClient.cpp @@ -278,7 +278,7 @@ void publishWidgets() { DeserializationError error = deserializeJson(doc, file); if (error) { SerialPrint("E", F("MQTT"), error.f_str()); - handleError("jse3", 1); + jsonWriteInt(errorsHeapJson, F("jse3"), 1); //Ошибка чтения json файла с виджетами при отправки в mqtt } JsonArray arr = doc.as(); for (JsonVariant value : arr) { diff --git a/src/NTP.cpp b/src/NTP.cpp index 495ff9d2..e2f83178 100644 --- a/src/NTP.cpp +++ b/src/NTP.cpp @@ -13,9 +13,11 @@ void ntpInit() { if (unixTime < MIN_DATETIME) { isTimeSynch = false; // SerialPrint("E", "NTP", "Time not synched"); + jsonWriteInt(errorsHeapJson, F("tme1"), 1); synchTime(); return; } + jsonWriteInt(errorsHeapJson, F("tme1"), 0); breakEpochToTime(unixTime + jsonReadInt(settingsFlashJson, F("timezone")) * 60 * 60, _time_local); breakEpochToTime(unixTime, _time_utc); isTimeSynch = true; diff --git a/src/PeriodicTasks.cpp b/src/PeriodicTasks.cpp index 9885aafc..e44f5ecc 100644 --- a/src/PeriodicTasks.cpp +++ b/src/PeriodicTasks.cpp @@ -31,14 +31,6 @@ void periodicTasksInit() { SerialPrint("i", "Task", "Periodic tasks init"); } -void handleError(String errorId, String errorValue) { - jsonWriteStr_(errorsHeapJson, errorId, errorValue); -} - -void handleError(String errorId, int errorValue) { - jsonWriteInt_(errorsHeapJson, errorId, errorValue); -} - void printGlobalVarSize() { size_t settingsFlashJsonSize = settingsFlashJson.length(); // SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize)); diff --git a/src/WsServer.cpp b/src/WsServer.cpp index b6f03380..e2bde5f7 100644 --- a/src/WsServer.cpp +++ b/src/WsServer.cpp @@ -134,23 +134,23 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) if (headerStr == "/sgnittes|") { writeUint8tToString(payload, length, headerLenth, settingsFlashJson); writeFileUint8tByFrames("settings.json", payload, length, headerLenth, 256); - standWebSocket.sendTXT(num, errorsHeapJson); + sendStringToWs("errors", errorsHeapJson, num); addThisDeviceToList(); } //обработка кнопки сохранить настройки mqtt if (headerStr == "/mqtt|") { - standWebSocket.sendTXT(num, settingsFlashJson); //отправляем в ответ новые полученные настройки - handleMqttStatus(false, 8); //меняем статус на неопределенный - mqttReconnect(); //начинаем переподключение - standWebSocket.sendTXT(num, errorsHeapJson); //отправляем что статус неопределен - standWebSocket.sendTXT(num, ssidListHeapJson); + sendStringToWs("settin", settingsFlashJson, num); //отправляем в ответ новые полученные настройки + handleMqttStatus(false, 8); //меняем статус на неопределенный + mqttReconnect(); //начинаем переподключение + sendStringToWs("errors", errorsHeapJson, num); //отправляем что статус неопределен + sendStringToWs("ssidli", ssidListHeapJson, num); } //запуск асинхронного сканирования wifi сетей при нажатии выпадающего списка if (headerStr == "/scan|") { RouterFind(jsonReadStr(settingsFlashJson, F("routerssid"))); - standWebSocket.sendTXT(num, ssidListHeapJson); + sendStringToWs("ssidli", ssidListHeapJson, num); } //----------------------------------------------------------------------// @@ -176,10 +176,14 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) // Страница веб интерфейса dev //----------------------------------------------------------------------// if (headerStr == "/dev|") { - // standWebSocket.sendTXT(num, errorsHeapJson); - // standWebSocket.sendTXT(num, settingsFlashJson); - // sendFileToWs("/config.json", num, 1024); - // sendFileToWs("/items.json", num, 1024); + sendStringToWs("errors", errorsHeapJson, num); + sendStringToWs("settin", settingsFlashJson, num); + sendFileToWsByFrames("/config.json", "config", "", num, WEB_SOCKETS_FRAME_SIZE); + sendFileToWsByFrames("/items.json", "itemsj", "", num, WEB_SOCKETS_FRAME_SIZE); + // sendFileToWsByFrames("/layout.json", "layout", "", num, WEB_SOCKETS_FRAME_SIZE); + } + + if (headerStr == "/test|") { } //----------------------------------------------------------------------// @@ -216,8 +220,10 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) SerialPrint("i", F("=>WS"), "Msg from svelte web, WS No: " + String(num) + ", msg: " + msg); } - if (headerStr == "/test|") { + if (headerStr == "/tst|") { + standWebSocket.sendTXT(num, "/tstr|"); } + } break; case WStype_BIN: { @@ -292,7 +298,7 @@ void hexdump(const void* mem, uint32_t len, uint8_t cols = 16) { #endif #endif -void sendFileToWsByFrames(const String& filename, const String& header, const String& json, uint8_t client_id, size_t frameSize) { +void sendFileToWsByFrames(const String& filename, const String& header, const String& json, int client_id, size_t frameSize) { if (header.length() != 6) { SerialPrint("E", "FS", F("wrong header size")); return; @@ -305,8 +311,8 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St return; } - // size_t totalSize = file.size(); - // Serial.println("Send file '" + String(filename) + "', file size: " + String(totalSize)); + size_t totalSize = file.size(); + // Serial.println("Send file '" + String(filename) + "', file size: " + String(totalSize)); char buf[32]; sprintf(buf, "%04d", json.length() + 12); @@ -346,9 +352,11 @@ void sendFileToWsByFrames(const String& filename, const String& header, const St continuation = true; } - // Serial.println(String(i) + ") fr sz: " + String(size) + " fin: " + String(fin) + " cnt: " + String(continuation)); + // Serial.println(String(i) + ") " + "ws: " + String(client_id) + " fr sz: " + String(size) + " fin: " + String(fin) + " cnt: " + String(continuation)); + if (client_id == -1) { standWebSocket.broadcastBIN(frameBuf, size, fin, continuation); + } else { standWebSocket.sendBIN(client_id, frameBuf, size, fin, continuation); } diff --git a/src/utils/JsonUtils.cpp b/src/utils/JsonUtils.cpp index f6da97af..141bd8e6 100644 --- a/src/utils/JsonUtils.cpp +++ b/src/utils/JsonUtils.cpp @@ -318,8 +318,9 @@ String jsonWriteFloat(String& json, String name, float value, bool e) { } void jsonErrorDetected() { - jsonWriteInt(errorsHeapJson, F("jse2"), 1); - int number = jsonReadInt(errorsHeapJson, F("jse2n")); - number++; - jsonWriteInt(errorsHeapJson, F("jse2n"), number); + // пример как отправить ошибку с количеством + // jsonWriteInt(errorsHeapJson, F("jse2"), 1); + // int number = jsonReadInt(errorsHeapJson, F("jse2n")); + // number++; + // jsonWriteInt(errorsHeapJson, F("jse2n"), number); } \ No newline at end of file