Merge pull request #227 from biveraxe/ver4dev

Расширяем модуль UART для обмена сообщениями с другими МК
This commit is contained in:
2022-11-04 17:04:01 +03:00
committed by GitHub
19 changed files with 238 additions and 112 deletions

View File

@@ -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;

View File

@@ -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<JSON_BUFFER_SIZE>* 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 { // объект, создаваемый при получении информации о событии на другом контроллере для хранения информации о событии указанное время

View File

@@ -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();

View File

@@ -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);

View File

@@ -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);

View File

@@ -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;

View File

@@ -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<IoTItem *>::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

View File

@@ -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);
}
}

View File

@@ -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);
}
//----------------------------------------------------------------------//

View File

@@ -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<IoTItem*>::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<IoTItem*>::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<JSON_BUFFER_SIZE> docForExport;
StaticJsonDocument<JSON_BUFFER_SIZE>* getLocalItemsAsJSON() {

View File

@@ -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;

View File

@@ -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;

View File

@@ -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<IoTValue> &param) {
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) {

View File

@@ -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,

View File

@@ -22,7 +22,7 @@ class Loging : public IoTItem {
String prevDate = "";
bool firstTimeDate = true;
unsigned long interval;
long interval;
public:
Loging(String parameters) : IoTItem(parameters) {

View File

@@ -21,7 +21,7 @@ class LogingDaily : public IoTItem {
String prevDate = "";
bool firstTimeDate = true;
unsigned long interval;
long interval;
public:
LogingDaily(String parameters) : IoTItem(parameters) {

View File

@@ -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<unsigned long>();
value = doc[key].as<long>();
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<JsonObject>(), doc2.as<JsonObject>());
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();
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}