Merge pull request #246 from biveraxe/ver4dev

Добавляем хук для возможности реагирования на сообщения из Mqtt +
This commit is contained in:
2022-11-25 13:47:23 +03:00
committed by GitHub
7 changed files with 56 additions and 32 deletions

View File

@@ -51,6 +51,7 @@ class IoTItem {
// хуки для системных событий // хуки для системных событий
virtual void onRegEvent(IoTItem* item); virtual void onRegEvent(IoTItem* item);
virtual void onMqttRecive(char* topic, uint8_t* payload, size_t length);
//методы для графиков //методы для графиков
virtual void publishValue(); virtual void publishValue();

View File

@@ -51,7 +51,7 @@ class IoTScenario {
int GetTokPrecedence(); int GetTokPrecedence();
/// Error* - Это небольшие вспомогательные функции для обработки ошибок. /// Error* - Это небольшие вспомогательные функции для обработки ошибок.
ExprAST *Error(const char *Str); ExprAST *Error(const String& Str);
/// identifierexpr /// identifierexpr
/// ::= identifier /// ::= identifier

View File

@@ -117,6 +117,11 @@ void mqttSubscribe() {
} }
void mqttCallback(char* topic, uint8_t* payload, size_t length) { void mqttCallback(char* topic, uint8_t* payload, size_t length) {
// распространяем принятое сообщение через хуки
for (std::list<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
(*it)->onMqttRecive(topic, payload, length);
}
String topicStr = String(topic); String topicStr = String(topic);
// SerialPrint("i", "=>MQTT", topicStr); // SerialPrint("i", "=>MQTT", topicStr);
String payloadStr; String payloadStr;
@@ -188,7 +193,7 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
// loadScenario(); // loadScenario();
// SerialPrint("i", F("=>MQTT"), F("Scenario received")); // SerialPrint("i", F("=>MQTT"), F("Scenario received"));
// } // }
//} //}
} }
boolean publish(const String& topic, const String& data) { boolean publish(const String& topic, const String& data) {

View File

@@ -175,6 +175,8 @@ void IoTItem::checkIntFromNet() {
void IoTItem::onRegEvent(IoTItem* item) {} void IoTItem::onRegEvent(IoTItem* item) {}
void IoTItem::onMqttRecive(char* topic, uint8_t* payload, size_t length) {}
void IoTItem::publishValue() {} void IoTItem::publishValue() {}
void IoTItem::clearValue() {} void IoTItem::clearValue() {}

View File

@@ -296,7 +296,7 @@ class CallExprAST : public ExprAST {
//if (!ItemIsLocal) Item = findIoTItem(Callee); // пробуем найти переменную если она не локальная (могла придти по сети в процессе) //if (!ItemIsLocal) Item = findIoTItem(Callee); // пробуем найти переменную если она не локальная (могла придти по сети в процессе)
if (!Item) return nullptr; // ret = zeroIotVal; // если все же не пришла, то либо опечатка, либо уже стерлась - выходим if (!Item) return nullptr; // ret = zeroIotVal; // если все же не пришла, то либо опечатка, либо уже стерлась - выходим
if (Cmd == "getIntFromNet") { if (Cmd == F("getIntFromNet")) {
ret.valD = Item->getIntFromNet(); ret.valD = Item->getIntFromNet();
ret.isDecimal = true; ret.isDecimal = true;
return &ret; return &ret;
@@ -467,43 +467,43 @@ class SysCallExprAST : public ExprAST {
public: public:
SysCallExprAST(const String &callee, std::vector<ExprAST *> &args) SysCallExprAST(const String &callee, std::vector<ExprAST *> &args)
: Callee(callee), Args(args) { : Callee(callee), Args(args) {
if (Callee == "reboot") if (Callee == F("reboot"))
operation = sysop_reboot; operation = sysop_reboot;
else if (Callee == "digitalRead") else if (Callee == F("digitalRead"))
operation = sysop_digitalRead; operation = sysop_digitalRead;
else if (Callee == "analogRead") else if (Callee == F("analogRead"))
operation = sysop_analogRead; operation = sysop_analogRead;
else if (Callee == "digitalWrite") else if (Callee == F("digitalWrite"))
operation = sysop_digitalWrite; operation = sysop_digitalWrite;
else if (Callee == "digitalInvert") else if (Callee == F("digitalInvert"))
operation = sysop_digitalInvert; operation = sysop_digitalInvert;
else if (Callee == "deepSleep") else if (Callee == F("deepSleep"))
operation = sysop_deepSleep; operation = sysop_deepSleep;
else if (Callee == "getTime") else if (Callee == F("getTime"))
operation = sysop_getTime; operation = sysop_getTime;
else if (Callee == "getHours") else if (Callee == F("getHours"))
operation = sysop_getHours; operation = sysop_getHours;
else if (Callee == "getMinutes") else if (Callee == F("getMinutes"))
operation = sysop_getMinutes; operation = sysop_getMinutes;
else if (Callee == "getSeconds") else if (Callee == F("getSeconds"))
operation = sysop_getSeconds; operation = sysop_getSeconds;
else if (Callee == "getMonth") else if (Callee == F("getMonth"))
operation = sysop_getMonth; operation = sysop_getMonth;
else if (Callee == "getDay") else if (Callee == F("getDay"))
operation = sysop_getDay; operation = sysop_getDay;
else if (Callee == "getRSSI") else if (Callee == F("getRSSI"))
operation = sysop_getRSSI; operation = sysop_getRSSI;
else if (Callee == "getIP") else if (Callee == F("getIP"))
operation = sysop_getIP; operation = sysop_getIP;
else if (Callee == "mqttPub") else if (Callee == F("mqttPub"))
operation = sysop_mqttPub; operation = sysop_mqttPub;
else if (Callee == "gethhmm") else if (Callee == F("gethhmm"))
operation = sysop_gethhmm; operation = sysop_gethhmm;
else if (Callee == "gethhmmss") else if (Callee == F("gethhmmss"))
operation = sysop_gethhmmss; operation = sysop_gethhmmss;
else if (Callee == "getTime") else if (Callee == F("getTime"))
operation = sysop_getTime; operation = sysop_getTime;
else if (Callee == "getUptime") else if (Callee == F("getUptime"))
operation = sysop_getUptime; operation = sysop_getUptime;
else else
operation = sysop_notfound; operation = sysop_notfound;
@@ -775,7 +775,6 @@ int IoTScenario::gettok() {
/// токен, просматриваемый парсером. getNextToken получает следующий токен от /// токен, просматриваемый парсером. getNextToken получает следующий токен от
/// лексического анализатора и обновляет CurTok. /// лексического анализатора и обновляет CurTok.
int IoTScenario::getNextToken() { int IoTScenario::getNextToken() {
scenario_yield();
return CurTok = gettok(); return CurTok = gettok();
} }
@@ -791,8 +790,8 @@ int IoTScenario::GetTokPrecedence() {
} }
/// Error* - Это небольшие вспомогательные функции для обработки ошибок. /// Error* - Это небольшие вспомогательные функции для обработки ошибок.
ExprAST *IoTScenario::Error(const char *Str) { ExprAST *IoTScenario::Error(const String& Str) {
Serial.printf("Scenario error in line %d: %s\n", curLine, Str); Serial.printf("Scenario error in line %d: %s\n", curLine, Str.c_str());
isIotScenException = true; isIotScenException = true;
return nullptr; return nullptr;
} }
@@ -835,7 +834,7 @@ ExprAST *IoTScenario::ParseIdentifierExpr(String *IDNames, bool callFromConditio
if (CurTok == ')') break; if (CurTok == ')') break;
if (CurTok != ',') { if (CurTok != ',') {
return Error("Expected ')' or ',' in argument list"); return Error(F("Expected ')' or ',' in argument list"));
} }
getNextToken(); getNextToken();
} }
@@ -892,7 +891,7 @@ ExprAST *IoTScenario::ParseBracketsExpr(String *IDNames, bool callFromCondition)
// int ttok = getNextToken(); // int ttok = getNextToken();
if (CurTok == tok_eof) { if (CurTok == tok_eof) {
return Error("Expected '}'"); return Error(F("Expected '}'"));
} }
} }
@@ -947,7 +946,7 @@ ExprAST *IoTScenario::ParsePrimary(String *IDNames, bool callFromCondition) {
switch (CurTok) { switch (CurTok) {
default: default:
Serial.println(CurTok); Serial.println(CurTok);
return Error("unknown token when expecting an expression"); return Error(F("unknown token when expecting an expression"));
case tok_identifier: { case tok_identifier: {
if (callFromCondition && IDNames) { if (callFromCondition && IDNames) {
String tmpstr = *IDNames; String tmpstr = *IDNames;
@@ -1019,13 +1018,13 @@ void IoTScenario::loadScenario(String fileName) { // подготавливае
if (file) file.close(); if (file) file.close();
file = FileFS.open(fileName.c_str(), "r"); file = FileFS.open(fileName.c_str(), "r");
if (!file) { if (!file) {
Error("Open file scenario error"); Error(F("Open file scenario error"));
return; return;
} }
} else if (mode == 1) { } else if (mode == 1) {
file = FileFS.open(fileName.c_str(), "r"); file = FileFS.open(fileName.c_str(), "r");
if (!file) { if (!file) {
Error("Open file scenario error"); Error(F("Open file scenario error"));
return; return;
} }
strFromFile = file.readString(); strFromFile = file.readString();

View File

@@ -56,6 +56,23 @@
"descr": "Введите текст", "descr": "Введите текст",
"int": "0", "int": "0",
"val": "текст" "val": "текст"
},
{
"global": 0,
"name": "Вывод значения",
"type": "Reading",
"subtype": "Variable",
"id": "vout",
"needSave": 0,
"widget": "anydataDef",
"page": "Вывод",
"descr": "Значение",
"int": "0",
"val": "0.0",
"map": "1024,1024,1,100",
"plus": 0,
"multiply": 1,
"round": 0
} }
], ],
"about": { "about": {

View File

@@ -13,7 +13,7 @@ void SerialPrint(const String& errorLevel, const String& module, const String& m
if (isNetworkActive()) { if (isNetworkActive()) {
if (jsonReadInt(settingsFlashJson, F("log")) != 0) { if (jsonReadInt(settingsFlashJson, F("log")) != 0) {
sendStringToWs("corelg", tosend, -1); sendStringToWs(F("corelg"), tosend, -1);
} }
} }
@@ -21,7 +21,7 @@ void SerialPrint(const String& errorLevel, const String& module, const String& m
cleanString(tosend); cleanString(tosend);
// создаем событие об ошибке для возможной реакции в сценарии // создаем событие об ошибке для возможной реакции в сценарии
if (itemId != "") { if (itemId != "") {
createItemFromNet(itemId + "_onError", tosend, -4); createItemFromNet(itemId + F("_onError"), tosend, -4);
} else { } else {
// createItemFromNet("onError", tosend, -4); // createItemFromNet("onError", tosend, -4);
} }