diff options
| author | hathach <[email protected]> | 2020-03-22 17:19:57 +0700 |
|---|---|---|
| committer | hathach <[email protected]> | 2020-03-22 17:19:57 +0700 |
| commit | 4f871063fd33db2b55c6f78130c723a8854e0b11 (patch) | |
| tree | ddc78bd68c16a0895e0a7b4f9d1aff6380a20484 /src/device | |
| parent | 1ab3a1035c997e66b2014e8edfb92e10202cd988 (diff) | |
| parent | e47f9921570c75afd3288407601897c5b283f043 (diff) | |
Merge branch 'master' into cr1901-msp430f5529
Diffstat (limited to 'src/device')
| -rw-r--r-- | src/device/dcd.h | 299 | ||||
| -rw-r--r-- | src/device/usbd.c | 2065 | ||||
| -rw-r--r-- | src/device/usbd.h | 751 | ||||
| -rw-r--r-- | src/device/usbd_control.c | 399 |
4 files changed, 1819 insertions, 1695 deletions
diff --git a/src/device/dcd.h b/src/device/dcd.h index d6e8b2029..143a2de34 100644 --- a/src/device/dcd.h +++ b/src/device/dcd.h @@ -1,148 +1,151 @@ -/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2019 Ha Thach (tinyusb.org)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * This file is part of the TinyUSB stack.
- */
-
-/** \ingroup group_usbd
- * \defgroup group_dcd Device Controller Driver (DCD)
- * @{ */
-
-#ifndef _TUSB_DCD_H_
-#define _TUSB_DCD_H_
-
-#include "common/tusb_common.h"
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-typedef enum
-{
- DCD_EVENT_INVALID = 0,
- DCD_EVENT_BUS_RESET,
- DCD_EVENT_UNPLUGGED,
- DCD_EVENT_SOF,
- DCD_EVENT_SUSPEND, // TODO LPM Sleep L1 support
- DCD_EVENT_RESUME,
-
- DCD_EVENT_SETUP_RECEIVED,
- DCD_EVENT_XFER_COMPLETE,
-
- // Not an DCD event, just a convenient way to defer ISR function
- USBD_EVENT_FUNC_CALL,
-
- DCD_EVENT_COUNT
-} dcd_eventid_t;
-
-typedef struct TU_ATTR_ALIGNED(4)
-{
- uint8_t rhport;
- uint8_t event_id;
-
- union {
- // USBD_EVT_SETUP_RECEIVED
- tusb_control_request_t setup_received;
-
- // USBD_EVT_XFER_COMPLETE
- struct {
- uint8_t ep_addr;
- uint8_t result;
- uint32_t len;
- }xfer_complete;
-
- // USBD_EVENT_FUNC_CALL
- struct {
- void (*func) (void*);
- void* param;
- }func_call;
- };
-} dcd_event_t;
-
-//TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct");
-
-/*------------------------------------------------------------------*/
-/* Device API
- *------------------------------------------------------------------*/
-
-// Initialize controller to device mode
-void dcd_init (uint8_t rhport);
-
-// Enable device interrupt
-void dcd_int_enable (uint8_t rhport);
-
-// Disable device interrupt
-void dcd_int_disable(uint8_t rhport);
-
-// Receive Set Address request, mcu port must also include status IN response
-void dcd_set_address(uint8_t rhport, uint8_t dev_addr);
-
-// Receive Set Configure request
-void dcd_set_config (uint8_t rhport, uint8_t config_num);
-
-// Wake up host
-void dcd_remote_wakeup(uint8_t rhport);
-
-//--------------------------------------------------------------------+
-// Endpoint API
-//--------------------------------------------------------------------+
-
-// Configure endpoint's registers according to descriptor
-bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc);
-
-// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
-bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
-
-// Stall endpoint
-void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
-
-// clear stall, data toggle is also reset to DATA0
-void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr);
-
-// Invoked when a control transfer's status stage is complete.
-// May help DCD to prepare for next control transfer, this API is optional.
-void dcd_control_status_complete(uint8_t rhport) TU_ATTR_WEAK;
-
-//--------------------------------------------------------------------+
-// Event API (Implemented by device stack)
-//--------------------------------------------------------------------+
-
-// Called by DCD to notify device stack
-extern void dcd_event_handler(dcd_event_t const * event, bool in_isr);
-
-// helper to send bus signal event
-extern void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr);
-
-// helper to send setup received
-extern void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr);
-
-// helper to send transfer complete event
-extern void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr);
-
-#ifdef __cplusplus
- }
-#endif
-
-#endif /* _TUSB_DCD_H_ */
-
-/// @}
+/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usbd + * \defgroup group_dcd Device Controller Driver (DCD) + * @{ */ + +#ifndef _TUSB_DCD_H_ +#define _TUSB_DCD_H_ + +#include "common/tusb_common.h" + +#ifdef __cplusplus + extern "C" { +#endif + +typedef enum +{ + DCD_EVENT_INVALID = 0, + DCD_EVENT_BUS_RESET, + DCD_EVENT_UNPLUGGED, + DCD_EVENT_SOF, + DCD_EVENT_SUSPEND, // TODO LPM Sleep L1 support + DCD_EVENT_RESUME, + + DCD_EVENT_SETUP_RECEIVED, + DCD_EVENT_XFER_COMPLETE, + + // Not an DCD event, just a convenient way to defer ISR function + USBD_EVENT_FUNC_CALL, + + DCD_EVENT_COUNT +} dcd_eventid_t; + +typedef struct TU_ATTR_ALIGNED(4) +{ + uint8_t rhport; + uint8_t event_id; + + union { + // USBD_EVT_SETUP_RECEIVED + tusb_control_request_t setup_received; + + // USBD_EVT_XFER_COMPLETE + struct { + uint8_t ep_addr; + uint8_t result; + uint32_t len; + }xfer_complete; + + // USBD_EVENT_FUNC_CALL + struct { + void (*func) (void*); + void* param; + }func_call; + }; +} dcd_event_t; + +//TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct"); + +/*------------------------------------------------------------------*/ +/* Device API + *------------------------------------------------------------------*/ + +// Initialize controller to device mode +void dcd_init (uint8_t rhport); + +// Interrupt Handler +void dcd_isr (uint8_t rhport); + +// Enable device interrupt +void dcd_int_enable (uint8_t rhport); + +// Disable device interrupt +void dcd_int_disable(uint8_t rhport); + +// Receive Set Address request, mcu port must also include status IN response +void dcd_set_address(uint8_t rhport, uint8_t dev_addr); + +// Receive Set Configure request +void dcd_set_config (uint8_t rhport, uint8_t config_num); + +// Wake up host +void dcd_remote_wakeup(uint8_t rhport); + +//--------------------------------------------------------------------+ +// Endpoint API +//--------------------------------------------------------------------+ + +// Invoked when a control transfer's status stage is complete. +// May help DCD to prepare for next control transfer, this API is optional. +void dcd_edpt0_status_complete(uint8_t rhport, tusb_control_request_t const * request) TU_ATTR_WEAK; + +// Configure endpoint's registers according to descriptor +bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc); + +// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack +bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes); + +// Stall endpoint +void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr); + +// clear stall, data toggle is also reset to DATA0 +void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr); + +//--------------------------------------------------------------------+ +// Event API (Implemented by device stack) +//--------------------------------------------------------------------+ + +// Called by DCD to notify device stack +extern void dcd_event_handler(dcd_event_t const * event, bool in_isr); + +// helper to send bus signal event +extern void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr); + +// helper to send setup received +extern void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr); + +// helper to send transfer complete event +extern void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr); + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_DCD_H_ */ + +/// @} diff --git a/src/device/usbd.c b/src/device/usbd.c index 85ec4acd6..ddd99d7f1 100644 --- a/src/device/usbd.c +++ b/src/device/usbd.c @@ -1,1026 +1,1039 @@ -/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2019 Ha Thach (tinyusb.org)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * This file is part of the TinyUSB stack.
- */
-
-#include "tusb_option.h"
-
-#if TUSB_OPT_DEVICE_ENABLED
-
-#include "tusb.h"
-#include "usbd.h"
-#include "device/usbd_pvt.h"
-#include "dcd.h"
-
-#ifndef CFG_TUD_TASK_QUEUE_SZ
-#define CFG_TUD_TASK_QUEUE_SZ 16
-#endif
-
-//--------------------------------------------------------------------+
-// Device Data
-//--------------------------------------------------------------------+
-typedef struct {
- struct TU_ATTR_PACKED
- {
- volatile uint8_t connected : 1;
- volatile uint8_t addressed : 1;
- volatile uint8_t configured : 1;
- volatile uint8_t suspended : 1;
-
- uint8_t remote_wakeup_en : 1; // enable/disable by host
- uint8_t remote_wakeup_support : 1; // configuration descriptor's attribute
- uint8_t self_powered : 1; // configuration descriptor's attribute
- };
-
- uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid)
- uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid )
-
- struct TU_ATTR_PACKED
- {
- volatile bool busy : 1;
- volatile bool stalled : 1;
-
- // TODO merge ep2drv here, 4-bit should be sufficient
- }ep_status[8][2];
-}usbd_device_t;
-
-static usbd_device_t _usbd_dev;
-
-// Invalid driver ID in itf2drv[] ep2drv[][] mapping
-enum { DRVID_INVALID = 0xFFu };
-
-//--------------------------------------------------------------------+
-// Class Driver
-//--------------------------------------------------------------------+
-typedef struct {
- uint8_t class_code;
-
- void (* init ) (void);
- void (* reset ) (uint8_t rhport);
- bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length);
- bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request);
- bool (* control_complete ) (uint8_t rhport, tusb_control_request_t const * request);
- bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
- void (* sof ) (uint8_t rhport);
-} usbd_class_driver_t;
-
-static usbd_class_driver_t const usbd_class_drivers[] =
-{
- #if CFG_TUD_CDC
- {
- .class_code = TUSB_CLASS_CDC,
- .init = cdcd_init,
- .reset = cdcd_reset,
- .open = cdcd_open,
- .control_request = cdcd_control_request,
- .control_complete = cdcd_control_complete,
- .xfer_cb = cdcd_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_MSC
- {
- .class_code = TUSB_CLASS_MSC,
- .init = mscd_init,
- .reset = mscd_reset,
- .open = mscd_open,
- .control_request = mscd_control_request,
- .control_complete = mscd_control_complete,
- .xfer_cb = mscd_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_HID
- {
- .class_code = TUSB_CLASS_HID,
- .init = hidd_init,
- .reset = hidd_reset,
- .open = hidd_open,
- .control_request = hidd_control_request,
- .control_complete = hidd_control_complete,
- .xfer_cb = hidd_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_MIDI
- {
- .class_code = TUSB_CLASS_AUDIO,
- .init = midid_init,
- .open = midid_open,
- .reset = midid_reset,
- .control_request = midid_control_request,
- .control_complete = midid_control_complete,
- .xfer_cb = midid_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_VENDOR
- {
- .class_code = TUSB_CLASS_VENDOR_SPECIFIC,
- .init = vendord_init,
- .reset = vendord_reset,
- .open = vendord_open,
- .control_request = tud_vendor_control_request_cb,
- .control_complete = tud_vendor_control_complete_cb,
- .xfer_cb = vendord_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_USBTMC
- // Presently USBTMC is the only defined class with the APP_SPECIFIC class code.
- // We maybe need to add subclass codes here, or a callback to ask if a driver can
- // handle a particular interface.
- {
- .class_code = TUD_USBTMC_APP_CLASS,
- //.subclass_code = TUD_USBTMC_APP_SUBCLASS
- .init = usbtmcd_init_cb,
- .reset = usbtmcd_reset_cb,
- .open = usbtmcd_open_cb,
- .control_request = usbtmcd_control_request_cb,
- .control_complete = usbtmcd_control_complete_cb,
- .xfer_cb = usbtmcd_xfer_cb,
- .sof = NULL
- },
- #endif
-
- #if CFG_TUD_DFU_RT
- {
- .class_code = TUD_DFU_APP_CLASS,
- //.subclass_code = TUD_DFU_APP_SUBCLASS
- .init = dfu_rtd_init,
- .reset = dfu_rtd_reset,
- .open = dfu_rtd_open,
- .control_request = dfu_rtd_control_request,
- .control_complete = dfu_rtd_control_complete,
- .xfer_cb = dfu_rtd_xfer_cb,
- .sof = NULL
- },
- #endif
-};
-
-enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(usbd_class_drivers) };
-
-//--------------------------------------------------------------------+
-// DCD Event
-//--------------------------------------------------------------------+
-
-// Event queue
-// OPT_MODE_DEVICE is used by OS NONE for mutex (disable usb isr)
-OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t);
-static osal_queue_t _usbd_q;
-
-//--------------------------------------------------------------------+
-// Prototypes
-//--------------------------------------------------------------------+
-static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id);
-static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
-static bool process_set_config(uint8_t rhport, uint8_t cfg_num);
-static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request);
-
-void usbd_control_reset (uint8_t rhport);
-bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
-void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) );
-
-
-//--------------------------------------------------------------------+
-// Debugging
-//--------------------------------------------------------------------+
-#if CFG_TUSB_DEBUG > 1
-static char const* const _usbd_event_str[DCD_EVENT_COUNT] =
-{
- "INVALID" ,
- "BUS_RESET" ,
- "UNPLUGGED" ,
- "SOF" ,
- "SUSPEND" ,
- "RESUME" ,
- "SETUP_RECEIVED" ,
- "XFER_COMPLETE" ,
- "FUNC_CALL"
-};
-
-// must be same driver order as usbd_class_drivers[]
-static char const* const _usbd_driver_str[USBD_CLASS_DRIVER_COUNT] =
-{
- #if CFG_TUD_CDC
- "CDC",
- #endif
- #if CFG_TUD_MSC
- "MSC",
- #endif
- #if CFG_TUD_HID
- "HID",
- #endif
- #if CFG_TUD_MIDI
- "MIDI",
- #endif
- #if CFG_TUD_VENDOR
- "Vendor",
- #endif
- #if CFG_TUD_USBTMC
- "USBTMC"
- #endif
-};
-
-static char const* const _tusb_std_request_str[] =
-{
- "Get Status" ,
- "Clear Feature" ,
- "Reserved" ,
- "Set Feature" ,
- "Reserved" ,
- "Set Address" ,
- "Get Descriptor" ,
- "Set Descriptor" ,
- "Get Configuration" ,
- "Set Configuration" ,
- "Get Interface" ,
- "Set Interface" ,
- "Synch Frame"
-};
-
-#endif
-
-//--------------------------------------------------------------------+
-// Application API
-//--------------------------------------------------------------------+
-bool tud_mounted(void)
-{
- return _usbd_dev.configured;
-}
-
-bool tud_suspended(void)
-{
- return _usbd_dev.suspended;
-}
-
-bool tud_remote_wakeup(void)
-{
- // only wake up host if this feature is supported and enabled and we are suspended
- TU_VERIFY (_usbd_dev.suspended && _usbd_dev.remote_wakeup_support && _usbd_dev.remote_wakeup_en );
- dcd_remote_wakeup(TUD_OPT_RHPORT);
- return true;
-}
-
-//--------------------------------------------------------------------+
-// USBD Task
-//--------------------------------------------------------------------+
-bool tud_init (void)
-{
- TU_LOG2("USBD init\r\n");
-
- tu_varclr(&_usbd_dev);
-
- // Init device queue & task
- _usbd_q = osal_queue_create(&_usbd_qdef);
- TU_ASSERT(_usbd_q != NULL);
-
- // Init class drivers
- for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++)
- {
- TU_LOG2("%s init\r\n", _usbd_driver_str[i]);
- usbd_class_drivers[i].init();
- }
-
- // Init device controller driver
- dcd_init(TUD_OPT_RHPORT);
- dcd_int_enable(TUD_OPT_RHPORT);
-
- return true;
-}
-
-static void usbd_reset(uint8_t rhport)
-{
- tu_varclr(&_usbd_dev);
-
- memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping
- memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping
-
- usbd_control_reset(rhport);
-
- for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++)
- {
- if ( usbd_class_drivers[i].reset ) usbd_class_drivers[i].reset( rhport );
- }
-}
-
-/* USB Device Driver task
- * This top level thread manages all device controller event and delegates events to class-specific drivers.
- * This should be called periodically within the mainloop or rtos thread.
- *
- @code
- int main(void)
- {
- application_init();
- tusb_init();
-
- while(1) // the mainloop
- {
- application_code();
- tud_task(); // tinyusb device task
- }
- }
- @endcode
- */
-void tud_task (void)
-{
- // Skip if stack is not initialized
- if ( !tusb_inited() ) return;
-
- // Loop until there is no more events in the queue
- while (1)
- {
- dcd_event_t event;
-
- if ( !osal_queue_receive(_usbd_q, &event) ) return;
-
- TU_LOG2("USBD: event %s\r\n", event.event_id < DCD_EVENT_COUNT ? _usbd_event_str[event.event_id] : "CORRUPTED");
-
- switch ( event.event_id )
- {
- case DCD_EVENT_BUS_RESET:
- usbd_reset(event.rhport);
- break;
-
- case DCD_EVENT_UNPLUGGED:
- usbd_reset(event.rhport);
-
- // invoke callback
- if (tud_umount_cb) tud_umount_cb();
- break;
-
- case DCD_EVENT_SETUP_RECEIVED:
- TU_LOG2(" ");
- TU_LOG1_MEM(&event.setup_received, 1, 8);
-
- // Mark as connected after receiving 1st setup packet.
- // But it is easier to set it every time instead of wasting time to check then set
- _usbd_dev.connected = 1;
-
- // Process control request
- if ( !process_control_request(event.rhport, &event.setup_received) )
- {
- TU_LOG1(" Stall EP0\r\n");
- // Failed -> stall both control endpoint IN and OUT
- dcd_edpt_stall(event.rhport, 0);
- dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK);
- }
- break;
-
- case DCD_EVENT_XFER_COMPLETE:
- {
- // Invoke the class callback associated with the endpoint address
- uint8_t const ep_addr = event.xfer_complete.ep_addr;
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const ep_dir = tu_edpt_dir(ep_addr);
-
- TU_LOG2(" Endpoint: 0x%02X, Bytes: %ld\r\n", ep_addr, event.xfer_complete.len);
-
- _usbd_dev.ep_status[epnum][ep_dir].busy = false;
-
- if ( 0 == epnum )
- {
- TU_LOG1(" EP Addr = 0x%02X, len = %ld\r\n", ep_addr, event.xfer_complete.len);
- usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
- }
- else
- {
- uint8_t const drv_id = _usbd_dev.ep2drv[epnum][ep_dir];
- TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,);
-
- TU_LOG2(" %s xfer callback\r\n", _usbd_driver_str[drv_id]);
- usbd_class_drivers[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
- }
- }
- break;
-
- case DCD_EVENT_SUSPEND:
- if (tud_suspend_cb) tud_suspend_cb(_usbd_dev.remote_wakeup_en);
- break;
-
- case DCD_EVENT_RESUME:
- if (tud_resume_cb) tud_resume_cb();
- break;
-
- case DCD_EVENT_SOF:
- for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ )
- {
- if ( usbd_class_drivers[i].sof )
- {
- usbd_class_drivers[i].sof(event.rhport);
- }
- }
- break;
-
- case USBD_EVENT_FUNC_CALL:
- if ( event.func_call.func ) event.func_call.func(event.func_call.param);
- break;
-
- default:
- TU_BREAKPOINT();
- break;
- }
- }
-}
-
-//--------------------------------------------------------------------+
-// Control Request Parser & Handling
-//--------------------------------------------------------------------+
-
-// This handles the actual request and its response.
-// return false will cause its caller to stall control endpoint
-static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
-{
- usbd_control_set_complete_callback(NULL);
-
- TU_ASSERT(p_request->bmRequestType_bit.type < TUSB_REQ_TYPE_INVALID);
-
- // Vendor request
- if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR )
- {
- TU_VERIFY(tud_vendor_control_request_cb);
-
- if (tud_vendor_control_complete_cb) usbd_control_set_complete_callback(tud_vendor_control_complete_cb);
- return tud_vendor_control_request_cb(rhport, p_request);
- }
-
-#if CFG_TUSB_DEBUG > 1
- if (TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type && p_request->bRequest <= TUSB_REQ_SYNCH_FRAME)
- {
- TU_LOG2(" %s\r\n", _tusb_std_request_str[p_request->bRequest]);
- }
-#endif
-
- switch ( p_request->bmRequestType_bit.recipient )
- {
- //------------- Device Requests e.g in enumeration -------------//
- case TUSB_REQ_RCPT_DEVICE:
- if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type )
- {
- // Non standard request is not supported
- TU_BREAKPOINT();
- return false;
- }
-
- switch ( p_request->bRequest )
- {
- case TUSB_REQ_SET_ADDRESS:
- // Depending on mcu, status phase could be sent either before or after changing device address
- // Therefore DCD must include zero-length status response
- dcd_set_address(rhport, (uint8_t) p_request->wValue);
- _usbd_dev.addressed = 1;
- return true; // skip status
- break;
-
- case TUSB_REQ_GET_CONFIGURATION:
- {
- uint8_t cfgnum = _usbd_dev.configured ? 1 : 0;
- tud_control_xfer(rhport, p_request, &cfgnum, 1);
- }
- break;
-
- case TUSB_REQ_SET_CONFIGURATION:
- {
- uint8_t const cfg_num = (uint8_t) p_request->wValue;
-
- dcd_set_config(rhport, cfg_num);
- _usbd_dev.configured = cfg_num ? 1 : 0;
-
- if ( cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) );
- tud_control_status(rhport, p_request);
- }
- break;
-
- case TUSB_REQ_GET_DESCRIPTOR:
- TU_VERIFY( process_get_descriptor(rhport, p_request) );
- break;
-
- case TUSB_REQ_SET_FEATURE:
- // Only support remote wakeup for device feature
- TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
-
- // Host may enable remote wake up before suspending especially HID device
- _usbd_dev.remote_wakeup_en = true;
- tud_control_status(rhport, p_request);
- break;
-
- case TUSB_REQ_CLEAR_FEATURE:
- // Only support remote wakeup for device feature
- TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
-
- // Host may disable remote wake up after resuming
- _usbd_dev.remote_wakeup_en = false;
- tud_control_status(rhport, p_request);
- break;
-
- case TUSB_REQ_GET_STATUS:
- {
- // Device status bit mask
- // - Bit 0: Self Powered
- // - Bit 1: Remote Wakeup enabled
- uint16_t status = (_usbd_dev.self_powered ? 1 : 0) | (_usbd_dev.remote_wakeup_en ? 2 : 0);
- tud_control_xfer(rhport, p_request, &status, 2);
- }
- break;
-
- // Unknown/Unsupported request
- default: TU_BREAKPOINT(); return false;
- }
- break;
-
- //------------- Class/Interface Specific Request -------------//
- case TUSB_REQ_RCPT_INTERFACE:
- {
- uint8_t const itf = tu_u16_low(p_request->wIndex);
- TU_VERIFY(itf < TU_ARRAY_SIZE(_usbd_dev.itf2drv));
-
- uint8_t const drvid = _usbd_dev.itf2drv[itf];
- TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT);
-
- if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD)
- {
- switch ( p_request->bRequest )
- {
- case TUSB_REQ_GET_INTERFACE:
- {
- // TODO not support alternate interface yet
- uint8_t alternate = 0;
- tud_control_xfer(rhport, p_request, &alternate, 1);
- }
- break;
-
- case TUSB_REQ_SET_INTERFACE:
- {
- uint8_t const alternate = (uint8_t) p_request->wValue;
-
- // TODO not support alternate interface yet
- TU_ASSERT(alternate == 0);
- tud_control_status(rhport, p_request);
- }
- break;
-
- default:
- // forward to class driver: "STD request to Interface"
- // GET HID REPORT DESCRIPTOR falls into this case
- // stall control endpoint if driver return false
- usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_complete);
- TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]);
- TU_VERIFY(usbd_class_drivers[drvid].control_request != NULL &&
- usbd_class_drivers[drvid].control_request(rhport, p_request));
- break;
- }
- }else
- {
- // forward to class driver: "non-STD request to Interface"
- // stall control endpoint if driver return false
- usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_complete);
- TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]);
- TU_VERIFY(usbd_class_drivers[drvid].control_request != NULL &&
- usbd_class_drivers[drvid].control_request(rhport, p_request));
- }
- }
- break;
-
- //------------- Endpoint Request -------------//
- case TUSB_REQ_RCPT_ENDPOINT:
- {
- uint8_t const ep_addr = tu_u16_low(p_request->wIndex);
- uint8_t const ep_num = tu_edpt_number(ep_addr);
- uint8_t const ep_dir = tu_edpt_dir(ep_addr);
-
- TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) );
-
- uint8_t const drv_id = _usbd_dev.ep2drv[ep_num][ep_dir];
- TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT);
-
- bool ret = false;
-
- if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type )
- {
- // complete callback is also capable of stalling/acking the request
- usbd_control_set_complete_callback(usbd_class_drivers[drv_id].control_complete);
- }
-
- // Then handle if it is standard request
- if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type )
- {
- // force return true for standard request
- ret = true;
-
- switch ( p_request->bRequest )
- {
- case TUSB_REQ_GET_STATUS:
- {
- uint16_t status = usbd_edpt_stalled(rhport, ep_addr) ? 0x0001 : 0x0000;
- tud_control_xfer(rhport, p_request, &status, 2);
- }
- break;
-
- case TUSB_REQ_CLEAR_FEATURE:
- if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue )
- {
- usbd_edpt_clear_stall(rhport, ep_addr);
- }
- tud_control_status(rhport, p_request);
- break;
-
- case TUSB_REQ_SET_FEATURE:
- if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue )
- {
- usbd_edpt_stall(rhport, ep_addr);
- }
- tud_control_status(rhport, p_request);
- break;
-
- // Unknown/Unsupported request
- default: TU_BREAKPOINT(); return false;
- }
- }
- // Some classes such as TMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request
- // We will forward all request targeted endpoint to its class driver
- // For class-type requests: must (call tud_control_status(); return true) or (return false)
- // For std-type requests: non-std request codes are already discarded.
- // must not call tud_control_status(), and return value will have no effect
- // class driver is invoked last, so that EP already has EP stall cleared (in event of clear feature EP halt)
- TU_LOG2(" %s control request\r\n", _usbd_driver_str[drv_id]);
- if ( usbd_class_drivers[drv_id].control_request &&
- usbd_class_drivers[drv_id].control_request(rhport, p_request))
- {
- ret = true;
- }
- return ret;
- }
- break;
-
- // Unknown recipient
- default: TU_BREAKPOINT(); return false;
- }
-
- return true;
-}
-
-// Process Set Configure Request
-// This function parse configuration descriptor & open drivers accordingly
-static bool process_set_config(uint8_t rhport, uint8_t cfg_num)
-{
- tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1); // index is cfg_num-1
- TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION);
-
- // Parse configuration descriptor
- _usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0;
- _usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0;
-
- // Parse interface descriptor
- uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t);
- uint8_t const * desc_end = ((uint8_t const*) desc_cfg) + desc_cfg->wTotalLength;
-
- while( p_desc < desc_end )
- {
- // Each interface always starts with Interface or Association descriptor
- if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) )
- {
- p_desc = tu_desc_next(p_desc); // ignore Interface Association
- }else
- {
- TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) );
-
- tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc;
-
- // Check if class is supported
- uint8_t drv_id;
- for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++)
- {
- if ( usbd_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break;
- }
- TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT );
-
- // Interface number must not be used already TODO alternate interface
- TU_ASSERT( DRVID_INVALID == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] );
- _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id;
-
- uint16_t itf_len=0;
- TU_LOG2(" %s open\r\n", _usbd_driver_str[drv_id]);
- TU_ASSERT( usbd_class_drivers[drv_id].open(rhport, desc_itf, &itf_len) );
- TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) );
-
- mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id);
-
- p_desc += itf_len; // next interface
- }
- }
-
- // invoke callback
- if (tud_mount_cb) tud_mount_cb();
-
- return true;
-}
-
-// Helper marking endpoint of interface belongs to class driver
-static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id)
-{
- uint16_t len = 0;
-
- while( len < desc_len )
- {
- if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
- {
- uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress;
-
- ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id;
- }
-
- len = (uint16_t)(len + tu_desc_len(p_desc));
- p_desc = tu_desc_next(p_desc);
- }
-}
-
-// return descriptor's buffer and update desc_len
-static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request)
-{
- tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue);
- uint8_t const desc_index = tu_u16_low( p_request->wValue );
-
- switch(desc_type)
- {
- case TUSB_DESC_DEVICE:
- {
- uint16_t len = sizeof(tusb_desc_device_t);
-
- // Only send up to EP0 Packet Size if not addressed
- // This only happens with the very first get device descriptor and EP0 size = 8 or 16.
- if ((CFG_TUD_ENDPOINT0_SIZE < sizeof(tusb_desc_device_t)) && !_usbd_dev.addressed)
- {
- len = CFG_TUD_ENDPOINT0_SIZE;
-
- // Hack here: we modify the request length to prevent usbd_control response with zlp
- ((tusb_control_request_t*) p_request)->wLength = CFG_TUD_ENDPOINT0_SIZE;
- }
-
- return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), len);
- }
- break;
-
- case TUSB_DESC_BOS:
- {
- // requested by host if USB > 2.0 ( i.e 2.1 or 3.x )
- if (!tud_descriptor_bos_cb) return false;
-
- tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb();
- uint16_t total_len;
- memcpy(&total_len, &desc_bos->wTotalLength, 2); // possibly mis-aligned memory
-
- return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len);
- }
- break;
-
- case TUSB_DESC_CONFIGURATION:
- {
- tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index);
- TU_ASSERT(desc_config);
-
- uint16_t total_len;
- memcpy(&total_len, &desc_config->wTotalLength, 2); // possibly mis-aligned memory
-
- return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len);
- }
- break;
-
- case TUSB_DESC_STRING:
- // String Descriptor always uses the desc set from user
- if ( desc_index == 0xEE )
- {
- // The 0xEE index string is a Microsoft OS Descriptors.
- // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
- return false;
- }else
- {
- uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index);
- TU_ASSERT(desc_str);
-
- // first byte of descriptor is its size
- return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]);
- }
- break;
-
- case TUSB_DESC_DEVICE_QUALIFIER:
- // TODO If not highspeed capable stall this request otherwise
- // return the descriptor that could work in highspeed
- return false;
- break;
-
- default: return false;
- }
-
- return true;
-}
-
-//--------------------------------------------------------------------+
-// DCD Event Handler
-//--------------------------------------------------------------------+
-void dcd_event_handler(dcd_event_t const * event, bool in_isr)
-{
- switch (event->event_id)
- {
- case DCD_EVENT_BUS_RESET:
- osal_queue_send(_usbd_q, event, in_isr);
- break;
-
- case DCD_EVENT_UNPLUGGED:
- _usbd_dev.connected = 0;
- _usbd_dev.addressed = 0;
- _usbd_dev.configured = 0;
- _usbd_dev.suspended = 0;
- osal_queue_send(_usbd_q, event, in_isr);
- break;
-
- case DCD_EVENT_SOF:
- // nothing to do now
- break;
-
- case DCD_EVENT_SUSPEND:
- // NOTE: When plugging/unplugging device, the D+/D- state are unstable and can accidentally meet the
- // SUSPEND condition ( Idle for 3ms ). Some MCUs such as SAMD doesn't distinguish suspend vs disconnect as well.
- // We will skip handling SUSPEND/RESUME event if not currently connected
- if ( _usbd_dev.connected )
- {
- _usbd_dev.suspended = 1;
- osal_queue_send(_usbd_q, event, in_isr);
- }
- break;
-
- case DCD_EVENT_RESUME:
- if ( _usbd_dev.connected )
- {
- _usbd_dev.suspended = 0;
- osal_queue_send(_usbd_q, event, in_isr);
- }
- break;
-
- case DCD_EVENT_SETUP_RECEIVED:
- osal_queue_send(_usbd_q, event, in_isr);
- break;
-
- case DCD_EVENT_XFER_COMPLETE:
- osal_queue_send(_usbd_q, event, in_isr);
- TU_ASSERT(event->xfer_complete.result == XFER_RESULT_SUCCESS,);
- break;
-
- // Not an DCD event, just a convenient way to defer ISR function should we need to
- case USBD_EVENT_FUNC_CALL:
- osal_queue_send(_usbd_q, event, in_isr);
- break;
-
- default: break;
- }
-}
-
-void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr)
-{
- dcd_event_t event = { .rhport = rhport, .event_id = eid, };
- dcd_event_handler(&event, in_isr);
-}
-
-void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr)
-{
- dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED };
- memcpy(&event.setup_received, setup, 8);
-
- dcd_event_handler(&event, in_isr);
-}
-
-void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr)
-{
- dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE };
-
- event.xfer_complete.ep_addr = ep_addr;
- event.xfer_complete.len = xferred_bytes;
- event.xfer_complete.result = result;
-
- dcd_event_handler(&event, in_isr);
-}
-
-//--------------------------------------------------------------------+
-// Helper
-//--------------------------------------------------------------------+
-
-// Parse consecutive endpoint descriptors (IN & OUT)
-bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in)
-{
- for(int i=0; i<ep_count; i++)
- {
- tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) p_desc;
-
- TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && xfer_type == desc_ep->bmAttributes.xfer);
- TU_ASSERT(dcd_edpt_open(rhport, desc_ep));
-
- if ( tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN )
- {
- (*ep_in) = desc_ep->bEndpointAddress;
- }else
- {
- (*ep_out) = desc_ep->bEndpointAddress;
- }
-
- p_desc = tu_desc_next(p_desc);
- }
-
- return true;
-}
-
-// Helper to defer an isr function
-void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr)
-{
- dcd_event_t event =
- {
- .rhport = 0,
- .event_id = USBD_EVENT_FUNC_CALL,
- };
-
- event.func_call.func = func;
- event.func_call.param = param;
-
- dcd_event_handler(&event, in_isr);
-}
-
-//--------------------------------------------------------------------+
-// USBD Endpoint API
-//--------------------------------------------------------------------+
-
-bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
-{
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const dir = tu_edpt_dir(ep_addr);
-
- TU_VERIFY( dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes) );
- _usbd_dev.ep_status[epnum][dir].busy = true;
-
- return true;
-}
-
-bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr)
-{
- (void) rhport;
-
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const dir = tu_edpt_dir(ep_addr);
-
- return _usbd_dev.ep_status[epnum][dir].busy;
-}
-
-void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
-{
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const dir = tu_edpt_dir(ep_addr);
-
- dcd_edpt_stall(rhport, ep_addr);
- _usbd_dev.ep_status[epnum][dir].stalled = true;
- _usbd_dev.ep_status[epnum][dir].busy = true;
-}
-
-void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
-{
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const dir = tu_edpt_dir(ep_addr);
-
- dcd_edpt_clear_stall(rhport, ep_addr);
- _usbd_dev.ep_status[epnum][dir].stalled = false;
- _usbd_dev.ep_status[epnum][dir].busy = false;
-}
-
-bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr)
-{
- (void) rhport;
-
- uint8_t const epnum = tu_edpt_number(ep_addr);
- uint8_t const dir = tu_edpt_dir(ep_addr);
-
- return _usbd_dev.ep_status[epnum][dir].stalled;
-}
-
-#endif
+/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED + +#include "tusb.h" +#include "usbd.h" +#include "device/usbd_pvt.h" +#include "dcd.h" + +#ifndef CFG_TUD_TASK_QUEUE_SZ +#define CFG_TUD_TASK_QUEUE_SZ 16 +#endif + +//--------------------------------------------------------------------+ +// Device Data +//--------------------------------------------------------------------+ +typedef struct { + struct TU_ATTR_PACKED + { + volatile uint8_t connected : 1; + volatile uint8_t addressed : 1; + volatile uint8_t configured : 1; + volatile uint8_t suspended : 1; + + uint8_t remote_wakeup_en : 1; // enable/disable by host + uint8_t remote_wakeup_support : 1; // configuration descriptor's attribute + uint8_t self_powered : 1; // configuration descriptor's attribute + }; + + uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid) + uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid ) + + struct TU_ATTR_PACKED + { + volatile bool busy : 1; + volatile bool stalled : 1; + + // TODO merge ep2drv here, 4-bit should be sufficient + }ep_status[8][2]; +}usbd_device_t; + +static usbd_device_t _usbd_dev; + +// Invalid driver ID in itf2drv[] ep2drv[][] mapping +enum { DRVID_INVALID = 0xFFu }; + +//--------------------------------------------------------------------+ +// Class Driver +//--------------------------------------------------------------------+ +typedef struct { + uint8_t class_code; + + void (* init ) (void); + void (* reset ) (uint8_t rhport); + bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length); + bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request); + bool (* control_complete ) (uint8_t rhport, tusb_control_request_t const * request); + bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + void (* sof ) (uint8_t rhport); +} usbd_class_driver_t; + +static usbd_class_driver_t const _usbd_driver[] = +{ + #if CFG_TUD_CDC + { + .class_code = TUSB_CLASS_CDC, + .init = cdcd_init, + .reset = cdcd_reset, + .open = cdcd_open, + .control_request = cdcd_control_request, + .control_complete = cdcd_control_complete, + .xfer_cb = cdcd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_MSC + { + .class_code = TUSB_CLASS_MSC, + .init = mscd_init, + .reset = mscd_reset, + .open = mscd_open, + .control_request = mscd_control_request, + .control_complete = mscd_control_complete, + .xfer_cb = mscd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_HID + { + .class_code = TUSB_CLASS_HID, + .init = hidd_init, + .reset = hidd_reset, + .open = hidd_open, + .control_request = hidd_control_request, + .control_complete = hidd_control_complete, + .xfer_cb = hidd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_MIDI + { + .class_code = TUSB_CLASS_AUDIO, + .init = midid_init, + .open = midid_open, + .reset = midid_reset, + .control_request = midid_control_request, + .control_complete = midid_control_complete, + .xfer_cb = midid_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_VENDOR + { + .class_code = TUSB_CLASS_VENDOR_SPECIFIC, + .init = vendord_init, + .reset = vendord_reset, + .open = vendord_open, + .control_request = tud_vendor_control_request_cb, + .control_complete = tud_vendor_control_complete_cb, + .xfer_cb = vendord_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_USBTMC + // Presently USBTMC is the only defined class with the APP_SPECIFIC class code. + // We maybe need to add subclass codes here, or a callback to ask if a driver can + // handle a particular interface. + { + .class_code = TUD_USBTMC_APP_CLASS, + //.subclass_code = TUD_USBTMC_APP_SUBCLASS + .init = usbtmcd_init_cb, + .reset = usbtmcd_reset_cb, + .open = usbtmcd_open_cb, + .control_request = usbtmcd_control_request_cb, + .control_complete = usbtmcd_control_complete_cb, + .xfer_cb = usbtmcd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_DFU_RT + { + .class_code = TUD_DFU_APP_CLASS, + //.subclass_code = TUD_DFU_APP_SUBCLASS + .init = dfu_rtd_init, + .reset = dfu_rtd_reset, + .open = dfu_rtd_open, + .control_request = dfu_rtd_control_request, + .control_complete = dfu_rtd_control_complete, + .xfer_cb = dfu_rtd_xfer_cb, + .sof = NULL + }, + #endif + + #if CFG_TUD_NET + { + .class_code = +#if CFG_TUD_NET == OPT_NET_RNDIS + TUD_RNDIS_ITF_CLASS, +#else + TUSB_CLASS_CDC, +#endif + .init = netd_init, + .reset = netd_reset, + .open = netd_open, + .control_request = netd_control_request, + .control_complete = netd_control_complete, + .xfer_cb = netd_xfer_cb, + .sof = NULL + }, + #endif +}; + +enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SIZE(_usbd_driver) }; + +//--------------------------------------------------------------------+ +// DCD Event +//--------------------------------------------------------------------+ + +// Event queue +// OPT_MODE_DEVICE is used by OS NONE for mutex (disable usb isr) +OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t); +static osal_queue_t _usbd_q; + +//--------------------------------------------------------------------+ +// Prototypes +//--------------------------------------------------------------------+ +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id); +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request); +static bool process_set_config(uint8_t rhport, uint8_t cfg_num); +static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request); + +void usbd_control_reset(void); +void usbd_control_set_request(tusb_control_request_t const *request); +void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ); +bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes); + + +//--------------------------------------------------------------------+ +// Debugging +//--------------------------------------------------------------------+ +#if CFG_TUSB_DEBUG >= 2 +static char const* const _usbd_event_str[DCD_EVENT_COUNT] = +{ + "INVALID" , + "BUS_RESET" , + "UNPLUGGED" , + "SOF" , + "SUSPEND" , + "RESUME" , + "SETUP_RECEIVED" , + "XFER_COMPLETE" , + "FUNC_CALL" +}; + +// must be same driver order as usbd_class_drivers[] +static char const* const _usbd_driver_str[USBD_CLASS_DRIVER_COUNT] = +{ + #if CFG_TUD_CDC + "CDC", + #endif + #if CFG_TUD_MSC + "MSC", + #endif + #if CFG_TUD_HID + "HID", + #endif + #if CFG_TUD_MIDI + "MIDI", + #endif + #if CFG_TUD_VENDOR + "Vendor", + #endif + #if CFG_TUD_USBTMC + "USBTMC" + #endif + #if CFG_TUD_NET + "NET" + #endif +}; + +static char const* const _tusb_std_request_str[] = +{ + "Get Status" , + "Clear Feature" , + "Reserved" , + "Set Feature" , + "Reserved" , + "Set Address" , + "Get Descriptor" , + "Set Descriptor" , + "Get Configuration" , + "Set Configuration" , + "Get Interface" , + "Set Interface" , + "Synch Frame" +}; + +#endif + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ +bool tud_mounted(void) +{ + return _usbd_dev.configured; +} + +bool tud_suspended(void) +{ + return _usbd_dev.suspended; +} + +bool tud_remote_wakeup(void) +{ + // only wake up host if this feature is supported and enabled and we are suspended + TU_VERIFY (_usbd_dev.suspended && _usbd_dev.remote_wakeup_support && _usbd_dev.remote_wakeup_en ); + dcd_remote_wakeup(TUD_OPT_RHPORT); + return true; +} + +//--------------------------------------------------------------------+ +// USBD Task +//--------------------------------------------------------------------+ +bool tud_init (void) +{ + TU_LOG2("USBD init\r\n"); + + tu_varclr(&_usbd_dev); + + // Init device queue & task + _usbd_q = osal_queue_create(&_usbd_qdef); + TU_ASSERT(_usbd_q != NULL); + + // Init class drivers + for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) + { + TU_LOG2("%s init\r\n", _usbd_driver_str[i]); + _usbd_driver[i].init(); + } + + // Init device controller driver + dcd_init(TUD_OPT_RHPORT); + dcd_int_enable(TUD_OPT_RHPORT); + + return true; +} + +static void usbd_reset(uint8_t rhport) +{ + tu_varclr(&_usbd_dev); + + memset(_usbd_dev.itf2drv, DRVID_INVALID, sizeof(_usbd_dev.itf2drv)); // invalid mapping + memset(_usbd_dev.ep2drv , DRVID_INVALID, sizeof(_usbd_dev.ep2drv )); // invalid mapping + + usbd_control_reset(); + + for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) + { + if ( _usbd_driver[i].reset ) _usbd_driver[i].reset( rhport ); + } +} + +/* USB Device Driver task + * This top level thread manages all device controller event and delegates events to class-specific drivers. + * This should be called periodically within the mainloop or rtos thread. + * + @code + int main(void) + { + application_init(); + tusb_init(); + + while(1) // the mainloop + { + application_code(); + tud_task(); // tinyusb device task + } + } + @endcode + */ +void tud_task (void) +{ + // Skip if stack is not initialized + if ( !tusb_inited() ) return; + + // Loop until there is no more events in the queue + while (1) + { + dcd_event_t event; + + if ( !osal_queue_receive(_usbd_q, &event) ) return; + + TU_LOG2("USBD: event %s\r\n", event.event_id < DCD_EVENT_COUNT ? _usbd_event_str[event.event_id] : "CORRUPTED"); + + switch ( event.event_id ) + { + case DCD_EVENT_BUS_RESET: + usbd_reset(event.rhport); + break; + + case DCD_EVENT_UNPLUGGED: + usbd_reset(event.rhport); + + // invoke callback + if (tud_umount_cb) tud_umount_cb(); + break; + + case DCD_EVENT_SETUP_RECEIVED: + TU_LOG2_MEM(&event.setup_received, 8, 2); + + // Mark as connected after receiving 1st setup packet. + // But it is easier to set it every time instead of wasting time to check then set + _usbd_dev.connected = 1; + + // Process control request + if ( !process_control_request(event.rhport, &event.setup_received) ) + { + TU_LOG2(" Stall EP0\r\n"); + // Failed -> stall both control endpoint IN and OUT + dcd_edpt_stall(event.rhport, 0); + dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK); + } + break; + + case DCD_EVENT_XFER_COMPLETE: + { + // Invoke the class callback associated with the endpoint address + uint8_t const ep_addr = event.xfer_complete.ep_addr; + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const ep_dir = tu_edpt_dir(ep_addr); + + TU_LOG2(" Endpoint: 0x%02X, Bytes: %ld\r\n", ep_addr, event.xfer_complete.len); + + _usbd_dev.ep_status[epnum][ep_dir].busy = false; + + if ( 0 == epnum ) + { + usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + } + else + { + uint8_t const drv_id = _usbd_dev.ep2drv[epnum][ep_dir]; + TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,); + + TU_LOG2(" %s xfer callback\r\n", _usbd_driver_str[drv_id]); + _usbd_driver[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len); + } + } + break; + + case DCD_EVENT_SUSPEND: + if (tud_suspend_cb) tud_suspend_cb(_usbd_dev.remote_wakeup_en); + break; + + case DCD_EVENT_RESUME: + if (tud_resume_cb) tud_resume_cb(); + break; + + case DCD_EVENT_SOF: + for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ ) + { + if ( _usbd_driver[i].sof ) + { + _usbd_driver[i].sof(event.rhport); + } + } + break; + + case USBD_EVENT_FUNC_CALL: + if ( event.func_call.func ) event.func_call.func(event.func_call.param); + break; + + default: + TU_BREAKPOINT(); + break; + } + } +} + +//--------------------------------------------------------------------+ +// Control Request Parser & Handling +//--------------------------------------------------------------------+ + +// Helper to invoke class driver control request handler +static bool invoke_class_control(uint8_t rhport, uint8_t drvid, tusb_control_request_t const * request) +{ + TU_ASSERT(_usbd_driver[drvid].control_request); + + usbd_control_set_complete_callback(_usbd_driver[drvid].control_complete); + TU_LOG2(" %s control request\r\n", _usbd_driver_str[drvid]); + return _usbd_driver[drvid].control_request(rhport, request); +} + +// This handles the actual request and its response. +// return false will cause its caller to stall control endpoint +static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request) +{ + usbd_control_set_complete_callback(NULL); + + TU_ASSERT(p_request->bmRequestType_bit.type < TUSB_REQ_TYPE_INVALID); + + // Vendor request + if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR ) + { + TU_VERIFY(tud_vendor_control_request_cb); + + if (tud_vendor_control_complete_cb) usbd_control_set_complete_callback(tud_vendor_control_complete_cb); + return tud_vendor_control_request_cb(rhport, p_request); + } + +#if CFG_TUSB_DEBUG > 1 + if (TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type && p_request->bRequest <= TUSB_REQ_SYNCH_FRAME) + { + TU_LOG2(" %s\r\n", _tusb_std_request_str[p_request->bRequest]); + } +#endif + + switch ( p_request->bmRequestType_bit.recipient ) + { + //------------- Device Requests e.g in enumeration -------------// + case TUSB_REQ_RCPT_DEVICE: + if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type ) + { + // Non standard request is not supported + TU_BREAKPOINT(); + return false; + } + + switch ( p_request->bRequest ) + { + case TUSB_REQ_SET_ADDRESS: + // Depending on mcu, status phase could be sent either before or after changing device address, + // or even require stack to not response with status at all + // Therefore DCD must take full responsibility to response and include zlp status packet if needed. + usbd_control_set_request(p_request); // set request since DCD has no access to tud_control_status() API + dcd_set_address(rhport, (uint8_t) p_request->wValue); + // skip tud_control_status() + _usbd_dev.addressed = 1; + break; + + case TUSB_REQ_GET_CONFIGURATION: + { + uint8_t cfgnum = _usbd_dev.configured ? 1 : 0; + tud_control_xfer(rhport, p_request, &cfgnum, 1); + } + break; + + case TUSB_REQ_SET_CONFIGURATION: + { + uint8_t const cfg_num = (uint8_t) p_request->wValue; + + dcd_set_config(rhport, cfg_num); + + if ( !_usbd_dev.configured && cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) ); + + _usbd_dev.configured = cfg_num ? 1 : 0; + + tud_control_status(rhport, p_request); + } + break; + + case TUSB_REQ_GET_DESCRIPTOR: + TU_VERIFY( process_get_descriptor(rhport, p_request) ); + break; + + case TUSB_REQ_SET_FEATURE: + // Only support remote wakeup for device feature + TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); + + // Host may enable remote wake up before suspending especially HID device + _usbd_dev.remote_wakeup_en = true; + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_CLEAR_FEATURE: + // Only support remote wakeup for device feature + TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue); + + // Host may disable remote wake up after resuming + _usbd_dev.remote_wakeup_en = false; + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_GET_STATUS: + { + // Device status bit mask + // - Bit 0: Self Powered + // - Bit 1: Remote Wakeup enabled + uint16_t status = (_usbd_dev.self_powered ? 1 : 0) | (_usbd_dev.remote_wakeup_en ? 2 : 0); + tud_control_xfer(rhport, p_request, &status, 2); + } + break; + + // Unknown/Unsupported request + default: TU_BREAKPOINT(); return false; + } + break; + + //------------- Class/Interface Specific Request -------------// + case TUSB_REQ_RCPT_INTERFACE: + { + uint8_t const itf = tu_u16_low(p_request->wIndex); + TU_VERIFY(itf < TU_ARRAY_SIZE(_usbd_dev.itf2drv)); + + uint8_t const drvid = _usbd_dev.itf2drv[itf]; + TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT); + + if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) + { + switch ( p_request->bRequest ) + { + case TUSB_REQ_GET_INTERFACE: + { + // TODO not support alternate interface yet + uint8_t alternate = 0; + tud_control_xfer(rhport, p_request, &alternate, 1); + } + break; + + case TUSB_REQ_SET_INTERFACE: + { + uint8_t const alternate = (uint8_t) p_request->wValue; + + // TODO not support alternate interface yet + TU_ASSERT(alternate == 0); + tud_control_status(rhport, p_request); + } + break; + + default: + // forward to class driver: "STD request to Interface" + // GET HID REPORT DESCRIPTOR falls into this case + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); + break; + } + }else + { + // forward to class driver: "non-STD request to Interface" + TU_VERIFY(invoke_class_control(rhport, drvid, p_request)); + } + } + break; + + //------------- Endpoint Request -------------// + case TUSB_REQ_RCPT_ENDPOINT: + { + uint8_t const ep_addr = tu_u16_low(p_request->wIndex); + uint8_t const ep_num = tu_edpt_number(ep_addr); + uint8_t const ep_dir = tu_edpt_dir(ep_addr); + + TU_ASSERT(ep_num < TU_ARRAY_SIZE(_usbd_dev.ep2drv) ); + + uint8_t const drvid = _usbd_dev.ep2drv[ep_num][ep_dir]; + + bool ret = false; + + // Handle STD request to endpoint + if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + { + // force return true for standard request + ret = true; + + switch ( p_request->bRequest ) + { + case TUSB_REQ_GET_STATUS: + { + uint16_t status = usbd_edpt_stalled(rhport, ep_addr) ? 0x0001 : 0x0000; + tud_control_xfer(rhport, p_request, &status, 2); + } + break; + + case TUSB_REQ_CLEAR_FEATURE: + if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) + { + usbd_edpt_clear_stall(rhport, ep_addr); + } + tud_control_status(rhport, p_request); + break; + + case TUSB_REQ_SET_FEATURE: + if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue ) + { + usbd_edpt_stall(rhport, ep_addr); + } + tud_control_status(rhport, p_request); + break; + + // Unknown/Unsupported request + default: TU_BREAKPOINT(); return false; + } + } + + if (drvid < 0xFF) { + TU_ASSERT(drvid < USBD_CLASS_DRIVER_COUNT); + + // Some classes such as USBTMC needs to clear/re-init its buffer when receiving CLEAR_FEATURE request + // We will forward all request targeted endpoint to class drivers after + // - For class-type requests: driver is fully responsible to reply to host + // - For std-type requests : driver init/re-init internal variable/buffer only, and + // must not call tud_control_status(), driver's return value will have no effect. + // EP state has already affected (stalled/cleared) + if ( invoke_class_control(rhport, drvid, p_request) ) ret = true; + } + + if ( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type ) + { + // Set complete callback = NULL since it can also stall the request. + usbd_control_set_complete_callback(NULL); + } + + return ret; + } + break; + + // Unknown recipient + default: TU_BREAKPOINT(); return false; + } + + return true; +} + +// Process Set Configure Request +// This function parse configuration descriptor & open drivers accordingly +static bool process_set_config(uint8_t rhport, uint8_t cfg_num) +{ + tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_descriptor_configuration_cb(cfg_num-1); // index is cfg_num-1 + TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION); + + // Parse configuration descriptor + _usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0; + _usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0; + + // Parse interface descriptor + uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t); + uint8_t const * desc_end = ((uint8_t const*) desc_cfg) + desc_cfg->wTotalLength; + + while( p_desc < desc_end ) + { + // Each interface always starts with Interface or Association descriptor + if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) ) + { + p_desc = tu_desc_next(p_desc); // ignore Interface Association + }else + { + TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) ); + + tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc; + + // Check if class is supported + uint8_t drv_id; + for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++) + { + if ( _usbd_driver[drv_id].class_code == desc_itf->bInterfaceClass ) break; + } + TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT ); + + // Interface number must not be used already TODO alternate interface + TU_ASSERT( DRVID_INVALID == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] ); + _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id; + + uint16_t itf_len=0; + TU_LOG2(" %s open\r\n", _usbd_driver_str[drv_id]); + TU_ASSERT( _usbd_driver[drv_id].open(rhport, desc_itf, &itf_len) ); + TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) ); + + mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id); + + p_desc += itf_len; // next interface + } + } + + // invoke callback + if (tud_mount_cb) tud_mount_cb(); + + return true; +} + +// Helper marking endpoint of interface belongs to class driver +static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id) +{ + uint16_t len = 0; + + while( len < desc_len ) + { + if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) ) + { + uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress; + + ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id; + } + + len = (uint16_t)(len + tu_desc_len(p_desc)); + p_desc = tu_desc_next(p_desc); + } +} + +// return descriptor's buffer and update desc_len +static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const * p_request) +{ + tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue); + uint8_t const desc_index = tu_u16_low( p_request->wValue ); + + switch(desc_type) + { + case TUSB_DESC_DEVICE: + { + uint16_t len = sizeof(tusb_desc_device_t); + + // Only send up to EP0 Packet Size if not addressed + // This only happens with the very first get device descriptor and EP0 size = 8 or 16. + if ((CFG_TUD_ENDPOINT0_SIZE < sizeof(tusb_desc_device_t)) && !_usbd_dev.addressed) + { + len = CFG_TUD_ENDPOINT0_SIZE; + + // Hack here: we modify the request length to prevent usbd_control response with zlp + ((tusb_control_request_t*) p_request)->wLength = CFG_TUD_ENDPOINT0_SIZE; + } + + return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), len); + } + break; + + case TUSB_DESC_BOS: + { + // requested by host if USB > 2.0 ( i.e 2.1 or 3.x ) + if (!tud_descriptor_bos_cb) return false; + + tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb(); + uint16_t total_len; + memcpy(&total_len, &desc_bos->wTotalLength, 2); // possibly mis-aligned memory + + return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len); + } + break; + + case TUSB_DESC_CONFIGURATION: + { + tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index); + TU_ASSERT(desc_config); + + uint16_t total_len; + memcpy(&total_len, &desc_config->wTotalLength, 2); // possibly mis-aligned memory + + return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len); + } + break; + + case TUSB_DESC_STRING: + // String Descriptor always uses the desc set from user + if ( desc_index == 0xEE ) + { + // The 0xEE index string is a Microsoft OS Descriptors. + // https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors + return false; + }else + { + uint8_t const* desc_str = (uint8_t const*) tud_descriptor_string_cb(desc_index, p_request->wIndex); + TU_ASSERT(desc_str); + + // first byte of descriptor is its size + return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]); + } + break; + + case TUSB_DESC_DEVICE_QUALIFIER: + // TODO If not highspeed capable stall this request otherwise + // return the descriptor that could work in highspeed + return false; + break; + + default: return false; + } + + return true; +} + +//--------------------------------------------------------------------+ +// DCD Event Handler +//--------------------------------------------------------------------+ +void dcd_event_handler(dcd_event_t const * event, bool in_isr) +{ + switch (event->event_id) + { + case DCD_EVENT_UNPLUGGED: + _usbd_dev.connected = 0; + _usbd_dev.addressed = 0; + _usbd_dev.configured = 0; + _usbd_dev.suspended = 0; + osal_queue_send(_usbd_q, event, in_isr); + break; + + case DCD_EVENT_SOF: + return; // skip SOF event for now + break; + + case DCD_EVENT_SUSPEND: + // NOTE: When plugging/unplugging device, the D+/D- state are unstable and can accidentally meet the + // SUSPEND condition ( Idle for 3ms ). Some MCUs such as SAMD doesn't distinguish suspend vs disconnect as well. + // We will skip handling SUSPEND/RESUME event if not currently connected + if ( _usbd_dev.connected ) + { + _usbd_dev.suspended = 1; + osal_queue_send(_usbd_q, event, in_isr); + } + break; + + case DCD_EVENT_RESUME: + // skip event if not connected (especially required for SAMD) + if ( _usbd_dev.connected ) + { + _usbd_dev.suspended = 0; + osal_queue_send(_usbd_q, event, in_isr); + } + break; + + default: + osal_queue_send(_usbd_q, event, in_isr); + break; + } +} + +void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = eid, }; + dcd_event_handler(&event, in_isr); +} + +void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED }; + memcpy(&event.setup_received, setup, 8); + + dcd_event_handler(&event, in_isr); +} + +void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr) +{ + dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE }; + + event.xfer_complete.ep_addr = ep_addr; + event.xfer_complete.len = xferred_bytes; + event.xfer_complete.result = result; + + dcd_event_handler(&event, in_isr); +} + +//--------------------------------------------------------------------+ +// Helper +//--------------------------------------------------------------------+ + +// Parse consecutive endpoint descriptors (IN & OUT) +bool usbd_open_edpt_pair(uint8_t rhport, uint8_t const* p_desc, uint8_t ep_count, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in) +{ + for(int i=0; i<ep_count; i++) + { + tusb_desc_endpoint_t const * desc_ep = (tusb_desc_endpoint_t const *) p_desc; + + TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && xfer_type == desc_ep->bmAttributes.xfer); + TU_ASSERT(dcd_edpt_open(rhport, desc_ep)); + + if ( tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN ) + { + (*ep_in) = desc_ep->bEndpointAddress; + }else + { + (*ep_out) = desc_ep->bEndpointAddress; + } + + p_desc = tu_desc_next(p_desc); + } + + return true; +} + +// Helper to defer an isr function +void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr) +{ + dcd_event_t event = + { + .rhport = 0, + .event_id = USBD_EVENT_FUNC_CALL, + }; + + event.func_call.func = func; + event.func_call.param = param; + + dcd_event_handler(&event, in_isr); +} + +//--------------------------------------------------------------------+ +// USBD Endpoint API +//--------------------------------------------------------------------+ + +bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + TU_VERIFY( dcd_edpt_xfer(rhport, ep_addr, buffer, total_bytes) ); + _usbd_dev.ep_status[epnum][dir].busy = true; + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, total_bytes); + + return true; +} + +bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + return _usbd_dev.ep_status[epnum][dir].busy; +} + +void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + dcd_edpt_stall(rhport, ep_addr); + _usbd_dev.ep_status[epnum][dir].stalled = true; + _usbd_dev.ep_status[epnum][dir].busy = true; +} + +void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr) +{ + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + dcd_edpt_clear_stall(rhport, ep_addr); + _usbd_dev.ep_status[epnum][dir].stalled = false; + _usbd_dev.ep_status[epnum][dir].busy = false; +} + +bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr) +{ + (void) rhport; + + uint8_t const epnum = tu_edpt_number(ep_addr); + uint8_t const dir = tu_edpt_dir(ep_addr); + + return _usbd_dev.ep_status[epnum][dir].stalled; +} + +#endif diff --git a/src/device/usbd.h b/src/device/usbd.h index b3665d7f2..07163a013 100644 --- a/src/device/usbd.h +++ b/src/device/usbd.h @@ -1,332 +1,419 @@ -/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2019 Ha Thach (tinyusb.org)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * This file is part of the TinyUSB stack.
- */
-
-/** \ingroup group_usbd
- * @{ */
-
-#ifndef _TUSB_USBD_H_
-#define _TUSB_USBD_H_
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#include "common/tusb_common.h"
-#include "dcd.h"
-
-//--------------------------------------------------------------------+
-// Application API
-//--------------------------------------------------------------------+
-
-// Init device stack
-bool tud_init (void);
-
-// Task function should be called in main/rtos loop
-void tud_task (void);
-
-// Check if device is connected and configured
-bool tud_mounted(void);
-
-// Check if device is suspended
-bool tud_suspended(void);
-
-// Check if device is ready to transfer
-static inline bool tud_ready(void)
-{
- return tud_mounted() && !tud_suspended();
-}
-
-// Remote wake up host, only if suspended and enabled by host
-bool tud_remote_wakeup(void);
-
-// Carry out Data and Status stage of control transfer
-// - If len = 0, it is equivalent to sending status only
-// - If len > wLength : it will be truncated
-bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len);
-
-// Send STATUS (zero length) packet
-bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request);
-
-//--------------------------------------------------------------------+
-// Application Callbacks (WEAK is optional)
-//--------------------------------------------------------------------+
-
-// Invoked when received GET DEVICE DESCRIPTOR request
-// Application return pointer to descriptor
-uint8_t const * tud_descriptor_device_cb(void);
-
-// Invoked when received GET BOS DESCRIPTOR request
-// Application return pointer to descriptor
-TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void);
-
-// Invoked when received GET CONFIGURATION DESCRIPTOR request
-// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
-uint8_t const * tud_descriptor_configuration_cb(uint8_t index);
-
-// Invoked when received GET STRING DESCRIPTOR request
-// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
-uint16_t const* tud_descriptor_string_cb(uint8_t index);
-
-// Invoked when device is mounted (configured)
-TU_ATTR_WEAK void tud_mount_cb(void);
-
-// Invoked when device is unmounted
-TU_ATTR_WEAK void tud_umount_cb(void);
-
-// Invoked when usb bus is suspended
-// Within 7ms, device must draw an average of current less than 2.5 mA from bus
-TU_ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en);
-
-// Invoked when usb bus is resumed
-TU_ATTR_WEAK void tud_resume_cb(void);
-
-// Invoked when received control request with VENDOR TYPE
-TU_ATTR_WEAK bool tud_vendor_control_request_cb(uint8_t rhport, tusb_control_request_t const * request);
-TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const * request);
-
-
-//--------------------------------------------------------------------+
-// Binary Device Object Store (BOS) Descriptor Templates
-//--------------------------------------------------------------------+
-
-#define TUD_BOS_DESC_LEN 5
-
-// total length, number of device caps
-#define TUD_BOS_DESCRIPTOR(_total_len, _caps_num) \
- 5, TUSB_DESC_BOS, U16_TO_U8S_LE(_total_len), _caps_num
-
-// Device Capability Platform 128-bit UUID + Data
-#define TUD_BOS_PLATFORM_DESCRIPTOR(...) \
- 4+TU_ARGS_NUM(__VA_ARGS__), TUSB_DESC_DEVICE_CAPABILITY, DEVICE_CAPABILITY_PLATFORM, 0x00, __VA_ARGS__
-
-//------------- WebUSB BOS Platform -------------//
-
-// Descriptor Length
-#define TUD_BOS_WEBUSB_DESC_LEN 24
-
-// Vendor Code, iLandingPage
-#define TUD_BOS_WEBUSB_DESCRIPTOR(_vendor_code, _ipage) \
- TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_WEBUSB_UUID, U16_TO_U8S_LE(0x0100), _vendor_code, _ipage)
-
-#define TUD_BOS_WEBUSB_UUID \
- 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, \
- 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65
-
-//------------- Microsoft OS 2.0 Platform -------------//
-#define TUD_BOS_MICROSOFT_OS_DESC_LEN 28
-
-// Total Length of descriptor set, vendor code
-#define TUD_BOS_MS_OS_20_DESCRIPTOR(_desc_set_len, _vendor_code) \
- TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_MS_OS_20_UUID, U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(_desc_set_len), _vendor_code, 0)
-
-#define TUD_BOS_MS_OS_20_UUID \
- 0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, \
- 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F
-
-//--------------------------------------------------------------------+
-// Configuration & Interface Descriptor Templates
-//--------------------------------------------------------------------+
-
-//------------- Configuration -------------//
-#define TUD_CONFIG_DESC_LEN (9)
-
-// Interface count, string index, total length, attribute, power in mA
-#define TUD_CONFIG_DESCRIPTOR(_itfcount, _stridx, _total_len, _attribute, _power_ma) \
- 9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, 1, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2
-
-//------------- CDC -------------//
-
-// Length of template descriptor: 66 bytes
-#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7)
-
-// CDC Descriptor Template
-// Interface number, string index, EP notification address and size, EP data address (out, in) and size.
-#define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \
- /* Interface Associate */\
- 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\
- /* CDC Control Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, _stridx,\
- /* CDC Header */\
- 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\
- /* CDC Call */\
- 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\
- /* CDC ACM: support line request */\
- 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\
- /* CDC Union */\
- 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\
- /* Endpoint Notification */\
- 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 16,\
- /* CDC Data Interface */\
- 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\
- /* Endpoint Out */\
- 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
-
-//------------- MSC -------------//
-
-// Length of template descriptor: 23 bytes
-#define TUD_MSC_DESC_LEN (9 + 7 + 7)
-
-// Interface number, string index, EP Out & EP In address, EP size
-#define TUD_MSC_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
- /* Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_MSC, MSC_SUBCLASS_SCSI, MSC_PROTOCOL_BOT, _stridx,\
- /* Endpoint Out */\
- 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
-
-//------------- HID -------------//
-
-// Length of template descriptor: 25 bytes
-#define TUD_HID_DESC_LEN (9 + 9 + 7)
-
-// HID Input only descriptor
-// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval
-#define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \
- /* Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\
- /* HID descriptor */\
- 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
-
-// Length of template descriptor: 32 bytes
-#define TUD_HID_INOUT_DESC_LEN (9 + 9 + 7 + 7)
-
-// HID Input & Output descriptor
-// Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval
-#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \
- /* Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\
- /* HID descriptor */\
- 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\
- /* Endpoint Out */\
- 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval, \
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
-
-//------------- MIDI -------------//
-
-// Length of template descriptor (96 bytes)
-#define TUD_MIDI_DESC_LEN (9 + 9 + 9 + 7 + 6 + 6 + 9 + 9 + 7 + 5 + 7 + 5)
-
-// MIDI simple descriptor
-// - 1 Embedded Jack In connected to 1 External Jack Out
-// - 1 Embedded Jack out connected to 1 External Jack In
-#define TUD_MIDI_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
- /* Audio Control (AC) Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_PROTOCOL_V1, _stridx,\
- /* AC Header */\
- 9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0009), 1, (uint8_t)((_itfnum)+1),\
- /* MIDI Streaming (MS) Interface */\
- 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_PROTOCOL_V1, 0,\
- /* MS Header */\
- 7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0025),\
- /* MS In Jack (Embedded) */\
- 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, 1, 0,\
- /* MS In Jack (External) */\
- 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, 2, 0,\
- /* MS Out Jack (Embedded), connected to In Jack External */\
- 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, 3, 1, 2, 1, 0,\
- /* MS Out Jack (External), connected to In Jack Embedded */\
- 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, 4, 1, 1, 1, 0,\
- /* Endpoint Out */\
- 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
- /* MS Endpoint (connected to embedded jack in) */\
- 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 1,\
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
- /* MS Endpoint (connected to embedded jack out) */\
- 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 3
-
-//------------- TUD_USBTMC/USB488 -------------//
-#define TUD_USBTMC_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC)
-#define TUD_USBTMC_APP_SUBCLASS 0x03u
-
-#define TUD_USBTMC_PROTOCOL_STD 0x00u
-#define TUD_USBTMC_PROTOCOL_USB488 0x01u
-
-// Interface number, number of endpoints, EP string index, USB_TMC_PROTOCOL*, bulk-out endpoint ID,
-// bulk-in endpoint ID
-#define TUD_USBTMC_IF_DESCRIPTOR(_itfnum, _bNumEndpoints, _stridx, _itfProtocol) \
-/* Interface */ \
- 0x09, TUSB_DESC_INTERFACE, _itfnum, 0x00, _bNumEndpoints, TUD_USBTMC_APP_CLASS, TUD_USBTMC_APP_SUBCLASS, _itfProtocol, _stridx
-
-#define TUD_USBTMC_IF_DESCRIPTOR_LEN 9u
-
-#define TUD_USBTMC_BULK_DESCRIPTORS(_epout, _epin, _bulk_epsize) \
-/* Endpoint Out */ \
-7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u, \
-/* Endpoint In */ \
-7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u
-
-#define TUD_USBTMC_BULK_DESCRIPTORS_LEN (7u+7u)
-
-/* optional interrupt endpoint */ \
-// _int_pollingInterval : for LS/FS, expressed in frames (1ms each). 16 may be a good number?
-#define TUD_USBTMC_INT_DESCRIPTOR(_ep_interrupt, _ep_interrupt_size, _int_pollingInterval ) \
-7, TUSB_DESC_ENDPOINT, _ep_interrupt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_interrupt_size), 0x16
-
-#define TUD_USBTMC_INT_DESCRIPTOR_LEN (7u)
-
-
-//------------- Vendor -------------//
-#define TUD_VENDOR_DESC_LEN (9+7+7)
-
-// Interface number, string index, EP Out & IN address, EP size
-#define TUD_VENDOR_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
- /* Interface */\
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_VENDOR_SPECIFIC, 0x00, 0x00, _stridx,\
- /* Endpoint Out */\
- 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
- /* Endpoint In */\
- 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
-
-//------------- DFU Runtime -------------//
-#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC)
-#define TUD_DFU_APP_SUBCLASS 0x01u
-
-// Length of template descriptr: 18 bytes
-#define TUD_DFU_RT_DESC_LEN (9 + 9)
-
-// DFU runtime descriptor
-// Interface number, string index, attributes, detach timeout, transfer size
-#define TUD_DFU_RT_DESCRIPTOR(_itfnum, _stridx, _attr, _timeout, _xfer_size) \
- /* Interface */ \
- 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_RT, _stridx, \
- /* Function */ \
- 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101)
-
-
-#ifdef __cplusplus
- }
-#endif
-
-#endif /* _TUSB_USBD_H_ */
-
-/** @} */
+/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +/** \ingroup group_usbd + * @{ */ + +#ifndef _TUSB_USBD_H_ +#define _TUSB_USBD_H_ + +#ifdef __cplusplus + extern "C" { +#endif + +#include "common/tusb_common.h" +#include "dcd.h" + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +// Init device stack +bool tud_init (void); + +// Task function should be called in main/rtos loop +void tud_task (void); + +// Interrupt handler, name alias to DCD +#define tud_isr dcd_isr + +// Check if device is connected and configured +bool tud_mounted(void); + +// Check if device is suspended +bool tud_suspended(void); + +// Check if device is ready to transfer +static inline bool tud_ready(void) +{ + return tud_mounted() && !tud_suspended(); +} + +// Remote wake up host, only if suspended and enabled by host +bool tud_remote_wakeup(void); + +// Carry out Data and Status stage of control transfer +// - If len = 0, it is equivalent to sending status only +// - If len > wLength : it will be truncated +bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len); + +// Send STATUS (zero length) packet +bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request); + +//--------------------------------------------------------------------+ +// Application Callbacks (WEAK is optional) +//--------------------------------------------------------------------+ + +// Invoked when received GET DEVICE DESCRIPTOR request +// Application return pointer to descriptor +uint8_t const * tud_descriptor_device_cb(void); + +// Invoked when received GET BOS DESCRIPTOR request +// Application return pointer to descriptor +TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void); + +// Invoked when received GET CONFIGURATION DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint8_t const * tud_descriptor_configuration_cb(uint8_t index); + +// Invoked when received GET STRING DESCRIPTOR request +// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete +uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid); + +// Invoked when device is mounted (configured) +TU_ATTR_WEAK void tud_mount_cb(void); + +// Invoked when device is unmounted +TU_ATTR_WEAK void tud_umount_cb(void); + +// Invoked when usb bus is suspended +// Within 7ms, device must draw an average of current less than 2.5 mA from bus +TU_ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en); + +// Invoked when usb bus is resumed +TU_ATTR_WEAK void tud_resume_cb(void); + +// Invoked when received control request with VENDOR TYPE +TU_ATTR_WEAK bool tud_vendor_control_request_cb(uint8_t rhport, tusb_control_request_t const * request); +TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const * request); + + +//--------------------------------------------------------------------+ +// Binary Device Object Store (BOS) Descriptor Templates +//--------------------------------------------------------------------+ + +#define TUD_BOS_DESC_LEN 5 + +// total length, number of device caps +#define TUD_BOS_DESCRIPTOR(_total_len, _caps_num) \ + 5, TUSB_DESC_BOS, U16_TO_U8S_LE(_total_len), _caps_num + +// Device Capability Platform 128-bit UUID + Data +#define TUD_BOS_PLATFORM_DESCRIPTOR(...) \ + 4+TU_ARGS_NUM(__VA_ARGS__), TUSB_DESC_DEVICE_CAPABILITY, DEVICE_CAPABILITY_PLATFORM, 0x00, __VA_ARGS__ + +//------------- WebUSB BOS Platform -------------// + +// Descriptor Length +#define TUD_BOS_WEBUSB_DESC_LEN 24 + +// Vendor Code, iLandingPage +#define TUD_BOS_WEBUSB_DESCRIPTOR(_vendor_code, _ipage) \ + TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_WEBUSB_UUID, U16_TO_U8S_LE(0x0100), _vendor_code, _ipage) + +#define TUD_BOS_WEBUSB_UUID \ + 0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, \ + 0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65 + +//------------- Microsoft OS 2.0 Platform -------------// +#define TUD_BOS_MICROSOFT_OS_DESC_LEN 28 + +// Total Length of descriptor set, vendor code +#define TUD_BOS_MS_OS_20_DESCRIPTOR(_desc_set_len, _vendor_code) \ + TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_MS_OS_20_UUID, U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(_desc_set_len), _vendor_code, 0) + +#define TUD_BOS_MS_OS_20_UUID \ + 0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, \ + 0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F + +//--------------------------------------------------------------------+ +// Configuration & Interface Descriptor Templates +//--------------------------------------------------------------------+ + +//------------- Configuration -------------// +#define TUD_CONFIG_DESC_LEN (9) + +// Interface count, string index, total length, attribute, power in mA +#define TUD_CONFIG_DESCRIPTOR(_itfcount, _stridx, _total_len, _attribute, _power_ma) \ + 9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, 1, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2 + +//------------- CDC -------------// + +// Length of template descriptor: 66 bytes +#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7) + +// CDC Descriptor Template +// Interface number, string index, EP notification address and size, EP data address (out, in) and size. +#define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ + /* Interface Associate */\ + 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, _stridx,\ + /* CDC Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\ + /* CDC Call */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\ + /* CDC ACM: support line request */\ + 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\ + /* CDC Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 16,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- MSC -------------// + +// Length of template descriptor: 23 bytes +#define TUD_MSC_DESC_LEN (9 + 7 + 7) + +// Interface number, string index, EP Out & EP In address, EP size +#define TUD_MSC_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_MSC, MSC_SUBCLASS_SCSI, MSC_PROTOCOL_BOT, _stridx,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- HID -------------// + +// Length of template descriptor: 25 bytes +#define TUD_HID_DESC_LEN (9 + 9 + 7) + +// HID Input only descriptor +// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval +#define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ + /* HID descriptor */\ + 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval + +// Length of template descriptor: 32 bytes +#define TUD_HID_INOUT_DESC_LEN (9 + 9 + 7 + 7) + +// HID Input & Output descriptor +// Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval +#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (uint8_t)((_boot_protocol) ? HID_SUBCLASS_BOOT : 0), _boot_protocol, _stridx,\ + /* HID descriptor */\ + 9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval, \ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval + +//------------- MIDI -------------// + +// Length of template descriptor (96 bytes) +#define TUD_MIDI_DESC_LEN (9 + 9 + 9 + 7 + 6 + 6 + 9 + 9 + 7 + 5 + 7 + 5) + +// MIDI simple descriptor +// - 1 Embedded Jack In connected to 1 External Jack Out +// - 1 Embedded Jack out connected to 1 External Jack In +#define TUD_MIDI_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Audio Control (AC) Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_PROTOCOL_V1, _stridx,\ + /* AC Header */\ + 9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0009), 1, (uint8_t)((_itfnum)+1),\ + /* MIDI Streaming (MS) Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_PROTOCOL_V1, 0,\ + /* MS Header */\ + 7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0025),\ + /* MS In Jack (Embedded) */\ + 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, 1, 0,\ + /* MS In Jack (External) */\ + 6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, 2, 0,\ + /* MS Out Jack (Embedded), connected to In Jack External */\ + 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, 3, 1, 2, 1, 0,\ + /* MS Out Jack (External), connected to In Jack Embedded */\ + 9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, 4, 1, 1, 1, 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* MS Endpoint (connected to embedded jack in) */\ + 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 1,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* MS Endpoint (connected to embedded jack out) */\ + 5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 3 + +//------------- TUD_USBTMC/USB488 -------------// +#define TUD_USBTMC_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) +#define TUD_USBTMC_APP_SUBCLASS 0x03u + +#define TUD_USBTMC_PROTOCOL_STD 0x00u +#define TUD_USBTMC_PROTOCOL_USB488 0x01u + +// Interface number, number of endpoints, EP string index, USB_TMC_PROTOCOL*, bulk-out endpoint ID, +// bulk-in endpoint ID +#define TUD_USBTMC_IF_DESCRIPTOR(_itfnum, _bNumEndpoints, _stridx, _itfProtocol) \ +/* Interface */ \ + 0x09, TUSB_DESC_INTERFACE, _itfnum, 0x00, _bNumEndpoints, TUD_USBTMC_APP_CLASS, TUD_USBTMC_APP_SUBCLASS, _itfProtocol, _stridx + +#define TUD_USBTMC_IF_DESCRIPTOR_LEN 9u + +#define TUD_USBTMC_BULK_DESCRIPTORS(_epout, _epin, _bulk_epsize) \ +/* Endpoint Out */ \ +7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u, \ +/* Endpoint In */ \ +7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_bulk_epsize), 0u + +#define TUD_USBTMC_BULK_DESCRIPTORS_LEN (7u+7u) + +/* optional interrupt endpoint */ \ +// _int_pollingInterval : for LS/FS, expressed in frames (1ms each). 16 may be a good number? +#define TUD_USBTMC_INT_DESCRIPTOR(_ep_interrupt, _ep_interrupt_size, _int_pollingInterval ) \ +7, TUSB_DESC_ENDPOINT, _ep_interrupt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_interrupt_size), 0x16 + +#define TUD_USBTMC_INT_DESCRIPTOR_LEN (7u) + + +//------------- Vendor -------------// +#define TUD_VENDOR_DESC_LEN (9+7+7) + +// Interface number, string index, EP Out & IN address, EP size +#define TUD_VENDOR_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_VENDOR_SPECIFIC, 0x00, 0x00, _stridx,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + +//------------- DFU Runtime -------------// +#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC) +#define TUD_DFU_APP_SUBCLASS 0x01u + +// Length of template descriptr: 18 bytes +#define TUD_DFU_RT_DESC_LEN (9 + 9) + +// DFU runtime descriptor +// Interface number, string index, attributes, detach timeout, transfer size +#define TUD_DFU_RT_DESCRIPTOR(_itfnum, _stridx, _attr, _timeout, _xfer_size) \ + /* Interface */ \ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_RT, _stridx, \ + /* Function */ \ + 9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101) + + +//------------- CDC-ECM -------------// + +// Length of template descriptor: 62 bytes +#define TUD_CDC_ECM_DESC_LEN (9+5+5+13+7+9+7+7) + +// CDC-ECM Descriptor Template +// Interface number, description string index, MAC address string index, EP notification address and size, EP data address (out, in), and size, max segment size. +#define TUD_CDC_ECM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize) \ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL, 0, _desc_stridx,\ + /* CDC-ECM Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\ + /* CDC-ECM Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* CDC-ECM Functional Descriptor */\ + 13, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ETHERNET_NETWORKING, _mac_stridx, 0, 0, 0, 0, U16_TO_U8S_LE(_maxsegmentsize), U16_TO_U8S_LE(0), 0,\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 1,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + +//------------- RNDIS -------------// + +#if 0 + /* Windows XP */ + #define TUD_RNDIS_ITF_CLASS TUSB_CLASS_CDC + #define TUD_RNDIS_ITF_SUBCLASS CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL + #define TUD_RNDIS_ITF_PROTOCOL CDC_COMM_PROTOCOL_MICROSOFT_RNDIS +#else + /* Windows 7+ */ + #define TUD_RNDIS_ITF_CLASS 0xE0 + #define TUD_RNDIS_ITF_SUBCLASS 0x01 + #define TUD_RNDIS_ITF_PROTOCOL 0x03 +#endif + +// Length of template descriptor: 66 bytes +#define TUD_RNDIS_DESC_LEN (8+9+5+5+4+5+7+9+7+7) + +// RNDIS Descriptor Template +// Interface number, string index, EP notification address and size, EP data address (out, in) and size. +#define TUD_RNDIS_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ + /* Interface Association */\ + 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUD_RNDIS_ITF_CLASS, TUD_RNDIS_ITF_SUBCLASS, TUD_RNDIS_ITF_PROTOCOL, 0,\ + /* CDC Control Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUD_RNDIS_ITF_CLASS, TUD_RNDIS_ITF_SUBCLASS, TUD_RNDIS_ITF_PROTOCOL, _stridx,\ + /* CDC-ACM Header */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0110),\ + /* CDC Call Management */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (uint8_t)((_itfnum) + 1),\ + /* ACM */\ + 4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 0,\ + /* CDC Union */\ + 5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\ + /* Endpoint Notification */\ + 7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 1,\ + /* CDC Data Interface */\ + 9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + +//------------- CDC-EEM -------------// + +// Length of template descriptor: 23 bytes +#define TUD_CDC_EEM_DESC_LEN (9+7+7) + +// CDC-EEM Descriptor Template +// Interface number, description string index, EP data address (out, in) and size. +#define TUD_CDC_EEM_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \ + /* EEM Interface */\ + 9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL, CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL, _stridx,\ + /* Endpoint In */\ + 7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\ + /* Endpoint Out */\ + 7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0 + + +#ifdef __cplusplus + } +#endif + +#endif /* _TUSB_USBD_H_ */ + +/** @} */ diff --git a/src/device/usbd_control.c b/src/device/usbd_control.c index e0352e7e2..4fd40c440 100644 --- a/src/device/usbd_control.c +++ b/src/device/usbd_control.c @@ -1,189 +1,210 @@ -/*
- * The MIT License (MIT)
- *
- * Copyright (c) 2019 Ha Thach (tinyusb.org)
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * This file is part of the TinyUSB stack.
- */
-
-#include "tusb_option.h"
-
-#if TUSB_OPT_DEVICE_ENABLED
-
-#include "tusb.h"
-#include "device/usbd_pvt.h"
-#include "dcd.h"
-
-enum
-{
- EDPT_CTRL_OUT = 0x00,
- EDPT_CTRL_IN = 0x80
-};
-
-typedef struct
-{
- tusb_control_request_t request;
-
- uint8_t* buffer;
- uint16_t data_len;
- uint16_t total_xferred;
-
- bool (*complete_cb) (uint8_t, tusb_control_request_t const *);
-} usbd_control_xfer_t;
-
-static usbd_control_xfer_t _ctrl_xfer;
-
-CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _usbd_ctrl_buf[CFG_TUD_ENDPOINT0_SIZE];
-
-
-//--------------------------------------------------------------------+
-// Application API
-//--------------------------------------------------------------------+
-
-static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t const * request)
-{
- // status direction is reversed to one in the setup packet
- return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0);
-}
-
-bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request)
-{
- _ctrl_xfer.request = (*request);
- _ctrl_xfer.buffer = NULL;
- _ctrl_xfer.total_xferred = 0;
- _ctrl_xfer.data_len = 0;
-
- return _status_stage_xact(rhport, request);
-}
-
-// Transfer an transaction in Data Stage
-// Each transaction has up to Endpoint0's max packet size.
-// This function can also transfer an zero-length packet
-static bool _data_stage_xact(uint8_t rhport)
-{
- uint16_t const xact_len = tu_min16(_ctrl_xfer.data_len - _ctrl_xfer.total_xferred, CFG_TUD_ENDPOINT0_SIZE);
-
- uint8_t ep_addr = EDPT_CTRL_OUT;
-
- if ( _ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_IN )
- {
- ep_addr = EDPT_CTRL_IN;
- if ( xact_len ) memcpy(_usbd_ctrl_buf, _ctrl_xfer.buffer, xact_len);
- }
-
- return dcd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len);
-}
-
-bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len)
-{
- _ctrl_xfer.request = (*request);
- _ctrl_xfer.buffer = (uint8_t*) buffer;
- _ctrl_xfer.total_xferred = 0;
- _ctrl_xfer.data_len = tu_min16(len, request->wLength);
-
- if ( _ctrl_xfer.data_len )
- {
- TU_ASSERT(buffer);
-
- // Data stage
- TU_ASSERT( _data_stage_xact(rhport) );
- }else
- {
- // Status stage
- TU_ASSERT( _status_stage_xact(rhport, request) );
- }
-
- return true;
-}
-
-//--------------------------------------------------------------------+
-// USBD API
-//--------------------------------------------------------------------+
-
-void usbd_control_reset (uint8_t rhport)
-{
- (void) rhport;
- tu_varclr(&_ctrl_xfer);
-}
-
-// TODO may find a better way
-void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) )
-{
- _ctrl_xfer.complete_cb = fp;
-}
-
-// callback when a transaction complete on DATA stage of control endpoint
-bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
-{
- (void) result;
-
- // Endpoint Address is opposite to direction bit, this is Status Stage complete event
- if ( tu_edpt_dir(ep_addr) != _ctrl_xfer.request.bmRequestType_bit.direction )
- {
- TU_ASSERT(0 == xferred_bytes);
- if (dcd_control_status_complete) dcd_control_status_complete(rhport);
- return true;
- }
-
- if ( _ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_OUT )
- {
- TU_VERIFY(_ctrl_xfer.buffer);
- memcpy(_ctrl_xfer.buffer, _usbd_ctrl_buf, xferred_bytes);
- }
-
- _ctrl_xfer.total_xferred += xferred_bytes;
- _ctrl_xfer.buffer += xferred_bytes;
-
- // Data Stage is complete when all request's length are transferred or
- // a short packet is sent including zero-length packet.
- if ( (_ctrl_xfer.request.wLength == _ctrl_xfer.total_xferred) || xferred_bytes < CFG_TUD_ENDPOINT0_SIZE )
- {
- // DATA stage is complete
- bool is_ok = true;
-
- // invoke complete callback if set
- // callback can still stall control in status phase e.g out data does not make sense
- if ( _ctrl_xfer.complete_cb )
- {
- is_ok = _ctrl_xfer.complete_cb(rhport, &_ctrl_xfer.request);
- }
-
- if ( is_ok )
- {
- // Send status
- TU_ASSERT( _status_stage_xact(rhport, &_ctrl_xfer.request) );
- }else
- {
- // Stall both IN and OUT control endpoint
- dcd_edpt_stall(rhport, EDPT_CTRL_OUT);
- dcd_edpt_stall(rhport, EDPT_CTRL_IN);
- }
- }
- else
- {
- // More data to transfer
- TU_ASSERT( _data_stage_xact(rhport) );
- }
-
- return true;
-}
-
-#endif
+/* + * The MIT License (MIT) + * + * Copyright (c) 2019 Ha Thach (tinyusb.org) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * This file is part of the TinyUSB stack. + */ + +#include "tusb_option.h" + +#if TUSB_OPT_DEVICE_ENABLED + +#include "tusb.h" +#include "device/usbd_pvt.h" +#include "dcd.h" + +enum +{ + EDPT_CTRL_OUT = 0x00, + EDPT_CTRL_IN = 0x80 +}; + +typedef struct +{ + tusb_control_request_t request; + + uint8_t* buffer; + uint16_t data_len; + uint16_t total_xferred; + + bool (*complete_cb) (uint8_t, tusb_control_request_t const *); +} usbd_control_xfer_t; + +static usbd_control_xfer_t _ctrl_xfer; + +CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN +static uint8_t _usbd_ctrl_buf[CFG_TUD_ENDPOINT0_SIZE]; + +//--------------------------------------------------------------------+ +// Application API +//--------------------------------------------------------------------+ + +static inline bool _status_stage_xact(uint8_t rhport, tusb_control_request_t const * request) +{ + // Opposite to endpoint in Data Phase + uint8_t const ep_addr = request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN; + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", ep_addr, 0); + + // status direction is reversed to one in the setup packet + // Note: Status must always be DATA1 + return dcd_edpt_xfer(rhport, ep_addr, NULL, 0); +} + +// Status phase +bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request) +{ + _ctrl_xfer.request = (*request); + _ctrl_xfer.buffer = NULL; + _ctrl_xfer.total_xferred = 0; + _ctrl_xfer.data_len = 0; + + return _status_stage_xact(rhport, request); +} + +// Transfer an transaction in Data Stage +// Each transaction has up to Endpoint0's max packet size. +// This function can also transfer an zero-length packet +static bool _data_stage_xact(uint8_t rhport) +{ + uint16_t const xact_len = tu_min16(_ctrl_xfer.data_len - _ctrl_xfer.total_xferred, CFG_TUD_ENDPOINT0_SIZE); + + uint8_t ep_addr = EDPT_CTRL_OUT; + + if ( _ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_IN ) + { + ep_addr = EDPT_CTRL_IN; + if ( xact_len ) memcpy(_usbd_ctrl_buf, _ctrl_xfer.buffer, xact_len); + } + + TU_LOG2(" XACT Control: 0x%02X, Bytes: %d\r\n", ep_addr, xact_len); + + return dcd_edpt_xfer(rhport, ep_addr, xact_len ? _usbd_ctrl_buf : NULL, xact_len); +} + +bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len) +{ + _ctrl_xfer.request = (*request); + _ctrl_xfer.buffer = (uint8_t*) buffer; + _ctrl_xfer.total_xferred = 0; + _ctrl_xfer.data_len = tu_min16(len, request->wLength); + + if ( _ctrl_xfer.data_len ) + { + TU_ASSERT(buffer); + + TU_LOG2(" XFER Endpoint: 0x%02X, Bytes: %d\r\n", request->bmRequestType_bit.direction ? EDPT_CTRL_IN : EDPT_CTRL_OUT, _ctrl_xfer.data_len); + + // Data stage + TU_ASSERT( _data_stage_xact(rhport) ); + }else + { + // Status stage + TU_ASSERT( _status_stage_xact(rhport, request) ); + } + + return true; +} + +//--------------------------------------------------------------------+ +// USBD API +//--------------------------------------------------------------------+ + +void usbd_control_reset(void) +{ + tu_varclr(&_ctrl_xfer); +} + +// TODO may find a better way +void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) ) +{ + _ctrl_xfer.complete_cb = fp; +} + +// useful for dcd_set_address where DCD is responsible for status response +void usbd_control_set_request(tusb_control_request_t const *request) +{ + _ctrl_xfer.request = (*request); + _ctrl_xfer.buffer = NULL; + _ctrl_xfer.total_xferred = 0; + _ctrl_xfer.data_len = 0; +} + +// callback when a transaction complete on +// - DATA stage of control endpoint or +// - Status stage +bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) +{ + (void) result; + + // Endpoint Address is opposite to direction bit, this is Status Stage complete event + if ( tu_edpt_dir(ep_addr) != _ctrl_xfer.request.bmRequestType_bit.direction ) + { + TU_ASSERT(0 == xferred_bytes); + if (dcd_edpt0_status_complete) dcd_edpt0_status_complete(rhport, &_ctrl_xfer.request); + return true; + } + + if ( _ctrl_xfer.request.bmRequestType_bit.direction == TUSB_DIR_OUT ) + { + TU_VERIFY(_ctrl_xfer.buffer); + memcpy(_ctrl_xfer.buffer, _usbd_ctrl_buf, xferred_bytes); + } + + _ctrl_xfer.total_xferred += xferred_bytes; + _ctrl_xfer.buffer += xferred_bytes; + + // Data Stage is complete when all request's length are transferred or + // a short packet is sent including zero-length packet. + if ( (_ctrl_xfer.request.wLength == _ctrl_xfer.total_xferred) || xferred_bytes < CFG_TUD_ENDPOINT0_SIZE ) + { + // DATA stage is complete + bool is_ok = true; + + // invoke complete callback if set + // callback can still stall control in status phase e.g out data does not make sense + if ( _ctrl_xfer.complete_cb ) + { + is_ok = _ctrl_xfer.complete_cb(rhport, &_ctrl_xfer.request); + } + + if ( is_ok ) + { + // Send status + TU_ASSERT( _status_stage_xact(rhport, &_ctrl_xfer.request) ); + }else + { + // Stall both IN and OUT control endpoint + dcd_edpt_stall(rhport, EDPT_CTRL_OUT); + dcd_edpt_stall(rhport, EDPT_CTRL_IN); + } + } + else + { + // More data to transfer + TU_ASSERT( _data_stage_xact(rhport) ); + } + + return true; +} + +#endif |
