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 "esp_log.h"
17 #include "esp_check.h"
18 #include "esp_err.h"
19 #include "esp_private/usb_phy.h"
20 #include "soc/usb_pins.h"
21 #include "tinyusb.h"
22 #include "descriptors_control.h"
23 #include "tusb.h"
24 #include "tusb_tasks.h"
25 
26 const static char *TAG = "TinyUSB";
27 static usb_phy_handle_t phy_hdl;
28 
tinyusb_driver_install(const tinyusb_config_t * config)29 esp_err_t tinyusb_driver_install(const tinyusb_config_t *config)
30 {
31     tusb_desc_device_t *dev_descriptor;
32     const char **string_descriptor;
33     ESP_RETURN_ON_FALSE(config, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
34 
35     // Configure USB PHY
36     usb_phy_config_t phy_conf = {
37         .controller = USB_PHY_CTRL_OTG,
38         .otg_mode = USB_OTG_MODE_DEVICE,
39     };
40     if (config->external_phy) {
41         phy_conf.target = USB_PHY_TARGET_EXT;
42         usb_phy_gpio_conf_t gpio_conf = {
43             .vp_io_num = USBPHY_VP_NUM,
44             .vm_io_num = USBPHY_VM_NUM,
45             .rcv_io_num = USBPHY_RCV_NUM,
46             .oen_io_num = USBPHY_OEN_NUM,
47             .vpo_io_num = USBPHY_VPO_NUM,
48             .vmo_io_num = USBPHY_VMO_NUM,
49         };
50         phy_conf.gpio_conf = &gpio_conf;
51     } else {
52         phy_conf.target = USB_PHY_TARGET_INT;
53     }
54     ESP_RETURN_ON_ERROR(usb_new_phy(&phy_conf, &phy_hdl), TAG, "Install USB PHY failed");
55 
56     dev_descriptor = config->descriptor ? config->descriptor : &descriptor_kconfig;
57     string_descriptor = config->string_descriptor ? config->string_descriptor : descriptor_str_kconfig;
58 
59     tusb_set_descriptor(dev_descriptor, string_descriptor);
60 
61     ESP_RETURN_ON_FALSE(tusb_init(), ESP_FAIL, TAG, "Init TinyUSB stack failed");
62 #if !CONFIG_TINYUSB_NO_DEFAULT_TASK
63     ESP_RETURN_ON_ERROR(tusb_run_task(), TAG, "Run TinyUSB task failed");
64 #endif
65     ESP_LOGI(TAG, "TinyUSB Driver installed");
66     return ESP_OK;
67 }
68