1 /*
2 * Copyright 2023 Google LLC
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/input/input.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/logging/log.h>
10 #include <zephyr/sys/iterable_sections.h>
11
12 LOG_MODULE_REGISTER(input, CONFIG_INPUT_LOG_LEVEL);
13
14 #ifdef CONFIG_INPUT_MODE_THREAD
15
16 K_MSGQ_DEFINE(input_msgq, sizeof(struct input_event),
17 CONFIG_INPUT_QUEUE_MAX_MSGS, 4);
18
19 #endif
20
input_process(struct input_event * evt)21 static void input_process(struct input_event *evt)
22 {
23 STRUCT_SECTION_FOREACH(input_listener, listener) {
24 if (listener->dev == NULL || listener->dev == evt->dev) {
25 listener->callback(evt);
26 }
27 }
28 }
29
input_queue_empty(void)30 bool input_queue_empty(void)
31 {
32 #ifdef CONFIG_INPUT_MODE_THREAD
33 if (k_msgq_num_used_get(&input_msgq) > 0) {
34 return false;
35 }
36 #endif
37 return true;
38 }
39
input_report(const struct device * dev,uint8_t type,uint16_t code,int32_t value,bool sync,k_timeout_t timeout)40 int input_report(const struct device *dev,
41 uint8_t type, uint16_t code, int32_t value, bool sync,
42 k_timeout_t timeout)
43 {
44 struct input_event evt = {
45 .dev = dev,
46 .sync = sync,
47 .type = type,
48 .code = code,
49 .value = value,
50 };
51
52 #ifdef CONFIG_INPUT_MODE_THREAD
53 return k_msgq_put(&input_msgq, &evt, timeout);
54 #else
55 input_process(&evt);
56 return 0;
57 #endif
58 }
59
60 #ifdef CONFIG_INPUT_MODE_THREAD
61
input_thread(void)62 static void input_thread(void)
63 {
64 struct input_event evt;
65 int ret;
66
67 while (true) {
68 ret = k_msgq_get(&input_msgq, &evt, K_FOREVER);
69 if (ret) {
70 LOG_ERR("k_msgq_get error: %d", ret);
71 continue;
72 }
73
74 input_process(&evt);
75 }
76 }
77
78 #define INPUT_THREAD_PRIORITY \
79 COND_CODE_1(CONFIG_INPUT_THREAD_PRIORITY_OVERRIDE, \
80 (CONFIG_INPUT_THREAD_PRIORITY), (K_LOWEST_APPLICATION_THREAD_PRIO))
81
82 K_THREAD_DEFINE(input,
83 CONFIG_INPUT_THREAD_STACK_SIZE,
84 input_thread,
85 NULL, NULL, NULL,
86 INPUT_THREAD_PRIORITY, 0, 0);
87
88 #endif /* CONFIG_INPUT_MODE_THREAD */
89