diff --git a/include/Global.h b/include/Global.h index a8ae38d9..fb0e535f 100644 --- a/include/Global.h +++ b/include/Global.h @@ -139,7 +139,7 @@ extern Time_t _time_local; extern Time_t _time_utc; extern bool _time_isTrust; -extern unsigned long loopPeriod; +//extern unsigned long loopPeriod; // extern DynamicJsonDocument settingsFlashJsonDoc; // extern DynamicJsonDocument paramsFlashJsonDoc; diff --git a/include/classes/IoTItem.h b/include/classes/IoTItem.h index 39c5fbbd..fa8533a8 100644 --- a/include/classes/IoTItem.h +++ b/include/classes/IoTItem.h @@ -26,8 +26,9 @@ class IoTItem { String getID(); int getIntFromNet(); virtual String getValue(); + long getInterval(); - void setInterval(unsigned long interval); + void setInterval(long interval); void setIntFromNet(int interval); unsigned long currentMillis; @@ -45,6 +46,10 @@ class IoTItem { virtual void setValue(const IoTValue& Value, bool genEvent = true); virtual void setValue(const String& valStr, bool genEvent = true); String getRoundValue(); + void getNetEvent(String& event); + + // хуки для системных событий + virtual void onRegEvent(IoTItem* item); //методы для графиков virtual void publishValue(); @@ -56,8 +61,8 @@ class IoTItem { protected: bool _needSave = false; // признак необходимости сохранять и загружать значение элемента на flash String _subtype = ""; - String _id = ""; - unsigned long _interval = 1000; + String _id = "errorId"; // если будет попытка создания Item без указания id, то элемент оставит это значение + long _interval = 0; int _intFromNet = -2; // количество секунд доверия, пришедших из сети вместе с данными для текущего ИД // -2 - данные не приходили, скорее всего, элемент локальный, доверие есть // -1 - данные приходили и обратный отсчет дошел до нуля, значит доверия нет @@ -79,6 +84,8 @@ bool isItemExist(const String& name); // суще StaticJsonDocument* getLocalItemsAsJSON(); // сбор всех локальных значений Items IoTItem* createItemFromNet(const String& itemId, const String& value, int interval); +IoTItem* createItemFromNet(const String& msgFromNet); +void analyzeMsgFromNet(const String& msg, String altId = ""); // class externalVariable : IoTItem { // объект, создаваемый при получении информации о событии на другом контроллере для хранения информации о событии указанное время diff --git a/include/classes/IoTScenario.h b/include/classes/IoTScenario.h index 9e14a92c..c1a6cf83 100644 --- a/include/classes/IoTScenario.h +++ b/include/classes/IoTScenario.h @@ -8,7 +8,7 @@ class ExprAST { virtual ~ExprAST(); virtual IoTValue *exec(); virtual int setValue(IoTValue *val, bool generateEvent); // ret 0 - установка значения не поддерживается наследником - virtual bool hasEventIdName(String eventIdName); + virtual bool hasEventIdName(const String& eventIdName); }; class IoTScenario { @@ -93,7 +93,7 @@ class IoTScenario { public: void loadScenario(String fileName); - void exec(String eventIdName); + void exec(const String& eventIdName); IoTScenario(); ~IoTScenario(); diff --git a/include/utils/JsonUtils.h b/include/utils/JsonUtils.h index 8418163f..a9810dc2 100644 --- a/include/utils/JsonUtils.h +++ b/include/utils/JsonUtils.h @@ -10,7 +10,7 @@ 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(const String& json, String key, unsigned long& value, bool e = true); +extern bool jsonRead(const String& json, String key, long& value, bool e = true); extern bool jsonRead(const String& json, String key, float& value, bool e = true); extern bool jsonRead(const String& json, String key, String& value, bool e = true); extern bool jsonRead(const String& json, String key, bool& value, bool e = true); diff --git a/include/utils/StringUtils.h b/include/utils/StringUtils.h index 7f5b7f90..816d8353 100644 --- a/include/utils/StringUtils.h +++ b/include/utils/StringUtils.h @@ -43,3 +43,5 @@ String prettyBytes(size_t size); String uint64ToString(uint64_t input, uint8_t base = 10); void cleanString(String& str); + +unsigned char ChartoHex(char ch); diff --git a/src/Global.cpp b/src/Global.cpp index 2be45040..309e379a 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -70,7 +70,7 @@ String mqttRootDevice = ""; unsigned long unixTime = 0; unsigned long unixTimeShort = 0; -unsigned long loopPeriod; +//unsigned long loopPeriod; bool isTimeSynch = false; Time_t _time_local; diff --git a/src/Main.cpp b/src/Main.cpp index 3ffb623f..6961e6a1 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -89,7 +89,7 @@ void setup() { iotScen.loadScenario("/scenario.txt"); // создаем событие завершения конфигурирования для возможности выполнения блока кода при загрузке - createItemFromNet("onStart", "1", 1); + createItemFromNet("onStart", "1", -4); stInit(); @@ -105,6 +105,8 @@ void setup() { // проверяем все элементы на тухлость for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { (*it)->checkIntFromNet(); + + Serial.printf("[ITEM] size: %d, id: %s, int: %d, intnet: %d\n", sizeof(**it), (*it)->getID(), (*it)->getInterval(), (*it)->getIntFromNet()); } }, nullptr, true); @@ -162,10 +164,10 @@ void loop() { handleOrder(); handleEvent(); -#ifdef LOOP_DEBUG - loopPeriod = millis() - st; - if (loopPeriod > 2) Serial.println(loopPeriod); -#endif +// #ifdef LOOP_DEBUG +// loopPeriod = millis() - st; +// if (loopPeriod > 2) Serial.println(loopPeriod); +// #endif } //отправка json diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp index 234753dc..28d37249 100644 --- a/src/MqttClient.cpp +++ b/src/MqttClient.cpp @@ -166,30 +166,8 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) { if (topicStr.indexOf(chipId) == -1) { String devId = selectFromMarkerToMarker(topicStr, "/", 2); String id = selectFromMarkerToMarker(topicStr, "/", 3); - String valAsStr; - if (!jsonRead(payloadStr, F("val"), valAsStr, false)) valAsStr = payloadStr; - - unsigned long interval = 0; - jsonRead(payloadStr, F("int"), interval); - IoTItem* itemExist = findIoTItem(id); - if (itemExist) { - itemExist->setInterval(interval); // устанавливаем такой же интервал как на источнике события - itemExist->setValue(valAsStr, false); // только регистрируем изменения в интерфейсе без создания цикла сетевых событий - if (interval) itemExist->setIntFromNet(interval+5); // если пришедший интервал =0, значит не нужно контролировать доверие, иначе даем фору в 5 сек - } else { - // зафиксируем данные в базе, если локально элемент отсутствует - //itemExist = (IoTItem*)new externalVariable(payloadStr); - //IoTItems.push_back(itemExist); - - itemExist = new IoTItem(payloadStr); - itemExist->setIntFromNet(interval+5); // устанавливаем время жизни 3 сек - itemExist->iAmLocal = false; - IoTItems.push_back(itemExist); - } - // запустим проверку его в сценариях - generateEvent(id, valAsStr); - SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + id + " " + valAsStr); - + analyzeMsgFromNet(payloadStr, id); + //SerialPrint("i", F("=>MQTT"), "Received event from other device: '" + devId + "' " + id + " " + valAsStr); } } diff --git a/src/WsServer.cpp b/src/WsServer.cpp index ca80bde8..a3901634 100644 --- a/src/WsServer.cpp +++ b/src/WsServer.cpp @@ -113,7 +113,7 @@ void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) configure("/config.json"); iotScen.loadScenario("/scenario.txt"); // создаем событие завершения конфигурирования для возможности выполнения блока кода при загрузке - createItemFromNet("onStart", "1", 1); + createItemFromNet("onStart", "1", -4); } //----------------------------------------------------------------------// diff --git a/src/classes/IoTItem.cpp b/src/classes/IoTItem.cpp index bc6c98fd..4a4e3721 100644 --- a/src/classes/IoTItem.cpp +++ b/src/classes/IoTItem.cpp @@ -7,8 +7,8 @@ //получение параметров в экземпляр класса IoTItem::IoTItem(const String& parameters) { - jsonRead(parameters, F("int"), _interval); - if (_interval == 0) enableDoByInt = false; + jsonRead(parameters, F("int"), _interval, false); + if (_interval <= 0) enableDoByInt = false; _interval = _interval * 1000; jsonRead(parameters, F("subtype"), _subtype, false); jsonRead(parameters, F("id"), _id); @@ -57,6 +57,8 @@ String IoTItem::getValue() { return value.valS; } +long IoTItem::getInterval() { return _interval; } + //определяем тип прилетевшей величины void IoTItem::setValue(const String& valStr, bool genEvent) { value.isDecimal = isDigitDotCommaStr(valStr); @@ -89,10 +91,15 @@ void IoTItem::regEvent(const String& value, const String& consoleInfo, bool erro publishStatusMqtt(_id, value); publishStatusWs(_id, value); //SerialPrint("i", "Sensor", consoleInfo + " '" + _id + "' data: " + value + "'"); - + if (genEvent) { generateEvent(_id, value); + // распространяем событие через хуки + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { + (*it)->onRegEvent(this); + } + //отправка события другим устройствам в сети если не было ошибки============================== if (jsonReadBool(settingsFlashJson, "mqttin") && _global && !error) { String json = "{}"; @@ -141,6 +148,13 @@ int IoTItem::getIntFromNet() { return _intFromNet; } +void IoTItem::getNetEvent(String& event) { + event = "{}"; + jsonWriteStr_(event, "id", _id); + jsonWriteStr_(event, "val", getValue()); + jsonWriteInt_(event, "int", _interval/1000); +} + void IoTItem::setIntFromNet(int interval) { _intFromNet = interval; } @@ -157,6 +171,8 @@ void IoTItem::checkIntFromNet() { } } +void IoTItem::onRegEvent(IoTItem* item) {} + void IoTItem::publishValue() {} void IoTItem::clearValue() {} @@ -171,7 +187,7 @@ String IoTItem::getID() { return _id; }; -void IoTItem::setInterval(unsigned long interval) { +void IoTItem::setInterval(long interval) { _interval = interval; } @@ -179,6 +195,7 @@ IoTGpio* IoTItem::getGpioDriver() { return nullptr; } + //сетевое общение==================================================================================================================================== // externalVariable::externalVariable(const String& parameters) : IoTItem(parameters) { @@ -201,6 +218,7 @@ IoTItem* myIoTItem; // поиск элемента модуля в существующей конфигурации IoTItem* findIoTItem(const String& name) { + if (name == "") return nullptr; for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { if ((*it)->getID() == name) return *it; } @@ -225,6 +243,7 @@ bool isItemExist(const String& name) { return false; } +// создаем временную копию элемента из сети на основе события IoTItem* createItemFromNet(const String& itemId, const String& value, int interval) { String jsonStr = "{\"id\":\""; jsonStr += itemId; @@ -234,14 +253,38 @@ IoTItem* createItemFromNet(const String& itemId, const String& value, int interv jsonStr += interval; jsonStr += "}"; - IoTItem *tmpp = new IoTItem(jsonStr); - tmpp->setIntFromNet(interval); // устанавливаем время жизни 3 сек + return createItemFromNet(jsonStr); +} + +// создаем временную копию элемента из сети на основе события +IoTItem* createItemFromNet(const String& msgFromNet) { + IoTItem *tmpp = new IoTItem(msgFromNet); + if (tmpp->getInterval()) tmpp->setIntFromNet(tmpp->getInterval()/1000 + 5); tmpp->iAmLocal = false; IoTItems.push_back(tmpp); - generateEvent(itemId, "1"); + generateEvent(tmpp->getID(), tmpp->getValue()); return tmpp; } +void analyzeMsgFromNet(const String& msg, String altId) { + if (!jsonRead(msg, F("id"), altId, altId == "") && altId == "") return; // ничего не предпринимаем, если ошибка и altId = "", вообще данная конструкция нужна для совместимости с форматом данных 3 версией + IoTItem* itemExist = findIoTItem(altId); + if (itemExist) { + String valAsStr = msg; + jsonRead(msg, F("val"), valAsStr, false); + long interval = 0; + jsonRead(msg, F("int"), interval, false); + + itemExist->setInterval(interval); // устанавливаем такой же интервал как на источнике события + itemExist->setValue(valAsStr, false); // только регистрируем изменения в интерфейсе без создания цикла сетевых событий + if (interval) itemExist->setIntFromNet(interval+5); // если пришедший интервал =0, значит не нужно контролировать доверие, иначе даем фору в 5 сек + generateEvent(altId, valAsStr); + } else { + // временно зафиксируем данные в базе, если локально элемент отсутствует + createItemFromNet(msg); + } +} + StaticJsonDocument docForExport; StaticJsonDocument* getLocalItemsAsJSON() { diff --git a/src/classes/IoTScenario.cpp b/src/classes/IoTScenario.cpp index 3175ef17..39d4954a 100644 --- a/src/classes/IoTScenario.cpp +++ b/src/classes/IoTScenario.cpp @@ -37,7 +37,7 @@ enum Token { ExprAST::~ExprAST() {} IoTValue *ExprAST::exec() { return nullptr; } int ExprAST::setValue(IoTValue *val, bool generateEvent) { return 0; } // 0 - установка значения не поддерживается наследником -bool ExprAST::hasEventIdName(String eventIdName) { return false; } // по умолчанию все узлы не связаны с ИД события, для которого выполняется сценарий +bool ExprAST::hasEventIdName(const String& eventIdName) { return false; } // по умолчанию все узлы не связаны с ИД события, для которого выполняется сценарий // struct IoTValue zeroIotVal; /// NumberExprAST - Класс узла выражения для числовых литералов (Например, "1.0"). @@ -543,7 +543,7 @@ class IfExprAST : public ExprAST { _IDNames = ""; } - bool hasEventIdName(String eventIdName) { + bool hasEventIdName(const String& eventIdName) { // Serial.printf("Call from BinaryExprAST _IDNames:%s\n", _IDNames.c_str()); return _IDNames.indexOf(" " + eventIdName + " ") >= 0; // определяем встречался ли ИД, для которого исполняем сценарий в выражении IF } @@ -1026,7 +1026,7 @@ void IoTScenario::loadScenario(String fileName) { // подготавливае } } -void IoTScenario::exec(String eventIdName) { // посимвольно считываем и сразу интерпретируем сценарий в дерево AST +void IoTScenario::exec(const String& eventIdName) { // посимвольно считываем и сразу интерпретируем сценарий в дерево AST if (mode == 0 && !file) return; LastChar = 0; diff --git a/src/modules/exec/ButtonIn/ButtonIn.cpp b/src/modules/exec/ButtonIn/ButtonIn.cpp index 18e8a87f..204fcbd4 100644 --- a/src/modules/exec/ButtonIn/ButtonIn.cpp +++ b/src/modules/exec/ButtonIn/ButtonIn.cpp @@ -12,7 +12,7 @@ class ButtonIn : public IoTItem { String _pinMode; int _lastButtonState = LOW; unsigned long _lastDebounceTime = 0; - unsigned long _debounceDelay = 50; + long _debounceDelay = 50; int _buttonState; int _reading; diff --git a/src/modules/sensors/UART/Uart.cpp b/src/modules/sensors/UART/Uart.cpp index 052acb61..444dc31f 100644 --- a/src/modules/sensors/UART/Uart.cpp +++ b/src/modules/sensors/UART/Uart.cpp @@ -6,58 +6,143 @@ #include "modules/sensors/UART/Uart.h" #ifdef ESP8266 -SoftwareSerial* myUART = nullptr; + SoftwareSerial* myUART = nullptr; #else -HardwareSerial* myUART = nullptr; + HardwareSerial* myUART = nullptr; #endif class UART : public IoTItem { private: - int tx; - int rx; - int speed; + int _tx; + int _rx; + int _speed; + int _eventFormat = 0; // 0 - нет приема, 1 - json IoTM, 2 - Nextion + +#ifdef ESP8266 + SoftwareSerial* _myUART = nullptr; +#else + HardwareSerial* _myUART = nullptr; +#endif public: UART(String parameters) : IoTItem(parameters) { - tx = jsonReadInt(parameters, "tx"); - rx = jsonReadInt(parameters, "rx"); - speed = jsonReadInt(parameters, "speed"); + jsonRead(parameters, "tx", _tx); + jsonRead(parameters, "rx", _rx); + jsonRead(parameters, "speed", _speed); + jsonRead(parameters, "eventFormat", _eventFormat); - if (!myUART) { #ifdef ESP8266 - myUART = new SoftwareSerial(tx, rx); - myUART->begin(speed); + myUART = _myUART = new SoftwareSerial(_tx, _rx); + _myUART->begin(_speed); #endif #ifdef ESP32 - myUART = new HardwareSerial(2); - myUART->begin(speed, SERIAL_8N1, rx, tx); + _myUART = new HardwareSerial(2); + _myUART->begin(speed, SERIAL_8N1, rx, tx); #endif + } + + // проверяем формат и если событие, то регистрируем его + void analyzeString(const String& msg) { + switch (_eventFormat) { + case 0: // не указан формат, значит все полученные данные воспринимаем как общее значение из UART + setValue(msg); + break; + + case 1: // формат событий IoTM с использованием json, значит создаем временную копию + analyzeMsgFromNet(msg); + break; + + case 2: // формат команд от Nextion ID=Value + String id = selectToMarker(msg, "="); + IoTItem *item = findIoTItem(id); + if (!item) return; + String valStr = selectToMarkerLast(msg, "="); + valStr.replace("\"", ""); + item->setValue(valStr); + break; } - SerialPrint("i", F("UART"), F("UART Init")); } void uartHandle() { - if (myUART) { - static String incStr; - if (myUART->available()) { - char inc; - inc = myUART->read(); - incStr += inc; - if (inc == '\n') { - parse(incStr); - incStr = ""; - } + if (!_myUART) return; + + if (_myUART->available()) { + static String inStr = ""; + char inc; + inc = _myUART->read(); + inStr += inc; + if (inc == '\n') { + analyzeString(inStr); + inStr = ""; } } } - void parse(String& incStr) { - SerialPrint("I", "=>UART", incStr); + void onRegEvent(IoTItem* eventItem) { + if (!_myUART) return; + + String printStr = ""; + switch (_eventFormat) { + case 0: return; // не указан формат, значит не следим за событиями + case 1: // формат событий IoTM с использованием json + eventItem->getNetEvent(printStr); + _myUART->println(printStr); + break; + + case 2: // формат событий для Nextion ID=Value0xFF0xFF0xFF + printStr += eventItem->getID(); + printStr += "="; + if (eventItem->value.isDecimal) + printStr += eventItem->value.valD; + else { + printStr += "\""; + printStr += eventItem->value.valS; + printStr += "\""; + } + _myUART->print(printStr); + _myUART->write(0xff); + _myUART->write(0xff); + _myUART->write(0xff); + break; + } } - void uartPrint(String msg) { - myUART->print(msg); + virtual void loop() { + uartHandle(); } + + void uartPrint(const String& msg) { + if (_myUART) { + _myUART->println(msg); + } + } + + void uartPrintHex(const String& msg) { + if (!_myUART) return; + + unsigned char Hi, Lo; + uint8_t byteTx; + const char* strPtr = msg.c_str(); + while ((Hi = *strPtr++) && (Lo = *strPtr++)) { + byteTx = (ChartoHex(Hi) << 4) | ChartoHex(Lo); + _myUART->write(byteTx); + } + } + + IoTValue execute(String command, std::vector ¶m) { + if (command == "print") { + if (param.size() == 1) { + uartPrint(param[0].valS); + } + } else if (command == "printHex") { + if (param.size() == 1) { + uartPrintHex(param[0].valS); + } + } + + return {}; + } + }; void* getAPI_UART(String subtype, String param) { diff --git a/src/modules/sensors/UART/modinfo.json b/src/modules/sensors/UART/modinfo.json index ff4f9710..02a35f33 100644 --- a/src/modules/sensors/UART/modinfo.json +++ b/src/modules/sensors/UART/modinfo.json @@ -2,7 +2,6 @@ "menuSection": "Сенсоры", "configItem": [ { - "global": 0, "name": "UART", "type": "Reading", "subtype": "UART", @@ -12,7 +11,8 @@ "id": "u", "tx": 12, "rx": 13, - "speed": 9600 + "speed": 9600, + "eventFormat": 0 } ], "about": { @@ -30,11 +30,12 @@ "SoftUART" ], "title": "Software uart для esp8266 или hardware uart для esp32", - "moduleDesc": "Используется вместе с Pzem004t или с другими работающими по uart сенсорами, в последствии будет доработан для связи с arduino платами", + "moduleDesc": "Используется вместе с Pzem004t или с другими работающими по uart сенсорами. Пригоден для обмена данными с другими контроллерами в ручном режиме или с автоматической трансляцией событий как по сети.", "propInfo": { "tx": "TX пин", "rx": "RX пин", - "speed": "Скорость UART" + "speed": "Скорость UART", + "eventFormat": "Выбор формата обмена сообщениями с другими контроллерами. =0 - не указан формат, значит не следим за событиями, =1 - формат событий IoTM с использованием json, =2 - формат событий для Nextion отправка событий: ID=Value0xFF0xFF0xFF прием ордеров: ID=Value" } }, "defActive": true, diff --git a/src/modules/virtual/Loging/Loging.cpp b/src/modules/virtual/Loging/Loging.cpp index a189d046..9fb21aec 100644 --- a/src/modules/virtual/Loging/Loging.cpp +++ b/src/modules/virtual/Loging/Loging.cpp @@ -22,7 +22,7 @@ class Loging : public IoTItem { String prevDate = ""; bool firstTimeDate = true; - unsigned long interval; + long interval; public: Loging(String parameters) : IoTItem(parameters) { diff --git a/src/modules/virtual/LogingDaily/LogingDaily.cpp b/src/modules/virtual/LogingDaily/LogingDaily.cpp index 05981d39..50ed724f 100644 --- a/src/modules/virtual/LogingDaily/LogingDaily.cpp +++ b/src/modules/virtual/LogingDaily/LogingDaily.cpp @@ -21,7 +21,7 @@ class LogingDaily : public IoTItem { String prevDate = ""; bool firstTimeDate = true; - unsigned long interval; + long interval; public: LogingDaily(String parameters) : IoTItem(parameters) { diff --git a/src/utils/JsonUtils.cpp b/src/utils/JsonUtils.cpp index ab362ac3..f04f910f 100644 --- a/src/utils/JsonUtils.cpp +++ b/src/utils/JsonUtils.cpp @@ -11,21 +11,23 @@ void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String value) { } // new============================================================================== -bool jsonRead(const String& json, String key, unsigned long& value, bool e) { +bool jsonRead(const String& json, String key, long& value, 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("E", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } return false; } else if (!doc.containsKey(key)) { if (e) { - SerialPrint("EE", F("jsonRead"), key + " missing"); + SerialPrint("E", F("jsonRead"), key + " missing"); jsonErrorDetected(); } return false; } - value = doc[key].as(); + value = doc[key].as(); return true; } @@ -33,12 +35,14 @@ bool jsonRead(const String& json, String key, float& value, 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("E", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } return false; } else if (!doc.containsKey(key)) { if (e) { - SerialPrint("EE", F("jsonRead"), key + " missing"); + SerialPrint("E", F("jsonRead"), key + " missing"); jsonErrorDetected(); } return false; @@ -51,12 +55,14 @@ bool jsonRead(const String& json, String key, String& value, 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("E", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } return false; } else if (!doc.containsKey(key)) { if (e) { - SerialPrint("EE", F("jsonRead"), key + " missing"); + SerialPrint("E", F("jsonRead"), key + " missing"); jsonErrorDetected(); } return false; @@ -76,12 +82,14 @@ bool jsonRead(const String& json, String key, int& value, 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("E", F("jsonRead"), error.f_str()); + jsonErrorDetected(); + } return false; } else if (!doc.containsKey(key)) { if (e) { - SerialPrint("EE", F("jsonRead"), key + " missing"); + SerialPrint("E", F("jsonRead"), key + " missing"); jsonErrorDetected(); } return false; @@ -97,7 +105,7 @@ bool jsonWriteStr_(String& json, const String& key, const String& value, bool e) DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } ret = false; @@ -114,7 +122,7 @@ bool jsonWriteBool_(String& json, const String& key, bool value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } ret = false; @@ -131,7 +139,7 @@ bool jsonWriteInt_(String& json, const String& key, int value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } ret = false; @@ -148,7 +156,7 @@ bool jsonWriteFloat_(String& json, const String &key, float value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } ret = false; @@ -177,7 +185,7 @@ bool jsonMergeObjects(String& json1, String& json2, bool e) { jsonMergeDocs(doc1.as(), doc2.as()); if (error1 || error2) { if (e) { - SerialPrint("EE", F("json"), "jsonMergeObjects error"); + SerialPrint("E", F("json"), "jsonMergeObjects error"); jsonErrorDetected(); } ret = false; @@ -199,7 +207,7 @@ String jsonReadStr(const String& json, String name, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonRead"), error.f_str()); + SerialPrint("E", F("jsonRead"), error.f_str()); jsonErrorDetected(); } } @@ -211,7 +219,7 @@ boolean jsonReadBool(const String& json, String name, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonRead"), error.f_str()); + SerialPrint("E", F("jsonRead"), error.f_str()); jsonErrorDetected(); } } @@ -223,7 +231,7 @@ int jsonReadInt(const String& json, String name, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonRead"), error.f_str()); + SerialPrint("E", F("jsonRead"), error.f_str()); jsonErrorDetected(); } } @@ -236,7 +244,7 @@ String jsonWriteStr(String& json, String name, String value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } } @@ -251,7 +259,7 @@ String jsonWriteBool(String& json, String name, boolean value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } } @@ -266,7 +274,7 @@ String jsonWriteInt(String& json, String name, int value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } } @@ -281,7 +289,7 @@ String jsonWriteFloat(String& json, String name, float value, bool e) { DeserializationError error = deserializeJson(doc, json); if (error) { if (e) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); + SerialPrint("E", F("jsonWrite"), error.f_str()); jsonErrorDetected(); } } diff --git a/src/utils/SerialPrint.cpp b/src/utils/SerialPrint.cpp index 60cc41e1..e633df9c 100644 --- a/src/utils/SerialPrint.cpp +++ b/src/utils/SerialPrint.cpp @@ -23,9 +23,9 @@ void SerialPrint(const String& errorLevel, const String& module, const String& m cleanString(tosend); // создаем событие об ошибке для возможной реакции в сценарии if (itemId != "") { - createItemFromNet(itemId + "_onError", tosend, 2); + createItemFromNet(itemId + "_onError", tosend, -4); } else { - createItemFromNet("onError", tosend, 2); + createItemFromNet("onError", tosend, -4); } } diff --git a/src/utils/StringUtils.cpp b/src/utils/StringUtils.cpp index a2a425d4..4234a68f 100644 --- a/src/utils/StringUtils.cpp +++ b/src/utils/StringUtils.cpp @@ -79,7 +79,7 @@ void hex2string(byte array[], unsigned int len, char buffer[]) { buffer[len * 2] = '\0'; } -inline unsigned char ChartoHex(char ch) { +unsigned char ChartoHex(char ch) { return ((ch >= 'A') ? (ch - 'A' + 0xA) : (ch - '0')) & 0x0F; }