Files
IoTManager/include/Clock.h

84 lines
1.9 KiB
C
Raw Normal View History

2020-06-22 03:11:02 +03:00
#pragma once
2020-06-25 09:21:42 +03:00
#include "Utils/TimeUtils.h"
#include "Utils/PrintMessage.h"
2020-06-22 03:11:02 +03:00
2020-06-25 20:13:20 +03:00
#include "TZ.h"
2020-06-22 03:11:02 +03:00
2020-06-25 09:21:42 +03:00
class Clock {
const char* MODULE = "Clock";
public:
2020-06-26 01:38:29 +03:00
Clock() : _timezone{0}, _hasSynced{false}, _configured{false} {}
2020-06-25 09:21:42 +03:00
bool hasSync() {
if (!_hasSynced) {
startSync();
}
return _hasSynced;
}
2020-06-25 20:13:20 +03:00
void setNtpPool(String ntp) {
2020-06-25 09:21:42 +03:00
_ntp = ntp;
}
void setTimezone(int timezone) {
_timezone = timezone;
}
void startSync() {
if (!_configured) {
pm.info("sync to: " + _ntp + " time zone: " + String(_timezone));
setupSntp();
_configured = true;
}
_hasSynced = hasTimeSynced();
if (_hasSynced) {
pm.info("synced " + getDateDigitalFormated() + " " + getTime());
} else {
pm.error("failed to obtain");
}
}
void setupSntp() {
2020-06-26 01:38:29 +03:00
int tzs = getOffsetInSeconds(_timezone);
2020-06-25 09:21:42 +03:00
int tzh = tzs / 3600;
tzs -= tzh * 3600;
int tzm = tzs / 60;
tzs -= tzm * 60;
char tzstr[64];
snprintf(tzstr, sizeof tzstr, "ESPUSER<%+d:%02d:%02d>", tzh, tzm, tzs);
pm.info(String(tzstr));
configTime(tzstr, _ntp.c_str());
}
// #ifdef ESP32
// uint8_t i = 0;
// struct tm timeinfo;
// while (!getLocalTime(&timeinfo) && i <= 4) {
// Serial.print(".");
// i++;
// delay(1000);
// }
2020-06-26 01:38:29 +03:00
// #endifr
2020-06-25 20:13:20 +03:00
2020-06-25 09:21:42 +03:00
bool hasTimeSynced() {
2020-06-26 01:38:29 +03:00
return getSystemTime() > 30000;
2020-06-25 20:13:20 +03:00
}
time_t getSystemTime() {
timeval tv{0, 0};
2020-06-26 01:38:29 +03:00
timezone tz = timezone{getOffsetInMinutes(_timezone), 0};
2020-06-25 20:13:20 +03:00
if (gettimeofday(&tv, &tz) != -1) {
2020-06-26 01:38:29 +03:00
_epoch = tv.tv_sec;
2020-06-25 20:13:20 +03:00
}
2020-06-26 01:38:29 +03:00
return _epoch;
2020-06-25 09:21:42 +03:00
}
private:
2020-06-26 01:38:29 +03:00
time_t _epoch;
2020-06-25 09:21:42 +03:00
int _timezone;
String _ntp;
bool _hasSynced;
bool _configured;
};