From c002bafc1c85fdcc546ed0e74984d03513b0e882 Mon Sep 17 00:00:00 2001 From: biver Date: Fri, 31 Dec 2021 10:55:38 +0300 Subject: [PATCH] =?UTF-8?q?=D0=97=D0=B0=D0=B2=D0=B5=D1=80=D1=88=D0=B0?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=BE=D1=81=20But?= =?UTF-8?q?tonOut=20=D0=B2=20=D0=BD=D0=BE=D0=B2=D1=83=D1=8E=20=D1=81=D0=B8?= =?UTF-8?q?=D1=81=D1=82=D0=B5=D0=BC=D1=83=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D0=BE=D0=B2,=20=D1=82=D1=80=D0=B5=D0=B1=D1=83=D0=B5=D1=82?= =?UTF-8?q?=D1=81=D1=8F=20=D0=B4=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=B2=D0=B7=D0=B0=D0=B8=D0=BC=D0=BE=D0=B4=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D1=82=D0=B2=D0=B8=D1=8F=20=D1=81=20=D0=B2=D0=B8=D0=B4?= =?UTF-8?q?=D0=B6=D0=B8=D1=82=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Class/IoTVariable.h | 3 + include/items/vButtonOut.h | 30 ----- src/BufferExecute.cpp | 7 +- src/Class/IoTVariable.cpp | 13 +- src/Init.cpp | 8 -- .../Variables/IoTVariableButtonOut.cpp | 98 ++++++++++++++ src/Modules/Variables/IoTVariableVirtual.cpp | 6 +- src/Modules/api.cpp | 2 + src/items/vButtonOut.cpp | 121 ------------------ 9 files changed, 118 insertions(+), 170 deletions(-) delete mode 100644 include/items/vButtonOut.h create mode 100644 src/Modules/Variables/IoTVariableButtonOut.cpp delete mode 100644 src/items/vButtonOut.cpp diff --git a/include/Class/IoTVariable.h b/include/Class/IoTVariable.h index 244f8f0d..180b6e1a 100644 --- a/include/Class/IoTVariable.h +++ b/include/Class/IoTVariable.h @@ -1,5 +1,6 @@ #pragma once +#include "Utils/JsonUtils.h" #include class IoTVariable { @@ -10,9 +11,11 @@ class IoTVariable { virtual String execute(String command); virtual void selfExec(); virtual void loop(); + virtual String getValue(String key); void init(String key, String id); void regEvent(String value, String consoleInfo); + String loadValue(String id); String getKey(); String getID(); diff --git a/include/items/vButtonOut.h b/include/items/vButtonOut.h deleted file mode 100644 index ecfacfcc..00000000 --- a/include/items/vButtonOut.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifdef EnableButtonOut -#pragma once -#include - -#include "Global.h" - -class ButtonOut; - -typedef std::vector MyButtonOutVector; - -class ButtonOut { - public: - ButtonOut(String pin, boolean inv, String key, String type); - - ~ButtonOut(); - - void execute(String state); - - private: - String _pin; - boolean _inv; - String _key; - String _type; -}; - -extern MyButtonOutVector* myButtonOut; - -extern void buttonOut(); -extern void buttonOutExecute(); -#endif \ No newline at end of file diff --git a/src/BufferExecute.cpp b/src/BufferExecute.cpp index 8b851184..e0bd1f23 100644 --- a/src/BufferExecute.cpp +++ b/src/BufferExecute.cpp @@ -3,7 +3,6 @@ #include "Global.h" #include "SoftUART.h" #include "items/test.h" -#include "items/vButtonOut.h" #include "items/vCountDown.h" #include "items/vImpulsOut.h" #include "items/vInput.h" @@ -83,11 +82,7 @@ void csvCmdExecute(String& cmdStr) { // SerialPrint("I", "Items", buf); String order = selectToMarker(buf, " "); //отсечка самой команды - if (order == F("button-out")) { -#ifdef EnableButtonOut - sCmd.addCommand(order.c_str(), buttonOut); -#endif - } else if (order == F("pwm-out")) { + if (order == F("pwm-out")) { #ifdef EnablePwmOut sCmd.addCommand(order.c_str(), pwmOut); #endif diff --git a/src/Class/IoTVariable.cpp b/src/Class/IoTVariable.cpp index 31545ff3..b1d09241 100644 --- a/src/Class/IoTVariable.cpp +++ b/src/Class/IoTVariable.cpp @@ -9,6 +9,7 @@ IoTVariable::~IoTVariable() {} String IoTVariable::execute(String command) { return "";} void IoTVariable::selfExec() {} void IoTVariable::loop() {} +String IoTVariable::getValue(String key) { return "";} void IoTVariable::init(String key, String id) { _key = key; @@ -16,10 +17,10 @@ void IoTVariable::init(String key, String id) { } void IoTVariable::regEvent(String value, String consoleInfo = "") { - eventGen2(_key, String(value)); - jsonWriteStr(configLiveJson, _key, String(value)); - publishStatus(_key, String(value)); - SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(value) + "' " + consoleInfo); + eventGen2(_id, String(value)); + jsonWriteStr(configLiveJson, _id, String(value)); + publishStatus(_id, String(value)); + SerialPrint("I", "Variable", "'" + _id + "' data: " + String(value) + "' " + consoleInfo); } String IoTVariable::getKey() { @@ -28,4 +29,8 @@ String IoTVariable::getKey() { String IoTVariable::getID() { return _id; +}; + +String IoTVariable::loadValue(String id) { + return jsonReadStr(configStoreJson, id); //прочитали из памяти }; \ No newline at end of file diff --git a/src/Init.cpp b/src/Init.cpp index b37643dc..f784462e 100644 --- a/src/Init.cpp +++ b/src/Init.cpp @@ -4,7 +4,6 @@ #include "Class/LineParsing.h" #include "Cmd.h" #include "Global.h" -#include "items/vButtonOut.h" #include "items/vCountDown.h" #include "items/vImpulsOut.h" #include "items/vInput.h" @@ -154,13 +153,6 @@ for (unsigned int i = 0; i < iotModules.size(); i++) { countDown_EnterCounter = -1; #endif -#ifdef EnableButtonOut - if (myButtonOut != nullptr) { - myButtonOut->clear(); - } - buttonOut_KeyList = ""; - buttonOut_EnterCounter = -1; -#endif #ifdef EnableInput if (myInput != nullptr) { myInput->clear(); diff --git a/src/Modules/Variables/IoTVariableButtonOut.cpp b/src/Modules/Variables/IoTVariableButtonOut.cpp new file mode 100644 index 00000000..d3a1d78b --- /dev/null +++ b/src/Modules/Variables/IoTVariableButtonOut.cpp @@ -0,0 +1,98 @@ +#include "Utils/JsonUtils.h" +#include "Utils/SerialPrint.h" +#include "Utils/StringUtils.h" + +#include "Class/IoTVariable.h" +#include "Class/IoTModule.h" + + +class IoTVariableButtonOut: public IoTVariable { + private: + //описание переменных экземпляра Variable - аналог глобальных переменных из Arduino + bool _state; + + //описание параметров передаваемых из настроек переменной из веба + bool _isInvert; + int _pin; + + public: + //аналог setup() из Arduino + IoTVariableButtonOut(String parameters) { + //передаем часть базовых параметров в конструктор базового класса для обеспечения работы его методов + init(jsonReadStr(parameters, "key"), jsonReadStr(parameters, "id")); + + _pin = jsonReadBool(parameters, "pin"); + _isInvert = jsonReadBool(parameters, "inv"); + + _state = this->loadValue(_id); //прочитали из памяти + if (_pin) { + pinMode(_pin, OUTPUT); + this->execute(String(_state)); //установили это состояние + } + } + + ~IoTVariableButtonOut() {} + + //аналог loop() из Arduino + void loop() { + + } + + //вызывается при выполнении команды связанной с конкретным экземпляром переменной, передаем команду целиком после идентификатора в сценарии (минус пробел) + String execute(String command) { + if (command != "" && _pin > 0) { + if (command == "change") { + _state = !digitalRead(_pin); + digitalWrite(_pin, _state); + } else { + int newState = command.toInt(); + if (_isInvert) { + digitalWrite(_pin, !newState); + } else { + digitalWrite(_pin, newState); + } + } + selfExec(); + regEvent((String)_state, ""); + } + return ""; + } + + //EXPEREMENTAL.вызывается при любом изменении переменной (задумка для реализации возможности вызова своего кода при клике на кнопку в веб-интерфейсе. + //Создаем модуль с реализацией и выбираем в конфигурации нужный виджет с кнопкой) для других реализаций + void selfExec() { + + } + + String getValue(String key) { + return (String)_state; + } +}; + +//технический класс для взаимодействия с ядром, меняются только названия +class IoTModuleButtonOut: public IoTModule { + //обязательный метод для инициализации экземпляра переменной, вызывается при чтении конфигурации. + void* initInstance(String parameters) { + return new IoTVariableButtonOut(parameters); + }; + + //обязательный к заполнению метод, если модуль использует свои глобальные переменные. Необходимо сбросить и очистить используемую память. + void clear() { + //и так чисто + } + + //обязательный метод для отправки информации о модуле, + ModuleInfo getInfo() { + ModuleInfo MI; + MI.name = "button-out"; + MI.title = "Кнопка управляющая пином"; + MI.parameters = "{\"key\": \"button-out\", \"id\": \"var\", \"pin\": \"2\", \"inv\": \"0\"}"; + MI.type = "Variable"; + return MI; + }; +}; + +//точка входа в модуль для заполнения вектора, требуется только изменить имя и прописать в файле api.cpp + void* getApiIoTVariableButtonOut() { + return new IoTModuleButtonOut(); +} \ No newline at end of file diff --git a/src/Modules/Variables/IoTVariableVirtual.cpp b/src/Modules/Variables/IoTVariableVirtual.cpp index 9b9a558d..cff4b91f 100644 --- a/src/Modules/Variables/IoTVariableVirtual.cpp +++ b/src/Modules/Variables/IoTVariableVirtual.cpp @@ -9,7 +9,7 @@ class IoTVariableVirtual: public IoTVariable { private: //описание переменных экземпляра Variable - аналог глобальных переменных из Arduino - String value; + String _value; //описание параметров передаваемых из настроек переменной из веба @@ -38,6 +38,10 @@ class IoTVariableVirtual: public IoTVariable { void selfExec() { } + + String getValue(String key="") { + return _value; + } }; //технический класс для взаимодействия с ядром, меняются только названия diff --git a/src/Modules/api.cpp b/src/Modules/api.cpp index 7c1f9b69..caced9c4 100644 --- a/src/Modules/api.cpp +++ b/src/Modules/api.cpp @@ -11,6 +11,7 @@ void* getApiIoTSensorSHT20(); void* getApiIoTSensorButtonIn(); void* getApiIoTVariableVirtual(); +void* getApiIoTVariableButtonOut(); //формируем вектор модулей путем вызова из каждого модуля специальной функции //в дальнейшем предполагается отключать вызов, если модуль не участвует в сборке @@ -20,4 +21,5 @@ void InitModulesApi() { iotModules.push_back((IoTModule*) getApiIoTSensorButtonIn()); iotModules.push_back((IoTModule*) getApiIoTVariableVirtual()); + iotModules.push_back((IoTModule*) getApiIoTVariableButtonOut()); } \ No newline at end of file diff --git a/src/items/vButtonOut.cpp b/src/items/vButtonOut.cpp deleted file mode 100644 index 7d4aa191..00000000 --- a/src/items/vButtonOut.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include "Consts.h" -#ifdef EnableButtonOut -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "SoftUART.h" -#include "items/vButtonOut.h" -//#include "WebServer.h" -//this class save data to flash -ButtonOut::ButtonOut(String pin, boolean inv, String key, String type) { - _pin = pin; - _inv = inv; - _key = key; - _type = type; -#ifdef ESP_MODE - if (_pin != "") { - pinMode(_pin.toInt(), OUTPUT); - } - int state = jsonReadInt(configStoreJson, key); //прочитали из памяти - this->execute(String(state)); //установили это состояние -#endif -#ifdef GATE_MODE - if (_pin != "") { - pinMode(_pin.toInt(), OUTPUT); - } - int state = jsonReadInt(configStoreJson, key); //прочитали из памяти - this->execute(String(state)); //установили это состояние - -//TO DO запросили ноду о состоянии реле -//установили в это состояние кнопку в приложении -//если нода не ответила - кнопку сделать красным цветом -#endif -} -ButtonOut::~ButtonOut() {} - -void ButtonOut::execute(String state) { -#ifdef ESP_MODE - if (state != "" && _pin != "") { - if (state == "change") { - state = String(!digitalRead(_pin.toInt())); - digitalWrite(_pin.toInt(), state.toInt()); - } else { - if (_inv) { - digitalWrite(_pin.toInt(), !state.toInt()); - } else { - digitalWrite(_pin.toInt(), state.toInt()); - } - } - } -#endif -#ifdef GATE_MODE -// включаем кнопки на ESP гейта - if (state != "" && _pin != "") { - if (state == "change") { - state = String(!digitalRead(_pin.toInt())); - digitalWrite(_pin.toInt(), state.toInt()); - } else { - if (_inv) { - digitalWrite(_pin.toInt(), !state.toInt()); - } else { - digitalWrite(_pin.toInt(), state.toInt()); - } - } - } - -//отправили ноде команду на вкл выкл -//получили обратную связь - переставили кнопку в приложении -//не получили обратную связь - сделали кнопку красной -#endif - eventGen2(_key, state); - jsonWriteInt(configStoreJson, _key, state.toInt()); - saveStore(); - publishStatus(_key, state); - String path = mqttRootDevice + "/" + _key + "/status"; - String json = "{}"; - jsonWriteStr(json, "status", state); - String MyJson = json; - jsonWriteStr(MyJson, "topic", path); - ws.textAll(MyJson); -} - -MyButtonOutVector* myButtonOut = nullptr; - -void buttonOut() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String pin = myLineParsing.gpin(); - String inv = myLineParsing.ginv(); - String type = myLineParsing.gtype(); - - bool invb = false; - if (inv.toInt() == 1) invb = true; - - myLineParsing.clear(); - - buttonOut_EnterCounter++; - addKey(key, buttonOut_KeyList, buttonOut_EnterCounter); - - static bool firstTime = true; - if (firstTime) myButtonOut = new MyButtonOutVector(); - firstTime = false; - myButtonOut->push_back(ButtonOut(pin, invb, key, type)); - - sCmd.addCommand(key.c_str(), buttonOutExecute); -} - -void buttonOutExecute() { - String key = sCmd.order(); - String state = sCmd.next(); - - int number = getKeyNum(key, buttonOut_KeyList); - - if (myButtonOut != nullptr) { - if (number != -1) { - myButtonOut->at(number).execute(state); - } - } -} -#endif