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 
15 #include "sdkconfig.h"
16 #include "freertos/FreeRTOS.h"
17 #include "freertos/task.h"
18 #include "esp_log.h"
19 #include "esp_check.h"
20 #include "tinyusb.h"
21 #include "tusb_tasks.h"
22 
23 const static char *TAG = "tusb_tsk";
24 static TaskHandle_t s_tusb_tskh;
25 
26 /**
27  * @brief This top level thread processes all usb events and invokes callbacks
28  */
tusb_device_task(void * arg)29 static void tusb_device_task(void *arg)
30 {
31     ESP_LOGD(TAG, "tinyusb task started");
32     while (1) { // RTOS forever loop
33         tud_task();
34     }
35 }
36 
tusb_run_task(void)37 esp_err_t tusb_run_task(void)
38 {
39     // This function is not garanteed to be thread safe, if invoked multiple times without calling `tusb_stop_task`, will cause memory leak
40     // doing a sanity check anyway
41     ESP_RETURN_ON_FALSE(!s_tusb_tskh, ESP_ERR_INVALID_STATE, TAG, "TinyUSB main task already started");
42     // Create a task for tinyusb device stack:
43     xTaskCreate(tusb_device_task, "TinyUSB", CONFIG_TINYUSB_TASK_STACK_SIZE, NULL, CONFIG_TINYUSB_TASK_PRIORITY, &s_tusb_tskh);
44     ESP_RETURN_ON_FALSE(s_tusb_tskh, ESP_FAIL, TAG, "create TinyUSB main task failed");
45     return ESP_OK;
46 }
47 
tusb_stop_task(void)48 esp_err_t tusb_stop_task(void)
49 {
50     ESP_RETURN_ON_FALSE(s_tusb_tskh, ESP_ERR_INVALID_STATE, TAG, "TinyUSB main task not started yet");
51     vTaskDelete(s_tusb_tskh);
52     s_tusb_tskh = NULL;
53     return ESP_OK;
54 }
55