-
Notifications
You must be signed in to change notification settings - Fork 9
/
RealTimeClock.cpp
95 lines (91 loc) · 2.06 KB
/
RealTimeClock.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
//
//
//
#include "RealTimeClock.h"
RealTimeClock::RealTimeClock()
{
gTimeClient = new (BUFFER_TIME_CLIENT) NTPClient(TIME_SERVER, 0, 0);
SetupNtp();
}
RealTimeClock::~RealTimeClock()
{
//delete(gTimeClient);
}
unsigned long RealTimeClock::GetTime()
{
UpdateTime(false);
// I first thought we had to implement rollover code, but the
// beauty of the unsigned variables just so happens to smile
// (the result will be the remainder plus the value anyway)
return gLastTime + (millis() - gLastUpdatedTime) / 1000;
}
bool RealTimeClock::Update()
{
return UpdateTime(false);
}
void RealTimeClock::SetupNtp()
{
Serial1.print("Connecting to NTP server");
while (!UpdateTime(true)) {
Serial1.print(".");
}
Serial1.println("");
}
bool RealTimeClock::UpdateTime(bool pForceUpdate)
{
if (pForceUpdate)
{
Serial1.println("Force time update...");
gTimeClient->update();
if (gTimeClient->getRawTime() > 1000)
{
gLastUpdatedTime = millis();
gLastTime = gTimeClient->getRawTime();
Serial1.println("Time is ");
Serial1.println(gTimeClient->getFormattedTime().c_str());
return true;
}
else
return false;
}
else
{
if (ShouldUpdateTime())
{
Serial1.println("Updating time now...");
if (!UpdateTime(true))
{
Serial1.println("Failed to update time...");
if (ShouldUpdateTime(10))
{
Serial1.println("ERROR updating time for a long time now...");
// It's been way too long since last update
return false;
}
}
else
{
Serial1.println("Time is ");
Serial1.println(gTimeClient->getFormattedTime());
}
}
return true;
}
}
bool RealTimeClock::ShouldUpdateTime()
{
return ShouldUpdateTime(1);
}
bool RealTimeClock::ShouldUpdateTime(int pFactor)
{
if (gLastUpdatedTime == 0)
return true;
else if (gLastUpdatedTime > millis())
return true; // Millis counter just past the max value
else if ((millis() - gLastUpdatedTime) > (UPDATE_TIME_INTERVAL * (unsigned long)pFactor))
return true;
else
{
return false;
}
}