tusb_tasks.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2020 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "sdkconfig.h"
  15. #include "freertos/FreeRTOS.h"
  16. #include "freertos/task.h"
  17. #include "esp_log.h"
  18. #include "esp_check.h"
  19. #include "tinyusb.h"
  20. #include "tusb_tasks.h"
  21. const static char *TAG = "tusb_tsk";
  22. static TaskHandle_t s_tusb_tskh;
  23. /**
  24. * @brief This top level thread processes all usb events and invokes callbacks
  25. */
  26. static void tusb_device_task(void *arg)
  27. {
  28. ESP_LOGD(TAG, "tinyusb task started");
  29. while (1) { // RTOS forever loop
  30. tud_task();
  31. }
  32. }
  33. esp_err_t tusb_run_task(void)
  34. {
  35. // This function is not garanteed to be thread safe, if invoked multiple times without calling `tusb_stop_task`, will cause memory leak
  36. // doing a sanity check anyway
  37. ESP_RETURN_ON_FALSE(!s_tusb_tskh, ESP_ERR_INVALID_STATE, TAG, "TinyUSB main task already started");
  38. // Create a task for tinyusb device stack:
  39. xTaskCreate(tusb_device_task, "TinyUSB", CONFIG_TINYUSB_TASK_STACK_SIZE, NULL, CONFIG_TINYUSB_TASK_PRIORITY, &s_tusb_tskh);
  40. ESP_RETURN_ON_FALSE(s_tusb_tskh, ESP_FAIL, TAG, "create TinyUSB main task failed");
  41. return ESP_OK;
  42. }
  43. esp_err_t tusb_stop_task(void)
  44. {
  45. ESP_RETURN_ON_FALSE(s_tusb_tskh, ESP_ERR_INVALID_STATE, TAG, "TinyUSB main task not started yet");
  46. vTaskDelete(s_tusb_tskh);
  47. s_tusb_tskh = NULL;
  48. return ESP_OK;
  49. }