buttons.c 13 KB

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