1 /*
2  * Copyright (c) 2016, Freescale Semiconductor, Inc.
3  * Copyright 2016-2020 NXP
4  * All rights reserved.
5  *
6  * SPDX-License-Identifier: BSD-3-Clause
7  */
8 
9 #include "fsl_rtc.h"
10 
11 /*******************************************************************************
12  * Definitions
13  ******************************************************************************/
14 
15 /* Component ID definition, used by tools. */
16 #ifndef FSL_COMPONENT_ID
17 #define FSL_COMPONENT_ID "platform.drivers.lpc_rtc"
18 #endif
19 
20 #define SECONDS_IN_A_DAY    (86400U)
21 #define SECONDS_IN_A_HOUR   (3600U)
22 #define SECONDS_IN_A_MINUTE (60U)
23 #define DAYS_IN_A_YEAR      (365U)
24 #define YEAR_RANGE_START    (1970U)
25 #define YEAR_RANGE_END      (2099U)
26 
27 /*******************************************************************************
28  * Prototypes
29  ******************************************************************************/
30 /*!
31  * @brief Check whether the date and time passed in is valid
32  *
33  * @param datetime Pointer to structure where the date and time details are stored
34  *
35  * @return Returns false if the date & time details are out of range; true if in range
36  */
37 static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime);
38 
39 /*!
40  * @brief Convert time data from datetime to seconds
41  *
42  * @param datetime Pointer to datetime structure where the date and time details are stored
43  *
44  * @return The result of the conversion in seconds
45  */
46 static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime);
47 
48 /*!
49  * @brief Convert time data from seconds to a datetime structure
50  *
51  * @param seconds  Seconds value that needs to be converted to datetime format
52  * @param datetime Pointer to the datetime structure where the result of the conversion is stored
53  */
54 static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime);
55 
56 /*******************************************************************************
57  * Code
58  ******************************************************************************/
RTC_CheckDatetimeFormat(const rtc_datetime_t * datetime)59 static bool RTC_CheckDatetimeFormat(const rtc_datetime_t *datetime)
60 {
61     assert(datetime);
62 
63     /* Table of days in a month for a non leap year. First entry in the table is not used,
64      * valid months start from 1
65      */
66     uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U};
67 
68     /* Check year, month, hour, minute, seconds */
69     if ((datetime->year < YEAR_RANGE_START) || (datetime->year > YEAR_RANGE_END) || (datetime->month > 12U) ||
70         (datetime->month < 1U) || (datetime->hour >= 24U) || (datetime->minute >= 60U) || (datetime->second >= 60U))
71     {
72         /* If not correct then error*/
73         return false;
74     }
75 
76     /* Adjust the days in February for a leap year */
77     if ((((datetime->year & 3U) == 0U) && (datetime->year % 100U != 0U)) || (datetime->year % 400U == 0U))
78     {
79         daysPerMonth[2] = 29U;
80     }
81 
82     /* Check the validity of the day */
83     if ((datetime->day > daysPerMonth[datetime->month]) || (datetime->day < 1U))
84     {
85         return false;
86     }
87 
88     return true;
89 }
90 
RTC_ConvertDatetimeToSeconds(const rtc_datetime_t * datetime)91 static uint32_t RTC_ConvertDatetimeToSeconds(const rtc_datetime_t *datetime)
92 {
93     assert(datetime);
94 
95     /* Number of days from begin of the non Leap-year*/
96     /* Number of days from begin of the non Leap-year*/
97     uint16_t monthDays[] = {0U, 0U, 31U, 59U, 90U, 120U, 151U, 181U, 212U, 243U, 273U, 304U, 334U};
98     uint32_t seconds;
99 
100     /* Compute number of days from 1970 till given year*/
101     seconds = ((uint32_t)datetime->year - 1970U) * DAYS_IN_A_YEAR;
102     /* Add leap year days */
103     seconds += (((uint32_t)datetime->year / 4U) - (1970U / 4U));
104     /* Add number of days till given month*/
105     seconds += monthDays[datetime->month];
106     /* Add days in given month. We subtract the current day as it is
107      * represented in the hours, minutes and seconds field*/
108     seconds += ((uint32_t)datetime->day - 1U);
109     /* For leap year if month less than or equal to Febraury, decrement day counter*/
110     if (((datetime->year & 3U) == 0x00U) && (datetime->month <= 2U))
111     {
112         seconds--;
113     }
114 
115     seconds = (seconds * SECONDS_IN_A_DAY) + (datetime->hour * SECONDS_IN_A_HOUR) +
116               (datetime->minute * SECONDS_IN_A_MINUTE) + datetime->second;
117 
118     return seconds;
119 }
120 
RTC_ConvertSecondsToDatetime(uint32_t seconds,rtc_datetime_t * datetime)121 static void RTC_ConvertSecondsToDatetime(uint32_t seconds, rtc_datetime_t *datetime)
122 {
123     assert(datetime);
124 
125     uint8_t i;
126     uint16_t daysInYear;
127     uint32_t secondsRemaining;
128     uint32_t days;
129     /* Table of days in a month for a non leap year. First entry in the table is not used,
130      * valid months start from 1
131      */
132     uint8_t daysPerMonth[] = {0U, 31U, 28U, 31U, 30U, 31U, 30U, 31U, 31U, 30U, 31U, 30U, 31U};
133 
134     /* Start with the seconds value that is passed in to be converted to date time format */
135     secondsRemaining = seconds;
136 
137     /* Calcuate the number of days, we add 1 for the current day which is represented in the
138      * hours and seconds field
139      */
140     days = secondsRemaining / SECONDS_IN_A_DAY + 1U;
141 
142     /* Update seconds left*/
143     secondsRemaining = secondsRemaining % SECONDS_IN_A_DAY;
144 
145     /* Calculate the datetime hour, minute and second fields */
146     datetime->hour   = (uint8_t)(secondsRemaining / SECONDS_IN_A_HOUR);
147     secondsRemaining = secondsRemaining % SECONDS_IN_A_HOUR;
148     datetime->minute = (uint8_t)(secondsRemaining / 60U);
149     datetime->second = (uint8_t)(secondsRemaining % SECONDS_IN_A_MINUTE);
150 
151     /* Calculate year */
152     daysInYear     = DAYS_IN_A_YEAR;
153     datetime->year = YEAR_RANGE_START;
154     while (days > daysInYear)
155     {
156         /* Decrease day count by a year and increment year by 1 */
157         days -= daysInYear;
158         datetime->year++;
159 
160         /* Adjust the number of days for a leap year */
161         if ((datetime->year & 3U) != 0x00U)
162         {
163             daysInYear = DAYS_IN_A_YEAR;
164         }
165         else
166         {
167             daysInYear = DAYS_IN_A_YEAR + 1U;
168         }
169     }
170 
171     /* Adjust the days in February for a leap year */
172     if ((datetime->year & 3U) == 0x00U)
173     {
174         daysPerMonth[2] = 29U;
175     }
176 
177     for (i = 1U; i <= 12U; i++)
178     {
179         if (days <= daysPerMonth[i])
180         {
181             datetime->month = i;
182             break;
183         }
184         else
185         {
186             days -= daysPerMonth[i];
187         }
188     }
189 
190     datetime->day = (uint8_t)days;
191 }
192 
193 /*!
194  * brief Ungate the RTC clock and enables the RTC oscillator.
195  *
196  * note This API should be called at the beginning of the application using the RTC driver.
197  *
198  * param base RTC peripheral base address
199  */
RTC_Init(RTC_Type * base)200 void RTC_Init(RTC_Type *base)
201 {
202 #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL)
203     /* Enable the RTC peripheral clock */
204     CLOCK_EnableClock(kCLOCK_Rtc);
205 #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */
206 
207 #if !(defined(FSL_FEATURE_RTC_HAS_NO_RESET) && FSL_FEATURE_RTC_HAS_NO_RESET)
208     RESET_PeripheralReset(kRTC_RST_SHIFT_RSTn);
209 #endif
210     /* Make sure the reset bit is cleared */
211     base->CTRL &= ~RTC_CTRL_SWRESET_MASK;
212 
213 #if !(defined(FSL_FEATURE_RTC_HAS_NO_OSC_PD) && FSL_FEATURE_RTC_HAS_NO_OSC_PD)
214     /* Make sure the RTC OSC is powered up */
215     base->CTRL &= ~RTC_CTRL_RTC_OSC_PD_MASK;
216 #endif
217 }
218 
219 /*!
220  * brief Set the RTC date and time according to the given time structure.
221  *
222  * The RTC counter must be stopped prior to calling this function as writes to the RTC
223  * seconds register will fail if the RTC counter is running.
224  *
225  * param base     RTC peripheral base address
226  * param datetime Pointer to structure where the date and time details to set are stored
227  *
228  * return kStatus_Success: Success in setting the time and starting the RTC
229  *         kStatus_InvalidArgument: Error because the datetime format is incorrect
230  */
RTC_SetDatetime(RTC_Type * base,const rtc_datetime_t * datetime)231 status_t RTC_SetDatetime(RTC_Type *base, const rtc_datetime_t *datetime)
232 {
233     assert(datetime);
234 
235     /* Return error if the time provided is not valid */
236     if (!(RTC_CheckDatetimeFormat(datetime)))
237     {
238         return kStatus_InvalidArgument;
239     }
240 
241     /* Set time in seconds */
242     base->COUNT = RTC_ConvertDatetimeToSeconds(datetime);
243 
244     return kStatus_Success;
245 }
246 
247 /*!
248  * brief Gets the RTC time and stores it in the given time structure.
249  *
250  * param base     RTC peripheral base address
251  * param datetime Pointer to structure where the date and time details are stored.
252  */
RTC_GetDatetime(RTC_Type * base,rtc_datetime_t * datetime)253 void RTC_GetDatetime(RTC_Type *base, rtc_datetime_t *datetime)
254 {
255     assert(datetime);
256 
257     uint32_t seconds = 0;
258 
259     seconds = RTC_GetSecondsTimerCount(base);
260     RTC_ConvertSecondsToDatetime(seconds, datetime);
261 }
262 
263 /*!
264  * brief Set the RTC alarm time
265  *
266  * The function checks whether the specified alarm time is greater than the present
267  * time. If not, the function does not set the alarm and returns an error.
268  *
269  * param base      RTC peripheral base address
270  * param alarmTime Pointer to structure where the alarm time is stored.
271  *
272  * return kStatus_Success: success in setting the RTC alarm
273  *         kStatus_InvalidArgument: Error because the alarm datetime format is incorrect
274  *         kStatus_Fail: Error because the alarm time has already passed
275  */
RTC_SetAlarm(RTC_Type * base,const rtc_datetime_t * alarmTime)276 status_t RTC_SetAlarm(RTC_Type *base, const rtc_datetime_t *alarmTime)
277 {
278     assert(alarmTime != NULL);
279 
280     uint32_t alarmSeconds = 0;
281     uint32_t currSeconds  = 0;
282 
283     /* Return error if the alarm time provided is not valid */
284     if (!(RTC_CheckDatetimeFormat(alarmTime)))
285     {
286         return kStatus_InvalidArgument;
287     }
288 
289     alarmSeconds = RTC_ConvertDatetimeToSeconds(alarmTime);
290 
291     /* Get the current time */
292     currSeconds = RTC_GetSecondsTimerCount(base);
293 
294     /* Return error if the alarm time has passed */
295     if (alarmSeconds < currSeconds)
296     {
297         return kStatus_Fail;
298     }
299 
300     /* Set alarm in seconds*/
301     base->MATCH = alarmSeconds;
302 
303     return kStatus_Success;
304 }
305 
306 /*!
307  * brief Return the RTC alarm time.
308  *
309  * param base     RTC peripheral base address
310  * param datetime Pointer to structure where the alarm date and time details are stored.
311  */
RTC_GetAlarm(RTC_Type * base,rtc_datetime_t * datetime)312 void RTC_GetAlarm(RTC_Type *base, rtc_datetime_t *datetime)
313 {
314     assert(datetime);
315 
316     uint32_t alarmSeconds = 0;
317 
318     /* Get alarm in seconds  */
319     alarmSeconds = base->MATCH;
320 
321     RTC_ConvertSecondsToDatetime(alarmSeconds, datetime);
322 }
323