1 /*
2 * Copyright 2023 Fabian Blatz <fabianblatz@gmail.com>
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #define DT_DRV_COMPAT zephyr_lvgl_encoder_input
8
9 #include "lvgl_common_input.h"
10 #include "lvgl_encoder_input.h"
11
12 #include <zephyr/logging/log.h>
13
14 LOG_MODULE_DECLARE(lvgl);
15
16 struct lvgl_encoder_input_config {
17 struct lvgl_common_input_config common_config; /* Needs to be first member */
18 int rotation_input_code;
19 int button_input_code;
20 };
21
lvgl_encoder_process_event(const struct device * dev,struct input_event * evt)22 static void lvgl_encoder_process_event(const struct device *dev, struct input_event *evt)
23 {
24 struct lvgl_common_input_data *data = dev->data;
25 const struct lvgl_encoder_input_config *cfg = dev->config;
26
27 if (evt->code == cfg->rotation_input_code) {
28 data->pending_event.enc_diff = evt->value;
29 } else if (evt->code == cfg->button_input_code) {
30 data->pending_event.state = evt->value ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL;
31 } else {
32 LOG_DBG("Ignored input event: %u", evt->code);
33 return;
34 }
35
36 if (k_msgq_put(cfg->common_config.event_msgq, &data->pending_event, K_NO_WAIT) != 0) {
37 LOG_WRN("Could not put input data into queue");
38 }
39 }
40
lvgl_encoder_input_init(const struct device * dev)41 int lvgl_encoder_input_init(const struct device *dev)
42 {
43 return lvgl_input_register_driver(LV_INDEV_TYPE_ENCODER, dev);
44 }
45
46 #define BUTTON_CODE(inst) DT_INST_PROP_OR(inst, button_input_code, -1)
47 #define ROTATION_CODE(inst) DT_INST_PROP(inst, rotation_input_code)
48
49 #define ASSERT_PROPERTIES(inst) \
50 BUILD_ASSERT(IN_RANGE(ROTATION_CODE(inst), 0, 65536), \
51 "Property rotation-input-code needs to be between 0 and 65536."); \
52 BUILD_ASSERT(!DT_INST_NODE_HAS_PROP(inst, button_input_code) || \
53 IN_RANGE(BUTTON_CODE(inst), 0, 65536), \
54 "Property button-input-code needs to be between 0 and 65536."); \
55 BUILD_ASSERT(ROTATION_CODE(inst) != BUTTON_CODE(inst), \
56 "Property rotation-input-code and button-input-code should not be equal.")
57
58 #define LVGL_ENCODER_INPUT_DEFINE(inst) \
59 ASSERT_PROPERTIES(inst); \
60 LVGL_INPUT_DEFINE(inst, encoder, CONFIG_LV_Z_ENCODER_INPUT_MSGQ_COUNT, \
61 lvgl_encoder_process_event); \
62 static const struct lvgl_encoder_input_config lvgl_encoder_input_config_##inst = { \
63 .common_config.event_msgq = &LVGL_INPUT_EVENT_MSGQ(inst, encoder), \
64 .rotation_input_code = ROTATION_CODE(inst), \
65 .button_input_code = BUTTON_CODE(inst), \
66 }; \
67 static struct lvgl_common_input_data lvgl_common_input_data_##inst; \
68 DEVICE_DT_INST_DEFINE(inst, NULL, NULL, &lvgl_common_input_data_##inst, \
69 &lvgl_encoder_input_config_##inst, POST_KERNEL, \
70 CONFIG_INPUT_INIT_PRIORITY, NULL);
71
72 DT_INST_FOREACH_STATUS_OKAY(LVGL_ENCODER_INPUT_DEFINE)
73