Merge pull request #143 from biveraxe/ver4dev

Добавляем externalVariable для приема и фиксации на время значения события для использования в сценариях
This commit is contained in:
Dmitry Borisenko
2022-02-25 13:59:41 +01:00
committed by GitHub
19 changed files with 78 additions and 33 deletions

View File

@@ -2,7 +2,7 @@
#include "Global.h" #include "Global.h"
#include "classes/IoTItem.h" #include "classes/IoTItem.h"
extern std::vector<IoTItem*> IoTItems; // вектор ссылок базового класса IoTItem - список всех запущенных сенсоров extern std::list<IoTItem*> IoTItems; // вектор ссылок базового класса IoTItem - список всех запущенных сенсоров
extern void configure(String path); extern void configure(String path);
void clearConfigure(); void clearConfigure();

View File

@@ -8,6 +8,7 @@
#include <TickerScheduler.h> #include <TickerScheduler.h>
#include <PubSubClient.h> #include <PubSubClient.h>
#include <StringCommand.h> #include <StringCommand.h>
#include <list>
#ifdef ESP32 #ifdef ESP32
#include "WiFi.h" #include "WiFi.h"

View File

@@ -10,8 +10,7 @@ struct IoTValue {
class IoTItem { class IoTItem {
public: public:
IoTItem(String parameters); IoTItem(String parameters);
~IoTItem(); virtual ~IoTItem() {}
void loop(); void loop();
virtual void doByInterval(); virtual void doByInterval();
virtual IoTValue execute(String command, std::vector<IoTValue> &param); virtual IoTValue execute(String command, std::vector<IoTValue> &param);
@@ -27,6 +26,8 @@ class IoTItem {
unsigned long difference; unsigned long difference;
IoTValue value; // хранение основного значения, котрое обновляется из сценария, execute(), loop() или doByInterval() IoTValue value; // хранение основного значения, котрое обновляется из сценария, execute(), loop() или doByInterval()
bool iAmDead = false; // признак необходимости удалить объект из базы
virtual IoTGpio* getGpioDriver(); virtual IoTGpio* getGpioDriver();
virtual void setValue(IoTValue Value); virtual void setValue(IoTValue Value);
@@ -46,3 +47,13 @@ class IoTItem {
}; };
IoTItem* findIoTItem(String name); // поиск экземпляра элемента модуля по имени IoTItem* findIoTItem(String name); // поиск экземпляра элемента модуля по имени
class externalVariable: IoTItem { // объект, создаваемый при получении информации о событии на другом контроллере для хранения информации о событии указанное время
public:
externalVariable(String parameters);
~externalVariable();
void doByInterval(); // для данного класса doByInterval+int выполняет роль счетчика обратного отсчета до уничтожения
};

View File

@@ -3,7 +3,7 @@
extern IoTGpio IoTgpio; extern IoTGpio IoTgpio;
std::vector<IoTItem*> IoTItems; std::list<IoTItem*> IoTItems;
void* getAPI(String subtype, String params); void* getAPI(String subtype, String params);
void configure(String path) { void configure(String path) {
@@ -38,8 +38,8 @@ void configure(String path) {
void clearConfigure() { void clearConfigure() {
Serial.printf("Start clearing config\n"); Serial.printf("Start clearing config\n");
for (unsigned int i = 0; i < IoTItems.size(); i++) { for (std::list<IoTItem*>::iterator it=IoTItems.begin(); it != IoTItems.end(); ++it) {
if (IoTItems[i]) delete IoTItems[i]; if (*it) delete *it;
} }
IoTItems.clear(); IoTItems.clear();
} }

View File

@@ -56,12 +56,17 @@ void setup() {
//загрузка сценария //загрузка сценария
iotScen.loadScenario("/scenario.txt"); iotScen.loadScenario("/scenario.txt");
iotScen.ExecScenario(""); //iotScen.ExecScenario("");
// test // test
Serial.println("-------test start--------"); Serial.println("-------test start--------");
Serial.println("--------test end---------"); Serial.println("--------test end---------");
// симуляция добавления внешних событий
IoTItems.push_back((IoTItem*) new externalVariable("{\"id\":\"rel1\",\"val\":10,\"int\":20}"));
IoTItems.push_back((IoTItem*) new externalVariable("{\"id\":\"rel4\",\"val\":34,\"int\":30}"));
//тест перебора пинов из расширения //тест перебора пинов из расширения
// for (int i = 109; i < 112; i++) { // for (int i = 109; i < 112; i++) {
// IoTgpio.pinMode(i, OUTPUT); // IoTgpio.pinMode(i, OUTPUT);
@@ -94,8 +99,14 @@ void loop() {
//обновление mqtt //обновление mqtt
mqttLoop(); mqttLoop();
for (unsigned int i = 0; i < IoTItems.size(); i++) { // передаем управление каждому элементу конфигурации для выполнения своих функций
IoTItems[i]->loop(); for (std::list<IoTItem*>::iterator it=IoTItems.begin(); it != IoTItems.end(); ++it) {
(*it)->loop();
if ((*it)->iAmDead) {
delete *it;
IoTItems.erase(it);
break;
}
} }
handleOrder(); handleOrder();

View File

@@ -15,6 +15,13 @@ IoTItem::IoTItem(String parameters) {
jsonRead(parameters, F("plus"), _plus, false); jsonRead(parameters, F("plus"), _plus, false);
jsonRead(parameters, F("round"), _round, false); jsonRead(parameters, F("round"), _round, false);
String valAsStr;
if (jsonRead(parameters, F("val"), valAsStr, false)) // значение переменной или датчика при инициализации если есть в конфигурации
if (value.isDecimal = isDigitDotCommaStr(valAsStr))
value.valD = valAsStr.toFloat();
else
value.valS = valAsStr;
String map; String map;
jsonRead(parameters, F("map"), map, false); jsonRead(parameters, F("map"), map, false);
if (map != "") { if (map != "") {
@@ -24,7 +31,8 @@ IoTItem::IoTItem(String parameters) {
_map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); _map4 = selectFromMarkerToMarker(map, ",", 3).toInt();
} }
} }
IoTItem::~IoTItem() {}
// IoTItem::~IoTItem() {}
String IoTItem::getSubtype() { String IoTItem::getSubtype() {
return _subtype; return _subtype;
@@ -79,8 +87,8 @@ void IoTItem::doByInterval() {}
IoTValue IoTItem::execute(String command, std::vector<IoTValue>& param) { return {}; } IoTValue IoTItem::execute(String command, std::vector<IoTValue>& param) { return {}; }
IoTItem* findIoTItem(String name) { // поиск элемента модуля в существующей конфигурации IoTItem* findIoTItem(String name) { // поиск элемента модуля в существующей конфигурации
for (unsigned int i = 0; i < IoTItems.size(); i++) { for (std::list<IoTItem*>::iterator it=IoTItems.begin(); it != IoTItems.end(); ++it) {
if (IoTItems[i]->getID() == name) return IoTItems[i]; if ((*it)->getID() == name) return *it;
} }
return nullptr; return nullptr;
@@ -96,4 +104,18 @@ void IoTItem::setValue(IoTValue Value) {
value = Value; value = Value;
if (value.isDecimal) regEvent(value.valD, ""); if (value.isDecimal) regEvent(value.valD, "");
else regEvent(value.valS, ""); else regEvent(value.valS, "");
}
externalVariable::externalVariable(String parameters) : IoTItem(parameters) {
prevMillis = millis(); // запоминаем текущее значение таймера для выполения doByInterval после int сек
Serial.printf("Call from externalVariable: parameters %s %d\n", parameters.c_str(), _interval);
}
externalVariable::~externalVariable() {
Serial.printf("Call from ~externalVariable: Im dead\n");
}
void externalVariable::doByInterval() { // для данного класса doByInterval+int выполняет роль счетчика обратного отсчета до уничтожения
iAmDead = true;
} }

View File

@@ -58,7 +58,7 @@ class Ads1115 : public IoTItem {
} }
} }
~Ads1115(); ~Ads1115() {};
}; };

View File

@@ -26,7 +26,7 @@ class Aht20t : public IoTItem {
else SerialPrint("E", "Sensor AHTt", "Error"); else SerialPrint("E", "Sensor AHTt", "Error");
} }
~Aht20t(); ~Aht20t() {};
}; };
@@ -40,7 +40,7 @@ class Aht20h : public IoTItem {
else SerialPrint("E", "Sensor AHTt", "Error"); else SerialPrint("E", "Sensor AHTt", "Error");
} }
~Aht20h(); ~Aht20h() {};
}; };

View File

@@ -40,7 +40,7 @@ class AnalogAdc : public IoTItem {
} }
//======================================================================================================= //=======================================================================================================
~AnalogAdc(); ~AnalogAdc() {};
}; };
//после замены названия сенсора, на функцию можно не обращать внимания //после замены названия сенсора, на функцию можно не обращать внимания

View File

@@ -29,7 +29,7 @@ class Bme280t : public IoTItem {
SerialPrint("E", "Sensor Bme280t", "Error"); SerialPrint("E", "Sensor Bme280t", "Error");
} }
~Bme280t(); ~Bme280t() {};
}; };
class Bme280h : public IoTItem { class Bme280h : public IoTItem {
@@ -49,7 +49,7 @@ class Bme280h : public IoTItem {
SerialPrint("E", "Sensor Bme280h", "Error"); SerialPrint("E", "Sensor Bme280h", "Error");
} }
~Bme280h(); ~Bme280h() {};
}; };
class Bme280p : public IoTItem { class Bme280p : public IoTItem {
@@ -70,7 +70,7 @@ class Bme280p : public IoTItem {
SerialPrint("E", "Sensor Bme280p", "Error"); SerialPrint("E", "Sensor Bme280p", "Error");
} }
~Bme280p(); ~Bme280p() {};
}; };

View File

@@ -29,7 +29,7 @@ class Bmp280t : public IoTItem {
else SerialPrint("E", "Sensor DHTt", "Error"); else SerialPrint("E", "Sensor DHTt", "Error");
} }
~Bmp280t(); ~Bmp280t() {};
}; };
@@ -50,7 +50,7 @@ class Bmp280p : public IoTItem {
} else SerialPrint("E", "Sensor DHTh", "Error"); } else SerialPrint("E", "Sensor DHTh", "Error");
} }
~Bmp280p(); ~Bmp280p() {};
}; };

View File

@@ -47,7 +47,7 @@ class ButtonOut : public IoTItem {
} }
//======================================================================================================= //=======================================================================================================
~ButtonOut(); ~ButtonOut() {};
}; };
void* getAPI_ButtonOut(String subtype, String param) { void* getAPI_ButtonOut(String subtype, String param) {

View File

@@ -29,7 +29,7 @@ class Dht1122t : public IoTItem {
else SerialPrint("E", "Sensor DHTt", "Error"); else SerialPrint("E", "Sensor DHTt", "Error");
} }
~Dht1122t(); ~Dht1122t() {};
}; };
@@ -48,7 +48,7 @@ class Dht1122h : public IoTItem {
else SerialPrint("E", "Sensor DHTh", "Error"); else SerialPrint("E", "Sensor DHTh", "Error");
} }
~Dht1122h(); ~Dht1122h() {};
}; };

View File

@@ -81,7 +81,7 @@ class Ds18b20 : public IoTItem {
} }
//======================================================================================================= //=======================================================================================================
~Ds18b20(){}; ~Ds18b20() {};
}; };
//после замены названия сенсора, на функцию можно не обращать внимания //после замены названия сенсора, на функцию можно не обращать внимания

View File

@@ -24,7 +24,7 @@ class GY21t : public IoTItem {
else SerialPrint("E", "Sensor GY21t", "Error"); else SerialPrint("E", "Sensor GY21t", "Error");
} }
~GY21t(); ~GY21t() {};
}; };
class GY21h : public IoTItem { class GY21h : public IoTItem {
@@ -38,7 +38,7 @@ class GY21h : public IoTItem {
else SerialPrint("E", "Sensor GY21h", "Error"); else SerialPrint("E", "Sensor GY21h", "Error");
} }
~GY21h(); ~GY21h() {};
}; };
void* getAPI_GY21(String subtype, String param) { void* getAPI_GY21(String subtype, String param) {

View File

@@ -25,7 +25,7 @@ class Hdc1080t : public IoTItem {
else SerialPrint("E", "Sensor Hdc1080t", "Error"); else SerialPrint("E", "Sensor Hdc1080t", "Error");
} }
~Hdc1080t(); ~Hdc1080t() {};
}; };
class Hdc1080h : public IoTItem { class Hdc1080h : public IoTItem {
@@ -38,7 +38,7 @@ class Hdc1080h : public IoTItem {
else SerialPrint("E", "Sensor Hdc1080h", "Error"); else SerialPrint("E", "Sensor Hdc1080h", "Error");
} }
~Hdc1080h(); ~Hdc1080h() {};
}; };
void* getAPI_Hdc1080(String subtype, String param) { void* getAPI_Hdc1080(String subtype, String param) {

View File

@@ -85,7 +85,7 @@ class Lcd2004 : public IoTItem {
LCDI2C->print(tmpStr); LCDI2C->print(tmpStr);
} }
~Lcd2004(){}; ~Lcd2004() {};
}; };
void* getAPI_Lcd2004(String subtype, String param) { void* getAPI_Lcd2004(String subtype, String param) {

View File

@@ -18,7 +18,7 @@ class Sht20t : public IoTItem {
else SerialPrint("E", "Sensor Sht20t", "Error"); else SerialPrint("E", "Sensor Sht20t", "Error");
} }
~Sht20t(); ~Sht20t() {};
}; };
class Sht20h : public IoTItem { class Sht20h : public IoTItem {
@@ -32,7 +32,7 @@ class Sht20h : public IoTItem {
else SerialPrint("E", "Sensor Sht20h", "Error"); else SerialPrint("E", "Sensor Sht20h", "Error");
} }
~Sht20h(); ~Sht20h() {};
}; };

View File

@@ -36,7 +36,7 @@ class SysExt : public IoTItem {
return {}; // команда поддерживает возвращаемое значения. Т.е. по итогу выполнения команды или общения с внешней системой, можно вернуть значение в сценарий для дальнейшей обработки return {}; // команда поддерживает возвращаемое значения. Т.е. по итогу выполнения команды или общения с внешней системой, можно вернуть значение в сценарий для дальнейшей обработки
} }
~SysExt(){}; ~SysExt() {};
}; };
void* getAPI_SysExt(String subtype, String param) { void* getAPI_SysExt(String subtype, String param) {