buttons.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 int n_buttons = 0;
  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 QueueHandle_t button_queue, button_exp_queue;
  63. static TimerHandle_t button_exp_timer;
  64. static QueueSetHandle_t common_queue_set;
  65. static void buttons_task(void* arg);
  66. static void buttons_handler(struct button_s *button, int level);
  67. /****************************************************************************************
  68. * Start task needed by button,s rotaty and infrared
  69. */
  70. static void common_task_init(void) {
  71. static DRAM_ATTR StaticTask_t xTaskBuffer __attribute__ ((aligned (4)));
  72. static EXT_RAM_ATTR StackType_t xStack[BUTTON_STACK_SIZE] __attribute__ ((aligned (4)));
  73. if (!common_queue_set) {
  74. common_queue_set = xQueueCreateSet(BUTTON_QUEUE_LEN + 1);
  75. xTaskCreateStatic( (TaskFunction_t) buttons_task, "buttons_thread", BUTTON_STACK_SIZE, NULL, ESP_TASK_PRIO_MIN + 2, xStack, &xTaskBuffer);
  76. }
  77. }
  78. /****************************************************************************************
  79. * GPIO low-level ISR handler
  80. */
  81. static void IRAM_ATTR gpio_isr_handler(void* arg)
  82. {
  83. struct button_s *button = (struct button_s*) arg;
  84. BaseType_t woken = pdFALSE;
  85. if (xTimerGetPeriod(button->timer) > button->debounce / portTICK_RATE_MS) xTimerChangePeriodFromISR(button->timer, button->debounce / portTICK_RATE_MS, &woken); // does that restart the timer?
  86. else xTimerResetFromISR(button->timer, &woken);
  87. if (woken) portYIELD_FROM_ISR();
  88. ESP_EARLY_LOGD(TAG, "INT gpio %u level %u", button->gpio, button->level);
  89. }
  90. /****************************************************************************************
  91. * Buttons debounce/longpress timer
  92. */
  93. static void buttons_timer_handler( TimerHandle_t xTimer ) {
  94. struct button_s *button = (struct button_s*) pvTimerGetTimerID (xTimer);
  95. buttons_handler(button, gpio_get_level(button->gpio));
  96. }
  97. /****************************************************************************************
  98. * GPIO expander low-level ISR handler
  99. */
  100. static BaseType_t IRAM_ATTR gpio_exp_isr_handler(void* arg)
  101. {
  102. BaseType_t woken = pdFALSE;
  103. xTimerResetFromISR((TimerHandle_t) arg, &woken);
  104. return woken;
  105. }
  106. /****************************************************************************************
  107. * Buttons expander debounce timer
  108. */
  109. static void buttons_exp_timer_handler( TimerHandle_t xTimer ) {
  110. struct gpio_exp_s *expander = (struct gpio_exp_s*) pvTimerGetTimerID (xTimer);
  111. xQueueSend(button_exp_queue, &expander, 0);
  112. ESP_LOGD(TAG, "Button expander base %u debounced", gpio_exp_get_base(expander));
  113. }
  114. /****************************************************************************************
  115. * Buttons expander enumerator
  116. */
  117. static void buttons_exp_enumerator(int gpio, int level, struct gpio_exp_s *expander) {
  118. for (int i = 0; i < n_buttons; i++) if (buttons[i].gpio == gpio) {
  119. buttons_handler(buttons + i, level);
  120. return;
  121. }
  122. }
  123. /****************************************************************************************
  124. * Buttons polling timer
  125. */
  126. static void buttons_polling( TimerHandle_t xTimer ) {
  127. for (int i = 0; polled_gpio[i].gpio != -1; i++) {
  128. if (!polled_gpio[i].button) continue;
  129. int level = gpio_get_level(polled_gpio[i].gpio);
  130. if (level != polled_gpio[i].level) {
  131. polled_gpio[i].level = level;
  132. buttons_handler(polled_gpio[i].button, level);
  133. }
  134. }
  135. }
  136. /****************************************************************************************
  137. * Buttons timer handler for press/longpress
  138. */
  139. static void buttons_handler(struct button_s *button, int level) {
  140. button->level = level;
  141. if (button->shifter && button->shifter->type == button->shifter->level) button->shifter->shifting = true;
  142. if (button->long_press && !button->long_timer && button->level == button->type) {
  143. // detect a long press, so hold event generation
  144. ESP_LOGD(TAG, "setting long timer gpio:%u level:%u", button->gpio, button->level);
  145. xTimerChangePeriod(button->timer, button->long_press / portTICK_RATE_MS, 0);
  146. button->long_timer = true;
  147. } else {
  148. // send a button pressed/released event (content is copied in queue)
  149. ESP_LOGD(TAG, "sending event for gpio:%u level:%u", button->gpio, button->level);
  150. // queue will have a copy of button's context
  151. xQueueSend(button_queue, button, 0);
  152. button->long_timer = false;
  153. }
  154. }
  155. /****************************************************************************************
  156. * Tasks that calls the appropriate functions when buttons are pressed
  157. */
  158. static void buttons_task(void* arg) {
  159. ESP_LOGI(TAG, "starting button tasks");
  160. while (1) {
  161. QueueSetMemberHandle_t xActivatedMember;
  162. // wait on button, rotary and infrared queues
  163. if ((xActivatedMember = xQueueSelectFromSet( common_queue_set, portMAX_DELAY )) == NULL) continue;
  164. if (xActivatedMember == button_queue) {
  165. struct button_s button;
  166. button_event_e event;
  167. button_press_e press;
  168. // received a button event
  169. xQueueReceive(button_queue, &button, 0);
  170. event = (button.level == button.type) ? BUTTON_PRESSED : BUTTON_RELEASED;
  171. 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);
  172. // find if shifting is activated
  173. if (button.shifter && button.shifter->type == button.shifter->level) press = BUTTON_SHIFTED;
  174. else press = BUTTON_NORMAL;
  175. /*
  176. long_timer will be set either because we truly have a long press
  177. or we have a release before the long press timer elapsed, so two
  178. events shall be sent
  179. */
  180. if (button.long_timer) {
  181. if (event == BUTTON_RELEASED) {
  182. // early release of a long-press button, send press/release
  183. if (!button.shifting) {
  184. button.handler(button.client, BUTTON_PRESSED, press, false);
  185. button.handler(button.client, BUTTON_RELEASED, press, false);
  186. }
  187. // button is a copy, so need to go to real context
  188. button.self->shifting = false;
  189. } else if (!button.shifting) {
  190. // normal long press and not shifting so don't discard
  191. button.handler(button.client, BUTTON_PRESSED, press, true);
  192. }
  193. } else {
  194. // normal press/release of a button or release of a long-press button
  195. if (!button.shifting) button.handler(button.client, event, press, button.long_press);
  196. // button is a copy, so need to go to real context
  197. button.self->shifting = false;
  198. }
  199. } else if (xActivatedMember == button_exp_queue) {
  200. struct gpio_exp_s *expander;
  201. /*
  202. we are not there yet, this is just a notice of a debounce, we need to enumerate
  203. GPIOs and let buttons_handler take care of longpress & al
  204. */
  205. xQueueReceive(button_exp_queue, &expander, 0);
  206. gpio_exp_enumerate(buttons_exp_enumerator, expander);
  207. } else if (xActivatedMember == rotary.queue) {
  208. rotary_encoder_event_t event = { 0 };
  209. // received a rotary event
  210. xQueueReceive(rotary.queue, &event, 0);
  211. ESP_LOGD(TAG, "Event: position %d, direction %s", event.state.position,
  212. event.state.direction ? (event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ? "CW" : "CCW") : "NOT_SET");
  213. rotary.handler(rotary.client, event.state.direction == ROTARY_ENCODER_DIRECTION_CLOCKWISE ?
  214. ROTARY_RIGHT : ROTARY_LEFT, false);
  215. } else {
  216. // this is IR
  217. infrared_receive(infrared.rb, infrared.handler);
  218. }
  219. }
  220. }
  221. /****************************************************************************************
  222. * dummy button handler
  223. */
  224. void dummy_handler(void *id, button_event_e event, button_press_e press) {
  225. ESP_LOGW(TAG, "should not be here");
  226. }
  227. /****************************************************************************************
  228. * Create buttons
  229. */
  230. void button_create(void *client, int gpio, int type, bool pull, int debounce, button_handler handler, int long_press, int shifter_gpio) {
  231. struct gpio_exp_s *expander;
  232. if (n_buttons >= MAX_BUTTONS) return;
  233. 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);
  234. if (!n_buttons) {
  235. button_queue = xQueueCreate(BUTTON_QUEUE_LEN, sizeof(struct button_s));
  236. common_task_init();
  237. xQueueAddToSet( button_queue, common_queue_set );
  238. }
  239. // just in case this structure is allocated in a future release
  240. memset(buttons + n_buttons, 0, sizeof(struct button_s));
  241. // set mandatory parameters
  242. buttons[n_buttons].client = client;
  243. buttons[n_buttons].gpio = gpio;
  244. buttons[n_buttons].debounce = debounce ? debounce: DEBOUNCE;
  245. buttons[n_buttons].handler = handler;
  246. buttons[n_buttons].long_press = long_press;
  247. buttons[n_buttons].shifter_gpio = shifter_gpio;
  248. buttons[n_buttons].type = type;
  249. buttons[n_buttons].timer = xTimerCreate("buttonTimer", buttons[n_buttons].debounce / portTICK_RATE_MS, pdFALSE, (void *) &buttons[n_buttons], buttons_timer_handler);
  250. buttons[n_buttons].self = buttons + n_buttons;
  251. for (int i = 0; i < n_buttons; i++) {
  252. // first try to find our shifter
  253. if (buttons[i].gpio == shifter_gpio) {
  254. buttons[n_buttons].shifter = buttons + i;
  255. // a shifter must have a long-press handler
  256. if (!buttons[i].long_press) buttons[i].long_press = -1;
  257. }
  258. // then try to see if we are a non-assigned shifter
  259. if (buttons[i].shifter_gpio == gpio) {
  260. buttons[i].shifter = buttons + n_buttons;
  261. ESP_LOGI(TAG, "post-assigned shifter gpio %u", buttons[i].gpio);
  262. }
  263. }
  264. // creation is different is this is a native or an expanded GPIO
  265. if (gpio < GPIO_NUM_MAX) {
  266. gpio_pad_select_gpio(gpio);
  267. gpio_set_direction(gpio, GPIO_MODE_INPUT);
  268. // do we need pullup or pulldown
  269. if (pull) {
  270. if (GPIO_IS_VALID_OUTPUT_GPIO(gpio)) {
  271. if (type == BUTTON_LOW) gpio_set_pull_mode(gpio, GPIO_PULLUP_ONLY);
  272. else gpio_set_pull_mode(gpio, GPIO_PULLDOWN_ONLY);
  273. } else {
  274. ESP_LOGW(TAG, "cannot set pull up/down for gpio %u", gpio);
  275. }
  276. }
  277. // and initialize level ...
  278. buttons[n_buttons].level = gpio_get_level(gpio);
  279. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  280. for (int i = 0; polled_gpio[i].gpio != -1; i++) if (polled_gpio[i].gpio == gpio) {
  281. if (!polled_timer) {
  282. polled_timer = xTimerCreate("buttonsPolling", 100 / portTICK_RATE_MS, pdTRUE, polled_gpio, buttons_polling);
  283. xTimerStart(polled_timer, portMAX_DELAY);
  284. }
  285. polled_gpio[i].button = buttons + n_buttons;
  286. polled_gpio[i].level = gpio_get_level(gpio);
  287. ESP_LOGW(TAG, "creating polled gpio %u, level %u", gpio, polled_gpio[i].level);
  288. gpio = -1;
  289. break;
  290. }
  291. // only create ISR if this is not a polled gpio
  292. if (gpio != -1) {
  293. // we need any edge detection
  294. gpio_set_intr_type(gpio, GPIO_INTR_ANYEDGE);
  295. gpio_isr_handler_add(gpio, gpio_isr_handler, (void*) &buttons[n_buttons]);
  296. gpio_intr_enable(gpio);
  297. }
  298. } else if ((expander = gpio_exp_get_expander(gpio)) != NULL) {
  299. // set GPIO as an ouptut and acquire value
  300. gpio_exp_set_direction(gpio, GPIO_MODE_INPUT, expander);
  301. buttons[n_buttons].level = gpio_exp_get_level(gpio, 0, expander);
  302. // create queue and timer for GPIO expander
  303. if (!button_exp_queue && expander) {
  304. button_exp_queue = xQueueCreate(BUTTON_QUEUE_LEN, sizeof(struct gpio_exp_s*));
  305. button_exp_timer = xTimerCreate("button_expander", pdMS_TO_TICKS(DEBOUNCE), pdFALSE, expander, buttons_exp_timer_handler);
  306. xQueueAddToSet( button_exp_queue, common_queue_set );
  307. gpio_exp_add_isr(gpio_exp_isr_handler, button_exp_timer, expander);
  308. }
  309. } else {
  310. ESP_LOGE(TAG, "Can't create button, GPIO %d does not exist", gpio);
  311. }
  312. n_buttons++;
  313. }
  314. /****************************************************************************************
  315. * Get stored id
  316. */
  317. void *button_get_client(int gpio) {
  318. for (int i = 0; i < n_buttons; i++) {
  319. if (buttons[i].gpio == gpio) return buttons[i].client;
  320. }
  321. return NULL;
  322. }
  323. /****************************************************************************************
  324. * Get stored id
  325. */
  326. bool button_is_pressed(int gpio, void *client) {
  327. for (int i = 0; i < n_buttons; i++) {
  328. if (gpio != -1 && buttons[i].gpio == gpio) return buttons[i].level == buttons[i].type;
  329. else if (client && buttons[i].client == client) return buttons[i].level == buttons[i].type;
  330. }
  331. return false;
  332. }
  333. /****************************************************************************************
  334. * Update buttons
  335. */
  336. void *button_remap(void *client, int gpio, button_handler handler, int long_press, int shifter_gpio) {
  337. int i;
  338. struct button_s *button = NULL;
  339. void *prev_client;
  340. ESP_LOGI(TAG, "remapping GPIO %u, long press %u shifter %u", gpio, long_press, shifter_gpio);
  341. // find button
  342. for (i = 0; i < n_buttons; i++) {
  343. if (buttons[i].gpio == gpio) {
  344. button = buttons + i;
  345. break;
  346. }
  347. }
  348. // don't know what we are doing here
  349. if (!button) return NULL;
  350. prev_client = button->client;
  351. button->client = client;
  352. button->handler = handler;
  353. button->long_press = long_press;
  354. button->shifter_gpio = shifter_gpio;
  355. // find our shifter (if any)
  356. for (i = 0; shifter_gpio != -1 && i < n_buttons; i++) {
  357. if (buttons[i].gpio == shifter_gpio) {
  358. button->shifter = buttons + i;
  359. // a shifter must have a long-press handler
  360. if (!buttons[i].long_press) buttons[i].long_press = -1;
  361. break;
  362. }
  363. }
  364. return prev_client;
  365. }
  366. /****************************************************************************************
  367. * Rotary encoder handler
  368. */
  369. static void rotary_button_handler(void *id, button_event_e event, button_press_e mode, bool long_press) {
  370. ESP_LOGI(TAG, "Rotary push-button %d", event);
  371. rotary.handler(id, event == BUTTON_PRESSED ? ROTARY_PRESSED : ROTARY_RELEASED, long_press);
  372. }
  373. /****************************************************************************************
  374. * Create rotary encoder
  375. */
  376. bool create_rotary(void *id, int A, int B, int SW, int long_press, rotary_handler handler) {
  377. // nasty ESP32 bug: fire-up constantly INT on GPIO 36/39 if ADC1, AMP, Hall used which WiFi does when PS is activated
  378. if (A == -1 || B == -1 || A == 36 || A == 39 || B == 36 || B == 39) {
  379. ESP_LOGI(TAG, "Cannot create rotary %d %d", A, B);
  380. return false;
  381. }
  382. rotary.A = A;
  383. rotary.B = B;
  384. rotary.SW = SW;
  385. rotary.client = id;
  386. rotary.handler = handler;
  387. // Initialise the rotary encoder device with the GPIOs for A and B signals
  388. rotary_encoder_init(&rotary.info, A, B);
  389. // Create a queue for events from the rotary encoder driver.
  390. rotary.queue = rotary_encoder_create_queue();
  391. rotary_encoder_set_queue(&rotary.info, rotary.queue);
  392. common_task_init();
  393. xQueueAddToSet( rotary.queue, common_queue_set );
  394. // create companion button if rotary has a switch
  395. if (SW != -1) button_create(id, SW, BUTTON_LOW, true, 0, rotary_button_handler, long_press, -1);
  396. ESP_LOGI(TAG, "Creating rotary encoder A:%d B:%d, SW:%d", A, B, SW);
  397. return true;
  398. }
  399. /****************************************************************************************
  400. * Create Infrared
  401. */
  402. bool create_infrared(int gpio, infrared_handler handler) {
  403. // initialize IR infrastructure
  404. infrared_init(&infrared.rb, gpio);
  405. infrared.handler = handler;
  406. // join the queue set
  407. common_task_init();
  408. xRingbufferAddToQueueSetRead(infrared.rb, common_queue_set);
  409. return (infrared.rb != NULL);
  410. }