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/kernel.h>
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/rtc.h>
11 
12 #define RTC_TEST_CAL_RANGE_LIMIT (200000)
13 #define RTC_TEST_CAL_RANGE_STEP	 (10000)
14 
15 static const struct device *rtc = DEVICE_DT_GET(DT_ALIAS(rtc));
16 
test_set_get_calibration(int32_t calibrate_set)17 static int test_set_get_calibration(int32_t calibrate_set)
18 {
19 	int32_t calibrate_get;
20 	int ret;
21 
22 	ret = rtc_set_calibration(rtc, calibrate_set);
23 
24 	/* Check if calibration is within limits of hardware */
25 	if (ret == -EINVAL) {
26 		/* skip */
27 		return -EINVAL;
28 	}
29 
30 	/* Validate calibration was set */
31 	zassert_ok(ret, "Failed to set calibration");
32 
33 	ret = rtc_get_calibration(rtc, &calibrate_get);
34 
35 	/* Validate calibration was gotten */
36 	zassert_ok(ret, "Failed to get calibration");
37 
38 	/* Print comparison between set and get values */
39 	printk("Calibrate (set,get): %i, %i\n", calibrate_set, calibrate_get);
40 
41 	return 0;
42 }
43 
ZTEST(rtc_api,test_set_get_calibration)44 ZTEST(rtc_api, test_set_get_calibration)
45 {
46 	int32_t calibrate_get;
47 	int ret;
48 	int32_t range_limit;
49 	int32_t range_step;
50 
51 	ret = rtc_set_calibration(rtc, 0);
52 
53 	/* Validate calibration was set */
54 	zassert_ok(ret, "Failed to set calibration");
55 
56 	ret = rtc_get_calibration(rtc, &calibrate_get);
57 
58 	/* Validate calibration was gotten */
59 	zassert_ok(ret, "Failed to get calibration");
60 
61 	/* Validate edge values (0 already tested) */
62 	test_set_get_calibration(1);
63 	test_set_get_calibration(-1);
64 
65 	range_limit = RTC_TEST_CAL_RANGE_LIMIT;
66 	range_step = RTC_TEST_CAL_RANGE_STEP;
67 
68 	/* Validate over negative range */
69 	for (int32_t set = range_step; set <= range_limit; set += range_step) {
70 		ret = test_set_get_calibration(-set);
71 
72 		if (ret < 0) {
73 			/* Limit of hardware capabilties reached */
74 			break;
75 		}
76 	}
77 
78 	/* Validate over positive range */
79 	for (int32_t set = range_step; set <= range_limit; set += range_step) {
80 		ret = test_set_get_calibration(set);
81 
82 		if (ret < 0) {
83 			/* Limit of hardware capabilties reached */
84 			break;
85 		}
86 	}
87 }
88