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_callback, callback) {
24 if (callback->dev == NULL || callback->dev == evt->dev) {
25 callback->callback(evt, callback->user_data);
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 int ret;
54
55 if (!K_TIMEOUT_EQ(timeout, K_NO_WAIT) &&
56 k_current_get() == k_work_queue_thread_get(&k_sys_work_q)) {
57 LOG_DBG("Timeout discarded. No blocking in syswq.");
58 timeout = K_NO_WAIT;
59 }
60
61 ret = k_msgq_put(&input_msgq, &evt, timeout);
62 if (ret < 0) {
63 LOG_WRN("Event dropped, queue full, not blocking in syswq.");
64 return ret;
65 }
66
67 return 0;
68 #else
69 input_process(&evt);
70 return 0;
71 #endif
72 }
73
74 #ifdef CONFIG_INPUT_MODE_THREAD
75
input_thread(void)76 static void input_thread(void)
77 {
78 struct input_event evt;
79 int ret;
80
81 while (true) {
82 ret = k_msgq_get(&input_msgq, &evt, K_FOREVER);
83 if (ret) {
84 LOG_ERR("k_msgq_get error: %d", ret);
85 continue;
86 }
87
88 input_process(&evt);
89 }
90 }
91
92 #define INPUT_THREAD_PRIORITY \
93 COND_CODE_1(CONFIG_INPUT_THREAD_PRIORITY_OVERRIDE, \
94 (CONFIG_INPUT_THREAD_PRIORITY), (K_LOWEST_APPLICATION_THREAD_PRIO))
95
96 K_THREAD_DEFINE(input,
97 CONFIG_INPUT_THREAD_STACK_SIZE,
98 input_thread,
99 NULL, NULL, NULL,
100 INPUT_THREAD_PRIORITY, 0, 0);
101
102 #endif /* CONFIG_INPUT_MODE_THREAD */
103