49 Commits

Author SHA1 Message Date
Dmitry Borisenko
069ba9ae9f версия 306 добавлено блокирование многократного повторения события в сценарии - * 2022-02-03 23:33:39 +01:00
IoT Manager
810f3ca061 Merge pull request #123 from biveraxe/ver3
Исправление опечатки и новая функция в песочнице
2022-02-01 12:10:14 +01:00
dd8d173a94 Merge branch 'IoTManagerProject:ver3' into ver3 2022-02-01 09:03:00 +03:00
43a8614d8c Поправляем опечатку в items.txt для MS: input -> input-value 2022-02-01 09:02:24 +03:00
bfabd3965f Добавление в песочницу возможность атлавливать команды из сценариев 2022-02-01 09:01:07 +03:00
Dmitry Borisenko
adbe794edd добавил возможность работы многофакторных условий меж esp 2022-01-25 17:18:51 +01:00
Dmitry Borisenko
c7b649db07 Merge pull request #116 from biveraxe/ver3
Добавление LCD2004 в MySensors
2022-01-14 19:14:09 +01:00
51b137b3cc Merge branch 'IoTManagerProject:ver3' into ver3 2022-01-14 21:59:06 +05:00
8f33afec8c Наводим порядок с библиотеками для LCD2004 для MySensors 2022-01-14 21:15:26 +05:00
cc115c701b Добавляем поддержку LCD2004 в MySensors 2022-01-14 20:54:13 +05:00
Dmitry Borisenko
bc765cf3a6 version 305 2022-01-14 15:31:55 +01:00
IoT Manager
4f36adb407 Merge pull request #115 from biveraxe/ver3
Добавление TM1637
2022-01-14 15:27:55 +01:00
f135840ec4 Добавляем весь основной функционал для TM1637 2022-01-13 21:32:29 +03:00
f928766de5 Убераем лишний параметр index из интерфейса для TM1637 2022-01-13 21:05:06 +03:00
c87854b2ce Интегрируем дисплэй TM1637 в ядро 2022-01-12 19:01:15 +03:00
0a2c86ccbf Обновляем FS для новых пунктов меню для TM1637 2022-01-12 18:58:41 +03:00
2d8de37ee7 Обновляем FS для новых пунктов меню для TM1637 2022-01-12 18:24:46 +03:00
2b1cac904b Добавляем файлы модуля Display TM1637 в систему на базе уже существующего LCD 2022-01-12 18:02:43 +03:00
Dmitry Borisenko
e2b0f0e71e Merge pull request #114 from biveraxe/ver3
Поддержка LCD 2004 и 1602
2022-01-12 13:11:06 +01:00
56c0ec14fa Merge branch 'ver3' of https://github.com/biveraxe/IoTManager into ver3 2022-01-12 11:06:40 +03:00
a4e3b9d868 Merge branch 'IoTManagerProject:ver3' into ver3 2022-01-12 11:06:28 +03:00
5a029fb159 Добавляем возмодность изменить заголовок и содержимое выводимой информации 2022-01-12 11:05:56 +03:00
e979711372 Добавляем поддержку управления lCD2004 из сценария 2022-01-12 10:51:28 +03:00
46a87ebe26 Исключаем поддержку параллельного подключения LCD2004 и наводим порядок с библиотеками. 2022-01-12 10:00:19 +03:00
Dmitry Borisenko
68c9741226 добавил таймер 2022-01-12 00:26:33 +01:00
3787959f52 Merge branch 'ver3' of https://github.com/biveraxe/IoTManager into ver3 2022-01-11 15:33:36 +03:00
bcd6f06e5e Merge branch 'IoTManagerProject:ver3' into ver3 2022-01-11 15:33:15 +03:00
Dmitry Borisenko
bf9acf4c63 добавили возможность вывода любой величины в телеграм 2022-01-11 12:30:13 +01:00
Dmitry Borisenko
3fab2241aa исправил баг с шаговыми двигателями 2022-01-11 11:27:24 +01:00
3f1fbf647a Увеличиваем время между попытками установить соединение до брокера. На esp32 время ожидания доходило до 20 сек при таком же интервале переподключения. 2022-01-08 08:32:23 +03:00
ea53d5ccf1 Merge branch 'IoTManagerProject:ver3' into ver3 2022-01-05 23:41:51 +03:00
1abe6b20bc Отключаем версию LCD из песочницы 2022-01-05 23:40:17 +03:00
c2010c4979 Добавляем в параметр ip[] до 15 пинов 2022-01-05 23:39:04 +03:00
044867ca00 Дописываем интеграцию LCD 2022-01-05 23:38:32 +03:00
9f733a1535 Интегрируем LCD2004 в ядро 2022-01-05 18:01:20 +03:00
d78907d854 Добавляем необходимые файлы и первые записи в интервейс для экрана LCD2004 2022-01-05 17:49:33 +03:00
Dmitry Borisenko
b2b70a0d9d Merge pull request #113 from biveraxe/ver3
Дорабатываем механизм работы со временем в сценариях
2022-01-05 14:44:33 +01:00
3dcbd3dafb Добавляем возможность сравнения не только с константами, но и со значениями из переменных в рамках сценария 2022-01-05 16:26:53 +03:00
Dmitry Borisenko
c6d45f5d9a .. 2021-12-26 19:08:06 +01:00
Dmitry Borisenko
f477d5838b добавил датчик co2 2021-12-26 19:07:01 +01:00
Dmitry Borisenko
9b535f04aa исправил баг с датчиками 2021-12-26 18:52:48 +01:00
IoT Manager
eb22c713c0 Merge pull request #110 from biveraxe/ver3
Работаем со временем в сценариях и температурой сразу на нескольких линиях
2021-12-26 18:39:34 +01:00
4d36db0755 Merge branch 'ver3' of https://github.com/biveraxe/IoTManager into ver3 2021-12-21 15:40:48 +03:00
7e92d57d4d Исправляем ошибки в логике работы сценария связанной с проверкой времени 2021-12-21 15:40:23 +03:00
203ceafb19 Исправляем ошибку в модуле далласа, возникающую при использовании нескольких шин для разных датчиков. 2021-12-20 09:42:07 +03:00
8509de3efa Merge branch 'IoTManagerProject:ver3' into ver3 2021-12-20 01:51:19 +03:00
cfa8fc4212 Merge branch 'IoTManagerProject:ver3' into ver3 2021-12-20 00:36:33 +03:00
da7393e32a Merge branch 'ver3' of https://github.com/biveraxe/IoTManager into ver3 2021-12-19 23:09:20 +03:00
87191fa81b Дописываем логику работы с переменной timenow в сценариях. Теперь доступны выражения вида "timenow > 22:48 && timenow < 23:55 && btn = 1" 2021-12-19 23:08:14 +03:00
26 changed files with 618 additions and 64 deletions

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;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;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;Сенсоры;Параметр;1;c[1];int[10];type[type1];addr[0x76]*

Binary file not shown.

View File

@@ -1,10 +1,11 @@
0;button-out;btnid;toggleBtn;Кнопки;Освещение;order*
0;button-out;100-0;toggleBtn;Кнопки;Освещение;order;type[ms]*
0;input;dgtid;inputDigit;Ввод;Введите#цифру;order*
0;input-value;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;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]*

Binary file not shown.

View File

@@ -127,6 +127,7 @@ class LineParsing {
}
if (_pin != "") {
/*
if (_pin.indexOf(",") == -1) {
if (!isPinExist(_pin.toInt()) || !isDigitStr(_pin)) {
pinErrors++;
@@ -139,6 +140,17 @@ 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;
}
}
}

View File

@@ -10,10 +10,14 @@ 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, " ");
@@ -159,18 +163,20 @@ class Scenario {
private:
bool isScenarioNeedToDo(String &condition, String &incommingEventKey, String &incommingEventValue, int type) {
bool res = false;
if (condition == "") return false;
String setEventKey = selectFromMarkerToMarker(condition, " ", 0);
if (isEventExist(incommingEventKey, setEventKey)) {
String setEventSign;
String setEventValue;
if (type == 1) preCalculation(condition, setEventSign, setEventValue);
String cloneOfIncommingEventValue = incommingEventValue; //клонируем для изменения в preCalculation и передачи для проверки по условиям
if (type == 1) preCalculation(condition, setEventSign, cloneOfIncommingEventValue, setEventValue);
if (type == 2) preCalculationGisteresis(condition, setEventSign, setEventValue);
if (isConditionMatch(setEventSign, incommingEventValue, setEventValue)) {
res = true;
if (isConditionMatch(setEventSign, cloneOfIncommingEventValue, setEventValue)) {
return true;
}
//SerialPrint("I", "incommingEventKey", incommingEventKey);
}
return res;
return false;
}
bool isScenarioNeedToDoJson(String &condition) {
@@ -178,8 +184,9 @@ 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;
}
@@ -200,11 +207,24 @@ class Scenario {
// return res;
//}
void preCalculation(String &condition, String &setEventSign, String &setEventValue) {
void preCalculation(String &condition, String &setEventSign, String &incommingEventValue, String &setEventValue) {
setEventSign = selectFromMarkerToMarker(condition, " ", 1);
setEventValue = selectFromMarkerToMarker(condition, " ", 2);
String tmpStr;
tmpStr = getValue(setEventValue);
if (tmpStr != "no value") setEventValue = tmpStr;
if (!isDigitDotCommaStr(setEventValue)) {
setEventValue = getValue(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;
}
}
}
@@ -228,14 +248,20 @@ class Scenario {
bool isEventExist(String &incommingEventKey, String &setEventKey) {
bool res = false;
if (incommingEventKey == setEventKey) {
if (incommingEventKey != "not found" && 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 == "!=") {
@@ -249,6 +275,7 @@ class Scenario {
} else if (setEventSign == "<=") {
flag = incommingEventValue.toFloat() <= setEventValue.toFloat();
}
return flag;
}
};

View File

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

View File

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

View File

@@ -34,6 +34,8 @@ 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,9 +1,12 @@
#pragma once
#include <Arduino.h>
float yourSensorReading(String type, String addr);
extern float yourSensorReading(String type, String addr);
void HDC1080_init(String addr);
void AHTX0_init();
void LCD_init();
void BH1750_init();
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[]);

View File

@@ -32,6 +32,10 @@ class SensorDallas {
String _addr;
unsigned int _pin;
unsigned int _index;
//для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии
OneWire* oneWire;
DallasTemperature* sensors;
};
extern MySensorDallasVector* mySensorDallas2;

View File

@@ -0,0 +1,40 @@
#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

@@ -0,0 +1,44 @@
#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

@@ -43,8 +43,9 @@ 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
@@ -71,8 +72,9 @@ 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
@@ -90,6 +92,11 @@ 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
@@ -117,8 +124,9 @@ 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
@@ -138,6 +146,10 @@ lib_deps =
ESP32 AnalogWrite
ESP32Servo
MySensors @2.3.2
monitor_filters = esp32_exception_decoder
marcoschwartz/LiquidCrystal_I2C@^1.1.4
smougenot/TM1637@0.0.0-alpha+sha.9486982048
Adafruit AHTX0
BH1750
ClosedCube HDC1080
upload_speed = 921600
monitor_speed = 115200

View File

@@ -16,12 +16,15 @@
#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"
void loopCmdAdd(const String& cmdStr) {
if (cmdStr.endsWith(",")) {
@@ -101,10 +104,18 @@ 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
} else if (order == F("dht")) {
#ifdef EnableSensorDht
@@ -172,6 +183,16 @@ 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);

View File

@@ -16,6 +16,8 @@
#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"
@@ -23,6 +25,10 @@
#include "items/vSensorUltrasonic.h"
#include "items/vSensorUptime.h"
#ifdef EnableSensorLCD2004
extern LiquidCrystal_I2C *LCDI2C;
#endif
void loadConfig() {
configSetupJson = readFile("config.json", 4096);
configSetupJson.replace("\r\n", "");
@@ -169,6 +175,17 @@ void clearVectors() {
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) {
mySensorUltrasonic->clear();

View File

@@ -224,6 +224,7 @@ 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;
}
}
@@ -415,3 +416,14 @@ 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,13 +74,21 @@ 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")));
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("_", " ");
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
} else {
@@ -93,6 +101,13 @@ 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);
@@ -120,7 +135,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,6 +155,18 @@ 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,13 +20,30 @@ 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;
// 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);
//}
}
float yourSensorReading(String type, String paramsAny) {
float value;
@@ -51,17 +68,29 @@ float yourSensorReading(String type, String paramsAny) {
value = tmpEvent_t.relative_humidity;
}
//==========================================================LCD=================================================================
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);
}
//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);
//}
//==========================================================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;
}
@@ -90,13 +119,14 @@ void AHTX0_init() {
}
}
void LCD_init() {
static bool LCD_flag = true;
if (LCD_flag) {
LCD.init(); //инициализация дисплея
LCD.backlight(); //включаем подсветку
}
}
//void LCD_init() {
//static bool LCD_flag = true;
//if (LCD_flag) {
//LCD.init(); //инициализация дисплея
//LCD.backlight(); //включаем подсветку
//}
//LCD_flag = false;
//}
void BH1750_init() {
static bool BH1750_flag = true;

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,10 +50,28 @@ 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();
jsonWriteStr(params, "key", myLineParsing.gkey());
String key = myLineParsing.gkey();
jsonWriteStr(params, "key", key);
jsonWriteStr(params, "addr", myLineParsing.gaddr());
jsonWriteStr(params, "int", myLineParsing.gint());
jsonWriteStr(params, "c", myLineParsing.gc());
@@ -64,7 +82,10 @@ void AnySensor() {
myLineParsing.clear();
static bool firstTime = true;
if (firstTime) mySensorAny = new MySensorAnyVector();
if (firstTime) {
mySensorAny = new MySensorAnyVector();
sCmd.addCommand(key.c_str(), AnySensorExecute);
}
firstTime = false;
mySensorAny->push_back(SensorAny(params));
}

View File

@@ -6,12 +6,13 @@
#include "Global.h"
#include "DallasTemperature.h"
#include "Utils/StringUtils.h"
#include <map>
#include <Arduino.h>
//ИНТЕГРИРУЮ: переменные необходимые для работы интегрируемой библиотеки. Аналог Arduino
OneWire* oneWire;
DallasTemperature sensors;
std::map<int, OneWire*> oneWireTemperatureArray;
std::map<int, DallasTemperature*> sensorsTemperatureArray;
//ИНТЕГРИРУЮ:
//Для каждого датчика указанного в конфигурации вызывается конструктор для настройки перед запуском. Аналог функции setup() в Arduino.
@@ -26,10 +27,20 @@ SensorDallas::SensorDallas(unsigned long interval, unsigned int pin, unsigned in
//ИНТЕГРИРУЮ:
//вызываем необходимые инициирующие функции интегрируемой библиотеки
oneWire = new OneWire((uint8_t)_pin);
sensors.setOneWire(oneWire);
sensors.begin();
sensors.setResolution(12);
//учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась
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];
}
}
//ИНТЕГРИРУЮ: оставляем как есть или развиваем, если нужно правильно завершить работу с интегрируемой библиотекой после отключения датчика
@@ -48,18 +59,18 @@ void SensorDallas::loop() {
//ИНТЕГРИРУЮ: вызывается из цикла loop каждый установленный временно интервал в параметрах датчика. Необходимо изменить для чтения данных из датчика.
void SensorDallas::readDallas() {
//запускаем опрос измерений у всех датчиков на линии
sensors.requestTemperatures();
sensors->requestTemperatures();
//Определяем адрес. Если парамтер addr не установлен, то узнаем адрес по индексу
DeviceAddress deviceAddress;
if (_addr == "") {
sensors.getAddress(deviceAddress, _index);
sensors->getAddress(deviceAddress, _index);
} else {
string2hex(_addr.c_str(), deviceAddress);
}
//получаем температуру по адресу
float value = sensors.getTempC(deviceAddress);
float value = sensors->getTempC(deviceAddress);
//ИНТЕГРИРУЮ: блок генерации уведомлений в ядре системы. Стоит обратить внимание только на формат выводимого сообщения в консоли.
eventGen2(_key, String(value));

View File

@@ -0,0 +1,128 @@
#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

124
src/items/vSensorTM1637.cpp Normal file
View File

@@ -0,0 +1,124 @@
#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,4 +1,3 @@
#include <SSDP.h>
#include "BufferExecute.h"
@@ -29,6 +28,8 @@
#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"
@@ -153,6 +154,20 @@ void 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++) {