1 /*
2  * Copyright 2024 Trackunit Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/gnss.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/sys/atomic.h>
10 #include <zephyr/ztest.h>
11 
12 #define TEST_VALIDATE_PERIOD_MS 10000
13 #define TEST_VALIDATE_PERIOD    K_MSEC(TEST_VALIDATE_PERIOD_MS)
14 
15 #define TEST_MIN_CALLBACK_COUNT(_fix_interval) \
16 	(((TEST_VALIDATE_PERIOD_MS / _fix_interval) / 5) * 4)
17 
18 #define TEST_MAX_CALLBACK_COUNT(_fix_interval) \
19 	(((TEST_VALIDATE_PERIOD_MS / _fix_interval) / 5) * 6)
20 
21 #define TEST_CONFIG_DEFINE(_fix_interval)					\
22 	{									\
23 		.fix_interval = _fix_interval,					\
24 		.min_callback_count = TEST_MIN_CALLBACK_COUNT(_fix_interval),	\
25 		.max_callback_count = TEST_MAX_CALLBACK_COUNT(_fix_interval),	\
26 	}
27 
28 static const struct device *dev = DEVICE_DT_GET(DT_ALIAS(gnss));
29 
30 struct test_config {
31 	uint32_t fix_interval;
32 	uint32_t min_callback_count;
33 	uint32_t max_callback_count;
34 };
35 
36 static const struct test_config configs[] = {
37 	TEST_CONFIG_DEFINE(100),
38 	TEST_CONFIG_DEFINE(500),
39 	TEST_CONFIG_DEFINE(1000),
40 	TEST_CONFIG_DEFINE(2000),
41 };
42 
43 static atomic_t callback_count_atom = ATOMIC_INIT(0);
44 
gnss_data_cb(const struct device * dev,const struct gnss_data * data)45 static void gnss_data_cb(const struct device *dev, const struct gnss_data *data)
46 {
47 	atomic_inc(&callback_count_atom);
48 }
49 
50 GNSS_DATA_CALLBACK_DEFINE(DEVICE_DT_GET(DT_ALIAS(gnss)), gnss_data_cb);
51 
test_set_fix_rate(const struct test_config * config)52 static bool test_set_fix_rate(const struct test_config *config)
53 {
54 	int ret;
55 
56 	ret = gnss_set_fix_rate(dev, config->fix_interval);
57 	if (ret == -ENOSYS) {
58 		ztest_test_skip();
59 	}
60 	if (ret == -EINVAL) {
61 		return false;
62 	}
63 	zassert_ok(ret, "failed to set fix rate %u", config->fix_interval);
64 	return true;
65 }
66 
test_validate_fix_rate(const struct test_config * config)67 static void test_validate_fix_rate(const struct test_config *config)
68 {
69 	bool valid;
70 	uint32_t callback_count;
71 
72 	atomic_set(&callback_count_atom, 0);
73 	k_sleep(TEST_VALIDATE_PERIOD);
74 	callback_count = atomic_get(&callback_count_atom);
75 	valid = (callback_count >= config->min_callback_count) &&
76 		(callback_count <= config->max_callback_count);
77 	zassert_true(valid, "callback count %u invalid", callback_count);
78 }
79 
ZTEST(gnss_api,test_fix_rate)80 ZTEST(gnss_api, test_fix_rate)
81 {
82 	for (uint32_t i = 0; i < ARRAY_SIZE(configs); i++) {
83 		if (!test_set_fix_rate(&configs[i])) {
84 			continue;
85 		}
86 		test_validate_fix_rate(&configs[i]);
87 	}
88 }
89