buttons.c 14 KB

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