You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

122 lines
2.7 KiB

#include "AlarmClock.h"
AlarmClock::AlarmClock() {
}
bool AlarmClock::update(void) {
// time_t now;
// struct tm timeinfo;
time(&now); // update 'now' variable with current time
setenv("TZ", "CET-1CEST,M3.5.0/2,M10.5.0/3", 1);
tzset();
localtime_r(&now, &timeinfo);
}
bool AlarmClock::isTimeValid(void) {
update();
if (timeinfo.tm_year < (2016 - 1900)) {
return false; // time not set
}
return true;
}
bool AlarmClock::isNight(void) {
update();
return (timeinfo.tm_hour < 7 || timeinfo.tm_hour >= 22);
}
bool AlarmClock::isAlarmArmed(void) {
return alarmArmed;
}
double AlarmClock::getSecondsToAlarm(void) {
update();
return -difftime(now, mktime(&alarmTime));
}
bool AlarmClock::isPending(double window) {
double seconds = getSecondsToAlarm();
return (alarmArmed && seconds <= window);
}
void AlarmClock::setAlarmTime(struct tm time) {
alarmTime = time;
alarmArmed = true;
}
void AlarmClock::disableAlarm(void) {
alarmArmed = false;
}
struct tm AlarmClock::getAlarmTime() {
return alarmTime;
}
void AlarmClock::printTimeUnix(whichTime type) {
char strftime_buf[64];
getTime(strftime_buf, sizeof(strftime_buf), "%c", type);
Serial.println(strftime_buf);
}
void AlarmClock::getTime(char* ptr, size_t maxsize, const char* format, whichTime type) {
update();
switch (type) {
case TIME_CURRENT:
strftime(ptr, maxsize, format, &timeinfo);
break;
case TIME_ALARM:
strftime(ptr, maxsize, format, &alarmTime);
break;
default:
break;
}
}
/*
bool AlarmClock::getRTCTime(struct tm *timeinfo) {
time_t now;
time(&now); // update 'now' variable with current time
setenv("TZ", "CET-1CEST,M3.5.0/2,M10.5.0/3", 1);
tzset();
localtime_r(&now, timeinfo);
if (timeinfo->tm_year < (2016 - 1900)) {
// time not set
return false;
}
return true;
}
*/
bool AlarmClock::isNTPExpired(void) {
if (lastNTPRequest == 0 || millis() - lastNTPRequest >= 15*60*1000) {
lastNTPRequest = millis();
return true;
}
return false;
}
bool AlarmClock::updateNTPTime(void) {
ESP_LOGI(TAG, "Getting time over NTP.");
lastNTPRequest = millis();
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, "de.pool.ntp.org");
sntp_init();
// wait for time to be set
time_t now = 0;
struct tm timeinfo = { 0 };
int retry = 0;
const int retry_count = 10;
while(timeinfo.tm_year < (2016 - 1900) && ++retry < retry_count) {
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
vTaskDelay(2000 / portTICK_PERIOD_MS);
time(&now);
localtime_r(&now, &timeinfo);
}
if (timeinfo.tm_year < (2016 - 1900)) return false;
else return true;
}