diff --git a/include/Clock.h b/include/Clock.h index d2be007c..5ca2cbfe 100644 --- a/include/Clock.h +++ b/include/Clock.h @@ -152,8 +152,7 @@ class Clock { return String(buf); } - /* - /* + /* * Локальное время "чч:мм:cc" */ const String getTime() { diff --git a/include/Consts.h b/include/Consts.h index ac42d222..644c1411 100644 --- a/include/Consts.h +++ b/include/Consts.h @@ -60,7 +60,7 @@ #define DEVICE_SCENARIO_FILE "s.scen.txt" //#define OTA_UPDATES_ENABLED //#define MDNS_ENABLED -//#define WEBSOCKET_ENABLED +#define WEBSOCKET_ENABLED //#define LAYOUT_IN_RAM //#define UDP_ENABLED //#define SSDP_ENABLED diff --git a/include/items/vImpulsOut.h b/include/items/vImpulsOut.h index 885371ce..1ec19321 100644 --- a/include/items/vImpulsOut.h +++ b/include/items/vImpulsOut.h @@ -23,7 +23,6 @@ class ImpulsOutClass { unsigned int _impulsCount = 0; unsigned int _impulsCountBuf = 0; unsigned int _impulsPin = 0; - }; extern MyImpulsOutVector* myImpulsOut; diff --git a/include/items/vLogging.h b/include/items/vLogging.h index c1e5ad26..80bb1a73 100644 --- a/include/items/vLogging.h +++ b/include/items/vLogging.h @@ -11,15 +11,11 @@ typedef std::vector MyLoggingVector; class LoggingClass { public: - LoggingClass(String interval, unsigned int maxPoints, String loggingValueKey, String key, String startState, bool savedFromWeb); ~LoggingClass(); - void loop(); void execute(String keyOrValue); - private: - unsigned long currentMillis; unsigned long prevMillis; unsigned long difference; @@ -29,16 +25,14 @@ class LoggingClass { unsigned int _maxPoints; String _loggingValueKey; String _key; - - }; - extern MyLoggingVector* myLogging; - extern void logging(); extern void loggingExecute(); extern void choose_log_date_and_send(); +extern void choose_log_date_and_sendWS(); extern void sendLogData(String file, String topic); +extern void sendLogDataWS(String file, String topic); extern void sendLogData2(String file, String topic); extern void cleanLogAndData(); #endif diff --git a/include/items/vOutput.h b/include/items/vOutput.h index 76ae2d62..5ca61514 100644 --- a/include/items/vOutput.h +++ b/include/items/vOutput.h @@ -1,29 +1,19 @@ #ifdef EnableOutput #pragma once #include - #include "Global.h" - class Output; - typedef std::vector MyOutputVector; class Output { public: - Output(String key); ~Output(); - void execute(String value); - private: - String _key; - }; - extern MyOutputVector* myOutput; - extern void outputValue(); extern void outputExecute(); #endif diff --git a/src/MySensorsDataParse.cpp b/src/MySensorsDataParse.cpp index 10de9fe3..996b848c 100644 --- a/src/MySensorsDataParse.cpp +++ b/src/MySensorsDataParse.cpp @@ -7,7 +7,15 @@ //для того что бы выключить оригинальный лог нужно перейти в файл библиотеки MyGatewayTransportSerial.cpp //и заккоментировать строку 36 MY_SERIALDEVICE.print(protocolMyMessage2Serial(message)); - +boolean publishAnyJsonKeyWS(const String& topic, const String& key, const String& data) { + String path = mqttRootDevice + "/" + topic + "/status"; + String json = "{}"; + jsonWriteStr(json, key, data); + //добавляем топик, выводим в ws + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); +} void loopMySensorsExecute() { if (mysensorBuf.length()) { String tmp = selectToMarker(mysensorBuf, ";"); @@ -27,9 +35,15 @@ void loopMySensorsExecute() { if (command == "3") { //это особое внутреннее сообщение if (type == "11") { //название ноды SerialPrint("I", "MySensor", "Node name: " + value); - } +//* + publishAnyJsonKey("MySensors", "Node name:", value); +publishAnyJsonKeyWS("MySensors", "Node name:", value); + } if (type == "12") { //версия ноды SerialPrint("I", "MySensor", "Node version: " + value); + //* + publishAnyJsonKey("MySensors", "Node version: ", value); + publishAnyJsonKeyWS("MySensors", "Node version: ", value); } } } else { @@ -44,13 +58,26 @@ void loopMySensorsExecute() { addItemAuto(num, key, widget, descr); descr.replace("#", " "); SerialPrint("I", "MySensor", "Add new item: " + key + ": " + descr); +//* + publishAnyJsonKey("MySensors", key, descr); + publishAnyJsonKeyWS("MySensors", key, descr); + + } else { descr.replace("#", " "); SerialPrint("I", "MySensor", "Item already exist: " + key + ": " + descr); + +//* + publishAnyJsonKey("MySensors", key, descr); + publishAnyJsonKeyWS("MySensors", key, descr); } } else { descr.replace("#", " "); SerialPrint("I", "MySensor", "Presentation: " + key + ": " + descr); + +//* + publishAnyJsonKey("MySensors", key, descr); + publishAnyJsonKeyWS("MySensors", key, descr); } } if (command == "1") { //это данные @@ -63,6 +90,9 @@ void loopMySensorsExecute() { if (mySensorNode != nullptr) { for (unsigned int i = 0; i < mySensorNode->size(); i++) { mySensorNode->at(i).onChange(value, key); //вызываем поочередно все экземпляры, там где подойдет там и выполнится +//* + publishAnyJsonKey("MySensors", key, value); + publishAnyJsonKeyWS("MySensors", key, value); } } SerialPrint("I", "MySensor", "node: " + nodeId + ", sensor: " + childSensorId + ", command: " + command + ", type: " + type + ", val: " + value); diff --git a/src/UpgradeFirm.cpp b/src/UpgradeFirm.cpp index 58906f84..b81ff64a 100644 --- a/src/UpgradeFirm.cpp +++ b/src/UpgradeFirm.cpp @@ -8,11 +8,14 @@ #endif #include "Global.h" - + String msg = ""; void upgradeInit() { + + myNotAsyncActions->add( do_UPGRADE, [&](void*) { upgrade_firmware(3); + }, nullptr); @@ -27,7 +30,7 @@ void upgradeInit() { if (lastVersion > 0) { SerialPrint("I", F("Update"), "available version: " + String(lastVersion)); if (lastVersion > FIRMWARE_VERSION) { - jsonWriteStr(configSetupJson, "warning2", F("Вышла новая версия прошивки, нажмите обновить прошивку")); + jsonWriteStr(configSetupJson, "warning2", F("

Вышла новая версия прошивки, нажмите обновить прошивку

")); } } }; @@ -61,6 +64,8 @@ void getLastVersion() { } void upgrade_firmware(int type) { + + String scenario_ForUpdate; String devconfig_ForUpdate; String configSetup_ForUpdate; @@ -69,11 +74,11 @@ void upgrade_firmware(int type) { devconfig_ForUpdate = readFile(String(DEVICE_CONFIG_FILE), 4096); configSetup_ForUpdate = configSetupJson; - if (type == 1) { // only build + if (type == 1) { //only build if (upgradeBuild()) restartEsp(); } - else if (type == 2) { // only spiffs + else if (type == 2) { //only spiffs if (upgradeFS()) { writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate); writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate); @@ -82,8 +87,10 @@ void upgrade_firmware(int type) { } } - else if (type == 3) { // spiffs and build + else if (type == 3) { //spiffs and build if (upgradeFS()) { + String temp = jsonWriteInt(msg, "upgrade", 3 ); + ws.textAll(temp); writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate); writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate); writeFile("config.json", configSetup_ForUpdate); @@ -95,11 +102,18 @@ void upgrade_firmware(int type) { } } -bool upgradeFS() { - bool ret = false; +bool upgradeFS() { + + + + bool ret = false; #ifndef esp8266_1mb WiFiClient wifiClient; + + + Serial.printf("Start upgrade %s, please wait...", FS_NAME); + #ifdef esp8266_4mb ESPhttpUpdate.rebootOnUpdate(false); t_httpUpdate_return retFS = ESPhttpUpdate.updateFS(wifiClient, serverIP + F("/projects/iotmanager/esp8266/littlefs/littlefs.bin")); @@ -117,6 +131,8 @@ bool upgradeFS() { HTTPUpdateResult retFS = httpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp32ms/littlefs/spiffs.bin")); #endif if (retFS == HTTP_UPDATE_OK) { //если FS обновилась успешно + String temp = jsonWriteInt(msg, "upgrade", 2); + ws.textAll(temp); SerialPrint("I", F("Update"), F("FS upgrade done!")); ret = true; } @@ -125,6 +141,8 @@ bool upgradeFS() { } bool upgradeBuild() { + String temp = jsonWriteInt(msg, "upgrade", 4 ); + ws.textAll(temp); bool ret = false; #ifndef esp8266_1mb WiFiClient wifiClient; @@ -149,12 +167,16 @@ bool upgradeBuild() { if (retBuild == HTTP_UPDATE_OK) { //если BUILD обновился успешно SerialPrint("I", F("Update"), F("BUILD upgrade done!")); ret = true; + String temp = jsonWriteInt(msg, "upgrade", 5 ); + ws.textAll(temp); } #endif return ret; } void restartEsp() { + String temp = jsonWriteInt(msg, "upgrade", 6 ); + ws.textAll(temp); Serial.println(F("Restart ESP....")); delay(1000); ESP.restart(); diff --git a/src/Utils/SerialPrint.cpp b/src/Utils/SerialPrint.cpp index 6c923bfd..e7337841 100644 --- a/src/Utils/SerialPrint.cpp +++ b/src/Utils/SerialPrint.cpp @@ -1,9 +1,15 @@ #include "Utils\SerialPrint.h" - #include "Global.h" - void SerialPrint(String errorLevel, String module, String msg) { //if (module == "MySensor") { Serial.println(prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg); + String logtoWS = jsonReadStr(configSetupJson, "logtoWS"); + if (logtoWS == "true"){ + ws.textAll(" [" + errorLevel + "] [" + module + "] " + msg); + } + String logtoMQTT = jsonReadStr(configSetupJson, "logtoMQTT"); + if (logtoMQTT == "true"){ + publishAnyJsonKey("log", "log", errorLevel + " " + module + " " + msg); + } //} } \ No newline at end of file diff --git a/src/WebServer.cpp b/src/WebServer.cpp index 53898407..ea1e03bd 100644 --- a/src/WebServer.cpp +++ b/src/WebServer.cpp @@ -3,7 +3,13 @@ #include "Utils/FileUtils.h" #include "Utils/WebUtils.h" #include "FSEditor.h" +#include "Upgrade.h" +#include "Class/NotAsync.h" +#include "items/vLogging.h" +int flagq ; +AsyncWebSocket ws ("/ws"); +AsyncEventSource events("/events"); namespace HttpServer { @@ -84,12 +90,100 @@ void init() { SerialPrint("I", F("HTTP"), F("HttpServer Init")); } +/////////// +#ifndef LAYOUT_IN_RAM +void publishWidgetsWS() { + String str=""; + auto file = seekFile("layout.txt"); + if (!file) { + SerialPrint("E", F("WS"), F("no file layout.txt")); + return; + } + while (file.available()) { + + String payload = file.readStringUntil('\n'); + if (str==""){ + str += payload; + }else {str += "," + payload;} + + } + file.close(); + SerialPrint("I", "WS", "widgets: " + str); + ws.textAll(str); + + + +} + +void publishStateWS() { + String mystr=""; + String str; + if (configLiveJson != "{}") { + str += configLiveJson; + } + if (configStoreJson != "{}") { + str += "," + configStoreJson; + } + + + + str.replace("{", ""); + str.replace("}", ""); + str.replace("\"", ""); + str += ","; + + while (str.length() != 0) { + String tmp = selectToMarker(str, ","); + String topic = selectToMarker(tmp, ":"); + String state = deleteBeforeDelimiter(tmp, ":"); + + + if (topic != "" && state != "") { + + String json = "{}"; + jsonWriteStr(json, "status", state); + jsonWriteStr(json, "topic", mqttRootDevice + "/" + topic + "/status"); + SerialPrint("I", "ws", json.c_str()); + if (mystr==""){ + mystr += json; + }else {mystr += "," + json;} + + + } + str = deleteBeforeDelimiter(str, ","); + } + ws.textAll(mystr); + +} +/* +boolean publishStatusWS(const String& topic, const String& data) { + String path = mqttRootDevice + "/" + topic + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", data); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + +} +*/ + boolean publishAnyJsonKeyWS(const String& topic, const String& key, const String& data) { + String path = mqttRootDevice + "/" + topic + "/status"; + String json = "{}"; + jsonWriteStr(json, key, data); + //добавляем топик, выводим в ws + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); +} +#endif + +///////// void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { -#ifdef WS_enable +#ifdef WEBSOCKET_ENABLED if (type == WS_EVT_CONNECT) { Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); - client->printf(json.c_str(), client->id()); + // client->printf(json.c_str(), client->id()); //client->ping(); } else if (type == WS_EVT_DISCONNECT) { Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id()); @@ -116,6 +210,121 @@ void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventTyp } } Serial.printf("%s\n", msg.c_str()); + //-> +//если пришло HELLO публикуем виджеты и статусы + if (msg.startsWith("HELLO")) { + SerialPrint("I", F("WS"), F("Full update")); + publishWidgetsWS(); + publishStateWS(); + flagq = 1; + } +//если пришло UPGRADE + if (msg.startsWith("upgrade")) { + // SerialPrint("I", F("WS"), F("do_UPGRADEstart")); + myNotAsyncActions->make(do_UPGRADE); + String temp = jsonWriteInt(msg, "upgrade", 1 ); + ws.textAll(temp); + } + + String upgrade = jsonReadStr(msg, "upgrade"); + + if (upgrade != ""){ + // SerialPrint("I", F("WS"), F("do_UPGRADE")); + myNotAsyncActions->make(do_UPGRADE); + String temp = jsonWriteInt(msg, "upgrade", 1 ); + ws.textAll(temp); + } + + + +//отправляем конфигурацию на ESP + if (msg.startsWith("getconfigsetupjson")) { + ws.textAll(configSetupJson); + // Serial.printf("%s\n", configSetupJson.c_str()); + } +//отправляем NetworkMap в ESP + if (msg.startsWith("getNetworkMap")) { + String NetworkMap= readFile("NetworkMap.json", 409600); + // NetworkMap = NetworkMap.replace("\r\n", ""); + ws.textAll(NetworkMap); + + } + +//отправляем файл в ESP + String getFileName = jsonReadStr(msg, "getFileName"); + if (getFileName !=""){ + String getFile= readFile(getFileName, 409600); + // getFile.replace("\n", " "); + getFile="{getFileText:'"+getFile+"', getFileName: '"+getFileName+"'}"; + jsonWriteStr(getFile, "getFileName", getFileName); + ws.textAll(getFile); + Serial.printf("%s\n getFileName: ", getFileName.c_str()); + Serial.printf("%s\n getFile: ", getFile.c_str()); + } +//получаем файл от ESP + + String setFileName = jsonReadStr(msg, "setFileName"); + if (setFileName !=""){ + + + DynamicJsonBuffer jsonBuffer; + JsonObject& root = jsonBuffer.parseObject(msg); + + root.remove("setFileName"); + String newmsg; + root.printTo(newmsg); + + + writeFile(setFileName,newmsg); + //Serial.printf("%s\n setFileName: ", setFileName.c_str()); + Serial.printf("%s\n text: ", newmsg.c_str()); + } + +//получаем NetworkMap от ESP + String NetworkMap = jsonReadStr(msg, "NetworkMap"); + if (NetworkMap !=""){ + writeFile("NetworkMap.json", NetworkMap.c_str()); + // ws.textAll(NetworkMap); + } + //перезагрузка + String command = jsonReadStr(msg, "command"); + if (command !="" && jsonReadStr(msg, "command")=="reboot"){ + ESP.restart(); + } + + + +//получаем конфигурацию от ESP + + String changeConf = jsonReadStr(msg, "setconfigsetupjson"); + if (changeConf = "1"){ + + jsonWriteStr(configSetupJson, jsonReadStr(msg, "name"), jsonReadStr(msg, "val")); + saveConfig(); + Serial.printf("%s\n", jsonReadStr(msg, "name").c_str(), jsonReadStr(msg, "val").c_str()); + } + + + +// если пришло в control управляем + String path = jsonReadStr(msg, "path"); + String status = jsonReadStr(msg, "status"); + +if (path.indexOf("control") != -1) { + String key = selectFromMarkerToMarker(path, "/", 3); + + String order; + order += key; + order += " "; + order += status; + order += ","; + + loopCmdAdd(order); + + } + + + if (info->opcode == WS_TEXT) client->text("{}"); @@ -200,7 +409,7 @@ void initOta() { } void initWS() { -#ifdef WS_enable +#ifdef WEBSOCKET_ENABLED ws.onEvent(onWsEvent); server.addHandler(&ws); events.onConnect([](AsyncEventSourceClient *client) { diff --git a/src/items/vButtonOut.cpp b/src/items/vButtonOut.cpp index e861d68f..7d4aa191 100644 --- a/src/items/vButtonOut.cpp +++ b/src/items/vButtonOut.cpp @@ -7,6 +7,7 @@ #include "Global.h" #include "SoftUART.h" #include "items/vButtonOut.h" +//#include "WebServer.h" //this class save data to flash ButtonOut::ButtonOut(String pin, boolean inv, String key, String type) { _pin = pin; @@ -21,6 +22,12 @@ ButtonOut::ButtonOut(String pin, boolean inv, String key, String type) { this->execute(String(state)); //установили это состояние #endif #ifdef GATE_MODE + if (_pin != "") { + pinMode(_pin.toInt(), OUTPUT); + } + int state = jsonReadInt(configStoreJson, key); //прочитали из памяти + this->execute(String(state)); //установили это состояние + //TO DO запросили ноду о состоянии реле //установили в это состояние кнопку в приложении //если нода не ответила - кнопку сделать красным цветом @@ -44,6 +51,20 @@ void ButtonOut::execute(String state) { } #endif #ifdef GATE_MODE +// включаем кнопки на ESP гейта + if (state != "" && _pin != "") { + if (state == "change") { + state = String(!digitalRead(_pin.toInt())); + digitalWrite(_pin.toInt(), state.toInt()); + } else { + if (_inv) { + digitalWrite(_pin.toInt(), !state.toInt()); + } else { + digitalWrite(_pin.toInt(), state.toInt()); + } + } + } + //отправили ноде команду на вкл выкл //получили обратную связь - переставили кнопку в приложении //не получили обратную связь - сделали кнопку красной @@ -52,6 +73,12 @@ void ButtonOut::execute(String state) { jsonWriteInt(configStoreJson, _key, state.toInt()); saveStore(); publishStatus(_key, state); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", state); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); } MyButtonOutVector* myButtonOut = nullptr; diff --git a/src/items/vCountDown.cpp b/src/items/vCountDown.cpp index f8607713..d432ab06 100644 --- a/src/items/vCountDown.cpp +++ b/src/items/vCountDown.cpp @@ -32,6 +32,12 @@ void CountDownClass::loop() { String time = String(prettyMillis(sec * 1000)); jsonWriteStr(configLiveJson, _key, time); publishStatus(_key, time); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", time); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); sec--; if (sec < 0) { _countDownPeriod = 0; @@ -48,10 +54,8 @@ void countDown() { countDown_EnterCounter++; addKey(key, countDown_KeyList, countDown_EnterCounter); - //Serial.println(countDown_EnterCounter); //Serial.println(countDown_KeyList); - static bool firstTime = true; if (firstTime) myCountDown = new MyCountDownVector(); firstTime = false; diff --git a/src/items/vInput.cpp b/src/items/vInput.cpp index 081a7aa1..50b6f2f7 100644 --- a/src/items/vInput.cpp +++ b/src/items/vInput.cpp @@ -31,6 +31,12 @@ void Input::execute(String value) { jsonWriteStr(configStoreJson, _key, value); saveStore(); publishStatus(_key, value); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", value); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); } MyInputVector* myInput = nullptr; diff --git a/src/items/vLogging.cpp b/src/items/vLogging.cpp index 08519009..7ff48f83 100644 --- a/src/items/vLogging.cpp +++ b/src/items/vLogging.cpp @@ -166,7 +166,78 @@ void loggingExecute() { } } +void choose_log_date_and_sendWS() { + + String all_line = logging_KeyList; + while (all_line.length() != 0) { + String tmp = selectToMarker(all_line, ","); + sendLogDataWS("/logs/" + tmp + ".txt", tmp); + all_line = deleteBeforeDelimiter(all_line, ","); + } +} + +void sendLogDataWS(String file, String topic) { + File configFile = FileFS.open(file, "r"); + if (!configFile) { + return; + } + configFile.seek(0, SeekSet); + int i = 0; + String buf = "{}"; + String json_array; + String unix_time; + String value; + unsigned int psn; + unsigned int sz = configFile.size(); + do { + i++; + psn = configFile.position(); + String line = configFile.readStringUntil('\n'); + unix_time = selectToMarker(line, " "); + jsonWriteInt(buf, "x", unix_time.toInt()); + value = deleteBeforeDelimiter(line, " "); + jsonWriteFloat(buf, "y1", value.toFloat()); + if (unix_time != "" || value != "") { + json_array += buf + ","; + } + int grafmax = jsonReadInt(configSetupJson, "grafmax"); + if (grafmax != 0) { + if (i >= grafmax) { + json_array = "{\"status\":[" + json_array + "]}"; + json_array.replace("},]}", "}]}"); + // publishChart(topic, json_array); + + // добавляем топик, выводим в ws + String path = mqttRootDevice + "/" + topic; + String json = "{}"; + json=json_array; + jsonWriteStr(json, "topic", path); + ws.textAll(json); + + + json_array = ""; + i = 0; + } + } + } while (psn < sz); + + configFile.close(); + + json_array = "{\"status\":[" + json_array + "]}"; + json_array.replace("},]}", "}]}"); + //publishChart(topic, json_array); + + // добавляем топик, выводим в ws + String path = mqttRootDevice + "/" + topic; + String json = "{}"; + json=json_array; + jsonWriteStr(json, "topic", path); + ws.textAll(json); + +} + void choose_log_date_and_send() { + String all_line = logging_KeyList; while (all_line.length() != 0) { String tmp = selectToMarker(all_line, ","); @@ -205,7 +276,8 @@ void sendLogData(String file, String topic) { json_array = "{\"status\":[" + json_array + "]}"; json_array.replace("},]}", "}]}"); publishChart(topic, json_array); - json_array = ""; + + json_array = ""; i = 0; } } @@ -216,6 +288,7 @@ void sendLogData(String file, String topic) { json_array = "{\"status\":[" + json_array + "]}"; json_array.replace("},]}", "}]}"); publishChart(topic, json_array); + } void cleanLogAndData() { diff --git a/src/items/vOutput.cpp b/src/items/vOutput.cpp index 42dbce99..eed424be 100644 --- a/src/items/vOutput.cpp +++ b/src/items/vOutput.cpp @@ -19,6 +19,12 @@ void Output::execute(String value) { eventGen2(_key, value); jsonWriteStr(configLiveJson, _key, value); publishStatus(_key, value); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", value); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); //publishLastUpdateTime(_key, timeNow->getTime()); } diff --git a/src/items/vPwmOut.cpp b/src/items/vPwmOut.cpp index a6df133a..91dbcfaf 100644 --- a/src/items/vPwmOut.cpp +++ b/src/items/vPwmOut.cpp @@ -25,6 +25,12 @@ void PwmOut::execute(String state) { jsonWriteInt(configStoreJson, _key, state.toInt()); saveStore(); publishStatus(_key, state); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", state); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); } MyPwmOutVector* myPwmOut = nullptr; diff --git a/src/items/vSensorAnalog.cpp b/src/items/vSensorAnalog.cpp index b0df65df..c817f85f 100644 --- a/src/items/vSensorAnalog.cpp +++ b/src/items/vSensorAnalog.cpp @@ -45,6 +45,12 @@ void SensorAnalog::readAnalog() { eventGen2(_key, String(valueFloat)); jsonWriteStr(configLiveJson, _key, String(valueFloat)); publishStatus(_key, String(valueFloat)); + String path = mqttRootDevice + "/" + _key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(valueFloat)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(valueFloat)); } diff --git a/src/items/vSensorBme280.cpp b/src/items/vSensorBme280.cpp index 11daf71f..43ff545e 100644 --- a/src/items/vSensorBme280.cpp +++ b/src/items/vSensorBme280.cpp @@ -48,16 +48,34 @@ void SensorBme280::read() { eventGen2(_paramsTmp.key, String(tmp)); jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); publishStatus(_paramsTmp.key, String(tmp)); + String path = mqttRootDevice + "/" +_paramsTmp.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(tmp)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); eventGen2(_paramsHum.key, String(hum)); jsonWriteStr(configLiveJson, _paramsHum.key, String(hum)); publishStatus(_paramsHum.key, String(hum)); + path = mqttRootDevice + "/" +_paramsHum.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(hum)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum)); eventGen2(_paramsPrs.key, String(prs)); jsonWriteStr(configLiveJson, _paramsPrs.key, String(prs)); publishStatus(_paramsPrs.key, String(prs)); + path = mqttRootDevice + "/" +_paramsPrs.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(prs)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsPrs.key + "' data: " + String(prs)); } diff --git a/src/items/vSensorBmp280.cpp b/src/items/vSensorBmp280.cpp index 2d9672bb..03f479b9 100644 --- a/src/items/vSensorBmp280.cpp +++ b/src/items/vSensorBmp280.cpp @@ -44,11 +44,23 @@ void SensorBmp280::read() { eventGen2(_paramsTmp.key, String(tmp)); jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); publishStatus(_paramsTmp.key, String(tmp)); + String path = mqttRootDevice + "/" +_paramsTmp.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(tmp)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); eventGen2(_paramsPrs.key, String(prs)); jsonWriteStr(configLiveJson, _paramsPrs.key, String(prs)); publishStatus(_paramsPrs.key, String(prs)); + path = mqttRootDevice + "/" +_paramsPrs.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(prs)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsPrs.key + "' data: " + String(prs)); } diff --git a/src/items/vSensorCcs811.cpp b/src/items/vSensorCcs811.cpp index 3463ea31..433e351e 100644 --- a/src/items/vSensorCcs811.cpp +++ b/src/items/vSensorCcs811.cpp @@ -41,11 +41,23 @@ void SensorCcs811::read() { eventGen2(_paramsPpm.key, String(co2)); jsonWriteStr(configLiveJson, _paramsPpm.key, String(co2)); publishStatus(_paramsPpm.key, String(co2)); + String path = mqttRootDevice + "/" +_paramsPpm.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(co2)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsPpm.key + "' data: " + String(co2)); eventGen2(_paramsPpb.key, String(ppm)); jsonWriteStr(configLiveJson, _paramsPpb.key, String(ppm)); publishStatus(_paramsPpb.key, String(ppm)); + path = mqttRootDevice + "/" +_paramsPpb.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(ppm)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsPpb.key + "' data: " + String(ppm)); } else { SerialPrint("E", "Sensor CCS", "Error"); diff --git a/src/items/vSensorDallas.cpp b/src/items/vSensorDallas.cpp index 9a2161a9..4b3f46d8 100644 --- a/src/items/vSensorDallas.cpp +++ b/src/items/vSensorDallas.cpp @@ -39,6 +39,12 @@ void SensorDallas::readDallas() { eventGen2(_key, String(value)); jsonWriteStr(configLiveJson, _key, String(value)); publishStatus(_key, String(value)); + String path = mqttRootDevice + "/" +_key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(value)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(value)); } diff --git a/src/items/vSensorDht.cpp b/src/items/vSensorDht.cpp index dc605062..62c98531 100644 --- a/src/items/vSensorDht.cpp +++ b/src/items/vSensorDht.cpp @@ -44,11 +44,23 @@ void SensorDht::readTmpHum() { eventGen2(_paramsTmp.key, String(tmp)); jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); publishStatus(_paramsTmp.key, String(tmp)); + String path = mqttRootDevice + "/" +_paramsTmp.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(tmp)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); eventGen2(_paramsHum.key, String(hum)); jsonWriteStr(configLiveJson, _paramsHum.key, String(hum)); publishStatus(_paramsHum.key, String(hum)); + path = mqttRootDevice + "/" +_paramsHum.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(hum)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum)); } else { diff --git a/src/items/vSensorImpulsIn.cpp b/src/items/vSensorImpulsIn.cpp deleted file mode 100644 index 421d6219..00000000 --- a/src/items/vSensorImpulsIn.cpp +++ /dev/null @@ -1,51 +0,0 @@ -//#include "items/vSensorImpulsIn.h" -// -//#include "BufferExecute.h" -//#include "Class/LineParsing.h" -//#include "Global.h" -//#include "SoftUART.h" -// -//SensorImpulsIn::SensorImpulsIn(const paramsImpulsIn& paramsImpuls) { -// _paramsImpuls = paramsImpulsIn(paramsImpuls); -// pinMode(14, INPUT); -// //pinMode(_paramsImpuls.pin, INPUT_PULLUP); -// //attachInterrupt(digitalPinToInterrupt(14), MYinterrupt, CHANGE); -//} -// -//SensorImpulsIn::~SensorImpulsIn() {} -// -////void SensorImpulsIn::read() { -// float voltage; //= (impulsIn->values()->voltage * _paramsV.c) + _paramsV.k; -// -// eventGen2(_paramsImpuls.key, String(voltage)); -// jsonWriteStr(configLiveJson, _paramsImpuls.key, String(voltage)); -// publishStatus(_paramsImpuls.key, String(voltage)); -// SerialPrint("I", "Sensor", "'" + _paramsImpuls.key + "' data: " + String(voltage)); -//} -// -//MySensorImpulsInVector* mySensorImpulsIn = nullptr; -// -//void impulsInSensor() { -// myLineParsing.update(); -// String key = myLineParsing.gkey(); -// String pin = myLineParsing.gpin(); -// String c = myLineParsing.gc(); -// String k = myLineParsing.gk(); -// myLineParsing.clear(); -// -// static paramsImpulsIn paramsImpuls; -// -// paramsImpuls.key = key; -// paramsImpuls.pin = pin.toInt(); -// paramsImpuls.c = c.toFloat(); -// paramsImpuls.k = k.toFloat(); -// -// static bool firstTime = true; -// if (firstTime) mySensorImpulsIn = new MySensorImpulsInVector(); -// firstTime = false; -// mySensorImpulsIn->push_back(SensorImpulsIn(paramsImpuls)); -//} -// -//void MYinterrupt() { -// Serial.println("interrupt!"); -//} diff --git a/src/items/vSensorNode.cpp b/src/items/vSensorNode.cpp index 00295fcd..72427c93 100644 --- a/src/items/vSensorNode.cpp +++ b/src/items/vSensorNode.cpp @@ -37,6 +37,12 @@ void SensorNode::onChange(String newValue, String incommingKey) { eventGen2(_params.key, newValue); jsonWriteStr(configLiveJson, _params.key, newValue); publishStatus(_params.key, newValue); + String path = mqttRootDevice + "/" +_params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", newValue); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); _updateTime = timeNow->getDateTimeDotFormated(); @@ -48,17 +54,72 @@ void SensorNode::onChange(String newValue, String incommingKey) { void SensorNode::publish() { if (_minutesPassed < _params.tm1.toInt()) { publishAnyJsonKey(_params.key, "info", String(_minutesPassed) + " min"); + + String path = mqttRootDevice + "/" + _params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "info", String(_minutesPassed) + " min"); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + + publishAnyJsonKey(_params.key, "color", ""); + + + path = mqttRootDevice + "/" + _params.key + "/status"; + json = "{}"; + jsonWriteStr(json, "color", ""); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + } else if (_minutesPassed >= _params.tm1.toInt() && _minutesPassed < _params.tm2.toInt()) { publishAnyJsonKey(_params.key, "info", String(_minutesPassed) + " min"); + + String path = mqttRootDevice + "/" + _params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "info", String(_minutesPassed) + " min"); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + publishAnyJsonKey(_params.key, "color", "orange"); + path = mqttRootDevice + "/" + _params.key + "/status"; + json = "{}"; + jsonWriteStr(json, "color", "orange"); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + } else if (_minutesPassed >= _params.tm2.toInt()) { if (_updateTime == "") { publishAnyJsonKey(_params.key, "info", "offline"); + + + String path = mqttRootDevice + "/" + _params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "info", "offline"); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); } else { publishAnyJsonKey(_params.key, "info", _updateTime); + String path = mqttRootDevice + "/" + _params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "info", _updateTime); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + + } publishAnyJsonKey(_params.key, "color", "red"); + String path = mqttRootDevice + "/" + _params.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "color", "red"); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); } } diff --git a/src/items/vSensorPzem.cpp b/src/items/vSensorPzem.cpp index 3583e444..8058eb65 100644 --- a/src/items/vSensorPzem.cpp +++ b/src/items/vSensorPzem.cpp @@ -38,26 +38,56 @@ void SensorPzem::read() { eventGen2(_paramsV.key, String(voltage)); jsonWriteStr(configLiveJson, _paramsV.key, String(voltage)); publishStatus(_paramsV.key, String(voltage)); + String path = mqttRootDevice + "/" +_paramsV.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(voltage)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsV.key + "' data: " + String(voltage)); eventGen2(_paramsA.key, String(current)); jsonWriteStr(configLiveJson, _paramsA.key, String(current)); publishStatus(_paramsA.key, String(current)); + path = mqttRootDevice + "/" +_paramsA.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(current)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsA.key + "' data: " + String(current)); eventGen2(_paramsWatt.key, String(power)); jsonWriteStr(configLiveJson, _paramsWatt.key, String(power)); publishStatus(_paramsWatt.key, String(power)); + path = mqttRootDevice + "/" +_paramsWatt.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(power)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsWatt.key + "' data: " + String(power)); eventGen2(_paramsWattHrs.key, String(energy)); jsonWriteStr(configLiveJson, _paramsWattHrs.key, String(energy)); publishStatus(_paramsWattHrs.key, String(energy)); + path = mqttRootDevice + "/" +_paramsWattHrs.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(energy)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsWattHrs.key + "' data: " + String(energy)); eventGen2(_paramsHz.key, String(freq)); jsonWriteStr(configLiveJson, _paramsHz.key, String(freq)); publishStatus(_paramsHz.key, String(freq)); + path = mqttRootDevice + "/" +_paramsHz.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(freq)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsHz.key + "' data: " + String(freq)); } else { SerialPrint("E", "Sensor PZEM", "Error, UART switched off"); diff --git a/src/items/vSensorSHT20.cpp b/src/items/vSensorSHT20.cpp index 9c58b133..7f0134d8 100644 --- a/src/items/vSensorSHT20.cpp +++ b/src/items/vSensorSHT20.cpp @@ -49,11 +49,24 @@ void SensorSht20::read() { eventGen2(_paramsTmp.key, String(tmp)); jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); publishStatus(_paramsTmp.key, String(tmp)); + String path = mqttRootDevice + "/" +_paramsTmp.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(tmp)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); + SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); eventGen2(_paramsHum.key, String(hum)); jsonWriteStr(configLiveJson, _paramsHum.key, String(hum)); publishStatus(_paramsHum.key, String(hum)); + path = mqttRootDevice + "/" +_paramsHum.key + "/status"; + json = "{}"; + jsonWriteStr(json, "status", String(hum)); + MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum)); } diff --git a/src/items/vSensorUltrasonic.cpp b/src/items/vSensorUltrasonic.cpp index 6449d4d8..90a32b91 100644 --- a/src/items/vSensorUltrasonic.cpp +++ b/src/items/vSensorUltrasonic.cpp @@ -53,20 +53,22 @@ void SensorUltrasonic::readUltrasonic() { value = duration_ / 29 / 2; value = testFilter.filtered(value); - value = map(value, _map1, _map2, _map3, _map4); float valueFloat = value * _c; - if (counter > 10) { eventGen2(_key, String(valueFloat)); jsonWriteStr(configLiveJson, _key, String(valueFloat)); publishStatus(_key, String(valueFloat)); + String path = mqttRootDevice + "/" +_key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", String(valueFloat)); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(valueFloat)); } } - MySensorUltrasonicVector* mySensorUltrasonic = nullptr; - void ultrasonic() { myLineParsing.update(); String interval = myLineParsing.gint(); @@ -75,15 +77,12 @@ void ultrasonic() { String map = myLineParsing.gmap(); String c = myLineParsing.gc(); myLineParsing.clear(); - unsigned int trig = selectFromMarkerToMarker(pin, ",", 0).toInt(); unsigned int echo = selectFromMarkerToMarker(pin, ",", 1).toInt(); - int map1 = selectFromMarkerToMarker(map, ",", 0).toInt(); int map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); int map3 = selectFromMarkerToMarker(map, ",", 2).toInt(); int map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); - static bool firstTime = true; if (firstTime) mySensorUltrasonic = new MySensorUltrasonicVector(); firstTime = false; diff --git a/src/items/vSensorUptime.cpp b/src/items/vSensorUptime.cpp index 6d3babca..dae5cdb6 100644 --- a/src/items/vSensorUptime.cpp +++ b/src/items/vSensorUptime.cpp @@ -28,6 +28,12 @@ void SensorUptime::read() { eventGen2(_paramsUpt.key, upt); jsonWriteStr(configLiveJson, _paramsUpt.key, upt); publishStatus(_paramsUpt.key, upt); + String path = mqttRootDevice + "/" +_paramsUpt.key + "/status"; + String json = "{}"; + jsonWriteStr(json, "status", upt); + String MyJson = json; + jsonWriteStr(MyJson, "topic", path); + ws.textAll(MyJson); SerialPrint("I", "Sensor", "'" + _paramsUpt.key + "' data: " + upt); } @@ -38,12 +44,9 @@ void uptimeSensor() { String key = myLineParsing.gkey(); String interval = myLineParsing.gint(); myLineParsing.clear(); - static paramsUptime paramsUpt; - paramsUpt.key = key; paramsUpt.interval = interval.toInt() * 1000; - static bool firstTime = true; if (firstTime) mySensorUptime = new MySensorUptimeVector(); firstTime = false; diff --git a/src/main.cpp b/src/main.cpp index 298b051d..8f54d67c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -35,11 +35,12 @@ #include "items/vSensorUltrasonic.h" #include "items/vSensorUptime.h" +//#include "WebServer.h" void not_async_actions(); Timings metric; boolean initialized = false; - +extern int flagq ; void setup() { Serial.begin(115200); Serial.flush(); @@ -94,8 +95,14 @@ void loop() { #ifdef OTA_UPDATES_ENABLED ArduinoOTA.handle(); #endif -#ifdef WS_enable - ws.cleanupClients(); +#ifdef WEBSOCKET_ENABLED + + ws.cleanupClients(); + if ( flagq == 1){ + SerialPrint("I", "WS ", "choose_log_date_and_send()"); + choose_log_date_and_sendWS(); + flagq = 0; +} #endif timeNow->loop(); mqttLoop();