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/atomic.h>
11
12 static const struct device *rtc = DEVICE_DT_GET(DT_ALIAS(rtc));
13 static uint32_t callback_called_counter;
14 static void *callback_test_user_data_address;
15 static uint32_t test_user_data = 0x1234;
16 static struct k_spinlock lock;
17
test_rtc_update_callback_handler(const struct device * dev,void * user_data)18 static void test_rtc_update_callback_handler(const struct device *dev, void *user_data)
19 {
20 k_spinlock_key_t key = k_spin_lock(&lock);
21
22 callback_called_counter++;
23 callback_test_user_data_address = user_data;
24
25 k_spin_unlock(&lock, key);
26 }
27
ZTEST(rtc_api,test_update_callback)28 ZTEST(rtc_api, test_update_callback)
29 {
30 int ret;
31 k_spinlock_key_t key;
32 uint32_t counter;
33 void *address;
34
35 ret = rtc_update_set_callback(rtc, NULL, NULL);
36
37 if (ret == -ENOSYS) {
38 ztest_test_skip();
39 } else {
40 zassert_ok(ret, "Failed to clear and disable update callback");
41 }
42
43 key = k_spin_lock(&lock);
44
45 callback_called_counter = 0;
46 address = callback_test_user_data_address;
47
48 k_spin_unlock(&lock, key);
49
50 k_msleep(5000);
51
52 key = k_spin_lock(&lock);
53
54 counter = callback_called_counter;
55
56 k_spin_unlock(&lock, key);
57
58 zassert_equal(counter, 0, "Update callback should not have been called");
59
60 ret = rtc_update_set_callback(rtc, test_rtc_update_callback_handler, &test_user_data);
61
62 zassert_ok(ret, "Failed to set and enable update callback");
63
64 k_msleep(10000);
65
66 key = k_spin_lock(&lock);
67
68 counter = callback_called_counter;
69 address = callback_test_user_data_address;
70
71 k_spin_unlock(&lock, key);
72
73 zassert_true(counter < 12 && counter > 8, "Invalid update callback called counter");
74
75 zassert_equal(address, ((void *)&test_user_data), "Incorrect user data");
76 }
77