From 993b2b25fdaf0287f4be6d1abdf2631b697262d4 Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Tue, 22 Feb 2022 16:40:46 +0100 Subject: [PATCH] =?UTF-8?q?=D1=83=D0=B1=D1=80=D0=B0=D0=BB=D0=B8=20=D0=BB?= =?UTF-8?q?=D0=B8=D1=88=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B8=20json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Global.h | 2 + include/MqttClient.h | 3 + include/utils/JsonUtils.h | 34 ++++---- src/DeviceList.cpp | 12 +-- src/Global.cpp | 2 + src/MqttClient.cpp | 19 ++++- src/PeriodicTasks.cpp | 13 +-- src/classes/IoTItem.cpp | 16 ++-- src/modules/Bme280.cpp | 42 +++++----- src/modules/Ds18b20.cpp | 30 +++---- src/utils/JsonUtils.cpp | 166 ++++++++++++++++++++++++-------------- src/utils/SerialPrint.cpp | 6 +- 12 files changed, 208 insertions(+), 137 deletions(-) diff --git a/include/Global.h b/include/Global.h index bf0e010e..211c8148 100644 --- a/include/Global.h +++ b/include/Global.h @@ -106,6 +106,8 @@ extern String mqttPass; extern unsigned long mqttUptime; extern unsigned long flashWriteNumber; +extern unsigned long wifiUptime; + extern String mqttRootDevice; extern String chipId; extern String prex; diff --git a/include/MqttClient.h b/include/MqttClient.h index 6e035e18..cd766bd1 100644 --- a/include/MqttClient.h +++ b/include/MqttClient.h @@ -31,3 +31,6 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length); void handleMqttStatus(bool send); void handleMqttStatus(bool send, int state); const String getStateStr(int e); + +void mqttUptimeCalc(); +void wifiUptimeCalc(); \ No newline at end of file diff --git a/include/utils/JsonUtils.h b/include/utils/JsonUtils.h index a685da46..3a6912e9 100644 --- a/include/utils/JsonUtils.h +++ b/include/utils/JsonUtils.h @@ -5,26 +5,26 @@ extern String jsonReadStrDoc(DynamicJsonDocument& doc, String name); extern void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String 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); +extern String jsonWriteStr(String& json, String name, String value, bool e = true); +extern String jsonWriteInt(String& json, String name, int value, bool e = true); +extern String jsonWriteFloat(String& json, String name, float value, bool e = true); +extern String jsonWriteBool(String& json, String name, boolean value, bool e = true); -extern bool jsonRead(String& json, String key, unsigned long& value); -extern bool jsonRead(String& json, String key, float& 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); +extern bool jsonRead(String& json, String key, unsigned long& value, bool e = true); +extern bool jsonRead(String& json, String key, float& value, bool e = true); +extern bool jsonRead(String& json, String key, String& value, bool e = true); +extern bool jsonRead(String& json, String key, bool& value, bool e = true); +extern bool jsonRead(String& json, String key, int& value, bool e = true); -extern String jsonReadStr(String& json, String name); -extern int jsonReadInt(String& json, String name); -extern boolean jsonReadBool(String& json, String name); +extern String jsonReadStr(String& json, String name, bool e = true); +extern int jsonReadInt(String& json, String name, bool e = true); +extern boolean jsonReadBool(String& json, String name, bool e = true); -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); +extern bool jsonWriteStr_(String& json, String name, String value, bool e = true); +extern bool jsonWriteBool_(String& json, String name, bool value, bool e = true); +extern bool jsonWriteInt_(String& json, String name, int value, bool e = true); +extern bool jsonWriteFloat_(String& json, String name, float value, bool e = true); void writeUint8tValueToJsonString(uint8_t* payload, size_t length, size_t headerLenth, String& json); -extern bool jsonMergeObjects(String& json1, String& json2); +extern bool jsonMergeObjects(String& json1, String& json2, bool e = true); extern void jsonMergeDocs(JsonObject dest, JsonObjectConst src); extern void jsonErrorDetected(); diff --git a/src/DeviceList.cpp b/src/DeviceList.cpp index e193a0df..0836143b 100644 --- a/src/DeviceList.cpp +++ b/src/DeviceList.cpp @@ -52,13 +52,15 @@ void asyncUdpInit() { }); } - //будем отправлять каждые 60 секунд презентацию данного устройства + //будем отправлять каждые 30 секунд презентацию данного устройства ts.add( UDP, 30000, [&](void*) { - SerialPrint("i", F("UDP"), F("Broadcast device presentation")); - asyncUdp.broadcastTo(getThisDevice().c_str(), 4210); - // asyncUdp.broadcast("test"); - // asyncUdp.print("Hello Server!"); + if (isNetworkActive()) { + SerialPrint("i", F("UDP"), F("Broadcast device presentation")); + asyncUdp.broadcastTo(getThisDevice().c_str(), 4210); + // asyncUdp.broadcast("test"); + // asyncUdp.print("Hello Server!"); + } }, nullptr, true); diff --git a/src/Global.cpp b/src/Global.cpp index 28d8b2b9..b99d3bf9 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -57,6 +57,8 @@ String mqttPass = ""; unsigned long mqttUptime = 0; unsigned long flashWriteNumber = 0; +unsigned long wifiUptime = 0; + String chipId = ""; String prex = ""; String all_widgets = ""; diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp index 96c276b6..c96921d1 100644 --- a/src/MqttClient.cpp +++ b/src/MqttClient.cpp @@ -7,14 +7,12 @@ void mqttInit() { [&](void*) { if (WiFi.status() == WL_CONNECTED) { SerialPrint("i", F("WIFI"), F("OK")); + wifiUptimeCalc(); if (mqtt.connected()) { SerialPrint("i", F("MQTT"), "OK"); + mqttUptimeCalc(); handleMqttStatus(false); - static unsigned int prevMillis; - mqttUptime = mqttUptime + (millis() - prevMillis); - prevMillis = millis(); - // setLedStatus(LED_OFF); } else { SerialPrint("E", F("MQTT"), F("✖ Connection lost")); @@ -25,6 +23,7 @@ void mqttInit() { } else { SerialPrint("E", F("WIFI"), F("✖ Lost WiFi connection")); ts.remove(WIFI_MQTT_CONNECTION_CHECK); + wifiUptime = 0; startAPMode(); } }, @@ -347,3 +346,15 @@ const String getStateStr(int e) { break; } } + +void mqttUptimeCalc() { + static unsigned int prevMillis; + mqttUptime = mqttUptime + (millis() - prevMillis); + prevMillis = millis(); +} + +void wifiUptimeCalc() { + static unsigned int prevMillis; + wifiUptime = wifiUptime + (millis() - prevMillis); + prevMillis = millis(); +} diff --git a/src/PeriodicTasks.cpp b/src/PeriodicTasks.cpp index 19611021..e6689fda 100644 --- a/src/PeriodicTasks.cpp +++ b/src/PeriodicTasks.cpp @@ -14,11 +14,14 @@ void periodicTasksInit() { // uptime jsonWriteStr_(errorsHeapJson, F("upt"), prettyMillis(millis())); jsonWriteStr_(errorsHeapJson, F("uptm"), prettyMillis(mqttUptime)); + jsonWriteStr_(errorsHeapJson, F("uptw"), prettyMillis(wifiUptime)); // flash jsonWriteInt_(errorsHeapJson, F("fl"), flashWriteNumber); // build ver jsonWriteStr_(errorsHeapJson, F("bver"), String(FIRMWARE_VERSION)); jsonWriteStr_(errorsHeapJson, F("bn"), String(FIRMWARE_NAME)); + // reset reason + jsonWriteStr_(errorsHeapJson, F("rst"), ESP_getResetReason()); periodicWsSend(); }, nullptr, true); @@ -35,15 +38,15 @@ void handleError(String errorId, int errorValue) { void printGlobalVarSize() { size_t settingsFlashJsonSize = settingsFlashJson.length(); - SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize)); + // SerialPrint(F("i"), F("settingsFlashJson"), String(settingsFlashJsonSize)); size_t errorsHeapJsonSize = errorsHeapJson.length(); - SerialPrint(F("i"), F("errorsHeapJson"), String(errorsHeapJsonSize)); + // SerialPrint(F("i"), F("errorsHeapJson"), String(errorsHeapJsonSize)); size_t paramsFlashJsonSize = paramsFlashJson.length(); - SerialPrint(F("i"), F("paramsFlashJson"), String(paramsFlashJsonSize)); + // SerialPrint(F("i"), F("paramsFlashJson"), String(paramsFlashJsonSize)); size_t paramsHeapJsonSize = paramsHeapJson.length(); - SerialPrint(F("i"), F("paramsHeapJson"), String(paramsHeapJsonSize)); + // SerialPrint(F("i"), F("paramsHeapJson"), String(paramsHeapJsonSize)); size_t devListHeapJsonSize = devListHeapJson.length(); - SerialPrint(F("i"), F("devListHeapJson"), String(devListHeapJsonSize)); + // SerialPrint(F("i"), F("devListHeapJson"), String(devListHeapJsonSize)); size_t halfBuffer = JSON_BUFFER_SIZE / 2; diff --git a/src/classes/IoTItem.cpp b/src/classes/IoTItem.cpp index 5236278d..59d6c643 100644 --- a/src/classes/IoTItem.cpp +++ b/src/classes/IoTItem.cpp @@ -6,16 +6,16 @@ #include "ESPConfiguration.h" IoTItem::IoTItem(String parameters) { - jsonRead(parameters, "int", _interval); + jsonRead(parameters, F("int"), _interval); _interval = _interval * 1000; - jsonRead(parameters, "subtype", _subtype); - jsonRead(parameters, "id", _id); - jsonRead(parameters, "multiply", _multiply); - jsonRead(parameters, "plus", _plus); - jsonRead(parameters, "round", _round); + jsonRead(parameters, F("subtype"), _subtype); + jsonRead(parameters, F("id"), _id); + jsonRead(parameters, F("multiply"), _multiply, false); + jsonRead(parameters, F("plus"), _plus, false); + jsonRead(parameters, F("round"), _round, false); String map; - jsonRead(parameters, "map", map); + jsonRead(parameters, F("map"), map, false); if (map != "") { _map1 = selectFromMarkerToMarker(map, ",", 0).toInt(); _map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); @@ -63,7 +63,7 @@ void IoTItem::regEvent(float value, String consoleInfo = "") { value = value / _round; } - //value = (float)value / (_round ? pow(10, (int)_round) : 1); // todo: решить как указывать округление, количество знаков после запятой или десятые сотые ... + // value = (float)value / (_round ? pow(10, (int)_round) : 1); // todo: решить как указывать округление, количество знаков после запятой или десятые сотые ... } if (_map1 != _map2) value = map(value, _map1, _map2, _map3, _map4); diff --git a/src/modules/Bme280.cpp b/src/modules/Bme280.cpp index 64920ae1..b32f4499 100644 --- a/src/modules/Bme280.cpp +++ b/src/modules/Bme280.cpp @@ -4,76 +4,76 @@ https://github.com/adafruit/Adafruit_BME280_Library ******************************************************************/ - #include "Global.h" #include "classes/IoTItem.h" #include #include - std::map bmes; class Bme280t : public IoTItem { private: - Adafruit_BME280* _bme; - + Adafruit_BME280* _bme; + public: - Bme280t(Adafruit_BME280* bme, String parameters): IoTItem(parameters) { + Bme280t(Adafruit_BME280* bme, String parameters) : IoTItem(parameters) { _bme = bme; } - + void doByInterval() { value.valD = _bme->readTemperature(); - if (value.valD < 145) regEvent(value.valD, "Bme280t"); - else SerialPrint("E", "Sensor Bme280t", "Error"); + if (value.valD < 145) + regEvent(value.valD, "Bme280t"); + else + SerialPrint("E", "Sensor Bme280t", "Error"); } ~Bme280t(); }; - class Bme280h : public IoTItem { private: - Adafruit_BME280* _bme; + Adafruit_BME280* _bme; public: - Bme280h(Adafruit_BME280* bme, String parameters): IoTItem(parameters) { + Bme280h(Adafruit_BME280* bme, String parameters) : IoTItem(parameters) { _bme = bme; } - + void doByInterval() { value.valD = _bme->readHumidity(); - if (value.valD < 100) regEvent(value.valD, "Bme280h"); - else SerialPrint("E", "Sensor Bme280h", "Error"); + if (value.valD < 100) + regEvent(value.valD, "Bme280h"); + else + SerialPrint("E", "Sensor Bme280h", "Error"); } ~Bme280h(); }; - class Bme280p : public IoTItem { private: - Adafruit_BME280* _bme; + Adafruit_BME280* _bme; public: - Bme280p(Adafruit_BME280* bme, String parameters): IoTItem(parameters) { + Bme280p(Adafruit_BME280* bme, String parameters) : IoTItem(parameters) { _bme = bme; } - + void doByInterval() { value.valD = _bme->readPressure(); if (value.valD > 0) { value.valD = value.valD / 1.333224 / 100; regEvent(value.valD, "Bme280p"); - } else SerialPrint("E", "Sensor Bme280p", "Error"); + } else + SerialPrint("E", "Sensor Bme280p", "Error"); } ~Bme280p(); }; - -void* getAPI_Bme280(String subtype, String param) { +void* getAPI_Bme280(String subtype, String param) { String addr; jsonRead(param, "addr", addr); diff --git a/src/modules/Ds18b20.cpp b/src/modules/Ds18b20.cpp index 4079223e..3ead2b7a 100644 --- a/src/modules/Ds18b20.cpp +++ b/src/modules/Ds18b20.cpp @@ -12,13 +12,13 @@ std::map sensorsTemperatureArray; class Ds18b20 : public IoTItem { private: //для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии - OneWire* oneWire; - DallasTemperature* sensors; + OneWire* oneWire; + DallasTemperature* sensors; //описание параметров передаваемых из настроек датчика из веба - String _addr; - int _pin; - int _index; + String _addr; + int _pin; + int _index; public: //======================================================================================================= @@ -27,10 +27,10 @@ class Ds18b20 : public IoTItem { //Такие как ...begin и подставлять в них параметры полученные из web интерфейса. //Все параметры хранятся в перемененной parameters, вы можете прочитать любой параметр используя jsonRead функции: // jsonReadStr, jsonReadBool, jsonReadInt - Ds18b20(String parameters): IoTItem(parameters) { + Ds18b20(String parameters) : IoTItem(parameters) { jsonRead(parameters, "pin", _pin); - jsonRead(parameters, "index", _index); - jsonRead(parameters, "addr", _addr); + jsonRead(parameters, "index", _index, false); + jsonRead(parameters, "addr", _addr, false); //учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась if (oneWireTemperatureArray.find(_pin) == oneWireTemperatureArray.end()) { @@ -58,9 +58,9 @@ class Ds18b20 : public IoTItem { void doByInterval() { //запускаем опрос измерений у всех датчиков на линии sensors->requestTemperatures(); - + //Определяем адрес. Если парамтер addr не установлен, то узнаем адрес по индексу - // TODO: понять как лучше. в текущей реализации адрес вычисляется каждый раз при опросе шины, это хорошо при отладке, + // TODO: понять как лучше. в текущей реализации адрес вычисляется каждый раз при опросе шины, это хорошо при отладке, // но при постоянном контакте и использовании правильнее генерировать адрес при инициализации модуля. Но тогда нужно перезагружать устройство при новом датчике DeviceAddress deviceAddress; if (_addr == "") { @@ -69,13 +69,15 @@ class Ds18b20 : public IoTItem { string2hex(_addr.c_str(), deviceAddress); } //получаем температуру по адресу - value.valD = sensors->getTempC(deviceAddress); - + value.valD = sensors->getTempC(deviceAddress); + char addrStr[20] = ""; hex2string(deviceAddress, 8, addrStr); - if (value.valD != -127) regEvent(value.valD, "addr: " + String(addrStr)); //обязательный вызов для отправки результата работы - else SerialPrint("E", "Sensor Ds18b20", "Error"); + if (value.valD != -127) + regEvent(value.valD, "addr: " + String(addrStr)); //обязательный вызов для отправки результата работы + else + SerialPrint("E", "Sensor Ds18b20", "Error"); } //======================================================================================================= diff --git a/src/utils/JsonUtils.cpp b/src/utils/JsonUtils.cpp index d191280f..24594d16 100644 --- a/src/utils/JsonUtils.cpp +++ b/src/utils/JsonUtils.cpp @@ -11,85 +11,105 @@ void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String value) { } // new============================================================================== -bool jsonRead(String& json, String key, unsigned long& value) { +bool jsonRead(String& json, String key, unsigned long& value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } ret = false; } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + jsonErrorDetected(); + } ret = false; } value = doc[key].as(); return ret; } -bool jsonRead(String& json, String key, float& value) { +bool jsonRead(String& json, String key, float& value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } ret = false; } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + jsonErrorDetected(); + } ret = false; } value = doc[key].as(); return ret; } -bool jsonRead(String& json, String key, String& value) { +bool jsonRead(String& json, String key, String& value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } ret = false; } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + jsonErrorDetected(); + } ret = false; } value = doc[key].as(); return ret; } -bool jsonRead(String& json, String key, bool& value) { +bool jsonRead(String& json, String key, bool& value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } ret = false; } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + jsonErrorDetected(); + } ret = false; } value = doc[key].as(); return ret; } -bool jsonRead(String& json, String key, int& value) { +bool jsonRead(String& json, String key, int& value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } ret = false; } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + jsonErrorDetected(); + } ret = false; } value = doc[key].as(); @@ -97,13 +117,15 @@ bool jsonRead(String& json, String key, int& value) { } // new============================================================================== -bool jsonWriteStr_(String& json, String key, String value) { +bool jsonWriteStr_(String& json, String key, String value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } ret = false; } doc[key] = value; @@ -112,13 +134,15 @@ bool jsonWriteStr_(String& json, String key, String value) { return ret; } -bool jsonWriteBool_(String& json, String key, bool value) { +bool jsonWriteBool_(String& json, String key, bool value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } ret = false; } doc[key] = value; @@ -127,13 +151,15 @@ bool jsonWriteBool_(String& json, String key, bool value) { return ret; } -bool jsonWriteInt_(String& json, String key, int value) { +bool jsonWriteInt_(String& json, String key, int value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } ret = false; } doc[key] = value; @@ -142,13 +168,15 @@ bool jsonWriteInt_(String& json, String key, int value) { return ret; } -bool jsonWriteFloat_(String& json, String key, float value) { +bool jsonWriteFloat_(String& json, String key, float value, bool e) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } ret = false; } doc[key] = value; @@ -166,7 +194,7 @@ void writeUint8tValueToJsonString(uint8_t* payload, size_t length, size_t header jsonMergeObjects(json, payloadStr); } -bool jsonMergeObjects(String& json1, String& json2) { +bool jsonMergeObjects(String& json1, String& json2, bool e) { bool ret = true; DynamicJsonDocument doc1(JSON_BUFFER_SIZE); DeserializationError error1 = deserializeJson(doc1, json1); @@ -174,8 +202,10 @@ bool jsonMergeObjects(String& json1, String& json2) { DeserializationError error2 = deserializeJson(doc2, json2); jsonMergeDocs(doc1.as(), doc2.as()); if (error1 || error2) { - SerialPrint("EE", F("json"), "jsonMergeObjects error"); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("json"), "jsonMergeObjects error"); + jsonErrorDetected(); + } ret = false; } json1 = ""; @@ -190,43 +220,51 @@ void jsonMergeDocs(JsonObject dest, JsonObjectConst src) { } // depricated====================================================================== -String jsonReadStr(String& json, String name) { +String jsonReadStr(String& json, String name, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } } return doc[name].as(); } -boolean jsonReadBool(String& json, String name) { +boolean jsonReadBool(String& json, String name, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } } return doc[name].as(); } -int jsonReadInt(String& json, String name) { +int jsonReadInt(String& json, String name, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } } return doc[name].as(); } // depricated======================================================================== -String jsonWriteStr(String& json, String name, String value) { +String jsonWriteStr(String& json, String name, String value, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } } doc[name] = value; json = ""; @@ -234,12 +272,14 @@ String jsonWriteStr(String& json, String name, String value) { return json; } -String jsonWriteBool(String& json, String name, boolean value) { +String jsonWriteBool(String& json, String name, boolean value, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } } doc[name] = value; json = ""; @@ -247,12 +287,14 @@ String jsonWriteBool(String& json, String name, boolean value) { return json; } -String jsonWriteInt(String& json, String name, int value) { +String jsonWriteInt(String& json, String name, int value, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } } doc[name] = value; json = ""; @@ -260,12 +302,14 @@ String jsonWriteInt(String& json, String name, int value) { return json; } -String jsonWriteFloat(String& json, String name, float value) { +String jsonWriteFloat(String& json, String name, float value, bool e) { DynamicJsonDocument doc(JSON_BUFFER_SIZE); DeserializationError error = deserializeJson(doc, json); if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - jsonErrorDetected(); + if (e) { + SerialPrint("EE", F("jsonWrite"), error.f_str()); + jsonErrorDetected(); + } } doc[name] = value; json = ""; diff --git a/src/utils/SerialPrint.cpp b/src/utils/SerialPrint.cpp index d81980ef..7a2e9b40 100644 --- a/src/utils/SerialPrint.cpp +++ b/src/utils/SerialPrint.cpp @@ -5,7 +5,9 @@ void SerialPrint(String errorLevel, String module, String msg) { String tosend = prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg; Serial.println(tosend); - if (jsonReadInt(settingsFlashJson, F("log")) != 0) { - standWebSocket.broadcastTXT("/log|" + tosend); + if (isNetworkActive()) { + if (jsonReadInt(settingsFlashJson, F("log")) != 0) { + standWebSocket.broadcastTXT("/log|" + tosend); + } } } \ No newline at end of file