Merge pull request #10485 from iNavFlight/mmosca-patch-5
[inav.git] / src / main / common / time.c
blob8214398d26b704314f18763873fc52efc3bb2f62
1 /*
2 * This file is part of INAV.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
6 * You can obtain one at http://mozilla.org/MPL/2.0/.
8 * Alternatively, the contents of this file may be used under the terms
9 * of the GNU General Public License Version 3, as described below:
11 * This file is free software: you may copy, redistribute and/or modify
12 * it under the terms of the GNU General Public License as published by the
13 * Free Software Foundation, either version 3 of the License, or (at your
14 * option) any later version.
16 * This file is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
19 * Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see http://www.gnu.org/licenses/.
24 * @author Alberto Garcia Hierro <alberto@garciahierro.com>
27 #include "common/maths.h"
28 #include "common/printf.h"
29 #include "common/time.h"
30 #include "common/utils.h"
32 #include "config/parameter_group_ids.h"
34 #include "drivers/time.h"
36 #include "fc/settings.h"
38 #ifdef SITL_BUILD
39 #include <time.h>
40 #endif
42 // For the "modulo 4" arithmetic to work, we need a leap base year
43 #define REFERENCE_YEAR 2000
44 // Offset (seconds) from the UNIX epoch (1970-01-01) to 2000-01-01
45 #define EPOCH_2000_OFFSET 946684800
47 #define MILLIS_PER_SECOND 1000
49 // rtcTime_t when the system was started.
50 // Calculated in rtcSet().
51 static rtcTime_t started = 0;
53 static const uint16_t days[4][12] =
55 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335},
56 { 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700},
57 { 731, 762, 790, 821, 851, 882, 912, 943, 974, 1004, 1035, 1065},
58 {1096, 1127, 1155, 1186, 1216, 1247, 1277, 1308, 1339, 1369, 1400, 1430},
61 PG_REGISTER_WITH_RESET_TEMPLATE(timeConfig_t, timeConfig, PG_TIME_CONFIG, 1);
63 PG_RESET_TEMPLATE(timeConfig_t, timeConfig,
64 .tz_offset = SETTING_TZ_OFFSET_DEFAULT,
65 .tz_automatic_dst = SETTING_TZ_AUTOMATIC_DST_DEFAULT,
68 static rtcTime_t dateTimeToRtcTime(const dateTime_t *dt)
70 unsigned int second = dt->seconds; // 0-59
71 unsigned int minute = dt->minutes; // 0-59
72 unsigned int hour = dt->hours; // 0-23
73 unsigned int day = dt->day - 1; // 0-30
74 unsigned int month = dt->month - 1; // 0-11
75 unsigned int year = dt->year - REFERENCE_YEAR; // 0-99
76 int32_t unixTime = (((year / 4 * (365 * 4 + 1) + days[year % 4][month] + day) * 24 + hour) * 60 + minute) * 60 + second + EPOCH_2000_OFFSET;
77 return rtcTimeMake(unixTime, dt->millis);
80 static void rtcTimeToDateTime(dateTime_t *dt, rtcTime_t t)
82 int32_t unixTime = t / MILLIS_PER_SECOND - EPOCH_2000_OFFSET;
83 dt->seconds = unixTime % 60;
84 unixTime /= 60;
85 dt->minutes = unixTime % 60;
86 unixTime /= 60;
87 dt->hours = unixTime % 24;
88 unixTime /= 24;
90 unsigned int years = unixTime / (365 * 4 + 1) * 4;
91 unixTime %= 365 * 4 + 1;
93 unsigned int year;
94 for (year = 3; year > 0; year--) {
95 if (unixTime >= days[year][0]) {
96 break;
100 unsigned int month;
101 for (month = 11; month > 0; month--) {
102 if (unixTime >= days[year][month]) {
103 break;
107 dt->year = years + year + REFERENCE_YEAR;
108 dt->month = month + 1;
109 dt->day = unixTime - days[year][month] + 1;
110 dt->millis = t % MILLIS_PER_SECOND;
113 static void rtcGetDefaultDateTime(dateTime_t *dateTime)
115 dateTime->year = 0;
116 dateTime->month = 1;
117 dateTime->day = 1;
118 dateTime->hours = 0;
119 dateTime->minutes = 0;
120 dateTime->seconds = 0;
121 dateTime->millis = 0;
124 static bool rtcIsDateTimeValid(dateTime_t *dateTime)
126 return (dateTime->year >= REFERENCE_YEAR) &&
127 (dateTime->month >= 1 && dateTime->month <= 12) &&
128 (dateTime->day >= 1 && dateTime->day <= 31) &&
129 (dateTime->hours <= 23) &&
130 (dateTime->minutes <= 59) &&
131 (dateTime->seconds <= 59) &&
132 (dateTime->millis <= 999);
135 #if defined(RTC_AUTOMATIC_DST)
136 static int lastSundayOfMonth(int currentYear, int wantedMonth)
138 int days[] = { 31 , 29 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 };
139 days[1] -= (currentYear % 4) || (!(currentYear % 100) && (currentYear % 400));
140 int w = currentYear * 365 + (currentYear - 1) / 4 - (currentYear - 1) / 100 + (currentYear - 1) / 400 + 6;
142 for (int m = 0; m < 12; m++) {
143 w = (w + days[m]) % 7;
144 if (m == wantedMonth - 1) {
145 return days[m] - w;
148 return 0;
151 static int nthSundayOfMonth(int lastSunday, int nth)
153 while (lastSunday > 7 * nth) {
154 lastSunday -= 7;
156 return lastSunday;
159 static bool isDST(rtcTime_t t)
161 dateTime_t dateTime;
162 rtcTimeToDateTime(&dateTime, t);
163 int lastSunday;
164 switch ((tz_automatic_dst_e) timeConfig()->tz_automatic_dst) {
165 case TZ_AUTO_DST_OFF:
166 break;
167 case TZ_AUTO_DST_EU: // begins at 1:00 a.m. on the last Sunday of March and ends at 1:00 a.m. on the last Sunday of October
168 if (dateTime.month < 3 || dateTime.month > 10) {
169 return false;
171 if (dateTime.month > 3 && dateTime.month < 10) {
172 return true;
174 lastSunday = lastSundayOfMonth(dateTime.year, dateTime.month);
175 if ((dateTime.day < lastSunday) || (dateTime.day > lastSunday)) {
176 return !(dateTime.month == 3);
178 if (dateTime.day == lastSunday) {
179 if (dateTime.month == 3) {
180 return dateTime.hours >= 1;
182 if (dateTime.month == 10) {
183 return dateTime.hours < 1;
186 break;
187 case TZ_AUTO_DST_USA: // begins at 2:00 a.m. on the second Sunday of March and ends at 2:00 a.m. on the first Sunday of November
188 if (dateTime.month < 3 || dateTime.month > 11) {
189 return false;
191 if (dateTime.month > 3 && dateTime.month < 11) {
192 return true;
194 lastSunday = lastSundayOfMonth(dateTime.year, dateTime.month);
195 if (dateTime.month == 3) {
196 int secondSunday = nthSundayOfMonth(lastSunday, 2);
197 if (dateTime.day == secondSunday) {
198 return dateTime.hours >= 2;
200 return dateTime.day > secondSunday;
202 if (dateTime.month == 11) {
203 int firstSunday = nthSundayOfMonth(lastSunday, 1);
204 if (dateTime.day == firstSunday) {
205 return dateTime.hours < 2;
207 return dateTime.day < firstSunday;
209 break;
211 return false;
213 #endif
215 static void dateTimeWithOffset(dateTime_t *dateTimeOffset, const dateTime_t *dateTimeInitial, int16_t *minutes, bool automatic_dst)
217 rtcTime_t initialTime = dateTimeToRtcTime(dateTimeInitial);
218 rtcTime_t offsetTime = rtcTimeMake(rtcTimeGetSeconds(&initialTime) + *minutes * 60, rtcTimeGetMillis(&initialTime));
219 #if defined(RTC_AUTOMATIC_DST)
220 if (automatic_dst && isDST(offsetTime)) {
221 // Add one hour. Tell the caller that the
222 // offset has changed.
223 *minutes += 60;
224 offsetTime += 60 * 60 * MILLIS_PER_SECOND;
226 #else
227 UNUSED(automatic_dst);
228 #endif
229 rtcTimeToDateTime(dateTimeOffset, offsetTime);
232 static bool dateTimeFormat(char *buf, dateTime_t *dateTime, int16_t offset, bool automatic_dst)
234 dateTime_t local;
236 int tz_hours = 0;
237 int tz_minutes = 0;
238 bool retVal = true;
240 // Apply offset if necessary
241 if (offset != 0 || automatic_dst) {
242 dateTimeWithOffset(&local, dateTime, &offset, automatic_dst);
243 tz_hours = offset / 60;
244 tz_minutes = ABS(offset % 60);
245 dateTime = &local;
248 if (!rtcIsDateTimeValid(dateTime)) {
249 rtcGetDefaultDateTime(&local);
250 dateTime = &local;
251 retVal = false;
254 // XXX: Changes to this format might require updates in
255 // dateTimeSplitFormatted()
256 tfp_sprintf(buf, "%04u-%02u-%02uT%02u:%02u:%02u.%03u%c%02d:%02d",
257 dateTime->year, dateTime->month, dateTime->day,
258 dateTime->hours, dateTime->minutes, dateTime->seconds, dateTime->millis,
259 tz_hours >= 0 ? '+' : '-', ABS(tz_hours), tz_minutes);
261 return retVal;
264 rtcTime_t rtcTimeMake(int32_t secs, uint16_t millis)
266 return ((rtcTime_t)secs) * MILLIS_PER_SECOND + millis;
269 int32_t rtcTimeGetSeconds(rtcTime_t *t)
271 return *t / MILLIS_PER_SECOND;
274 uint16_t rtcTimeGetMillis(rtcTime_t *t)
276 return *t % MILLIS_PER_SECOND;
279 bool dateTimeFormatUTC(char *buf, dateTime_t *dt)
281 return dateTimeFormat(buf, dt, 0, false);
284 bool dateTimeFormatLocal(char *buf, dateTime_t *dt)
286 return dateTimeFormat(buf, dt, timeConfig()->tz_offset, true);
289 void dateTimeUTCToLocal(dateTime_t *localDateTime, const dateTime_t *utcDateTime)
291 int16_t offset = timeConfig()->tz_offset;
292 dateTimeWithOffset(localDateTime, utcDateTime, &offset, true);
295 bool dateTimeSplitFormatted(char *formatted, char **date, char **time)
297 // Just look for the T and replace it with a zero
298 // XXX: Keep in sync with dateTimeFormat()
299 for (char *p = formatted; *p; p++) {
300 if (*p == 'T') {
301 *date = formatted;
302 *time = (p+1);
303 *p = '\0';
304 return true;
307 return false;
310 bool rtcHasTime(void)
312 return started != 0;
315 bool rtcGet(rtcTime_t *t)
317 #ifdef SITL_BUILD
318 *t = (rtcTime_t)(time(NULL) * 1000);
319 return true;
320 #else
321 if (!rtcHasTime()) {
322 return false;
324 *t = started + millis();
325 return true;
326 #endif
329 bool rtcSet(rtcTime_t *t)
331 started = *t - millis();
332 return true;
336 bool rtcGetDateTime(dateTime_t *dt)
338 rtcTime_t t;
339 if (rtcGet(&t)) {
340 rtcTimeToDateTime(dt, t);
341 return true;
343 // No time stored, fill dt with 0000-01-01T00:00:00.000
344 rtcGetDefaultDateTime(dt);
345 return false;
348 bool rtcGetDateTimeLocal(dateTime_t *dt)
350 if (rtcGetDateTime(dt)) {
351 dateTimeUTCToLocal(dt, dt);
352 return true;
354 return false;
357 bool rtcSetDateTime(dateTime_t *dt)
359 rtcTime_t t = dateTimeToRtcTime(dt);
360 return rtcSet(&t);