EmlaLockSafe
RealTimeClock.h
Go to the documentation of this file.
1
5#pragma once
6
7#include <ds3231.h>
8#include <stdlib.h>
9#include <sys/time.h>
10
15public:
19 static void loadTimeFromRtc() {
20 char currentTimezone[100];
21 char* envTimezone = getenv("TZ");
22
23 // was the timezone set? create a copy
24 if (envTimezone) {
25 strcpy(currentTimezone, envTimezone);
26 }
27
28 // The DS3231 runs in UTC. Temporarily change the system to UTC as well
29 setenv("TZ", "UTC0", 1);
30 tzset();
31
32 // Initialize clock
33 DS3231_init(DS3231_CONTROL_INTCN);
34
35 // Get current time
36 struct ts rtcTime;
37 DS3231_get(&rtcTime);
38
39 // convert the ts to a tm struc
40 tm timeBuf;
41 memset(&timeBuf, 0, sizeof(tm));
42 timeBuf.tm_year = rtcTime.year - 1900;
43 timeBuf.tm_mon = rtcTime.mon - 1;
44 timeBuf.tm_mday = rtcTime.mday;
45 timeBuf.tm_hour = rtcTime.hour;
46 timeBuf.tm_min = rtcTime.min;
47 timeBuf.tm_sec = rtcTime.sec;
48 timeBuf.tm_isdst = -1; // negative value means no daylightsaving time as required for UTC0
49
50 // convert to timeval
51 struct timeval tv;
52 tv.tv_sec = mktime(&timeBuf);
53 tv.tv_usec = 0;
54
55 // set system-clock
56 settimeofday(&tv, NULL);
57
58 // was the timezone set before? Restore the original timezone
59 if (envTimezone) {
60 setenv("TZ", currentTimezone, 1);
61 tzset();
62 }
63 }
64
68 static void saveTimeToRtc() {
69 tm timeBuf;
70 struct ts rtcTime;
71 // convert current time to tm structure
72 time_t tNow;
73 time(&tNow);
74
75 // convert to UTC time
76 gmtime_r(&tNow, &timeBuf);
77
78 // convert tm structure to RTC structure
79 rtcTime.year = timeBuf.tm_year + 1900;
80 rtcTime.mon = timeBuf.tm_mon + 1;
81 rtcTime.mday = timeBuf.tm_mday;
82 rtcTime.hour = timeBuf.tm_hour;
83 rtcTime.min = timeBuf.tm_min;
84 rtcTime.sec = timeBuf.tm_sec;
85
86 // Initialize clock
87 DS3231_init(DS3231_CONTROL_INTCN);
88
89 // Set current time
90 DS3231_set(rtcTime);
91 }
92};
Helper syncinc the SystemClock with the RTC running in UTC.
Definition: RealTimeClock.h:14
static void loadTimeFromRtc()
Sets the system clock based on the RTC.
Definition: RealTimeClock.h:19
static void saveTimeToRtc()
Sets the RTC time to the value of the system clock.
Definition: RealTimeClock.h:68