1 /*
2  * Copyright 2022 Bjarki Arge Andreasen
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/ztest.h>
8 #include <zephyr/device.h>
9 #include <zephyr/drivers/rtc.h>
10 #include <zephyr/sys/timeutil.h>
11 
12 #include <time.h>
13 #include <string.h>
14 
15 /* Wed Dec 31 2025 23:59:55 GMT+0000 */
16 #define RTC_TEST_GET_SET_TIME	  (1767225595UL)
17 #define RTC_TEST_GET_SET_TIME_TOL (1UL)
18 
19 static const struct device *rtc = DEVICE_DT_GET(DT_ALIAS(rtc));
20 
ZTEST(rtc_api,test_set_get_time)21 ZTEST(rtc_api, test_set_get_time)
22 {
23 	struct rtc_time datetime_set;
24 	struct rtc_time datetime_get;
25 	time_t timer_get;
26 	time_t timer_set = RTC_TEST_GET_SET_TIME;
27 
28 	gmtime_r(&timer_set, (struct tm *)(&datetime_set));
29 
30 	datetime_set.tm_isdst = -1;
31 	datetime_set.tm_nsec = 0;
32 
33 	memset(&datetime_get, 0xFF, sizeof(datetime_get));
34 
35 	zassert_equal(rtc_set_time(rtc, &datetime_set), 0, "Failed to set time");
36 
37 	zassert_equal(rtc_get_time(rtc, &datetime_get), 0,
38 		      "Failed to get time using rtc_time_get()");
39 
40 	zassert_true((datetime_get.tm_sec > -1) && (datetime_get.tm_sec < 60),
41 		     "Invalid tm_sec");
42 
43 	zassert_true((datetime_get.tm_min > -1) && (datetime_get.tm_min < 60),
44 		     "Invalid tm_min");
45 
46 	zassert_true((datetime_get.tm_hour > -1) && (datetime_get.tm_hour < 24),
47 		     "Invalid tm_hour");
48 
49 	zassert_true((datetime_get.tm_mday > 0) && (datetime_get.tm_mday < 32),
50 		      "Invalid tm_mday");
51 
52 	zassert_true((datetime_get.tm_year > 124) && (datetime_get.tm_year < 127),
53 		     "Invalid tm_year");
54 
55 	zassert_true((datetime_get.tm_wday > -2) && (datetime_get.tm_wday < 7),
56 		     "Invalid tm_wday");
57 
58 	zassert_true((datetime_get.tm_yday > -2) && (datetime_get.tm_yday < 366),
59 		     "Invalid tm_yday");
60 
61 	zassert_equal(datetime_get.tm_isdst, -1, "Invalid tm_isdst");
62 
63 	zassert_true((datetime_get.tm_nsec > -1) && (datetime_get.tm_nsec < 1000000000),
64 		     "Invalid tm_nsec");
65 
66 	timer_get = timeutil_timegm((struct tm *)(&datetime_get));
67 
68 	zassert_true((timer_get >= RTC_TEST_GET_SET_TIME) &&
69 		     (timer_get <= (RTC_TEST_GET_SET_TIME + RTC_TEST_GET_SET_TIME_TOL)),
70 		     "Got unexpected time");
71 }
72