From 1189b7c289ced586774612cc6bee0bea99247fc4 Mon Sep 17 00:00:00 2001 From: biver Date: Fri, 17 Feb 2023 20:26:29 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D1=8F?= =?UTF-8?q?=D0=B5=D0=BC=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20RTC=20?= =?UTF-8?q?=D0=B8=20=D0=B5=D0=B3=D0=BE=20=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5?= =?UTF-8?q?=D1=80=D0=B6=D0=BA=D1=83=20=D0=B2=20=D1=81=D0=B8=D1=81=D1=82?= =?UTF-8?q?=D0=B5=D0=BC=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/Global.h | 1 + include/classes/IoTItem.h | 3 + src/ESPConfiguration.cpp | 5 ++ src/Global.cpp | 1 + src/NTP.cpp | 9 ++- src/classes/IoTItem.cpp | 8 +++ src/modules/sensors/RTC/RTC.cpp | 82 ++++++++++++++++++++++++++++ src/modules/sensors/RTC/modinfo.json | 67 +++++++++++++++++++++++ 8 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 src/modules/sensors/RTC/RTC.cpp create mode 100644 src/modules/sensors/RTC/modinfo.json diff --git a/include/Global.h b/include/Global.h index 38bc36c4..91cd2047 100644 --- a/include/Global.h +++ b/include/Global.h @@ -55,6 +55,7 @@ *****************************************глобальные объекты классов*************************************************** **********************************************************************************************************************/ extern IoTGpio IoTgpio; +extern IoTItem* rtcItem; extern TickerScheduler ts; extern WiFiClient espClient; diff --git a/include/classes/IoTItem.h b/include/classes/IoTItem.h index c0cce8ed..342bc02f 100644 --- a/include/classes/IoTItem.h +++ b/include/classes/IoTItem.h @@ -46,6 +46,9 @@ class IoTItem { bool enableDoByInt = true; virtual IoTGpio* getGpioDriver(); + virtual IoTItem* getRtcDriver(); + virtual ulong getRtcUnixTime(); + virtual void setValue(const IoTValue& Value, bool genEvent = true); virtual void setValue(const String& valStr, bool genEvent = true); String getRoundValue(); diff --git a/src/ESPConfiguration.cpp b/src/ESPConfiguration.cpp index 1ab3a874..796e7bb5 100644 --- a/src/ESPConfiguration.cpp +++ b/src/ESPConfiguration.cpp @@ -29,6 +29,8 @@ void configure(String path) { void* driver; // пробуем спросить драйвер GPIO if (driver = myIoTItem->getGpioDriver()) IoTgpio.regDriver((IoTGpio*)driver); + // пробуем спросить драйвер RTC + if (driver = myIoTItem->getRtcDriver()) rtcItem = (IoTItem*)driver; IoTItems.push_back(myIoTItem); } @@ -41,6 +43,9 @@ void configure(String path) { void clearConfigure() { Serial.printf("Start clearing config\n"); + rtcItem = nullptr; + IoTgpio.clearDrivers(); + 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/Global.cpp b/src/Global.cpp index cbe0310f..efab097a 100644 --- a/src/Global.cpp +++ b/src/Global.cpp @@ -30,6 +30,7 @@ WebSocketsServer standWebSocket = WebSocketsServer(81); ***********************************************глобальные переменные************************************************** **********************************************************************************************************************/ IoTGpio IoTgpio(0); +IoTItem* rtcItem = nullptr; String settingsFlashJson = "{}"; // переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью String valuesFlashJson = "{}"; // переменная в которой хранятся все значения элементов, которые необходимо сохранить на flash. Находится в оперативной памяти и синхронизированна с flash памятью diff --git a/src/NTP.cpp b/src/NTP.cpp index 112050fa..f9f8a4a1 100644 --- a/src/NTP.cpp +++ b/src/NTP.cpp @@ -9,14 +9,19 @@ void ntpInit() { ts.add( TIME, 1000, [&](void*) { unixTime = getSystemTime(); - unixTimeShort = unixTime - START_DATETIME; if (unixTime < MIN_DATETIME) { isTimeSynch = false; // SerialPrint("E", "NTP", "Time not synched"); jsonWriteInt(errorsHeapJson, F("tme1"), 1); synchTime(); - return; + + // проверяем присутствие RTC с батарейкой и получаем время при наличии + if (rtcItem) { + unixTime = rtcItem->getRtcUnixTime(); + } else return; } + + unixTimeShort = unixTime - START_DATETIME; jsonWriteInt(errorsHeapJson, F("tme1"), 0); breakEpochToTime(unixTime + jsonReadInt(settingsFlashJson, F("timezone")) * 60 * 60, _time_local); breakEpochToTime(unixTime, _time_utc); diff --git a/src/classes/IoTItem.cpp b/src/classes/IoTItem.cpp index 5b8c5476..c3606775 100644 --- a/src/classes/IoTItem.cpp +++ b/src/classes/IoTItem.cpp @@ -208,6 +208,14 @@ IoTGpio* IoTItem::getGpioDriver() { return nullptr; } +IoTItem* IoTItem::getRtcDriver() { + return nullptr; +} + +ulong IoTItem::getRtcUnixTime() { + return 0; +} + // сетевое общение==================================================================================================================================== // externalVariable::externalVariable(const String& parameters) : IoTItem(parameters) { diff --git a/src/modules/sensors/RTC/RTC.cpp b/src/modules/sensors/RTC/RTC.cpp new file mode 100644 index 00000000..727303f0 --- /dev/null +++ b/src/modules/sensors/RTC/RTC.cpp @@ -0,0 +1,82 @@ +#include "Global.h" +#include "classes/IoTItem.h" +#include + +class RTC : public IoTItem { + private: + bool _ticker = false; + iarduino_RTC* _watch; + String _timeFormat = ""; + + public: + RTC(String parameters) : IoTItem(parameters) { + jsonRead(parameters, F("ticker"), _ticker); + jsonRead(parameters, F("timeFormat"), _timeFormat); + _timeFormat = _timeFormat + " "; // костыль для коррекции ошибки в библиотеке + + int chipCode = 3; + jsonRead(parameters, F("chipCode"), chipCode); + if (chipCode == 1) { + int RST, CLK, DAT; + jsonRead(parameters, "RST", RST); + jsonRead(parameters, "CLK", CLK); + jsonRead(parameters, "DAT", DAT); + _watch = new iarduino_RTC(RTC_DS1302, RST, CLK, DAT); + } else { + _watch = new iarduino_RTC(chipCode); + } + _watch->begin(); + } + + void doByInterval() { + value.isDecimal = false; + value.valS = _watch->gettime(_timeFormat); + + if (_ticker) regEvent(value.valS, F("RTC tick")); + } + + IoTItem* getRtcDriver() { + return this; + } + + ulong getRtcUnixTime() { + return _watch->gettimeUnix(); + } + + void onModuleOrder(String &key, String &value) { + if (key == "setUTime") { + char *stopstring; + ulong ut = strtoul(value.c_str(), &stopstring, 10); + _watch->settimeUnix(ut); + SerialPrint("i", F("RTC"), "Устанавливаем время: " + value); + } else if (key == "setSysTime") { + _watch->settimeUnix(unixTime); + SerialPrint("i", F("RTC"), F("Запоминаем системное время")); + } + } + + IoTValue execute(String command, std::vector ¶m) { + if (command == "getTime") { + if (param.size() == 1) { + IoTValue valTmp; + valTmp.isDecimal = false; + valTmp.valS = _watch->gettime(param[0].valS + " "); + return valTmp; + } + } + + return {}; + } + + ~RTC(){ + if (_watch) delete _watch; + }; +}; + +void* getAPI_RTC(String subtype, String param) { + if (subtype == F("RTC")) { + return new RTC(param); + } else { + return nullptr; + } +} diff --git a/src/modules/sensors/RTC/modinfo.json b/src/modules/sensors/RTC/modinfo.json new file mode 100644 index 00000000..464dcb9c --- /dev/null +++ b/src/modules/sensors/RTC/modinfo.json @@ -0,0 +1,67 @@ +{ + "menuSection": "Сенсоры", + "configItem": [ + { + "global": 0, + "name": "Часы реального времени", + "type": "Reading", + "subtype": "RTC", + "id": "rtc", + "widget": "anydataDef", + "page": "Таймеры", + "descr": "Время RTC", + "chipCode": 1, + "timeFormat": "d-m-Y H:i:s", + "RST": -1, + "CLK": -1, + "DAT": -1, + "ticker": 0, + "int": 5, + "btn-setUTime": "0", + "btn-setSysTime": "nil" + } + ], + "about": { + "authorName": "Ilya Belyakov", + "authorContact": "https://t.me/Biveraxe", + "authorGit": "https://github.com/biveraxe", + "exampleURL": "https://iotmanager.org/wiki", + "specialThanks": "", + "moduleName": "RTC", + "moduleVersion": "1.0", + "usedRam": { + "esp32_4mb": 15, + "esp8266_4mb": 15 + }, + "title": "Часы реального времени", + "moduleDesc": "Позволяет хранить и получать время из модуля с батарейкой.", + "propInfo": { + "chipCode": "RX8025 - 4, DS3231 - 3, DS1307 - 2, DS1302 - 1 (необходимо установить пины RST, CLK и DAT)", + "timeFormat": "Формат времени для вывода. Как у функции date() в PHP", + "RST": "Пин RST", + "CLK": "Пин CLK", + "DAT": "Пин DAT", + "ticker": "Генерировать(1) или нет(0) события при каждом тике часов (каждые int секунд).", + "int": "Количество секунд между получениями данных из модуля", + "btn-setUTime": "Кнопка установки времени модуля на основе указанного unixtime", + "btn-setSysTime": "Кнопка установки времени модуля на основе системного с платы ESP" + }, + "retInfo": "Содержит текущее время из модуля RTC", + "funcInfo": [ + { + "name": "getTime", + "descr": "Получить строковое значение времени по указанному формату.", + "params": ["Формат как у функции date() в PHP"] + } + ] + }, + "defActive": true, + "usedLibs": { + "esp32_4mb": ["https://github.com/tremaru/iarduino_RTC"], + "esp8266_4mb": ["https://github.com/tremaru/iarduino_RTC"], + "esp8266_1mb": ["https://github.com/tremaru/iarduino_RTC"], + "esp8266_1mb_ota": ["https://github.com/tremaru/iarduino_RTC"], + "esp8285_1mb": ["https://github.com/tremaru/iarduino_RTC"], + "esp8285_1mb_ota": ["https://github.com/tremaru/iarduino_RTC"] + } +} \ No newline at end of file