summaryrefslogtreecommitdiff
path: root/src/ui/encoder_input.cpp
blob: 9aa5d29a2b38ebe65ca65276f206de19e53a6a4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
 * Copyright 2023 jacqueline <me@jacqueline.id.au>
 *
 * SPDX-License-Identifier: GPL-3.0-only
 */

#include "encoder_input.hpp"

#include <sys/_stdint.h>
#include <memory>

#include "core/lv_group.h"
#include "esp_timer.h"
#include "gpios.hpp"
#include "hal/lv_hal_indev.h"
#include "nvs.hpp"
#include "relative_wheel.hpp"
#include "touchwheel.hpp"

constexpr int kDPadAngleThreshold = 20;
constexpr int kLongPressDelayMs = 500;
constexpr int kRepeatDelayMs = 250;

static inline auto IsAngleWithin(int16_t wheel_angle,
                                 int16_t target_angle,
                                 int threshold) -> bool {
  int16_t difference = (wheel_angle - target_angle + 127 + 255) % 255 - 127;
  return difference <= threshold && difference >= -threshold;
}

namespace ui {

static void encoder_read(lv_indev_drv_t* drv, lv_indev_data_t* data) {
  EncoderInput* instance = reinterpret_cast<EncoderInput*>(drv->user_data);
  instance->Read(data);
}

EncoderInput::EncoderInput(drivers::IGpios& gpios, drivers::TouchWheel& wheel)
    : gpios_(gpios),
      raw_wheel_(wheel),
      relative_wheel_(std::make_unique<drivers::RelativeWheel>(wheel)),
      scroller_(std::make_unique<Scroller>()),
      mode_(drivers::NvsStorage::InputModes::kRotatingWheel),
      is_locked_(false) {
  lv_indev_drv_init(&driver_);
  driver_.type = LV_INDEV_TYPE_ENCODER;
  driver_.read_cb = encoder_read;
  driver_.user_data = this;

  registration_ = lv_indev_drv_register(&driver_);
}

auto EncoderInput::Read(lv_indev_data_t* data) -> void {
  if (is_locked_) {
    return;
  }

  raw_wheel_.Update();
  relative_wheel_->Update();
  // GPIOs updating is handled by system_fsm.

  uint64_t now_ms = esp_timer_get_time() / 1000;

  // Deal with the potential overflow of our timer.
  for (auto& it : touch_time_ms_) {
    if (it.second > now_ms) {
      // esp_timer overflowed.
      it.second = 0;
    }
  }

  // Check each button.
  HandleKey(Keys::kVolumeUp, now_ms, !gpios_.Get(drivers::IGpios::Pin::kKeyUp));
  HandleKey(Keys::kVolumeDown, now_ms,
            !gpios_.Get(drivers::IGpios::Pin::kKeyDown));

  drivers::TouchWheelData wheel_data = raw_wheel_.GetTouchWheelData();
  HandleKey(Keys::kTouchWheel, now_ms, wheel_data.is_wheel_touched);
  HandleKey(Keys::kTouchWheelCenter, now_ms, wheel_data.is_button_touched);

  HandleKey(
      Keys::kDirectionalUp, now_ms,
      wheel_data.is_wheel_touched &&
          IsAngleWithin(wheel_data.wheel_position, 0, kDPadAngleThreshold));
  HandleKey(
      Keys::kDirectionalLeft, now_ms,
      wheel_data.is_wheel_touched &&
          IsAngleWithin(wheel_data.wheel_position, 63, kDPadAngleThreshold));
  HandleKey(
      Keys::kDirectionalDown, now_ms,
      wheel_data.is_wheel_touched &&
          IsAngleWithin(wheel_data.wheel_position, 127, kDPadAngleThreshold));
  HandleKey(
      Keys::kDirectionalRight, now_ms,
      wheel_data.is_wheel_touched &&
          IsAngleWithin(wheel_data.wheel_position, 189, kDPadAngleThreshold));

  // We now have enough information to give LVGL its update.
  switch (mode_) {
    case drivers::NvsStorage::InputModes::kButtonsOnly:
      data->state = LV_INDEV_STATE_RELEASED;
      if (ShortPressTrigger(Keys::kVolumeUp)) {
        data->enc_diff = -1;
      } else if (ShortPressTrigger(Keys::kVolumeDown)) {
        data->enc_diff = 1;
      } else if (LongPressTrigger(Keys::kVolumeDown, now_ms)) {
        data->state = LV_INDEV_STATE_PRESSED;
      } else if (LongPressTrigger(Keys::kVolumeUp, now_ms)) {
        // TODO: Back button event
      }
      break;
    case drivers::NvsStorage::InputModes::kButtonsWithWheel:
      data->state = ShortPressTrigger(Keys::kTouchWheel)
                        ? LV_INDEV_STATE_PRESSED
                        : LV_INDEV_STATE_RELEASED;
      if (ShortPressTriggerRepeating(Keys::kVolumeUp, now_ms)) {
        data->enc_diff = scroller_->AddInput(now_ms, -1);
      } else if (ShortPressTriggerRepeating(Keys::kVolumeDown, now_ms)) {
        data->enc_diff = scroller_->AddInput(now_ms, 1);
      }

      if (!touch_time_ms_.contains(Keys::kVolumeDown) &&
          !touch_time_ms_.contains(Keys::kVolumeUp)) {
        data->enc_diff = scroller_->AddInput(now_ms, 0);
      }
      // TODO: Long-press events.
      break;
    case drivers::NvsStorage::InputModes::kDirectionalWheel:
      data->state = ShortPressTrigger(Keys::kTouchWheelCenter)
                        ? LV_INDEV_STATE_PRESSED
                        : LV_INDEV_STATE_RELEASED;
      if (!ShortPressTriggerRepeating(Keys::kTouchWheel, now_ms)) {
        break;
      }
      if (ShortPressTriggerRepeating(Keys::kDirectionalUp, now_ms)) {
        data->enc_diff = scroller_->AddInput(now_ms, -1);
      } else if (ShortPressTriggerRepeating(Keys::kDirectionalDown, now_ms)) {
        data->enc_diff = scroller_->AddInput(now_ms, 1);
      } else if (ShortPressTrigger(Keys::kDirectionalRight)) {
        // TODO: ???
      } else if (ShortPressTrigger(Keys::kDirectionalLeft)) {
        // TODO: Back button event.
      }

      if (!touch_time_ms_.contains(Keys::kDirectionalUp) &&
          !touch_time_ms_.contains(Keys::kDirectionalDown)) {
        data->enc_diff = scroller_->AddInput(now_ms, 0);
      }
      // TODO: Long-press events.
      break;
    case drivers::NvsStorage::InputModes::kRotatingWheel:
      if (!raw_wheel_.GetTouchWheelData().is_wheel_touched) {
        data->enc_diff = scroller_->AddInput(now_ms, 0);
      } else if (relative_wheel_->ticks() != 0) {
        data->enc_diff = scroller_->AddInput(now_ms, relative_wheel_->ticks());
      } else {
        data->enc_diff = 0;
      }
      data->state = relative_wheel_->is_clicking() ? LV_INDEV_STATE_PRESSED
                                                   : LV_INDEV_STATE_RELEASED;
      // TODO: Long-press events.
      break;
  }

  // TODO: Apply inertia / acceleration.
}

auto EncoderInput::HandleKey(Keys key, uint64_t ms, bool clicked) -> void {
  if (!clicked) {
    touch_time_ms_.erase(key);
    short_press_fired_.erase(key);
    long_press_fired_.erase(key);
    return;
  }
  if (!touch_time_ms_.contains(key)) {
    touch_time_ms_[key] = ms;
  }
}

auto EncoderInput::ShortPressTrigger(Keys key) -> bool {
  if (touch_time_ms_.contains(key) && !short_press_fired_.contains(key)) {
    short_press_fired_[key] = true;
    return true;
  }
  return false;
}

auto EncoderInput::ShortPressTriggerRepeating(Keys key, uint64_t ms) -> bool {
  if (touch_time_ms_.contains(key) &&
      (!short_press_fired_.contains(key) ||
       ms - touch_time_ms_[key] >= kRepeatDelayMs)) {
    touch_time_ms_[key] = ms;
    short_press_fired_[key] = true;
    return true;
  }
  return false;
}

auto EncoderInput::LongPressTrigger(Keys key, uint64_t ms) -> bool {
  if (touch_time_ms_.contains(key) && !long_press_fired_.contains(key) &&
      ms - touch_time_ms_[key] >= kLongPressDelayMs) {
    long_press_fired_[key] = true;
    return true;
  }
  return false;
}

auto Scroller::AddInput(uint64_t ms, int direction) -> int {
  bool dir_changed =
      ((velocity_ < 0 && direction > 0) || (velocity_ > 0 && direction < 0));
  if (direction == 0 || dir_changed) {
    last_input_ms_ = ms;
    velocity_ = 0;
    return 0;
  }
  // Decay with time
  if (last_input_ms_ > ms) {
    last_input_ms_ = 0;
  }
  uint diff = ms - last_input_ms_;
  uint diff_steps = diff / 25;
  last_input_ms_ = ms + (last_input_ms_ % 50);
  // Use powers of two for our exponential decay so we can implement decay
  // trivially via bit shifting.
  velocity_ >>= diff_steps;

  velocity_ += direction * 1000;
  if (velocity_ > 0) {
    return (velocity_ + 500) / 1000;
  } else {
    return (velocity_ - 500) / 1000;
  }
}
}  // namespace ui