Добавляем модуль RTC и его поддержку в систему

This commit is contained in:
2023-02-17 20:26:29 +03:00
parent e0b8613c99
commit 1189b7c289
8 changed files with 174 additions and 2 deletions

View File

@@ -55,6 +55,7 @@
*****************************************глобальные объекты классов***************************************************
**********************************************************************************************************************/
extern IoTGpio IoTgpio;
extern IoTItem* rtcItem;
extern TickerScheduler ts;
extern WiFiClient espClient;

View File

@@ -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();

View File

@@ -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<IoTItem*>::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) {
Serial.printf("Start delete iotitem %s \n", (*it)->getID().c_str());
if (*it) delete *it;

View File

@@ -30,6 +30,7 @@ WebSocketsServer standWebSocket = WebSocketsServer(81);
***********************************************глобальные переменные**************************************************
**********************************************************************************************************************/
IoTGpio IoTgpio(0);
IoTItem* rtcItem = nullptr;
String settingsFlashJson = "{}"; // переменная в которой хранятся все настройки, находится в оперативной памяти и синхронизированна с flash памятью
String valuesFlashJson = "{}"; // переменная в которой хранятся все значения элементов, которые необходимо сохранить на flash. Находится в оперативной памяти и синхронизированна с flash памятью

View File

@@ -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);

View File

@@ -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) {

View File

@@ -0,0 +1,82 @@
#include "Global.h"
#include "classes/IoTItem.h"
#include <iarduino_RTC.h>
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<IoTValue> &param) {
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;
}
}

View File

@@ -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"]
}
}