buttons.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /*
  2. * a crude button press/long-press/shift management based on GPIO
  3. *
  4. * (c) Philippe G. 2019, philippe_44@outlook.com
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #include <string.h>
  24. #include "freertos/FreeRTOS.h"
  25. #include "freertos/task.h"
  26. #include "freertos/timers.h"
  27. #include "freertos/queue.h"
  28. #include "esp_system.h"
  29. #include "esp_log.h"
  30. #include "esp_task.h"
  31. #include "driver/gpio.h"
  32. #include "buttons.h"
  33. #include "rotary_encoder.h"
  34. #include "globdefs.h"
  35. bool gpio36_39_used;
  36. static const char * TAG = "buttons";
  37. static int n_buttons = 0;
  38. #define BUTTON_STACK_SIZE 4096
  39. #define MAX_BUTTONS 16
  40. #define DEBOUNCE 50
  41. #define BUTTON_QUEUE_LEN 10
  42. static EXT_RAM_ATTR struct button_s {
  43. void *client;
  44. int gpio;
  45. int debounce;
  46. button_handler handler;
  47. struct button_s *self, *shifter;
  48. int shifter_gpio; // this one is just for post-creation
  49. int long_press;
  50. bool long_timer, shifted, shifting;
  51. int type, level;
  52. TimerHandle_t timer;
  53. } buttons[MAX_BUTTONS];
  54. static struct {
  55. QueueHandle_t queue;
  56. void *client;
  57. rotary_encoder_info_t info;
  58. int A, B, SW;
  59. rotary_handler handler;
  60. } rotary;
  61. static xQueueHandle button_evt_queue;
  62. static QueueSetHandle_t button_queue_set;
  63. static void buttons_task(void* arg);
  64. /****************************************************************************************
  65. * GPIO low-level handler
  66. */
  67. static void IRAM_ATTR gpio_isr_handler(void* arg)
  68. {
  69. struct button_s *button = (struct button_s*) arg;
  70. BaseType_t woken = pdFALSE;
  71. if (xTimerGetPeriod(button->timer) > button->debounce / portTICK_RATE_MS) xTimerChangePeriodFromISR(button->timer, button->debounce / portTICK_RATE_MS, &woken); // does that restart the timer?
  72. else xTimerResetFromISR(button->timer, &woken);
  73. // ESP_EARLY_LOGI(TAG, "INT gpio %u level %u", button->gpio, button->level);
  74. }
  75. /****************************************************************************************
  76. * Buttons debounce/longpress timer
  77. */
  78. static void buttons_timer( TimerHandle_t xTimer ) {
  79. struct button_s *button = (struct button_s*) pvTimerGetTimerID (xTimer);
  80. button->level = gpio_get_level(button->gpio);
  81. if (button->shifter && button->shifter->type == button->shifter->level) button->shifter->shifting = true;
  82. if (button->long_press && !button->long_timer && button->level == button->type) {
  83. // detect a long press, so hold event generation
  84. ESP_LOGD(TAG, "setting long timer gpio:%u level:%u", button->gpio, button->level);
  85. xTimerChangePeriod(xTimer, button->long_press / portTICK_RATE_MS, 0);
  86. button->long_timer = true;
  87. } else {
  88. // send a button pressed/released event (content is copied in queue)
  89. ESP_LOGD(TAG, "sending event for gpio:%u level:%u", button->gpio, button->level);
  90. // queue will have a copy of button's context
  91. xQueueSend(button_evt_queue, button, 0);
  92. button->long_timer = false;
  93. }
  94. }
  95. /****************************************************************************************
  96. * Tasks that calls the appropriate functions when buttons are pressed
  97. */
  98. static void buttons_task(void* arg) {
  99. ESP_LOGI(TAG, "starting button tasks");
  100. while (1) {
  101. QueueSetMemberHandle_t xActivatedMember;
  102. // wait on button and rotary queues
  103. if ((xActivatedMember = xQueueSelectFromSet( button_queue_set, portMAX_DELAY )) == NULL) continue;
  104. if (xActivatedMember == button_evt_queue) {
  105. struct button_s button;
  106. button_event_e event;
  107. button_press_e press;
  108. // received a button event
  109. xQueueReceive(button_evt_queue, &button, 0);
  110. event = (button.level == button.type) ? BUTTON_PRESSED : BUTTON_RELEASED;
  111. ESP_LOGD(TAG, "received event:%u from gpio:%u level:%u (timer %u shifting %u)", event, button.gpio, button.level, button.long_timer, button.shifting);
  112. // find if shifting is activated
  113. if (button.shifter && button.shifter->type == button.shifter->level) press = BUTTON_SHIFTED;
  114. else press = BUTTON_NORMAL;
  115. /*
  116. long_timer will be set either because we truly have a long press
  117. or we have a release before the long press timer elapsed, so two
  118. events shall be sent
  119. */
  120. if (button.long_timer) {
  121. if (event == BUTTON_RELEASED) {
  122. // early release of a long-press button, send press/release
  123. if (!button.shifting) {
  124. (*button.handler)(button.client, BUTTON_PRESSED, press, false);
  125. (*button.handler)(button.client, BUTTON_RELEASED, press, false);
  126. }
  127. // button is a copy, so need to go to real context
  128. button.self->shifting = false;
  129. } else if (!button.shifting) {
  130. // normal long press and not shifting so don't discard
  131. (*button.handler)(button.client, BUTTON_PRESSED, press, true);
  132. }
  133. } else {
  134. // normal press/release of a button or release of a long-press button
  135. if (!button.shifting) (*button.handler)(button.client, event, press, button.long_press);
  136. // button is a copy, so need to go to real context
  137. button.self->shifting = false;
  138. }
  139. } else {
  140. rotary_encoder_event_t event = { 0 };
  141. // received a rotary event
  142. xQueueReceive(rotary.queue, &event, 0);
  143. ESP_LOGD(TAG, "Event: position %d, direction %s", event.state.position,
  144. event.state.direction ? (event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ? "CW" : "CCW") : "NOT_SET");
  145. rotary.handler(rotary.client, event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ?
  146. ROTARY_RIGHT : ROTARY_LEFT, false);
  147. }
  148. }
  149. }
  150. /****************************************************************************************
  151. * dummy button handler
  152. */
  153. void dummy_handler(void *id, button_event_e event, button_press_e press) {
  154. ESP_LOGW(TAG, "should not be here");
  155. }
  156. /****************************************************************************************
  157. * Create buttons
  158. */
  159. void button_create(void *client, int gpio, int type, bool pull, int debounce, button_handler handler, int long_press, int shifter_gpio) {
  160. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  161. static EXT_RAM_ATTR StackType_t xStack[BUTTON_STACK_SIZE] __attribute__ ((aligned (4)));
  162. if (n_buttons >= MAX_BUTTONS) return;
  163. ESP_LOGI(TAG, "Creating button using GPIO %u, type %u, pull-up/down %u, long press %u shifter %u", gpio, type, pull, long_press, shifter_gpio);
  164. if (!n_buttons) {
  165. button_evt_queue = xQueueCreate(BUTTON_QUEUE_LEN, sizeof(struct button_s));
  166. if (!button_queue_set) button_queue_set = xQueueCreateSet(BUTTON_QUEUE_LEN + 1);
  167. xQueueAddToSet( button_evt_queue, button_queue_set );
  168. xTaskCreateStatic( (TaskFunction_t) buttons_task, "buttons_thread", BUTTON_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN + 1, xStack, &xTaskBuffer);
  169. }
  170. // just in case this structure is allocated in a future release
  171. memset(buttons + n_buttons, 0, sizeof(struct button_s));
  172. // set mandatory parameters
  173. buttons[n_buttons].client = client;
  174. buttons[n_buttons].gpio = gpio;
  175. buttons[n_buttons].debounce = debounce ? debounce: DEBOUNCE;
  176. buttons[n_buttons].handler = handler;
  177. buttons[n_buttons].long_press = long_press;
  178. buttons[n_buttons].level = -1;
  179. buttons[n_buttons].shifter_gpio = shifter_gpio;
  180. buttons[n_buttons].type = type;
  181. buttons[n_buttons].timer = xTimerCreate("buttonTimer", buttons[n_buttons].debounce / portTICK_RATE_MS, pdFALSE, (void *) &buttons[n_buttons], buttons_timer);
  182. buttons[n_buttons].self = buttons + n_buttons;
  183. for (int i = 0; i < n_buttons; i++) {
  184. // first try to find our shifter
  185. if (buttons[i].gpio == shifter_gpio) {
  186. buttons[n_buttons].shifter = buttons + i;
  187. // a shifter must have a long-press handler
  188. if (!buttons[i].long_press) buttons[i].long_press = -1;
  189. }
  190. // then try to see if we are a non-assigned shifter
  191. if (buttons[i].shifter_gpio == gpio) {
  192. buttons[i].shifter = buttons + n_buttons;
  193. ESP_LOGI(TAG, "post-assigned shifter gpio %u", buttons[i].gpio);
  194. }
  195. }
  196. gpio_pad_select_gpio(gpio);
  197. gpio_set_direction(gpio, GPIO_MODE_INPUT);
  198. // we need any edge detection
  199. gpio_set_intr_type(gpio, GPIO_INTR_ANYEDGE);
  200. // do we need pullup or pulldown
  201. if (pull) {
  202. if (GPIO_IS_VALID_OUTPUT_GPIO(gpio)) {
  203. if (type == BUTTON_LOW) gpio_set_pull_mode(gpio, GPIO_PULLUP_ONLY);
  204. else gpio_set_pull_mode(gpio, GPIO_PULLDOWN_ONLY);
  205. } else {
  206. ESP_LOGW(TAG, "cannot set pull up/down for gpio %u", gpio);
  207. }
  208. }
  209. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  210. if (gpio == 36 || gpio == 39) gpio36_39_used = true;
  211. gpio_isr_handler_add(gpio, gpio_isr_handler, (void*) &buttons[n_buttons]);
  212. gpio_intr_enable(gpio);
  213. n_buttons++;
  214. }
  215. /****************************************************************************************
  216. * Get stored id
  217. */
  218. void *button_get_client(int gpio) {
  219. for (int i = 0; i < n_buttons; i++) {
  220. if (buttons[i].gpio == gpio) return buttons[i].client;
  221. }
  222. return NULL;
  223. }
  224. /****************************************************************************************
  225. * Get stored id
  226. */
  227. bool button_is_pressed(int gpio, void *client) {
  228. for (int i = 0; i < n_buttons; i++) {
  229. if (gpio != -1 && buttons[i].gpio == gpio) return buttons[i].level == buttons[i].type;
  230. else if (client && buttons[i].client == client) return buttons[i].level == buttons[i].type;
  231. }
  232. return false;
  233. }
  234. /****************************************************************************************
  235. * Update buttons
  236. */
  237. void *button_remap(void *client, int gpio, button_handler handler, int long_press, int shifter_gpio) {
  238. int i;
  239. struct button_s *button = NULL;
  240. void *prev_client;
  241. ESP_LOGI(TAG, "remapping GPIO %u, long press %u shifter %u", gpio, long_press, shifter_gpio);
  242. // find button
  243. for (i = 0; i < n_buttons; i++) {
  244. if (buttons[i].gpio == gpio) {
  245. button = buttons + i;
  246. break;
  247. }
  248. }
  249. // huh
  250. if (!button) return NULL;
  251. prev_client = button->client;
  252. button->client = client;
  253. button->handler = handler;
  254. button->long_press = long_press;
  255. button->shifter_gpio = shifter_gpio;
  256. // find our shifter (if any)
  257. for (i = 0; shifter_gpio != -1 && i < n_buttons; i++) {
  258. if (buttons[i].gpio == shifter_gpio) {
  259. button->shifter = buttons + i;
  260. // a shifter must have a long-press handler
  261. if (!buttons[i].long_press) buttons[i].long_press = -1;
  262. break;
  263. }
  264. }
  265. return prev_client;
  266. }
  267. /****************************************************************************************
  268. * Create rotary encoder
  269. */
  270. static void rotary_button_handler(void *id, button_event_e event, button_press_e mode, bool long_press) {
  271. ESP_LOGI(TAG, "Rotary push-button %d", event);
  272. rotary.handler(id, event == BUTTON_PRESSED ? ROTARY_PRESSED : ROTARY_RELEASED, long_press);
  273. }
  274. /****************************************************************************************
  275. * Create rotary encoder
  276. */
  277. bool create_rotary(void *id, int A, int B, int SW, int long_press, rotary_handler handler) {
  278. if (A == -1 || B == -1) {
  279. ESP_LOGI(TAG, "Cannot create rotary %d %d", A, B);
  280. return false;
  281. }
  282. rotary.A = A;
  283. rotary.B = B;
  284. rotary.SW = SW;
  285. rotary.client = id;
  286. rotary.handler = handler;
  287. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  288. if (A == 36 || A == 39 || B == 36 || B == 39 || SW == 36 || SW == 39) gpio36_39_used = true;
  289. // Initialise the rotary encoder device with the GPIOs for A and B signals
  290. rotary_encoder_init(&rotary.info, A, B);
  291. // Create a queue for events from the rotary encoder driver.
  292. rotary.queue = rotary_encoder_create_queue();
  293. rotary_encoder_set_queue(&rotary.info, rotary.queue);
  294. if (!button_queue_set) button_queue_set = xQueueCreateSet(BUTTON_QUEUE_LEN + 1);
  295. xQueueAddToSet( rotary.queue, button_queue_set );
  296. // create companion button if rotary has a switch
  297. if (SW != -1) button_create(id, SW, BUTTON_LOW, true, 0, rotary_button_handler, long_press, -1);
  298. ESP_LOGI(TAG, "Creating rotary encoder A:%d B:%d, SW:%d", A, B, SW);
  299. return true;
  300. }