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 	memset(&datetime_get, 0xFF, sizeof(datetime_get));
31 
32 	zassert_equal(rtc_set_time(rtc, &datetime_set), 0, "Failed to set time");
33 
34 	zassert_equal(rtc_get_time(rtc, &datetime_get), 0,
35 		      "Failed to get time using rtc_time_get()");
36 
37 	zassert_true((datetime_get.tm_sec > -1) && (datetime_get.tm_sec < 60),
38 		     "Invalid tm_sec");
39 
40 	zassert_true((datetime_get.tm_min > -1) && (datetime_get.tm_min < 60),
41 		     "Invalid tm_min");
42 
43 	zassert_true((datetime_get.tm_hour > -1) && (datetime_get.tm_hour < 24),
44 		     "Invalid tm_hour");
45 
46 	zassert_true((datetime_get.tm_mday > 0) && (datetime_get.tm_mday < 32),
47 		      "Invalid tm_mday");
48 
49 	zassert_true((datetime_get.tm_year > 124) && (datetime_get.tm_year < 127),
50 		     "Invalid tm_year");
51 
52 	zassert_true((datetime_get.tm_wday > -2) && (datetime_get.tm_wday < 7),
53 		     "Invalid tm_wday");
54 
55 	zassert_true((datetime_get.tm_yday > -2) && (datetime_get.tm_yday < 366),
56 		     "Invalid tm_yday");
57 
58 	zassert_equal(datetime_get.tm_isdst, -1, "Invalid tm_isdst");
59 
60 	zassert_true((datetime_get.tm_nsec > -1) && (datetime_get.tm_yday < 1000000000),
61 		     "Invalid tm_yday");
62 
63 	timer_get = timeutil_timegm((struct tm *)(&datetime_get));
64 
65 	zassert_true((timer_get >= RTC_TEST_GET_SET_TIME) &&
66 		     (timer_get <= (RTC_TEST_GET_SET_TIME + RTC_TEST_GET_SET_TIME_TOL)),
67 		     "Got unexpected time");
68 }
69