diff --git a/PrepareProject.py b/PrepareProject.py index d29c8da4..46157d96 100644 --- a/PrepareProject.py +++ b/PrepareProject.py @@ -16,6 +16,7 @@ # поддерживаемые контроллеры (профили): # esp8266_4mb # esp32_4mb +# esp32s2_4mb # esp8266_1mb # esp8266_1mb_ota # esp8285_1mb @@ -23,6 +24,7 @@ # esp8266_2mb # esp8266_2mb_ota + import configparser import os, json, sys, getopt from pathlib import Path diff --git a/data_svelte/items.json b/data_svelte/items.json index 72366d57..ed78c67e 100644 --- a/data_svelte/items.json +++ b/data_svelte/items.json @@ -192,7 +192,19 @@ "header": "Сенсоры" }, { - "name": "13. Acs712 Ток", + "name": "13. A02 Дальность", + "type": "Reading", + "subtype": "A02Distance", + "id": "dist", + "widget": "anydataCm", + "page": "Сенсоры", + "descr": "Дальность", + "int": 5, + "round": 1, + "num": 13 + }, + { + "name": "14. Acs712 Ток", "type": "Reading", "subtype": "Acs712", "id": "amp", @@ -207,11 +219,11 @@ "sens": 100, "adczero": 512, "btn-setZero": "nil", - "num": 13 + "num": 14 }, { "global": 0, - "name": "14. AHTXX Температура", + "name": "15. AHTXX Температура", "type": "Reading", "subtype": "AhtXXt", "id": "Temp20", @@ -222,11 +234,11 @@ "addr": "0x38", "shtType": 1, "round": 1, - "num": 14 + "num": 15 }, { "global": 0, - "name": "15. AHTXX Влажность", + "name": "16. AHTXX Влажность", "type": "Reading", "subtype": "AhtXXh", "id": "Hum20", @@ -237,11 +249,11 @@ "addr": "0x38", "shtType": 1, "round": 1, - "num": 15 + "num": 16 }, { "global": 0, - "name": "16. Аналоговый сенсор", + "name": "17. Аналоговый сенсор", "type": "Reading", "subtype": "AnalogAdc", "id": "t", @@ -255,11 +267,11 @@ "pin": 0, "int": 15, "avgSteps": 1, - "num": 16 + "num": 17 }, { "global": 0, - "name": "17. BME280 Температура", + "name": "18. BME280 Температура", "type": "Reading", "subtype": "Bme280t", "id": "Tmp3", @@ -269,11 +281,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 17 + "num": 18 }, { "global": 0, - "name": "18. BME280 Давление", + "name": "19. BME280 Давление", "type": "Reading", "subtype": "Bme280p", "id": "Press3", @@ -283,11 +295,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 18 + "num": 19 }, { "global": 0, - "name": "19. BME280 Влажность", + "name": "20. BME280 Влажность", "type": "Reading", "subtype": "Bme280h", "id": "Hum3", @@ -297,11 +309,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 19 + "num": 20 }, { "global": 0, - "name": "20. BME280 Tочка росы", + "name": "21. BME280 Tочка росы", "type": "Reading", "subtype": "Bme280dp", "id": "Dew3", @@ -311,11 +323,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 20 + "num": 21 }, { "global": 0, - "name": "21. BMP280 Температура", + "name": "22. BMP280 Температура", "type": "Reading", "subtype": "Bmp280t", "id": "tmp3", @@ -325,11 +337,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 21 + "num": 22 }, { "global": 0, - "name": "22. BMP280 Давление", + "name": "23. BMP280 Давление", "type": "Reading", "subtype": "Bmp280p", "id": "Press3", @@ -339,11 +351,11 @@ "int": 15, "addr": "0x77", "round": 1, - "num": 22 + "num": 23 }, { "global": 0, - "name": "23. DHT11 Температура", + "name": "24. DHT11 Температура", "type": "Reading", "subtype": "Dht1122t", "id": "tmp3", @@ -353,11 +365,11 @@ "int": 15, "pin": 0, "senstype": "dht11", - "num": 23 + "num": 24 }, { "global": 0, - "name": "24. DHT11 Влажность", + "name": "25. DHT11 Влажность", "type": "Reading", "subtype": "Dht1122h", "id": "Hum3", @@ -367,11 +379,11 @@ "int": 15, "pin": 0, "senstype": "dht11", - "num": 24 + "num": 25 }, { "global": 0, - "name": "25. DS18B20 Температура", + "name": "26. DS18B20 Температура", "type": "Reading", "subtype": "Ds18b20", "id": "dstmp", @@ -383,11 +395,49 @@ "index": 0, "addr": "", "round": 1, - "num": 25 + "num": 26 }, { "global": 0, - "name": "26. Аналоговый счетчик импульсов", + "name": "27. DS2423 счетчик 1", + "type": "Reading", + "subtype": "Ds2423a", + "id": "dscounta", + "widget": "anydataDef", + "page": "Счетчики", + "descr": "DS1 V", + "plus": 0, + "multiply": 1, + "pin": 4, + "index": 0, + "addr": "", + "int": 10, + "round": 0, + "needSave": 0, + "num": 27 + }, + { + "global": 0, + "name": "28. DS2423 счетчик 2", + "type": "Reading", + "subtype": "Ds2423b", + "id": "dscountb", + "widget": "anydataDef", + "page": "Счетчики", + "descr": "DS2 V", + "plus": 0, + "multiply": 1, + "pin": 4, + "index": 0, + "addr": "", + "int": 10, + "round": 0, + "needSave": 0, + "num": 28 + }, + { + "global": 0, + "name": "29. Аналоговый счетчик импульсов", "type": "Writing", "subtype": "Impulse", "id": "impulse", @@ -400,11 +450,32 @@ "pinMode": "INPUT", "debounceDelay": 3, "multiply": 1, - "num": 26 + "num": 29 }, { "global": 0, - "name": "27. PZEM 004t Напряжение", + "name": "30. Cенсор температуры NTC", + "type": "Reading", + "subtype": "Ntc", + "id": "Ntctmp", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "NTC Температура", + "needSave": 0, + "val": "0", + "int": 15, + "pin": "35", + "R1": "10000", + "R0": "10000", + "Beta": "3950.0", + "T0": "25", + "Vs": "3.3", + "round": 1, + "num": 30 + }, + { + "global": 0, + "name": "31. PZEM 004t Напряжение", "type": "Reading", "subtype": "Pzem004v", "id": "v", @@ -414,11 +485,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 27 + "num": 31 }, { "global": 0, - "name": "28. PZEM 004t Сила тока", + "name": "32. PZEM 004t Сила тока", "type": "Reading", "subtype": "Pzem004a", "id": "a", @@ -428,11 +499,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 28 + "num": 32 }, { "global": 0, - "name": "29. PZEM 004t Мощность", + "name": "33. PZEM 004t Мощность", "type": "Reading", "subtype": "Pzem004w", "id": "w", @@ -442,11 +513,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 29 + "num": 33 }, { "global": 0, - "name": "30. PZEM 004t Энергия", + "name": "34. PZEM 004t Энергия", "type": "Reading", "subtype": "Pzem004wh", "id": "wh", @@ -456,11 +527,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 30 + "num": 34 }, { "global": 0, - "name": "31. PZEM 004t Частота", + "name": "35. PZEM 004t Частота", "type": "Reading", "subtype": "Pzem004hz", "id": "hz", @@ -470,11 +541,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 31 + "num": 35 }, { "global": 0, - "name": "32. PZEM 004t Косинус", + "name": "36. PZEM 004t Косинус", "type": "Reading", "subtype": "Pzem004pf", "id": "pf", @@ -484,11 +555,11 @@ "int": 15, "addr": "0xF8", "round": 1, - "num": 32 + "num": 36 }, { "global": 0, - "name": "33. PZEM настройка", + "name": "37. PZEM настройка", "type": "Reading", "subtype": "Pzem004cmd", "id": "set", @@ -500,11 +571,11 @@ "changeaddr": 0, "setaddr": "0x01", "reset": 0, - "num": 33 + "num": 37 }, { "global": 0, - "name": "34. Часы реального времени", + "name": "38. Часы реального времени", "type": "Reading", "subtype": "RTC", "id": "rtc", @@ -520,11 +591,11 @@ "int": 5, "btn-setUTime": "0", "btn-setSysTime": "nil", - "num": 34 + "num": 38 }, { - "name": "35. (S8) Cенсор качества воздуха", - "num": 35, + "name": "39. (S8) Cенсор качества воздуха", + "num": 39, "type": "Reading", "subtype": "S8co", "id": "s8co", @@ -538,7 +609,50 @@ }, { "global": 0, - "name": "36. Sht20 Температура", + "name": "40. SCD40 Углекислый газ", + "type": "Reading", + "subtype": "Scd40co2", + "id": "Scd40co2", + "widget": "anydataPpm", + "page": "Сенсоры", + "descr": "SCD40 Углекислый газ", + "int": 15, + "round": 0, + "lowPeriodic": 1, + "autoCalibration": 1, + "btn-Recalibration": 0, + "num": 40 + }, + { + "global": 0, + "name": "41. SCD40 Влажность", + "type": "Reading", + "subtype": "Scd40h", + "id": "Scd40h", + "widget": "anydataHum", + "page": "Сенсоры", + "descr": "SCD40 Влажность", + "int": 15, + "round": 1, + "num": 41 + }, + { + "global": 0, + "name": "42. SCD40 Температура", + "type": "Reading", + "subtype": "Scd40t", + "id": "Scd40t", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "SCD40 Температура", + "int": 15, + "round": 1, + "offset": 4, + "num": 42 + }, + { + "global": 0, + "name": "43. Sht20 Температура", "type": "Reading", "subtype": "Sht20t", "id": "tmp2", @@ -547,11 +661,11 @@ "descr": "Температура", "int": 15, "round": 1, - "num": 36 + "num": 43 }, { "global": 0, - "name": "37. Sht20 Влажность", + "name": "44. Sht20 Влажность", "type": "Reading", "subtype": "Sht20h", "id": "Hum2", @@ -560,11 +674,11 @@ "descr": "Влажность", "int": 15, "round": 1, - "num": 37 + "num": 44 }, { "global": 0, - "name": "38. Sht30 Температура", + "name": "45. Sht30 Температура", "type": "Reading", "subtype": "Sht30t", "id": "tmp30", @@ -573,11 +687,11 @@ "descr": "SHT30 Температура", "int": 15, "round": 1, - "num": 38 + "num": 45 }, { "global": 0, - "name": "39. Sht30 Влажность", + "name": "46. Sht30 Влажность", "type": "Reading", "subtype": "Sht30h", "id": "Hum30", @@ -586,12 +700,12 @@ "descr": "SHT30 Влажность", "int": 15, "round": 1, - "num": 39 + "num": 46 }, { "global": 0, - "name": "40. HC-SR04 Ультразвуковой дальномер", - "num": 40, + "name": "47. HC-SR04 Ультразвуковой дальномер", + "num": 47, "type": "Reading", "subtype": "Sonar", "id": "sonar", @@ -603,7 +717,7 @@ "int": 5 }, { - "name": "41. UART", + "name": "48. UART", "type": "Reading", "subtype": "UART", "page": "", @@ -615,14 +729,14 @@ "line": 2, "speed": 9600, "eventFormat": 0, - "num": 41 + "num": 48 }, { "header": "Исполнительные устройства" }, { "global": 0, - "name": "42. Кнопка подключенная к пину", + "name": "49. Кнопка подключенная к пину", "type": "Writing", "subtype": "ButtonIn", "id": "btn", @@ -637,11 +751,11 @@ "debounceDelay": 50, "fixState": 0, "inv": 0, - "num": 42 + "num": 49 }, { "global": 0, - "name": "43. Управление пином", + "name": "50. Управление пином", "type": "Writing", "subtype": "ButtonOut", "needSave": 0, @@ -652,11 +766,11 @@ "int": 0, "inv": 0, "pin": 2, - "num": 43 + "num": 50 }, { "global": 0, - "name": "44. Пассивный звуковой извещатель", + "name": "51. Пассивный звуковой извещатель", "type": "Writing", "subtype": "Buzzer", "id": "buzzer", @@ -675,11 +789,11 @@ "cycle": 0, "indication": 1, "val": 0, - "num": 44 + "num": 51 }, { "global": 0, - "name": "45. Энкодер", + "name": "52. Энкодер", "type": "Writing", "subtype": "Encoder", "id": "enc", @@ -692,11 +806,11 @@ "step": 1, "stepOnPress": 5, "pins": "4,5,2", - "num": 45 + "num": 52 }, { "global": 0, - "name": "46. Сервопривод", + "name": "53. Сервопривод", "type": "Writing", "subtype": "IoTServo", "id": "servo", @@ -707,11 +821,11 @@ "pin": 12, "apin": -1, "amap": "0, 4096, 0, 180", - "num": 46 + "num": 53 }, { "global": 0, - "name": "47. Расширитель портов Mcp23017", + "name": "54. Расширитель портов Mcp23017", "type": "Reading", "subtype": "Mcp23017", "id": "Mcp", @@ -721,11 +835,11 @@ "int": "0", "addr": "0x20", "index": 1, - "num": 47 + "num": 54 }, { "global": 0, - "name": "48. MP3 плеер", + "name": "55. MP3 плеер", "type": "Reading", "subtype": "Mp3", "id": "mp3", @@ -735,11 +849,11 @@ "int": 1, "pins": "14,12", "volume": 20, - "num": 48 + "num": 55 }, { "global": 0, - "name": "49. Сенсорная кнопка", + "name": "56. Сенсорная кнопка", "type": "Writing", "subtype": "Multitouch", "id": "impulse", @@ -753,11 +867,11 @@ "pinMode": "INPUT", "debounceDelay": 50, "PWMDelay": 500, - "num": 49 + "num": 56 }, { "global": 0, - "name": "50. Расширитель портов Pcf8574", + "name": "57. Расширитель портов Pcf8574", "type": "Reading", "subtype": "Pcf8574", "id": "Pcf", @@ -767,29 +881,27 @@ "int": "0", "addr": "0x20", "index": 1, - "num": 50 + "num": 57 }, { "global": 0, - "name": "51. PWM ESP32", + "name": "58. PWM ESP8266", "type": "Writing", - "subtype": "Pwm32", + "subtype": "Pwm8266", "id": "pwm", "widget": "range", "page": "Кнопки", "descr": "PWM", "int": 0, - "pin": 2, + "pin": 15, "freq": 5000, - "ledChannel": 2, - "PWM_resolution": 10, "val": 0, "apin": -1, - "num": 51 + "num": 58 }, { "global": 0, - "name": "52. Телеграм-Лайт", + "name": "59. Телеграм-Лайт", "type": "Writing", "subtype": "TelegramLT", "id": "tg", @@ -798,14 +910,14 @@ "descr": "", "token": "", "chatID": "", - "num": 52 + "num": 59 }, { "header": "Экраны" }, { "global": 0, - "name": "53. LCD экран 2004", + "name": "60. LCD экран 2004", "type": "Reading", "subtype": "Lcd2004", "id": "Lcd", @@ -817,10 +929,10 @@ "size": "20,4", "coord": "0,0", "id2show": "id датчика", - "num": 53 + "num": 60 }, { - "name": "54. LCD экран 1602", + "name": "61. LCD экран 1602", "type": "Reading", "subtype": "Lcd2004", "id": "Lcd", @@ -832,6 +944,6 @@ "size": "16,2", "coord": "0,0", "id2show": "id датчика", - "num": 54 + "num": 61 } ] \ No newline at end of file diff --git a/data_svelte/myProfile.json b/data_svelte/myProfile.json index b0ce54f5..01261688 100644 --- a/data_svelte/myProfile.json +++ b/data_svelte/myProfile.json @@ -24,8 +24,8 @@ }, "projectProp": { "platformio": { - "default_envs": "esp32_4mb", - "comments_default_envs": "choose from: esp8266_4mb or esp32_4mb or esp8266_1mb or esp8266_1mb_ota or esp8285_1mb or esp8285_1mb_ota" + "default_envs": "esp8266_4mb", + "comments_default_envs": "choose from: esp8266_4mb or esp32_4mb or esp32s2_4mb or esp8266_1mb or esp8266_1mb_ota or esp8285_1mb or esp8285_1mb_ota" } }, "modules": { @@ -34,6 +34,10 @@ "path": "src/modules/virtual/Cron", "active": true }, + { + "path": "src/modules/virtual/GoogleSheet", + "active": false + }, { "path": "src/modules/virtual/Loging", "active": true @@ -112,6 +116,10 @@ "path": "src/modules/sensors/DS2401", "active": false }, + { + "path": "src/modules/sensors/Ds2423", + "active": true + }, { "path": "src/modules/sensors/Emon", "active": false @@ -160,6 +168,10 @@ "path": "src/modules/sensors/Mhz19", "active": false }, + { + "path": "src/modules/sensors/Ntc", + "active": true + }, { "path": "src/modules/sensors/Pzem004t", "active": true @@ -176,6 +188,10 @@ "path": "src/modules/sensors/S8", "active": true }, + { + "path": "src/modules/sensors/Scd40", + "active": true + }, { "path": "src/modules/sensors/Sds011", "active": false diff --git a/include/Const.h b/include/Const.h index ed0c83dd..47841990 100644 --- a/include/Const.h +++ b/include/Const.h @@ -28,7 +28,11 @@ #define FIRMWARE_NAME "esp32_4mb" #endif -// Размер буфера json +#ifdef esp32s2_4mb +#define FIRMWARE_NAME "esp32s2_4mb" +#endif + +//Размер буфера json #define JSON_BUFFER_SIZE 2048 // держим 2 кб не меняем #define WEB_SOCKETS_FRAME_SIZE 2048 diff --git a/myProfile.json b/myProfile.json index b0ce54f5..01261688 100644 --- a/myProfile.json +++ b/myProfile.json @@ -24,8 +24,8 @@ }, "projectProp": { "platformio": { - "default_envs": "esp32_4mb", - "comments_default_envs": "choose from: esp8266_4mb or esp32_4mb or esp8266_1mb or esp8266_1mb_ota or esp8285_1mb or esp8285_1mb_ota" + "default_envs": "esp8266_4mb", + "comments_default_envs": "choose from: esp8266_4mb or esp32_4mb or esp32s2_4mb or esp8266_1mb or esp8266_1mb_ota or esp8285_1mb or esp8285_1mb_ota" } }, "modules": { @@ -34,6 +34,10 @@ "path": "src/modules/virtual/Cron", "active": true }, + { + "path": "src/modules/virtual/GoogleSheet", + "active": false + }, { "path": "src/modules/virtual/Loging", "active": true @@ -112,6 +116,10 @@ "path": "src/modules/sensors/DS2401", "active": false }, + { + "path": "src/modules/sensors/Ds2423", + "active": true + }, { "path": "src/modules/sensors/Emon", "active": false @@ -160,6 +168,10 @@ "path": "src/modules/sensors/Mhz19", "active": false }, + { + "path": "src/modules/sensors/Ntc", + "active": true + }, { "path": "src/modules/sensors/Pzem004t", "active": true @@ -176,6 +188,10 @@ "path": "src/modules/sensors/S8", "active": true }, + { + "path": "src/modules/sensors/Scd40", + "active": true + }, { "path": "src/modules/sensors/Sds011", "active": false diff --git a/platformio.ini b/platformio.ini index a13d7021..7cf8c373 100644 --- a/platformio.ini +++ b/platformio.ini @@ -1,5 +1,5 @@ [platformio] -default_envs = esp32_4mb +default_envs = esp8266_4mb data_dir = data_svelte [common_env_data] @@ -79,7 +79,7 @@ build_flags = -Desp8266_2mb="esp8266_2mb" framework = arduino board = d1_wroom_02 board_build.ldscript = eagle.flash.2m1m.ld -platform = espressif8266 +platform = espressif8266 @4.2.0 monitor_filters = esp8266_exception_decoder upload_speed = 921600 monitor_speed = 115200 @@ -100,7 +100,7 @@ build_flags = -Desp8266_2mb_ota="esp8266_2mb_ota" framework = arduino board = d1_wroom_02 board_build.ldscript = eagle.flash.2m256.ld -platform = espressif8266 +platform = espressif8266 @4.2.0 monitor_filters = esp8266_exception_decoder upload_speed = 921600 monitor_speed = 115200 @@ -174,6 +174,29 @@ build_src_filter = + ${env:esp32_4mb_fromitems.build_src_filter} +[env:esp32s2_4mb] +lib_deps = + ${common_env_data.lib_deps_external} + ${env:esp32s2_4mb_fromitems.lib_deps} +build_flags = + -Desp32s2_4mb="esp32s2_4mb" + -DARDUINO_USB_CDC_ON_BOOT=1 + -DARDUINO_USB_MODE=0 +framework = arduino +board = lolin_s2_mini +platform = espressif32 @6.3.1 +monitor_filters = esp32_exception_decoder +upload_speed = 921600 +monitor_speed = 115200 +debug_tool = esp-prog +board_build.filesystem = littlefs +build_src_filter = + +<*.cpp> + + + + + + + ${env:esp32s2_4mb_fromitems.build_src_filter} + [env:esp8266_1mb_ota_fromitems] lib_deps = adafruit/Adafruit BME280 Library @@ -371,7 +394,11 @@ lib_deps = adafruit/Adafruit BMP280 Library beegee-tokyo/DHT sensor library for ESPx https://github.com/milesburton/Arduino-Temperature-Control-Library + https://github.com/jbechter/arduino-onewire-DS2423 + paulstoffregen/OneWire @ ^2.3.7 https://github.com/tremaru/iarduino_RTC + Sensirion I2C SCD4x @0.4.0 + Sensirion Core @0.6.0 robtillaart/SHT2x@^0.1.1 WEMOS SHT3x@1.0.0 plerup/EspSoftwareSerial @@ -398,10 +425,13 @@ build_src_filter = + + + + + + + + + + + + + + + + @@ -421,23 +451,42 @@ build_src_filter = [env:esp32_4mb_fromitems] lib_deps = - https://github.com/enjoyneering/AHTxx.git - adafruit/Adafruit BME280 Library - adafruit/Adafruit BMP280 Library - beegee-tokyo/DHT sensor library for ESPx https://github.com/milesburton/Arduino-Temperature-Control-Library + https://github.com/jbechter/arduino-onewire-DS2423 + paulstoffregen/OneWire @ ^2.3.7 https://github.com/tremaru/iarduino_RTC - robtillaart/SHT2x@^0.1.1 WEMOS SHT3x@1.0.0 plerup/EspSoftwareSerial gyverlibs/EncButton @ ^2.0 - https://github.com/RoboticsBrno/ServoESP32 - 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 = + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[env:esp32s2_4mb_fromitems] +lib_deps = build_src_filter = + + @@ -447,30 +496,5 @@ build_src_filter = + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + + - + diff --git a/src/EspFileSystem.cpp b/src/EspFileSystem.cpp index e284d0ed..cac9df49 100644 --- a/src/EspFileSystem.cpp +++ b/src/EspFileSystem.cpp @@ -77,6 +77,7 @@ uint32_t ESP_getChipId(void) { } // устарела используем новую функцию ниже +#ifndef esp32s2_4mb uint32_t ESP_getFlashChipId(void) { #ifdef ESP32 // Нет аналогичной (без доп.кода) функций в 32 @@ -86,6 +87,7 @@ uint32_t ESP_getFlashChipId(void) { return ESP.getFlashChipId(); #endif } +#endif // https://github.com/espressif/arduino-esp32/issues/6945#issuecomment-1199900892 // получение flash ch id из проекта esp easy diff --git a/src/Main.cpp b/src/Main.cpp index 231053c2..6185235f 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -3,6 +3,9 @@ #include "classes/IoTDB.h" #include "utils/Statistic.h" #include +#ifdef esp32s2_4mb +#include +#endif IoTScenario iotScen; // объект управления сценарием @@ -77,6 +80,9 @@ void stopErrorMarker(int id) { } void setup() { +#ifdef esp32s2_4mb + USB.begin(); +#endif #ifdef esp32_4mb My_timer = timerBegin(0, 80, true); timerAttachInterrupt(My_timer, &onTimer, true); @@ -123,7 +129,7 @@ void setup() { jsonRead(settingsFlashJson, "i2cFreq", i2cFreq, false); jsonRead(settingsFlashJson, "i2c", i2c, false); if (i2c != 0) { -#ifdef esp32_4mb +#ifdef ESP32 Wire.end(); Wire.begin(pinSDA, pinSCL, (uint32_t)i2cFreq); #else diff --git a/src/PeriodicTasks.cpp b/src/PeriodicTasks.cpp index 64675569..9516a369 100644 --- a/src/PeriodicTasks.cpp +++ b/src/PeriodicTasks.cpp @@ -58,7 +58,50 @@ void printGlobalVarSize() { String ESP_getResetReason(void) { return ESP.getResetReason(); } -#else +#endif +#ifdef esp32s2_4mb +String ESP_getResetReason(void) { + return ESP32GetResetReason(0); // CPU 0 +} +String ESP32GetResetReason(uint32_t cpu_no) { + // tools\sdk\include\esp32\rom\rtc.h + switch (rtc_get_reset_reason((RESET_REASON)cpu_no)) { + case POWERON_RESET: + return F("Vbat power on reset"); // 1 + case RTC_SW_SYS_RESET: + return F("Software reset digital core"); // 3 +// case OWDT_RESET: +// return F("Legacy Watchdog reset digital core"); // 4 + case DEEPSLEEP_RESET: + return F("Deep Sleep reset digital core"); // 5 +// case SDIO_RESET: +// return F("Reset by SLC module, reset digital core"); // 6 + case TG0WDT_SYS_RESET: + return F("Timer Group0 Watchdog reset digital core"); // 7 + case TG1WDT_SYS_RESET: + return F("Timer Group1 Watchdog reset digital core"); // 8 + case RTCWDT_SYS_RESET: + return F("RTC Watchdog Reset digital core"); // 9 + case INTRUSION_RESET: + return F("Instrusion tested to reset CPU"); // 10 + case TG0WDT_CPU_RESET: + return F("Time Group reset CPU"); // 11 + case RTC_SW_CPU_RESET: + return F("Software reset CPU"); // 12 + case RTCWDT_CPU_RESET: + return F("RTC Watchdog Reset CPU"); // 13 +// case EXT_CPU_RESET: +// return F("or APP CPU, reseted by PRO CPU"); // 14 + case RTCWDT_BROWN_OUT_RESET: + return F("Reset when the vdd voltage is not stable"); // 15 + case RTCWDT_RTC_RESET: + return F("RTC Watchdog reset digital core and rtc module"); // 16 + default: + return F("NO_MEAN"); // 0 + } +} +#endif +#ifdef esp32_4mb String ESP_getResetReason(void) { return ESP32GetResetReason(0); // CPU 0 } diff --git a/src/UpgradeFirm.cpp b/src/UpgradeFirm.cpp index 2229f9d0..ac0ad9a7 100644 --- a/src/UpgradeFirm.cpp +++ b/src/UpgradeFirm.cpp @@ -78,7 +78,7 @@ bool upgradeBuild() { ESPhttpUpdate.rebootOnUpdate(false); t_httpUpdate_return retBuild = ESPhttpUpdate.update(wifiClient, getBinPath("firmware.bin")); #endif -#ifdef esp32_4mb +#ifdef ESP32 httpUpdate.rebootOnUpdate(false); HTTPUpdateResult retBuild = httpUpdate.update(wifiClient, getBinPath("firmware.bin")); #endif diff --git a/src/modules/API.cpp b/src/modules/API.cpp index 71529d10..643660ee 100644 --- a/src/modules/API.cpp +++ b/src/modules/API.cpp @@ -7,6 +7,7 @@ void* getAPI_Timer(String subtype, String params); void* getAPI_Variable(String subtype, String params); void* getAPI_VariableColor(String subtype, String params); void* getAPI_VButton(String subtype, String params); +void* getAPI_A02Distance(String subtype, String params); void* getAPI_Acs712(String subtype, String params); void* getAPI_AhtXX(String subtype, String params); void* getAPI_AnalogAdc(String subtype, String params); @@ -14,10 +15,13 @@ void* getAPI_Bme280(String subtype, String params); void* getAPI_Bmp280(String subtype, String params); void* getAPI_Dht1122(String subtype, String params); void* getAPI_Ds18b20(String subtype, String params); +void* getAPI_Ds2423(String subtype, String params); void* getAPI_Impulse(String subtype, String params); +void* getAPI_Ntc(String subtype, String params); void* getAPI_Pzem004(String subtype, String params); void* getAPI_RTC(String subtype, String params); void* getAPI_S8(String subtype, String params); +void* getAPI_Scd40(String subtype, String params); void* getAPI_Sht20(String subtype, String params); void* getAPI_Sht30(String subtype, String params); void* getAPI_Sonar(String subtype, String params); @@ -31,7 +35,7 @@ void* getAPI_Mcp23017(String subtype, String params); void* getAPI_Mp3(String subtype, String params); void* getAPI_Multitouch(String subtype, String params); void* getAPI_Pcf8574(String subtype, String params); -void* getAPI_Pwm32(String subtype, String params); +void* getAPI_Pwm8266(String subtype, String params); void* getAPI_TelegramLT(String subtype, String params); void* getAPI_Lcd2004(String subtype, String params); @@ -44,6 +48,7 @@ if ((tmpAPI = getAPI_Timer(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Variable(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_VariableColor(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_VButton(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_A02Distance(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Acs712(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_AhtXX(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_AnalogAdc(subtype, params)) != nullptr) return tmpAPI; @@ -51,10 +56,13 @@ if ((tmpAPI = getAPI_Bme280(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Bmp280(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Dht1122(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Ds18b20(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_Ds2423(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Impulse(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_Ntc(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Pzem004(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_RTC(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_S8(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_Scd40(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Sht20(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Sht30(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Sonar(subtype, params)) != nullptr) return tmpAPI; @@ -68,7 +76,7 @@ if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Multitouch(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Pcf8574(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Pwm32(subtype, params)) != nullptr) return tmpAPI; +if ((tmpAPI = getAPI_Pwm8266(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_TelegramLT(subtype, params)) != nullptr) return tmpAPI; if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI; return nullptr; diff --git a/src/modules/exec/TelegramLT/modinfo.json b/src/modules/exec/TelegramLT/modinfo.json index e718fd62..49c44966 100644 --- a/src/modules/exec/TelegramLT/modinfo.json +++ b/src/modules/exec/TelegramLT/modinfo.json @@ -56,6 +56,7 @@ "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/sensors/A02Distance/modinfo.json b/src/modules/sensors/A02Distance/modinfo.json index 2bee177d..bc6a494a 100644 --- a/src/modules/sensors/A02Distance/modinfo.json +++ b/src/modules/sensors/A02Distance/modinfo.json @@ -15,7 +15,7 @@ ], "about": { "authorName": "Bubnov Mikhail", - "authorContact": "https://t.me/Mitchel", + "authorContact": "https://t.me/Mit4bmw", "authorGit": "https://github.com/Mit4el", "exampleURL": "https://iotmanager.org/wiki", "specialThanks": "", diff --git a/src/modules/sensors/Acs712/modinfo.json b/src/modules/sensors/Acs712/modinfo.json index a3540924..ec03c837 100644 --- a/src/modules/sensors/Acs712/modinfo.json +++ b/src/modules/sensors/Acs712/modinfo.json @@ -21,7 +21,7 @@ ], "about": { "authorName": "Bubnov Mikhail", - "authorContact": "https://t.me/Mitchel", + "authorContact": "https://t.me/Mit4bmw", "authorGit": "https://github.com/Mit4el", "exampleURL": "https://iotmanager.org/wiki", "specialThanks": "", @@ -41,6 +41,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/sensors/Ds2423/Ds2423.cpp b/src/modules/sensors/Ds2423/Ds2423.cpp new file mode 100644 index 00000000..1ec384f7 --- /dev/null +++ b/src/modules/sensors/Ds2423/Ds2423.cpp @@ -0,0 +1,178 @@ + +#include "Global.h" +#include "classes/IoTItem.h" + +#include +#include +#include + +typedef uint8_t DeviceAddressDS2423[8]; +// глобальные списки необходимы для хранения объектов об активных линиях 1-wire используемых разными датчиками из модуля. Ключ - номер пина +std::map oneWireDS2423Array; + +// Функция инициализации библиотечного класса, возвращает Единстрвенный указать на библиотеку +OneWire *instanceOneWire_DS2423(uint8_t ONE_WIRE_PIN) +{ + // учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась + if (oneWireDS2423Array.find(ONE_WIRE_PIN) == oneWireDS2423Array.end()) + oneWireDS2423Array[ONE_WIRE_PIN] = new OneWire((uint8_t)ONE_WIRE_PIN); + return oneWireDS2423Array[ONE_WIRE_PIN]; +} + +// Определяем адрес. +bool getDeviceAddressDS2423(uint8_t pin, uint8_t *deviceAddress, int index) +{ + OneWire *_wire = instanceOneWire_DS2423(pin); + uint8_t depth = 0; + _wire->reset_search(); + while (depth <= index && _wire->search(deviceAddress)) + { + if (depth == index && _wire->crc8((uint8_t *)deviceAddress, 7) == deviceAddress[7]) + return true; + depth++; + } + return false; +} + + +class Ds2423a : public IoTItem +{ +private: + // описание параметров передаваемых из настроек датчика из веба + String _addr; + int _pin; + int _index; + DS2423 *ds2423; + DeviceAddressDS2423 _deviceAddress; + +public: + Ds2423a(String parameters) : IoTItem(parameters) + { + + jsonRead(parameters, "pin", _pin); + jsonRead(parameters, "index", _index, false); + jsonRead(parameters, "addr", _addr, false); + + // Определяем адрес. Если параметр addr не установлен, то узнаем адрес по индексу + if (_addr == "") + { + if (getDeviceAddressDS2423(_pin, _deviceAddress, _index)) + { + char addrStr[20] = ""; + hex2string(_deviceAddress, 8, addrStr); + SerialPrint("I", "Sensor " + (String)_id, "index: " + (String)_index + " addr: " + String(addrStr)); + } + else + { + SerialPrint("E", "Sensor " + (String)_id, "index: " + (String)_index + " addres not search"); + } + } + else + { + string2hex(_addr.c_str(), _deviceAddress); + } + + ds2423 = new DS2423(instanceOneWire_DS2423(_pin), _deviceAddress); + ds2423->begin(DS2423_COUNTER_A | DS2423_COUNTER_B); + + } + + void doByInterval() + { + ds2423->update(); + if (ds2423->isError()) + { + Serial.println("Error reading counter"); + } + else + { + value.valD = ds2423->getCount(DS2423_COUNTER_A); + // if (value.valD != -127) + regEvent(value.valD, "Ds2423a"); // обязательный вызов для отправки результата работы + // else + // SerialPrint("E", "Sensor Ds2423a", "Error"); + } + } + //======================================================================================================= + + ~Ds2423a(){}; +}; + +class Ds2423b : public IoTItem +{ +private: + // описание параметров передаваемых из настроек датчика из веба + String _addr; + int _pin; + int _index; + DS2423 *ds2423; + DeviceAddressDS2423 _deviceAddress; + +public: + Ds2423b(String parameters) : IoTItem(parameters) + { + jsonRead(parameters, "pin", _pin); + jsonRead(parameters, "index", _index, false); + jsonRead(parameters, "addr", _addr, false); + + // Определяем адрес. Если параметр addr не установлен, то узнаем адрес по индексу + if (_addr == "") + { + if (getDeviceAddressDS2423(_pin, _deviceAddress, _index)) + { + char addrStr[20] = ""; + hex2string(_deviceAddress, 8, addrStr); + SerialPrint("I", "Sensor " + (String)_id, "index: " + (String)_index + " addr: " + String(addrStr)); + } + else + { + SerialPrint("E", "Sensor " + (String)_id, "index: " + (String)_index + " addres not search"); + } + } + else + { + string2hex(_addr.c_str(), _deviceAddress); + } + + ds2423 = new DS2423(instanceOneWire_DS2423(_pin), _deviceAddress); + ds2423->begin(DS2423_COUNTER_A | DS2423_COUNTER_B); + } + + void doByInterval() + { + ds2423->update(); + + if (ds2423->isError()) + { + Serial.println("Error reading counter"); + } + else + { + // запускаем опрос измерений у всех датчиков на линии + value.valD = ds2423->getCount(DS2423_COUNTER_B); + // if (value.valD != -127) + regEvent(value.valD, "Ds2423b"); // обязательный вызов для отправки результата работы + // else + // SerialPrint("E", "Sensor Ds2423b", "Error"); + } + } + //======================================================================================================= + + ~Ds2423b(){}; +}; + +void *getAPI_Ds2423(String subtype, String param) +{ + if (subtype == F("Ds2423a")) + { + return new Ds2423a(param); + } + else if (subtype == F("Ds2423b")) + { + return new Ds2423b(param); + } + else + { + return nullptr; + } +} diff --git a/src/modules/sensors/Ds2423/modinfo.json b/src/modules/sensors/Ds2423/modinfo.json new file mode 100644 index 00000000..dffda1dc --- /dev/null +++ b/src/modules/sensors/Ds2423/modinfo.json @@ -0,0 +1,72 @@ +{ + "menuSection": "Сенсоры", + "configItem": [ + { + "global": 0, + "name": "DS2423 счетчик 1", + "type": "Reading", + "subtype": "Ds2423a", + "id": "dscounta", + "widget": "anydataDef", + "page": "Счетчики", + "descr": "DS1 V", + "plus": 0, + "multiply": 1, + "pin": 4, + "index": 0, + "addr": "", + "int": 10, + "round": 0, + "needSave": 0 + }, + { + "global": 0, + "name": "DS2423 счетчик 2", + "type": "Reading", + "subtype": "Ds2423b", + "id": "dscountb", + "widget": "anydataDef", + "page": "Счетчики", + "descr": "DS2 V", + "plus": 0, + "multiply": 1, + "pin": 4, + "index": 0, + "addr": "", + "int": 10, + "round": 0, + "needSave": 0 + } + ], + "about": { + "authorName": "Serghei Crasnicov", + "authorContact": "https://t.me/Serghei63", + "authorGit": "https://github.com/Serghei63", + "specialThanks": "Bubnov Mikhail @Mit4bmw", + "moduleName": "Ds2423", + "moduleVersion": "1.0", + "usedRam": { + "esp32_4mb": 15, + "esp8266_4mb": 15 + }, + "title": "Cчетчик ds2423", + "moduleDesc": "Позволяет получить значения с Ds2423.", + "propInfo": { + "pin": "GPIO номер, к которому подключена шина данных датчиков.", + "index": "Порядковый номер датчика на шине.", + "addr": "Адрес датчика на шине для точной идентификации. Если оставить пустым, то попробует найти по индексу и пину и Можно скопировать из консоли.", + "int": "Количество секунд между опросами датчика." + } + }, + "defActive": true, + "usedLibs": { + "esp32_4mb": [ + "https://github.com/jbechter/arduino-onewire-DS2423", + "paulstoffregen/OneWire @ ^2.3.7" + ], + "esp8266_4mb": [ + "https://github.com/jbechter/arduino-onewire-DS2423", + "paulstoffregen/OneWire @ ^2.3.7" + ] + } +} \ No newline at end of file diff --git a/src/modules/sensors/Ina219/modinfo.json b/src/modules/sensors/Ina219/modinfo.json index 1dc9638f..9bc76dbd 100644 --- a/src/modules/sensors/Ina219/modinfo.json +++ b/src/modules/sensors/Ina219/modinfo.json @@ -88,6 +88,9 @@ "esp32_4mb": [ "https://github.com/adafruit/Adafruit_INA219.git" ], + "esp32s2_4mb": [ + "https://github.com/adafruit/Adafruit_INA219.git" + ], "esp8266_4mb": [ "https://github.com/adafruit/Adafruit_INA219.git" diff --git a/src/modules/sensors/Mhz19/modinfo.json b/src/modules/sensors/Mhz19/modinfo.json index 638fe131..dc2ca89e 100644 --- a/src/modules/sensors/Mhz19/modinfo.json +++ b/src/modules/sensors/Mhz19/modinfo.json @@ -78,6 +78,7 @@ "defActive": false, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": ["plerup/EspSoftwareSerial"], "esp8266_4mb": [] } } \ No newline at end of file diff --git a/src/modules/sensors/Ntc/Ntc.cpp b/src/modules/sensors/Ntc/Ntc.cpp new file mode 100644 index 00000000..09354a66 --- /dev/null +++ b/src/modules/sensors/Ntc/Ntc.cpp @@ -0,0 +1,75 @@ +/****************************************************************** + Simple library for NTC thermistors + https://github.com/GyverLibs/GyverNTC + + adapted for version 4 @Serghei63 + ******************************************************************/ + + +#include "Global.h" +#include "classes/IoTItem.h" + + +class NTCt : public IoTItem { + private: + + unsigned int _pin; + float R1 = 10000.0; // voltage divider resistor value + float Beta = 3950.0; // Beta value + float To = 25.; // Temperature Celsius + float Ro = 10000.0; // Resistance of Thermistor at 25 degree Celsius + float adcMax = 1023.0; + float Vs = 3.3; + public: + NTCt(String parameters): IoTItem(parameters) { + + _pin = jsonReadInt(parameters, "pin"); + R1 = jsonReadInt(parameters, "R1"); // voltage divider resistor value + Beta = jsonReadInt(parameters, "Beta"); // Beta value + To = jsonReadInt(parameters, "T0"); // Temperature degree Celsius + Ro = jsonReadInt(parameters, "R0"); // Resistance of Thermistor at 25 degree Celsius + Vs = jsonReadInt(parameters, "Vs"); // Resistance of Thermistor at 25 degree Celsius + To = To+273.15; + +#if defined ESP8266 + adcMax = 1023.0; +#elif defined ESP32 + adcMax = 4095.0; +#endif + + } + + void doByInterval() { + + float Vout, Rt = 0; + float T = 0; + float adc = 0; + for (int i = 0; i < 10; i++) + { + adc += IoTgpio.analogRead(_pin); + } + adc /= 10; + + Vout = adc * Vs/adcMax; + Rt = R1 * Vout / (Vs - Vout); + T = 1/(1/To + log(Rt/Ro)/Beta); // Temperature in Kelvin + value.valD = T - 273.15; // Celsius + + SerialPrint("i", F("Ntc"), "adc = " + String(adc)+ " ,Vout = " + String(Vout)+ " ,T = " + String(value.valD)); + if (String(value.valD) != "nan") regEvent(value.valD, "Ntc"); + else + SerialPrint("E", "Ntc", "Error"); + } + + ~NTCt() {}; +}; + +void* getAPI_Ntc(String subtype, String param) { + if (subtype == F("Ntc")) { + + return new NTCt(param); + + } else { + return nullptr; + } +} diff --git a/src/modules/sensors/Ntc/modinfo.json b/src/modules/sensors/Ntc/modinfo.json new file mode 100644 index 00000000..7780d2a8 --- /dev/null +++ b/src/modules/sensors/Ntc/modinfo.json @@ -0,0 +1,65 @@ +{ + "menuSection": "Сенсоры", + "configItem": [ + { + "global": 0, + "name": "Cенсор температуры NTC", + "type": "Reading", + "subtype": "Ntc", + "id": "Ntctmp", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "NTC Температура", + "needSave": 0, + "val": "0", + "int": 15, + "pin": "35", + "R1":"10000", + "R0":"10000", + "Beta":"3950.0", + "T0":"25", + "Vs":"3.3", + "round" : 1 + + } + + + ], + "about": { + "authorName": "Serghei Crasnicov", + "authorContact": "https://t.me/Serghei63", + "authorGit": "https://github.com/Serghei63", + "specialThanks": "https://t.me/Mit4bmw", + "moduleName": "Ntc", + "moduleVersion": "1.1", + "usedRam": { + "esp32_4mb": 15, + "esp8266_4mb": 15 + }, + "subTypes": [ + "Ntc" + ], + "title": "Модуль датчика Ntc", + "moduleDesc": "", + "retInfo": "", + "propInfo": { + "pin": "Аналоговый пин (для esp8266 = 0, для esp32 алаоговый gpio, например 35)", + "R1":"Сопротивление подтягивающего резистора, должен быть равен сопротивлению термистера", + "Vs":"Напряжение питания датчика, Для точности измерить и ввести своё, по умолчанию 3.3В", + "R0":"Сопротивление термистора при температуре То, например 10 КОм при 25С", + "T0":"Базовая температура, температура измерения сопротивление термистора (Rterm), обычно 25С", + "Beta":"Beta термистора" + } + }, + "defActive": true, + "usedLibs": { + "esp32_4mb": [], + "esp8266_4mb": [], + "esp8266_1mb": [], + "esp8266_1mb_ota": [], + "esp8285_1mb": [], + "esp8285_1mb_ota": [], + "esp8266_2mb": [], + "esp8266_2mb_ota": [] + } +} diff --git a/src/modules/sensors/Scd40/Scd40.cpp b/src/modules/sensors/Scd40/Scd40.cpp new file mode 100644 index 00000000..eb93da2c --- /dev/null +++ b/src/modules/sensors/Scd40/Scd40.cpp @@ -0,0 +1,432 @@ +#include "Global.h" +#include "classes/IoTItem.h" + +#include +#include + +#include + +// SensirionI2CScd4x scd4x; + +SensirionI2CScd4x *scd4x = nullptr; // create an object of the CSD40 class +char errorMessageScd4x[256]; +uint16_t errorCodeScd4x; + +void printUint16Hex(uint16_t value) +{ + Serial.print(value < 4096 ? "0" : ""); + Serial.print(value < 256 ? "0" : ""); + Serial.print(value < 16 ? "0" : ""); + Serial.print(value, HEX); +} + +void printSerialNumber(uint16_t serial0, uint16_t serial1, uint16_t serial2) +{ + Serial.print("Serial: 0x"); + printUint16Hex(serial0); + printUint16Hex(serial1); + printUint16Hex(serial2); + Serial.println(); +} + +// Функция инициализации библиотечного класса, возвращает Единстрвенный указать на библиотеку +SensirionI2CScd4x *instance() +{ + if (!scd4x) + { // Если библиотека ранее инициализировалась, т о просто вернем указатель + // Инициализируем библиотеку + scd4x = new SensirionI2CScd4x(); + Wire.begin(); + scd4x->begin(Wire); + + //Останавливаем периодический опрос датчика вбиблиотеке для запроса Сер.номера (на всякий случай) + // stop potentially previously started measurement + errorCodeScd4x = instance()->stopPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + Serial.println(errorMessageScd4x); + } + + //Запрашиваем и выводим серийный номер датчика + uint16_t serial0; + uint16_t serial1; + uint16_t serial2; + errorCodeScd4x = instance()->getSerialNumber(serial0, serial1, serial2); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute getSerialNumber(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else + { + printSerialNumber(serial0, serial1, serial2); + } + + //Обратно стартуем периодический опрос датчика библиотекой (по описанию библиотеки каждые 5сек) + // Start Measurement + errorCodeScd4x = instance()->startPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute startPeriodicMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + + Serial.println("Waiting for first measurement... "); + } + return scd4x; +} + +class Scd40co2 : public IoTItem +{ +private: +bool lowPeriodic = true; +bool autoCalibration = true; +//int targetCo2 = 0; +public: + Scd40co2(String parameters) : IoTItem(parameters) + { + jsonRead(parameters, F("lowPeriodic"), lowPeriodic); + jsonRead(parameters, F("autoCalibration"), autoCalibration); + // jsonRead(parameters, F("targetCo2"), targetCo2); + settingParameters(); + } + + void doByInterval() + { + // Read Measurement + uint16_t co2 = 0; + float temperature = 0.0f; + float humidity = 0.0f; + bool isDataReady = false; + //Запрашиваем библиотеку о готовности отправить запрос + errorCodeScd4x = instance()->getDataReadyFlag(isDataReady); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute getDataReadyFlag(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + return; + } + if (!isDataReady) + { + return; + } + //Если все нормально забираем у библиотеки данные + errorCodeScd4x = instance()->readMeasurement(co2, temperature, humidity); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute readMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else if (co2 == 0) + { + Serial.println("Invalid sample detected, skipping."); + } + else + { + Serial.print("Co2:"); + Serial.print(co2); + Serial.print("\t"); + // Serial.print("Temperature:"); + // Serial.print(temperature); + // Serial.print("\t"); + // Serial.print("Humidity:"); + // Serial.println(humidity); + } + // value.valD = scd4x.readMeasurement(temperature); + value.valD = co2; + if (value.valD < 5000) + regEvent(value.valD, "Scd40co2"); + else + SerialPrint("E", "Sensor Scd40co2", "Error", _id); + } + + //Хук для обработки кнопки + void onModuleOrder(String &key, String &value) + { + if (key == "Recalibration")//название кнопки btn-Recalibration + { + SerialPrint("i", F("Sensor Scd40co2"), "User run calibration, targetCo2: " + value); + Recalibration(value.toInt()); + } + } + void Recalibration(int targetCo2) + { + //Останавливаем периодический опрос датчика вбиблиотеке для запроса Сер.номера (на всякий случай) + // stop potentially previously started measurement + errorCodeScd4x = instance()->stopPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + Serial.println(errorMessageScd4x); + } + delay(500); // Из описания performForcedRecalibration 2. Stop periodic measurement. Wait 500 ms. + uint16_t frcCorrection; + errorCodeScd4x = instance()->performForcedRecalibration(targetCo2, frcCorrection); + + if (errorCodeScd4x) + { + Serial.print("Error trying to execute performForcedRecalibration(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else + { + Serial.println("performForcedRecalibration(): OK!"); + SerialPrint("i", F("Sensor Scd40co2"), "Calibration is OK, frcCorrection: " + String(frcCorrection)); + } + + //Обратно стартуем периодический опрос датчика библиотекой (по описанию библиотеки каждые 5сек) + // Start Measurement + errorCodeScd4x = instance()->startPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute startPeriodicMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + + Serial.println("Waiting for first measurement... "); + } + + void settingParameters() + { + //Останавливаем периодический опрос датчика вбиблиотеке для запроса Сер.номера (на всякий случай) + // stop potentially previously started measurement + errorCodeScd4x = instance()->stopPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + Serial.println(errorMessageScd4x); + } + + errorCodeScd4x = instance()->startLowPowerPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute startLowPowerPeriodicMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else + { + Serial.println("startLowPowerPeriodicMeasurement(): OK!"); + } + + errorCodeScd4x = instance()->setAutomaticSelfCalibration((uint16_t)autoCalibration); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute setAutomaticSelfCalibration(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else + { + Serial.println("setAutomaticSelfCalibration(): OK!"); + } + + //Обратно стартуем периодический опрос датчика библиотекой (по описанию библиотеки каждые 5сек) + // Start Measurement + errorCodeScd4x = instance()->startPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute startPeriodicMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + + Serial.println("Waiting for first measurement... "); + } + + ~Scd40co2(){}; +}; + +class Scd40t : public IoTItem +{ +private: + int offsetT; +public: + Scd40t(String parameters) : IoTItem(parameters) + { + jsonRead(parameters, F("offset"), offsetT); + setTemperatureOffset(); + } + + void doByInterval() + { + // Read Measurement + uint16_t co2 = 0; + float temperature = 0.0f; + float humidity = 0.0f; + bool isDataReady = false; + errorCodeScd4x = instance()->getDataReadyFlag(isDataReady); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute getDataReadyFlag(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + return; + } + if (!isDataReady) + { + return; + } + errorCodeScd4x = instance()->readMeasurement(co2, temperature, humidity); + if (errorCodeScd4x) + { + Serial.print("errorCodeScd4x trying to execute readMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else if (co2 == 0) + { + Serial.println("Invalid sample detected, skipping."); + } + else + { + // Serial.print("Co2:"); + // Serial.print(co2); + // Serial.print("\t"); + Serial.print("Temperature:"); + Serial.print(temperature); + Serial.print("\t"); + // Serial.print("Humidity:"); + // Serial.println(humidity); + } + // value.valD = scd4x.readMeasurement(temperature); + value.valD = temperature; + if (value.valD < 124) + regEvent(value.valD, "Scd40t"); + else + SerialPrint("E", "Sensor Scd40t", "Error", _id); + } + + void setTemperatureOffset() + { + //Останавливаем периодический опрос датчика вбиблиотеке для запроса Сер.номера (на всякий случай) + // stop potentially previously started measurement + errorCodeScd4x = instance()->stopPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute stopPeriodicMeasurement(): "); + Serial.println(errorMessageScd4x); + } + + errorCodeScd4x = instance()->setTemperatureOffset((uint16_t)offsetT); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute setTemperatureOffset(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else + { + Serial.println("setTemperatureOffset(): OK!"); + } + + //Обратно стартуем периодический опрос датчика библиотекой (по описанию библиотеки каждые 5сек) + // Start Measurement + errorCodeScd4x = instance()->startPeriodicMeasurement(); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute startPeriodicMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + + Serial.println("Waiting for first measurement... "); + } + + ~Scd40t(){}; +}; + +class Scd40h : public IoTItem +{ +public: + Scd40h(String parameters) : IoTItem(parameters) + { + } + + void doByInterval() + { + // Read Measurement + uint16_t co2 = 0; + float temperature = 0.0f; + float humidity = 0.0f; + bool isDataReady = false; + errorCodeScd4x = instance()->getDataReadyFlag(isDataReady); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute getDataReadyFlag(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + return; + } + if (!isDataReady) + { + return; + } + errorCodeScd4x = instance()->readMeasurement(co2, temperature, humidity); + if (errorCodeScd4x) + { + Serial.print("Error trying to execute readMeasurement(): "); + errorToString(errorCodeScd4x, errorMessageScd4x, 256); + Serial.println(errorMessageScd4x); + } + else if (co2 == 0) + { + Serial.println("Invalid sample detected, skipping."); + } + else + { + // Serial.print("Co2:"); + // Serial.print(co2); + // Serial.print("\t"); + // Serial.print("Temperature:"); + // Serial.print(temperature); + // Serial.print("\t"); + Serial.print("Humidity:"); + Serial.println(humidity); + Serial.print("\t"); + } + // value.valD = scd4x.readMeasurement(temperature); + value.valD = humidity; + if (value.valD < 100) + regEvent(value.valD, "Scd40h"); + else + SerialPrint("E", "Sensor Scd40h", "Error", _id); + } + + ~Scd40h(){}; +}; + +void *getAPI_Scd40(String subtype, String param) +{ + + if (subtype == F("Scd40co2")) + { + // hdc1080.begin(0x40); + // scd4x->begin(Wire); + // scd4x.begin(Wire); + return new Scd40co2(param); + } + else if (subtype == F("Scd40t")) + { + // hdc1080.begin(0x40); + // scd4x->begin(Wire); + return new Scd40t(param); + } + else if (subtype == F("Scd40h")) + { + // hdc1080.begin(0x40); + // scd4x->begin(Wire); + return new Scd40h(param); + // } else { + // return nullptr; + } + + return nullptr; +} \ No newline at end of file diff --git a/src/modules/sensors/Scd40/modinfo.json b/src/modules/sensors/Scd40/modinfo.json new file mode 100644 index 00000000..aa365419 --- /dev/null +++ b/src/modules/sensors/Scd40/modinfo.json @@ -0,0 +1,84 @@ +{ + "menuSection": "Сенсоры", + "configItem": [ + { + "global": 0, + "name": "SCD40 Углекислый газ", + "type": "Reading", + "subtype": "Scd40co2", + "id": "Scd40co2", + "widget": "anydataPpm", + "page": "Сенсоры", + "descr": "SCD40 Углекислый газ", + "int": 15, + "round": 0, + "lowPeriodic": 1, + "autoCalibration": 1, + "btn-Recalibration": 0 + }, + { + "global": 0, + "name": "SCD40 Влажность", + "type": "Reading", + "subtype": "Scd40h", + "id": "Scd40h", + "widget": "anydataHum", + "page": "Сенсоры", + "descr": "SCD40 Влажность", + "int": 15, + "round": 1 + }, + { + "global": 0, + "name": "SCD40 Температура", + "type": "Reading", + "subtype": "Scd40t", + "id": "Scd40t", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "SCD40 Температура", + "int": 15, + "round": 1, + "offset": 4 + } + ], + "about": { + "authorName": "Serghei Crasnicov", + "authorContact": "https://t.me/Serghei63", + "authorGit": "https://github.com/Serghei63", + "specialThanks": "Bubnov Mikhail @Mit4bmw", + "moduleName": "Scd40", + "moduleVersion": "0.0", + "usedRam": { + "esp32_4mb": 15, + "esp8266_4mb": 15 + }, + "subTypes": [ + "Scd40co2", + "Scd40t", + "Scd40h" + ], + "title": "Датчик температуры и влажности Scd40", + "moduleDesc": "Позволяет получить значения температуры и влажности с Scd40.", + "propInfo": { + + "int": "Количество секунд между опросами библиотеки (датчик опрашивается библиотекой по своему таймеру, см. lowPeriodic).", + "offset": "Смещение температуры представляет собой разницу между температурой, измеренной SCD4x, и фактической температурой окружающей среды температура. По умолчанию смещение температуры в библиотеке/датчике установлено на 4°C.", + "lowPeriodic": "Медленные режим опроса датчика библиотекой. 0-каждые 5сек, 1-каждые 30сек", + "autoCalibration": "Автоматическая калибровка, по умолчанию включена AutomaticSelfCalibration, 0 - выключена", + "btn-Recalibration": "Кнопка принудительной калибровки. В поле указать Целевая концентрация CO₂ в миллионных долях. Перед калибровкой необходимо находтся в течение > 3 минут в среде с однородной и постоянной концентрацией CO₂. Выдает в лог Значение коррекции FRC в co₂ ppm" + + } + }, + "defActive": true, + "usedLibs": { + "esp32_4mb": [ + "Sensirion I2C SCD4x @0.4.0", + "Sensirion Core @0.6.0" + ], + "esp8266_4mb": [ + "Sensirion I2C SCD4x @0.4.0", + "Sensirion Core @0.6.0" + ] + } +} \ No newline at end of file diff --git a/src/modules/virtual/Cron/modinfo.json b/src/modules/virtual/Cron/modinfo.json index 2320e3e2..f6a3f89f 100644 --- a/src/modules/virtual/Cron/modinfo.json +++ b/src/modules/virtual/Cron/modinfo.json @@ -50,6 +50,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/GoogleSheet/GoogleSheet.cpp b/src/modules/virtual/GoogleSheet/GoogleSheet.cpp new file mode 100644 index 00000000..39b9d74a --- /dev/null +++ b/src/modules/virtual/GoogleSheet/GoogleSheet.cpp @@ -0,0 +1,92 @@ + +#include "Global.h" +#include "classes/IoTItem.h" + +String URL = "https://script.google.com/macros/s/"; + + +class GoogleSheet : public IoTItem +{ +private: + String id; + String logid; + String scid = ""; + String shname = ""; + bool init = false; + int interval = 1; + // long interval; +public: + GoogleSheet(String parameters) : IoTItem(parameters) + { + jsonRead(parameters, F("id"), id); + jsonRead(parameters, F("logid"), logid); + jsonRead(parameters, F("scid"), scid); + jsonRead(parameters, F("shname"), shname); + jsonRead(parameters, F("int"), interval); + interval = interval * 1000 * 60; // так как у нас в минутах + } + + void doByInterval() + { + if (WiFi.status() == WL_CONNECTED) + { + String value = getItemValue(logid); + String urlFinal = URL + scid + "/exec?"+"sheet=" + shname + "&id=" + logid + "&value=" + value; + if (!init){ init=true; urlFinal = urlFinal + "&init=1";} + + HTTPClient http; +#if defined ESP8266 + WiFiClientSecure client; + client.setInsecure(); + if (!http.begin(client, urlFinal)) + { +#elif defined ESP32 + WiFiClient client; + if (!http.begin(urlFinal)) + { +#endif + SerialPrint("I", F("GoogleSheet"), "connection failed "); + } + http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // HTTPC_STRICT_FOLLOW_REDIRECTS HTTPC_FORCE_FOLLOW_REDIRECTS + http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + int httpCode = http.GET(); +// String payload = http.getString(); + SerialPrint("<-", F("GoogleSheet"), "URL: " + urlFinal); + SerialPrint("->", F("GoogleSheet"), "server: " + (String)httpCode); /*"URL: " + urlFinal + */ +/* if (httpCode > 0) + { + SerialPrint("->", F("GoogleSheet"), "msg from server: " + (String)payload.c_str()); + } +*/ + http.end(); + } + } + + void loop() + { + if (enableDoByInt) + { + currentMillis = millis(); + difference = currentMillis - prevMillis; + if (difference >= interval) + { + prevMillis = millis(); + this->doByInterval(); + } + } + } + ~GoogleSheet(){}; +}; + +void *getAPI_GoogleSheet(String subtype, String param) +{ + + if (subtype == F("GoogleSheet")) + { + return new GoogleSheet(param); + } + else + { + return nullptr; + } +} diff --git a/src/modules/virtual/GoogleSheet/modinfo.json b/src/modules/virtual/GoogleSheet/modinfo.json new file mode 100644 index 00000000..efcb94dc --- /dev/null +++ b/src/modules/virtual/GoogleSheet/modinfo.json @@ -0,0 +1,45 @@ +{ + "menuSection": "Виртуальные элементы", + "configItem": [ + { + "global": 0, + "name": "GoogleSheet", + "type": "Reading", + "subtype": "GoogleSheet", + "id": "sheet", + "widget": "nil", + "page": "", + "descr": "", + "int": 5, + "logid": "id", + "scid": "Script_ID", + "shname": "Logger" + } + ], + "about": { + "authorName": "Bubnov Mikhail", + "authorContact": "https://t.me/Mit4bmw", + "authorGit": "https://github.com/Mit4el", + "exampleURL": "https://iotmanager.org/wiki", + "specialThanks": "", + "moduleName": "GoogleSheet", + "moduleVersion": "1.0", + "usedRam": { + "esp32_4mb": 10, + "esp8266_4mb": 10 + }, + "title": "Логирование в Google таблицы", + "moduleDesc": "Расширение позволяющее логировать любую величину в Google таблицы. Инструкция https://drive.google.com/file/d/1VuI06arObNfH3rsOSHKww1tyhfgqXd9F/view?usp=sharing", + "propInfo": { + "int": "Интервал логирования в минутах", + "logid": "ID величины которую будем логировать", + "scid": "Идентификатор развертывания Google Apps (script id)", + "shname": "Наименование листа в таблице (sheet name)" + } + }, + "defActive": false, + "usedLibs": { + "esp32_4mb": [], + "esp32s2_4mb": [] + } +} \ No newline at end of file diff --git a/src/modules/virtual/Loging/modinfo.json b/src/modules/virtual/Loging/modinfo.json index 8fbdcbe3..e39018e3 100644 --- a/src/modules/virtual/Loging/modinfo.json +++ b/src/modules/virtual/Loging/modinfo.json @@ -51,6 +51,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/LogingDaily/modinfo.json b/src/modules/virtual/LogingDaily/modinfo.json index 8118c82a..9c17af4b 100644 --- a/src/modules/virtual/LogingDaily/modinfo.json +++ b/src/modules/virtual/LogingDaily/modinfo.json @@ -44,6 +44,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/Timer/modinfo.json b/src/modules/virtual/Timer/modinfo.json index def3437c..be4abb02 100644 --- a/src/modules/virtual/Timer/modinfo.json +++ b/src/modules/virtual/Timer/modinfo.json @@ -70,6 +70,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/VButton/modinfo.json b/src/modules/virtual/VButton/modinfo.json index 36e5fabf..ab78d4d0 100644 --- a/src/modules/virtual/VButton/modinfo.json +++ b/src/modules/virtual/VButton/modinfo.json @@ -36,6 +36,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/Variable/modinfo.json b/src/modules/virtual/Variable/modinfo.json index 2a50d1c2..feb0370a 100644 --- a/src/modules/virtual/Variable/modinfo.json +++ b/src/modules/virtual/Variable/modinfo.json @@ -96,6 +96,7 @@ "defActive": true, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/VariableColor/modinfo.json b/src/modules/virtual/VariableColor/modinfo.json index e03c1ff9..59fd429b 100644 --- a/src/modules/virtual/VariableColor/modinfo.json +++ b/src/modules/virtual/VariableColor/modinfo.json @@ -37,6 +37,7 @@ "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/Weather/modinfo.json b/src/modules/virtual/Weather/modinfo.json index cbdad91f..9b315192 100644 --- a/src/modules/virtual/Weather/modinfo.json +++ b/src/modules/virtual/Weather/modinfo.json @@ -44,6 +44,7 @@ "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [],