From f146db165e1a63b861558e4ccdf186d6275f6fac Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <67171972+IoTManagerProject@users.noreply.github.com> Date: Sun, 4 Dec 2022 14:50:16 +0100 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=B8=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=B8=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=87=D0=B5=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/MqttClient.h | 6 +- include/WsServer.h | 2 +- include/classes/IoTItem.h | 6 +- src/MqttClient.cpp | 81 +++++---------------------- src/WsServer.cpp | 21 ++++--- src/classes/IoTItem.cpp | 17 ++---- src/modules/virtual/Loging/Loging.cpp | 1 + 7 files changed, 40 insertions(+), 94 deletions(-) diff --git a/include/MqttClient.h b/include/MqttClient.h index 17eb2255..99ed843f 100644 --- a/include/MqttClient.h +++ b/include/MqttClient.h @@ -18,17 +18,13 @@ void mqttSubscribe(); boolean publish(const String& topic, const String& data); boolean publishData(const String& topic, const String& data); boolean publishChartMqtt(const String& topic, const String& data); -boolean publishControl(String id, String topic, String state); boolean publishJsonMqtt(const String& topic, const String& json); boolean publishStatusMqtt(const String& topic, const String& data); boolean publishEvent(const String& topic, const String& data); -boolean publishInfo(const String& topic, const String& data); -boolean publishAnyJsonKeyMqtt(const String& topic, const String& key, const String& data); + bool publishChartFileToMqtt(String path, String id, int maxCount); void publishWidgets(); -void publishMainWidgetsValues(); -void publishSubWidgetsValues(); void mqttCallback(char* topic, uint8_t* payload, size_t length); void handleMqttStatus(bool send); diff --git a/include/WsServer.h b/include/WsServer.h index 89955c13..0fc6b884 100644 --- a/include/WsServer.h +++ b/include/WsServer.h @@ -14,7 +14,7 @@ extern void hexdump(const void* mem, uint32_t len, uint8_t cols); #endif void publishStatusWs(const String& topic, const String& data); -void publishChartWs(int num, String& path); +void publishJsonWs(const String& topic, String& json); void periodicWsSend(); void sendFileToWsByFrames(const String& filename, const String& header, const String& json, int client_id, size_t frameSize); diff --git a/include/classes/IoTItem.h b/include/classes/IoTItem.h index 5c61959c..e016f220 100644 --- a/include/classes/IoTItem.h +++ b/include/classes/IoTItem.h @@ -30,7 +30,6 @@ class IoTItem { bool isGlobal(); void sendSubWidgetsValues(String& id, String& json); - virtual void onMqttWsAppConnectEvent(); void setInterval(long interval); void setIntFromNet(int interval); @@ -52,11 +51,12 @@ class IoTItem { String getRoundValue(); void getNetEvent(String& event); - // хуки для системных событий + // хуки для системных событий (должны начинаться с "on") virtual void onRegEvent(IoTItem* item); virtual void onMqttRecive(String& topic, String& msg); + virtual void onMqttWsAppConnectEvent(); - //методы для графиков + //методы для графиков (будет упрощено) virtual void publishValue(); virtual void clearValue(); virtual void setPublishDestination(int type, int wsNum = -1); diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp index 5784ba15..75dec971 100644 --- a/src/MqttClient.cpp +++ b/src/MqttClient.cpp @@ -125,19 +125,26 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) { payloadStr += (char)payload[i]; } - // распространяем принятое сообщение через хуки + // генерация события прихода mqtt сообщения в модуле for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { (*it)->onMqttRecive(topicStr, payloadStr); } if (payloadStr.startsWith("HELLO")) { SerialPrint("i", F("MQTT"), F("Full update")); - publishWidgets(); - publishMainWidgetsValues(); - publishSubWidgetsValues(); - //обращение к логированию из ядра - //отправка данных графиков + //публикация всех виджетов + publishWidgets(); + + //публикация всех статус сообщений при подключении приложения и генерация события подключения приложения в модулях + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { + if ((*it)->iAmLocal) { + publishStatusMqtt((*it)->getID(), (*it)->getValue()); + (*it)->onMqttWsAppConnectEvent(); + } + } + + //отправка данных графиков - данный код будет оптимизирован после завершения написания приложения с новыми графиками for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { if ((*it)->getSubtype() == "Loging" || "LogingDaily") { (*it)->setPublishDestination(TO_MQTT); @@ -183,14 +190,6 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) { generateOrder(id, payloadStr); SerialPrint("i", F("=>MQTT"), "Received direct order " + id + " " + payloadStr); } - - // else if (topicStr.indexOf("info") != -1) { - // if (topicStr.indexOf("scen") != -1) { - // writeFile(String(DEVICE_SCENARIO_FILE), payloadStr); - // loadScenario(); - // SerialPrint("i", F("=>MQTT"), F("Scenario received")); - // } - //} } boolean publish(const String& topic, const String& data) { @@ -219,16 +218,6 @@ boolean publishChartMqtt(const String& topic, const String& data) { return true; } -boolean publishControl(String id, String topic, String state) { - String path = mqttPrefix + "/" + id + "/" + topic + "/control"; - return mqtt.publish(path.c_str(), state.c_str(), false); -} - -boolean publishJsonMqtt(const String& topic, const String& json) { - String path = mqttRootDevice + "/" + topic + "/status"; - return mqtt.publish(path.c_str(), json.c_str(), false); -} - boolean publishStatusMqtt(const String& topic, const String& data) { String path = mqttRootDevice + "/" + topic + "/status"; String json = "{}"; @@ -236,10 +225,8 @@ boolean publishStatusMqtt(const String& topic, const String& data) { return mqtt.publish(path.c_str(), json.c_str(), false); } -boolean publishAnyJsonKeyMqtt(const String& topic, const String& key, const String& data) { +boolean publishJsonMqtt(const String& topic, const String& json) { String path = mqttRootDevice + "/" + topic + "/status"; - String json = "{}"; - jsonWriteStr(json, key, data); return mqtt.publish(path.c_str(), json.c_str(), false); } @@ -248,11 +235,6 @@ boolean publishEvent(const String& topic, const String& data) { return mqtt.publish(path.c_str(), data.c_str(), false); } -boolean publishInfo(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/info"; - return mqtt.publish(path.c_str(), data.c_str(), false); -} - void publishWidgets() { auto file = seekFile("layout.json"); if (!file) { @@ -273,38 +255,6 @@ void publishWidgets() { file.close(); } -//устаревшая версия к удалению -// void publishMainWidgetsValues() { -// String json = getParamsJson(); -// SerialPrint("i", F("DATA"), json); -// json.replace("{", ""); -// json.replace("}", ""); -// json.replace("\"", ""); -// json += ","; -// while (json.length() != 0) { -// String tmp = selectToMarker(json, ","); -// String topic = selectToMarker(tmp, ":"); -// String state = deleteBeforeDelimiter(tmp, ":"); -// if (topic != "" && state != "") { -// publishStatusMqtt(topic, state); -// } -// json = deleteBeforeDelimiter(json, ","); -// } -//} - -//оптимизированная версия -void publishMainWidgetsValues() { - for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { - if ((*it)->iAmLocal) publishStatusMqtt((*it)->getID(), (*it)->getValue()); - } -} - -void publishSubWidgetsValues() { - for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { - if ((*it)->iAmLocal) (*it)->onMqttWsAppConnectEvent(); - } -} - bool publishChartFileToMqtt(String path, String id, int maxCount) { File configFile = FileFS.open(path, FILE_READ); if (!configFile) { @@ -325,7 +275,6 @@ void handleMqttStatus(bool send) { String stateStr = getStateStr(mqtt.state()); // Serial.println(stateStr); jsonWriteStr_(errorsHeapJson, F("mqtt"), stateStr); - if (!send) sendStringToWs("errors", errorsHeapJson, -1); } @@ -336,8 +285,6 @@ void handleMqttStatus(bool send, int state) { if (!send) sendStringToWs("errors", errorsHeapJson, -1); } -// log-20384820.txt - const String getStateStr(int e) { switch (e) { case -4: //Нет ответа от сервера diff --git a/src/WsServer.cpp b/src/WsServer.cpp index a3901634..9eec262a 100644 --- a/src/WsServer.cpp +++ b/src/WsServer.cpp @@ -54,21 +54,25 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) // Страница веб интерфейса dashboard //----------------------------------------------------------------------// - //отвечаем данными на запрос страницы + //публикация всех виджетов if (headerStr == "/|") { sendFileToWsByFrames("/layout.json", "layout", "", num, WEB_SOCKETS_FRAME_SIZE); } - //отвечаем на запрос параметров if (headerStr == "/params|") { + //публикация всех статус сообщений при подключении svelte приложения String params = "{}"; - // jsonWriteStr(params, "params_", ""); //метка для парсинга удалить for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { if ((*it)->getSubtype() != "Loging") { if ((*it)->iAmLocal) jsonWriteStr(params, (*it)->getID(), (*it)->getValue()); } } sendStringToWs("params", params, num); + + //генерация события подключения в модулях + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { + if ((*it)->iAmLocal) (*it)->onMqttWsAppConnectEvent(); + } } //отвечаем на запрос графиков @@ -261,7 +265,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) } } -//публикация статус сообщений (недостаток в том что делаем бродкаст всем клиентам поднятым в свелте!!!) +//публикация статус сообщений в ws (недостаток в том что делаем бродкаст всем клиентам поднятым в свелте!!!) void publishStatusWs(const String& topic, const String& data) { String path = mqttRootDevice + "/" + topic; String json = "{}"; @@ -270,8 +274,12 @@ void publishStatusWs(const String& topic, const String& data) { sendStringToWs("status", json, -1); } -void publishChartWs(int num, String& path) { - // sendFileToWs(path, num, 1000); +//публикация дополнительных json сообщений в ws +void publishJsonWs(const String& topic, String& json) { + String path = mqttRootDevice + "/" + topic; + jsonWriteStr(json, "topic", path); + // TO DO отправка полей в веб + // sendStringToWs("status", json, -1); } //данные которые мы отправляем в сокеты переодически @@ -375,7 +383,6 @@ void sendStringToWs(const String& header, String& payload, int client_id) { String msg = header + "|0012|" + payload; size_t totalSize = msg.length(); - // Serial.println("Send string '" + header + "', str size: " + String(totalSize)); char dataArray[totalSize]; msg.toCharArray(dataArray, totalSize + 1); diff --git a/src/classes/IoTItem.cpp b/src/classes/IoTItem.cpp index bd5a550f..f478291b 100644 --- a/src/classes/IoTItem.cpp +++ b/src/classes/IoTItem.cpp @@ -79,15 +79,13 @@ void IoTItem::setValue(const IoTValue& Value, bool genEvent) { } } -//метод отправки из модуля дополнительных json полей виджета в приложение и веб интерфейс, необходимый для изменения виджетов "на лету" из модуля +//метод отправки из модуля дополнительных json полей виджета в приложение и веб интерфейс, +//необходимый для изменения виджетов "на лету" из модуля void IoTItem::sendSubWidgetsValues(String& id, String& json) { publishJsonMqtt(id, json); - // to do publishJsonWs + publishJsonWs(id, json); } -//событие когда пользователь подключается приложением или веб интерфейсом к усройству -void IoTItem::onMqttWsAppConnectEvent() {} - //когда событие случилось void IoTItem::regEvent(const String& value, const String& consoleInfo, bool error, bool genEvent) { if (_needSave) { @@ -115,7 +113,6 @@ void IoTItem::regEvent(const String& value, const String& consoleInfo, bool erro publishEvent(_id, json); SerialPrint("i", F("<=MQTT"), "Broadcast event: " + json); } - //======================================================================== } } @@ -177,18 +174,16 @@ void IoTItem::checkIntFromNet() { } } +// хуки для системных событий (должны начинаться с "on") void IoTItem::onRegEvent(IoTItem* item) {} - void IoTItem::onMqttRecive(String& topic, String& msg) {} +void IoTItem::onMqttWsAppConnectEvent() {} +//методы для графиков (будет упрощено) void IoTItem::publishValue() {} - void IoTItem::clearValue() {} - void IoTItem::setPublishDestination(int publishType, int wsNum){}; - void IoTItem::clearHistory() {} - void IoTItem::setTodayDate() {} String IoTItem::getID() { diff --git a/src/modules/virtual/Loging/Loging.cpp b/src/modules/virtual/Loging/Loging.cpp index e6f0ff68..351211cb 100644 --- a/src/modules/virtual/Loging/Loging.cpp +++ b/src/modules/virtual/Loging/Loging.cpp @@ -104,6 +104,7 @@ class Loging : public IoTItem { //запускаем процедуру удаления старых файлов если память переполняется deleteLastFile(); } + void SetDoByInterval(String valse) { String value = valse; //если значение логгирования пустое