2
0

buttons.c 15 KB

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