mirror of
https://github.com/IoTManagerProject/IoTManager.git
synced 2026-03-26 22:22:16 +03:00
Переносм функционал физической кнопки в класс IoTSensor
This commit is contained in:
@@ -210,6 +210,9 @@ class LineParsing {
|
||||
String gtm2() {
|
||||
return _tm2;
|
||||
}
|
||||
String gdb() {
|
||||
return _db;
|
||||
}
|
||||
|
||||
int getPinErrors() {
|
||||
return pinErrors;
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
|
||||
#ifdef EnableButtonIn
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <Bounce2.h>
|
||||
#include "Class/LineParsing.h"
|
||||
#include "Global.h"
|
||||
|
||||
extern boolean but[NUM_BUTTONS];
|
||||
extern Bounce* buttons;
|
||||
|
||||
class ButtonInClass : public LineParsing {
|
||||
protected:
|
||||
int numberEntering = 0;
|
||||
int state = _state.toInt();
|
||||
|
||||
public:
|
||||
ButtonInClass() : LineParsing(){};
|
||||
|
||||
void init() {
|
||||
if (_pin != "") {
|
||||
int number = numberEntering++;
|
||||
buttons[number].attach(_pin.toInt(), INPUT);
|
||||
buttons[number].interval(_db.toInt());
|
||||
but[number] = true;
|
||||
jsonWriteStr(configOptionJson, "switch_num_" + String(number), _key);
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
static uint8_t switch_number = 1;
|
||||
if (but[switch_number]) {
|
||||
buttons[switch_number].update();
|
||||
if (buttons[switch_number].fell()) {
|
||||
String key = jsonReadStr(configOptionJson, "switch_num_" + String(switch_number));
|
||||
state = 1;
|
||||
switchChangeVirtual(key, String(state));
|
||||
}
|
||||
if (buttons[switch_number].rose()) {
|
||||
String key = jsonReadStr(configOptionJson, "switch_num_" + String(switch_number));
|
||||
state = 0;
|
||||
switchChangeVirtual(key, String(state));
|
||||
}
|
||||
}
|
||||
switch_number++;
|
||||
if (switch_number == NUM_BUTTONS) {
|
||||
switch_number = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void switchStateSetDefault() {
|
||||
if (_state != "") {
|
||||
switchChangeVirtual(_key, _state);
|
||||
}
|
||||
}
|
||||
|
||||
void switchChangeVirtual(String key, String state) {
|
||||
eventGen2(key, state);
|
||||
jsonWriteInt(configLiveJson, key, state.toInt());
|
||||
publishStatus(key, state);
|
||||
}
|
||||
};
|
||||
|
||||
extern ButtonInClass myButtonIn;
|
||||
#endif
|
||||
@@ -88,10 +88,6 @@ void csvCmdExecute(String& cmdStr) {
|
||||
} else if (order == F("pwm-out")) {
|
||||
#ifdef EnablePwmOut
|
||||
sCmd.addCommand(order.c_str(), pwmOut);
|
||||
#endif
|
||||
} else if (order == F("button-in")) {
|
||||
#ifdef EnableButtonIn
|
||||
sCmd.addCommand(order.c_str(), buttonIn);
|
||||
#endif
|
||||
} else if (order == F("input-value")) {
|
||||
#ifdef EnableInput
|
||||
@@ -182,8 +178,9 @@ void csvCmdExecute(String& cmdStr) {
|
||||
String c = myLineParsing.gc();
|
||||
String id = myLineParsing.gkey();
|
||||
String key = myLineParsing.gfile();
|
||||
String db = myLineParsing.gdb();
|
||||
myLineParsing.clear();
|
||||
String strTmp = "{\"key\": \"" + key + "\", \"id\": \"" + id + "\", \"addr\": \"" + addr + "\", \"int\": \"" + interval + "\", \"pin\": \"" + pin + "\", \"index\": \"" + index + "\", \"c\": \"" + c + "\"}";
|
||||
String strTmp = "{\"key\": \"" + key + "\", \"id\": \"" + id + "\", \"addr\": \"" + addr + "\", \"int\": \"" + interval + "\", \"pin\": \"" + pin + "\", \"index\": \"" + index + "\", \"c\": \"" + c + "\", \"db\": \"" + db + "\"}";
|
||||
|
||||
SerialPrint("I", "Строка параметров при инициализации модуля " + moduleInfo.name + ": ", strTmp);
|
||||
iotSensors.push_back((IoTSensor*)iotModules[i]->initInstance(strTmp));
|
||||
|
||||
@@ -25,7 +25,6 @@ void IoTSensor::loop() {
|
||||
difference = currentMillis - prevMillis;
|
||||
if (difference >= _interval) {
|
||||
prevMillis = millis();
|
||||
SerialPrint("I", "Sensor", "Вызывается loop");
|
||||
this->doByInterval();
|
||||
}
|
||||
}
|
||||
|
||||
82
src/Modules/Sensors/IoTSensorButtonIn.cpp
Normal file
82
src/Modules/Sensors/IoTSensorButtonIn.cpp
Normal file
@@ -0,0 +1,82 @@
|
||||
#include "Utils/JsonUtils.h"
|
||||
#include "Utils/SerialPrint.h"
|
||||
#include "Utils/StringUtils.h"
|
||||
#include "Class/IoTSensor.h"
|
||||
#include "Class/IoTModule.h"
|
||||
|
||||
#include <Bounce2.h>
|
||||
|
||||
extern std::vector<IoTModule*> iotModules; //v3dev: вектор ссылок базового класса IoTModule - интерфейсы для общения со всеми поддерживаемыми системой модулями
|
||||
|
||||
class IoTSensorButtonIn: public IoTSensor {
|
||||
private:
|
||||
//описание переменных экземпляра датчика - аналог глобальных переменных из Arduino
|
||||
//для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии
|
||||
Bounce* bButton;
|
||||
boolean status;
|
||||
|
||||
//описание параметров передаваемых из настроек датчика из веба
|
||||
unsigned int _pin;
|
||||
unsigned int _db;
|
||||
|
||||
public:
|
||||
//аналог setup() из Arduino
|
||||
IoTSensorButtonIn(String parameters) {
|
||||
//передаем часть базовых параметров в конструктор базового класса для обеспечения работы его методов
|
||||
init(jsonReadStr(parameters, "key"), jsonReadStr(parameters, "id"), 0);
|
||||
_pin = jsonReadInt(parameters, "pin");
|
||||
_db = jsonReadInt(parameters, "db");
|
||||
|
||||
bButton = new Bounce();
|
||||
bButton->attach(_pin, INPUT);
|
||||
bButton->interval(_db);
|
||||
status = true;
|
||||
}
|
||||
|
||||
~IoTSensorButtonIn() {
|
||||
delete bButton;
|
||||
}
|
||||
|
||||
//аналог loop() из Arduino, но квотируемый по времени параметром interval
|
||||
void doByInterval() {
|
||||
bButton->update();
|
||||
if (bButton->fell()) {
|
||||
status = 1;
|
||||
regEvent((String)status, ""); //обязательный вызов для отправки результата работы
|
||||
}
|
||||
if (bButton->rose()) {
|
||||
status = 0;
|
||||
regEvent((String)status, ""); //обязательный вызов для отправки результата работы
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//технический класс для взаимодействия с ядром, меняются только названия
|
||||
class IoTModuleButtonIn: public IoTModule {
|
||||
//обязательный метод для инициализации экземпляра датчика, вызывается при чтении конфигурации. Нужно учитывать, что некоторые датчики могут обеспечивать
|
||||
//несколько измерений, для каждого будет отдельный вызов.
|
||||
void* initInstance(String parameters) {
|
||||
return new IoTSensorButtonIn(parameters);
|
||||
};
|
||||
|
||||
//обязательный к заполнению метод, если модуль использует свои глобальные переменные. Необходимо сбросить и очистить используемую память.
|
||||
void clear() {
|
||||
//и так чисто
|
||||
}
|
||||
|
||||
//обязательный метод для отправки информации о модуле,
|
||||
ModuleInfo getInfo() {
|
||||
ModuleInfo MI;
|
||||
MI.name = "button-in";
|
||||
MI.title = "Кнопка физическая, чтение состояния пина (подключается проводами к устройству)";
|
||||
MI.parameters = "{\"key\": \"button-in\", \"id\": \"btn\", \"pin\": \"2\", \"db\": \"20\"}";
|
||||
MI.type = "Sensor";
|
||||
return MI;
|
||||
};
|
||||
};
|
||||
|
||||
//точка входа в модуль для заполнения вектора, требуется только изменить имя и прописать в файле api.cpp
|
||||
void getApiIoTSensorButtonIn() {
|
||||
iotModules.push_back(new IoTModuleButtonIn());
|
||||
return;
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
//объявляем функцию для добавления модуля в вектор
|
||||
void getApiIoTSensorDallasTemp();
|
||||
void getApiIoTSensorSHT20();
|
||||
void getApiIoTSensorButtonIn();
|
||||
|
||||
//формируем вектор модулей путем вызова из каждого модуля специальной функции
|
||||
//в дальнейшем предполагается отключать вызов, если модуль не участвует в сборке
|
||||
void InitModulesApi() {
|
||||
getApiIoTSensorDallasTemp();
|
||||
getApiIoTSensorSHT20();
|
||||
getApiIoTSensorButtonIn();
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
#include "Consts.h"
|
||||
#ifdef EnableButtonIn
|
||||
#include "BufferExecute.h"
|
||||
#include "items/ButtonInClass.h"
|
||||
//==========================================Модуль физических кнопок========================================
|
||||
//button-in switch1 toggle Кнопки Свет 1 pin[2] db[20]
|
||||
//==========================================================================================================
|
||||
|
||||
boolean but[NUM_BUTTONS];
|
||||
Bounce *buttons = new Bounce[NUM_BUTTONS];
|
||||
|
||||
ButtonInClass myButtonIn;
|
||||
void buttonIn() {
|
||||
myButtonIn.update();
|
||||
String key = myButtonIn.gkey();
|
||||
String pin = myButtonIn.gpin();
|
||||
sCmd.addCommand(key.c_str(), buttonInSet);
|
||||
myButtonIn.init();
|
||||
myButtonIn.switchStateSetDefault();
|
||||
myButtonIn.clear();
|
||||
}
|
||||
|
||||
void buttonInSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myButtonIn.switchChangeVirtual(key, state);
|
||||
}
|
||||
#endif
|
||||
@@ -19,7 +19,6 @@
|
||||
#include "Utils/statUtils.h"
|
||||
#include "Utils/Timings.h"
|
||||
#include "Utils/WebUtils.h"
|
||||
#include "items/ButtonInClass.h"
|
||||
#include "items/vCountDown.h"
|
||||
#include "items/vImpulsOut.h"
|
||||
#include "items/vLogging.h"
|
||||
@@ -231,9 +230,7 @@ void loop() {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#ifdef EnableButtonIn
|
||||
myButtonIn.loop();
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user