Files
wordclock/include/time_manager.h
2024-04-07 01:14:17 +02:00

89 lines
3.0 KiB
C++

#ifndef TIME_MANAGER_H
#define TIME_MANAGER_H
#include <Arduino.h>
#include <time.h>
#include "udp_logger.h"
typedef enum
{
NTP_UPDATE_FAILED = 0,
NTP_UPDATE_OK = 1,
NTP_UPDATE_PENDING = 2,
NTP_UPDATE_RETRY_DELAY = 3,
NTP_UPDATE_TOO_EARLY = 4,
NTP_UPDATE_SETUP_FAILED = 5,
} NtpUpdateState;
typedef enum
{
TM_INIT = 0,
TM_INITIAL_SYNC = 1,
TM_RETRY_SYNC = 2,
TM_NORMAL = 3,
TM_PROLONGED_SYNC_FAIL = 4,
TM_SETUP_FAILED = 5,
} TimeManagerState;
class TimeManager
{
#define NTP_MAX_UPDATE_TIME_US (500 * 1000) // 500ms max update time
public:
// constructor
TimeManager(const char *tz,
const char *ntp_server,
uint32 ntp_update_period_s,
uint32 ntp_retry_delay_us,
uint32 ntp_max_offline_time_s,
UDPLogger *logger);
// ntp methods
bool ntp_sync_successful(void) const; // was there a NTP sync once?
bool ntp_update_failed_prolonged(void); // indicates if maximum time since last NTP update was too long
NtpUpdateState ntp_time_update(); // main NTP time update method, called in loop
// ISR method
void increment_time_now_local(void); // should be called by timer ISR
// getter for time values
bool tm_isdst(void); // true if summertime
int tm_day(void);
int tm_hour(void);
int tm_min(void);
int tm_mon(void);
int tm_year(void);
struct tm time_info(void);
// getter
TimeManagerState tm_state(void) const; // get current state
// logging
void log_time() const; // log _time_info
void log_time(struct tm time_info) const; // log argument time_info
private:
// setup methods
void _set_up_ntp(void); // set up NTP server
void _set_up_timer_isr(void); // set up timer interrupt
const char *_tz; // timezone
const char *_ntp_server; // ntp server address
UDPLogger *_logger; // logger instance
TimeManagerState _tm_state = TM_INIT; // Main state
struct tm _time_info = {0, 0, 0, 0, 0, 0, 0, 0, 0}; // structure tm holds time information
time_t _time_now_local = 0; // local timer value, updated by timer interrupt and synced by NTP when needed
time_t _time_now_ntp = 0; // NTP timer value, seconds since Epoch (1970) - UTC, only synced by NTP request.
uint32 _ntp_max_offline_time_s; // maximum time in seconds which is considered ok since last NTP update
uint32 _ntp_update_period_s; // NTP request update period in seconds
uint32 _ntp_retry_delay_us; // minimum retry delay in us between two NTP requests
uint32 _ntp_sync_timestamp_us = 0; // timestamp of last successful ntp update
};
inline void TimeManager::increment_time_now_local(void)
{
_time_now_local++;
}
#endif /* TIME_MANAGER_H */