This repository has been archived by the owner on Mar 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimeProvider.cpp
80 lines (59 loc) · 1.67 KB
/
TimeProvider.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
#include "TimeProvider.h"
#include <Arduino.h>
#include <HTTPClient.h>
#include "Logger.h"
#include "Constants.h"
using namespace Constants::Clock;
bool TimeProvider::fetchTimeWithHttp(const String url, DateTime& dateTime)
{
HTTPClient http;
http.begin(url);
http.setConnectTimeout(10 * 1000);
http.setTimeout(10 * 1000);
if (http.GET() != 200) return false;
const auto html = http.getString();
const auto timeStr = html.substring(46, html.indexOf("\n", 46));
const uint32_t unixTime = timeStr.toDouble() + 0.5;
dateTime = DateTime(unixTime + 9 * 60 * 60);
return true;
}
bool TimeProvider::isRTCRunning()
{
return rtc.initialized();
}
bool TimeProvider::isRTCBatteryLow()
{
return rtc.readIfBatteryIsLow();
}
void TimeProvider::syncWithNTP()
{
DateTime dateTime;
if (!fetchTimeWithHttp(UNIX_TIME_URL, dateTime))
return;
rtc.reset();
rtc.adjust(dateTime);
}
DateTime TimeProvider::fetchRTCDateTime()
{
if (!isRTCRunning()) Throw("RTC is not running.");
return rtc.now();
}
void TimeProvider::GetDateStr(char *str, const DateTime dateTime)
{
sprintf(str, "%04u/%02u/%02u", dateTime.year(), dateTime.month(), dateTime.day());
}
void TimeProvider::GetTimeStr(char *str, const DateTime dateTime, const bool withSeconds = true)
{
if (withSeconds) sprintf(str, "%02u:%02u:%02u", dateTime.hour(), dateTime.minute(), dateTime.second());
else sprintf(str, "%02u:%02u", dateTime.hour(), dateTime.minute());
}
String TimeProvider::GetDateTimeStr(const DateTime dateTime)
{
String result;
char temp[16];
GetDateStr(temp, dateTime);
result += String(temp) + String(' ');
GetTimeStr(temp, dateTime);
result += String(temp);
return result;
}