buttons.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 software is released under the MIT License.
  7. * https://opensource.org/licenses/MIT
  8. *
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <unistd.h>
  13. #include <string.h>
  14. #include "freertos/FreeRTOS.h"
  15. #include "freertos/task.h"
  16. #include "freertos/timers.h"
  17. #include "freertos/queue.h"
  18. #include "esp_system.h"
  19. #include "esp_log.h"
  20. #include "esp_task.h"
  21. #include "driver/gpio.h"
  22. #include "driver/rmt.h"
  23. #include "gpio_exp.h"
  24. #include "buttons.h"
  25. #include "rotary_encoder.h"
  26. #include "globdefs.h"
  27. static const char * TAG = "buttons";
  28. static EXT_RAM_ATTR int n_buttons;
  29. #define BUTTON_STACK_SIZE 4096
  30. #define MAX_BUTTONS 32
  31. #define DEBOUNCE 50
  32. #define BUTTON_QUEUE_LEN 10
  33. static EXT_RAM_ATTR struct button_s {
  34. void *client;
  35. int gpio;
  36. int debounce;
  37. button_handler handler;
  38. struct button_s *self, *shifter;
  39. int shifter_gpio; // this one is just for post-creation
  40. int long_press;
  41. bool long_timer, shifted, shifting;
  42. int type, level;
  43. TimerHandle_t timer;
  44. } buttons[MAX_BUTTONS];
  45. // can't use EXT_RAM_ATTR for initialized structure
  46. static struct {
  47. int gpio, level;
  48. struct button_s *button;
  49. } polled_gpio[] = { {36, -1, NULL}, {39, -1, NULL}, {-1, -1, NULL} };
  50. static TimerHandle_t polled_timer;
  51. static EXT_RAM_ATTR struct {
  52. QueueHandle_t queue;
  53. void *client;
  54. rotary_encoder_info_t info;
  55. int A, B, SW;
  56. rotary_handler handler;
  57. } rotary;
  58. static EXT_RAM_ATTR struct {
  59. RingbufHandle_t rb;
  60. infrared_handler handler;
  61. } infrared;
  62. static EXT_RAM_ATTR QueueHandle_t button_queue;
  63. static EXT_RAM_ATTR QueueSetHandle_t common_queue_set;
  64. static void buttons_task(void* arg);
  65. static void buttons_handler(struct button_s *button, int level);
  66. /****************************************************************************************
  67. * Start task needed by button,s rotaty and infrared
  68. */
  69. static void common_task_init(void) {
  70. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  71. static EXT_RAM_ATTR StackType_t xStack[BUTTON_STACK_SIZE] __attribute__ ((aligned (4)));
  72. if (!common_queue_set) {
  73. common_queue_set = xQueueCreateSet(BUTTON_QUEUE_LEN + 1);
  74. xTaskCreateStatic( (TaskFunction_t) buttons_task, "buttons", BUTTON_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN + 2, xStack, &xTaskBuffer);
  75. }
  76. }
  77. /****************************************************************************************
  78. * GPIO low-level ISR handler
  79. */
  80. static void IRAM_ATTR gpio_isr_handler(void* arg)
  81. {
  82. struct button_s *button = (struct button_s*) arg;
  83. BaseType_t woken = pdFALSE;
  84. if (xTimerGetPeriod(button->timer) > pdMS_TO_TICKS(button->debounce)) {
  85. if (button->gpio < GPIO_NUM_MAX) xTimerChangePeriodFromISR(button->timer, pdMS_TO_TICKS(button->debounce), &woken);
  86. else xTimerChangePeriod(button->timer, pdMS_TO_TICKS(button->debounce), pdMS_TO_TICKS(10));
  87. } else {
  88. if (button->gpio < GPIO_NUM_MAX) xTimerResetFromISR(button->timer, &woken);
  89. else xTimerReset(button->timer, portMAX_DELAY);
  90. }
  91. if (woken) portYIELD_FROM_ISR();
  92. ESP_EARLY_LOGD(TAG, "INT gpio %u level %u", button->gpio, button->level);
  93. }
  94. /****************************************************************************************
  95. * Buttons debounce/longpress timer
  96. */
  97. static void buttons_timer_handler( TimerHandle_t xTimer ) {
  98. struct button_s *button = (struct button_s*) pvTimerGetTimerID (xTimer);
  99. // if this is an expanded GPIO, must give cache a chance
  100. buttons_handler(button, gpio_exp_get_level(button->gpio, (button->debounce * 3) / 2, NULL));
  101. }
  102. /****************************************************************************************
  103. * Buttons polling timer
  104. */
  105. static void buttons_polling( TimerHandle_t xTimer ) {
  106. for (int i = 0; polled_gpio[i].gpio != -1; i++) {
  107. if (!polled_gpio[i].button) continue;
  108. int level = gpio_get_level(polled_gpio[i].gpio);
  109. if (level != polled_gpio[i].level) {
  110. polled_gpio[i].level = level;
  111. buttons_handler(polled_gpio[i].button, level);
  112. }
  113. }
  114. }
  115. /****************************************************************************************
  116. * Buttons timer handler for press/longpress
  117. */
  118. static void buttons_handler(struct button_s *button, int level) {
  119. button->level = level;
  120. if (button->shifter && button->shifter->type == button->shifter->level) button->shifter->shifting = true;
  121. if (button->long_press && !button->long_timer && button->level == button->type) {
  122. // detect a long press, so hold event generation
  123. ESP_LOGD(TAG, "setting long timer gpio:%u level:%u", button->gpio, button->level);
  124. xTimerChangePeriod(button->timer, button->long_press / portTICK_RATE_MS, 0);
  125. button->long_timer = true;
  126. } else {
  127. // send a button pressed/released event (content is copied in queue)
  128. ESP_LOGD(TAG, "sending event for gpio:%u level:%u", button->gpio, button->level);
  129. // queue will have a copy of button's context
  130. xQueueSend(button_queue, button, 0);
  131. button->long_timer = false;
  132. }
  133. }
  134. /****************************************************************************************
  135. * Tasks that calls the appropriate functions when buttons are pressed
  136. */
  137. static void buttons_task(void* arg) {
  138. ESP_LOGI(TAG, "starting button tasks");
  139. while (1) {
  140. QueueSetMemberHandle_t xActivatedMember;
  141. // wait on button, rotary and infrared queues
  142. if ((xActivatedMember = xQueueSelectFromSet( common_queue_set, portMAX_DELAY )) == NULL) continue;
  143. if (xActivatedMember == button_queue) {
  144. struct button_s button;
  145. button_event_e event;
  146. button_press_e press;
  147. // received a button event
  148. xQueueReceive(button_queue, &button, 0);
  149. event = (button.level == button.type) ? BUTTON_PRESSED : BUTTON_RELEASED;
  150. 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);
  151. // find if shifting is activated
  152. if (button.shifter && button.shifter->type == button.shifter->level) press = BUTTON_SHIFTED;
  153. else press = BUTTON_NORMAL;
  154. /*
  155. long_timer will be set either because we truly have a long press
  156. or we have a release before the long press timer elapsed, so two
  157. events shall be sent
  158. */
  159. if (button.long_timer) {
  160. if (event == BUTTON_RELEASED) {
  161. // early release of a long-press button, send press/release
  162. if (!button.shifting) {
  163. button.handler(button.client, BUTTON_PRESSED, press, false);
  164. button.handler(button.client, BUTTON_RELEASED, press, false);
  165. }
  166. // button is a copy, so need to go to real context
  167. button.self->shifting = false;
  168. } else if (!button.shifting) {
  169. // normal long press and not shifting so don't discard
  170. button.handler(button.client, BUTTON_PRESSED, press, true);
  171. }
  172. } else {
  173. // normal press/release of a button or release of a long-press button
  174. if (!button.shifting) button.handler(button.client, event, press, button.long_press);
  175. // button is a copy, so need to go to real context
  176. button.self->shifting = false;
  177. }
  178. } else if (xActivatedMember == rotary.queue) {
  179. rotary_encoder_event_t event = { 0 };
  180. // received a rotary event
  181. xQueueReceive(rotary.queue, &event, 0);
  182. ESP_LOGD(TAG, "Event: position %d, direction %s", event.state.position,
  183. event.state.direction ? (event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ? "CW" : "CCW") : "NOT_SET");
  184. rotary.handler(rotary.client, event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ?
  185. ROTARY_RIGHT : ROTARY_LEFT, false);
  186. } else {
  187. // this is IR
  188. infrared_receive(infrared.rb, infrared.handler);
  189. }
  190. }
  191. }
  192. /****************************************************************************************
  193. * dummy button handler
  194. */
  195. void dummy_handler(void *id, button_event_e event, button_press_e press) {
  196. ESP_LOGW(TAG, "should not be here");
  197. }
  198. /****************************************************************************************
  199. * Create buttons
  200. */
  201. void button_create(void *client, int gpio, int type, bool pull, int debounce, button_handler handler, int long_press, int shifter_gpio) {
  202. if (n_buttons >= MAX_BUTTONS) return;
  203. ESP_LOGI(TAG, "Creating button using GPIO %u, type %u, pull-up/down %u, long press %u shifter %d", gpio, type, pull, long_press, shifter_gpio);
  204. if (!n_buttons) {
  205. button_queue = xQueueCreate(BUTTON_QUEUE_LEN, sizeof(struct button_s));
  206. common_task_init();
  207. xQueueAddToSet( button_queue, common_queue_set );
  208. }
  209. // just in case this structure is allocated in a future release
  210. memset(buttons + n_buttons, 0, sizeof(struct button_s));
  211. // set mandatory parameters
  212. buttons[n_buttons].client = client;
  213. buttons[n_buttons].gpio = gpio;
  214. buttons[n_buttons].debounce = debounce ? debounce: DEBOUNCE;
  215. buttons[n_buttons].handler = handler;
  216. buttons[n_buttons].long_press = long_press;
  217. buttons[n_buttons].shifter_gpio = shifter_gpio;
  218. buttons[n_buttons].type = type;
  219. buttons[n_buttons].timer = xTimerCreate("buttonTimer", buttons[n_buttons].debounce / portTICK_RATE_MS, pdFALSE, (void *) &buttons[n_buttons], buttons_timer_handler);
  220. buttons[n_buttons].self = buttons + n_buttons;
  221. for (int i = 0; i < n_buttons; i++) {
  222. // first try to find our shifter
  223. if (buttons[i].gpio == shifter_gpio) {
  224. buttons[n_buttons].shifter = buttons + i;
  225. // a shifter must have a long-press handler
  226. if (!buttons[i].long_press) buttons[i].long_press = -1;
  227. }
  228. // then try to see if we are a non-assigned shifter
  229. if (buttons[i].shifter_gpio == gpio) {
  230. buttons[i].shifter = buttons + n_buttons;
  231. ESP_LOGI(TAG, "post-assigned shifter gpio %u", buttons[i].gpio);
  232. }
  233. }
  234. gpio_pad_select_gpio_x(gpio);
  235. gpio_set_direction_x(gpio, GPIO_MODE_INPUT);
  236. // do we need pullup or pulldown
  237. if (pull) {
  238. if (GPIO_IS_VALID_OUTPUT_GPIO(gpio) || gpio >= GPIO_NUM_MAX) {
  239. if (type == BUTTON_LOW) gpio_set_pull_mode_x(gpio, GPIO_PULLUP_ONLY);
  240. else gpio_set_pull_mode_x(gpio, GPIO_PULLDOWN_ONLY);
  241. } else {
  242. ESP_LOGW(TAG, "cannot set pull up/down for gpio %u", gpio);
  243. }
  244. }
  245. // and initialize level ...
  246. buttons[n_buttons].level = gpio_get_level_x(gpio);
  247. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  248. for (int i = 0; polled_gpio[i].gpio != -1; i++) if (polled_gpio[i].gpio == gpio) {
  249. if (!polled_timer) {
  250. polled_timer = xTimerCreate("buttonsPolling", 100 / portTICK_RATE_MS, pdTRUE, polled_gpio, buttons_polling);
  251. xTimerStart(polled_timer, portMAX_DELAY);
  252. }
  253. polled_gpio[i].button = buttons + n_buttons;
  254. polled_gpio[i].level = gpio_get_level(gpio);
  255. ESP_LOGW(TAG, "creating polled gpio %u, level %u", gpio, polled_gpio[i].level);
  256. gpio = -1;
  257. break;
  258. }
  259. // only create ISR if this is not a polled gpio
  260. if (gpio != -1) {
  261. // we need any edge detection
  262. gpio_set_intr_type_x(gpio, GPIO_INTR_ANYEDGE);
  263. gpio_isr_handler_add_x(gpio, gpio_isr_handler, buttons + n_buttons);
  264. gpio_intr_enable_x(gpio);
  265. }
  266. n_buttons++;
  267. }
  268. /****************************************************************************************
  269. * Get stored id
  270. */
  271. void *button_get_client(int gpio) {
  272. for (int i = 0; i < n_buttons; i++) {
  273. if (buttons[i].gpio == gpio) return buttons[i].client;
  274. }
  275. return NULL;
  276. }
  277. /****************************************************************************************
  278. * Get stored id
  279. */
  280. bool button_is_pressed(int gpio, void *client) {
  281. for (int i = 0; i < n_buttons; i++) {
  282. if (gpio != -1 && buttons[i].gpio == gpio) return buttons[i].level == buttons[i].type;
  283. else if (client && buttons[i].client == client) return buttons[i].level == buttons[i].type;
  284. }
  285. return false;
  286. }
  287. /****************************************************************************************
  288. * Update buttons
  289. */
  290. void *button_remap(void *client, int gpio, button_handler handler, int long_press, int shifter_gpio) {
  291. int i;
  292. struct button_s *button = NULL;
  293. void *prev_client;
  294. ESP_LOGI(TAG, "remapping GPIO %u, long press %u shifter %u", gpio, long_press, shifter_gpio);
  295. // find button
  296. for (i = 0; i < n_buttons; i++) {
  297. if (buttons[i].gpio == gpio) {
  298. button = buttons + i;
  299. break;
  300. }
  301. }
  302. // don't know what we are doing here
  303. if (!button) return NULL;
  304. prev_client = button->client;
  305. button->client = client;
  306. button->handler = handler;
  307. button->long_press = long_press;
  308. button->shifter_gpio = shifter_gpio;
  309. // find our shifter (if any)
  310. for (i = 0; shifter_gpio != -1 && i < n_buttons; i++) {
  311. if (buttons[i].gpio == shifter_gpio) {
  312. button->shifter = buttons + i;
  313. // a shifter must have a long-press handler
  314. if (!buttons[i].long_press) buttons[i].long_press = -1;
  315. break;
  316. }
  317. }
  318. return prev_client;
  319. }
  320. /****************************************************************************************
  321. * Rotary encoder handler
  322. */
  323. static void rotary_button_handler(void *id, button_event_e event, button_press_e mode, bool long_press) {
  324. ESP_LOGI(TAG, "Rotary push-button %d", event);
  325. rotary.handler(id, event == BUTTON_PRESSED ? ROTARY_PRESSED : ROTARY_RELEASED, long_press);
  326. }
  327. /****************************************************************************************
  328. * Create rotary encoder
  329. */
  330. bool create_rotary(void *id, int A, int B, int SW, int long_press, rotary_handler handler) {
  331. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  332. if (A == -1 || B == -1 || A == 36 || A == 39 || B == 36 || B == 39) {
  333. ESP_LOGI(TAG, "Cannot create rotary %d %d", A, B);
  334. return false;
  335. }
  336. rotary.A = A;
  337. rotary.B = B;
  338. rotary.SW = SW;
  339. rotary.client = id;
  340. rotary.handler = handler;
  341. // Initialise the rotary encoder device with the GPIOs for A and B signals
  342. rotary_encoder_init(&rotary.info, A, B);
  343. // Create a queue for events from the rotary encoder driver.
  344. rotary.queue = rotary_encoder_create_queue();
  345. rotary_encoder_set_queue(&rotary.info, rotary.queue);
  346. common_task_init();
  347. xQueueAddToSet( rotary.queue, common_queue_set );
  348. // create companion button if rotary has a switch
  349. if (SW != -1) button_create(id, SW, BUTTON_LOW, true, 0, rotary_button_handler, long_press, -1);
  350. ESP_LOGI(TAG, "Creating rotary encoder A:%d B:%d, SW:%d", A, B, SW);
  351. return true;
  352. }
  353. /****************************************************************************************
  354. * Create Infrared
  355. */
  356. bool create_infrared(int gpio, infrared_handler handler) {
  357. // initialize IR infrastructure
  358. infrared_init(&infrared.rb, gpio);
  359. infrared.handler = handler;
  360. // join the queue set
  361. common_task_init();
  362. xRingbufferAddToQueueSetRead(infrared.rb, common_queue_set);
  363. return (infrared.rb != NULL);
  364. }