Завершаем перенос ButtonOut в новую систему классов, требуется доработка взаимодействия с виджитами

This commit is contained in:
2021-12-31 10:55:38 +03:00
parent 6b481de207
commit c002bafc1c
9 changed files with 118 additions and 170 deletions

View File

@@ -1,5 +1,6 @@
#pragma once
#include "Utils/JsonUtils.h"
#include <WString.h>
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();

View File

@@ -1,30 +0,0 @@
#ifdef EnableButtonOut
#pragma once
#include <Arduino.h>
#include "Global.h"
class ButtonOut;
typedef std::vector<ButtonOut> 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

View File

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

View File

@@ -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); //прочитали из памяти
};

View File

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

View File

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

View File

@@ -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;
}
};
//технический класс для взаимодействия с ядром, меняются только названия

View File

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

View File

@@ -1,121 +0,0 @@
#include "Consts.h"
#ifdef EnableButtonOut
#include <Arduino.h>
#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