forked from gunnwo/espclock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRTC.cpp
130 lines (104 loc) · 2.34 KB
/
CRTC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include "CRTC.h"
//TODO move into own header file
// CONNECTIONS:
// DS3231 SDA --> SDA
// DS3231 SCL --> SCL
// DS3231 VCC --> 3.3v or 5v
// DS3231 GND --> GND
//I2C pins
#define SDA 5
#define SCL 4
CRTC::CRTC():
m_pSyncProvider(0),
syncInterval(86400),
nextSyncTime(0),
Rtc(Wire)
{
}
CRTC::~CRTC()
{
}
bool CRTC::setup()
{
Wire.begin(SDA, SCL);
Rtc.Begin();
if (!Rtc.IsDateTimeValid())
{
Serial.println("CRTC::setup() - RTC lost confidence in the DateTime!");
// This will most likely happen when the battery is low or the RTC is used the first time.
// After setting the sync provider the time will be set correctly to utc
}
if (!Rtc.GetIsRunning())
{
Serial.println("CRTC::setup() - RTC was not actively running, starting now");
Rtc.SetIsRunning(true);
}
Rtc.Enable32kHzPin(false);
Rtc.SetSquareWavePin(DS3231SquareWavePin_ModeNone);
}
time_t CRTC::now()
{
Serial.println("CRTC::now() - called");
if (!Rtc.IsDateTimeValid())
{
// Common Cases:
// 1) the battery on the device is low or even missing and the power line was disconnected
Serial.println("CRTC::now() - RTC lost confidence in the DateTime! Trying to resync with SyncProvider");
sync(0, true);
}
RtcDateTime now = Rtc.GetDateTime();
time_t t((time_t)now.Epoch32Time());
t = sync(t);
return(t);
}
time_t CRTC::sync(time_t t, bool force)
{
if(nextSyncTime <= (uint32_t)t || force == true)
{
if(0 != m_pSyncProvider)
{
Serial.println("CRTC::sync - resyncing");
time_t tsync(m_pSyncProvider->now());
if(0 != tsync)
{
setTime(tsync);
t = tsync;
}
else
{
delay(1000);
time_t tsync(m_pSyncProvider->now());
if (0 != tsync)
{
setTime(tsync);
t = tsync;
}
else
{
nextSyncTime = (uint32_t)t + syncInterval;
}
}
}
}
return t;
}
void CRTC::setTime(time_t t)
{
RtcDateTime now;
now.InitWithEpoch32Time((uint32_t)t);
Rtc.SetDateTime(now);
nextSyncTime = (uint32_t)t + syncInterval;
}
void CRTC::setSyncProvider(ISyncProvider* pSyncProvider)
{
m_pSyncProvider = pSyncProvider;
nextSyncTime = 0;
now(); // this will sync the clock
}
// set the number of seconds between re-sync
void CRTC::setSyncInterval(time_t interval)
{
syncInterval = (uint32_t)interval;
RtcDateTime now = Rtc.GetDateTime();
nextSyncTime = now.Epoch32Time() + syncInterval;
}