mirror of
https://github.com/IoTManagerProject/IoTManager.git
synced 2026-04-01 21:09:14 +03:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fe10441b1 | ||
| c002bafc1c | |||
|
|
6b481de207 | ||
| b0fb71832c | |||
| 6a7653c7ff | |||
| ee94853ad9 | |||
| ede9092a73 | |||
| 30cf9cc3bb | |||
| 41f4be6139 | |||
|
|
c8df0de972 | ||
| bebea0732a | |||
| 5fecb51d69 | |||
| faa865e78d |
53
.vscode/settings.json
vendored
53
.vscode/settings.json
vendored
@@ -1,5 +1,54 @@
|
|||||||
{
|
{
|
||||||
"files.associations": {
|
"files.associations": {
|
||||||
"array": "cpp"
|
"array": "cpp",
|
||||||
}
|
"atomic": "cpp",
|
||||||
|
"*.tcc": "cpp",
|
||||||
|
"bitset": "cpp",
|
||||||
|
"cctype": "cpp",
|
||||||
|
"clocale": "cpp",
|
||||||
|
"cmath": "cpp",
|
||||||
|
"cstdarg": "cpp",
|
||||||
|
"cstdint": "cpp",
|
||||||
|
"cstdio": "cpp",
|
||||||
|
"cstdlib": "cpp",
|
||||||
|
"cstring": "cpp",
|
||||||
|
"ctime": "cpp",
|
||||||
|
"cwchar": "cpp",
|
||||||
|
"cwctype": "cpp",
|
||||||
|
"deque": "cpp",
|
||||||
|
"list": "cpp",
|
||||||
|
"unordered_map": "cpp",
|
||||||
|
"vector": "cpp",
|
||||||
|
"exception": "cpp",
|
||||||
|
"fstream": "cpp",
|
||||||
|
"functional": "cpp",
|
||||||
|
"initializer_list": "cpp",
|
||||||
|
"iosfwd": "cpp",
|
||||||
|
"iostream": "cpp",
|
||||||
|
"istream": "cpp",
|
||||||
|
"limits": "cpp",
|
||||||
|
"new": "cpp",
|
||||||
|
"ostream": "cpp",
|
||||||
|
"numeric": "cpp",
|
||||||
|
"sstream": "cpp",
|
||||||
|
"stdexcept": "cpp",
|
||||||
|
"streambuf": "cpp",
|
||||||
|
"cinttypes": "cpp",
|
||||||
|
"regex": "cpp",
|
||||||
|
"tuple": "cpp",
|
||||||
|
"type_traits": "cpp",
|
||||||
|
"utility": "cpp",
|
||||||
|
"typeinfo": "cpp",
|
||||||
|
"chrono": "cpp",
|
||||||
|
"mutex": "cpp",
|
||||||
|
"ratio": "cpp",
|
||||||
|
"system_error": "cpp",
|
||||||
|
"cstddef": "cpp",
|
||||||
|
"unordered_set": "cpp",
|
||||||
|
"algorithm": "cpp",
|
||||||
|
"iomanip": "cpp",
|
||||||
|
"memory": "cpp",
|
||||||
|
"string": "cpp"
|
||||||
|
},
|
||||||
|
"cmake.configureOnOpen": false
|
||||||
}
|
}
|
||||||
21
include/Class/IoTModule.h
Normal file
21
include/Class/IoTModule.h
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <WString.h>
|
||||||
|
|
||||||
|
struct ModuleInfo
|
||||||
|
{
|
||||||
|
String name; //имя модуля
|
||||||
|
String title; //заголовок для описания модуля
|
||||||
|
String parameters; //параметры, которые может принять модуль и сущность
|
||||||
|
String type; //тип для определения сущности, которую генерирует модуль Sensor или Variable
|
||||||
|
};
|
||||||
|
|
||||||
|
class IoTModule {
|
||||||
|
public:
|
||||||
|
IoTModule();
|
||||||
|
~IoTModule();
|
||||||
|
|
||||||
|
virtual void* initInstance(String parameters);
|
||||||
|
virtual ModuleInfo getInfo();
|
||||||
|
virtual void clear();
|
||||||
|
};
|
||||||
26
include/Class/IoTSensor.h
Normal file
26
include/Class/IoTSensor.h
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <WString.h>
|
||||||
|
|
||||||
|
class IoTSensor {
|
||||||
|
public:
|
||||||
|
IoTSensor();
|
||||||
|
~IoTSensor();
|
||||||
|
|
||||||
|
void loop();
|
||||||
|
virtual void doByInterval();
|
||||||
|
void init(String key, String id, unsigned long interval);
|
||||||
|
void regEvent(String value, String consoleInfo);
|
||||||
|
|
||||||
|
String getKey();
|
||||||
|
String getID();
|
||||||
|
|
||||||
|
unsigned long currentMillis;
|
||||||
|
unsigned long prevMillis;
|
||||||
|
unsigned long difference;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
String _key;
|
||||||
|
String _id;
|
||||||
|
unsigned long _interval;
|
||||||
|
};
|
||||||
27
include/Class/IoTVariable.h
Normal file
27
include/Class/IoTVariable.h
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include <WString.h>
|
||||||
|
|
||||||
|
class IoTVariable {
|
||||||
|
public:
|
||||||
|
IoTVariable();
|
||||||
|
~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();
|
||||||
|
|
||||||
|
protected:
|
||||||
|
String _key; //имя переменной, для идентификации при работе с несколькими переменными в одном модуле
|
||||||
|
String _id; //код переменной для идентификации событий, команд в сценариях и логах
|
||||||
|
|
||||||
|
};
|
||||||
@@ -210,6 +210,9 @@ class LineParsing {
|
|||||||
String gtm2() {
|
String gtm2() {
|
||||||
return _tm2;
|
return _tm2;
|
||||||
}
|
}
|
||||||
|
String gdb() {
|
||||||
|
return _db;
|
||||||
|
}
|
||||||
|
|
||||||
int getPinErrors() {
|
int getPinErrors() {
|
||||||
return pinErrors;
|
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
|
|
||||||
@@ -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
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#ifdef EnableSensorDallas
|
|
||||||
#pragma once
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <OneWire.h>
|
|
||||||
#include <DallasTemperature.h>
|
|
||||||
#include "Global.h"
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: Объявляем глагольные переменные необходимые интегрируемой библиотеке
|
|
||||||
extern DallasTemperature sensors;
|
|
||||||
extern OneWire* oneWire;
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: следим за наименованиями далее
|
|
||||||
class SensorDallas;
|
|
||||||
|
|
||||||
typedef std::vector<SensorDallas> MySensorDallasVector;
|
|
||||||
|
|
||||||
class SensorDallas {
|
|
||||||
public:
|
|
||||||
//ИНТЕГРИРУЮ: обращаем внимание на параметры, берутся из таблицы настроек
|
|
||||||
SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String addr, String key);
|
|
||||||
~SensorDallas();
|
|
||||||
|
|
||||||
void loop();
|
|
||||||
void readDallas();
|
|
||||||
|
|
||||||
private:
|
|
||||||
unsigned long currentMillis;
|
|
||||||
unsigned long prevMillis;
|
|
||||||
unsigned long difference;
|
|
||||||
unsigned long _interval;
|
|
||||||
String _key;
|
|
||||||
String _addr;
|
|
||||||
unsigned int _pin;
|
|
||||||
unsigned int _index;
|
|
||||||
};
|
|
||||||
|
|
||||||
extern MySensorDallasVector* mySensorDallas2;
|
|
||||||
|
|
||||||
extern void dallas();
|
|
||||||
#endif
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#ifdef EnableSensorSht20
|
|
||||||
#pragma once
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include "Wire.h"
|
|
||||||
#include "SHT2x.h"
|
|
||||||
|
|
||||||
#include "Global.h"
|
|
||||||
|
|
||||||
extern SHT2x* sht;
|
|
||||||
|
|
||||||
class SensorSht20;
|
|
||||||
|
|
||||||
typedef std::vector<SensorSht20> MySensorSht20Vector;
|
|
||||||
|
|
||||||
struct paramsSht {
|
|
||||||
String key;
|
|
||||||
unsigned long interval;
|
|
||||||
float c;
|
|
||||||
};
|
|
||||||
|
|
||||||
class SensorSht20 {
|
|
||||||
public:
|
|
||||||
SensorSht20(const paramsSht& paramsTmp, const paramsSht& paramsHum);
|
|
||||||
~SensorSht20();
|
|
||||||
|
|
||||||
void loop();
|
|
||||||
void read();
|
|
||||||
|
|
||||||
private:
|
|
||||||
paramsSht _paramsTmp;
|
|
||||||
paramsSht _paramsHum;
|
|
||||||
|
|
||||||
unsigned long prevMillis;
|
|
||||||
unsigned long difference;
|
|
||||||
};
|
|
||||||
|
|
||||||
extern MySensorSht20Vector* mySensorSht20;
|
|
||||||
|
|
||||||
extern void sht20Sensor();
|
|
||||||
#endif
|
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
; https://docs.platformio.org/page/projectconf.html
|
; https://docs.platformio.org/page/projectconf.html
|
||||||
|
|
||||||
[platformio]
|
[platformio]
|
||||||
default_envs = esp8266_4mb
|
default_envs = esp32_4mb
|
||||||
data_dir = data_esp
|
data_dir = data_esp
|
||||||
|
|
||||||
[common_env_data]
|
[common_env_data]
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
#include "Global.h"
|
#include "Global.h"
|
||||||
#include "SoftUART.h"
|
#include "SoftUART.h"
|
||||||
#include "items/test.h"
|
#include "items/test.h"
|
||||||
#include "items/vButtonOut.h"
|
|
||||||
#include "items/vCountDown.h"
|
#include "items/vCountDown.h"
|
||||||
#include "items/vImpulsOut.h"
|
#include "items/vImpulsOut.h"
|
||||||
#include "items/vInput.h"
|
#include "items/vInput.h"
|
||||||
@@ -15,14 +14,23 @@
|
|||||||
#include "items/vSensorBme280.h"
|
#include "items/vSensorBme280.h"
|
||||||
#include "items/vSensorBmp280.h"
|
#include "items/vSensorBmp280.h"
|
||||||
#include "items/vSensorCcs811.h"
|
#include "items/vSensorCcs811.h"
|
||||||
#include "items/vSensorDallas.h"
|
|
||||||
#include "items/vSensorDht.h"
|
#include "items/vSensorDht.h"
|
||||||
#include "items/vSensorNode.h"
|
#include "items/vSensorNode.h"
|
||||||
#include "items/vSensorPzem.h"
|
#include "items/vSensorPzem.h"
|
||||||
#include "items/vSensorSHT20.h"
|
|
||||||
#include "items/vSensorUltrasonic.h"
|
#include "items/vSensorUltrasonic.h"
|
||||||
#include "items/vSensorUptime.h"
|
#include "items/vSensorUptime.h"
|
||||||
|
|
||||||
|
#include "Class/LineParsing.h"
|
||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTVariable.h"
|
||||||
|
|
||||||
|
extern std::vector<IoTModule*> iotModules; //v3dev: вектор ссылок базового класса IoTModule - интерфейсы для общения со всеми поддерживаемыми системой модулями
|
||||||
|
extern std::vector<IoTSensor*> iotSensors; //v3dev: вектор ссылок базового класса IoTSensor - список всех запущенных сенсоров
|
||||||
|
extern std::vector<IoTVariable*> iotVariables; //v3dev: вектор ссылок базового класса IoTVariable - список всех подготовленных переменных
|
||||||
|
|
||||||
void loopCmdAdd(const String& cmdStr) {
|
void loopCmdAdd(const String& cmdStr) {
|
||||||
if (cmdStr.endsWith(",")) {
|
if (cmdStr.endsWith(",")) {
|
||||||
orderBuf += cmdStr;
|
orderBuf += cmdStr;
|
||||||
@@ -73,17 +81,10 @@ void csvCmdExecute(String& cmdStr) {
|
|||||||
if (count > 1) {
|
if (count > 1) {
|
||||||
// SerialPrint("I", "Items", buf);
|
// SerialPrint("I", "Items", buf);
|
||||||
String order = selectToMarker(buf, " "); //отсечка самой команды
|
String order = selectToMarker(buf, " "); //отсечка самой команды
|
||||||
if (order == F("button-out")) {
|
|
||||||
#ifdef EnableButtonOut
|
if (order == F("pwm-out")) {
|
||||||
sCmd.addCommand(order.c_str(), buttonOut);
|
|
||||||
#endif
|
|
||||||
} else if (order == F("pwm-out")) {
|
|
||||||
#ifdef EnablePwmOut
|
#ifdef EnablePwmOut
|
||||||
sCmd.addCommand(order.c_str(), pwmOut);
|
sCmd.addCommand(order.c_str(), pwmOut);
|
||||||
#endif
|
|
||||||
} else if (order == F("button-in")) {
|
|
||||||
#ifdef EnableButtonIn
|
|
||||||
sCmd.addCommand(order.c_str(), buttonIn);
|
|
||||||
#endif
|
#endif
|
||||||
} else if (order == F("input-value")) {
|
} else if (order == F("input-value")) {
|
||||||
#ifdef EnableInput
|
#ifdef EnableInput
|
||||||
@@ -103,9 +104,9 @@ void csvCmdExecute(String& cmdStr) {
|
|||||||
#endif
|
#endif
|
||||||
//ИНТЕГРИРУЮ: Первая интеграция в ядро. Следим за наименованием
|
//ИНТЕГРИРУЮ: Первая интеграция в ядро. Следим за наименованием
|
||||||
} else if (order == F("dallas-temp")) {
|
} else if (order == F("dallas-temp")) {
|
||||||
#ifdef EnableSensorDallas
|
// #ifdef EnableSensorDallas
|
||||||
sCmd.addCommand(order.c_str(), dallas);
|
// sCmd.addCommand(order.c_str(), dallas);
|
||||||
#endif
|
// #endif
|
||||||
} else if (order == F("dht")) {
|
} else if (order == F("dht")) {
|
||||||
#ifdef EnableSensorDht
|
#ifdef EnableSensorDht
|
||||||
sCmd.addCommand(order.c_str(), dhtSensor);
|
sCmd.addCommand(order.c_str(), dhtSensor);
|
||||||
@@ -113,10 +114,6 @@ void csvCmdExecute(String& cmdStr) {
|
|||||||
} else if (order == F("bme280")) {
|
} else if (order == F("bme280")) {
|
||||||
#ifdef EnableSensorBme280
|
#ifdef EnableSensorBme280
|
||||||
sCmd.addCommand(order.c_str(), bme280Sensor);
|
sCmd.addCommand(order.c_str(), bme280Sensor);
|
||||||
#endif
|
|
||||||
} else if (order == F("sht20")) {
|
|
||||||
#ifdef EnableSensorSht20
|
|
||||||
sCmd.addCommand(order.c_str(), sht20Sensor);
|
|
||||||
#endif
|
#endif
|
||||||
} else if (order == F("sensor")) {
|
} else if (order == F("sensor")) {
|
||||||
#ifdef EnableSensorAny
|
#ifdef EnableSensorAny
|
||||||
@@ -161,6 +158,34 @@ void csvCmdExecute(String& cmdStr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
sCmd.readStr(buf);
|
sCmd.readStr(buf);
|
||||||
|
|
||||||
|
//v3dev: инициируем экземпляр модулей в случае необходимости
|
||||||
|
for (unsigned int i = 0; i < iotModules.size(); i++) {
|
||||||
|
ModuleInfo moduleInfo = iotModules[i]->getInfo();
|
||||||
|
//del SerialPrint("I", "moduleInfo.name", moduleInfo.name);
|
||||||
|
//del SerialPrint("I", "order", order);
|
||||||
|
if (moduleInfo.name == order) { //проверка вхождения имени искомого модуля в ключе элемента настройки
|
||||||
|
myLineParsing.update(); //v3dev: пока используем мостик для совместимости версий, предполагается, что настройки сразу будут в JSON
|
||||||
|
String interval = myLineParsing.gint();
|
||||||
|
if (interval == "") interval = "50";
|
||||||
|
String pin = myLineParsing.gpin();
|
||||||
|
String index = myLineParsing.gindex();
|
||||||
|
String addr = myLineParsing.gaddr();
|
||||||
|
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 + "\", \"db\": \"" + db + "\"}";
|
||||||
|
SerialPrint("I", "Строка параметров при инициализации модуля " + moduleInfo.name + ": ", strTmp);
|
||||||
|
|
||||||
|
if (moduleInfo.type == "Sensor") {
|
||||||
|
iotSensors.push_back((IoTSensor*)iotModules[i]->initInstance(strTmp));
|
||||||
|
} else if (moduleInfo.type == "Variable") {
|
||||||
|
iotVariables.push_back((IoTVariable*)iotModules[i]->initInstance(strTmp));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
|
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
|
||||||
}
|
}
|
||||||
|
|||||||
7
src/Class/IoTModule.cpp
Normal file
7
src/Class/IoTModule.cpp
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
IoTModule::IoTModule() {};
|
||||||
|
IoTModule::~IoTModule() {};
|
||||||
|
void* IoTModule::initInstance(String parameters) {};
|
||||||
|
ModuleInfo IoTModule::getInfo() {};
|
||||||
|
void IoTModule::clear() {};
|
||||||
39
src/Class/IoTSensor.cpp
Normal file
39
src/Class/IoTSensor.cpp
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Class/ScenarioClass3.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
|
||||||
|
void IoTSensor::init(String key, String id, unsigned long interval) {
|
||||||
|
_interval = interval * 1000;
|
||||||
|
_key = key;
|
||||||
|
_id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
IoTSensor::IoTSensor() {}
|
||||||
|
IoTSensor::~IoTSensor() {}
|
||||||
|
|
||||||
|
String IoTSensor::getKey() {
|
||||||
|
return _key;
|
||||||
|
}
|
||||||
|
|
||||||
|
String IoTSensor::getID() {
|
||||||
|
return _id;
|
||||||
|
};
|
||||||
|
|
||||||
|
void IoTSensor::loop() {
|
||||||
|
currentMillis = millis();
|
||||||
|
difference = currentMillis - prevMillis;
|
||||||
|
if (difference >= _interval) {
|
||||||
|
prevMillis = millis();
|
||||||
|
this->doByInterval();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void IoTSensor::regEvent(String value, String consoleInfo = "") {
|
||||||
|
eventGen2(_id, String(value));
|
||||||
|
jsonWriteStr(configLiveJson, _id, String(value));
|
||||||
|
publishStatus(_id, String(value));
|
||||||
|
SerialPrint("I", "Sensor", "'" + _id + "' data: " + String(value) + "' " + consoleInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
void IoTSensor::doByInterval() {}
|
||||||
36
src/Class/IoTVariable.cpp
Normal file
36
src/Class/IoTVariable.cpp
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Class/ScenarioClass3.h"
|
||||||
|
#include "Class/IoTVariable.h"
|
||||||
|
|
||||||
|
IoTVariable::IoTVariable() {}
|
||||||
|
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;
|
||||||
|
_id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
void IoTVariable::regEvent(String value, String 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() {
|
||||||
|
return _key;
|
||||||
|
}
|
||||||
|
|
||||||
|
String IoTVariable::getID() {
|
||||||
|
return _id;
|
||||||
|
};
|
||||||
|
|
||||||
|
String IoTVariable::loadValue(String id) {
|
||||||
|
return jsonReadStr(configStoreJson, id); //прочитали из памяти
|
||||||
|
};
|
||||||
44
src/Init.cpp
44
src/Init.cpp
@@ -4,7 +4,6 @@
|
|||||||
#include "Class/LineParsing.h"
|
#include "Class/LineParsing.h"
|
||||||
#include "Cmd.h"
|
#include "Cmd.h"
|
||||||
#include "Global.h"
|
#include "Global.h"
|
||||||
#include "items/vButtonOut.h"
|
|
||||||
#include "items/vCountDown.h"
|
#include "items/vCountDown.h"
|
||||||
#include "items/vImpulsOut.h"
|
#include "items/vImpulsOut.h"
|
||||||
#include "items/vInput.h"
|
#include "items/vInput.h"
|
||||||
@@ -15,14 +14,19 @@
|
|||||||
#include "items/vSensorBme280.h"
|
#include "items/vSensorBme280.h"
|
||||||
#include "items/vSensorBmp280.h"
|
#include "items/vSensorBmp280.h"
|
||||||
#include "items/vSensorCcs811.h"
|
#include "items/vSensorCcs811.h"
|
||||||
#include "items/vSensorDallas.h"
|
|
||||||
#include "items/vSensorDht.h"
|
#include "items/vSensorDht.h"
|
||||||
#include "items/vSensorNode.h"
|
#include "items/vSensorNode.h"
|
||||||
#include "items/vSensorPzem.h"
|
#include "items/vSensorPzem.h"
|
||||||
#include "items/vSensorSHT20.h"
|
|
||||||
#include "items/vSensorUltrasonic.h"
|
#include "items/vSensorUltrasonic.h"
|
||||||
#include "items/vSensorUptime.h"
|
#include "items/vSensorUptime.h"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
extern std::vector<IoTModule*> iotModules; //v3dev: вектор ссылок базового класса IoTModule - интерфейсы для общения со всеми поддерживаемыми системой модулями
|
||||||
|
extern std::vector<IoTSensor*> iotSensors; //v3dev: вектор ссылок базового класса IoTSensor - список всех запущенных сенсоров
|
||||||
|
|
||||||
void loadConfig() {
|
void loadConfig() {
|
||||||
configSetupJson = readFile("config.json", 4096);
|
configSetupJson = readFile("config.json", 4096);
|
||||||
configSetupJson.replace("\r\n", "");
|
configSetupJson.replace("\r\n", "");
|
||||||
@@ -111,6 +115,21 @@ void handle_uptime() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void clearVectors() {
|
void clearVectors() {
|
||||||
|
|
||||||
|
//v3dev: очищаем вектора с сенсорами...
|
||||||
|
for (unsigned int i = 0; i < iotSensors.size(); i++) {
|
||||||
|
IoTSensor* tmpptr = iotSensors[i]; //временно сохраняем указатель на сенсор, т.к. его преждевременное удаление оставит поломаную запись в векторе, к которой может обратиться ядро и вызвать исключение
|
||||||
|
iotSensors.erase(iotSensors.begin() + i); //сначала удаляем элемент вектора,
|
||||||
|
delete tmpptr; //а далее уже удаляем объект сенсора
|
||||||
|
}
|
||||||
|
//...и переменными
|
||||||
|
//...
|
||||||
|
//заставляем модули прибраться за собой
|
||||||
|
for (unsigned int i = 0; i < iotModules.size(); i++) {
|
||||||
|
iotModules[i]->clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
#ifdef EnableLogging
|
#ifdef EnableLogging
|
||||||
if (myLogging != nullptr) {
|
if (myLogging != nullptr) {
|
||||||
myLogging->clear();
|
myLogging->clear();
|
||||||
@@ -134,13 +153,6 @@ void clearVectors() {
|
|||||||
countDown_EnterCounter = -1;
|
countDown_EnterCounter = -1;
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef EnableButtonOut
|
|
||||||
if (myButtonOut != nullptr) {
|
|
||||||
myButtonOut->clear();
|
|
||||||
}
|
|
||||||
buttonOut_KeyList = "";
|
|
||||||
buttonOut_EnterCounter = -1;
|
|
||||||
#endif
|
|
||||||
#ifdef EnableInput
|
#ifdef EnableInput
|
||||||
if (myInput != nullptr) {
|
if (myInput != nullptr) {
|
||||||
myInput->clear();
|
myInput->clear();
|
||||||
@@ -161,13 +173,6 @@ void clearVectors() {
|
|||||||
}
|
}
|
||||||
pwmOut_KeyList = "";
|
pwmOut_KeyList = "";
|
||||||
pwmOut_EnterCounter = -1;
|
pwmOut_EnterCounter = -1;
|
||||||
#endif
|
|
||||||
//==================================
|
|
||||||
//ИНТЕГРИРУЮ: Вторая интеграция в ядро. Следим за наименованием
|
|
||||||
#ifdef EnableSensorDallas
|
|
||||||
if (mySensorDallas2 != nullptr) {
|
|
||||||
mySensorDallas2->clear();
|
|
||||||
}
|
|
||||||
#endif
|
#endif
|
||||||
#ifdef EnableSensorUltrasonic
|
#ifdef EnableSensorUltrasonic
|
||||||
if (mySensorUltrasonic != nullptr) {
|
if (mySensorUltrasonic != nullptr) {
|
||||||
@@ -189,11 +194,6 @@ void clearVectors() {
|
|||||||
mySensorBme280->clear();
|
mySensorBme280->clear();
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
#ifdef EnableSensorSht20
|
|
||||||
if (mySensorSht20 != nullptr) {
|
|
||||||
mySensorSht20->clear();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#ifdef EnableSensorBmp280
|
#ifdef EnableSensorBmp280
|
||||||
if (mySensorBmp280 != nullptr) {
|
if (mySensorBmp280 != nullptr) {
|
||||||
mySensorBmp280->clear();
|
mySensorBmp280->clear();
|
||||||
|
|||||||
79
src/Modules/Sensors/IoTSensorButtonIn.cpp
Normal file
79
src/Modules/Sensors/IoTSensorButtonIn.cpp
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Utils/StringUtils.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
#include <Bounce2.h>
|
||||||
|
|
||||||
|
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() {
|
||||||
|
return new IoTModuleButtonIn();
|
||||||
|
}
|
||||||
117
src/Modules/Sensors/IoTSensorDallasTemp.cpp
Normal file
117
src/Modules/Sensors/IoTSensorDallasTemp.cpp
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Utils/StringUtils.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include "DallasTemperature.h"
|
||||||
|
#include <OneWire.h>
|
||||||
|
#include <map>
|
||||||
|
|
||||||
|
|
||||||
|
//глобальные списки необходимы для хранения объектов об активных линиях 1-wire используемых разными датчиками из модуля. Ключ - номер пина
|
||||||
|
std::map<int, OneWire*> oneWireTemperatureArray;
|
||||||
|
std::map<int, DallasTemperature*> sensorsTemperatureArray;
|
||||||
|
|
||||||
|
class IoTSensorDallas: public IoTSensor {
|
||||||
|
private:
|
||||||
|
//описание переменных экземпляра датчика - аналог глобальных переменных из Arduino
|
||||||
|
//для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии
|
||||||
|
OneWire* oneWire;
|
||||||
|
DallasTemperature* sensors;
|
||||||
|
|
||||||
|
//описание параметров передаваемых из настроек датчика из веба
|
||||||
|
String _addr;
|
||||||
|
unsigned int _pin;
|
||||||
|
unsigned int _index;
|
||||||
|
|
||||||
|
public:
|
||||||
|
//аналог setup() из Arduino
|
||||||
|
IoTSensorDallas(String parameters) {
|
||||||
|
//передаем часть базовых параметров в конструктор базового класса для обеспечения работы его методов
|
||||||
|
init(jsonReadStr(parameters, "key"), jsonReadStr(parameters, "id"), jsonReadInt(parameters, "int"));
|
||||||
|
_pin = jsonReadInt(parameters, "pin");
|
||||||
|
_index = jsonReadInt(parameters, "index");
|
||||||
|
_addr = jsonReadStr(parameters, "addr");
|
||||||
|
|
||||||
|
//учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась
|
||||||
|
if (oneWireTemperatureArray.find(_pin) == oneWireTemperatureArray.end()) {
|
||||||
|
oneWire = new OneWire((uint8_t)_pin);
|
||||||
|
sensors = new DallasTemperature();
|
||||||
|
sensors->setOneWire(oneWire);
|
||||||
|
sensors->begin();
|
||||||
|
sensors->setResolution(12);
|
||||||
|
|
||||||
|
oneWireTemperatureArray[_pin] = oneWire;
|
||||||
|
sensorsTemperatureArray[_pin] = sensors;
|
||||||
|
} else {
|
||||||
|
oneWire = oneWireTemperatureArray[_pin];
|
||||||
|
sensors = sensorsTemperatureArray[_pin];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~IoTSensorDallas() {}
|
||||||
|
|
||||||
|
//аналог loop() из Arduino но квотируемый по времени параметром interval
|
||||||
|
void doByInterval() {
|
||||||
|
//запускаем опрос измерений у всех датчиков на линии
|
||||||
|
sensors->requestTemperatures();
|
||||||
|
|
||||||
|
//Определяем адрес. Если парамтер addr не установлен, то узнаем адрес по индексу
|
||||||
|
DeviceAddress deviceAddress;
|
||||||
|
if (_addr == "") {
|
||||||
|
sensors->getAddress(deviceAddress, _index);
|
||||||
|
} else {
|
||||||
|
string2hex(_addr.c_str(), deviceAddress);
|
||||||
|
}
|
||||||
|
//получаем температуру по адресу
|
||||||
|
float value = sensors->getTempC(deviceAddress);
|
||||||
|
|
||||||
|
char addrStr[20] = "";
|
||||||
|
hex2string(deviceAddress, 8, addrStr);
|
||||||
|
|
||||||
|
regEvent((String)value, "addr: " + String(addrStr)); //обязательный вызов для отправки результата работы
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
//технический класс для взаимодействия с ядром, меняются только названия
|
||||||
|
class IoTModuleDallasTemp: public IoTModule {
|
||||||
|
//обязательный метод для инициализации экземпляра датчика, вызывается при чтении конфигурации. Нужно учитывать, что некоторые датчики могут обеспечивать
|
||||||
|
//несколько измерений, для каждого будет отдельный вызов.
|
||||||
|
void* initInstance(String parameters) {
|
||||||
|
return new IoTSensorDallas(parameters);
|
||||||
|
};
|
||||||
|
|
||||||
|
//обязательный к заполнению метод, если модуль использует свои глобальные переменные. Необходимо сбросить и очистить используемую память.
|
||||||
|
void clear() {
|
||||||
|
// for (auto it = sensorsTemperatureArray.cbegin(), next_it = it; it != sensorsTemperatureArray.cend(); it = next_it) {
|
||||||
|
// ++next_it;
|
||||||
|
// DallasTemperature* tmpptr = it->second; //временно сохраняем указатель на сенсор, т.к. его преждевременное удаление оставит поломаную запись в векторе, к которой может обратиться ядро и вызвать исключение
|
||||||
|
// sensorsTemperatureArray.erase(it);
|
||||||
|
// delete tmpptr; //а далее уже удаляем объект сенсора
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for (auto it = oneWireTemperatureArray.cbegin(), next_it = it; it != oneWireTemperatureArray.cend(); it = next_it) {
|
||||||
|
// ++next_it;
|
||||||
|
// OneWire* tmpptr = it->second; //временно сохраняем указатель на сенсор, т.к. его преждевременное удаление оставит поломаную запись в векторе, к которой может обратиться ядро и вызвать исключение
|
||||||
|
// oneWireTemperatureArray.erase(it);
|
||||||
|
// delete tmpptr; //а далее уже удаляем объект сенсора
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
//обязательный метод для отправки информации о модуле,
|
||||||
|
ModuleInfo getInfo() {
|
||||||
|
ModuleInfo MI;
|
||||||
|
MI.name = "dallas-temp";
|
||||||
|
MI.title = "Датчик температуры Ds18b20";
|
||||||
|
MI.parameters = "{\"key\": \"dallas-temp\", \"id\": \"tmp\", \"addr\": \"\", \"int\": \"10\", \"pin\": \"18\", \"index\": \"0\"}";
|
||||||
|
MI.type = "Sensor";
|
||||||
|
return MI;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
//точка входа в модуль для заполнения вектора, требуется только изменить имя и прописать в файле api.cpp
|
||||||
|
void* getApiIoTSensorDallasTemp() {
|
||||||
|
return new IoTModuleDallasTemp();
|
||||||
|
}
|
||||||
80
src/Modules/Sensors/IoTSensorSHT20.cpp
Normal file
80
src/Modules/Sensors/IoTSensorSHT20.cpp
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Utils/StringUtils.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include "Wire.h"
|
||||||
|
#include "SHT2x.h"
|
||||||
|
|
||||||
|
|
||||||
|
SHT2x* sht = nullptr;
|
||||||
|
|
||||||
|
class IoTSensorSHT20: public IoTSensor {
|
||||||
|
private:
|
||||||
|
//описание переменных экземпляра датчика - аналог глобальных переменных из Arduino
|
||||||
|
|
||||||
|
//описание параметров передаваемых из настроек датчика из веба
|
||||||
|
float _c;
|
||||||
|
|
||||||
|
public:
|
||||||
|
//аналог setup() из Arduino
|
||||||
|
IoTSensorSHT20(String parameters) {
|
||||||
|
//передаем часть базовых параметров в конструктор базового класса для обеспечения работы его методов
|
||||||
|
init(jsonReadStr(parameters, "key"), jsonReadStr(parameters, "id"), jsonReadInt(parameters, "int"));
|
||||||
|
_c = jsonReadFloat(parameters, "c");
|
||||||
|
|
||||||
|
if (!sht) {
|
||||||
|
sht = new SHT2x;
|
||||||
|
sht->begin();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~IoTSensorSHT20() {}
|
||||||
|
|
||||||
|
//аналог loop() из Arduino но квотируемый по времени параметром interval
|
||||||
|
void doByInterval() {
|
||||||
|
//запускаем опрос измерений
|
||||||
|
sht->read();
|
||||||
|
float value;
|
||||||
|
if (getKey() == "anydataTemp") {
|
||||||
|
value = sht->getTemperature();
|
||||||
|
} else {
|
||||||
|
value = sht->getHumidity();
|
||||||
|
}
|
||||||
|
value = _c * value;
|
||||||
|
|
||||||
|
regEvent((String)value, ""); //обязательный вызов для отправки результата измерений
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
//технический класс для взаимодействия с ядром, меняются только названия
|
||||||
|
class IoTModuleSHT20: public IoTModule {
|
||||||
|
//обязательный метод для инициализации экземпляра датчика, вызывается при чтении конфигурации. Нужно учитывать, что некоторые датчики могут обеспечивать
|
||||||
|
//несколько измерений, для каждого будет отдельный вызов.
|
||||||
|
void* initInstance(String parameters) {
|
||||||
|
return new IoTSensorSHT20(parameters);
|
||||||
|
};
|
||||||
|
|
||||||
|
//обязательный к заполнению метод, если модуль использует свои глобальные переменные. Необходимо сбросить и очистить используемую память.
|
||||||
|
void clear() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//обязательный метод для отправки информации о модуле,
|
||||||
|
ModuleInfo getInfo() {
|
||||||
|
ModuleInfo MI;
|
||||||
|
MI.name = "sht20";
|
||||||
|
MI.title = "Датчик температуры и влажности SHT2x, HTU2x and Si70xx";
|
||||||
|
//v3dev: key - это внутренний маркер-ключ определяющий значение для измерений, на этапе апробации на ver3 установлено значение = типу виджета, т.к. в таблице настройки отсутствует парамтер key в этой интерпретации
|
||||||
|
MI.parameters = "{\"key\": \"anydataTemp\", \"id\": \"SHT20\", \"int\": \"10\", \"c\": \"1\"}, {\"key\": \"anydataHum\", \"id\": \"SHT20\", \"int\": \"10\", \"c\": \"1\"}";
|
||||||
|
MI.type = "Sensor";
|
||||||
|
return MI;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
//точка входа в модуль для заполнения вектора, требуется только изменить имя и прописать в файле api.cpp
|
||||||
|
void* getApiIoTSensorSHT20() {
|
||||||
|
return new IoTModuleSHT20();
|
||||||
|
}
|
||||||
98
src/Modules/Variables/IoTVariableButtonOut.cpp
Normal file
98
src/Modules/Variables/IoTVariableButtonOut.cpp
Normal 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();
|
||||||
|
}
|
||||||
73
src/Modules/Variables/IoTVariableVirtual.cpp
Normal file
73
src/Modules/Variables/IoTVariableVirtual.cpp
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
#include "Utils/JsonUtils.h"
|
||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Utils/StringUtils.h"
|
||||||
|
|
||||||
|
#include "Class/IoTVariable.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
|
||||||
|
|
||||||
|
class IoTVariableVirtual: public IoTVariable {
|
||||||
|
private:
|
||||||
|
//описание переменных экземпляра Variable - аналог глобальных переменных из Arduino
|
||||||
|
String _value;
|
||||||
|
|
||||||
|
//описание параметров передаваемых из настроек переменной из веба
|
||||||
|
|
||||||
|
public:
|
||||||
|
//аналог setup() из Arduino
|
||||||
|
IoTVariableVirtual(String parameters) {
|
||||||
|
//передаем часть базовых параметров в конструктор базового класса для обеспечения работы его методов
|
||||||
|
init(jsonReadStr(parameters, "key"), jsonReadStr(parameters, "id"));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
~IoTVariableVirtual() {}
|
||||||
|
|
||||||
|
//аналог loop() из Arduino
|
||||||
|
void loop() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//вызывается при выполнении команды связанной с конкретным экземпляром переменной
|
||||||
|
String execute(String command) {
|
||||||
|
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
//вызывается при любом изменении переменной
|
||||||
|
void selfExec() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
String getValue(String key="") {
|
||||||
|
return _value;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
//технический класс для взаимодействия с ядром, меняются только названия
|
||||||
|
class IoTModuleVariable: public IoTModule {
|
||||||
|
//обязательный метод для инициализации экземпляра переменной, вызывается при чтении конфигурации.
|
||||||
|
void* initInstance(String parameters) {
|
||||||
|
return new IoTVariableVirtual(parameters);
|
||||||
|
};
|
||||||
|
|
||||||
|
//обязательный к заполнению метод, если модуль использует свои глобальные переменные. Необходимо сбросить и очистить используемую память.
|
||||||
|
void clear() {
|
||||||
|
//и так чисто
|
||||||
|
}
|
||||||
|
|
||||||
|
//обязательный метод для отправки информации о модуле,
|
||||||
|
ModuleInfo getInfo() {
|
||||||
|
ModuleInfo MI;
|
||||||
|
MI.name = "variable";
|
||||||
|
MI.title = "Переменная для хранения значений пользователя";
|
||||||
|
MI.parameters = "{\"key\": \"variable\", \"id\": \"var\"}";
|
||||||
|
MI.type = "Variable";
|
||||||
|
return MI;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
//точка входа в модуль для заполнения вектора, требуется только изменить имя и прописать в файле api.cpp
|
||||||
|
void* getApiIoTVariableVirtual() {
|
||||||
|
return new IoTModuleVariable();
|
||||||
|
}
|
||||||
25
src/Modules/api.cpp
Normal file
25
src/Modules/api.cpp
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
#include "Utils/SerialPrint.h"
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
#include "Class/IoTVariable.h"
|
||||||
|
|
||||||
|
extern std::vector<IoTModule*> iotModules; //v3dev: вектор ссылок базового класса IoTModule - интерфейсы для общения со всеми поддерживаемыми системой модулями
|
||||||
|
|
||||||
|
//объявляем функцию для добавления модуля в вектор
|
||||||
|
void* getApiIoTSensorDallasTemp();
|
||||||
|
void* getApiIoTSensorSHT20();
|
||||||
|
void* getApiIoTSensorButtonIn();
|
||||||
|
|
||||||
|
void* getApiIoTVariableVirtual();
|
||||||
|
void* getApiIoTVariableButtonOut();
|
||||||
|
|
||||||
|
//формируем вектор модулей путем вызова из каждого модуля специальной функции
|
||||||
|
//в дальнейшем предполагается отключать вызов, если модуль не участвует в сборке
|
||||||
|
void InitModulesApi() {
|
||||||
|
iotModules.push_back((IoTModule*) getApiIoTSensorDallasTemp());
|
||||||
|
iotModules.push_back((IoTModule*) getApiIoTSensorSHT20());
|
||||||
|
iotModules.push_back((IoTModule*) getApiIoTSensorButtonIn());
|
||||||
|
|
||||||
|
iotModules.push_back((IoTModule*) getApiIoTVariableVirtual());
|
||||||
|
iotModules.push_back((IoTModule*) getApiIoTVariableButtonOut());
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
@@ -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
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
#include "Consts.h"
|
|
||||||
#ifdef EnableSensorDallas
|
|
||||||
#include "items/vSensorDallas.h"
|
|
||||||
#include "BufferExecute.h"
|
|
||||||
#include "Class/LineParsing.h"
|
|
||||||
#include "Global.h"
|
|
||||||
#include "DallasTemperature.h"
|
|
||||||
#include "Utils/StringUtils.h"
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: переменные необходимые для работы интегрируемой библиотеки. Аналог Arduino
|
|
||||||
OneWire* oneWire;
|
|
||||||
DallasTemperature sensors;
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ:
|
|
||||||
//Для каждого датчика указанного в конфигурации вызывается конструктор для настройки перед запуском. Аналог функции setup() в Arduino.
|
|
||||||
//В параметрах передаются дополнительные настройки, указанные все в той же таблице настройки устройства.
|
|
||||||
SensorDallas::SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String addr, String key) {
|
|
||||||
//все особые параметры сливаем в локальные переменные экземпляра для будущего доступа
|
|
||||||
_interval = interval * 1000;
|
|
||||||
_key = key;
|
|
||||||
_pin = pin;
|
|
||||||
_index = index;
|
|
||||||
_addr = addr;
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ:
|
|
||||||
//вызываем необходимые инициирующие функции интегрируемой библиотеки
|
|
||||||
oneWire = new OneWire((uint8_t)_pin);
|
|
||||||
sensors.setOneWire(oneWire);
|
|
||||||
sensors.begin();
|
|
||||||
sensors.setResolution(12);
|
|
||||||
}
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: оставляем как есть или развиваем, если нужно правильно завершить работу с интегрируемой библиотекой после отключения датчика
|
|
||||||
SensorDallas::~SensorDallas() {}
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: аналог loop() в Arduino. Требуется изменить, если интегрируемая библиотека нуждается в другом алгоритме квотирования времени.
|
|
||||||
void SensorDallas::loop() {
|
|
||||||
currentMillis = millis();
|
|
||||||
difference = currentMillis - prevMillis;
|
|
||||||
if (difference >= _interval) {
|
|
||||||
prevMillis = millis();
|
|
||||||
readDallas();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: вызывается из цикла loop каждый установленный временно интервал в параметрах датчика. Необходимо изменить для чтения данных из датчика.
|
|
||||||
void SensorDallas::readDallas() {
|
|
||||||
//запускаем опрос измерений у всех датчиков на линии
|
|
||||||
sensors.requestTemperatures();
|
|
||||||
|
|
||||||
//Определяем адрес. Если парамтер addr не установлен, то узнаем адрес по индексу
|
|
||||||
DeviceAddress deviceAddress;
|
|
||||||
if (_addr == "") {
|
|
||||||
sensors.getAddress(deviceAddress, _index);
|
|
||||||
} else {
|
|
||||||
string2hex(_addr.c_str(), deviceAddress);
|
|
||||||
}
|
|
||||||
|
|
||||||
//получаем температуру по адресу
|
|
||||||
float value = sensors.getTempC(deviceAddress);
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: блок генерации уведомлений в ядре системы. Стоит обратить внимание только на формат выводимого сообщения в консоли.
|
|
||||||
eventGen2(_key, String(value));
|
|
||||||
jsonWriteStr(configLiveJson, _key, String(value));
|
|
||||||
publishStatus(_key, String(value));
|
|
||||||
char addrStr[20] = "";
|
|
||||||
hex2string(deviceAddress, 8, addrStr);
|
|
||||||
SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(value) + "' addr: " + String(addrStr));
|
|
||||||
}
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: глобальная переменная необходима для интеграции в ядро. Следим за наименованием.
|
|
||||||
MySensorDallasVector* mySensorDallas2 = nullptr;
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: функция вызывается ядром для каждой записи в таблице настроки для создания экземпляров датчиков
|
|
||||||
//некоторые датчики записаны в таблице в виде нескольких строк, поэтому необходимо контролировать итерации обращения к данной функции
|
|
||||||
void dallas() {
|
|
||||||
//ИНТЕГРИРУЮ: не меняем
|
|
||||||
myLineParsing.update();
|
|
||||||
//ИНТЕГРИРУЮ: устанавливаем в соответствии с параметрами таблицы
|
|
||||||
String interval = myLineParsing.gint();
|
|
||||||
String pin = myLineParsing.gpin();
|
|
||||||
String index = myLineParsing.gindex();
|
|
||||||
String key = myLineParsing.gkey();
|
|
||||||
String addr = myLineParsing.gaddr();
|
|
||||||
//ИНТЕГРИРУЮ: не меняем
|
|
||||||
myLineParsing.clear();
|
|
||||||
|
|
||||||
//ИНТЕГРИРУЮ: блок создания экземпляров датчиков. Обратить внимание на наименования и передаваемые параметры в конструктор
|
|
||||||
static bool firstTime = true;
|
|
||||||
if (firstTime) mySensorDallas2 = new MySensorDallasVector();
|
|
||||||
firstTime = false;
|
|
||||||
mySensorDallas2->push_back(SensorDallas(interval.toInt(), pin.toInt(), index.toInt(), addr, key));
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
#include "Consts.h"
|
|
||||||
#ifdef EnableSensorSht20
|
|
||||||
#include "items/vSensorSHT20.h"
|
|
||||||
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
#include "BufferExecute.h"
|
|
||||||
#include "Class/LineParsing.h"
|
|
||||||
#include "Global.h"
|
|
||||||
|
|
||||||
#include "Wire.h"
|
|
||||||
#include "SHT2x.h"
|
|
||||||
SHT2x* sht = nullptr;
|
|
||||||
|
|
||||||
SensorSht20::SensorSht20(const paramsSht& paramsTmp, const paramsSht& paramsHum) {
|
|
||||||
_paramsTmp = paramsSht(paramsTmp);
|
|
||||||
_paramsHum = paramsSht(paramsHum);
|
|
||||||
|
|
||||||
if (!sht) {
|
|
||||||
sht = new SHT2x;
|
|
||||||
}
|
|
||||||
|
|
||||||
sht->begin();
|
|
||||||
|
|
||||||
uint8_t stat = sht->getStatus();
|
|
||||||
Serial.print(stat, HEX);
|
|
||||||
Serial.println();
|
|
||||||
}
|
|
||||||
|
|
||||||
SensorSht20::~SensorSht20() {}
|
|
||||||
|
|
||||||
void SensorSht20::loop() {
|
|
||||||
difference = millis() - prevMillis;
|
|
||||||
if (difference >= _paramsHum.interval) {
|
|
||||||
prevMillis = millis();
|
|
||||||
read();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void SensorSht20::read() {
|
|
||||||
sht->read();
|
|
||||||
|
|
||||||
float tmp = sht->getTemperature();
|
|
||||||
float hum = sht->getHumidity();
|
|
||||||
|
|
||||||
tmp = tmp * _paramsTmp.c;
|
|
||||||
hum = hum * _paramsHum.c;
|
|
||||||
|
|
||||||
eventGen2(_paramsTmp.key, String(tmp));
|
|
||||||
jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp));
|
|
||||||
publishStatus(_paramsTmp.key, String(tmp));
|
|
||||||
String path = mqttRootDevice + "/" +_paramsTmp.key + "/status";
|
|
||||||
String json = "{}";
|
|
||||||
jsonWriteStr(json, "status", String(tmp));
|
|
||||||
String MyJson = json;
|
|
||||||
jsonWriteStr(MyJson, "topic", path);
|
|
||||||
ws.textAll(MyJson);
|
|
||||||
|
|
||||||
SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp));
|
|
||||||
|
|
||||||
eventGen2(_paramsHum.key, String(hum));
|
|
||||||
jsonWriteStr(configLiveJson, _paramsHum.key, String(hum));
|
|
||||||
publishStatus(_paramsHum.key, String(hum));
|
|
||||||
path = mqttRootDevice + "/" +_paramsHum.key + "/status";
|
|
||||||
json = "{}";
|
|
||||||
jsonWriteStr(json, "status", String(hum));
|
|
||||||
MyJson = json;
|
|
||||||
jsonWriteStr(MyJson, "topic", path);
|
|
||||||
ws.textAll(MyJson);
|
|
||||||
SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum));
|
|
||||||
}
|
|
||||||
|
|
||||||
MySensorSht20Vector* mySensorSht20 = nullptr;
|
|
||||||
|
|
||||||
void sht20Sensor() {
|
|
||||||
myLineParsing.update();
|
|
||||||
String key = myLineParsing.gkey();
|
|
||||||
String interval = myLineParsing.gint();
|
|
||||||
String c = myLineParsing.gc();
|
|
||||||
myLineParsing.clear();
|
|
||||||
|
|
||||||
static int enterCnt = -1;
|
|
||||||
enterCnt++;
|
|
||||||
|
|
||||||
static paramsSht paramsTmp;
|
|
||||||
static paramsSht paramsHum;
|
|
||||||
|
|
||||||
if (enterCnt == 0) {
|
|
||||||
paramsTmp.key = key;
|
|
||||||
paramsTmp.c = c.toFloat();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (enterCnt == 1) {
|
|
||||||
paramsHum.key = key;
|
|
||||||
paramsHum.c = c.toFloat();
|
|
||||||
paramsHum.interval = interval.toInt() * 1000;
|
|
||||||
|
|
||||||
static bool firstTime = true;
|
|
||||||
if (firstTime) mySensorSht20 = new MySensorSht20Vector();
|
|
||||||
firstTime = false;
|
|
||||||
mySensorSht20->push_back(SensorSht20(paramsTmp, paramsHum));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
47
src/main.cpp
47
src/main.cpp
@@ -19,7 +19,6 @@
|
|||||||
#include "Utils/statUtils.h"
|
#include "Utils/statUtils.h"
|
||||||
#include "Utils/Timings.h"
|
#include "Utils/Timings.h"
|
||||||
#include "Utils/WebUtils.h"
|
#include "Utils/WebUtils.h"
|
||||||
#include "items/ButtonInClass.h"
|
|
||||||
#include "items/vCountDown.h"
|
#include "items/vCountDown.h"
|
||||||
#include "items/vImpulsOut.h"
|
#include "items/vImpulsOut.h"
|
||||||
#include "items/vLogging.h"
|
#include "items/vLogging.h"
|
||||||
@@ -28,14 +27,25 @@
|
|||||||
#include "items/vSensorBme280.h"
|
#include "items/vSensorBme280.h"
|
||||||
#include "items/vSensorBmp280.h"
|
#include "items/vSensorBmp280.h"
|
||||||
#include "items/vSensorCcs811.h"
|
#include "items/vSensorCcs811.h"
|
||||||
#include "items/vSensorDallas.h"
|
|
||||||
#include "items/vSensorDht.h"
|
#include "items/vSensorDht.h"
|
||||||
#include "items/vSensorNode.h"
|
#include "items/vSensorNode.h"
|
||||||
#include "items/vSensorPzem.h"
|
#include "items/vSensorPzem.h"
|
||||||
#include "items/vSensorSHT20.h"
|
|
||||||
#include "items/vSensorUltrasonic.h"
|
#include "items/vSensorUltrasonic.h"
|
||||||
#include "items/vSensorUptime.h"
|
#include "items/vSensorUptime.h"
|
||||||
//#include "WebServer.h"
|
//#include "WebServer.h"
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
#include "Class/IoTSensor.h"
|
||||||
|
#include "Class/IoTModule.h"
|
||||||
|
#include "Class/IoTVariable.h"
|
||||||
|
|
||||||
|
|
||||||
|
std::vector<IoTModule*> iotModules; //v3dev: вектор ссылок базового класса IoTModule - интерфейсы для общения со всеми поддерживаемыми системой модулями
|
||||||
|
std::vector<IoTSensor*> iotSensors; //v3dev: вектор ссылок базового класса IoTSensor - список всех запущенных сенсоров
|
||||||
|
std::vector<IoTVariable*> iotVariables; //v3dev: вектор ссылок базового класса IoTVariable - список всех подготовленных переменных
|
||||||
|
void InitModulesApi(); //v3dev: инициализация модуля при первом вызове .
|
||||||
|
|
||||||
|
|
||||||
void not_async_actions();
|
void not_async_actions();
|
||||||
|
|
||||||
Timings metric;
|
Timings metric;
|
||||||
@@ -60,6 +70,10 @@ void setup() {
|
|||||||
clockInit();
|
clockInit();
|
||||||
timeInit();
|
timeInit();
|
||||||
itemsListInit();
|
itemsListInit();
|
||||||
|
|
||||||
|
SerialPrint("I", "Debug", "call setup");
|
||||||
|
InitModulesApi(); //v3dev: инициализация модуля при первом вызове .
|
||||||
|
|
||||||
espInit();
|
espInit();
|
||||||
routerConnect();
|
routerConnect();
|
||||||
#ifdef EnableTelegram
|
#ifdef EnableTelegram
|
||||||
@@ -146,13 +160,7 @@ void loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
#ifdef EnableSensorDallas
|
|
||||||
if (mySensorDallas2 != nullptr) {
|
|
||||||
for (unsigned int i = 0; i < mySensorDallas2->size(); i++) {
|
|
||||||
mySensorDallas2->at(i).loop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#ifdef EnableSensorUltrasonic
|
#ifdef EnableSensorUltrasonic
|
||||||
if (mySensorUltrasonic != nullptr) {
|
if (mySensorUltrasonic != nullptr) {
|
||||||
for (unsigned int i = 0; i < mySensorUltrasonic->size(); i++) {
|
for (unsigned int i = 0; i < mySensorUltrasonic->size(); i++) {
|
||||||
@@ -182,13 +190,6 @@ void loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
#ifdef EnableSensorSht20
|
|
||||||
if (mySensorSht20 != nullptr) {
|
|
||||||
for (unsigned int i = 0; i < mySensorSht20->size(); i++) {
|
|
||||||
mySensorSht20->at(i).loop();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#ifdef EnableSensorAny
|
#ifdef EnableSensorAny
|
||||||
if (mySensorAny != nullptr) {
|
if (mySensorAny != nullptr) {
|
||||||
for (unsigned int i = 0; i < mySensorAny->size(); i++) {
|
for (unsigned int i = 0; i < mySensorAny->size(); i++) {
|
||||||
@@ -231,7 +232,13 @@ void loop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
#ifdef EnableButtonIn
|
|
||||||
myButtonIn.loop();
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
|
//v3dev: перебираем все экземпляры сенсоров должно заменить в v4 все вызовы сенсоров выше
|
||||||
|
for (unsigned int i = 0; i < iotSensors.size(); i++) {
|
||||||
|
iotSensors[i]->loop();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user