From d22580aac92afef105a3feceb786d3c005ef025a Mon Sep 17 00:00:00 2001 From: Dmitry Borisenko <49808844+DmitryBorisenko33@users.noreply.github.com> Date: Fri, 12 Aug 2022 22:13:50 +0200 Subject: [PATCH] =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D1=87=D0=B0=D1=81=D0=BE=D0=B2=20=D1=80=D0=B5=D0=B0?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=B2=D1=80=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/classes/IoTItem.h | 3 +- include/classes/IoTRTC.h | 22 ---- src/ESPConfiguration.cpp | 22 +--- src/Main.cpp | 41 +------ src/classes/IoTItem.cpp | 4 +- src/classes/IoTRTC.cpp | 46 -------- src/modules/API.cpp | 54 +++++---- src/modules/exec/IarduinoRTC/IarduinoRTC.cpp | 112 ------------------- src/modules/exec/IarduinoRTC/modinfo.json | 47 -------- src/modules/exec/Mcp23017/Mcp23017.cpp | 19 ++-- src/modules/exec/SysExt/SysExt.cpp | 106 +++++++++--------- src/modules/sensors/AnalogAdc/AnalogAdc.cpp | 9 +- src/modules/virtual/Logging/Logging.cpp | 0 src/utils/SerialPrint.cpp | 7 +- training/IarduinoRTC.cpp | 106 ++++++++++++++++++ training/IoTRTC.cpp | 45 ++++++++ training/IoTRTC.h | 22 ++++ 17 files changed, 278 insertions(+), 387 deletions(-) delete mode 100644 include/classes/IoTRTC.h delete mode 100644 src/classes/IoTRTC.cpp delete mode 100644 src/modules/exec/IarduinoRTC/IarduinoRTC.cpp delete mode 100644 src/modules/exec/IarduinoRTC/modinfo.json create mode 100644 src/modules/virtual/Logging/Logging.cpp create mode 100644 training/IarduinoRTC.cpp create mode 100644 training/IoTRTC.cpp create mode 100644 training/IoTRTC.h diff --git a/include/classes/IoTItem.h b/include/classes/IoTItem.h index eb1d4154..4991e44f 100644 --- a/include/classes/IoTItem.h +++ b/include/classes/IoTItem.h @@ -41,7 +41,8 @@ class IoTItem { bool needSave = false; bool enableDoByInt = true; - virtual IoTGpio* getGpioDriver(); + virtual bool isGpioDriver(); + virtual iarduino_RTC_BASE* getRtcDriver(); virtual void setValue(IoTValue Value); virtual void setValue(String valStr); diff --git a/include/classes/IoTRTC.h b/include/classes/IoTRTC.h deleted file mode 100644 index b2163aaf..00000000 --- a/include/classes/IoTRTC.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include -#include - -class iarduino_RTC_NTP: public iarduino_RTC_BASE { - public: - iarduino_RTC_NTP(); - ~iarduino_RTC_NTP(); - void begin(void); - uint8_t funcReadTimeIndex(uint8_t i); - void funcWriteTimeIndex(uint8_t i, uint8_t j); - uint8_t funcConvertNumToCode (uint8_t i) {return ((i/10) << 4) + (i%10);} -}; - -class IoTRTC : public iarduino_RTC { - public: - IoTRTC(uint8_t i, uint8_t j=SS, uint8_t k=SCK, uint8_t n=MOSI) : iarduino_RTC(i, j, k, n) { - if (i == 0) objClass = new iarduino_RTC_NTP(); - }; - - ~IoTRTC(); -}; \ No newline at end of file diff --git a/src/ESPConfiguration.cpp b/src/ESPConfiguration.cpp index 2c767798..9c05b39a 100644 --- a/src/ESPConfiguration.cpp +++ b/src/ESPConfiguration.cpp @@ -1,9 +1,7 @@ #include "ESPConfiguration.h" #include "classes/IoTGpio.h" -#include "classes/IoTRTC.h" extern IoTGpio IoTgpio; -extern IoTRTC *watch; std::list IoTItems; void* getAPI(String subtype, String params); @@ -25,24 +23,12 @@ void configure(String path) { SerialPrint(F("E"), F("Config"), "json error " + subtype); continue; } else { + //(IoTItem*) - getAPI вернула ссылку, что бы ее привести к классу IoTItem используем myIoTItem = (IoTItem*)getAPI(subtype, jsonArrayElement); if (myIoTItem) { // пробуем спросить драйвер GPIO - IoTGpio* gpiotmp = myIoTItem->getGpioDriver(); - if (gpiotmp) IoTgpio.regDriver(gpiotmp); - - // пробуем спросить драйвер RTC - iarduino_RTC_BASE* rtctmp = myIoTItem->getRtcDriver(); - if (rtctmp) { - Serial.println("Start delete watch objClass"); - delete watch->objClass; - watch->objClass = rtctmp; - int valPeriod_save = watch->valPeriod; - watch->valPeriod = 0; - watch->gettime(); - watch->valPeriod = valPeriod_save; - } - + if (myIoTItem->isGpioDriver()) IoTgpio.regDriver((IoTGpio*)myIoTItem); + IoTItems.push_back(myIoTItem); } } @@ -54,7 +40,7 @@ void configure(String path) { void clearConfigure() { Serial.printf("Start clearing config\n"); - for (std::list::iterator it=IoTItems.begin(); it != IoTItems.end(); ++it) { + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { Serial.printf("Start delete iotitem %s \n", (*it)->getID().c_str()); if (*it) delete *it; } diff --git a/src/Main.cpp b/src/Main.cpp index 01b5d131..a93353a6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1,12 +1,8 @@ #include "Main.h" -#include "classes/IoTRTC.h" #include IoTScenario iotScen; // объект управления сценарием -IoTRTC *watch; // объект хранения времени, при старте часы 00:00 -time_t iotTimeNow; - String volStrForSave = ""; unsigned long currentMillis; unsigned long prevMillis; @@ -32,29 +28,6 @@ void setup() { //подключаемся к роутеру routerConnect(); - // настраиваем получение времени из сети Интернет - String ntpServer = jsonReadStr(settingsFlashJson, F("ntp")); - int timezone = jsonReadInt(settingsFlashJson, F("timezone")); - configTime(3600*timezone, 0, ntpServer.c_str(), "ru.pool.ntp.org", "pool.ntp.org"); - Serial.println("Start syncing NTP time"); - time(&iotTimeNow); - // int i = 0; - // while (isNetworkActive() && iotTimeNow < 1510592825 && i < 200) - // { - // time(&iotTimeNow); - // delay(300); - // Serial.print("."); - // i++; - // } - // Serial.println(); - - // настраиваем локальный RTC - watch = new IoTRTC(0); // создаем объект главного хранилища времени, но с заглушкой (0) для получения системного времени - watch->period(60); // время в минутах для синхронизации с часами реального времени или системным - watch->begin(); - //Serial.print(F("Time from Local: ")); - //Serial.println(watch->gettime("d-m-Y, H:i:s, M")); - //инициализация асинхронного веб сервера и веб сокетов #ifdef ASYNC_WEB_SERVER asyncWebServerInit(); @@ -89,7 +62,7 @@ void setup() { //загрузка сценария iotScen.loadScenario("/scenario.txt"); // создаем событие завершения конфигурирования для возможности выполнения блока кода при загрузке - IoTItems.push_back((IoTItem*)new externalVariable("{\"id\":\"onStart\",\"val\":1,\"int\":60}")); + IoTItems.push_back((IoTItem *)new externalVariable("{\"id\":\"onStart\",\"val\":1,\"int\":60}")); generateEvent("onStart", ""); // test @@ -122,8 +95,7 @@ void loop() { // Serial.println(watch->gettime("d-m-Y, H:i:s, M")); // delay(1); // } - - + //обновление задач таскера ts.update(); @@ -146,7 +118,7 @@ void loop() { mqttLoop(); // передаем управление каждому элементу конфигурации для выполнения своих функций - for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { (*it)->loop(); if ((*it)->iAmDead) { delete *it; @@ -164,7 +136,7 @@ void loop() { if (currentMillis - prevMillis >= 1000) { prevMillis = millis(); volStrForSave = ""; - for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) { if ((*it)->needSave) { (*it)->needSave = false; volStrForSave = volStrForSave + (*it)->getID() + "=" + (*it)->getValue() + ";"; @@ -173,10 +145,7 @@ void loop() { if (volStrForSave != "") { Serial.print("volStrForSave: "); - Serial.println(volStrForSave.c_str()); + Serial.println(volStrForSave.c_str()); } } - - - } diff --git a/src/classes/IoTItem.cpp b/src/classes/IoTItem.cpp index e44324e8..ad92c38f 100644 --- a/src/classes/IoTItem.cpp +++ b/src/classes/IoTItem.cpp @@ -128,8 +128,8 @@ void IoTItem::setInterval(unsigned long interval) { _interval = interval; } -IoTGpio* IoTItem::getGpioDriver() { - return nullptr; +bool IoTItem::isGpioDriver() { + return false; } iarduino_RTC_BASE* IoTItem::getRtcDriver() { diff --git a/src/classes/IoTRTC.cpp b/src/classes/IoTRTC.cpp deleted file mode 100644 index 94b6c741..00000000 --- a/src/classes/IoTRTC.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "classes/IoTRTC.h" - -IoTRTC::~IoTRTC() { - -} - - -iarduino_RTC_NTP::iarduino_RTC_NTP() { - -} - -void iarduino_RTC_NTP::begin(void) { - -} - -uint8_t iarduino_RTC_NTP::funcReadTimeIndex(uint8_t i) { - static tm localTimeVar; - if (i == 0) { - Serial.println(F("Read time from system.")); - time_t timeNowVar; - time(&timeNowVar); - localTimeVar = *localtime(&timeNowVar); - } - - switch (i) - { - case 0: return funcConvertNumToCode(localTimeVar.tm_sec); - case 1: return funcConvertNumToCode(localTimeVar.tm_min); - case 2: return funcConvertNumToCode(localTimeVar.tm_hour); - case 3: return funcConvertNumToCode(localTimeVar.tm_mday); - case 4: return funcConvertNumToCode(localTimeVar.tm_mon+1); - case 5: return funcConvertNumToCode(localTimeVar.tm_year-100); - case 6: return funcConvertNumToCode(localTimeVar.tm_wday); - } - - return 0; -} - -void iarduino_RTC_NTP::funcWriteTimeIndex(uint8_t i, uint8_t j) { - -} - -iarduino_RTC_NTP::~iarduino_RTC_NTP() { - -} - diff --git a/src/modules/API.cpp b/src/modules/API.cpp index db2bda52..0c251dcf 100644 --- a/src/modules/API.cpp +++ b/src/modules/API.cpp @@ -18,7 +18,6 @@ void* getAPI_Sht30(String subtype, String params); void* getAPI_Sonar(String subtype, String params); void* getAPI_ButtonIn(String subtype, String params); void* getAPI_ButtonOut(String subtype, String params); -void* getAPI_IarduinoRTC(String subtype, String params); void* getAPI_IoTServo(String subtype, String params); void* getAPI_Mcp23017(String subtype, String params); void* getAPI_Mp3(String subtype, String params); @@ -27,31 +26,30 @@ void* getAPI_SysExt(String subtype, String params); void* getAPI_Lcd2004(String subtype, String params); void* getAPI(String subtype, String params) { -void* tmpAPI; -if ((tmpAPI = getAPI_Timer(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Variable(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_VButton(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Aht20(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_AnalogAdc(subtype, params)) != nullptr) return tmpAPI; -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_GY21(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Hdc1080(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Max6675(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_RCswitch(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; -if ((tmpAPI = getAPI_ButtonIn(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_ButtonOut(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_IarduinoRTC(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_IoTServo(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Pwm8266(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_SysExt(subtype, params)) != nullptr) return tmpAPI; -if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI; -return nullptr; + void* tmpAPI; + if ((tmpAPI = getAPI_Timer(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Variable(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_VButton(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Aht20(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_AnalogAdc(subtype, params)) != nullptr) return tmpAPI; + 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_GY21(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Hdc1080(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Max6675(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_RCswitch(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; + if ((tmpAPI = getAPI_ButtonIn(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_ButtonOut(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_IoTServo(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Mcp23017(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Mp3(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Pwm8266(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_SysExt(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Lcd2004(subtype, params)) != nullptr) return tmpAPI; + return nullptr; } \ No newline at end of file diff --git a/src/modules/exec/IarduinoRTC/IarduinoRTC.cpp b/src/modules/exec/IarduinoRTC/IarduinoRTC.cpp deleted file mode 100644 index b2cbb936..00000000 --- a/src/modules/exec/IarduinoRTC/IarduinoRTC.cpp +++ /dev/null @@ -1,112 +0,0 @@ -#include "Global.h" -#include "classes/IoTItem.h" -#include "classes/IoTRTC.h" - -#include -#include "iarduino_RTC_DS1302.h" // Подключаем файл iarduino_RTC_DS1302.h -#include "iarduino_RTC_DS1307.h" // Подключаем файл iarduino_RTC_DS1307.h -#include "iarduino_RTC_DS3231.h" // Подключаем файл iarduino_RTC_DS3231.h -#include "iarduino_RTC_RX8025.h" - -extern IoTRTC *watch; - - -class IarduinoRTC : public IoTItem { - private: - int _chipNum, _rst, _clk, _dat, _ticker; - String _defFormat; - iarduino_RTC_BASE *RTCDriver; - - public: - - IarduinoRTC(String parameters): IoTItem(parameters) { - jsonRead(parameters, "chipNum", _chipNum); - jsonRead(parameters, "rst", _rst); - jsonRead(parameters, "clk", _clk); - jsonRead(parameters, "dat", _dat); - jsonRead(parameters, "defFormat", _defFormat); - jsonRead(parameters, "ticker", _ticker); - - switch (_chipNum) { - case 0: - RTCDriver = new iarduino_RTC_NTP(); - break; - case 1: - RTCDriver = new iarduino_RTC_DS1302(_rst, _clk, _dat); - break; - case 2: - RTCDriver = new iarduino_RTC_DS1307(); - break; - case 3: - RTCDriver = new iarduino_RTC_DS3231(); - break; - case 4: - RTCDriver = new iarduino_RTC_RX8025(); - break; - } - if (RTCDriver) RTCDriver->begin(); - } - - void doByInterval() { - value.isDecimal = false; - value.valS = watch->gettime(_defFormat.c_str()); - if (_ticker) regEvent(value.valS, "time ticker"); - } - - IoTValue execute(String command, std::vector ¶m) { - IoTValue tmpValue; - if (command == "getTime") { - if (param.size()) { - tmpValue.isDecimal = false; - tmpValue.valS = watch->gettime(param[0].valS.c_str()); - return tmpValue; - } - } else if (command == "saveSysTime") { - tm localTimeVar; - time_t timeNowVar; - time(&timeNowVar); - localTimeVar = *localtime(&timeNowVar); - watch->settime(localTimeVar.tm_sec, localTimeVar.tm_min, localTimeVar.tm_hour, localTimeVar.tm_mday, localTimeVar.tm_mon+1, localTimeVar.tm_year-100, localTimeVar.tm_wday); - } else if (command == "setTime") { - if (param.size()) { - watch->settime(param[0].valD, param[1].valD, param[2].valD, param[3].valD, param[4].valD, param[5].valD, param[6].valD); - } - } else if (command == "setUnixTime") { - if (param.size()) { - watch->settimeUnix(param[0].valD); - } - } else if (command == "getHours") { - tmpValue.valD = watch->Hours; // Часы 0-23 - return tmpValue; - } else if (command == "getMinutes") { - tmpValue.valD = watch->minutes; // Минуты 0-59 - return tmpValue; - } else if (command == "getSeconds") { - tmpValue.valD = watch->seconds; // Секунды 0-59 - return tmpValue; - } else if (command == "getMonth") { - tmpValue.valD = watch->month; // Месяц 1-12 - return tmpValue; - } else if (command == "getDay") { - tmpValue.valD = watch->day; // День месяца 1-31 - return tmpValue; - } - - return {}; - } - - iarduino_RTC_BASE* getRtcDriver() { - return RTCDriver; - } - - ~IarduinoRTC() {}; -}; - - -void* getAPI_IarduinoRTC(String subtype, String param) { - if (subtype == F("IarduinoRTC")) { - return new IarduinoRTC(param); - } else { - return nullptr; - } -} diff --git a/src/modules/exec/IarduinoRTC/modinfo.json b/src/modules/exec/IarduinoRTC/modinfo.json deleted file mode 100644 index 8dec3def..00000000 --- a/src/modules/exec/IarduinoRTC/modinfo.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "menuSection": "Исполнительные устройства", - - "configItem": [{ - "name": "Поддержка DS1302(1), DS1307(2), DS3231(3), RX8025(4)", - "type": "Reading", - "subtype": "IarduinoRTC", - "id": "RTC", - "widget": "", - "page": "", - "descr": "", - - "int": "1", - "chipNum": 1, - "rst": 16, - "clk": 5, - "dat": 4, - "defFormat": "d-m-Y", - "ticker": 0 - }], - - "about": { - "authorName": "Ilya Belyakov", - "authorContact": "https://t.me/Biveraxe", - "authorGit": "https://github.com/biveraxe", - "specialThanks": "Sergey @Serghei63", - "moduleName": "IarduinoRTC", - "moduleVersion": "1.0", - "moduleDesc": "Позволяет использовать часы реального времени в виде внешнего физического модуля или виртуального с синхронизацией через сеть Интернет.", - "propInfo": { - "int": "Период времени в секундах между опросами времени с RTC", - "chipNum": "Выбор источника: 0 - время с Интернет, 1 - модуль DS1302, 2 - модуль DS1307, 3 - модуль DS3231, 4 - модуль RX38025", - "rst": "Номер пина для подключения вашего модуля часов. (не всегда используется).", - "clk": "Номер пина для SDL вашего модуля часов", - "dat": "Номер пина для SDA вашего модуля часов", - "defFormat": "Вывод информации в формате defFormat", - "ticker": "Генерировать(1) или нет(0) события при каждом тике модуля = int. Позволяет не применять модуль таймера, если нужно просто тактировать работу." - } - }, - - "defActive": true, - - "devices": { - "esp32_4mb": [], - "esp8266_4mb": [] - } -} \ No newline at end of file diff --git a/src/modules/exec/Mcp23017/Mcp23017.cpp b/src/modules/exec/Mcp23017/Mcp23017.cpp index a360230f..07f77bab 100644 --- a/src/modules/exec/Mcp23017/Mcp23017.cpp +++ b/src/modules/exec/Mcp23017/Mcp23017.cpp @@ -3,25 +3,21 @@ #include "classes/IoTGpio.h" #include - class Mcp23017 : public IoTItem, IoTGpio { private: - public: Adafruit_MCP23X17 mcp; - Mcp23017(String parameters, int index): IoTItem(parameters), IoTGpio(index) { - + Mcp23017(String parameters, int index) : IoTItem(parameters), IoTGpio(index) { } - + void doByInterval() { - - - //regEvent(value.valD, "Mcp23017"); + // regEvent(value.valD, "Mcp23017"); } - IoTGpio* getGpioDriver() { - return this; + //возвращает ссылку на экземпляр класса Mcp23017 + bool isGpioDriver() { + return true; } void pinMode(uint8_t pin, uint8_t mode) { @@ -40,10 +36,9 @@ class Mcp23017 : public IoTItem, IoTGpio { mcp.digitalWrite(pin, 1 - mcp.digitalRead(pin)); } - ~Mcp23017() {}; + ~Mcp23017(){}; }; - void* getAPI_Mcp23017(String subtype, String param) { if (subtype == F("Mcp23017")) { String addr; diff --git a/src/modules/exec/SysExt/SysExt.cpp b/src/modules/exec/SysExt/SysExt.cpp index 9c233202..99f58677 100644 --- a/src/modules/exec/SysExt/SysExt.cpp +++ b/src/modules/exec/SysExt/SysExt.cpp @@ -1,98 +1,96 @@ #include "Global.h" #include "classes/IoTItem.h" -#include "classes/IoTRTC.h" -extern IoTRTC *watch; // Пример модуля расширения возможностей системы на примере добавления новых команд в сценарии // При комбинации использования doByInterval() и execute() можно обеспечить интеграцию с внешними сервисами, такими как Telegram, например. -// +// class SysExt : public IoTItem { public: - SysExt(String parameters): IoTItem(parameters) { + SysExt(String parameters) : IoTItem(parameters) { // инициализация внутренних переменных и объектов для взаимодействия с внешними системами - //jsonRead(parameters, "addr", addr); // получаем параметры из настроек модуля. Наименования могут быть любыми. - } - + // jsonRead(parameters, "addr", addr); // получаем параметры из настроек модуля. Наименования могут быть любыми. + } + void doByInterval() { // выполнение периодических проверок каждые Int секунд из настроек модуля - //regEvent(Значение, Описание); // регистрация найденного события после проверок для запуска сценариев и других реакций в системе + // regEvent(Значение, Описание); // регистрация найденного события после проверок для запуска сценариев и других реакций в системе } - //void loop() { - // выполнение необходимых проверок в теле основного цикла программы. - // ВАЖНО: 1. при использовании loop() отключается doByInterval() - // 2. любые заминки в данном цикле повлияют на общую работу системы + // void loop() { + // выполнение необходимых проверок в теле основного цикла программы. + // ВАЖНО: 1. при использовании loop() отключается doByInterval() + // 2. любые заминки в данном цикле повлияют на общую работу системы //} - IoTValue execute(String command, std::vector ¶m) { + IoTValue execute(String command, std::vector& param) { // реакция на вызов команды модуля из сценария // String command - имя команды после ID. (ID.Команда()) // param - вектор ("массив") значений параметров переданных вместе с командой: ID.Команда("пар1", 22, 33) -> param[0].ValS = "пар1", param[1].ValD = 22 - + if (command == "reboot") { // выполняем код при вызове спец команды из сценария: ID.reboot(); ESP.restart(); - } else if (command == "digitalRead") { + } else if (command == "digitalRead") { if (param.size()) { IoTgpio.pinMode(param[0].valD, INPUT); value.valD = IoTgpio.digitalRead(param[0].valD); return value; } - } else if (command == "analogRead") { + } else if (command == "analogRead") { if (param.size()) { IoTgpio.pinMode(param[0].valD, INPUT); value.valD = IoTgpio.analogRead(param[0].valD); return value; } - } else if (command == "digitalWrite") { + } else if (command == "digitalWrite") { if (param.size() == 2) { IoTgpio.pinMode(param[0].valD, OUTPUT); IoTgpio.digitalWrite(param[0].valD, param[1].valD); return {}; } - } else if (command == "digitalInvert") { + } else if (command == "digitalInvert") { if (param.size()) { IoTgpio.pinMode(param[0].valD, OUTPUT); IoTgpio.digitalInvert(param[0].valD); return {}; } - } else if (command == "getTime") { - if (param.size()) { - value.isDecimal = false; - value.valS = watch->gettime(param[0].valS.c_str()); - return value; - } - } else if (command == "getHours") { - value.valD = watch->Hours; // Часы 0-23 - value.isDecimal = true; - return value; - } else if (command == "getMinutes") { - value.valD = watch->minutes; // Минуты 0-59 - value.isDecimal = true; - return value; - } else if (command == "getSeconds") { - value.valD = watch->seconds; // Секунды 0-59 - value.isDecimal = true; - return value; - } else if (command == "getMonth") { - value.valD = watch->month; // Месяц 1-12 - value.isDecimal = true; - return value; - } else if (command == "getDay") { - value.valD = watch->day; // День месяца 1-31 - value.isDecimal = true; - return value; + //} else if (command == "getTime") { + // if (param.size()) { + // value.isDecimal = false; + // value.valS = watch->gettime(param[0].valS.c_str()); + // return value; + // } + //} else if (command == "getHours") { + // value.valD = watch->Hours; // Часы 0-23 + // value.isDecimal = true; + // return value; + //} else if (command == "getMinutes") { + // value.valD = watch->minutes; // Минуты 0-59 + // value.isDecimal = true; + // return value; + //} else if (command == "getSeconds") { + // value.valD = watch->seconds; // Секунды 0-59 + // value.isDecimal = true; + // return value; + //} else if (command == "getMonth") { + // value.valD = watch->month; // Месяц 1-12 + // value.isDecimal = true; + // return value; + //} else if (command == "getDay") { + // value.valD = watch->day; // День месяца 1-31 + // value.isDecimal = true; + // return value; } else if (command == "deepSleep") { - if (param.size()) { + if (param.size()) { Serial.printf("Ушел спать на %d сек...", (int)param[0].valD); - #ifdef ESP32 - esp_sleep_enable_timer_wakeup(param[0].valD * 1000000); - delay(1000); - esp_deep_sleep_start(); - #else - ESP.deepSleep(param[0].valD * 1000000); - #endif +#ifdef ESP32 + esp_sleep_enable_timer_wakeup(param[0].valD * 1000000); + delay(1000); + esp_deep_sleep_start(); +#else + ESP.deepSleep(param[0].valD * 1000000); +#endif } return {}; } @@ -125,8 +123,8 @@ class SysExt : public IoTItem { // } return {}; // команда поддерживает возвращаемое значения. Т.е. по итогу выполнения команды или общения с внешней системой, можно вернуть значение в сценарий для дальнейшей обработки } - - ~SysExt() {}; + + ~SysExt(){}; }; void* getAPI_SysExt(String subtype, String param) { diff --git a/src/modules/sensors/AnalogAdc/AnalogAdc.cpp b/src/modules/sensors/AnalogAdc/AnalogAdc.cpp index 167c9ac0..4099a059 100644 --- a/src/modules/sensors/AnalogAdc/AnalogAdc.cpp +++ b/src/modules/sensors/AnalogAdc/AnalogAdc.cpp @@ -7,6 +7,7 @@ extern IoTGpio IoTgpio; // для добавления сенсора вам нужно скопировать этот файл и заменить в нем текст AnalogAdc на название вашего сенсора // Название должно быть уникальным, коротким и отражать суть сенсора. +//ребенок - родитель class AnalogAdc : public IoTItem { private: //======================================================================================================= @@ -24,7 +25,7 @@ class AnalogAdc : public IoTItem { // Такие как ...begin и подставлять в них параметры полученные из web интерфейса. // Все параметры хранятся в перемененной parameters, вы можете прочитать любой параметр используя jsonRead функции: // jsonReadStr, jsonReadBool, jsonReadInt - AnalogAdc(String parameters): IoTItem(parameters) { + AnalogAdc(String parameters) : IoTItem(parameters) { _pin = jsonReadInt(parameters, "pin"); _avgSteps = jsonReadInt(parameters, "avgSteps"); _avgSumm = 0; @@ -54,8 +55,8 @@ class AnalogAdc : public IoTItem { if (_avgCount > _avgSteps) { value.valD = _avgSumm / _avgSteps; _avgSumm = 0; - _avgCount = 0; - } + _avgCount = 0; + } _avgSumm = _avgSumm + IoTgpio.analogRead(_pin); _avgCount++; @@ -69,7 +70,7 @@ class AnalogAdc : public IoTItem { } } - ~AnalogAdc() {}; + ~AnalogAdc(){}; }; // после замены названия сенсора, на функцию можно не обращать внимания diff --git a/src/modules/virtual/Logging/Logging.cpp b/src/modules/virtual/Logging/Logging.cpp new file mode 100644 index 00000000..e69de29b diff --git a/src/utils/SerialPrint.cpp b/src/utils/SerialPrint.cpp index ed4c7cbc..071ecead 100644 --- a/src/utils/SerialPrint.cpp +++ b/src/utils/SerialPrint.cpp @@ -1,13 +1,10 @@ #include "utils/SerialPrint.h" -#include "classes/IoTRTC.h" - -extern IoTRTC *watch; void SerialPrint(String errorLevel, String module, String msg) { String tosend; - if (watch) tosend = watch->gettime("d.m.y H:i:s"); - else tosend = prettyMillis(millis()); + + tosend = prettyMillis(millis()); tosend = tosend + " [" + errorLevel + "] [" + module + "] " + msg; Serial.println(tosend); diff --git a/training/IarduinoRTC.cpp b/training/IarduinoRTC.cpp new file mode 100644 index 00000000..3145e364 --- /dev/null +++ b/training/IarduinoRTC.cpp @@ -0,0 +1,106 @@ +//#include "Global.h" +//#include "classes/IoTItem.h" +// +//#include +//#include "iarduino_RTC_DS1302.h" // Подключаем файл iarduino_RTC_DS1302.h +//#include "iarduino_RTC_DS1307.h" // Подключаем файл iarduino_RTC_DS1307.h +//#include "iarduino_RTC_DS3231.h" // Подключаем файл iarduino_RTC_DS3231.h +//#include "iarduino_RTC_RX8025.h" +// +// class IarduinoRTC : public IoTItem { +// private: +// int _chipNum, _rst, _clk, _dat, _ticker; +// String _defFormat; +// iarduino_RTC_BASE* RTCDriver; +// +// public: +// IarduinoRTC(String parameters) : IoTItem(parameters) { +// jsonRead(parameters, "chipNum", _chipNum); +// jsonRead(parameters, "rst", _rst); +// jsonRead(parameters, "clk", _clk); +// jsonRead(parameters, "dat", _dat); +// jsonRead(parameters, "defFormat", _defFormat); +// jsonRead(parameters, "ticker", _ticker); +// +// switch (_chipNum) { +// case 0: +// RTCDriver = new iarduino_RTC_NTP(); +// break; +// case 1: +// RTCDriver = new iarduino_RTC_DS1302(_rst, _clk, _dat); +// break; +// case 2: +// RTCDriver = new iarduino_RTC_DS1307(); +// break; +// case 3: +// RTCDriver = new iarduino_RTC_DS3231(); +// break; +// case 4: +// RTCDriver = new iarduino_RTC_RX8025(); +// break; +// } +// if (RTCDriver) RTCDriver->begin(); +// } +// +// void doByInterval() { +// value.isDecimal = false; +// value.valS = watch->gettime(_defFormat.c_str()); +// if (_ticker) regEvent(value.valS, "time ticker"); +// } +// +// IoTValue execute(String command, std::vector& param) { +// IoTValue tmpValue; +// if (command == "getTime") { +// if (param.size()) { +// tmpValue.isDecimal = false; +// tmpValue.valS = watch->gettime(param[0].valS.c_str()); +// return tmpValue; +// } +// } else if (command == "saveSysTime") { +// tm localTimeVar; +// time_t timeNowVar; +// time(&timeNowVar); +// localTimeVar = *localtime(&timeNowVar); +// watch->settime(localTimeVar.tm_sec, localTimeVar.tm_min, localTimeVar.tm_hour, localTimeVar.tm_mday, localTimeVar.tm_mon + 1, localTimeVar.tm_year - 100, localTimeVar.tm_wday); +// } else if (command == "setTime") { +// if (param.size()) { +// watch->settime(param[0].valD, param[1].valD, param[2].valD, param[3].valD, param[4].valD, param[5].valD, param[6].valD); +// } +// } else if (command == "setUnixTime") { +// if (param.size()) { +// watch->settimeUnix(param[0].valD); +// } +// } else if (command == "getHours") { +// tmpValue.valD = watch->Hours; // Часы 0-23 +// return tmpValue; +// } else if (command == "getMinutes") { +// tmpValue.valD = watch->minutes; // Минуты 0-59 +// return tmpValue; +// } else if (command == "getSeconds") { +// tmpValue.valD = watch->seconds; // Секунды 0-59 +// return tmpValue; +// } else if (command == "getMonth") { +// tmpValue.valD = watch->month; // Месяц 1-12 +// return tmpValue; +// } else if (command == "getDay") { +// tmpValue.valD = watch->day; // День месяца 1-31 +// return tmpValue; +// } +// +// return {}; +// } +// +// iarduino_RTC_BASE* getRtcDriver() { +// return RTCDriver; +// } +// +// ~IarduinoRTC(){}; +//}; +// +// void* getAPI_IarduinoRTC(String subtype, String param) { +// if (subtype == F("IarduinoRTC")) { +// return new IarduinoRTC(param); +// } else { +// return nullptr; +// } +//} diff --git a/training/IoTRTC.cpp b/training/IoTRTC.cpp new file mode 100644 index 00000000..40f35c7b --- /dev/null +++ b/training/IoTRTC.cpp @@ -0,0 +1,45 @@ +//#include "classes/IoTRTC.h" +// +// IoTRTC::~IoTRTC() { +// +//} +// +// +// iarduino_RTC_NTP::iarduino_RTC_NTP() { +// +//} +// +// void iarduino_RTC_NTP::begin(void) { +// +//} +// +// uint8_t iarduino_RTC_NTP::funcReadTimeIndex(uint8_t i) { +// static tm localTimeVar; +// if (i == 0) { +// Serial.println(F("Read time from system.")); +// time_t timeNowVar; +// time(&timeNowVar); +// localTimeVar = *localtime(&timeNowVar); +// } +// +// switch (i) +// { +// case 0: return funcConvertNumToCode(localTimeVar.tm_sec); +// case 1: return funcConvertNumToCode(localTimeVar.tm_min); +// case 2: return funcConvertNumToCode(localTimeVar.tm_hour); +// case 3: return funcConvertNumToCode(localTimeVar.tm_mday); +// case 4: return funcConvertNumToCode(localTimeVar.tm_mon+1); +// case 5: return funcConvertNumToCode(localTimeVar.tm_year-100); +// case 6: return funcConvertNumToCode(localTimeVar.tm_wday); +// } +// +// return 0; +//} +// +// void iarduino_RTC_NTP::funcWriteTimeIndex(uint8_t i, uint8_t j) { +// +//} +// +// iarduino_RTC_NTP::~iarduino_RTC_NTP() { +// +//} diff --git a/training/IoTRTC.h b/training/IoTRTC.h new file mode 100644 index 00000000..15640aac --- /dev/null +++ b/training/IoTRTC.h @@ -0,0 +1,22 @@ +//#pragma once +//#include +//#include +// +// class iarduino_RTC_NTP: public iarduino_RTC_BASE { +// public: +// iarduino_RTC_NTP(); +// ~iarduino_RTC_NTP(); +// void begin(void); +// uint8_t funcReadTimeIndex(uint8_t i); +// void funcWriteTimeIndex(uint8_t i, uint8_t j); +// uint8_t funcConvertNumToCode (uint8_t i) {return ((i/10) << 4) + (i%10);} +//}; +// +// class IoTRTC : public iarduino_RTC { +// public: +// IoTRTC(uint8_t i, uint8_t j=SS, uint8_t k=SCK, uint8_t n=MOSI) : iarduino_RTC(i, j, k, n) { +// if (i == 0) objClass = new iarduino_RTC_NTP(); +// }; +// +// ~IoTRTC(); +//}; \ No newline at end of file