Merge pull request #267 from biveraxe/ver4dev

Новые модули и оптимизация кода
This commit is contained in:
2023-03-08 15:26:21 +03:00
committed by GitHub
19 changed files with 653 additions and 83 deletions

View File

@@ -117,7 +117,21 @@
},
{
"global": 0,
"name": "8. Виртуальная кнопка",
"name": "8. Цветной текст",
"type": "Reading",
"subtype": "VariableColor",
"id": "color",
"needSave": 0,
"widget": "anydataDef",
"page": "Вывод",
"descr": "Цветной текст",
"val": "...",
"round": 0,
"num": 8
},
{
"global": 0,
"name": "9. Виртуальная кнопка",
"type": "Reading",
"subtype": "VButton",
"id": "vbtn",
@@ -127,14 +141,60 @@
"descr": "Кнопка",
"int": "0",
"val": "0",
"num": 8
"num": 9
},
{
"header": "Сенсоры"
},
{
"global": 0,
"name": "9. DS18B20 Температура",
"name": "10. Аналоговый сенсор",
"type": "Reading",
"subtype": "AnalogAdc",
"id": "t",
"widget": "anydataTmp",
"page": "Сенсоры",
"descr": "Температура",
"map": "1,1024,1,100",
"plus": 0,
"multiply": 1,
"round": 1,
"pin": 0,
"int": 15,
"avgSteps": 1,
"num": 10
},
{
"global": 0,
"name": "11. BMP280 Температура",
"type": "Reading",
"subtype": "Bmp280t",
"id": "tmp3",
"widget": "anydataTmp",
"page": "Сенсоры",
"descr": "280 Температура",
"int": 15,
"addr": "0x77",
"round": 1,
"num": 11
},
{
"global": 0,
"name": "12. BMP280 Давление",
"type": "Reading",
"subtype": "Bmp280p",
"id": "Press3",
"widget": "anydataMm",
"page": "Сенсоры",
"descr": "280 Давление",
"int": 15,
"addr": "0x77",
"round": 1,
"num": 12
},
{
"global": 0,
"name": "13. DS18B20 Температура",
"type": "Reading",
"subtype": "Ds18b20",
"id": "dstmp",
@@ -146,12 +206,84 @@
"index": 0,
"addr": "",
"round": 1,
"num": 9
"num": 13
},
{
"global": 0,
"name": "10. HC-SR04 Ультразвуковой дальномер",
"num": 10,
"name": "14. Часы реального времени",
"type": "Reading",
"subtype": "RTC",
"id": "rtc",
"widget": "anydataDef",
"page": "Таймеры",
"descr": "Время RTC",
"chipCode": 1,
"timeFormat": "d-m-Y H:i:s",
"RST": -1,
"CLK": -1,
"DAT": -1,
"ticker": 0,
"int": 5,
"btn-setUTime": "0",
"btn-setSysTime": "nil",
"num": 14
},
{
"global": 0,
"name": "15. Sht20 Температура",
"type": "Reading",
"subtype": "Sht20t",
"id": "tmp2",
"widget": "anydataTmp",
"page": "Сенсоры",
"descr": "Температура",
"int": 15,
"round": 1,
"num": 15
},
{
"global": 0,
"name": "16. Sht20 Влажность",
"type": "Reading",
"subtype": "Sht20h",
"id": "Hum2",
"widget": "anydataHum",
"page": "Сенсоры",
"descr": "Влажность",
"int": 15,
"round": 1,
"num": 16
},
{
"global": 0,
"name": "17. Sht30 Температура",
"type": "Reading",
"subtype": "Sht30t",
"id": "tmp30",
"widget": "anydataTmp",
"page": "Сенсоры",
"descr": "SHT30 Температура",
"int": 15,
"round": 1,
"num": 17
},
{
"global": 0,
"name": "18. Sht30 Влажность",
"type": "Reading",
"subtype": "Sht30h",
"id": "Hum30",
"widget": "anydataHum",
"page": "Сенсоры",
"descr": "SHT30 Влажность",
"int": 15,
"round": 1,
"num": 18
},
{
"global": 0,
"name": "19. HC-SR04 Ультразвуковой дальномер",
"num": 19,
"type": "Reading",
"subtype": "Sonar",
"id": "sonar",
@@ -167,7 +299,7 @@
},
{
"global": 0,
"name": "11. Кнопка подключенная к пину",
"name": "20. Кнопка подключенная к пину",
"type": "Writing",
"subtype": "ButtonIn",
"id": "btn",
@@ -181,11 +313,12 @@
"pinMode": "INPUT",
"debounceDelay": 50,
"fixState": 0,
"num": 11
"inv": 0,
"num": 20
},
{
"global": 0,
"name": "12. Управление пином",
"name": "21. Управление пином",
"type": "Writing",
"subtype": "ButtonOut",
"needSave": 0,
@@ -196,11 +329,11 @@
"int": 0,
"inv": 0,
"pin": 2,
"num": 12
"num": 21
},
{
"global": 0,
"name": "13. Расширитель портов Mcp23017",
"name": "22. Расширитель портов Mcp23017",
"type": "Reading",
"subtype": "Mcp23017",
"id": "Mcp",
@@ -210,11 +343,11 @@
"int": "0",
"addr": "0x20",
"index": 1,
"num": 13
"num": 22
},
{
"global": 0,
"name": "14. Сенсорная кнопка",
"name": "23. Сенсорная кнопка",
"type": "Writing",
"subtype": "Multitouch",
"id": "impulse",
@@ -228,11 +361,11 @@
"pinMode": "INPUT",
"debounceDelay": 50,
"PWMDelay": 500,
"num": 14
"num": 23
},
{
"global": 0,
"name": "15. Расширитель портов Pcf8574",
"name": "24. Расширитель портов Pcf8574",
"type": "Reading",
"subtype": "Pcf8574",
"id": "Pcf",
@@ -242,11 +375,11 @@
"int": "0",
"addr": "0x20",
"index": 1,
"num": 15
"num": 24
},
{
"global": 0,
"name": "16. PWM ESP8266",
"name": "25. PWM ESP8266",
"type": "Writing",
"subtype": "Pwm8266",
"id": "pwm",
@@ -258,11 +391,11 @@
"freq": 5000,
"val": 0,
"apin": -1,
"num": 16
"num": 25
},
{
"global": 0,
"name": "17. Телеграм-Лайт",
"name": "26. Телеграм-Лайт",
"type": "Writing",
"subtype": "TelegramLT",
"id": "tg",
@@ -271,14 +404,14 @@
"descr": "",
"token": "",
"chatID": "",
"num": 17
"num": 26
},
{
"header": "Экраны"
},
{
"global": 0,
"name": "18. LCD экран 2004",
"name": "27. LCD экран 2004",
"type": "Reading",
"subtype": "Lcd2004",
"id": "Lcd",
@@ -290,10 +423,10 @@
"size": "20,4",
"coord": "0,0",
"id2show": "id датчика",
"num": 18
"num": 27
},
{
"name": "19. LCD экран 1602",
"name": "28. LCD экран 1602",
"type": "Reading",
"subtype": "Lcd2004",
"id": "Lcd",
@@ -305,6 +438,6 @@
"size": "16,2",
"coord": "0,0",
"id2show": "id датчика",
"num": 19
"num": 28
}
]

View File

@@ -13,6 +13,5 @@ extern const String getThisDevice();
extern void addThisDeviceToList();
extern void asyncUdpInit();
extern String uint8tToString(uint8_t* data, size_t len);
extern bool udpPacketValidation(String& data);
extern void udpPacketParse(String& data);
extern void jsonMergeArrays(String& existJson, String& incJson);

View File

@@ -80,6 +80,10 @@
"path": "src/modules/sensors/AnalogAdc",
"active": true
},
{
"path": "src/modules/sensors/BH_1750",
"active": false
},
{
"path": "src/modules/sensors/Ble",
"active": false
@@ -100,6 +104,10 @@
"path": "src/modules/sensors/Ds18b20",
"active": true
},
{
"path": "src/modules/sensors/DS2401",
"active": false
},
{
"path": "src/modules/sensors/Emon",
"active": false
@@ -252,6 +260,10 @@
}
],
"Экраны": [
{
"path": "src/modules/display/DwinI",
"active": false
},
{
"path": "src/modules/display/Lcd2004",
"active": true

View File

@@ -116,7 +116,7 @@ build_src_filter =
lib_deps =
${common_env_data.lib_deps_external}
${env:esp32_4mb_fromitems.lib_deps}
plerup/EspSoftwareSerial
plerup/EspSoftwareSerial@^7.0.0
build_flags = -Desp32_4mb="esp32_4mb"
framework = arduino
board = esp32dev
@@ -135,17 +135,28 @@ build_src_filter =
[env:esp8266_1mb_ota_fromitems]
lib_deps =
milesburton/DallasTemperature@^3.9.1
adafruit/Adafruit BMP280 Library
https://github.com/milesburton/Arduino-Temperature-Control-Library
https://github.com/tremaru/iarduino_RTC
robtillaart/SHT2x@^0.1.1
WEMOS SHT3x@1.0.0
adafruit/Adafruit MCP23017 Arduino Library@^2.1.0
adafruit/Adafruit BusIO @ ^1.13.2
adafruit/Adafruit BusIO @ ^1.13.2
https://github.com/robotclass/RobotClass_LiquidCrystal_I2C
marcoschwartz/LiquidCrystal_I2C@^1.1.4
build_src_filter =
+<modules/virtual/Cron>
+<modules/virtual/Timer>
+<modules/virtual/Variable>
+<modules/virtual/VariableColor>
+<modules/virtual/VButton>
+<modules/sensors/AnalogAdc>
+<modules/sensors/Bmp280>
+<modules/sensors/Ds18b20>
+<modules/sensors/RTC>
+<modules/sensors/Sht20>
+<modules/sensors/Sht30>
+<modules/sensors/Sonar>
+<modules/exec/ButtonIn>
+<modules/exec/ButtonOut>
@@ -253,11 +264,12 @@ lib_deps =
https://github.com/tremaru/iarduino_RTC
robtillaart/SHT2x@^0.1.1
WEMOS SHT3x@1.0.0
plerup/espsoftwareserial
plerup/EspSoftwareSerial@^7.0.0
adafruit/Adafruit MCP23017 Arduino Library@^2.1.0
adafruit/Adafruit BusIO @ ^1.13.2
dfrobot/DFRobotDFPlayerMini @ ^1.0.5
adafruit/Adafruit BusIO @ ^1.13.2
https://github.com/robotclass/RobotClass_LiquidCrystal_I2C
marcoschwartz/LiquidCrystal_I2C@^1.1.4
build_src_filter =
+<modules/virtual/Cron>
@@ -307,6 +319,7 @@ lib_deps =
adafruit/Adafruit BusIO @ ^1.13.2
dfrobot/DFRobotDFPlayerMini @ ^1.0.5
adafruit/Adafruit BusIO @ ^1.13.2
https://github.com/robotclass/RobotClass_LiquidCrystal_I2C
marcoschwartz/LiquidCrystal_I2C@^1.1.4
build_src_filter =
+<modules/virtual/Cron>

View File

@@ -36,13 +36,19 @@ void asyncUdpInit() {
// Serial.print(packet.length());
// Serial.print(", Data: ");
// Serial.write(packet.data(), packet.length());
//String data = {packet.data(), packet.length()}; // для ESP32 подходит как замена uint8tToString, но 8266 не переваривает
String data = uint8tToString(packet.data(), packet.length());
// Serial.println(data);
if (udpPacketValidation(data)) {
SerialPrint("i", F("UDP"), "IP: " + packet.remoteIP().toString() + ":" + String(packet.remotePort()));
// Serial.println(data);
jsonMergeArrays(devListHeapJson, data);
// Serial.println(devListHeapJson);
String remoteWorkgroup = "";
data.replace("[", "");
data.replace("]", "");
if (jsonRead(data, F("wg"), remoteWorkgroup)) { // проверяем чтоб полученный формат был Json и заодно вытягиваем имя группы
String loacalWorkgroup = "";
jsonRead(settingsFlashJson, F("wg"), loacalWorkgroup);
if (remoteWorkgroup == loacalWorkgroup) {
SerialPrint("i", F("UDP"), "IP: " + packet.remoteIP().toString() + ":" + String(packet.remotePort()));
jsonMergeArrays(devListHeapJson, data);
}
} else {
SerialPrint("E", F("UDP"), F("Udp packet invalid"));
}
@@ -68,36 +74,26 @@ void asyncUdpInit() {
SerialPrint("i", F("UDP"), F("Udp Init"));
}
bool udpPacketValidation(String& data) {
// SerialPrint("i", F("UDP"), data);
String workgroup = jsonReadStr(settingsFlashJson, "wg");
if (workgroup != "" && data.indexOf(workgroup) != -1) {
return true;
} else {
return false;
}
}
void jsonMergeArrays(String& existJson, String& incJson) {
DynamicJsonDocument incJsonDoc(1024);
DeserializationError incJsonError = deserializeJson(incJsonDoc, incJson);
if (incJsonError) {
SerialPrint("E", F("UDP"), "Invailed json in incomming udp packet " + String(incJsonError.f_str()));
jsonErrorDetected();
return;
}
// if (incJsonError) { // upd: devlist заведомо верный, зачем проверять еще раз?
// SerialPrint("E", F("UDP"), "Invailed json in incomming udp packet " + String(incJsonError.f_str()));
// jsonErrorDetected();
// return;
// }
DynamicJsonDocument existJsonDoc(1024);
DeserializationError existJsonError = deserializeJson(existJsonDoc, existJson);
if (existJsonError) {
SerialPrint("E", F("UDP"), "Invailed json in existing udp dev list " + String(incJsonError.f_str()));
jsonErrorDetected();
return;
}
// if (existJsonError) { // upd: полученный json уже проверен на целостность
// SerialPrint("E", F("UDP"), "Invailed json in existing udp dev list " + String(incJsonError.f_str()));
// jsonErrorDetected();
// return;
// }
JsonArray existJsonArr = existJsonDoc.as<JsonArray>();
incJson.replace("[", "");
incJson.replace("]", "");
// incJson.replace("[", ""); // upd: уже исключены символы ранее при получении пакета
// incJson.replace("]", "");
String incIP = jsonReadStr(incJson, "ip");
String outArr = "[";
bool ipExistInList = false;

View File

@@ -30,7 +30,72 @@ void elementsLoop() {
}
#define SETUPBASE_ERRORMARKER 0
#define SETUPCONF_ERRORMARKER 1
#define SETUPSCEN_ERRORMARKER 2
#define SETUPINET_ERRORMARKER 3
#define SETUPLAST_ERRORMARKER 4
#define TICKER_ERRORMARKER 5
#define HTTP_ERRORMARKER 6
#define SOCKETS_ERRORMARKER 7
#define MQTT_ERRORMARKER 8
#define MODULES_ERRORMARKER 9
#define COUNTER_ERRORMARKER 4 // количество шагов счетчика
#define STEPPER_ERRORMARKER 100000 // размер шага счетчика интервала доверия выполнения блока кода мкс
#ifdef esp32_4mb
static int IRAM_ATTR initErrorMarkerId = 0; // ИД маркера
static int IRAM_ATTR errorMarkerId = 0;
static int IRAM_ATTR errorMarkerCounter = 0;
hw_timer_t *My_timer = NULL;
void IRAM_ATTR onTimer(){
if (errorMarkerCounter >= 0) {
if (errorMarkerCounter >= COUNTER_ERRORMARKER) {
errorMarkerId = initErrorMarkerId;
errorMarkerCounter = -1;
} else
errorMarkerCounter++;
}
}
#endif
void initErrorMarker(int id) {
#ifdef esp32_4mb
initErrorMarkerId = id;
errorMarkerCounter = 0;
#endif
}
void stopErrorMarker(int id) {
#ifdef esp32_4mb
errorMarkerCounter = -1;
if (errorMarkerId)
SerialPrint("I", "WARNING!", "A lazy (freezing loop more than " + (String)(COUNTER_ERRORMARKER * STEPPER_ERRORMARKER / 1000) + " ms) section has been found! With ID=" + (String)errorMarkerId);
errorMarkerId = 0;
initErrorMarkerId = 0;
#endif
}
void setup() {
#ifdef esp32_4mb
My_timer = timerBegin(0, 80, true);
timerAttachInterrupt(My_timer, &onTimer, true);
timerAlarmWrite(My_timer, STEPPER_ERRORMARKER, true);
timerAlarmEnable(My_timer);
//timerAlarmDisable(My_timer);
initErrorMarker(SETUPBASE_ERRORMARKER);
#endif
Serial.begin(115200);
Serial.flush();
Serial.println();
@@ -53,9 +118,12 @@ void setup() {
// синхронизация глобальных переменных с flash
globalVarsSync();
stopErrorMarker(SETUPBASE_ERRORMARKER);
initErrorMarker(SETUPCONF_ERRORMARKER);
// настраиваем микроконтроллер
configure("/config.json");
@@ -76,17 +144,24 @@ void setup() {
SerialPrint("i", "i2c", F("i2c pins overriding done"));
}
stopErrorMarker(SETUPCONF_ERRORMARKER);
initErrorMarker(SETUPSCEN_ERRORMARKER);
// подготавливаем сценарии
iotScen.loadScenario("/scenario.txt");
// создаем событие завершения инициализации основных моментов для возможности выполнения блока кода при загрузке
createItemFromNet("onInit", "1", 1);
elementsLoop();
stopErrorMarker(SETUPSCEN_ERRORMARKER);
initErrorMarker(SETUPINET_ERRORMARKER);
// подключаемся к роутеру
routerConnect();
@@ -106,14 +181,15 @@ void setup() {
standWebSocketsInit();
#endif
stopErrorMarker(SETUPINET_ERRORMARKER);
initErrorMarker(SETUPLAST_ERRORMARKER);
// NTP
ntpInit();
// инициализация mqtt
//mqttInit();
// инициализация задач переодического выполнения
periodicTasksInit();
@@ -149,6 +225,8 @@ void setup() {
// test
Serial.println("-------test start--------");
Serial.println("--------test end---------");
stopErrorMarker(SETUPLAST_ERRORMARKER);
}
@@ -158,21 +236,29 @@ void loop() {
unsigned long st = millis();
#endif
initErrorMarker(TICKER_ERRORMARKER);
ts.update();
stopErrorMarker(TICKER_ERRORMARKER);
#ifdef STANDARD_WEB_SERVER
initErrorMarker(HTTP_ERRORMARKER);
HTTP.handleClient();
stopErrorMarker(HTTP_ERRORMARKER);
#endif
#ifdef STANDARD_WEB_SOCKETS
initErrorMarker(SOCKETS_ERRORMARKER);
standWebSocket.loop();
stopErrorMarker(SOCKETS_ERRORMARKER);
#endif
initErrorMarker(MQTT_ERRORMARKER);
mqttLoop();
stopErrorMarker(MQTT_ERRORMARKER);
initErrorMarker(MODULES_ERRORMARKER);
elementsLoop();
stopErrorMarker(MODULES_ERRORMARKER);
// #ifdef LOOP_DEBUG
// loopPeriod = millis() - st;

View File

@@ -0,0 +1,56 @@
#include "Global.h"
#include "classes/IoTItem.h"
#ifdef ESP8266
#include <SoftwareSerial.h>
#else
#include <HardwareSerial.h>
#endif
class DwinI : public IoTItem {
private:
#ifdef ESP8266
SoftwareSerial* _myUART;
#else
HardwareSerial* _myUART;
#endif
public:
DwinI(String parameters) : IoTItem(parameters) {
int _tx, _rx, _speed, _line;
jsonRead(parameters, "RX", _rx);
jsonRead(parameters, "TX", _tx);
jsonRead(parameters, "speed", _speed);
jsonRead(parameters, "line", _line);
#ifdef ESP8266
_myUART = new SoftwareSerial(_rx, _tx);
_myUART->begin(_speed);
#endif
#ifdef ESP32
_myUART = new HardwareSerial(_line);
_myUART->begin(_speed, SERIAL_8N1, _rx, _tx);
#endif
}
void doByInterval() {
Serial.println("ddddddddddddd");
}
IoTValue execute(String command, std::vector<IoTValue> &param) { // будет возможным использовать, когда сценарии запустятся
return {};
}
~DwinI(){
};
};
void *getAPI_DwinI(String subtype, String param) {
if (subtype == F("DwinI")) {
return new DwinI(param);
} else {
return nullptr;
}
}

View File

@@ -0,0 +1,61 @@
{
"menuSection": "Экраны",
"configItem": [{
"global": 0,
"name": "LCD Dwin экран",
"type": "Reading",
"subtype": "DwinI",
"id": "dwin",
"widget": "",
"page": "",
"descr": "",
"int": 15,
"TX": 17,
"RX": 16,
"line": 2,
"speed": 115200
}],
"about": {
"authorName": "Ilya Belyakov",
"authorContact": "https://t.me/Biveraxe",
"authorGit": "https://github.com/biveraxe",
"specialThanks": "",
"moduleName": "DwinI",
"moduleVersion": "1.0",
"usedRam": {
"esp32_4mb": 15,
"esp8266_4mb": 15
},
"moduleDesc": "Позволяет выводить на графические экраны фирмы Dwin информацию от элементов конфигурации в автоматическом режиме.",
"propInfo": {
"int": ""
},
"funcInfo": [
{
"name": "rrrr",
"descr": "rrrr",
"params": []
}
]
},
"defActive": false,
"usedLibs": {
"esp32_4mb": [
],
"esp8266_4mb": [
],
"esp8266_1mb": [
],
"esp8266_1mb_ota": [
],
"esp8285_1mb": [
],
"esp8285_1mb_ota": [
]
}
}

View File

@@ -1,12 +1,15 @@
#include "Global.h"
#include "classes/IoTItem.h"
#include "LiquidCrystal_I2C.h"
//#include "LiquidCrystal_I2C.h"
#include <RobotClass_LiquidCrystal_I2C.h>
#include <map>
void scanI2C();
LiquidCrystal_I2C *LCDI2C;
//LiquidCrystal_I2C *LCDI2C;
RobotClass_LiquidCrystal_I2C *LCDI2C;
class Lcd2004 : public IoTItem {
private:
@@ -34,7 +37,8 @@ class Lcd2004 : public IoTItem {
int w = selectFromMarkerToMarker(size, ",", 0).toInt(); //количество столбцов
int h = selectFromMarkerToMarker(size, ",", 1).toInt(); //количество строк
if (LCDI2C == nullptr) { //инициализации экрана еще не было
LCDI2C = new LiquidCrystal_I2C(hexStringToUint8(_addr), w, h);
//LCDI2C = new LiquidCrystal_I2C(hexStringToUint8(_addr), w, h);
LCDI2C = new RobotClass_LiquidCrystal_I2C(hexStringToUint8(_addr), w, h, CP_UTF8);
if (LCDI2C != nullptr) {
LCDI2C->init();
}

View File

@@ -105,21 +105,27 @@
"usedLibs": {
"esp32_4mb": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
],
"esp8266_4mb": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
],
"esp8266_1mb": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
],
"esp8266_1mb_ota": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
],
"esp8285_1mb": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
],
"esp8285_1mb_ota": [
"https://github.com/robotclass/RobotClass_LiquidCrystal_I2C",
"marcoschwartz/LiquidCrystal_I2C@^1.1.4"
]
}

View File

@@ -0,0 +1,32 @@
#include "Global.h"
#include "classes/IoTItem.h"
#include "BH1750.h"
class Bh1750 : public IoTItem {
BH1750 _lightMeter;
public:
Bh1750(String parameters): IoTItem(parameters){
_lightMeter.begin();
}
void doByInterval() {
value.valD = _lightMeter.readLightLevel();
if (value.valD < 70000)
regEvent(value.valD, "BH1750");
else
SerialPrint("E", "Sensor BH1750", "Error");
}
~Bh1750() {};
};
void* getAPI_Bh1750(String subtype, String param) {
if (subtype == F("Bh1750")) {
return new Bh1750(param);
} else {
return nullptr;
}
}

View File

@@ -0,0 +1,44 @@
{
"menuSection": "Сенсоры",
"configItem": [{
"global": 0,
"name": "Cенсор освещенность Bh1750",
"type": "Reading",
"subtype": "Bh1750",
"id": "Bh1750",
"widget": "anydata",
"page": "Сенсоры",
"descr": "Освещённость",
"round": 1,
"int": 15
}],
"about": {
"authorName": "Ilya Belyakov",
"authorContact": "https://t.me/Biveraxe",
"authorGit": "https://github.com/biveraxe",
"exampleURL": "https://iotmanager.org/wiki",
"specialThanks": "",
"moduleName": "Bh1750",
"moduleVersion": "1.0",
"usedRam": {
"esp32_4mb": 15,
"esp8266_4mb": 15
},
"title": "Cенсор освещённости",
"moduleDesc": "Позволяет получить текущее значение освещённости в LUX.",
"propInfo": {
"int": "Количество секунд между опросами датчика."
}
},
"defActive": false,
"usedLibs": {
"esp32_4mb": [
"BH1750"
],
"esp8266_4mb": [
"BH1750"
]
}
}

View File

@@ -0,0 +1,62 @@
#include "Global.h"
#include "classes/IoTItem.h"
#include <OneWire.h>
bool cmpAddr(uint8_t *addr1, uint8_t *addr2, int size) {
for (int i=0; i<size; i++) {
if (addr1[i] != addr2[i]) return false;
}
return true;
}
class DS2401 : public IoTItem {
private:
OneWire* _ds = nullptr;
byte _addr[8], _oldAddr[8];
char _addrStr[20];
int _intRepeat;
int _repeatCount = 0;
public:
DS2401(String parameters): IoTItem(parameters) {
int pin;
jsonRead(parameters, "pin", pin);
jsonRead(parameters, "intRepeat", _intRepeat);
_interval = _interval / 1000; // корректируем величину интервала int, теперь он в миллисекундах
_ds = new OneWire(pin);
}
void doByInterval() {
if (_ds->search(_addr) && _ds) {
if ( OneWire::crc8( _addr, 7) != _addr[7]) {
SerialPrint("E", "DS2401", "CRC is not valid!", _id);
return;
}
if (!cmpAddr(_addr, _oldAddr, 8) || _repeatCount > _intRepeat) {
hex2string(_addr, 8, _addrStr);
value.valS = _addrStr;
value.isDecimal = false;
regEvent(value.valS, "DS2401");
memcpy(_oldAddr, _addr, 8);
_repeatCount = 0;
}
}
if (_repeatCount <= _intRepeat) _repeatCount++;
}
~DS2401() {
if (_ds) delete _ds;
};
};
void* getAPI_DS2401(String subtype, String param) {
if (subtype == F("DS2401")) {
return new DS2401(param);
} else {
return nullptr;
}
}

View File

@@ -0,0 +1,51 @@
{
"menuSection": "Сенсоры",
"configItem": [
{
"global": 0,
"name": "Сканер DS2401 меток",
"type": "Reading",
"subtype": "DS2401",
"id": "rds",
"int": 100,
"intRepeat": 6,
"pin": 12
}
],
"about": {
"authorName": "Ilya Belyakov",
"authorContact": "https://t.me/Biveraxe",
"authorGit": "https://github.com/biveraxe",
"specialThanks": "",
"moduleName": "DS2401",
"moduleVersion": "1.0",
"usedRam": {
"esp32_4mb": 15,
"esp8266_4mb": 15
},
"title": "Сканер DS2401 меток",
"moduleDesc": "Ожидает появления на шине 1-wire метки DS2401",
"propInfo": {
"pin": "GPIO номер, к которому подключена шина 1-Wire с подтяжкой 4,7к",
"int": "Количество миллисекунд между опросами шины. 0 - выключено.",
"intRepeat": "Количество интервалов int пропускаем повторы, т.е. при int=100 и intRepeat=6, первые 600мс игнорируем одинаковые адреса меток."
},
"retInfo": "Содержит 64-битный адрес метки в формате HEX строки",
"funcInfo": []
},
"defActive": false,
"usedLibs": {
"esp32_4mb": [
],
"esp8266_4mb": [
],
"esp8266_1mb": [
],
"esp8266_1mb_ota": [
],
"esp8285_1mb": [
],
"esp8285_1mb_ota": [
]
}
}

View File

@@ -21,7 +21,7 @@ class GY21t : public IoTItem {
// wire->read();
value.valD = sensor->GY21_Temperature();
if (value.valD < 300)
regEvent(value.valD, "GY21"); // TODO: найти способ понимания ошибки получения данных
regEvent(value.valD, "GY21");
else
SerialPrint("E", "Sensor GY21t", "Error", _id);
}
@@ -36,8 +36,8 @@ class GY21h : public IoTItem {
void doByInterval() {
// sht->read();
value.valD = sensor->GY21_Humidity();
if (value.valD != 0)
regEvent(value.valD, "GY21h"); // TODO: найти способ понимания ошибки получения данных
if (value.valD > 0)
regEvent(value.valD, "GY21h");
else
SerialPrint("E", "Sensor GY21h", "Error", _id);
}

View File

@@ -9,11 +9,16 @@ class RCswitch : public IoTItem {
private:
int _pinRx; // Выход радио модуля
int _pinTx; // Выход модуля передатчика
int _intRepeat = 6;
int _repeatCount = 0;
unsigned long _oldValue = 0;
unsigned long _newValue = 0;
public:
RCswitch(String parameters): IoTItem(parameters) {
jsonRead(parameters, "pinRx", _pinRx);
jsonRead(parameters, "pinTx", _pinTx);
jsonRead(parameters, "intRepeat", _intRepeat);
_interval = _interval / 1000; // корректируем величину интервала int, теперь он в миллисекундах
if (_pinRx >= 0) {
Serial.printf("Protocol: %d", _pinRx);
@@ -32,11 +37,19 @@ class RCswitch : public IoTItem {
// Serial.print("bit ");
// Serial.print("Protocol: ");
// Serial.println( mySwitch.getReceivedProtocol() );
value.valD = mySwitch.getReceivedValue();
regEvent(value.valD, "RCswitch");
_newValue = mySwitch.getReceivedValue();
if (_newValue != _oldValue || _repeatCount > _intRepeat) {
value.valD = _newValue;
regEvent(value.valD, "RCswitch");
_oldValue = _newValue;
_repeatCount = 0;
}
mySwitch.resetAvailable();
}
if (_repeatCount <= _intRepeat) _repeatCount++;
}
IoTValue execute(String command, std::vector<IoTValue> &param) {

View File

@@ -8,7 +8,8 @@
"type": "Reading",
"subtype": "RCswitch",
"id": "rsw",
"int": 500,
"int": 100,
"intRepeat": 6,
"pinRx": 12,
"pinTx": 12
}
@@ -29,7 +30,8 @@
"propInfo": {
"pinRx": "GPIO номер, к которому подключен радио приемник 433 MHz. Если < 0, то приемник выключен",
"pinTx": "GPIO номер, к которому подключен радио передатчик 433 MHz. Если < 0, то передатчик выключен",
"int": "Количество миллисекунд между опросами датчика. 0 - выключено. (устранение повторений при нажатой кнопке)"
"int": "Количество миллисекунд между опросами датчика. 0 - выключено.",
"intRepeat": "Количество интервалов int пропускаем повторы, т.е. при int=100 и intRepeat=6, первые 600мс игнорируем одинаковые значения."
},
"retInfo": "Содержит принятое значение",
"funcInfo": [

View File

@@ -66,10 +66,10 @@
"defActive": true,
"usedLibs": {
"esp32_4mb": [
"plerup/espsoftwareserial"
"plerup/EspSoftwareSerial@^7.0.0"
],
"esp8266_4mb": [
"plerup/espsoftwareserial"
"plerup/EspSoftwareSerial@^7.0.0"
]
}
}

View File

@@ -16,7 +16,7 @@ class Loging : public IoTItem {
int _wsNum = -1;
int points;
int keepdays;
//int keepdays;
IoTItem *dateIoTItem;
@@ -36,12 +36,12 @@ class Loging : public IoTItem {
}
jsonRead(parameters, F("int"), interval);
interval = interval * 1000 * 60; // приводим к милисекундам
jsonRead(parameters, F("keepdays"), keepdays);
//jsonRead(parameters, F("keepdays"), keepdays, false);
// создадим экземпляр класса даты
dateIoTItem = (IoTItem *)getAPI_Date("{\"id\": \"" + id + "-date\",\"int\":\"20\",\"subtype\":\"date\"}");
IoTItems.push_back(dateIoTItem);
SerialPrint("E", F("Loging"), "created date instance " + id);
SerialPrint("I", F("Loging"), "created date instance " + id);
}
void doByInterval() {