13 Commits

Author SHA1 Message Date
Dmitry Borisenko
6fe10441b1 Merge pull request #112 from biveraxe/ver3dev
Завершаем перенос ButtonOut в новую систему классов, требуется дорабо…
2022-01-12 13:10:43 +01:00
c002bafc1c Завершаем перенос ButtonOut в новую систему классов, требуется доработка взаимодействия с виджитами 2021-12-31 10:55:38 +03:00
IoT Manager
6b481de207 Merge pull request #111 from biveraxe/ver3dev
Класс IoTSensor вроде готов
2021-12-31 01:52:44 +01:00
b0fb71832c Убираем глобальные переменные из модулей, есть веростность, что получится при линковке не включать модули, которые исключены из api.cpp 2021-12-30 12:11:19 +03:00
6a7653c7ff Добавляем IoTVariable для дальнейшей доработки 2021-12-30 11:56:08 +03:00
ee94853ad9 Переносм функционал физической кнопки в класс IoTSensor 2021-12-28 11:04:14 +03:00
ede9092a73 Исправляем проблему начала измерений. Не все строки перенесены были из основной версии модуля. 2021-12-27 22:47:30 +03:00
30cf9cc3bb Исправляем ошибку при очистке глобальных списков в модуле Dallas 2021-12-27 22:05:23 +03:00
41f4be6139 Добавляем работу сенсоров с несколькими измерениями. Добавляем первую версию класса Variable. 2021-12-27 21:24:55 +03:00
IoT Manager
c8df0de972 Merge pull request #109 from biveraxe/ver3dev
Первая интеграция глобальных векторов в ver3dev
2021-12-26 18:39:57 +01:00
bebea0732a Добавляем в модуль далласа поддержку нескольких линий одновременно 2021-12-24 20:03:38 +03:00
5fecb51d69 Добавляем комментарии и наводим порядок 2021-12-23 13:02:06 +03:00
faa865e78d Добавляем механизм глобальных векторов для модулей и сенсоров. Модуль Dallas полностью интегрирован поновому 2021-12-23 09:09:26 +03:00
45 changed files with 830 additions and 1196 deletions

53
.vscode/settings.json vendored
View File

@@ -1,5 +1,54 @@
{
"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
}

View File

@@ -38,6 +38,6 @@
0;sensor;anyid;anydata;Сенсоры;Параметр;1;c[1];int[10];type[HDC1080_hum];addr[0x76]*
0;sensor;anyid;anydata;Сенсоры;Параметр;1;c[1];int[10];type[AHTX0_temp];addr[0x76]
0;sensor;anyid;anydata;Сенсоры;Параметр;1;c[1];int[10];type[AHTX0_hum];addr[0x76]*
0;LCD2004;lcdid;na;na;IP;1;addr[0x27];k[16,2];int[10];c[0,0];val[ip]*
0;TM1637;dispid;na;na;f;1;pin[12,13];int[10];c[4];k[0];val[1234]*
0;sensor;anyid;anydata;Page;Tmp;1;c[0];k[0];int[10];type[LCD];val[any]
0;sensor;anyid;anydata;Page;Hum;1;c[8];k[1];int[10];type[LCD];val[any]*
0;sensor;anyid;anydata;Сенсоры;Параметр;1;c[1];int[10];type[type1];addr[0x76]*

Binary file not shown.

View File

@@ -1,11 +1,10 @@
0;button-out;btnid;toggleBtn;Кнопки;Освещение;order*
0;button-out;100-0;toggleBtn;Кнопки;Освещение;order;type[ms]*
0;input-value;dgtid;inputDigit;Ввод;Введите#цифру;order*
0;input;dgtid;inputDigit;Ввод;Введите#цифру;order*
0;input;tmid;inputTime;Ввод;Введите#время;order*
0;output;txtid;anydata;Вывод;Сигнализация;order*
0;count-down;cntid;anydata;Таймер;Обратный#отчет;order*
0;sensor-node;100-0;anydataTemp;MySensors;Температура;order;tm1[30];tm2[60];c[1];k[0]*
0;logging;crtid;chart;Графики;История;order;val[any];int[60];cnt[100]*
0;logging;crtid;chart3;Графики;История;order;val[any];int[23:30];cnt[100];st[0]*
0;uptime;uptid;anydataTime;Системные;%name%#uptime;order;int[60]*
0;LCD2004;lcdid;anydata;Вывод;IP;1;addr[0x27];k[20,4];int[10];c[0,0];val[ip]*
0;uptime;uptid;anydataTime;Системные;%name%#uptime;order;int[60]*

Binary file not shown.

21
include/Class/IoTModule.h Normal file
View 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
View 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;
};

View 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; //код переменной для идентификации событий, команд в сценариях и логах
};

View File

@@ -127,7 +127,6 @@ class LineParsing {
}
if (_pin != "") {
/*
if (_pin.indexOf(",") == -1) {
if (!isPinExist(_pin.toInt()) || !isDigitStr(_pin)) {
pinErrors++;
@@ -140,17 +139,6 @@ class LineParsing {
pinErrors++;
_pin = "";
}
}*/
String tmpstr;
for (int i=0; i<15; i++) {
tmpstr = selectFromMarkerToMarker(_pin, ",", i);
if(tmpstr == "not found") break;
if(!isDigitStr(tmpstr) || !isPinExist(tmpstr.toInt())){
pinErrors++;
_pin = "";
break;
}
}
}
@@ -222,6 +210,9 @@ class LineParsing {
String gtm2() {
return _tm2;
}
String gdb() {
return _db;
}
int getPinErrors() {
return pinErrors;

View File

@@ -10,14 +10,10 @@ class Scenario {
if (!jsonReadBool(configSetupJson, "scen")) {
return;
}
String allBlocks = scenario;
allBlocks += "\n";
String incommingEvent = selectToMarker(eventBuf, ",");
if (incommingEvent == "") {
return;
}
String incommingEventKey = selectToMarker(incommingEvent, " ");
String incommingEventValue = selectToMarkerLast(incommingEvent, " ");
@@ -163,20 +159,18 @@ class Scenario {
private:
bool isScenarioNeedToDo(String &condition, String &incommingEventKey, String &incommingEventValue, int type) {
if (condition == "") return false;
bool res = false;
String setEventKey = selectFromMarkerToMarker(condition, " ", 0);
if (isEventExist(incommingEventKey, setEventKey)) {
String setEventSign;
String setEventValue;
String cloneOfIncommingEventValue = incommingEventValue; //клонируем для изменения в preCalculation и передачи для проверки по условиям
if (type == 1) preCalculation(condition, setEventSign, cloneOfIncommingEventValue, setEventValue);
if (type == 1) preCalculation(condition, setEventSign, setEventValue);
if (type == 2) preCalculationGisteresis(condition, setEventSign, setEventValue);
if (isConditionMatch(setEventSign, cloneOfIncommingEventValue, setEventValue)) {
return true;
if (isConditionMatch(setEventSign, incommingEventValue, setEventValue)) {
res = true;
}
//SerialPrint("I", "incommingEventKey", incommingEventKey);
}
return false;
return res;
}
bool isScenarioNeedToDoJson(String &condition) {
@@ -184,9 +178,8 @@ class Scenario {
String setEventKey = selectFromMarkerToMarker(condition, " ", 0);
String setEventSign;
String setEventValue;
preCalculation(condition, setEventSign, setEventValue);
String jsonValue = getValue(setEventKey);
preCalculation(condition, setEventSign, jsonValue, setEventValue);
if (isConditionMatch(setEventSign, jsonValue, setEventValue)) {
res = true;
}
@@ -207,24 +200,11 @@ class Scenario {
// return res;
//}
void preCalculation(String &condition, String &setEventSign, String &incommingEventValue, String &setEventValue) {
void preCalculation(String &condition, String &setEventSign, String &setEventValue) {
setEventSign = selectFromMarkerToMarker(condition, " ", 1);
setEventValue = selectFromMarkerToMarker(condition, " ", 2);
String tmpStr;
tmpStr = getValue(setEventValue);
if (tmpStr != "no value") setEventValue = tmpStr;
if (!isDigitDotCommaStr(setEventValue)) {
if (isTimeStr(incommingEventValue)) {
int hhLStr = selectToMarker(incommingEventValue, ":").toInt();
int mmLStr = selectToMarkerLast(incommingEventValue, ":").toInt();
int hhRStr = selectToMarker(setEventValue, ":").toInt();
int mmRStr = selectToMarkerLast(setEventValue, ":").toInt();
incommingEventValue = hhLStr*60 + mmLStr;
setEventValue = hhRStr*60 + mmRStr;
}
setEventValue = getValue(setEventValue);
}
}
@@ -248,20 +228,14 @@ class Scenario {
bool isEventExist(String &incommingEventKey, String &setEventKey) {
bool res = false;
if (incommingEventKey != "not found" && incommingEventKey == setEventKey) {
if (incommingEventKey == setEventKey) {
res = true;
}
return res;
}
bool isConditionMatch(String &setEventSign, String &incommingEventValue, String &setEventValue) {
if (setEventValue == "no value") return false;
boolean flag = false;
//SerialPrint("I", "setEventSign", setEventSign);
//SerialPrint("I", "incommingEventValue", incommingEventValue);
//SerialPrint("I", "setEventValue", setEventValue);
//SerialPrint("I", "==========", "===============");
if (setEventSign == "=") {
flag = incommingEventValue == setEventValue;
} else if (setEventSign == "!=") {
@@ -275,7 +249,6 @@ class Scenario {
} else if (setEventSign == "<=") {
flag = incommingEventValue.toFloat() <= setEventValue.toFloat();
}
return flag;
}
};

View File

@@ -1,6 +1,6 @@
#pragma once
#define FIRMWARE_VERSION 306
#define FIRMWARE_VERSION 304
//#define svelte
@@ -53,7 +53,7 @@
#define NUM_BUTTONS 8
#endif
#define MQTT_RECONNECT_INTERVAL 60000
#define MQTT_RECONNECT_INTERVAL 20000
#define CHANGE_BROKER_AFTER 5
#define TELEMETRY_UPDATE_INTERVAL_MIN 60
#define DEVICE_CONFIG_FILE "s.conf.csv"
@@ -87,8 +87,6 @@
#define EnableSensorAny
#define EnableTelegram
#define EnableUart
#define EnableSensorLCD2004
#define EnableSensorTM1637
#endif
#ifdef GATE_MODE
@@ -101,7 +99,6 @@
#define EnableSensorUptime
#define EnableTelegram
#define EnableUart
#define EnableSensorLCD2004
#endif
//================================================================================================================================================================

View File

@@ -2,6 +2,8 @@
#include <Arduino.h>
void mqttInit();
void selectBroker();
void getMqttData1();
@@ -27,5 +29,3 @@ void publishState();
void mqttCallback(char* topic, uint8_t* payload, size_t length);
const String getStateStr();
String getAllJson();

View File

@@ -34,8 +34,6 @@ size_t itemsCount(String& str, const char* delim);
boolean isDigitStr(const String& str);
boolean isTimeStr(const String& str);
boolean isDigitDotCommaStr(const String& str);
String prettyBytes(size_t size);

View File

@@ -1,12 +1,9 @@
#pragma once
#include <Arduino.h>
extern float yourSensorReading(String type, String addr);
float yourSensorReading(String type, String addr);
extern void HDC1080_init(String addr);
extern void AHTX0_init();
extern void LCD_init();
extern void BH1750_init();
extern unsigned long getValue(byte packet[]);
extern void sendRequest(byte packet[]);
void HDC1080_init(String addr);
void AHTX0_init();
void LCD_init();
void BH1750_init();

View File

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

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

@@ -1,44 +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;
//для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии
OneWire* oneWire;
DallasTemperature* sensors;
};
extern MySensorDallasVector* mySensorDallas2;
extern void dallas();
#endif

View File

@@ -1,40 +0,0 @@
#ifdef EnableSensorLCD2004
#pragma once
#include <Arduino.h>
#include <OneWire.h>
#include "Global.h"
#include "LiquidCrystal_I2C.h"
class SensorLCD2004;
typedef std::vector<SensorLCD2004> MySensorLCD2004Vector;
class SensorLCD2004 {
public:
SensorLCD2004(String key, unsigned long interval, unsigned int x, unsigned int y, String val, String descr);
~SensorLCD2004();
void loop();
void writeLCD2004();
void execute(String command);
String _key;
void printBlankStr(int strSize);
private:
unsigned long currentMillis;
unsigned long prevMillis;
unsigned long difference;
unsigned long _interval;
unsigned int _x;
unsigned int _y;
String _val;
String _descr;
int _prevStrSize;
};
extern MySensorLCD2004Vector* mySensorLCD20042;
extern void lcd2004();
#endif

View File

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

View File

@@ -1,44 +0,0 @@
#ifdef EnableSensorTM1637
#pragma once
#include <Arduino.h>
#include <OneWire.h>
#include "Global.h"
#include <TM1637Display.h>
struct DisplayObj {
TM1637Display* disp;
int curIndex;
};
class SensorTM1637;
typedef std::vector<SensorTM1637> MySensorTM1637Vector;
class SensorTM1637 {
public:
SensorTM1637(String key, int pin1, int pin2, unsigned long interval, unsigned int c, unsigned int k, String val, String descr);
~SensorTM1637();
void loop();
void writeTM1637();
void execute(String command);
String _key;
private:
unsigned long currentMillis;
unsigned long prevMillis;
unsigned long difference;
String _descr;
unsigned long _interval;
unsigned int _c;
unsigned int _k;
String _val;
TM1637Display* _disp;
};
extern MySensorTM1637Vector* mySensorTM1637;
extern void TM1637();
#endif

View File

@@ -9,7 +9,7 @@
; https://docs.platformio.org/page/projectconf.html
[platformio]
default_envs = esp8266_4mb
default_envs = esp32_4mb
data_dir = data_esp
[common_env_data]
@@ -43,9 +43,8 @@ lib_deps =
robtillaart/SHT2x@^0.1.1
ClosedCube HDC1080
Adafruit AHTX0
LiquidCrystal_I2C
BH1750
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
monitor_filters = esp8266_exception_decoder
upload_speed = 921600
monitor_speed = 115200
@@ -72,9 +71,8 @@ lib_deps =
robtillaart/SHT2x@^0.1.1
ClosedCube HDC1080
Adafruit AHTX0
LiquidCrystal_I2C
BH1750
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
monitor_filters = esp8266_exception_decoder
upload_speed = 921600
monitor_speed = 115200
@@ -92,11 +90,6 @@ lib_deps =
ESPAsyncUDP
CTBot @2.1.6
MySensors @2.3.2
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
Adafruit AHTX0
BH1750
ClosedCube HDC1080
monitor_filters = esp8266_exception_decoder
upload_speed = 921600
monitor_speed = 115200
@@ -124,9 +117,8 @@ lib_deps =
robtillaart/SHT2x@^0.1.1
ClosedCube HDC1080
Adafruit AHTX0
LiquidCrystal_I2C
BH1750
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
monitor_filters = esp32_exception_decoder
upload_speed = 921600
monitor_speed = 115200
@@ -146,10 +138,6 @@ lib_deps =
ESP32 AnalogWrite
ESP32Servo
MySensors @2.3.2
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
Adafruit AHTX0
BH1750
ClosedCube HDC1080
monitor_filters = esp32_exception_decoder
upload_speed = 921600
monitor_speed = 115200

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"
@@ -15,16 +14,22 @@
#include "items/vSensorBme280.h"
#include "items/vSensorBmp280.h"
#include "items/vSensorCcs811.h"
#include "items/vSensorDallas.h"
#include "items/vSensorLCD2004.h"
#include "items/vSensorTM1637.h"
#include "items/vSensorDht.h"
#include "items/vSensorNode.h"
#include "items/vSensorPzem.h"
#include "items/vSensorSHT20.h"
#include "items/vSensorUltrasonic.h"
#include "items/vSensorUptime.h"
#include "MqttClient.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) {
if (cmdStr.endsWith(",")) {
@@ -76,17 +81,10 @@ void csvCmdExecute(String& cmdStr) {
if (count > 1) {
// 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
} else if (order == F("button-in")) {
#ifdef EnableButtonIn
sCmd.addCommand(order.c_str(), buttonIn);
#endif
} else if (order == F("input-value")) {
#ifdef EnableInput
@@ -104,19 +102,11 @@ void csvCmdExecute(String& cmdStr) {
#ifdef EnableSensorUltrasonic
sCmd.addCommand(order.c_str(), ultrasonic);
#endif
//ИНТЕГРИРУЮ: Первая интеграция в ядро. Следим за наименованием
//ИНТЕГРИРУЮ: Первая интеграция в ядро. Следим за наименованием
} else if (order == F("dallas-temp")) {
#ifdef EnableSensorDallas
sCmd.addCommand(order.c_str(), dallas);
#endif
} else if (order == F("LCD2004")) {
#ifdef EnableSensorLCD2004
sCmd.addCommand(order.c_str(), lcd2004);
#endif
} else if (order == F("TM1637")) {
#ifdef EnableSensorTM1637
sCmd.addCommand(order.c_str(), TM1637);
#endif
// #ifdef EnableSensorDallas
// sCmd.addCommand(order.c_str(), dallas);
// #endif
} else if (order == F("dht")) {
#ifdef EnableSensorDht
sCmd.addCommand(order.c_str(), dhtSensor);
@@ -124,10 +114,6 @@ void csvCmdExecute(String& cmdStr) {
} else if (order == F("bme280")) {
#ifdef EnableSensorBme280
sCmd.addCommand(order.c_str(), bme280Sensor);
#endif
} else if (order == F("sht20")) {
#ifdef EnableSensorSht20
sCmd.addCommand(order.c_str(), sht20Sensor);
#endif
} else if (order == F("sensor")) {
#ifdef EnableSensorAny
@@ -172,6 +158,34 @@ void csvCmdExecute(String& cmdStr) {
}
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");
}
@@ -183,16 +197,6 @@ void spaceCmdExecute(String& cmdStr) {
cmdStr.replace("\r", "\n");
while (cmdStr.length()) {
String buf = selectToMarker(cmdStr, "\n");
if (buf.indexOf("*") != -1) {
buf.replace("*", "");
String order = selectToMarker(buf, " ");
String newValue = selectToMarkerLast(buf, " ");
String allJson = getAllJson();
String currentValue = jsonReadStr(allJson, order);
if (newValue == currentValue) {
buf = "";
}
}
if (buf != "") {
sCmd.readStr(buf);
SerialPrint("I", F("Order done W"), buf);

7
src/Class/IoTModule.cpp Normal file
View 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
View 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
View 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); //прочитали из памяти
};

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"
@@ -15,19 +14,18 @@
#include "items/vSensorBme280.h"
#include "items/vSensorBmp280.h"
#include "items/vSensorCcs811.h"
#include "items/vSensorDallas.h"
#include "items/vSensorLCD2004.h"
#include "items/vSensorTM1637.h"
#include "items/vSensorDht.h"
#include "items/vSensorNode.h"
#include "items/vSensorPzem.h"
#include "items/vSensorSHT20.h"
#include "items/vSensorUltrasonic.h"
#include "items/vSensorUptime.h"
#ifdef EnableSensorLCD2004
extern LiquidCrystal_I2C *LCDI2C;
#endif
#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() {
configSetupJson = readFile("config.json", 4096);
@@ -117,6 +115,21 @@ void handle_uptime() {
}
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
if (myLogging != nullptr) {
myLogging->clear();
@@ -140,13 +153,6 @@ void clearVectors() {
countDown_EnterCounter = -1;
#endif
#ifdef EnableButtonOut
if (myButtonOut != nullptr) {
myButtonOut->clear();
}
buttonOut_KeyList = "";
buttonOut_EnterCounter = -1;
#endif
#ifdef EnableInput
if (myInput != nullptr) {
myInput->clear();
@@ -167,24 +173,6 @@ void clearVectors() {
}
pwmOut_KeyList = "";
pwmOut_EnterCounter = -1;
#endif
//==================================
//ИНТЕГРИРУЮ: Вторая интеграция в ядро. Следим за наименованием
#ifdef EnableSensorDallas
if (mySensorDallas2 != nullptr) {
mySensorDallas2->clear();
}
#endif
#ifdef EnableSensorLCD2004
if (mySensorLCD20042 != nullptr) {
if(LCDI2C != nullptr) LCDI2C->clear();
mySensorLCD20042->clear();
}
#endif
#ifdef EnableSensorTM1637
if (mySensorTM1637 != nullptr) {
mySensorTM1637->clear();
}
#endif
#ifdef EnableSensorUltrasonic
if (mySensorUltrasonic != nullptr) {
@@ -206,11 +194,6 @@ void clearVectors() {
mySensorBme280->clear();
}
#endif
#ifdef EnableSensorSht20
if (mySensorSht20 != nullptr) {
mySensorSht20->clear();
}
#endif
#ifdef EnableSensorBmp280
if (mySensorBmp280 != nullptr) {
mySensorBmp280->clear();

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

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

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

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

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

View File

@@ -224,7 +224,6 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
String key = selectFromMarkerToMarker(topicStr, "/", 3);
SerialPrint("I", F("=>MQTT"), "Received event from other device: '" + devId + "' " + key + " " + payloadStr);
String event = key + " " + payloadStr + ",";
jsonWriteStr(configLiveJson, key, payloadStr);
eventBuf += event;
}
}
@@ -416,14 +415,3 @@ const String getStateStr() {
break;
}
}
String getAllJson() {
String str;
if (configLiveJson != "{}") {
str += configLiveJson;
}
if (configStoreJson != "{}") {
str += "," + configStoreJson;
}
return str;
}

View File

@@ -59,7 +59,7 @@ void telegramMsgParse(String msg) {
SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg));
} else if (msg.indexOf("get") != -1) {
msg = deleteBeforeDelimiter(msg, "_");
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), getValue(msg)); // jsonReadStr(configLiveJson , msg));
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), getValue(msg)); //jsonReadStr(configLiveJson , msg));
SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg));
} else if (msg.indexOf("all") != -1) {
String list = returnListOfParams();
@@ -74,21 +74,13 @@ void telegramMsgParse(String msg) {
void sendTelegramMsg() {
String sabject = sCmd.next();
String msg = sCmd.next();
String ID_name = "";
String ID_value = "";
if (sabject == "often") {
msg.replace("#", " ");
msg.replace("%date%", timeNow->getDateTimeDotFormated());
msg.replace("%weekday%", timeNow->getWeekday());
msg.replace("%IP%", jsonReadStr(configSetupJson, F("ip")));
msg.replace("%name%", jsonReadStr(configSetupJson, F("name")));
if (msg.indexOf("_") != -1) {
ID_name = deleteBeforeDelimiter(msg, "_");
ID_name = deleteAfterDelimiter(ID_name, "_");
ID_value = getValue(ID_name);
msg.replace(ID_name, ID_value);
}
msg.replace("_", " ");
msg.replace("%date%", timeNow->getDateTimeDotFormated());
msg.replace("%weekday%", timeNow->getWeekday());
msg.replace("%IP%", jsonReadStr(configSetupJson, F("ip")));
msg.replace("%name%", jsonReadStr(configSetupJson, F("name")));
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
} else {
@@ -101,13 +93,6 @@ void sendTelegramMsg() {
msg.replace("%weekday%", timeNow->getWeekday());
msg.replace("%IP%", jsonReadStr(configSetupJson, F("ip")));
msg.replace("%name%", jsonReadStr(configSetupJson, F("name")));
if (msg.indexOf("_") != -1) {
ID_name = deleteBeforeDelimiter(msg, "_");
ID_name = deleteAfterDelimiter(ID_name, "_");
ID_value = getValue(ID_name);
msg.replace(ID_name, ID_value);
}
msg.replace("_", " ");
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
@@ -135,7 +120,7 @@ String returnListOfParams() {
count++;
if (count > 1) {
String id = selectFromMarkerToMarker(buf, ";", 2);
String value = getValue(id); // jsonReadStr(configLiveJson , id);
String value = getValue(id); //jsonReadStr(configLiveJson , id);
String page = selectFromMarkerToMarker(buf, ";", 4);
page.replace("#", " ");
String name = selectFromMarkerToMarker(buf, ";", 5);

View File

@@ -155,18 +155,6 @@ boolean isDigitStr(const String& str) {
return str.length();
}
boolean isTimeStr(const String& str) {
for (size_t i = 0; i < str.length(); i++) {
char latter = str.charAt(i);
if (!isDigit(latter) && latter != ':') {
return false;
}
}
if (str.charAt(2) != ':') return false;
return true;
}
boolean isDigitDotCommaStr(const String& str) {
for (size_t i = 0; i < str.length(); i++) {
char latter = str.charAt(i);

View File

@@ -9,7 +9,7 @@
#include "Adafruit_AHTX0.h"
#include "BH1750.h"
#include "ClosedCube_HDC1080.h"
//#include "LiquidCrystal_I2C.h"
#include "LiquidCrystal_I2C.h"
//создаем объект HDC1080
ClosedCube_HDC1080 hdc1080;
@@ -20,30 +20,13 @@ Adafruit_Sensor *aht_humidity, *aht_temp;
sensors_event_t tmpEvent_t;
//создаем объект LCD
//LiquidCrystal_I2C LCD(0x27, 16, 2);
LiquidCrystal_I2C LCD(0x27, 16, 2);
//создаем объект BH1750
BH1750 lightMeter;
//создаем объект ADS1015
// Adafruit_ADS1015 ads;
// co2 sensor
//SoftwareSerial K_30_Serial(13, 15); //Программный порт
byte readCO2[] = {0xFE, 0X44, 0X00, 0X08, 0X02, 0X9F, 0X25}; //Команды для запроса показаний с датчика
byte response[] = {0, 0, 0, 0, 0, 0, 0}; //массив для ответа от датчика
unsigned long getValue(byte packet[]) {
int high = packet[3]; //верхний байт показания СО2
int low = packet[4]; //нижний байт показания СО2
unsigned long val_1 = high * 256 + low; //соединяем байты
return val_1;
}
void sendRequest(byte packet[]) {
//while (!K_30_Serial.available()) {
// K_30_Serial.write(readCO2, 7);
// delay(50);
//}
}
//Adafruit_ADS1015 ads;
float yourSensorReading(String type, String paramsAny) {
float value;
@@ -68,29 +51,17 @@ float yourSensorReading(String type, String paramsAny) {
value = tmpEvent_t.relative_humidity;
}
//==========================================================LCD=================================================================
//if (type == "LCD") {
//LCD_init();
// LCD.setCursor(jsonReadInt(paramsAny, "c"), jsonReadInt(paramsAny, "k"));
// String toPrint = jsonReadStr(paramsAny, "descr") + " " + jsonReadStr(configLiveJson, jsonReadStr(paramsAny, "val"));
// LCD.print(toPrint);
//}
if (type == "LCD") {
LCD_init();
LCD.setCursor(jsonReadInt(paramsAny, "с"), jsonReadInt(paramsAny, "k"));
String toPrint = jsonReadStr(paramsAny, "descr") + " " + jsonReadStr(configLiveJson, jsonReadStr(paramsAny, "val"));
LCD.print(toPrint);
}
//==========================================================BH1750=================================================================
if (type == "BH1750_lux") {
BH1750_init();
value = lightMeter.readLightLevel();
}
//==========================================================co2=================================================================
if (type == "valCO2") {
//K_30_Serial.begin(9600);
//sendRequest(readCO2);
//int valCO2 = getValue(response);
//value = valCO2;
// Serial.println(valCO2);
}
//==========================================================timer=================================================================
if (type == "timer") {
value = jsonReadFloat(configLiveJson, jsonReadStr(paramsAny, "val"));
}
return value;
}
@@ -119,14 +90,13 @@ void AHTX0_init() {
}
}
//void LCD_init() {
//static bool LCD_flag = true;
//if (LCD_flag) {
//LCD.init(); //инициализация дисплея
//LCD.backlight(); //включаем подсветку
//}
//LCD_flag = false;
//}
void LCD_init() {
static bool LCD_flag = true;
if (LCD_flag) {
LCD.init(); //инициализация дисплея
LCD.backlight(); //включаем подсветку
}
}
void BH1750_init() {
static bool BH1750_flag = true;

View File

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

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

View File

@@ -24,7 +24,7 @@ void ImpulsOutClass::loop() {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (_impulsCountBuf > 0) {
if (difference >= _impulsPeriod) {
if (difference > _impulsPeriod) {
_impulsCountBuf--;
prevMillis = millis();
yield();

View File

@@ -50,28 +50,10 @@ void SensorAny::read() {
MySensorAnyVector* mySensorAny = nullptr;
void AnySensorExecute() {
String key = sCmd.order();
String command = sCmd.next();
if (command == "cmd1") {
SerialPrint("I", "Sensor", key + " выполняет cmd1 без параметра");
}
else if (command == "cmd2") {
String par = sCmd.next();
SerialPrint("I", "Sensor", key + " выполняет cmd2 c параметром " + par);
}
else if (command == "cmd3") {
String par = sCmd.next();
SerialPrint("I", "Sensor", key + " выполняет cmd3 c параметром " + par);
}
}
void AnySensor() {
String params = "{}";
myLineParsing.update();
String key = myLineParsing.gkey();
jsonWriteStr(params, "key", key);
jsonWriteStr(params, "key", myLineParsing.gkey());
jsonWriteStr(params, "addr", myLineParsing.gaddr());
jsonWriteStr(params, "int", myLineParsing.gint());
jsonWriteStr(params, "c", myLineParsing.gc());
@@ -82,10 +64,7 @@ void AnySensor() {
myLineParsing.clear();
static bool firstTime = true;
if (firstTime) {
mySensorAny = new MySensorAnyVector();
sCmd.addCommand(key.c_str(), AnySensorExecute);
}
if (firstTime) mySensorAny = new MySensorAnyVector();
firstTime = false;
mySensorAny->push_back(SensorAny(params));
}

View File

@@ -1,107 +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 <map>
#include <Arduino.h>
//ИНТЕГРИРУЮ: переменные необходимые для работы интегрируемой библиотеки. Аналог Arduino
std::map<int, OneWire*> oneWireTemperatureArray;
std::map<int, DallasTemperature*> sensorsTemperatureArray;
//ИНТЕГРИРУЮ:
//Для каждого датчика указанного в конфигурации вызывается конструктор для настройки перед запуском. Аналог функции 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;
//ИНТЕГРИРУЮ:
//вызываем необходимые инициирующие функции интегрируемой библиотеки
//учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась
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];
}
}
//ИНТЕГРИРУЮ: оставляем как есть или развиваем, если нужно правильно завершить работу с интегрируемой библиотекой после отключения датчика
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

View File

@@ -1,128 +0,0 @@
#include "Consts.h"
#ifdef EnableSensorLCD2004
#include "items/vSensorLCD2004.h"
#include "BufferExecute.h"
#include "Class/LineParsing.h"
#include "Global.h"
#include "Utils/StringUtils.h"
#include <map>
#include <Arduino.h>
LiquidCrystal_I2C *LCDI2C;
SensorLCD2004::SensorLCD2004(String key, unsigned long interval, unsigned int x, unsigned int y, String val, String descr) {
_key = key;
_interval = interval * 1000;
_x = x;
_y = y;
_val = val;
_descr = descr;
_prevStrSize = 0;
}
SensorLCD2004::~SensorLCD2004() {}
//печать пустой строки нужной длинны для затирания предыдущего значения на экране
void SensorLCD2004::printBlankStr(int strSize){
String tmpStr = "";
for(int i=0; i<strSize; i++) tmpStr += " ";
LCDI2C->setCursor(_x, _y);
LCDI2C->print(tmpStr);
}
void SensorLCD2004::execute(String command) {
if (command == "noBacklight") LCDI2C->noBacklight();
else if (command == "backlight") LCDI2C->backlight();
else if (command == "noDisplay") LCDI2C->noDisplay();
else if (command == "display") LCDI2C->display();
else if (command == "x") {
printBlankStr(_prevStrSize);
String par = sCmd.next();
_x = par.toInt();
}
else if (command == "y") {
printBlankStr(_prevStrSize);
String par = sCmd.next();
_y = par.toInt();
}
else if (command == "descr") {
printBlankStr(_prevStrSize);
String par = sCmd.next();
_descr = par;
}
else { //не команда, значит данные
_val = command;
}
writeLCD2004();
}
void SensorLCD2004::loop() {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= _interval) {
prevMillis = millis();
writeLCD2004();
}
}
void SensorLCD2004::writeLCD2004() {
if (LCDI2C != nullptr) {
printBlankStr(_prevStrSize);
String tmpStr = getValue(_val);
if (tmpStr == "no value") tmpStr = _val;
if (_descr != "none") tmpStr = _descr + " " + tmpStr;
LCDI2C->setCursor(_x, _y);
LCDI2C->print(tmpStr);
_prevStrSize = tmpStr.length();
}
}
MySensorLCD2004Vector* mySensorLCD20042 = nullptr;
void lcd2004Execute() {
String key = sCmd.order();
String command = sCmd.next();
for (unsigned int i = 0; i < mySensorLCD20042->size(); i++) {
if (mySensorLCD20042->at(i)._key == key) mySensorLCD20042->at(i).execute(command);
}
}
void lcd2004() {
myLineParsing.update();
String key = myLineParsing.gkey();
String addr = myLineParsing.gaddr();
String interval = myLineParsing.gint();
String c = myLineParsing.gc();
String k = myLineParsing.gk();
String val = myLineParsing.gval();
String descr = myLineParsing.gdescr();
myLineParsing.clear();
int x = selectFromMarkerToMarker(c, ",", 0).toInt();
int y = selectFromMarkerToMarker(c, ",", 1).toInt();
int w = selectFromMarkerToMarker(k, ",", 0).toInt(); //количество столбцов
int h = selectFromMarkerToMarker(k, ",", 1).toInt(); //количество строк
if (LCDI2C == nullptr) { //инициализации экрана еще не было
LCDI2C = new LiquidCrystal_I2C(hexStringToUint8(addr), w, h);//hexStringToUint8(addr), w, h);
if(LCDI2C != nullptr) {
LCDI2C->init();
LCDI2C->backlight();
}
}
static bool firstTime = true;
if (firstTime) mySensorLCD20042 = new MySensorLCD2004Vector();
firstTime = false;
mySensorLCD20042->push_back(SensorLCD2004(key, interval.toInt(), x, y, val, descr));
sCmd.addCommand(key.c_str(), lcd2004Execute);
}
#endif

View File

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

View File

@@ -1,124 +0,0 @@
#include "Consts.h"
#ifdef EnableSensorTM1637
#include "items/vSensorTM1637.h"
#include "BufferExecute.h"
#include "Class/LineParsing.h"
#include "Global.h"
#include "Utils/StringUtils.h"
#include <map>
#include <Arduino.h>
const uint8_t segmentsVal[] = {0x77, 0x7f, 0x39, 0x3f, 0x79, 0x71, 0x3d, 0x76, 0x1e, 0x38, 0x37, 0x3f, 0x73, 0x6d, 0x3e, 0x6e, 0x5f, 0x7c, 0x58, 0x5e, 0x7b, 0x71, 0x74, 0x10, 0x0e, 0x06, 0x54, 0x5c, 0x67, 0x50, 0x78, 0x1c, 0x6e, 0x40, 0x08, 0x48, 0x00, 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f};
char segmentsIndex[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'L', 'N', 'O', 'P', 'S', 'U', 'Y', 'a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'j', 'l', 'n', 'o', 'q', 'r', 't', 'u', 'y', '-', '_', '=', ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
std::map<int, DisplayObj> displayObjects;
uint8_t char2Segment(char ch) {
for (int i=0; i<sizeof(segmentsIndex); i++) {
if (ch == segmentsIndex[i]) return segmentsVal[i];
}
return 0;
}
SensorTM1637::SensorTM1637(String key, int pin1, int pin2, unsigned long interval, unsigned int c, unsigned int k, String val, String descr) {
_key = key;
_interval = interval * 1000;
_c = c;
_k = k;
_val = val;
_descr = descr;
if (displayObjects.find(pin1) == displayObjects.end()) {
_disp = new TM1637Display(pin1, pin2);
DisplayObj dispObj;
dispObj.curIndex = 0;
dispObj.disp = _disp;
displayObjects[pin1] = dispObj;
_disp->setBrightness(0x0f);
_disp->clear();
} else {
_disp = displayObjects[pin1].disp;
}
}
SensorTM1637::~SensorTM1637() {}
void SensorTM1637::execute(String command) {
if (command == "noDisplay") _disp->setBrightness(0x00, false);
else if (command == "display") _disp->setBrightness(0x0f, true);
else if (command == "setBrightness") {
String par = sCmd.next();
_disp->setBrightness(par.toInt());
}
else if (command == "descr") {
String par = sCmd.next();
_descr = par;
}
else { //не команда, значит данные
_val = command;
}
writeTM1637();
}
void SensorTM1637::loop() {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= _interval) {
prevMillis = millis();
writeTM1637();
}
}
void SensorTM1637::writeTM1637() {
if (_disp != nullptr) {
if (_descr != "none") {
uint8_t segments[] = {0};
segments[0] = char2Segment(_descr.c_str()[0]);
_disp->setSegments(segments, 1, 0); //выводим поле описания в самом первой секции экрана, один символ
}
String tmpStr = getValue(_val);
if (tmpStr == "no value") tmpStr = _val;
_disp->showNumberDec(tmpStr.toInt(), false, _c, _k);
}
}
MySensorTM1637Vector* mySensorTM1637 = nullptr;
void TM1637Execute() {
String key = sCmd.order();
String command = sCmd.next();
for (unsigned int i = 0; i < mySensorTM1637->size(); i++) {
if (mySensorTM1637->at(i)._key == key) mySensorTM1637->at(i).execute(command);
}
}
void TM1637() {
myLineParsing.update();
String key = myLineParsing.gkey();
String pins = myLineParsing.gpin();
String interval = myLineParsing.gint();
String c = myLineParsing.gc();
String k = myLineParsing.gk();
String val = myLineParsing.gval();
String descr = myLineParsing.gdescr();
myLineParsing.clear();
int pin1 = selectFromMarkerToMarker(pins, ",", 0).toInt();
int pin2 = selectFromMarkerToMarker(pins, ",", 1).toInt();
static bool firstTime = true;
if (firstTime) mySensorTM1637 = new MySensorTM1637Vector();
firstTime = false;
mySensorTM1637->push_back(SensorTM1637(key, pin1, pin2, interval.toInt(), c.toInt(), k.toInt(), val, descr));
sCmd.addCommand(key.c_str(), TM1637Execute);
}
#endif

View File

@@ -1,3 +1,4 @@
#include <SSDP.h>
#include "BufferExecute.h"
@@ -18,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"
@@ -27,16 +27,25 @@
#include "items/vSensorBme280.h"
#include "items/vSensorBmp280.h"
#include "items/vSensorCcs811.h"
#include "items/vSensorDallas.h"
#include "items/vSensorLCD2004.h"
#include "items/vSensorTM1637.h"
#include "items/vSensorDht.h"
#include "items/vSensorNode.h"
#include "items/vSensorPzem.h"
#include "items/vSensorSHT20.h"
#include "items/vSensorUltrasonic.h"
#include "items/vSensorUptime.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();
Timings metric;
@@ -61,6 +70,10 @@ void setup() {
clockInit();
timeInit();
itemsListInit();
SerialPrint("I", "Debug", "call setup");
InitModulesApi(); //v3dev: инициализация модуля при первом вызове .
espInit();
routerConnect();
#ifdef EnableTelegram
@@ -147,27 +160,7 @@ void loop() {
}
}
#endif
#ifdef EnableSensorDallas
if (mySensorDallas2 != nullptr) {
for (unsigned int i = 0; i < mySensorDallas2->size(); i++) {
mySensorDallas2->at(i).loop();
}
}
#endif
#ifdef EnableSensorLCD2004
if (mySensorLCD20042 != nullptr) {
for (unsigned int i = 0; i < mySensorLCD20042->size(); i++) {
mySensorLCD20042->at(i).loop();
}
}
#endif
#ifdef EnableSensorTM1637
if (mySensorTM1637 != nullptr) {
for (unsigned int i = 0; i < mySensorTM1637->size(); i++) {
mySensorTM1637->at(i).loop();
}
}
#endif
#ifdef EnableSensorUltrasonic
if (mySensorUltrasonic != nullptr) {
for (unsigned int i = 0; i < mySensorUltrasonic->size(); i++) {
@@ -197,13 +190,6 @@ void loop() {
}
}
#endif
#ifdef EnableSensorSht20
if (mySensorSht20 != nullptr) {
for (unsigned int i = 0; i < mySensorSht20->size(); i++) {
mySensorSht20->at(i).loop();
}
}
#endif
#ifdef EnableSensorAny
if (mySensorAny != nullptr) {
for (unsigned int i = 0; i < mySensorAny->size(); i++) {
@@ -246,7 +232,13 @@ void loop() {
}
}
#endif
#ifdef EnableButtonIn
myButtonIn.loop();
#endif
//v3dev: перебираем все экземпляры сенсоров должно заменить в v4 все вызовы сенсоров выше
for (unsigned int i = 0; i < iotSensors.size(); i++) {
iotSensors[i]->loop();
}
}