Esp32 s3 support (#6341)

Co-authored-by: Jason2866 <24528715+Jason2866@users.noreply.github.com>
Co-authored-by: Unexpected Maker <seon@unexpectedmaker.com>
Co-authored-by: Rodrigo Garcia <rodrigo.garcia@espressif.com>
Co-authored-by: Tomáš Pilný <34927466+PilnyTomas@users.noreply.github.com>
Co-authored-by: Pedro Minatel <pedro.minatel@espressif.com>
Co-authored-by: Ivan Grokhotkov <ivan@espressif.com>
Co-authored-by: Jan Procházka <90197375+P-R-O-C-H-Y@users.noreply.github.com>
Co-authored-by: Limor "Ladyada" Fried <limor@ladyada.net>
This commit is contained in:
Me No Dev
2022-03-28 12:09:41 +03:00
committed by GitHub
parent 3f79097d5f
commit 8ee5f0a11e
3774 changed files with 685773 additions and 19284 deletions

View File

@ -0,0 +1,135 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org),
* Additions Copyright (c) 2020, Espressif Systems (Shanghai) PTE LTD
*
* 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.
*
*/
#pragma once
#include "tusb_option.h"
#include "sdkconfig.h"
#ifdef __cplusplus
extern "C" {
#endif
/* */
/* KCONFIG */
/* */
#ifndef CONFIG_TINYUSB_CDC_ENABLED
# define CONFIG_TINYUSB_CDC_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_MSC_ENABLED
# define CONFIG_TINYUSB_MSC_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_HID_ENABLED
# define CONFIG_TINYUSB_HID_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_MIDI_ENABLED
# define CONFIG_TINYUSB_MIDI_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_VIDEO_ENABLED
# define CONFIG_TINYUSB_VIDEO_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_CUSTOM_CLASS_ENABLED
# define CONFIG_TINYUSB_CUSTOM_CLASS_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_DFU_RT_ENABLED
# define CONFIG_TINYUSB_DFU_RT_ENABLED 0
#endif
#ifndef CONFIG_TINYUSB_VENDOR_ENABLED
# define CONFIG_TINYUSB_VENDOR_ENABLED 0
#endif
/* */
/* COMMON CONFIGURATION */
/* */
#define CFG_TUSB_MCU OPT_MCU_ESP32S2
#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE
#define CFG_TUSB_OS OPT_OS_FREERTOS
/* USB DMA on some MCUs can only access a specific SRAM region with restriction on alignment.
* Tinyusb use follows macros to declare transferring memory so that they can be put
* into those specific section.
* e.g
* - CFG_TUSB_MEM SECTION : __attribute__ (( section(".usb_ram") ))
* - CFG_TUSB_MEM_ALIGN : __attribute__ ((aligned(4)))
*/
#ifndef CFG_TUSB_MEM_SECTION
# define CFG_TUSB_MEM_SECTION
#endif
#ifndef CFG_TUSB_MEM_ALIGN
# define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4)
#endif
/* */
/* DRIVER CONFIGURATION */
/* */
#define CFG_TUD_MAINTASK_SIZE 4096
#define CFG_TUD_ENDOINT0_SIZE 64
// Enabled Drivers
#define CFG_TUD_CDC CONFIG_TINYUSB_CDC_ENABLED
#define CFG_TUD_MSC CONFIG_TINYUSB_MSC_ENABLED
#define CFG_TUD_HID CONFIG_TINYUSB_HID_ENABLED
#define CFG_TUD_MIDI CONFIG_TINYUSB_MIDI_ENABLED
#define CFG_TUD_VIDEO CONFIG_TINYUSB_VIDEO_ENABLED
#define CFG_TUD_CUSTOM_CLASS CONFIG_TINYUSB_CUSTOM_CLASS_ENABLED
#define CFG_TUD_DFU_RUNTIME CONFIG_TINYUSB_DFU_RT_ENABLED
#define CFG_TUD_VENDOR CONFIG_TINYUSB_VENDOR_ENABLED
// CDC FIFO size of TX and RX
#define CFG_TUD_CDC_RX_BUFSIZE CONFIG_TINYUSB_CDC_RX_BUFSIZE
#define CFG_TUD_CDC_TX_BUFSIZE CONFIG_TINYUSB_CDC_TX_BUFSIZE
// MSC Buffer size of Device Mass storage:
#define CFG_TUD_MSC_BUFSIZE CONFIG_TINYUSB_MSC_BUFSIZE
// HID buffer size Should be sufficient to hold ID (if any) + Data
#define CFG_TUD_HID_BUFSIZE CONFIG_TINYUSB_HID_BUFSIZE
// MIDI FIFO size of TX and RX
#define CFG_TUD_MIDI_RX_BUFSIZE CONFIG_TINYUSB_MIDI_RX_BUFSIZE
#define CFG_TUD_MIDI_TX_BUFSIZE CONFIG_TINYUSB_MIDI_TX_BUFSIZE
// The number of video streaming interfaces and endpoint size
#define CFG_TUD_VIDEO_STREAMING CONFIG_TINYUSB_VIDEO_STREAMING_IFS
#define CFG_TUD_VIDEO_STREAMING_EP_BUFSIZE CONFIG_TINYUSB_VIDEO_STREAMING_BUFSIZE
// VENDOR FIFO size of TX and RX
#define CFG_TUD_VENDOR_RX_BUFSIZE CONFIG_TINYUSB_VENDOR_RX_BUFSIZE
#define CFG_TUD_VENDOR_TX_BUFSIZE CONFIG_TINYUSB_VENDOR_TX_BUFSIZE
#ifdef __cplusplus
}
#endif

View File

@ -0,0 +1,933 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
* Copyright (c) 2020 Reinhard Panhuber
*
* 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_class
* \defgroup ClassDriver_Audio Audio
* Currently only MIDI subclass is supported
* @{ */
#ifndef _TUSB_AUDIO_H__
#define _TUSB_AUDIO_H__
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
/// Audio Device Class Codes
/// A.2 - Audio Function Subclass Codes
typedef enum
{
AUDIO_FUNCTION_SUBCLASS_UNDEFINED = 0x00,
} audio_function_subclass_type_t;
/// A.3 - Audio Function Protocol Codes
typedef enum
{
AUDIO_FUNC_PROTOCOL_CODE_UNDEF = 0x00,
AUDIO_FUNC_PROTOCOL_CODE_V2 = 0x20, ///< Version 2.0
} audio_function_protocol_code_t;
/// A.5 - Audio Interface Subclass Codes
typedef enum
{
AUDIO_SUBCLASS_UNDEFINED = 0x00,
AUDIO_SUBCLASS_CONTROL , ///< Audio Control
AUDIO_SUBCLASS_STREAMING , ///< Audio Streaming
AUDIO_SUBCLASS_MIDI_STREAMING , ///< MIDI Streaming
} audio_subclass_type_t;
/// A.6 - Audio Interface Protocol Codes
typedef enum
{
AUDIO_INT_PROTOCOL_CODE_UNDEF = 0x00,
AUDIO_INT_PROTOCOL_CODE_V2 = 0x20, ///< Version 2.0
} audio_interface_protocol_code_t;
/// A.7 - Audio Function Category Codes
typedef enum
{
AUDIO_FUNC_UNDEF = 0x00,
AUDIO_FUNC_DESKTOP_SPEAKER = 0x01,
AUDIO_FUNC_HOME_THEATER = 0x02,
AUDIO_FUNC_MICROPHONE = 0x03,
AUDIO_FUNC_HEADSET = 0x04,
AUDIO_FUNC_TELEPHONE = 0x05,
AUDIO_FUNC_CONVERTER = 0x06,
AUDIO_FUNC_SOUND_RECODER = 0x07,
AUDIO_FUNC_IO_BOX = 0x08,
AUDIO_FUNC_MUSICAL_INSTRUMENT = 0x09,
AUDIO_FUNC_PRO_AUDIO = 0x0A,
AUDIO_FUNC_AUDIO_VIDEO = 0x0B,
AUDIO_FUNC_CONTROL_PANEL = 0x0C,
AUDIO_FUNC_OTHER = 0xFF,
} audio_function_code_t;
/// A.9 - Audio Class-Specific AC Interface Descriptor Subtypes UAC2
typedef enum
{
AUDIO_CS_AC_INTERFACE_AC_DESCRIPTOR_UNDEF = 0x00,
AUDIO_CS_AC_INTERFACE_HEADER = 0x01,
AUDIO_CS_AC_INTERFACE_INPUT_TERMINAL = 0x02,
AUDIO_CS_AC_INTERFACE_OUTPUT_TERMINAL = 0x03,
AUDIO_CS_AC_INTERFACE_MIXER_UNIT = 0x04,
AUDIO_CS_AC_INTERFACE_SELECTOR_UNIT = 0x05,
AUDIO_CS_AC_INTERFACE_FEATURE_UNIT = 0x06,
AUDIO_CS_AC_INTERFACE_EFFECT_UNIT = 0x07,
AUDIO_CS_AC_INTERFACE_PROCESSING_UNIT = 0x08,
AUDIO_CS_AC_INTERFACE_EXTENSION_UNIT = 0x09,
AUDIO_CS_AC_INTERFACE_CLOCK_SOURCE = 0x0A,
AUDIO_CS_AC_INTERFACE_CLOCK_SELECTOR = 0x0B,
AUDIO_CS_AC_INTERFACE_CLOCK_MULTIPLIER = 0x0C,
AUDIO_CS_AC_INTERFACE_SAMPLE_RATE_CONVERTER = 0x0D,
} audio_cs_ac_interface_subtype_t;
/// A.10 - Audio Class-Specific AS Interface Descriptor Subtypes UAC2
typedef enum
{
AUDIO_CS_AS_INTERFACE_AS_DESCRIPTOR_UNDEF = 0x00,
AUDIO_CS_AS_INTERFACE_AS_GENERAL = 0x01,
AUDIO_CS_AS_INTERFACE_FORMAT_TYPE = 0x02,
AUDIO_CS_AS_INTERFACE_ENCODER = 0x03,
AUDIO_CS_AS_INTERFACE_DECODER = 0x04,
} audio_cs_as_interface_subtype_t;
/// A.11 - Effect Unit Effect Types
typedef enum
{
AUDIO_EFFECT_TYPE_UNDEF = 0x00,
AUDIO_EFFECT_TYPE_PARAM_EQ_SECTION = 0x01,
AUDIO_EFFECT_TYPE_REVERBERATION = 0x02,
AUDIO_EFFECT_TYPE_MOD_DELAY = 0x03,
AUDIO_EFFECT_TYPE_DYN_RANGE_COMP = 0x04,
} audio_effect_unit_effect_type_t;
/// A.12 - Processing Unit Process Types
typedef enum
{
AUDIO_PROCESS_TYPE_UNDEF = 0x00,
AUDIO_PROCESS_TYPE_UP_DOWN_MIX = 0x01,
AUDIO_PROCESS_TYPE_DOLBY_PROLOGIC = 0x02,
AUDIO_PROCESS_TYPE_STEREO_EXTENDER = 0x03,
} audio_processing_unit_process_type_t;
/// A.13 - Audio Class-Specific EP Descriptor Subtypes UAC2
typedef enum
{
AUDIO_CS_EP_SUBTYPE_UNDEF = 0x00,
AUDIO_CS_EP_SUBTYPE_GENERAL = 0x01,
} audio_cs_ep_subtype_t;
/// A.14 - Audio Class-Specific Request Codes
typedef enum
{
AUDIO_CS_REQ_UNDEF = 0x00,
AUDIO_CS_REQ_CUR = 0x01,
AUDIO_CS_REQ_RANGE = 0x02,
AUDIO_CS_REQ_MEM = 0x03,
} audio_cs_req_t;
/// A.17 - Control Selector Codes
/// A.17.1 - Clock Source Control Selectors
typedef enum
{
AUDIO_CS_CTRL_UNDEF = 0x00,
AUDIO_CS_CTRL_SAM_FREQ = 0x01,
AUDIO_CS_CTRL_CLK_VALID = 0x02,
} audio_clock_src_control_selector_t;
/// A.17.2 - Clock Selector Control Selectors
typedef enum
{
AUDIO_CX_CTRL_UNDEF = 0x00,
AUDIO_CX_CTRL_CONTROL = 0x01,
} audio_clock_sel_control_selector_t;
/// A.17.3 - Clock Multiplier Control Selectors
typedef enum
{
AUDIO_CM_CTRL_UNDEF = 0x00,
AUDIO_CM_CTRL_NUMERATOR_CONTROL = 0x01,
AUDIO_CM_CTRL_DENOMINATOR_CONTROL = 0x02,
} audio_clock_mul_control_selector_t;
/// A.17.4 - Terminal Control Selectors
typedef enum
{
AUDIO_TE_CTRL_UNDEF = 0x00,
AUDIO_TE_CTRL_COPY_PROTECT = 0x01,
AUDIO_TE_CTRL_CONNECTOR = 0x02,
AUDIO_TE_CTRL_OVERLOAD = 0x03,
AUDIO_TE_CTRL_CLUSTER = 0x04,
AUDIO_TE_CTRL_UNDERFLOW = 0x05,
AUDIO_TE_CTRL_OVERFLOW = 0x06,
AUDIO_TE_CTRL_LATENCY = 0x07,
} audio_terminal_control_selector_t;
/// A.17.5 - Mixer Control Selectors
typedef enum
{
AUDIO_MU_CTRL_UNDEF = 0x00,
AUDIO_MU_CTRL_MIXER = 0x01,
AUDIO_MU_CTRL_CLUSTER = 0x02,
AUDIO_MU_CTRL_UNDERFLOW = 0x03,
AUDIO_MU_CTRL_OVERFLOW = 0x04,
AUDIO_MU_CTRL_LATENCY = 0x05,
} audio_mixer_control_selector_t;
/// A.17.6 - Selector Control Selectors
typedef enum
{
AUDIO_SU_CTRL_UNDEF = 0x00,
AUDIO_SU_CTRL_SELECTOR = 0x01,
AUDIO_SU_CTRL_LATENCY = 0x02,
} audio_sel_control_selector_t;
/// A.17.7 - Feature Unit Control Selectors
typedef enum
{
AUDIO_FU_CTRL_UNDEF = 0x00,
AUDIO_FU_CTRL_MUTE = 0x01,
AUDIO_FU_CTRL_VOLUME = 0x02,
AUDIO_FU_CTRL_BASS = 0x03,
AUDIO_FU_CTRL_MID = 0x04,
AUDIO_FU_CTRL_TREBLE = 0x05,
AUDIO_FU_CTRL_GRAPHIC_EQUALIZER = 0x06,
AUDIO_FU_CTRL_AGC = 0x07,
AUDIO_FU_CTRL_DELAY = 0x08,
AUDIO_FU_CTRL_BASS_BOOST = 0x09,
AUDIO_FU_CTRL_LOUDNESS = 0x0A,
AUDIO_FU_CTRL_INPUT_GAIN = 0x0B,
AUDIO_FU_CTRL_GAIN_PAD = 0x0C,
AUDIO_FU_CTRL_INVERTER = 0x0D,
AUDIO_FU_CTRL_UNDERFLOW = 0x0E,
AUDIO_FU_CTRL_OVERVLOW = 0x0F,
AUDIO_FU_CTRL_LATENCY = 0x10,
} audio_feature_unit_control_selector_t;
/// A.17.8 Effect Unit Control Selectors
/// A.17.8.1 Parametric Equalizer Section Effect Unit Control Selectors
typedef enum
{
AUDIO_PE_CTRL_UNDEF = 0x00,
AUDIO_PE_CTRL_ENABLE = 0x01,
AUDIO_PE_CTRL_CENTERFREQ = 0x02,
AUDIO_PE_CTRL_QFACTOR = 0x03,
AUDIO_PE_CTRL_GAIN = 0x04,
AUDIO_PE_CTRL_UNDERFLOW = 0x05,
AUDIO_PE_CTRL_OVERFLOW = 0x06,
AUDIO_PE_CTRL_LATENCY = 0x07,
} audio_parametric_equalizer_control_selector_t;
/// A.17.8.2 Reverberation Effect Unit Control Selectors
typedef enum
{
AUDIO_RV_CTRL_UNDEF = 0x00,
AUDIO_RV_CTRL_ENABLE = 0x01,
AUDIO_RV_CTRL_TYPE = 0x02,
AUDIO_RV_CTRL_LEVEL = 0x03,
AUDIO_RV_CTRL_TIME = 0x04,
AUDIO_RV_CTRL_FEEDBACK = 0x05,
AUDIO_RV_CTRL_PREDELAY = 0x06,
AUDIO_RV_CTRL_DENSITY = 0x07,
AUDIO_RV_CTRL_HIFREQ_ROLLOFF = 0x08,
AUDIO_RV_CTRL_UNDERFLOW = 0x09,
AUDIO_RV_CTRL_OVERFLOW = 0x0A,
AUDIO_RV_CTRL_LATENCY = 0x0B,
} audio_reverberation_effect_control_selector_t;
/// A.17.8.3 Modulation Delay Effect Unit Control Selectors
typedef enum
{
AUDIO_MD_CTRL_UNDEF = 0x00,
AUDIO_MD_CTRL_ENABLE = 0x01,
AUDIO_MD_CTRL_BALANCE = 0x02,
AUDIO_MD_CTRL_RATE = 0x03,
AUDIO_MD_CTRL_DEPTH = 0x04,
AUDIO_MD_CTRL_TIME = 0x05,
AUDIO_MD_CTRL_FEEDBACK = 0x06,
AUDIO_MD_CTRL_UNDERFLOW = 0x07,
AUDIO_MD_CTRL_OVERFLOW = 0x08,
AUDIO_MD_CTRL_LATENCY = 0x09,
} audio_modulation_delay_control_selector_t;
/// A.17.8.4 Dynamic Range Compressor Effect Unit Control Selectors
typedef enum
{
AUDIO_DR_CTRL_UNDEF = 0x00,
AUDIO_DR_CTRL_ENABLE = 0x01,
AUDIO_DR_CTRL_COMPRESSION_RATE = 0x02,
AUDIO_DR_CTRL_MAXAMPL = 0x03,
AUDIO_DR_CTRL_THRESHOLD = 0x04,
AUDIO_DR_CTRL_ATTACK_TIME = 0x05,
AUDIO_DR_CTRL_RELEASE_TIME = 0x06,
AUDIO_DR_CTRL_UNDERFLOW = 0x07,
AUDIO_DR_CTRL_OVERFLOW = 0x08,
AUDIO_DR_CTRL_LATENCY = 0x09,
} audio_dynamic_range_compression_control_selector_t;
/// A.17.9 Processing Unit Control Selectors
/// A.17.9.1 Up/Down-mix Processing Unit Control Selectors
typedef enum
{
AUDIO_UD_CTRL_UNDEF = 0x00,
AUDIO_UD_CTRL_ENABLE = 0x01,
AUDIO_UD_CTRL_MODE_SELECT = 0x02,
AUDIO_UD_CTRL_CLUSTER = 0x03,
AUDIO_UD_CTRL_UNDERFLOW = 0x04,
AUDIO_UD_CTRL_OVERFLOW = 0x05,
AUDIO_UD_CTRL_LATENCY = 0x06,
} audio_up_down_mix_control_selector_t;
/// A.17.9.2 Dolby Prologic ™ Processing Unit Control Selectors
typedef enum
{
AUDIO_DP_CTRL_UNDEF = 0x00,
AUDIO_DP_CTRL_ENABLE = 0x01,
AUDIO_DP_CTRL_MODE_SELECT = 0x02,
AUDIO_DP_CTRL_CLUSTER = 0x03,
AUDIO_DP_CTRL_UNDERFLOW = 0x04,
AUDIO_DP_CTRL_OVERFLOW = 0x05,
AUDIO_DP_CTRL_LATENCY = 0x06,
} audio_dolby_prologic_control_selector_t;
/// A.17.9.3 Stereo Extender Processing Unit Control Selectors
typedef enum
{
AUDIO_ST_EXT_CTRL_UNDEF = 0x00,
AUDIO_ST_EXT_CTRL_ENABLE = 0x01,
AUDIO_ST_EXT_CTRL_WIDTH = 0x02,
AUDIO_ST_EXT_CTRL_UNDERFLOW = 0x03,
AUDIO_ST_EXT_CTRL_OVERFLOW = 0x04,
AUDIO_ST_EXT_CTRL_LATENCY = 0x05,
} audio_stereo_extender_control_selector_t;
/// A.17.10 Extension Unit Control Selectors
typedef enum
{
AUDIO_XU_CTRL_UNDEF = 0x00,
AUDIO_XU_CTRL_ENABLE = 0x01,
AUDIO_XU_CTRL_CLUSTER = 0x02,
AUDIO_XU_CTRL_UNDERFLOW = 0x03,
AUDIO_XU_CTRL_OVERFLOW = 0x04,
AUDIO_XU_CTRL_LATENCY = 0x05,
} audio_extension_unit_control_selector_t;
/// A.17.11 AudioStreaming Interface Control Selectors
typedef enum
{
AUDIO_AS_CTRL_UNDEF = 0x00,
AUDIO_AS_CTRL_ACT_ALT_SETTING = 0x01,
AUDIO_AS_CTRL_VAL_ALT_SETTINGS = 0x02,
AUDIO_AS_CTRL_AUDIO_DATA_FORMAT = 0x03,
} audio_audiostreaming_interface_control_selector_t;
/// A.17.12 Encoder Control Selectors
typedef enum
{
AUDIO_EN_CTRL_UNDEF = 0x00,
AUDIO_EN_CTRL_BIT_RATE = 0x01,
AUDIO_EN_CTRL_QUALITY = 0x02,
AUDIO_EN_CTRL_VBR = 0x03,
AUDIO_EN_CTRL_TYPE = 0x04,
AUDIO_EN_CTRL_UNDERFLOW = 0x05,
AUDIO_EN_CTRL_OVERFLOW = 0x06,
AUDIO_EN_CTRL_ENCODER_ERROR = 0x07,
AUDIO_EN_CTRL_PARAM1 = 0x08,
AUDIO_EN_CTRL_PARAM2 = 0x09,
AUDIO_EN_CTRL_PARAM3 = 0x0A,
AUDIO_EN_CTRL_PARAM4 = 0x0B,
AUDIO_EN_CTRL_PARAM5 = 0x0C,
AUDIO_EN_CTRL_PARAM6 = 0x0D,
AUDIO_EN_CTRL_PARAM7 = 0x0E,
AUDIO_EN_CTRL_PARAM8 = 0x0F,
} audio_encoder_control_selector_t;
/// A.17.13 Decoder Control Selectors
/// A.17.13.1 MPEG Decoder Control Selectors
typedef enum
{
AUDIO_MPD_CTRL_UNDEF = 0x00,
AUDIO_MPD_CTRL_DUAL_CHANNEL = 0x01,
AUDIO_MPD_CTRL_SECOND_STEREO = 0x02,
AUDIO_MPD_CTRL_MULTILINGUAL = 0x03,
AUDIO_MPD_CTRL_DYN_RANGE = 0x04,
AUDIO_MPD_CTRL_SCALING = 0x05,
AUDIO_MPD_CTRL_HILO_SCALING = 0x06,
AUDIO_MPD_CTRL_UNDERFLOW = 0x07,
AUDIO_MPD_CTRL_OVERFLOW = 0x08,
AUDIO_MPD_CTRL_DECODER_ERROR = 0x09,
} audio_MPEG_decoder_control_selector_t;
/// A.17.13.2 AC-3 Decoder Control Selectors
typedef enum
{
AUDIO_AD_CTRL_UNDEF = 0x00,
AUDIO_AD_CTRL_MODE = 0x01,
AUDIO_AD_CTRL_DYN_RANGE = 0x02,
AUDIO_AD_CTRL_SCALING = 0x03,
AUDIO_AD_CTRL_HILO_SCALING = 0x04,
AUDIO_AD_CTRL_UNDERFLOW = 0x05,
AUDIO_AD_CTRL_OVERFLOW = 0x06,
AUDIO_AD_CTRL_DECODER_ERROR = 0x07,
} audio_AC3_decoder_control_selector_t;
/// A.17.13.3 WMA Decoder Control Selectors
typedef enum
{
AUDIO_WD_CTRL_UNDEF = 0x00,
AUDIO_WD_CTRL_UNDERFLOW = 0x01,
AUDIO_WD_CTRL_OVERFLOW = 0x02,
AUDIO_WD_CTRL_DECODER_ERROR = 0x03,
} audio_WMA_decoder_control_selector_t;
/// A.17.13.4 DTS Decoder Control Selectors
typedef enum
{
AUDIO_DD_CTRL_UNDEF = 0x00,
AUDIO_DD_CTRL_UNDERFLOW = 0x01,
AUDIO_DD_CTRL_OVERFLOW = 0x02,
AUDIO_DD_CTRL_DECODER_ERROR = 0x03,
} audio_DTS_decoder_control_selector_t;
/// A.17.14 Endpoint Control Selectors
typedef enum
{
AUDIO_EP_CTRL_UNDEF = 0x00,
AUDIO_EP_CTRL_PITCH = 0x01,
AUDIO_EP_CTRL_DATA_OVERRUN = 0x02,
AUDIO_EP_CTRL_DATA_UNDERRUN = 0x03,
} audio_EP_control_selector_t;
/// Terminal Types
/// 2.1 - Audio Class-Terminal Types UAC2
typedef enum
{
AUDIO_TERM_TYPE_USB_UNDEFINED = 0x0100,
AUDIO_TERM_TYPE_USB_STREAMING = 0x0101,
AUDIO_TERM_TYPE_USB_VENDOR_SPEC = 0x01FF,
} audio_terminal_type_t;
/// 2.2 - Audio Class-Input Terminal Types UAC2
typedef enum
{
AUDIO_TERM_TYPE_IN_UNDEFINED = 0x0200,
AUDIO_TERM_TYPE_IN_GENERIC_MIC = 0x0201,
AUDIO_TERM_TYPE_IN_DESKTOP_MIC = 0x0202,
AUDIO_TERM_TYPE_IN_PERSONAL_MIC = 0x0203,
AUDIO_TERM_TYPE_IN_OMNI_MIC = 0x0204,
AUDIO_TERM_TYPE_IN_ARRAY_MIC = 0x0205,
AUDIO_TERM_TYPE_IN_PROC_ARRAY_MIC = 0x0206,
} audio_terminal_input_type_t;
/// 2.3 - Audio Class-Output Terminal Types UAC2
typedef enum
{
AUDIO_TERM_TYPE_OUT_UNDEFINED = 0x0300,
AUDIO_TERM_TYPE_OUT_GENERIC_SPEAKER = 0x0301,
AUDIO_TERM_TYPE_OUT_HEADPHONES = 0x0302,
AUDIO_TERM_TYPE_OUT_HEAD_MNT_DISP_AUIDO = 0x0303,
AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER = 0x0304,
AUDIO_TERM_TYPE_OUT_ROOM_SPEAKER = 0x0305,
AUDIO_TERM_TYPE_OUT_COMMUNICATION_SPEAKER = 0x0306,
AUDIO_TERM_TYPE_OUT_LOW_FRQ_EFFECTS_SPEAKER = 0x0307,
} audio_terminal_output_type_t;
/// Rest is yet to be implemented
/// Additional Audio Device Class Codes - Source: Audio Data Formats
/// A.1 - Audio Class-Format Type Codes UAC2
typedef enum
{
AUDIO_FORMAT_TYPE_UNDEFINED = 0x00,
AUDIO_FORMAT_TYPE_I = 0x01,
AUDIO_FORMAT_TYPE_II = 0x02,
AUDIO_FORMAT_TYPE_III = 0x03,
AUDIO_FORMAT_TYPE_IV = 0x04,
AUDIO_EXT_FORMAT_TYPE_I = 0x81,
AUDIO_EXT_FORMAT_TYPE_II = 0x82,
AUDIO_EXT_FORMAT_TYPE_III = 0x83,
} audio_format_type_t;
// A.2.1 - Audio Class-Audio Data Format Type I UAC2
typedef enum
{
AUDIO_DATA_FORMAT_TYPE_I_PCM = (uint32_t) (1 << 0),
AUDIO_DATA_FORMAT_TYPE_I_PCM8 = (uint32_t) (1 << 1),
AUDIO_DATA_FORMAT_TYPE_I_IEEE_FLOAT = (uint32_t) (1 << 2),
AUDIO_DATA_FORMAT_TYPE_I_ALAW = (uint32_t) (1 << 3),
AUDIO_DATA_FORMAT_TYPE_I_MULAW = (uint32_t) (1 << 4),
AUDIO_DATA_FORMAT_TYPE_I_RAW_DATA = 0x80000000,
} audio_data_format_type_I_t;
/// All remaining definitions are taken from the descriptor descriptions in the UAC2 main specification
/// Audio Class-Control Values UAC2
typedef enum
{
AUDIO_CTRL_NONE = 0x00, ///< No Host access
AUDIO_CTRL_R = 0x01, ///< Host read access only
AUDIO_CTRL_RW = 0x03, ///< Host read write access
} audio_control_t;
/// Audio Class-Specific AC Interface Descriptor Controls UAC2
typedef enum
{
AUDIO_CS_AS_INTERFACE_CTRL_LATENCY_POS = 0,
} audio_cs_ac_interface_control_pos_t;
/// Audio Class-Specific AS Interface Descriptor Controls UAC2
typedef enum
{
AUDIO_CS_AS_INTERFACE_CTRL_ACTIVE_ALT_SET_POS = 0,
AUDIO_CS_AS_INTERFACE_CTRL_VALID_ALT_SET_POS = 2,
} audio_cs_as_interface_control_pos_t;
/// Audio Class-Specific AS Isochronous Data EP Attributes UAC2
typedef enum
{
AUDIO_CS_AS_ISO_DATA_EP_ATT_MAX_PACKETS_ONLY = 0x80,
AUDIO_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK = 0x00,
} audio_cs_as_iso_data_ep_attribute_t;
/// Audio Class-Specific AS Isochronous Data EP Controls UAC2
typedef enum
{
AUDIO_CS_AS_ISO_DATA_EP_CTRL_PITCH_POS = 0,
AUDIO_CS_AS_ISO_DATA_EP_CTRL_DATA_OVERRUN_POS = 2,
AUDIO_CS_AS_ISO_DATA_EP_CTRL_DATA_UNDERRUN_POS = 4,
} audio_cs_as_iso_data_ep_control_pos_t;
/// Audio Class-Specific AS Isochronous Data EP Lock Delay Units UAC2
typedef enum
{
AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED = 0x00,
AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_MILLISEC = 0x01,
AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_PCM_SAMPLES = 0x02,
} audio_cs_as_iso_data_ep_lock_delay_unit_t;
/// Audio Class-Clock Source Attributes UAC2
typedef enum
{
AUDIO_CLOCK_SOURCE_ATT_EXT_CLK = 0x00,
AUDIO_CLOCK_SOURCE_ATT_INT_FIX_CLK = 0x01,
AUDIO_CLOCK_SOURCE_ATT_INT_VAR_CLK = 0x02,
AUDIO_CLOCK_SOURCE_ATT_INT_PRO_CLK = 0x03,
AUDIO_CLOCK_SOURCE_ATT_CLK_SYC_SOF = 0x04,
} audio_clock_source_attribute_t;
/// Audio Class-Clock Source Controls UAC2
typedef enum
{
AUDIO_CLOCK_SOURCE_CTRL_CLK_FRQ_POS = 0,
AUDIO_CLOCK_SOURCE_CTRL_CLK_VAL_POS = 2,
} audio_clock_source_control_pos_t;
/// Audio Class-Clock Selector Controls UAC2
typedef enum
{
AUDIO_CLOCK_SELECTOR_CTRL_POS = 0,
} audio_clock_selector_control_pos_t;
/// Audio Class-Clock Multiplier Controls UAC2
typedef enum
{
AUDIO_CLOCK_MULTIPLIER_CTRL_NUMERATOR_POS = 0,
AUDIO_CLOCK_MULTIPLIER_CTRL_DENOMINATOR_POS = 2,
} audio_clock_multiplier_control_pos_t;
/// Audio Class-Input Terminal Controls UAC2
typedef enum
{
AUDIO_IN_TERM_CTRL_CPY_PROT_POS = 0,
AUDIO_IN_TERM_CTRL_CONNECTOR_POS = 2,
AUDIO_IN_TERM_CTRL_OVERLOAD_POS = 4,
AUDIO_IN_TERM_CTRL_CLUSTER_POS = 6,
AUDIO_IN_TERM_CTRL_UNDERFLOW_POS = 8,
AUDIO_IN_TERM_CTRL_OVERFLOW_POS = 10,
} audio_terminal_input_control_pos_t;
/// Audio Class-Output Terminal Controls UAC2
typedef enum
{
AUDIO_OUT_TERM_CTRL_CPY_PROT_POS = 0,
AUDIO_OUT_TERM_CTRL_CONNECTOR_POS = 2,
AUDIO_OUT_TERM_CTRL_OVERLOAD_POS = 4,
AUDIO_OUT_TERM_CTRL_UNDERFLOW_POS = 6,
AUDIO_OUT_TERM_CTRL_OVERFLOW_POS = 8,
} audio_terminal_output_control_pos_t;
/// Audio Class-Feature Unit Controls UAC2
typedef enum
{
AUDIO_FEATURE_UNIT_CTRL_MUTE_POS = 0,
AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS = 2,
AUDIO_FEATURE_UNIT_CTRL_BASS_POS = 4,
AUDIO_FEATURE_UNIT_CTRL_MID_POS = 6,
AUDIO_FEATURE_UNIT_CTRL_TREBLE_POS = 8,
AUDIO_FEATURE_UNIT_CTRL_GRAPHIC_EQU_POS = 10,
AUDIO_FEATURE_UNIT_CTRL_AGC_POS = 12,
AUDIO_FEATURE_UNIT_CTRL_DELAY_POS = 14,
AUDIO_FEATURE_UNIT_CTRL_BASS_BOOST_POS = 16,
AUDIO_FEATURE_UNIT_CTRL_LOUDNESS_POS = 18,
AUDIO_FEATURE_UNIT_CTRL_INPUT_GAIN_POS = 20,
AUDIO_FEATURE_UNIT_CTRL_INPUT_GAIN_PAD_POS = 22,
AUDIO_FEATURE_UNIT_CTRL_PHASE_INV_POS = 24,
AUDIO_FEATURE_UNIT_CTRL_UNDERFLOW_POS = 26,
AUDIO_FEATURE_UNIT_CTRL_OVERFLOW_POS = 28,
} audio_feature_unit_control_pos_t;
/// Audio Class-Audio Channel Configuration UAC2
typedef enum
{
AUDIO_CHANNEL_CONFIG_NON_PREDEFINED = 0x00000000,
AUDIO_CHANNEL_CONFIG_FRONT_LEFT = 0x00000001,
AUDIO_CHANNEL_CONFIG_FRONT_RIGHT = 0x00000002,
AUDIO_CHANNEL_CONFIG_FRONT_CENTER = 0x00000004,
AUDIO_CHANNEL_CONFIG_LOW_FRQ_EFFECTS = 0x00000008,
AUDIO_CHANNEL_CONFIG_BACK_LEFT = 0x00000010,
AUDIO_CHANNEL_CONFIG_BACK_RIGHT = 0x00000020,
AUDIO_CHANNEL_CONFIG_FRONT_LEFT_OF_CENTER = 0x00000040,
AUDIO_CHANNEL_CONFIG_FRONT_RIGHT_OF_CENTER = 0x00000080,
AUDIO_CHANNEL_CONFIG_BACK_CENTER = 0x00000100,
AUDIO_CHANNEL_CONFIG_SIDE_LEFT = 0x00000200,
AUDIO_CHANNEL_CONFIG_SIDE_RIGHT = 0x00000400,
AUDIO_CHANNEL_CONFIG_TOP_CENTER = 0x00000800,
AUDIO_CHANNEL_CONFIG_TOP_FRONT_LEFT = 0x00001000,
AUDIO_CHANNEL_CONFIG_TOP_FRONT_CENTER = 0x00002000,
AUDIO_CHANNEL_CONFIG_TOP_FRONT_RIGHT = 0x00004000,
AUDIO_CHANNEL_CONFIG_TOP_BACK_LEFT = 0x00008000,
AUDIO_CHANNEL_CONFIG_TOP_BACK_CENTER = 0x00010000,
AUDIO_CHANNEL_CONFIG_TOP_BACK_RIGHT = 0x00020000,
AUDIO_CHANNEL_CONFIG_TOP_FRONT_LEFT_OF_CENTER = 0x00040000,
AUDIO_CHANNEL_CONFIG_TOP_FRONT_RIGHT_OF_CENTER = 0x00080000,
AUDIO_CHANNEL_CONFIG_LEFT_LOW_FRQ_EFFECTS = 0x00100000,
AUDIO_CHANNEL_CONFIG_RIGHT_LOW_FRQ_EFFECTS = 0x00200000,
AUDIO_CHANNEL_CONFIG_TOP_SIDE_LEFT = 0x00400000,
AUDIO_CHANNEL_CONFIG_TOP_SIDE_RIGHT = 0x00800000,
AUDIO_CHANNEL_CONFIG_BOTTOM_CENTER = 0x01000000,
AUDIO_CHANNEL_CONFIG_BACK_LEFT_OF_CENTER = 0x02000000,
AUDIO_CHANNEL_CONFIG_BACK_RIGHT_OF_CENTER = 0x04000000,
AUDIO_CHANNEL_CONFIG_RAW_DATA = 0x80000000,
} audio_channel_config_t;
/// AUDIO Channel Cluster Descriptor (4.1)
typedef struct TU_ATTR_PACKED {
uint8_t bNrChannels; ///< Number of channels currently connected.
audio_channel_config_t bmChannelConfig; ///< Bitmap according to 'audio_channel_config_t' with a 1 set if channel is connected and 0 else. In case channels are non-predefined ignore them here (see UAC2 specification 4.1 Audio Channel Cluster Descriptor.
uint8_t iChannelNames; ///< Index of a string descriptor, describing the name of the first inserted channel with a non-predefined spatial location.
} audio_desc_channel_cluster_t;
/// AUDIO Class-Specific AC Interface Header Descriptor (4.7.2)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes: 9.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_HEADER.
uint16_t bcdADC ; ///< Audio Device Class Specification Release Number in Binary-Coded Decimal. Value: U16_TO_U8S_LE(0x0200).
uint8_t bCategory ; ///< Constant, indicating the primary use of this audio function, as intended by the manufacturer. See: audio_function_t.
uint16_t wTotalLength ; ///< Total number of bytes returned for the class-specific AudioControl interface descriptor. Includes the combined length of this descriptor header and all Clock Source, Unit and Terminal descriptors.
uint8_t bmControls ; ///< See: audio_cs_ac_interface_control_pos_t.
} audio_desc_cs_ac_interface_t;
/// AUDIO Clock Source Descriptor (4.7.2.1)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes: 8.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_CLOCK_SOURCE.
uint8_t bClockID ; ///< Constant uniquely identifying the Clock Source Entity within the audio function. This value is used in all requests to address this Entity.
uint8_t bmAttributes ; ///< See: audio_clock_source_attribute_t.
uint8_t bmControls ; ///< See: audio_clock_source_control_pos_t.
uint8_t bAssocTerminal ; ///< Terminal ID of the Terminal that is associated with this Clock Source.
uint8_t iClockSource ; ///< Index of a string descriptor, describing the Clock Source Entity.
} audio_desc_clock_source_t;
/// AUDIO Clock Selector Descriptor (4.7.2.2) for ONE pin
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 7+p.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_CLOCK_SELECTOR.
uint8_t bClockID ; ///< Constant uniquely identifying the Clock Selector Entity within the audio function. This value is used in all requests to address this Entity.
uint8_t bNrInPins ; ///< Number of Input Pins of this Unit: p = 1 thus bNrInPins = 1.
uint8_t baCSourceID ; ///< ID of the Clock Entity to which the first Clock Input Pin of this Clock Selector Entity is connected..
uint8_t bmControls ; ///< See: audio_clock_selector_control_pos_t.
uint8_t iClockSource ; ///< Index of a string descriptor, describing the Clock Selector Entity.
} audio_desc_clock_selector_t;
/// AUDIO Clock Selector Descriptor (4.7.2.2) for multiple pins
#define audio_desc_clock_selector_n_t(source_num) \
struct TU_ATTR_PACKED { \
uint8_t bLength ; \
uint8_t bDescriptorType ; \
uint8_t bDescriptorSubType ; \
uint8_t bClockID ; \
uint8_t bNrInPins ; \
struct TU_ATTR_PACKED { \
uint8_t baSourceID ; \
} sourceID[source_num] ; \
uint8_t bmControls ; \
uint8_t iClockSource ; \
}
/// AUDIO Clock Multiplier Descriptor (4.7.2.3)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 7.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_CLOCK_MULTIPLIER.
uint8_t bClockID ; ///< Constant uniquely identifying the Clock Multiplier Entity within the audio function. This value is used in all requests to address this Entity.
uint8_t bCSourceID ; ///< ID of the Clock Entity to which the last Clock Input Pin of this Clock Selector Entity is connected.
uint8_t bmControls ; ///< See: audio_clock_multiplier_control_pos_t.
uint8_t iClockSource ; ///< Index of a string descriptor, describing the Clock Multiplier Entity.
} audio_desc_clock_multiplier_t;
/// AUDIO Input Terminal Descriptor(4.7.2.4)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 17.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_INPUT_TERMINAL.
uint16_t wTerminalType ; ///< Constant characterizing the type of Terminal. See: audio_terminal_type_t for USB streaming and audio_terminal_input_type_t for other input types.
uint8_t bAssocTerminal ; ///< ID of the Output Terminal to which this Input Terminal is associated.
uint8_t bCSourceID ; ///< ID of the Clock Entity to which this Input Terminal is connected.
uint8_t bNrChannels ; ///< Number of logical output channels in the Terminals output audio channel cluster.
uint32_t bmChannelConfig ; ///< Describes the spatial location of the logical channels. See:audio_channel_config_t.
uint16_t bmControls ; ///< See: audio_terminal_input_control_pos_t.
uint8_t iTerminal ; ///< Index of a string descriptor, describing the Input Terminal.
} audio_desc_input_terminal_t;
/// AUDIO Output Terminal Descriptor(4.7.2.5)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 12.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_OUTPUT_TERMINAL.
uint8_t bTerminalID ; ///< Constant uniquely identifying the Terminal within the audio function. This value is used in all requests to address this Terminal.
uint16_t wTerminalType ; ///< Constant characterizing the type of Terminal. See: audio_terminal_type_t for USB streaming and audio_terminal_output_type_t for other output types.
uint8_t bAssocTerminal ; ///< Constant, identifying the Input Terminal to which this Output Terminal is associated.
uint8_t bSourceID ; ///< ID of the Unit or Terminal to which this Terminal is connected.
uint8_t bCSourceID ; ///< ID of the Clock Entity to which this Output Terminal is connected.
uint16_t bmControls ; ///< See: audio_terminal_output_type_t.
uint8_t iTerminal ; ///< Index of a string descriptor, describing the Output Terminal.
} audio_desc_output_terminal_t;
/// AUDIO Feature Unit Descriptor(4.7.2.8) for ONE channel
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 14.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AC_INTERFACE_FEATURE_UNIT.
uint8_t bUnitID ; ///< Constant uniquely identifying the Unit within the audio function. This value is used in all requests to address this Unit.
uint8_t bSourceID ; ///< ID of the Unit or Terminal to which this Feature Unit is connected.
struct TU_ATTR_PACKED {
uint32_t bmaControls ; ///< See: audio_feature_unit_control_pos_t. Controls0 is master channel 0 (always present) and Controls1 is logical channel 1.
} controls[2] ;
uint8_t iTerminal ; ///< Index of a string descriptor, describing this Feature Unit.
} audio_desc_feature_unit_t;
/// AUDIO Feature Unit Descriptor(4.7.2.8) for multiple channels
#define audio_desc_feature_unit_n_t(ch_num)\
struct TU_ATTR_PACKED { \
uint8_t bLength ; /* 6+(ch_num+1)*4 */\
uint8_t bDescriptorType ; \
uint8_t bDescriptorSubType ; \
uint8_t bUnitID ; \
uint8_t bSourceID ; \
struct TU_ATTR_PACKED { \
uint32_t bmaControls ; \
} controls[ch_num+1] ; \
uint8_t iTerminal ; \
}
/// AUDIO Class-Specific AS Interface Descriptor(4.9.2)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 16.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AS_INTERFACE_AS_GENERAL.
uint8_t bTerminalLink ; ///< The Terminal ID of the Terminal to which this interface is connected.
uint8_t bmControls ; ///< See: audio_cs_as_interface_control_pos_t.
uint8_t bFormatType ; ///< Constant identifying the Format Type the AudioStreaming interface is using. See: audio_format_type_t.
uint32_t bmFormats ; ///< The Audio Data Format(s) that can be used to communicate with this interface.See: audio_data_format_type_I_t.
uint8_t bNrChannels ; ///< Number of physical channels in the AS Interface audio channel cluster.
uint32_t bmChannelConfig ; ///< Describes the spatial location of the physical channels. See: audio_channel_config_t.
uint8_t iChannelNames ; ///< Index of a string descriptor, describing the name of the first physical channel.
} audio_desc_cs_as_interface_t;
/// AUDIO Type I Format Type Descriptor(2.3.1.6 - Audio Formats)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 6.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_INTERFACE.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_AS_INTERFACE_FORMAT_TYPE.
uint8_t bFormatType ; ///< Constant identifying the Format Type the AudioStreaming interface is using. Value: AUDIO_FORMAT_TYPE_I.
uint8_t bSubslotSize ; ///< The number of bytes occupied by one audio subslot. Can be 1, 2, 3 or 4.
uint8_t bBitResolution ; ///< The number of effectively used bits from the available bits in an audio subslot.
} audio_desc_type_I_format_t;
/// AUDIO Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor, in bytes: 8.
uint8_t bDescriptorType ; ///< Descriptor Type. Value: TUSB_DESC_CS_ENDPOINT.
uint8_t bDescriptorSubType ; ///< Descriptor SubType. Value: AUDIO_CS_EP_SUBTYPE_GENERAL.
uint8_t bmAttributes ; ///< See: audio_cs_as_iso_data_ep_attribute_t.
uint8_t bmControls ; ///< See: audio_cs_as_iso_data_ep_control_pos_t.
uint8_t bLockDelayUnits ; ///< Indicates the units used for the wLockDelay field. See: audio_cs_as_iso_data_ep_lock_delay_unit_t.
uint16_t wLockDelay ; ///< Indicates the time it takes this endpoint to reliably lock its internal clock recovery circuitry. Units used depend on the value of the bLockDelayUnits field.
} audio_desc_cs_as_iso_data_ep_t;
// 5.2.2 Control Request Layout
typedef struct TU_ATTR_PACKED
{
union
{
struct TU_ATTR_PACKED
{
uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
uint8_t type : 2; ///< Request type tusb_request_type_t.
uint8_t direction : 1; ///< Direction type. tusb_dir_t
} bmRequestType_bit;
uint8_t bmRequestType;
};
uint8_t bRequest; ///< Request type audio_cs_req_t
uint8_t bChannelNumber;
uint8_t bControlSelector;
union
{
uint8_t bInterface;
uint8_t bEndpoint;
};
uint8_t bEntityID;
uint16_t wLength;
} audio_control_request_t;
//// 5.2.3 Control Request Parameter Block Layout
// 5.2.3.1 1-byte Control CUR Parameter Block
typedef struct TU_ATTR_PACKED
{
int8_t bCur ; ///< The setting for the CUR attribute of the addressed Control
} audio_control_cur_1_t;
// 5.2.3.2 2-byte Control CUR Parameter Block
typedef struct TU_ATTR_PACKED
{
int16_t bCur ; ///< The setting for the CUR attribute of the addressed Control
} audio_control_cur_2_t;
// 5.2.3.3 4-byte Control CUR Parameter Block
typedef struct TU_ATTR_PACKED
{
int32_t bCur ; ///< The setting for the CUR attribute of the addressed Control
} audio_control_cur_4_t;
// Use the following ONLY for RECEIVED data - compiler does not know how many subranges are defined! Use the one below for predefined lengths - or if you know what you are doing do what you like
// 5.2.3.1 1-byte Control RANGE Parameter Block
typedef struct TU_ATTR_PACKED {
uint16_t wNumSubRanges;
struct TU_ATTR_PACKED {
int8_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/
int8_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/
uint8_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/
} subrange[] ;
} audio_control_range_1_t;
// 5.2.3.2 2-byte Control RANGE Parameter Block
typedef struct TU_ATTR_PACKED {
uint16_t wNumSubRanges;
struct TU_ATTR_PACKED {
int16_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/
int16_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/
uint16_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/
} subrange[] ;
} audio_control_range_2_t;
// 5.2.3.3 4-byte Control RANGE Parameter Block
typedef struct TU_ATTR_PACKED {
uint16_t wNumSubRanges;
struct TU_ATTR_PACKED {
int32_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/
int32_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/
uint32_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/
} subrange[] ;
} audio_control_range_4_t;
// 5.2.3.1 1-byte Control RANGE Parameter Block
#define audio_control_range_1_n_t(numSubRanges) \
struct TU_ATTR_PACKED { \
uint16_t wNumSubRanges; \
struct TU_ATTR_PACKED { \
int8_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/\
int8_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/\
uint8_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/\
} subrange[numSubRanges] ; \
}
/// 5.2.3.2 2-byte Control RANGE Parameter Block
#define audio_control_range_2_n_t(numSubRanges) \
struct TU_ATTR_PACKED { \
uint16_t wNumSubRanges; \
struct TU_ATTR_PACKED { \
int16_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/\
int16_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/\
uint16_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/\
} subrange[numSubRanges]; \
}
// 5.2.3.3 4-byte Control RANGE Parameter Block
#define audio_control_range_4_n_t(numSubRanges) \
struct TU_ATTR_PACKED { \
uint16_t wNumSubRanges; \
struct TU_ATTR_PACKED { \
int32_t bMin ; /*The setting for the MIN attribute of the nth subrange of the addressed Control*/\
int32_t bMax ; /*The setting for the MAX attribute of the nth subrange of the addressed Control*/\
uint32_t bRes ; /*The setting for the RES attribute of the nth subrange of the addressed Control*/\
} subrange[numSubRanges]; \
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View File

@ -0,0 +1,637 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ha Thach (tinyusb.org)
* Copyright (c) 2020 Reinhard Panhuber
*
* 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.
*/
#ifndef _TUSB_AUDIO_DEVICE_H_
#define _TUSB_AUDIO_DEVICE_H_
#include "audio.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
// All sizes are in bytes!
#ifndef CFG_TUD_AUDIO_FUNC_1_DESC_LEN
#error You must tell the driver the length of the audio function descriptor including IAD descriptor
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_DESC_LEN
#error You must tell the driver the length of the audio function descriptor including IAD descriptor
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_DESC_LEN
#error You must tell the driver the length of the audio function descriptor including IAD descriptor
#endif
#endif
// Number of Standard AS Interface Descriptors (4.9.1) defined per audio function - this is required to be able to remember the current alternate settings of these interfaces
#ifndef CFG_TUD_AUDIO_FUNC_1_N_AS_INT
#error You must tell the driver the number of Standard AS Interface Descriptors you have defined in the audio function descriptor!
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_N_AS_INT
#error You must tell the driver the number of Standard AS Interface Descriptors you have defined in the audio function descriptor!
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_N_AS_INT
#error You must tell the driver the number of Standard AS Interface Descriptors you have defined in the audio function descriptor!
#endif
#endif
// Size of control buffer used to receive and send control messages via EP0 - has to be big enough to hold your biggest request structure e.g. range requests with multiple intervals defined or cluster descriptors
#ifndef CFG_TUD_AUDIO_FUNC_1_CTRL_BUF_SZ
#error You must define an audio class control request buffer size!
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_CTRL_BUF_SZ
#error You must define an audio class control request buffer size!
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_CTRL_BUF_SZ
#error You must define an audio class control request buffer size!
#endif
#endif
// End point sizes IN BYTES - Limits: Full Speed <= 1023, High Speed <= 1024
#ifndef CFG_TUD_AUDIO_ENABLE_EP_IN
#define CFG_TUD_AUDIO_ENABLE_EP_IN 0 // TX
#endif
#ifndef CFG_TUD_AUDIO_ENABLE_EP_OUT
#define CFG_TUD_AUDIO_ENABLE_EP_OUT 0 // RX
#endif
// Maximum EP sizes for all alternate AS interface settings - used for checks and buffer allocation
#if CFG_TUD_AUDIO_ENABLE_EP_IN
#ifndef CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX
#error You must tell the driver the biggest EP IN size!
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX
#error You must tell the driver the biggest EP IN size!
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX
#error You must tell the driver the biggest EP IN size!
#endif
#endif
#endif // CFG_TUD_AUDIO_ENABLE_EP_IN
#if CFG_TUD_AUDIO_ENABLE_EP_OUT
#ifndef CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX
#error You must tell the driver the biggest EP OUT size!
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX
#error You must tell the driver the biggest EP OUT size!
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX
#error You must tell the driver the biggest EP OUT size!
#endif
#endif
#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT
// Software EP FIFO buffer sizes - must be >= max EP SIZEs!
#ifndef CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ
#define CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ 0
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_IN
#if CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#if CFG_TUD_AUDIO > 1
#if CFG_TUD_AUDIO_FUNC_2_EP_IN_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_2_EP_IN_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#endif
#if CFG_TUD_AUDIO > 2
#if CFG_TUD_AUDIO_FUNC_3_EP_IN_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_3_EP_IN_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#endif
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT
#if CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#if CFG_TUD_AUDIO > 1
#if CFG_TUD_AUDIO_FUNC_2_EP_OUT_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_2_EP_OUT_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#endif
#if CFG_TUD_AUDIO > 2
#if CFG_TUD_AUDIO_FUNC_3_EP_OUT_SW_BUF_SZ < CFG_TUD_AUDIO_FUNC_3_EP_OUT_SZ_MAX
#error EP software buffer size MUST BE at least as big as maximum EP size
#endif
#endif
#endif
// Enable/disable feedback EP (required for asynchronous RX applications)
#ifndef CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
#define CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP 0 // Feedback - 0 or 1
#endif
// Enable/disable conversion from 16.16 to 10.14 format on full-speed devices. See tud_audio_n_fb_set().
#ifndef CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION
#define CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION 0 // 0 or 1
#endif
// Audio interrupt control EP size - disabled if 0
#ifndef CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN
#define CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN 0 // Audio interrupt control - if required - 6 Bytes according to UAC 2 specification (p. 74)
#endif
#ifndef CFG_TUD_AUDIO_INT_CTR_EP_IN_SW_BUFFER_SIZE
#define CFG_TUD_AUDIO_INT_CTR_EP_IN_SW_BUFFER_SIZE 6 // Buffer size of audio control interrupt EP - 6 Bytes according to UAC 2 specification (p. 74)
#endif
// Use software encoding/decoding
// The software coding feature of the driver is not mandatory. It is useful if, for instance, you have two I2S streams which need to be interleaved
// into a single PCM stream as SAMPLE_1 | SAMPLE_2 | SAMPLE_3 | SAMPLE_4.
//
// Currently, only PCM type I encoding/decoding is supported!
//
// If the coding feature is to be used, support FIFOs need to be configured. Their sizes and numbers are defined below.
// Encoding/decoding is done in software and thus time consuming. If you can encode/decode your stream more efficiently do not use the
// support FIFOs but write/read directly into/from the EP_X_SW_BUFFER_FIFOs using
// - tud_audio_n_write() or
// - tud_audio_n_read().
// To write/read to/from the support FIFOs use
// - tud_audio_n_write_support_ff() or
// - tud_audio_n_read_support_ff().
//
// The encoding/decoding format type done is defined below.
//
// The encoding/decoding starts when the private callback functions
// - audio_tx_done_cb()
// - audio_rx_done_cb()
// are invoked. If support FIFOs are used, the corresponding encoding/decoding functions are called from there.
// Once encoding/decoding is done the result is put directly into the EP_X_SW_BUFFER_FIFOs. You can use the public callback functions
// - tud_audio_tx_done_pre_load_cb() or tud_audio_tx_done_post_load_cb()
// - tud_audio_rx_done_pre_read_cb() or tud_audio_rx_done_post_read_cb()
// if you want to get informed what happened.
//
// If you don't use the support FIFOs you may use the public callback functions
// - tud_audio_tx_done_pre_load_cb() or tud_audio_tx_done_post_load_cb()
// - tud_audio_rx_done_pre_read_cb() or tud_audio_rx_done_post_read_cb()
// to write/read from/into the EP_X_SW_BUFFER_FIFOs at the right time.
//
// If you need a different encoding which is not support so far implement it in the
// - audio_tx_done_cb()
// - audio_rx_done_cb()
// functions.
// Enable encoding/decodings - for these to work, support FIFOs need to be setup in appropriate numbers and size
// The actual coding parameters of active AS alternate interface is parsed from the descriptors
// The item size of the FIFO is always fixed to one i.e. bytes! Furthermore, the actively used FIFO depth is reconfigured such that the depth is a multiple of the current sample size in order to avoid samples to get split up in case of a wrap in the FIFO ring buffer (depth = (max_depth / sampe_sz) * sampe_sz)!
// This is important to remind in case you use DMAs! If the sample sizes changes, the DMA MUST BE RECONFIGURED just like the FIFOs for a different depth!!!
// For PCM encoding/decoding
#ifndef CFG_TUD_AUDIO_ENABLE_ENCODING
#define CFG_TUD_AUDIO_ENABLE_ENCODING 0
#endif
#ifndef CFG_TUD_AUDIO_ENABLE_DECODING
#define CFG_TUD_AUDIO_ENABLE_DECODING 0
#endif
// This enabling allows to save the current coding parameters e.g. # of bytes per sample etc. - TYPE_I includes common PCM encoding
#ifndef CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING
#define CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING 0
#endif
#ifndef CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING
#define CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING 0
#endif
// Type I Coding parameters not given within UAC2 descriptors
// It would be possible to allow for a more flexible setting and not fix this parameter as done below. However, this is most often not needed and kept for later if really necessary. The more flexible setting could be implemented within set_interface(), however, how the values are saved per alternate setting is to be determined!
#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING && CFG_TUD_AUDIO_ENABLE_TYPE_I_ENCODING
#ifndef CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_TX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_TX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_TX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#endif
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING && CFG_TUD_AUDIO_ENABLE_TYPE_I_DECODING
#ifndef CFG_TUD_AUDIO_FUNC_1_CHANNEL_PER_FIFO_RX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#if CFG_TUD_AUDIO > 1
#ifndef CFG_TUD_AUDIO_FUNC_2_CHANNEL_PER_FIFO_RX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#endif
#if CFG_TUD_AUDIO > 2
#ifndef CFG_TUD_AUDIO_FUNC_3_CHANNEL_PER_FIFO_RX
#error You must tell the driver the number of channels per FIFO for the interleaved encoding! E.g. for an I2S interface having two channels, CHANNEL_PER_FIFO = 2 as the I2S stream having two channels is usually saved within one FIFO
#endif
#endif
#endif
// Remaining types not support so far
// Number of support FIFOs to set up - multiple channels can be handled by one FIFO - very common is two channels per FIFO stemming from one I2S interface
#ifndef CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_1_N_TX_SUPP_SW_FIFO 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_2_N_TX_SUPP_SW_FIFO 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_3_N_TX_SUPP_SW_FIFO 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_1_N_RX_SUPP_SW_FIFO 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_2_N_RX_SUPP_SW_FIFO 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO
#define CFG_TUD_AUDIO_FUNC_3_N_RX_SUPP_SW_FIFO 0
#endif
// Size of support FIFOs IN BYTES - if size > 0 there are as many FIFOs set up as CFG_TUD_AUDIO_FUNC_X_N_TX_SUPP_SW_FIFO and CFG_TUD_AUDIO_FUNC_X_N_RX_SUPP_SW_FIFO
#ifndef CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_1_TX_SUPP_SW_FIFO_SZ 0 // FIFO size - minimum size: ceil(f_s/1000) * max(# of TX channels) / (# of TX support FIFOs) * max(# of bytes per sample)
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_2_TX_SUPP_SW_FIFO_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_3_TX_SUPP_SW_FIFO_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_1_RX_SUPP_SW_FIFO_SZ 0 // FIFO size - minimum size: ceil(f_s/1000) * max(# of RX channels) / (# of RX support FIFOs) * max(# of bytes per sample)
#endif
#ifndef CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_2_RX_SUPP_SW_FIFO_SZ 0
#endif
#ifndef CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ
#define CFG_TUD_AUDIO_FUNC_3_RX_SUPP_SW_FIFO_SZ 0
#endif
//static_assert(sizeof(tud_audio_desc_lengths) != CFG_TUD_AUDIO, "Supply audio function descriptor pack length!");
// Supported types of this driver:
// AUDIO_DATA_FORMAT_TYPE_I_PCM - Required definitions: CFG_TUD_AUDIO_N_CHANNELS and CFG_TUD_AUDIO_BYTES_PER_CHANNEL
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup AUDIO_Serial Serial
* @{
* \defgroup AUDIO_Serial_Device Device
* @{ */
//--------------------------------------------------------------------+
// Application API (Multiple Interfaces)
// CFG_TUD_AUDIO > 1
//--------------------------------------------------------------------+
bool tud_audio_n_mounted (uint8_t func_id);
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING
uint16_t tud_audio_n_available (uint8_t func_id);
uint16_t tud_audio_n_read (uint8_t func_id, void* buffer, uint16_t bufsize);
bool tud_audio_n_clear_ep_out_ff (uint8_t func_id); // Delete all content in the EP OUT FIFO
tu_fifo_t* tud_audio_n_get_ep_out_ff (uint8_t func_id);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING
bool tud_audio_n_clear_rx_support_ff (uint8_t func_id, uint8_t ff_idx); // Delete all content in the support RX FIFOs
uint16_t tud_audio_n_available_support_ff (uint8_t func_id, uint8_t ff_idx);
uint16_t tud_audio_n_read_support_ff (uint8_t func_id, uint8_t ff_idx, void* buffer, uint16_t bufsize);
tu_fifo_t* tud_audio_n_get_rx_support_ff (uint8_t func_id, uint8_t ff_idx);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING
uint16_t tud_audio_n_write (uint8_t func_id, const void * data, uint16_t len);
bool tud_audio_n_clear_ep_in_ff (uint8_t func_id); // Delete all content in the EP IN FIFO
tu_fifo_t* tud_audio_n_get_ep_in_ff (uint8_t func_id);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING
uint16_t tud_audio_n_flush_tx_support_ff (uint8_t func_id); // Force all content in the support TX FIFOs to be written into EP SW FIFO
bool tud_audio_n_clear_tx_support_ff (uint8_t func_id, uint8_t ff_idx);
uint16_t tud_audio_n_write_support_ff (uint8_t func_id, uint8_t ff_idx, const void * data, uint16_t len);
tu_fifo_t* tud_audio_n_get_tx_support_ff (uint8_t func_id, uint8_t ff_idx);
#endif
#if CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN
uint16_t tud_audio_int_ctr_n_write (uint8_t func_id, uint8_t const* buffer, uint16_t len);
#endif
//--------------------------------------------------------------------+
// Application API (Interface0)
//--------------------------------------------------------------------+
static inline bool tud_audio_mounted (void);
// RX API
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING
static inline uint16_t tud_audio_available (void);
static inline bool tud_audio_clear_ep_out_ff (void); // Delete all content in the EP OUT FIFO
static inline uint16_t tud_audio_read (void* buffer, uint16_t bufsize);
static inline tu_fifo_t* tud_audio_get_ep_out_ff (void);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING
static inline bool tud_audio_clear_rx_support_ff (uint8_t ff_idx);
static inline uint16_t tud_audio_available_support_ff (uint8_t ff_idx);
static inline uint16_t tud_audio_read_support_ff (uint8_t ff_idx, void* buffer, uint16_t bufsize);
static inline tu_fifo_t* tud_audio_get_rx_support_ff (uint8_t ff_idx);
#endif
// TX API
#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING
static inline uint16_t tud_audio_write (const void * data, uint16_t len);
static inline bool tud_audio_clear_ep_in_ff (void);
static inline tu_fifo_t* tud_audio_get_ep_in_ff (void);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING
static inline uint16_t tud_audio_flush_tx_support_ff (void);
static inline uint16_t tud_audio_clear_tx_support_ff (uint8_t ff_idx);
static inline uint16_t tud_audio_write_support_ff (uint8_t ff_idx, const void * data, uint16_t len);
static inline tu_fifo_t* tud_audio_get_tx_support_ff (uint8_t ff_idx);
#endif
// INT CTR API
#if CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN
static inline uint16_t tud_audio_int_ctr_write (uint8_t const* buffer, uint16_t len);
#endif
// Buffer control EP data and schedule a transmit
// This function is intended to be used if you do not have a persistent buffer or memory location available (e.g. non-local variables) and need to answer onto a
// get request. This function buffers your answer request frame into the control buffer of the corresponding audio driver and schedules a transmit for sending it.
// Since transmission is triggered via interrupts, a persistent memory location is required onto which the buffer pointer in pointing. If you already have such
// available you may directly use 'tud_control_xfer(...)'. In this case data does not need to be copied into an additional buffer and you save some time.
// If the request's wLength is zero, a status packet is sent instead.
bool tud_audio_buffer_and_schedule_control_xfer(uint8_t rhport, tusb_control_request_t const * p_request, void* data, uint16_t len);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
#if CFG_TUD_AUDIO_ENABLE_EP_IN
TU_ATTR_WEAK bool tud_audio_tx_done_pre_load_cb(uint8_t rhport, uint8_t func_id, uint8_t ep_in, uint8_t cur_alt_setting);
TU_ATTR_WEAK bool tud_audio_tx_done_post_load_cb(uint8_t rhport, uint16_t n_bytes_copied, uint8_t func_id, uint8_t ep_in, uint8_t cur_alt_setting);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT
TU_ATTR_WEAK bool tud_audio_rx_done_pre_read_cb(uint8_t rhport, uint16_t n_bytes_received, uint8_t func_id, uint8_t ep_out, uint8_t cur_alt_setting);
TU_ATTR_WEAK bool tud_audio_rx_done_post_read_cb(uint8_t rhport, uint16_t n_bytes_received, uint8_t func_id, uint8_t ep_out, uint8_t cur_alt_setting);
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
TU_ATTR_WEAK bool tud_audio_fb_done_cb(uint8_t rhport);
// This function is used to provide data rate feedback from an asynchronous sink. Feedback value will be sent at FB endpoint interval till it's changed.
//
// The feedback format is specified to be 16.16 for HS and 10.14 for FS devices (see Universal Serial Bus Specification Revision 2.0 5.12.4.2). By default,
// the choice of format is left to the caller and feedback argument is sent as-is. If CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION is set, then tinyusb
// expects 16.16 format and handles the conversion to 10.14 on FS.
//
// Note that due to a bug in its USB Audio 2.0 driver, Windows currently requires 16.16 format for _all_ USB 2.0 devices. On Linux and macOS it seems the
// driver can work with either format. So a good compromise is to keep format correction disabled and stick to 16.16 format.
bool tud_audio_n_fb_set(uint8_t func_id, uint32_t feedback);
static inline bool tud_audio_fb_set(uint32_t feedback);
#endif
#if CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN
TU_ATTR_WEAK bool tud_audio_int_ctr_done_cb(uint8_t rhport, uint16_t n_bytes_copied);
#endif
// Invoked when audio set interface request received
TU_ATTR_WEAK bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request);
// Invoked when audio set interface request received which closes an EP
TU_ATTR_WEAK bool tud_audio_set_itf_close_EP_cb(uint8_t rhport, tusb_control_request_t const * p_request);
// Invoked when audio class specific set request received for an EP
TU_ATTR_WEAK bool tud_audio_set_req_ep_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff);
// Invoked when audio class specific set request received for an interface
TU_ATTR_WEAK bool tud_audio_set_req_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff);
// Invoked when audio class specific set request received for an entity
TU_ATTR_WEAK bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const * p_request, uint8_t *pBuff);
// Invoked when audio class specific get request received for an EP
TU_ATTR_WEAK bool tud_audio_get_req_ep_cb(uint8_t rhport, tusb_control_request_t const * p_request);
// Invoked when audio class specific get request received for an interface
TU_ATTR_WEAK bool tud_audio_get_req_itf_cb(uint8_t rhport, tusb_control_request_t const * p_request);
// Invoked when audio class specific get request received for an entity
TU_ATTR_WEAK bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const * p_request);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline bool tud_audio_mounted(void)
{
return tud_audio_n_mounted(0);
}
// RX API
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && !CFG_TUD_AUDIO_ENABLE_DECODING
static inline uint16_t tud_audio_available(void)
{
return tud_audio_n_available(0);
}
static inline uint16_t tud_audio_read(void* buffer, uint16_t bufsize)
{
return tud_audio_n_read(0, buffer, bufsize);
}
static inline bool tud_audio_clear_ep_out_ff(void)
{
return tud_audio_n_clear_ep_out_ff(0);
}
static inline tu_fifo_t* tud_audio_get_ep_out_ff(void)
{
return tud_audio_n_get_ep_out_ff(0);
}
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_DECODING
static inline bool tud_audio_clear_rx_support_ff(uint8_t ff_idx)
{
return tud_audio_n_clear_rx_support_ff(0, ff_idx);
}
static inline uint16_t tud_audio_available_support_ff(uint8_t ff_idx)
{
return tud_audio_n_available_support_ff(0, ff_idx);
}
static inline uint16_t tud_audio_read_support_ff(uint8_t ff_idx, void* buffer, uint16_t bufsize)
{
return tud_audio_n_read_support_ff(0, ff_idx, buffer, bufsize);
}
static inline tu_fifo_t* tud_audio_get_rx_support_ff(uint8_t ff_idx)
{
return tud_audio_n_get_rx_support_ff(0, ff_idx);
}
#endif
// TX API
#if CFG_TUD_AUDIO_ENABLE_EP_IN && !CFG_TUD_AUDIO_ENABLE_ENCODING
static inline uint16_t tud_audio_write(const void * data, uint16_t len)
{
return tud_audio_n_write(0, data, len);
}
static inline bool tud_audio_clear_ep_in_ff(void)
{
return tud_audio_n_clear_ep_in_ff(0);
}
static inline tu_fifo_t* tud_audio_get_ep_in_ff(void)
{
return tud_audio_n_get_ep_in_ff(0);
}
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_IN && CFG_TUD_AUDIO_ENABLE_ENCODING
static inline uint16_t tud_audio_flush_tx_support_ff(void)
{
return tud_audio_n_flush_tx_support_ff(0);
}
static inline uint16_t tud_audio_clear_tx_support_ff(uint8_t ff_idx)
{
return tud_audio_n_clear_tx_support_ff(0, ff_idx);
}
static inline uint16_t tud_audio_write_support_ff(uint8_t ff_idx, const void * data, uint16_t len)
{
return tud_audio_n_write_support_ff(0, ff_idx, data, len);
}
static inline tu_fifo_t* tud_audio_get_tx_support_ff(uint8_t ff_idx)
{
return tud_audio_n_get_tx_support_ff(0, ff_idx);
}
#endif
#if CFG_TUD_AUDIO_INT_CTR_EPSIZE_IN
static inline uint16_t tud_audio_int_ctr_write(uint8_t const* buffer, uint16_t len)
{
return tud_audio_int_ctr_n_write(0, buffer, len);
}
#endif
#if CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
static inline bool tud_audio_fb_set(uint32_t feedback)
{
return tud_audio_n_fb_set(0, feedback);
}
#endif
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void audiod_init (void);
void audiod_reset (uint8_t rhport);
uint16_t audiod_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool audiod_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool audiod_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_AUDIO_DEVICE_H_ */
/** @} */
/** @} */

View File

@ -0,0 +1,109 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Jerzy Kasenberg
*
* 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.
*/
#ifndef _TUSB_BTH_DEVICE_H_
#define _TUSB_BTH_DEVICE_H_
#include <common/tusb_common.h>
#include <device/usbd.h>
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUD_BTH_EVENT_EPSIZE
#define CFG_TUD_BTH_EVENT_EPSIZE 16
#endif
#ifndef CFG_TUD_BTH_DATA_EPSIZE
#define CFG_TUD_BTH_DATA_EPSIZE 64
#endif
typedef struct TU_ATTR_PACKED
{
uint16_t op_code;
uint8_t param_length;
uint8_t param[255];
} bt_hci_cmd_t;
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when HCI command was received over USB from Bluetooth host.
// Detailed format is described in Bluetooth core specification Vol 2,
// Part E, 5.4.1.
// Length of the command is from 3 bytes (2 bytes for OpCode,
// 1 byte for parameter total length) to 258.
TU_ATTR_WEAK void tud_bt_hci_cmd_cb(void *hci_cmd, size_t cmd_len);
// Invoked when ACL data was received over USB from Bluetooth host.
// Detailed format is described in Bluetooth core specification Vol 2,
// Part E, 5.4.2.
// Length is from 4 bytes, (12 bits for Handle, 4 bits for flags
// and 16 bits for data total length) to endpoint size.
TU_ATTR_WEAK void tud_bt_acl_data_received_cb(void *acl_data, uint16_t data_len);
// Called when event sent with tud_bt_event_send() was delivered to BT stack.
// Controller can release/reuse buffer with Event packet at this point.
TU_ATTR_WEAK void tud_bt_event_sent_cb(uint16_t sent_bytes);
// Called when ACL data that was sent with tud_bt_acl_data_send()
// was delivered to BT stack.
// Controller can release/reuse buffer with ACL packet at this point.
TU_ATTR_WEAK void tud_bt_acl_data_sent_cb(uint16_t sent_bytes);
// Bluetooth controller calls this function when it wants to send even packet
// as described in Bluetooth core specification Vol 2, Part E, 5.4.4.
// Event has at least 2 bytes, first is Event code second contains parameter
// total length. Controller can release/reuse event memory after
// tud_bt_event_sent_cb() is called.
bool tud_bt_event_send(void *event, uint16_t event_len);
// Bluetooth controller calls this to send ACL data packet
// as described in Bluetooth core specification Vol 2, Part E, 5.4.2
// Minimum length is 4 bytes, (12 bits for Handle, 4 bits for flags
// and 16 bits for data total length). Upper limit is not limited
// to endpoint size since buffer is allocate by controller
// and must not be reused till tud_bt_acl_data_sent_cb() is called.
bool tud_bt_acl_data_send(void *acl_data, uint16_t data_len);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void btd_init (void);
void btd_reset (uint8_t rhport);
uint16_t btd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool btd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const *request);
bool btd_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_BTH_DEVICE_H_ */

View File

@ -0,0 +1,409 @@
/*
* 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_class
* \defgroup ClassDriver_CDC Communication Device Class (CDC)
* Currently only Abstract Control Model subclass is supported
* @{ */
#ifndef _TUSB_CDC_H__
#define _TUSB_CDC_H__
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
/** \defgroup ClassDriver_CDC_Common Common Definitions
* @{ */
// TODO remove
/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In)
typedef enum
{
CDC_PIPE_NOTIFICATION , ///< Notification pipe
CDC_PIPE_DATA_IN , ///< Data in pipe
CDC_PIPE_DATA_OUT , ///< Data out pipe
CDC_PIPE_ERROR , ///< Invalid Pipe ID
}cdc_pipeid_t;
//--------------------------------------------------------------------+
// CDC Communication Interface Class
//--------------------------------------------------------------------+
/// Communication Interface Subclass Codes
typedef enum
{
CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL = 0x02 , ///< Abstract Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL = 0x03 , ///< Telephone Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL = 0x04 , ///< Multi-Channel Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL = 0x05 , ///< CAPI Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL = 0x06 , ///< Ethernet Networking Control Model [USBECM1.2]
CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL = 0x07 , ///< ATM Networking Control Model [USBATM1.2]
CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL = 0x08 , ///< Wireless Handset Control Model [USBWMC1.1]
CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT = 0x09 , ///< Device Management [USBWMC1.1]
CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL = 0x0A , ///< Mobile Direct Line Model [USBWMC1.1]
CDC_COMM_SUBCLASS_OBEX = 0x0B , ///< OBEX [USBWMC1.1]
CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL = 0x0C , ///< Ethernet Emulation Model [USBEEM1.0]
CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL = 0x0D ///< Network Control Model [USBNCM1.0]
} cdc_comm_sublcass_type_t;
/// Communication Interface Protocol Codes
typedef enum
{
CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol
CDC_COMM_PROTOCOL_ATCOMMAND = 0x01 , ///< AT Commands: V.250 etc
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 = 0x02 , ///< AT Commands defined by PCCA-101
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO = 0x03 , ///< AT Commands defined by PCCA-101 & Annex O
CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 = 0x04 , ///< AT Commands defined by GSM 07.07
CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 = 0x05 , ///< AT Commands defined by 3GPP 27.007
CDC_COMM_PROTOCOL_ATCOMMAND_CDMA = 0x06 , ///< AT Commands defined by TIA for CDMA
CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL = 0x07 ///< Ethernet Emulation Model
} cdc_comm_protocol_type_t;
//------------- SubType Descriptor in COMM Functional Descriptor -------------//
/// Communication Interface SubType Descriptor
typedef enum
{
CDC_FUNC_DESC_HEADER = 0x00 , ///< Header Functional Descriptor, which marks the beginning of the concatenated set of functional descriptors for the interface.
CDC_FUNC_DESC_CALL_MANAGEMENT = 0x01 , ///< Call Management Functional Descriptor.
CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT = 0x02 , ///< Abstract Control Management Functional Descriptor.
CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT = 0x03 , ///< Direct Line Management Functional Descriptor.
CDC_FUNC_DESC_TELEPHONE_RINGER = 0x04 , ///< Telephone Ringer Functional Descriptor.
CDC_FUNC_DESC_TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPACITY = 0x05 , ///< Telephone Call and Line State Reporting Capabilities Functional Descriptor.
CDC_FUNC_DESC_UNION = 0x06 , ///< Union Functional Descriptor
CDC_FUNC_DESC_COUNTRY_SELECTION = 0x07 , ///< Country Selection Functional Descriptor
CDC_FUNC_DESC_TELEPHONE_OPERATIONAL_MODES = 0x08 , ///< Telephone Operational ModesFunctional Descriptor
CDC_FUNC_DESC_USB_TERMINAL = 0x09 , ///< USB Terminal Functional Descriptor
CDC_FUNC_DESC_NETWORK_CHANNEL_TERMINAL = 0x0A , ///< Network Channel Terminal Descriptor
CDC_FUNC_DESC_PROTOCOL_UNIT = 0x0B , ///< Protocol Unit Functional Descriptor
CDC_FUNC_DESC_EXTENSION_UNIT = 0x0C , ///< Extension Unit Functional Descriptor
CDC_FUNC_DESC_MULTICHANEL_MANAGEMENT = 0x0D , ///< Multi-Channel Management Functional Descriptor
CDC_FUNC_DESC_CAPI_CONTROL_MANAGEMENT = 0x0E , ///< CAPI Control Management Functional Descriptor
CDC_FUNC_DESC_ETHERNET_NETWORKING = 0x0F , ///< Ethernet Networking Functional Descriptor
CDC_FUNC_DESC_ATM_NETWORKING = 0x10 , ///< ATM Networking Functional Descriptor
CDC_FUNC_DESC_WIRELESS_HANDSET_CONTROL_MODEL = 0x11 , ///< Wireless Handset Control Model Functional Descriptor
CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL = 0x12 , ///< Mobile Direct Line Model Functional Descriptor
CDC_FUNC_DESC_MOBILE_DIRECT_LINE_MODEL_DETAIL = 0x13 , ///< MDLM Detail Functional Descriptor
CDC_FUNC_DESC_DEVICE_MANAGEMENT_MODEL = 0x14 , ///< Device Management Model Functional Descriptor
CDC_FUNC_DESC_OBEX = 0x15 , ///< OBEX Functional Descriptor
CDC_FUNC_DESC_COMMAND_SET = 0x16 , ///< Command Set Functional Descriptor
CDC_FUNC_DESC_COMMAND_SET_DETAIL = 0x17 , ///< Command Set Detail Functional Descriptor
CDC_FUNC_DESC_TELEPHONE_CONTROL_MODEL = 0x18 , ///< Telephone Control Model Functional Descriptor
CDC_FUNC_DESC_OBEX_SERVICE_IDENTIFIER = 0x19 , ///< OBEX Service Identifier Functional Descriptor
CDC_FUNC_DESC_NCM = 0x1A , ///< NCM Functional Descriptor
}cdc_func_desc_type_t;
//--------------------------------------------------------------------+
// CDC Data Interface Class
//--------------------------------------------------------------------+
// SUBCLASS code of Data Interface is not used and should/must be zero
// Data Interface Protocol Codes
typedef enum{
CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI
CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC
CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent
CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol
CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931
CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol
CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures
CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control
CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN
CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands
CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack.
CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface
}cdc_data_protocol_type_t;
//--------------------------------------------------------------------+
// Management Element Request (Control Endpoint)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Request Codes
typedef enum
{
CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface
CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface.
CDC_REQUEST_SET_COMM_FEATURE = 0x02,
CDC_REQUEST_GET_COMM_FEATURE = 0x03,
CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04,
CDC_REQUEST_SET_AUX_LINE_STATE = 0x10,
CDC_REQUEST_SET_HOOK_STATE = 0x11,
CDC_REQUEST_PULSE_SETUP = 0x12,
CDC_REQUEST_SEND_PULSE = 0x13,
CDC_REQUEST_SET_PULSE_TIME = 0x14,
CDC_REQUEST_RING_AUX_JACK = 0x15,
CDC_REQUEST_SET_LINE_CODING = 0x20,
CDC_REQUEST_GET_LINE_CODING = 0x21,
CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22,
CDC_REQUEST_SEND_BREAK = 0x23,
CDC_REQUEST_SET_RINGER_PARMS = 0x30,
CDC_REQUEST_GET_RINGER_PARMS = 0x31,
CDC_REQUEST_SET_OPERATION_PARMS = 0x32,
CDC_REQUEST_GET_OPERATION_PARMS = 0x33,
CDC_REQUEST_SET_LINE_PARMS = 0x34,
CDC_REQUEST_GET_LINE_PARMS = 0x35,
CDC_REQUEST_DIAL_DIGITS = 0x36,
CDC_REQUEST_SET_UNIT_PARAMETER = 0x37,
CDC_REQUEST_GET_UNIT_PARAMETER = 0x38,
CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39,
CDC_REQUEST_GET_PROFILE = 0x3A,
CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40,
CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41,
CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42,
CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43,
CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44,
CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50,
CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51,
CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52,
CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53,
CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60,
}cdc_management_request_t;
//--------------------------------------------------------------------+
// Management Elemenent Notification (Notification Endpoint)
//--------------------------------------------------------------------+
/// 6.3 Notification Codes
typedef enum
{
CDC_NOTIF_NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status.
CDC_NOTIF_RESPONSE_AVAILABLE = 0x01, ///< This notification allows the device to notify the hostthat a response is available. This response can be retrieved with a subsequent \ref CDC_REQUEST_GET_ENCAPSULATED_RESPONSE request.
CDC_NOTIF_AUX_JACK_HOOK_STATE = 0x08,
CDC_NOTIF_RING_DETECT = 0x09,
CDC_NOTIF_SERIAL_STATE = 0x20,
CDC_NOTIF_CALL_STATE_CHANGE = 0x28,
CDC_NOTIF_LINE_STATE_CHANGE = 0x29,
CDC_NOTIF_CONNECTION_SPEED_CHANGE = 0x2A, ///< This notification allows the device to inform the host-networking driver that a change in either the upstream or the downstream bit rate of the connection has occurred
CDC_NOTIF_MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40,
}cdc_notification_request_t;
//--------------------------------------------------------------------+
// Class Specific Functional Descriptor (Communication Interface)
//--------------------------------------------------------------------+
// Start of all packed definitions for compiler without per-type packed
TU_ATTR_PACKED_BEGIN
TU_ATTR_BIT_FIELD_ORDER_BEGIN
/// Header Functional Descriptor (Communication Interface)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUNC_DESC_
uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal
}cdc_desc_func_header_t;
/// Union Functional Descriptor (Communication Interface)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
uint8_t bControlInterface ; ///< Interface number of Communication Interface
uint8_t bSubordinateInterface ; ///< Array of Interface number of Data Interface
}cdc_desc_func_union_t;
#define cdc_desc_func_union_n_t(no_slave)\
struct TU_ATTR_PACKED { \
uint8_t bLength ;\
uint8_t bDescriptorType ;\
uint8_t bDescriptorSubType ;\
uint8_t bControlInterface ;\
uint8_t bSubordinateInterface[no_slave] ;\
}
/// Country Selection Functional Descriptor (Communication Interface)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
uint8_t iCountryCodeRelDate ; ///< Index of a string giving the release date for the implemented ISO 3166 Country Codes.
uint16_t wCountryCode ; ///< Country code in the format as defined in [ISO3166], release date as specified inoffset 3 for the first supported country.
}cdc_desc_func_country_selection_t;
#define cdc_desc_func_country_selection_n_t(no_country) \
struct TU_ATTR_PACKED { \
uint8_t bLength ;\
uint8_t bDescriptorType ;\
uint8_t bDescriptorSubType ;\
uint8_t iCountryCodeRelDate ;\
uint16_t wCountryCode[no_country] ;\
}
//--------------------------------------------------------------------+
// PUBLIC SWITCHED TELEPHONE NETWORK (PSTN) SUBCLASS
//--------------------------------------------------------------------+
/// \brief Call Management Functional Descriptor
/// \details This functional descriptor describes the processing of calls for the Communications Class interface.
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
struct {
uint8_t handle_call : 1; ///< 0 - Device sends/receives call management information only over the Communications Class interface. 1 - Device can send/receive call management information over a Data Class interface.
uint8_t send_recv_call : 1; ///< 0 - Device does not handle call management itself. 1 - Device handles call management itself.
uint8_t TU_RESERVED : 6;
} bmCapabilities;
uint8_t bDataInterface;
}cdc_desc_func_call_management_t;
typedef struct TU_ATTR_PACKED
{
uint8_t support_comm_request : 1; ///< Device supports the request combination of Set_Comm_Feature, Clear_Comm_Feature, and Get_Comm_Feature.
uint8_t support_line_request : 1; ///< Device supports the request combination of Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and the notification Serial_State.
uint8_t support_send_break : 1; ///< Device supports the request Send_Break
uint8_t support_notification_network_connection : 1; ///< Device supports the notification Network_Connection.
uint8_t TU_RESERVED : 4;
}cdc_acm_capability_t;
TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler");
/// Abstract Control Management Functional Descriptor
/// This functional descriptor describes the commands supported by by the Communications Class interface with SubClass code of \ref CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
cdc_acm_capability_t bmCapabilities ;
}cdc_desc_func_acm_t;
/// \brief Direct Line Management Functional Descriptor
/// \details This functional descriptor describes the commands supported by the Communications Class interface with SubClass code of \ref CDC_FUNC_DESC_DIRECT_LINE_MANAGEMENT
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
struct {
uint8_t require_pulse_setup : 1; ///< Device requires extra Pulse_Setup request during pulse dialing sequence to disengage holding circuit.
uint8_t support_aux_request : 1; ///< Device supports the request combination of Set_Aux_Line_State, Ring_Aux_Jack, and notification Aux_Jack_Hook_State.
uint8_t support_pulse_request : 1; ///< Device supports the request combination of Pulse_Setup, Send_Pulse, and Set_Pulse_Time.
uint8_t TU_RESERVED : 5;
} bmCapabilities;
}cdc_desc_func_direct_line_management_t;
/// \brief Telephone Ringer Functional Descriptor
/// \details The Telephone Ringer functional descriptor describes the ringer capabilities supported by the Communications Class interface,
/// with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
uint8_t bRingerVolSteps ;
uint8_t bNumRingerPatterns ;
}cdc_desc_func_telephone_ringer_t;
/// \brief Telephone Operational Modes Functional Descriptor
/// \details The Telephone Operational Modes functional descriptor describes the operational modes supported by
/// the Communications Class interface, with the SubClass code of \ref CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
struct {
uint8_t simple_mode : 1;
uint8_t standalone_mode : 1;
uint8_t computer_centric_mode : 1;
uint8_t TU_RESERVED : 5;
} bmCapabilities;
}cdc_desc_func_telephone_operational_modes_t;
/// \brief Telephone Call and Line State Reporting Capabilities Descriptor
/// \details The Telephone Call and Line State Reporting Capabilities functional descriptor describes the abilities of a
/// telephone device to report optional call and line states.
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
struct {
uint32_t interrupted_dialtone : 1; ///< 0 : Reports only dialtone (does not differentiate between normal and interrupted dialtone). 1 : Reports interrupted dialtone in addition to normal dialtone
uint32_t ringback_busy_fastbusy : 1; ///< 0 : Reports only dialing state. 1 : Reports ringback, busy, and fast busy states.
uint32_t caller_id : 1; ///< 0 : Does not report caller ID. 1 : Reports caller ID information.
uint32_t incoming_distinctive : 1; ///< 0 : Reports only incoming ringing. 1 : Reports incoming distinctive ringing patterns.
uint32_t dual_tone_multi_freq : 1; ///< 0 : Cannot report dual tone multi-frequency (DTMF) digits input remotely over the telephone line. 1 : Can report DTMF digits input remotely over the telephone line.
uint32_t line_state_change : 1; ///< 0 : Does not support line state change notification. 1 : Does support line state change notification
uint32_t TU_RESERVED : 26;
} bmCapabilities;
}cdc_desc_func_telephone_call_state_reporting_capabilities_t;
// TODO remove
static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc)
{
return p_desc[2];
}
//--------------------------------------------------------------------+
// Requests
//--------------------------------------------------------------------+
typedef struct TU_ATTR_PACKED
{
uint32_t bit_rate;
uint8_t stop_bits; ///< 0: 1 stop bit - 1: 1.5 stop bits - 2: 2 stop bits
uint8_t parity; ///< 0: None - 1: Odd - 2: Even - 3: Mark - 4: Space
uint8_t data_bits; ///< can be 5, 6, 7, 8 or 16
} cdc_line_coding_t;
TU_VERIFY_STATIC(sizeof(cdc_line_coding_t) == 7, "size is not correct");
typedef struct TU_ATTR_PACKED
{
uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR.
uint16_t half_duplex_carrier_control : 1;
uint16_t : 14;
} cdc_line_control_state_t;
TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct");
TU_ATTR_PACKED_END // End of all packed definitions
TU_ATTR_BIT_FIELD_ORDER_END
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View File

@ -0,0 +1,260 @@
/*
* 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.
*/
#ifndef _TUSB_CDC_DEVICE_H_
#define _TUSB_CDC_DEVICE_H_
#include "common/tusb_common.h"
#include "cdc.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#if !defined(CFG_TUD_CDC_EP_BUFSIZE) && defined(CFG_TUD_CDC_EPSIZE)
#warning CFG_TUD_CDC_EPSIZE is renamed to CFG_TUD_CDC_EP_BUFSIZE, please update to use the new name
#define CFG_TUD_CDC_EP_BUFSIZE CFG_TUD_CDC_EPSIZE
#endif
#ifndef CFG_TUD_CDC_EP_BUFSIZE
#define CFG_TUD_CDC_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup CDC_Serial Serial
* @{
* \defgroup CDC_Serial_Device Device
* @{ */
//--------------------------------------------------------------------+
// Application API (Multiple Ports)
// CFG_TUD_CDC > 1
//--------------------------------------------------------------------+
// Check if terminal is connected to this port
bool tud_cdc_n_connected (uint8_t itf);
// Get current line state. Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send)
uint8_t tud_cdc_n_get_line_state (uint8_t itf);
// Get current line encoding: bit rate, stop bits parity etc ..
void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding);
// Set special character that will trigger tud_cdc_rx_wanted_cb() callback on receiving
void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted);
// Get the number of bytes available for reading
uint32_t tud_cdc_n_available (uint8_t itf);
// Read received bytes
uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
// Read a byte, return -1 if there is none
static inline
int32_t tud_cdc_n_read_char (uint8_t itf);
// Clear the received FIFO
void tud_cdc_n_read_flush (uint8_t itf);
// Get a byte from FIFO at the specified position without removing it
bool tud_cdc_n_peek (uint8_t itf, uint8_t* ui8);
// Write bytes to TX FIFO, data may remain in the FIFO for a while
uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
// Write a byte
static inline
uint32_t tud_cdc_n_write_char (uint8_t itf, char ch);
// Write a null-terminated string
static inline
uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str);
// Force sending data if possible, return number of forced bytes
uint32_t tud_cdc_n_write_flush (uint8_t itf);
// Return the number of bytes (characters) available for writing to TX FIFO buffer in a single n_write operation.
uint32_t tud_cdc_n_write_available (uint8_t itf);
// Clear the transmit FIFO
bool tud_cdc_n_write_clear (uint8_t itf);
//--------------------------------------------------------------------+
// Application API (Single Port)
//--------------------------------------------------------------------+
static inline bool tud_cdc_connected (void);
static inline uint8_t tud_cdc_get_line_state (void);
static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding);
static inline void tud_cdc_set_wanted_char (char wanted);
static inline uint32_t tud_cdc_available (void);
static inline int32_t tud_cdc_read_char (void);
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize);
static inline void tud_cdc_read_flush (void);
static inline bool tud_cdc_peek (uint8_t* ui8);
static inline uint32_t tud_cdc_write_char (char ch);
static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize);
static inline uint32_t tud_cdc_write_str (char const* str);
static inline uint32_t tud_cdc_write_flush (void);
static inline uint32_t tud_cdc_write_available (void);
static inline bool tud_cdc_write_clear (void);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when received new data
TU_ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf);
// Invoked when received `wanted_char`
TU_ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char);
// Invoked when space becomes available in TX buffer
TU_ATTR_WEAK void tud_cdc_tx_complete_cb(uint8_t itf);
// Invoked when line state DTR & RTS are changed via SET_CONTROL_LINE_STATE
TU_ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts);
// Invoked when line coding is change via SET_LINE_CODING
TU_ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding);
// Invoked when received send break
TU_ATTR_WEAK void tud_cdc_send_break_cb(uint8_t itf, uint16_t duration_ms);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline int32_t tud_cdc_n_read_char (uint8_t itf)
{
uint8_t ch;
return tud_cdc_n_read(itf, &ch, 1) ? (int32_t) ch : -1;
}
static inline uint32_t tud_cdc_n_write_char(uint8_t itf, char ch)
{
return tud_cdc_n_write(itf, &ch, 1);
}
static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str)
{
return tud_cdc_n_write(itf, str, strlen(str));
}
static inline bool tud_cdc_connected (void)
{
return tud_cdc_n_connected(0);
}
static inline uint8_t tud_cdc_get_line_state (void)
{
return tud_cdc_n_get_line_state(0);
}
static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding)
{
tud_cdc_n_get_line_coding(0, coding);
}
static inline void tud_cdc_set_wanted_char (char wanted)
{
tud_cdc_n_set_wanted_char(0, wanted);
}
static inline uint32_t tud_cdc_available (void)
{
return tud_cdc_n_available(0);
}
static inline int32_t tud_cdc_read_char (void)
{
return tud_cdc_n_read_char(0);
}
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize)
{
return tud_cdc_n_read(0, buffer, bufsize);
}
static inline void tud_cdc_read_flush (void)
{
tud_cdc_n_read_flush(0);
}
static inline bool tud_cdc_peek (uint8_t* ui8)
{
return tud_cdc_n_peek(0, ui8);
}
static inline uint32_t tud_cdc_write_char (char ch)
{
return tud_cdc_n_write_char(0, ch);
}
static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize)
{
return tud_cdc_n_write(0, buffer, bufsize);
}
static inline uint32_t tud_cdc_write_str (char const* str)
{
return tud_cdc_n_write_str(0, str);
}
static inline uint32_t tud_cdc_write_flush (void)
{
return tud_cdc_n_write_flush(0);
}
static inline uint32_t tud_cdc_write_available(void)
{
return tud_cdc_n_write_available(0);
}
static inline bool tud_cdc_write_clear(void)
{
return tud_cdc_n_write_clear(0);
}
/** @} */
/** @} */
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void cdcd_init (void);
void cdcd_reset (uint8_t rhport);
uint16_t cdcd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool cdcd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CDC_DEVICE_H_ */

View File

@ -0,0 +1,134 @@
/*
* 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.
*/
#ifndef _TUSB_CDC_HOST_H_
#define _TUSB_CDC_HOST_H_
#include "cdc.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// CDC APPLICATION PUBLIC API
//--------------------------------------------------------------------+
/** \ingroup ClassDriver_CDC Communication Device Class (CDC)
* \addtogroup CDC_Serial Serial
* @{
* \defgroup CDC_Serial_Host Host
* @{ */
bool tuh_cdc_set_control_line_state(uint8_t dev_addr, bool dtr, bool rts, tuh_control_xfer_cb_t complete_cb);
static inline bool tuh_cdc_connect(uint8_t dev_addr, tuh_control_xfer_cb_t complete_cb)
{
return tuh_cdc_set_control_line_state(dev_addr, true, true, complete_cb);
}
static inline bool tuh_cdc_disconnect(uint8_t dev_addr, tuh_control_xfer_cb_t complete_cb)
{
return tuh_cdc_set_control_line_state(dev_addr, false, false, complete_cb);
}
/** \brief Check if device support CDC Serial interface or not
* \param[in] dev_addr device address
* \retval true if device supports
* \retval false if device does not support or is not mounted
*/
bool tuh_cdc_serial_is_mounted(uint8_t dev_addr);
/** \brief Check if the interface is currently busy or not
* \param[in] dev_addr device address
* \param[in] pipeid value from \ref cdc_pipeid_t to indicate target pipe.
* \retval true if the interface is busy, meaning the stack is still transferring/waiting data from/to device
* \retval false if the interface is not busy, meaning the stack successfully transferred data from/to device
* \note This function is used to check if previous transfer is complete (success or error), so that the next transfer
* can be scheduled. User needs to make sure the corresponding interface is mounted
* (by \ref tuh_cdc_serial_is_mounted) before calling this function.
*/
bool tuh_cdc_is_busy(uint8_t dev_addr, cdc_pipeid_t pipeid);
/** \brief Perform USB OUT transfer to device
* \param[in] dev_addr device address
* \param[in] p_data Buffer containing data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
* \param[in] length Number of bytes to be transferred via USB bus
* \retval TUSB_ERROR_NONE on success
* \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
* \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
* \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
* \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the
* interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION.
*/
bool tuh_cdc_send(uint8_t dev_addr, void const * p_data, uint32_t length, bool is_notify);
/** \brief Perform USB IN transfer to get data from device
* \param[in] dev_addr device address
* \param[in] p_buffer Buffer containing received data. Must be accessible by USB controller (see \ref CFG_TUSB_MEM_SECTION)
* \param[in] length Number of bytes to be transferred via USB bus
* \retval TUSB_ERROR_NONE on success
* \retval TUSB_ERROR_INTERFACE_IS_BUSY if the interface is already transferring data with device
* \retval TUSB_ERROR_DEVICE_NOT_READY if device is not yet configured (by SET CONFIGURED request)
* \retval TUSB_ERROR_INVALID_PARA if input parameters are not correct
* \note This function is non-blocking and returns immediately. The result of USB transfer will be reported by the
* interface's callback function. \a p_data must be declared with \ref CFG_TUSB_MEM_SECTION.
*/
bool tuh_cdc_receive(uint8_t dev_addr, void * p_buffer, uint32_t length, bool is_notify);
//--------------------------------------------------------------------+
// CDC APPLICATION CALLBACKS
//--------------------------------------------------------------------+
/** \brief Callback function that is invoked when an transferring event occurred
* \param[in] dev_addr Address of device
* \param[in] event an value from \ref xfer_result_t
* \param[in] pipe_id value from \ref cdc_pipeid_t indicate the pipe
* \param[in] xferred_bytes Number of bytes transferred via USB bus
* \note event can be one of following
* - XFER_RESULT_SUCCESS : previously scheduled transfer completes successfully.
* - XFER_RESULT_FAILED : previously scheduled transfer encountered a transaction error.
* - XFER_RESULT_STALLED : previously scheduled transfer is stalled by device.
* \note
*/
void tuh_cdc_xfer_isr(uint8_t dev_addr, xfer_result_t event, cdc_pipeid_t pipe_id, uint32_t xferred_bytes);
/// @} // group CDC_Serial_Host
/// @}
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void cdch_init (void);
bool cdch_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len);
bool cdch_set_config (uint8_t dev_addr, uint8_t itf_num);
bool cdch_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void cdch_close (uint8_t dev_addr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CDC_HOST_H_ */

View File

@ -0,0 +1,301 @@
/*
* 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 ClassDriver_CDC Communication Device Class (CDC)
* \defgroup CDC_RNDIS Remote Network Driver Interface Specification (RNDIS)
* @{
* \defgroup CDC_RNDIS_Common Common Definitions
* @{ */
#ifndef _TUSB_CDC_RNDIS_H_
#define _TUSB_CDC_RNDIS_H_
#include "cdc.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __CC_ARM
#pragma diag_suppress 66 // Suppress Keil warnings #66-D: enumeration value is out of "int" range
#endif
/// RNDIS Message Types
typedef enum
{
RNDIS_MSG_PACKET = 0x00000001UL, ///< The host and device use this to send network data to one another.
RNDIS_MSG_INITIALIZE = 0x00000002UL, ///< Sent by the host to initialize the device.
RNDIS_MSG_INITIALIZE_CMPLT = 0x80000002UL, ///< Device response to an initialize message.
RNDIS_MSG_HALT = 0x00000003UL, ///< Sent by the host to halt the device. This does not have a response. It is optional for the device to send this message to the host.
RNDIS_MSG_QUERY = 0x00000004UL, ///< Sent by the host to send a query OID.
RNDIS_MSG_QUERY_CMPLT = 0x80000004UL, ///< Device response to a query OID.
RNDIS_MSG_SET = 0x00000005UL, ///< Sent by the host to send a set OID.
RNDIS_MSG_SET_CMPLT = 0x80000005UL, ///< Device response to a set OID.
RNDIS_MSG_RESET = 0x00000006UL, ///< Sent by the host to perform a soft reset on the device.
RNDIS_MSG_RESET_CMPLT = 0x80000006UL, ///< Device response to reset message.
RNDIS_MSG_INDICATE_STATUS = 0x00000007UL, ///< Sent by the device to indicate its status or an error when an unrecognized message is received.
RNDIS_MSG_KEEP_ALIVE = 0x00000008UL, ///< During idle periods, sent every few seconds by the host to check that the device is still responsive. It is optional for the device to send this message to check if the host is active.
RNDIS_MSG_KEEP_ALIVE_CMPLT = 0x80000008UL ///< The device response to a keepalivemessage. The host can respond with this message to a keepalive message from the device when the device implements the optional KeepAliveTimer.
}rndis_msg_type_t;
/// RNDIS Message Status Values
typedef enum
{
RNDIS_STATUS_SUCCESS = 0x00000000UL, ///< Success
RNDIS_STATUS_FAILURE = 0xC0000001UL, ///< Unspecified error
RNDIS_STATUS_INVALID_DATA = 0xC0010015UL, ///< Invalid data error
RNDIS_STATUS_NOT_SUPPORTED = 0xC00000BBUL, ///< Unsupported request error
RNDIS_STATUS_MEDIA_CONNECT = 0x4001000BUL, ///< Device is connected to a network medium.
RNDIS_STATUS_MEDIA_DISCONNECT = 0x4001000CUL ///< Device is disconnected from the medium.
}rndis_msg_status_t;
#ifdef __CC_ARM
#pragma diag_default 66 // return Keil 66 to normal severity
#endif
//--------------------------------------------------------------------+
// MESSAGE STRUCTURE
//--------------------------------------------------------------------+
//------------- Initialize -------------//
/// \brief Initialize Message
/// \details This message MUST be sent by the host to initialize the device.
typedef struct {
uint32_t type ; ///< Message type, must be \ref RNDIS_MSG_INITIALIZE
uint32_t length ; ///< Message length in bytes, must be 0x18
uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device.
uint32_t major_version ; ///< The major version of the RNDIS Protocol implemented by the host.
uint32_t minor_version ; ///< The minor version of the RNDIS Protocol implemented by the host
uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the host expects to receive from the device.
}rndis_msg_initialize_t;
/// \brief Initialize Complete Message
/// \details This message MUST be sent by the device in response to an initialize message.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_INITIALIZE_CMPLT
uint32_t length ; ///< Message length in bytes, must be 0x30
uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_initialize_t to which this message is a response.
uint32_t status ; ///< The initialization status of the device, has value from \ref rndis_msg_status_t
uint32_t major_version ; ///< the highest-numbered RNDIS Protocol version supported by the device.
uint32_t minor_version ; ///< the highest-numbered RNDIS Protocol version supported by the device.
uint32_t device_flags ; ///< MUST be set to 0x000000010. Other values are reserved for future use.
uint32_t medium ; ///< is 0x00 for RNDIS_MEDIUM_802_3
uint32_t max_packet_per_xfer ; ///< The maximum number of concatenated \ref RNDIS_MSG_PACKET messages that the device can handle in a single bus transfer to it. This value MUST be at least 1.
uint32_t max_xfer_size ; ///< The maximum size, in bytes, of any single bus data transfer that the device expects to receive from the host.
uint32_t packet_alignment_factor ; ///< The byte alignment the device expects for each RNDIS message that is part of a multimessage transfer to it. The value is specified as an exponent of 2; for example, the host uses 2<SUP>{PacketAlignmentFactor}</SUP> as the alignment value.
uint32_t reserved[2] ;
} rndis_msg_initialize_cmplt_t;
//------------- Query -------------//
/// \brief Query Message
/// \details This message MUST be sent by the host to query an OID.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY
uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer
uint32_t request_id ; ///< A 32-bit integer value, generated by the host, used to match the host's sent request to the response from the device.
uint32_t oid ; ///< The integer value of the host operating system-defined identifier, for the parameter of the device being queried for.
uint32_t buffer_length ; ///< The length, in bytes, of the input data required for the OID query. This MUST be set to 0 when there is no input data associated with the OID.
uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the input data for the query is located in the message. This value MUST be set to 0 when there is no input data associated with the OID.
uint32_t reserved ;
uint8_t oid_buffer[] ; ///< Flexible array contains the input data supplied by the host, required for the OID query request processing by the device, as per the host NDIS specification.
} rndis_msg_query_t, rndis_msg_set_t;
TU_VERIFY_STATIC(sizeof(rndis_msg_query_t) == 28, "Make sure flexible array member does not affect layout");
/// \brief Query Complete Message
/// \details This message MUST be sent by the device in response to a query OID message.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_QUERY_CMPLT
uint32_t length ; ///< Message length in bytes, including the header and the \a oid_buffer
uint32_t request_id ; ///< A 32-bit integer value from \a request_id field of the \ref rndis_msg_query_t to which this message is a response.
uint32_t status ; ///< The status of processing for the query request, has value from \ref rndis_msg_status_t.
uint32_t buffer_length ; ///< The length, in bytes, of the data in the response to the query. This MUST be set to 0 when there is no OIDInputBuffer.
uint32_t buffer_offset ; ///< The offset, in bytes, from the beginning of \a request_id field where the response data for the query is located in the message. This MUST be set to 0 when there is no \ref oid_buffer.
uint8_t oid_buffer[] ; ///< Flexible array member contains the response data to the OID query request as specified by the host.
} rndis_msg_query_cmplt_t;
TU_VERIFY_STATIC(sizeof(rndis_msg_query_cmplt_t) == 24, "Make sure flexible array member does not affect layout");
//------------- Reset -------------//
/// \brief Reset Message
/// \details This message MUST be sent by the host to perform a soft reset on the device.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET
uint32_t length ; ///< Message length in bytes, MUST be 0x06
uint32_t reserved ;
} rndis_msg_reset_t;
/// \brief Reset Complete Message
/// \details This message MUST be sent by the device in response to a reset message.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_RESET_CMPLT
uint32_t length ; ///< Message length in bytes, MUST be 0x10
uint32_t status ; ///< The status of processing for the \ref rndis_msg_reset_t, has value from \ref rndis_msg_status_t.
uint32_t addressing_reset ; ///< This field indicates whether the addressing information, which is the multicast address list or packet filter, has been lost during the reset operation. This MUST be set to 0x00000001 if the device requires that the host to resend addressing information or MUST be set to zero otherwise.
} rndis_msg_reset_cmplt_t;
//typedef struct {
// uint32_t type;
// uint32_t length;
// uint32_t status;
// uint32_t buffer_length;
// uint32_t buffer_offset;
// uint32_t diagnostic_status; // optional
// uint32_t diagnostic_error_offset; // optional
// uint32_t status_buffer[0]; // optional
//} rndis_msg_indicate_status_t;
/// \brief Keep Alive Message
/// \details This message MUST be sent by the host to check that device is still responsive. It is optional for the device to send this message to check if the host is active
typedef struct {
uint32_t type ; ///< Message Type
uint32_t length ; ///< Message length in bytes, MUST be 0x10
uint32_t request_id ;
} rndis_msg_keep_alive_t, rndis_msg_halt_t;
/// \brief Set Complete Message
/// \brief This message MUST be sent in response to a the request message
typedef struct {
uint32_t type ; ///< Message Type
uint32_t length ; ///< Message length in bytes, MUST be 0x10
uint32_t request_id ; ///< must be the same as requesting message
uint32_t status ; ///< The status of processing for the request message request by the device to which this message is the response.
} rndis_msg_set_cmplt_t, rndis_msg_keep_alive_cmplt_t;
/// \brief Packet Data Message
/// \brief This message MUST be used by the host and the device to send network data to one another.
typedef struct {
uint32_t type ; ///< Message Type, must be \ref RNDIS_MSG_PACKET
uint32_t length ; ///< Message length in bytes, The total length of this RNDIS message including the header, payload, and padding.
uint32_t data_offset ; ///< Specifies the offset, in bytes, from the start of this \a data_offset field of this message to the start of the data. This MUST be an integer multiple of 4.
uint32_t data_length ; ///< Specifies the number of bytes in the payload of this message.
uint32_t out_of_band_data_offet ; ///< Specifies the offset, in bytes, of the first out-of-band data record from the start of the DataOffset field in this message. MUST be an integer multiple of 4 when out-of-band data is present or set to 0 otherwise. When there are multiple out-ofband data records, each subsequent record MUST immediately follow the previous out-of-band data record.
uint32_t out_of_band_data_length ; ///< Specifies, in bytes, the total length of the out-of-band data.
uint32_t num_out_of_band_data_elements ; ///< Specifies the number of out-of-band records in this message.
uint32_t per_packet_info_offset ; ///< Specifies the offset, in bytes, of the start of per-packet-info data record from the start of the \a data_offset field in this message. MUST be an integer multiple of 4 when per-packet-info data record is present or MUST be set to 0 otherwise. When there are multiple per-packet-info data records, each subsequent record MUST immediately follow the previous record.
uint32_t per_packet_info_length ; ///< Specifies, in bytes, the total length of per-packetinformation contained in this message.
uint32_t reserved[2] ;
uint32_t payload[0] ; ///< Network data contained in this message.
// uint8_t padding[0]
// Additional bytes of zeros added at the end of the message to comply with
// the internal and external padding requirements. Internal padding SHOULD be as per the
// specification of the out-of-band data record and per-packet-info data record. The external
//padding size SHOULD be determined based on the PacketAlignmentFactor field specification
//in REMOTE_NDIS_INITIALIZE_CMPLT message by the device, when multiple
//REMOTE_NDIS_PACKET_MSG messages are bundled together in a single bus-native message.
//In this case, all but the very last REMOTE_NDIS_PACKET_MSG MUST respect the
//PacketAlignmentFactor field.
// rndis_msg_packet_t [0] : (optional) more packet if multiple packet per bus transaction is supported
} rndis_msg_packet_t;
typedef struct {
uint32_t size ; ///< Length, in bytes, of this header and appended data and padding. This value MUST be an integer multiple of 4.
uint32_t type ; ///< MUST be as per host operating system specification.
uint32_t offset ; ///< The byte offset from the beginning of this record to the beginning of data.
uint32_t data[0] ; ///< Flexible array contains data
} rndis_msg_out_of_band_data_t, rndis_msg_per_packet_info_t;
//--------------------------------------------------------------------+
// NDIS Object ID
//--------------------------------------------------------------------+
/// NDIS Object ID
typedef enum
{
//------------- General Required OIDs -------------//
RNDIS_OID_GEN_SUPPORTED_LIST = 0x00010101, ///< List of supported OIDs
RNDIS_OID_GEN_HARDWARE_STATUS = 0x00010102, ///< Hardware status
RNDIS_OID_GEN_MEDIA_SUPPORTED = 0x00010103, ///< Media types supported (encoded)
RNDIS_OID_GEN_MEDIA_IN_USE = 0x00010104, ///< Media types in use (encoded)
RNDIS_OID_GEN_MAXIMUM_LOOKAHEAD = 0x00010105, ///<
RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE = 0x00010106, ///< Maximum frame size in bytes
RNDIS_OID_GEN_LINK_SPEED = 0x00010107, ///< Link speed in units of 100 bps
RNDIS_OID_GEN_TRANSMIT_BUFFER_SPACE = 0x00010108, ///< Transmit buffer space
RNDIS_OID_GEN_RECEIVE_BUFFER_SPACE = 0x00010109, ///< Receive buffer space
RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE = 0x0001010A, ///< Minimum amount of storage, in bytes, that a single packet occupies in the transmit buffer space of the NIC
RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE = 0x0001010B, ///< Amount of storage, in bytes, that a single packet occupies in the receive buffer space of the NIC
RNDIS_OID_GEN_VENDOR_ID = 0x0001010C, ///< Vendor NIC code
RNDIS_OID_GEN_VENDOR_DESCRIPTION = 0x0001010D, ///< Vendor network card description
RNDIS_OID_GEN_CURRENT_PACKET_FILTER = 0x0001010E, ///< Current packet filter (encoded)
RNDIS_OID_GEN_CURRENT_LOOKAHEAD = 0x0001010F, ///< Current lookahead size in bytes
RNDIS_OID_GEN_DRIVER_VERSION = 0x00010110, ///< NDIS version number used by the driver
RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE = 0x00010111, ///< Maximum total packet length in bytes
RNDIS_OID_GEN_PROTOCOL_OPTIONS = 0x00010112, ///< Optional protocol flags (encoded)
RNDIS_OID_GEN_MAC_OPTIONS = 0x00010113, ///< Optional NIC flags (encoded)
RNDIS_OID_GEN_MEDIA_CONNECT_STATUS = 0x00010114, ///< Whether the NIC is connected to the network
RNDIS_OID_GEN_MAXIMUM_SEND_PACKETS = 0x00010115, ///< The maximum number of send packets the driver can accept per call to its MiniportSendPacketsfunction
//------------- General Optional OIDs -------------//
RNDIS_OID_GEN_VENDOR_DRIVER_VERSION = 0x00010116, ///< Vendor-assigned version number of the driver
RNDIS_OID_GEN_SUPPORTED_GUIDS = 0x00010117, ///< The custom GUIDs (Globally Unique Identifier) supported by the miniport driver
RNDIS_OID_GEN_NETWORK_LAYER_ADDRESSES = 0x00010118, ///< List of network-layer addresses associated with the binding between a transport and the driver
RNDIS_OID_GEN_TRANSPORT_HEADER_OFFSET = 0x00010119, ///< Size of packets' additional headers
RNDIS_OID_GEN_MEDIA_CAPABILITIES = 0x00010201, ///<
RNDIS_OID_GEN_PHYSICAL_MEDIUM = 0x00010202, ///< Physical media supported by the miniport driver (encoded)
//------------- 802.3 Objects (Ethernet) -------------//
RNDIS_OID_802_3_PERMANENT_ADDRESS = 0x01010101, ///< Permanent station address
RNDIS_OID_802_3_CURRENT_ADDRESS = 0x01010102, ///< Current station address
RNDIS_OID_802_3_MULTICAST_LIST = 0x01010103, ///< Current multicast address list
RNDIS_OID_802_3_MAXIMUM_LIST_SIZE = 0x01010104, ///< Maximum size of multicast address list
} rndis_oid_type_t;
/// RNDIS Packet Filter Bits \ref RNDIS_OID_GEN_CURRENT_PACKET_FILTER.
typedef enum
{
RNDIS_PACKET_TYPE_DIRECTED = 0x00000001, ///< Directed packets. Directed packets contain a destination address equal to the station address of the NIC.
RNDIS_PACKET_TYPE_MULTICAST = 0x00000002, ///< Multicast address packets sent to addresses in the multicast address list.
RNDIS_PACKET_TYPE_ALL_MULTICAST = 0x00000004, ///< All multicast address packets, not just the ones enumerated in the multicast address list.
RNDIS_PACKET_TYPE_BROADCAST = 0x00000008, ///< Broadcast packets.
RNDIS_PACKET_TYPE_SOURCE_ROUTING = 0x00000010, ///< All source routing packets. If the protocol driver sets this bit, the NDIS library attempts to act as a source routing bridge.
RNDIS_PACKET_TYPE_PROMISCUOUS = 0x00000020, ///< Specifies all packets regardless of whether VLAN filtering is enabled or not and whether the VLAN identifier matches or not.
RNDIS_PACKET_TYPE_SMT = 0x00000040, ///< SMT packets that an FDDI NIC receives.
RNDIS_PACKET_TYPE_ALL_LOCAL = 0x00000080, ///< All packets sent by installed protocols and all packets indicated by the NIC that is identified by a given NdisBindingHandle.
RNDIS_PACKET_TYPE_GROUP = 0x00001000, ///< Packets sent to the current group address.
RNDIS_PACKET_TYPE_ALL_FUNCTIONAL = 0x00002000, ///< All functional address packets, not just the ones in the current functional address.
RNDIS_PACKET_TYPE_FUNCTIONAL = 0x00004000, ///< Functional address packets sent to addresses included in the current functional address.
RNDIS_PACKET_TYPE_MAC_FRAME = 0x00008000, ///< NIC driver frames that a Token Ring NIC receives.
RNDIS_PACKET_TYPE_NO_LOCAL = 0x00010000,
} rndis_packet_filter_type_t;
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CDC_RNDIS_H_ */
/** @} */
/** @} */

View File

@ -0,0 +1,63 @@
/*
* 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 CDC_RNDIS
* \defgroup CDC_RNSID_Host Host
* @{ */
#ifndef _TUSB_CDC_RNDIS_HOST_H_
#define _TUSB_CDC_RNDIS_HOST_H_
#include "common/tusb_common.h"
#include "host/usbh.h"
#include "cdc_rndis.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// INTERNAL RNDIS-CDC Driver API
//--------------------------------------------------------------------+
typedef struct {
OSAL_SEM_DEF(semaphore_notification);
osal_semaphore_handle_t sem_notification_hdl; // used to wait on notification pipe
uint32_t max_xfer_size; // got from device's msg initialize complete
uint8_t mac_address[6];
}rndish_data_t;
void rndish_init(void);
bool rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc);
void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes);
void rndish_close(uint8_t dev_addr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CDC_RNDIS_HOST_H_ */
/** @} */

View File

@ -0,0 +1,119 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 XMOS LIMITED
*
* 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.
*/
#ifndef _TUSB_DFU_H_
#define _TUSB_DFU_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Common Definitions
//--------------------------------------------------------------------+
// DFU Protocol
typedef enum
{
DFU_PROTOCOL_RT = 0x01,
DFU_PROTOCOL_DFU = 0x02,
} dfu_protocol_type_t;
// DFU Descriptor Type
typedef enum
{
DFU_DESC_FUNCTIONAL = 0x21,
} dfu_descriptor_type_t;
// DFU Requests
typedef enum {
DFU_REQUEST_DETACH = 0,
DFU_REQUEST_DNLOAD = 1,
DFU_REQUEST_UPLOAD = 2,
DFU_REQUEST_GETSTATUS = 3,
DFU_REQUEST_CLRSTATUS = 4,
DFU_REQUEST_GETSTATE = 5,
DFU_REQUEST_ABORT = 6,
} dfu_requests_t;
// DFU States
typedef enum {
APP_IDLE = 0,
APP_DETACH = 1,
DFU_IDLE = 2,
DFU_DNLOAD_SYNC = 3,
DFU_DNBUSY = 4,
DFU_DNLOAD_IDLE = 5,
DFU_MANIFEST_SYNC = 6,
DFU_MANIFEST = 7,
DFU_MANIFEST_WAIT_RESET = 8,
DFU_UPLOAD_IDLE = 9,
DFU_ERROR = 10,
} dfu_state_t;
// DFU Status
typedef enum {
DFU_STATUS_OK = 0x00,
DFU_STATUS_ERR_TARGET = 0x01,
DFU_STATUS_ERR_FILE = 0x02,
DFU_STATUS_ERR_WRITE = 0x03,
DFU_STATUS_ERR_ERASE = 0x04,
DFU_STATUS_ERR_CHECK_ERASED = 0x05,
DFU_STATUS_ERR_PROG = 0x06,
DFU_STATUS_ERR_VERIFY = 0x07,
DFU_STATUS_ERR_ADDRESS = 0x08,
DFU_STATUS_ERR_NOTDONE = 0x09,
DFU_STATUS_ERR_FIRMWARE = 0x0A,
DFU_STATUS_ERR_VENDOR = 0x0B,
DFU_STATUS_ERR_USBR = 0x0C,
DFU_STATUS_ERR_POR = 0x0D,
DFU_STATUS_ERR_UNKNOWN = 0x0E,
DFU_STATUS_ERR_STALLEDPKT = 0x0F,
} dfu_status_t;
#define DFU_ATTR_CAN_DOWNLOAD (1u << 0)
#define DFU_ATTR_CAN_UPLOAD (1u << 1)
#define DFU_ATTR_MANIFESTATION_TOLERANT (1u << 2)
#define DFU_ATTR_WILL_DETACH (1u << 3)
// DFU Status Request Payload
typedef struct TU_ATTR_PACKED
{
uint8_t bStatus;
uint8_t bwPollTimeout[3];
uint8_t bState;
uint8_t iString;
} dfu_status_response_t;
TU_VERIFY_STATIC( sizeof(dfu_status_response_t) == 6, "size is not correct");
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DFU_H_ */

View File

@ -0,0 +1,98 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 XMOS LIMITED
*
* 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.
*/
#ifndef _TUSB_DFU_DEVICE_H_
#define _TUSB_DFU_DEVICE_H_
#include "dfu.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Default Configure & Validation
//--------------------------------------------------------------------+
#if !defined(CFG_TUD_DFU_XFER_BUFSIZE)
#error "CFG_TUD_DFU_XFER_BUFSIZE must be defined, it has to be set to the buffer size used in TUD_DFU_DESCRIPTOR"
#endif
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Must be called when the application is done with flashing started by
// tud_dfu_download_cb() and tud_dfu_manifest_cb().
// status is DFU_STATUS_OK if successful, any other error status will cause state to enter dfuError
void tud_dfu_finish_flashing(uint8_t status);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Note: alt is used as the partition number, in order to support multiple partitions like FLASH, EEPROM, etc.
// Invoked right before tud_dfu_download_cb() (state=DFU_DNBUSY) or tud_dfu_manifest_cb() (state=DFU_MANIFEST)
// Application return timeout in milliseconds (bwPollTimeout) for the next download/manifest operation.
// During this period, USB host won't try to communicate with us.
uint32_t tud_dfu_get_timeout_cb(uint8_t alt, uint8_t state);
// Invoked when received DFU_DNLOAD (wLength>0) following by DFU_GETSTATUS (state=DFU_DNBUSY) requests
// This callback could be returned before flashing op is complete (async).
// Once finished flashing, application must call tud_dfu_finish_flashing()
void tud_dfu_download_cb (uint8_t alt, uint16_t block_num, uint8_t const *data, uint16_t length);
// Invoked when download process is complete, received DFU_DNLOAD (wLength=0) following by DFU_GETSTATUS (state=Manifest)
// Application can do checksum, or actual flashing if buffered entire image previously.
// Once finished flashing, application must call tud_dfu_finish_flashing()
void tud_dfu_manifest_cb(uint8_t alt);
// Invoked when received DFU_UPLOAD request
// Application must populate data with up to length bytes and
// Return the number of written bytes
TU_ATTR_WEAK uint16_t tud_dfu_upload_cb(uint8_t alt, uint16_t block_num, uint8_t* data, uint16_t length);
// Invoked when a DFU_DETACH request is received
TU_ATTR_WEAK void tud_dfu_detach_cb(void);
// Invoked when the Host has terminated a download or upload transfer
TU_ATTR_WEAK void tud_dfu_abort_cb(uint8_t alt);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void dfu_moded_init(void);
void dfu_moded_reset(uint8_t rhport);
uint16_t dfu_moded_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool dfu_moded_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DFU_MODE_DEVICE_H_ */

View File

@ -0,0 +1,54 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Sylvain Munaut <tnt@246tNt.com>
*
* 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.
*/
#ifndef _TUSB_DFU_RT_DEVICE_H_
#define _TUSB_DFU_RT_DEVICE_H_
#include "dfu.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when a DFU_DETACH request is received and bitWillDetach is set
void tud_dfu_runtime_reboot_to_dfu_cb(void);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void dfu_rtd_init(void);
void dfu_rtd_reset(uint8_t rhport);
uint16_t dfu_rtd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool dfu_rtd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DFU_RT_DEVICE_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,393 @@
/*
* 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.
*/
#ifndef _TUSB_HID_DEVICE_H_
#define _TUSB_HID_DEVICE_H_
#include "hid.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Default Configure & Validation
//--------------------------------------------------------------------+
#if !defined(CFG_TUD_HID_EP_BUFSIZE) & defined(CFG_TUD_HID_BUFSIZE)
// TODO warn user to use new name later on
// #warning CFG_TUD_HID_BUFSIZE is renamed to CFG_TUD_HID_EP_BUFSIZE, please update to use the new name
#define CFG_TUD_HID_EP_BUFSIZE CFG_TUD_HID_BUFSIZE
#endif
#ifndef CFG_TUD_HID_EP_BUFSIZE
#define CFG_TUD_HID_EP_BUFSIZE 64
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Instances)
// CFG_TUD_HID > 1
//--------------------------------------------------------------------+
// Check if the interface is ready to use
bool tud_hid_n_ready(uint8_t instance);
// Get interface supported protocol (bInterfaceProtocol) check out hid_interface_protocol_enum_t for possible values
uint8_t tud_hid_n_interface_protocol(uint8_t instance);
// Get current active protocol: HID_PROTOCOL_BOOT (0) or HID_PROTOCOL_REPORT (1)
uint8_t tud_hid_n_get_protocol(uint8_t instance);
// Send report to host
bool tud_hid_n_report(uint8_t instance, uint8_t report_id, void const* report, uint8_t len);
// KEYBOARD: convenient helper to send keyboard report if application
// use template layout report as defined by hid_keyboard_report_t
bool tud_hid_n_keyboard_report(uint8_t instance, uint8_t report_id, uint8_t modifier, uint8_t keycode[6]);
// MOUSE: convenient helper to send mouse report if application
// use template layout report as defined by hid_mouse_report_t
bool tud_hid_n_mouse_report(uint8_t instance, uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal);
// Gamepad: convenient helper to send gamepad report if application
// use template layout report TUD_HID_REPORT_DESC_GAMEPAD
bool tud_hid_n_gamepad_report(uint8_t instance, uint8_t report_id, int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint32_t buttons);
//--------------------------------------------------------------------+
// Application API (Single Port)
//--------------------------------------------------------------------+
static inline bool tud_hid_ready(void);
static inline uint8_t tud_hid_interface_protocol(void);
static inline uint8_t tud_hid_get_protocol(void);
static inline bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len);
static inline bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6]);
static inline bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal);
static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint32_t buttons);
//--------------------------------------------------------------------+
// Callbacks (Weak is optional)
//--------------------------------------------------------------------+
// Invoked when received GET HID REPORT DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
uint8_t const * tud_hid_descriptor_report_cb(uint8_t instance);
// Invoked when received GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request
uint16_t tud_hid_get_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen);
// Invoked when received SET_REPORT control request or
// received data on OUT endpoint ( Report ID = 0, Type = 0 )
void tud_hid_set_report_cb(uint8_t instance, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize);
// Invoked when received SET_PROTOCOL request
// protocol is either HID_PROTOCOL_BOOT (0) or HID_PROTOCOL_REPORT (1)
TU_ATTR_WEAK void tud_hid_set_protocol_cb(uint8_t instance, uint8_t protocol);
// Invoked when received SET_IDLE request. return false will stall the request
// - Idle Rate = 0 : only send report if there is changes, i.e skip duplication
// - Idle Rate > 0 : skip duplication, but send at least 1 report every idle rate (in unit of 4 ms).
TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t instance, uint8_t idle_rate);
// Invoked when sent REPORT successfully to host
// Application can use this to send the next report
// Note: For composite reports, report[0] is report ID
TU_ATTR_WEAK void tud_hid_report_complete_cb(uint8_t instance, uint8_t const* report, uint8_t len);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline bool tud_hid_ready(void)
{
return tud_hid_n_ready(0);
}
static inline uint8_t tud_hid_interface_protocol(void)
{
return tud_hid_n_interface_protocol(0);
}
static inline uint8_t tud_hid_get_protocol(void)
{
return tud_hid_n_get_protocol(0);
}
static inline bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len)
{
return tud_hid_n_report(0, report_id, report, len);
}
static inline bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6])
{
return tud_hid_n_keyboard_report(0, report_id, modifier, keycode);
}
static inline bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t vertical, int8_t horizontal)
{
return tud_hid_n_mouse_report(0, report_id, buttons, x, y, vertical, horizontal);
}
static inline bool tud_hid_gamepad_report(uint8_t report_id, int8_t x, int8_t y, int8_t z, int8_t rz, int8_t rx, int8_t ry, uint8_t hat, uint32_t buttons)
{
return tud_hid_n_gamepad_report(0, report_id, x, y, z, rz, rx, ry, hat, buttons);
}
/* --------------------------------------------------------------------+
* HID Report Descriptor Template
*
* Convenient for declaring popular HID device (keyboard, mouse, consumer,
* gamepad etc...). Templates take "HID_REPORT_ID(n)" as input, leave
* empty if multiple reports is not used
*
* - Only 1 report: no parameter
* uint8_t const report_desc[] = { TUD_HID_REPORT_DESC_KEYBOARD() };
*
* - Multiple Reports: "HID_REPORT_ID(ID)" must be passed to template
* uint8_t const report_desc[] =
* {
* TUD_HID_REPORT_DESC_KEYBOARD( HID_REPORT_ID(1) ) ,
* TUD_HID_REPORT_DESC_MOUSE ( HID_REPORT_ID(2) )
* };
*--------------------------------------------------------------------*/
// Keyboard Report Descriptor Template
#define TUD_HID_REPORT_DESC_KEYBOARD(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_KEYBOARD ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */\
__VA_ARGS__ \
/* 8 bits Modifier Keys (Shfit, Control, Alt) */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
HID_USAGE_MIN ( 224 ) ,\
HID_USAGE_MAX ( 231 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
HID_REPORT_COUNT ( 8 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* 8 bit reserved */ \
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_CONSTANT ) ,\
/* Output 5-bit LED Indicator Kana | Compose | ScrollLock | CapsLock | NumLock */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_LED ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 5 ) ,\
HID_REPORT_COUNT ( 5 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* led padding */ \
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 3 ) ,\
HID_OUTPUT ( HID_CONSTANT ) ,\
/* 6-byte Keycodes */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
HID_USAGE_MIN ( 0 ) ,\
HID_USAGE_MAX_N ( 255, 2 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX_N( 255, 2 ) ,\
HID_REPORT_COUNT ( 6 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
// Mouse Report Descriptor Template
#define TUD_HID_REPORT_DESC_MOUSE(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_MOUSE ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */\
__VA_ARGS__ \
HID_USAGE ( HID_USAGE_DESKTOP_POINTER ) ,\
HID_COLLECTION ( HID_COLLECTION_PHYSICAL ) ,\
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 5 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
/* Left, Right, Middle, Backward, Forward buttons */ \
HID_REPORT_COUNT( 5 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* 3 bit padding */ \
HID_REPORT_COUNT( 1 ) ,\
HID_REPORT_SIZE ( 3 ) ,\
HID_INPUT ( HID_CONSTANT ) ,\
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
/* X, Y position [-127, 127] */ \
HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
HID_LOGICAL_MIN ( 0x81 ) ,\
HID_LOGICAL_MAX ( 0x7f ) ,\
HID_REPORT_COUNT( 2 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\
/* Verital wheel scroll [-127, 127] */ \
HID_USAGE ( HID_USAGE_DESKTOP_WHEEL ) ,\
HID_LOGICAL_MIN ( 0x81 ) ,\
HID_LOGICAL_MAX ( 0x7f ) ,\
HID_REPORT_COUNT( 1 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ) ,\
HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ), \
/* Horizontal wheel scroll [-127, 127] */ \
HID_USAGE_N ( HID_USAGE_CONSUMER_AC_PAN, 2 ), \
HID_LOGICAL_MIN ( 0x81 ), \
HID_LOGICAL_MAX ( 0x7f ), \
HID_REPORT_COUNT( 1 ), \
HID_REPORT_SIZE ( 8 ), \
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_RELATIVE ), \
HID_COLLECTION_END , \
HID_COLLECTION_END \
// Consumer Control Report Descriptor Template
#define TUD_HID_REPORT_DESC_CONSUMER(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_CONSUMER ) ,\
HID_USAGE ( HID_USAGE_CONSUMER_CONTROL ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */\
__VA_ARGS__ \
HID_LOGICAL_MIN ( 0x00 ) ,\
HID_LOGICAL_MAX_N( 0x03FF, 2 ) ,\
HID_USAGE_MIN ( 0x00 ) ,\
HID_USAGE_MAX_N ( 0x03FF, 2 ) ,\
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 16 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
/* System Control Report Descriptor Template
* 0x00 - do nothing
* 0x01 - Power Off
* 0x02 - Standby
* 0x03 - Wake Host
*/
#define TUD_HID_REPORT_DESC_SYSTEM_CONTROL(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_CONTROL ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */\
__VA_ARGS__ \
/* 2 bit system power control */ \
HID_LOGICAL_MIN ( 1 ) ,\
HID_LOGICAL_MAX ( 3 ) ,\
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 2 ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_SLEEP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_WAKE_UP ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
/* 6 bit padding */ \
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 6 ) ,\
HID_INPUT ( HID_CONSTANT ) ,\
HID_COLLECTION_END \
// Gamepad Report Descriptor Template
// with 32 buttons, 2 joysticks and 1 hat/dpad with following layout
// | X | Y | Z | Rz | Rx | Ry (1 byte each) | hat/DPAD (1 byte) | Button Map (4 bytes) |
#define TUD_HID_REPORT_DESC_GAMEPAD(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */\
__VA_ARGS__ \
/* 8 bit X, Y, Z, Rz, Rx, Ry (min -127, max 127 ) */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_Z ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_RZ ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_RX ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_RY ) ,\
HID_LOGICAL_MIN ( 0x81 ) ,\
HID_LOGICAL_MAX ( 0x7f ) ,\
HID_REPORT_COUNT ( 6 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* 8 bit DPad/Hat Button Map */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_HAT_SWITCH ) ,\
HID_LOGICAL_MIN ( 1 ) ,\
HID_LOGICAL_MAX ( 8 ) ,\
HID_PHYSICAL_MIN ( 0 ) ,\
HID_PHYSICAL_MAX_N ( 315, 2 ) ,\
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* 32 bit Button Map */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 32 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
HID_REPORT_COUNT ( 32 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
// HID Generic Input & Output
// - 1st parameter is report size (mandatory)
// - 2nd parameter is report id HID_REPORT_ID(n) (optional)
#define TUD_HID_REPORT_DESC_GENERIC_INOUT(report_size, ...) \
HID_USAGE_PAGE_N ( HID_USAGE_PAGE_VENDOR, 2 ),\
HID_USAGE ( 0x01 ),\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ),\
/* Report ID if any */\
__VA_ARGS__ \
/* Input */ \
HID_USAGE ( 0x02 ),\
HID_LOGICAL_MIN ( 0x00 ),\
HID_LOGICAL_MAX_N ( 0xff, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT( report_size ),\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
/* Output */ \
HID_USAGE ( 0x03 ),\
HID_LOGICAL_MIN ( 0x00 ),\
HID_LOGICAL_MAX_N ( 0xff, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT( report_size ),\
HID_OUTPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END \
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void hidd_init (void);
void hidd_reset (uint8_t rhport);
uint16_t hidd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool hidd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool hidd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HID_DEVICE_H_ */

View File

@ -0,0 +1,152 @@
/*
* 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.
*/
#ifndef _TUSB_HID_HOST_H_
#define _TUSB_HID_HOST_H_
#include "hid.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
// TODO Highspeed interrupt can be up to 512 bytes
#ifndef CFG_TUH_HID_EPIN_BUFSIZE
#define CFG_TUH_HID_EPIN_BUFSIZE 64
#endif
#ifndef CFG_TUH_HID_EPOUT_BUFSIZE
#define CFG_TUH_HID_EPOUT_BUFSIZE 64
#endif
typedef struct
{
uint8_t report_id;
uint8_t usage;
uint16_t usage_page;
// TODO still use the endpoint size for now
// uint8_t in_len; // length of IN report
// uint8_t out_len; // length of OUT report
} tuh_hid_report_info_t;
//--------------------------------------------------------------------+
// Interface API
//--------------------------------------------------------------------+
// Get the number of HID instances
uint8_t tuh_hid_instance_count(uint8_t dev_addr);
// Check if HID instance is mounted
bool tuh_hid_mounted(uint8_t dev_addr, uint8_t instance);
// Get interface supported protocol (bInterfaceProtocol) check out hid_interface_protocol_enum_t for possible values
uint8_t tuh_hid_interface_protocol(uint8_t dev_addr, uint8_t instance);
// Parse report descriptor into array of report_info struct and return number of reports.
// For complicated report, application should write its own parser.
uint8_t tuh_hid_parse_report_descriptor(tuh_hid_report_info_t* reports_info_arr, uint8_t arr_count, uint8_t const* desc_report, uint16_t desc_len) TU_ATTR_UNUSED;
//--------------------------------------------------------------------+
// Control Endpoint API
//--------------------------------------------------------------------+
// Get current protocol: HID_PROTOCOL_BOOT (0) or HID_PROTOCOL_REPORT (1)
// Note: Device will be initialized in Boot protocol for simplicity.
// Application can use set_protocol() to switch back to Report protocol.
uint8_t tuh_hid_get_protocol(uint8_t dev_addr, uint8_t instance);
// Set protocol to HID_PROTOCOL_BOOT (0) or HID_PROTOCOL_REPORT (1)
// This function is only supported by Boot interface (tuh_n_hid_interface_protocol() != NONE)
bool tuh_hid_set_protocol(uint8_t dev_addr, uint8_t instance, uint8_t protocol);
// Set Report using control endpoint
// report_type is either Intput, Output or Feature, (value from hid_report_type_t)
bool tuh_hid_set_report(uint8_t dev_addr, uint8_t instance, uint8_t report_id, uint8_t report_type, void* report, uint16_t len);
//--------------------------------------------------------------------+
// Interrupt Endpoint API
//--------------------------------------------------------------------+
// Check if the interface is ready to use
//bool tuh_n_hid_n_ready(uint8_t dev_addr, uint8_t instance);
// Try to receive next report on Interrupt Endpoint. Immediately return
// - true If succeeded, tuh_hid_report_received_cb() callback will be invoked when report is available
// - false if failed to queue the transfer e.g endpoint is busy
bool tuh_hid_receive_report(uint8_t dev_addr, uint8_t instance);
// Send report using interrupt endpoint
// If report_id > 0 (composite), it will be sent as 1st byte, then report contents. Otherwise only report content is sent.
//void tuh_hid_send_report(uint8_t dev_addr, uint8_t instance, uint8_t report_id, uint8_t const* report, uint16_t len);
//--------------------------------------------------------------------+
// Callbacks (Weak is optional)
//--------------------------------------------------------------------+
// Invoked when device with hid interface is mounted
// Report descriptor is also available for use. tuh_hid_parse_report_descriptor()
// can be used to parse common/simple enough descriptor.
// Note: if report descriptor length > CFG_TUH_ENUMERATION_BUFSIZE, it will be skipped
// therefore report_desc = NULL, desc_len = 0
void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report_desc, uint16_t desc_len);
// Invoked when device with hid interface is un-mounted
TU_ATTR_WEAK void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance);
// Invoked when received report from device via interrupt endpoint
// Note: if there is report ID (composite), it is 1st byte of report
void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len);
// Invoked when sent report to device successfully via interrupt endpoint
TU_ATTR_WEAK void tuh_hid_report_sent_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len);
// Invoked when Sent Report to device via either control endpoint
// len = 0 indicate there is error in the transfer e.g stalled response
TU_ATTR_WEAK void tuh_hid_set_report_complete_cb(uint8_t dev_addr, uint8_t instance, uint8_t report_id, uint8_t report_type, uint16_t len);
// Invoked when Set Protocol request is complete
TU_ATTR_WEAK void tuh_hid_set_protocol_complete_cb(uint8_t dev_addr, uint8_t instance, uint8_t protocol);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void hidh_init (void);
bool hidh_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len);
bool hidh_set_config (uint8_t dev_addr, uint8_t itf_num);
bool hidh_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
void hidh_close (uint8_t dev_addr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HID_HOST_H_ */

View File

@ -0,0 +1,212 @@
/*
* 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_class
* \defgroup ClassDriver_CDC Communication Device Class (CDC)
* Currently only Abstract Control Model subclass is supported
* @{ */
#ifndef _TUSB_MIDI_H__
#define _TUSB_MIDI_H__
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Specific Descriptor
//--------------------------------------------------------------------+
typedef enum
{
MIDI_CS_INTERFACE_HEADER = 0x01,
MIDI_CS_INTERFACE_IN_JACK = 0x02,
MIDI_CS_INTERFACE_OUT_JACK = 0x03,
MIDI_CS_INTERFACE_ELEMENT = 0x04,
} midi_cs_interface_subtype_t;
typedef enum
{
MIDI_CS_ENDPOINT_GENERAL = 0x01
} midi_cs_endpoint_subtype_t;
typedef enum
{
MIDI_JACK_EMBEDDED = 0x01,
MIDI_JACK_EXTERNAL = 0x02
} midi_jack_type_t;
typedef enum
{
MIDI_CIN_MISC = 0,
MIDI_CIN_CABLE_EVENT = 1,
MIDI_CIN_SYSCOM_2BYTE = 2, // 2 byte system common message e.g MTC, SongSelect
MIDI_CIN_SYSCOM_3BYTE = 3, // 3 byte system common message e.g SPP
MIDI_CIN_SYSEX_START = 4, // SysEx starts or continue
MIDI_CIN_SYSEX_END_1BYTE = 5, // SysEx ends with 1 data, or 1 byte system common message
MIDI_CIN_SYSEX_END_2BYTE = 6, // SysEx ends with 2 data
MIDI_CIN_SYSEX_END_3BYTE = 7, // SysEx ends with 3 data
MIDI_CIN_NOTE_ON = 8,
MIDI_CIN_NOTE_OFF = 9,
MIDI_CIN_POLY_KEYPRESS = 10,
MIDI_CIN_CONTROL_CHANGE = 11,
MIDI_CIN_PROGRAM_CHANGE = 12,
MIDI_CIN_CHANNEL_PRESSURE = 13,
MIDI_CIN_PITCH_BEND_CHANGE = 14,
MIDI_CIN_1BYTE_DATA = 15
} midi_code_index_number_t;
// MIDI 1.0 status byte
enum
{
//------------- System Exclusive -------------//
MIDI_STATUS_SYSEX_START = 0xF0,
MIDI_STATUS_SYSEX_END = 0xF7,
//------------- System Common -------------//
MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME = 0xF1,
MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER = 0xF2,
MIDI_STATUS_SYSCOM_SONG_SELECT = 0xF3,
// F4, F5 is undefined
MIDI_STATUS_SYSCOM_TUNE_REQUEST = 0xF6,
//------------- System RealTime -------------//
MIDI_STATUS_SYSREAL_TIMING_CLOCK = 0xF8,
// 0xF9 is undefined
MIDI_STATUS_SYSREAL_START = 0xFA,
MIDI_STATUS_SYSREAL_CONTINUE = 0xFB,
MIDI_STATUS_SYSREAL_STOP = 0xFC,
// 0xFD is undefined
MIDI_STATUS_SYSREAL_ACTIVE_SENSING = 0xFE,
MIDI_STATUS_SYSREAL_SYSTEM_RESET = 0xFF,
};
/// MIDI Interface Header Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal
uint16_t wTotalLength ;
} midi_desc_header_t;
/// MIDI In Jack Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bJackType ; ///< Embedded or External
uint8_t bJackID ; ///< Unique ID for MIDI IN Jack
uint8_t iJack ; ///< string descriptor
} midi_desc_in_jack_t;
/// MIDI Out Jack Descriptor with single pin
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bJackType ; ///< Embedded or External
uint8_t bJackID ; ///< Unique ID for MIDI IN Jack
uint8_t bNrInputPins;
uint8_t baSourceID;
uint8_t baSourcePin;
uint8_t iJack ; ///< string descriptor
} midi_desc_out_jack_t ;
/// MIDI Out Jack Descriptor with multiple pins
#define midi_desc_out_jack_n_t(input_num) \
struct TU_ATTR_PACKED { \
uint8_t bLength ; \
uint8_t bDescriptorType ; \
uint8_t bDescriptorSubType ; \
uint8_t bJackType ; \
uint8_t bJackID ; \
uint8_t bNrInputPins ; \
struct TU_ATTR_PACKED { \
uint8_t baSourceID; \
uint8_t baSourcePin; \
} pins[input_num]; \
uint8_t iJack ; \
}
/// MIDI Element Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bElementID;
uint8_t bNrInputPins;
uint8_t baSourceID;
uint8_t baSourcePin;
uint8_t bNrOutputPins;
uint8_t bInTerminalLink;
uint8_t bOutTerminalLink;
uint8_t bElCapsSize;
uint16_t bmElementCaps;
uint8_t iElement;
} midi_desc_element_t;
/// MIDI Element Descriptor with multiple pins
#define midi_desc_element_n_t(input_num) \
struct TU_ATTR_PACKED { \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint8_t bDescriptorSubType; \
uint8_t bElementID; \
uint8_t bNrInputPins; \
struct TU_ATTR_PACKED { \
uint8_t baSourceID; \
uint8_t baSourcePin; \
} pins[input_num]; \
uint8_t bNrOutputPins; \
uint8_t bInTerminalLink; \
uint8_t bOutTerminalLink; \
uint8_t bElCapsSize; \
uint16_t bmElementCaps; \
uint8_t iElement; \
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View File

@ -0,0 +1,173 @@
/*
* 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.
*/
#ifndef _TUSB_MIDI_DEVICE_H_
#define _TUSB_MIDI_DEVICE_H_
#include "class/audio/audio.h"
#include "midi.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#if !defined(CFG_TUD_MIDI_EP_BUFSIZE) && defined(CFG_TUD_MIDI_EPSIZE)
#warning CFG_TUD_MIDI_EPSIZE is renamed to CFG_TUD_MIDI_EP_BUFSIZE, please update to use the new name
#define CFG_TUD_MIDI_EP_BUFSIZE CFG_TUD_MIDI_EPSIZE
#endif
#ifndef CFG_TUD_MIDI_EP_BUFSIZE
#define CFG_TUD_MIDI_EP_BUFSIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup MIDI_Serial Serial
* @{
* \defgroup MIDI_Serial_Device Device
* @{ */
//--------------------------------------------------------------------+
// Application API (Multiple Interfaces)
// CFG_TUD_MIDI > 1
//--------------------------------------------------------------------+
// Check if midi interface is mounted
bool tud_midi_n_mounted (uint8_t itf);
// Get the number of bytes available for reading
uint32_t tud_midi_n_available (uint8_t itf, uint8_t cable_num);
// Read byte stream (legacy)
uint32_t tud_midi_n_stream_read (uint8_t itf, uint8_t cable_num, void* buffer, uint32_t bufsize);
// Write byte Stream (legacy)
uint32_t tud_midi_n_stream_write (uint8_t itf, uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize);
// Read event packet (4 bytes)
bool tud_midi_n_packet_read (uint8_t itf, uint8_t packet[4]);
// Write event packet (4 bytes)
bool tud_midi_n_packet_write (uint8_t itf, uint8_t const packet[4]);
//--------------------------------------------------------------------+
// Application API (Single Interface)
//--------------------------------------------------------------------+
static inline bool tud_midi_mounted (void);
static inline uint32_t tud_midi_available (void);
static inline uint32_t tud_midi_stream_read (void* buffer, uint32_t bufsize);
static inline uint32_t tud_midi_stream_write (uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize);
static inline bool tud_midi_packet_read (uint8_t packet[4]);
static inline bool tud_midi_packet_write (uint8_t const packet[4]);
//------------- Deprecated API name -------------//
// TODO remove after 0.10.0 release
TU_ATTR_DEPRECATED("tud_midi_read() is renamed to tud_midi_stream_read()")
static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize)
{
return tud_midi_stream_read(buffer, bufsize);
}
TU_ATTR_DEPRECATED("tud_midi_write() is renamed to tud_midi_stream_write()")
static inline uint32_t tud_midi_write(uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize)
{
return tud_midi_stream_write(cable_num, buffer, bufsize);
}
TU_ATTR_DEPRECATED("tud_midi_send() is renamed to tud_midi_packet_write()")
static inline bool tud_midi_send(uint8_t packet[4])
{
return tud_midi_packet_write(packet);
}
TU_ATTR_DEPRECATED("tud_midi_receive() is renamed to tud_midi_packet_read()")
static inline bool tud_midi_receive(uint8_t packet[4])
{
return tud_midi_packet_read(packet);
}
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
TU_ATTR_WEAK void tud_midi_rx_cb(uint8_t itf);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline bool tud_midi_mounted (void)
{
return tud_midi_n_mounted(0);
}
static inline uint32_t tud_midi_available (void)
{
return tud_midi_n_available(0, 0);
}
static inline uint32_t tud_midi_stream_read (void* buffer, uint32_t bufsize)
{
return tud_midi_n_stream_read(0, 0, buffer, bufsize);
}
static inline uint32_t tud_midi_stream_write (uint8_t cable_num, uint8_t const* buffer, uint32_t bufsize)
{
return tud_midi_n_stream_write(0, cable_num, buffer, bufsize);
}
static inline bool tud_midi_packet_read (uint8_t packet[4])
{
return tud_midi_n_packet_read(0, packet);
}
static inline bool tud_midi_packet_write (uint8_t const packet[4])
{
return tud_midi_n_packet_write(0, packet);
}
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void midid_init (void);
void midid_reset (uint8_t rhport);
uint16_t midid_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool midid_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool midid_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MIDI_DEVICE_H_ */
/** @} */
/** @} */

View File

@ -0,0 +1,382 @@
/*
* 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.
*/
#ifndef _TUSB_MSC_H_
#define _TUSB_MSC_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Mass Storage Class Constant
//--------------------------------------------------------------------+
/// MassStorage Subclass
typedef enum
{
MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D
MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device
MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device
MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device
MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device
MSC_SUBCLASS_SCSI ///< SCSI transparent command set
}msc_subclass_type_t;
enum {
MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian)
MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian)
};
/// \brief MassStorage Protocol.
/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy
typedef enum
{
MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt)
MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt)
MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport
}msc_protocol_type_t;
/// MassStorage Class-Specific Control Request
typedef enum
{
MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15
MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host.
}msc_request_type_t;
/// \brief Command Block Status Values
/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed
/// successfully. A non-zero value shall indicate a failure during command execution according to the following
typedef enum
{
MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED
MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED
MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR
}msc_csw_status_t;
/// Command Block Wrapper
typedef struct TU_ATTR_PACKED
{
uint32_t signature; ///< Signature that helps identify this data packet as a CBW. The signature field shall contain the value 43425355h (little endian), indicating a CBW.
uint32_t tag; ///< Tag sent by the host. The device shall echo the contents of this field back to the host in the dCSWTagfield of the associated CSW. The dCSWTagpositively associates a CSW with the corresponding CBW.
uint32_t total_bytes; ///< The number of bytes of data that the host expects to transfer on the Bulk-In or Bulk-Out endpoint (as indicated by the Direction bit) during the execution of this command. If this field is zero, the device and the host shall transfer no data between the CBW and the associated CSW, and the device shall ignore the value of the Direction bit in bmCBWFlags.
uint8_t dir; ///< Bit 7 of this field define transfer direction \n - 0 : Data-Out from host to the device. \n - 1 : Data-In from the device to the host.
uint8_t lun; ///< The device Logical Unit Number (LUN) to which the command block is being sent. For devices that support multiple LUNs, the host shall place into this field the LUN to which this command block is addressed. Otherwise, the host shall set this field to zero.
uint8_t cmd_len; ///< The valid length of the CBWCBin bytes. This defines the valid length of the command block. The only legal values are 1 through 16
uint8_t command[16]; ///< The command block to be executed by the device. The device shall interpret the first cmd_len bytes in this field as a command block
}msc_cbw_t;
TU_VERIFY_STATIC(sizeof(msc_cbw_t) == 31, "size is not correct");
/// Command Status Wrapper
typedef struct TU_ATTR_PACKED
{
uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW.
uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW.
uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device
uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t
}msc_csw_t;
TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct");
//--------------------------------------------------------------------+
// SCSI Constant
//--------------------------------------------------------------------+
/// SCSI Command Operation Code
typedef enum
{
SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation.
SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device.
SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters.
SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command.
SCSI_CMD_START_STOP_UNIT = 0x1B,
SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device.
SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device.
SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed
SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer.
SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them.
}scsi_cmd_type_t;
/// SCSI Sense Key
typedef enum
{
SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command
SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive.
SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed.
SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition.
SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test.
SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters
SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset.
SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed.
SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key.
SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command.
SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison.
SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium.
SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium.
}scsi_sense_key_type_t;
//--------------------------------------------------------------------+
// SCSI Primary Command (SPC-4)
//--------------------------------------------------------------------+
/// SCSI Test Unit Ready Command
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_TEST_UNIT_READY
uint8_t lun ; ///< Logical Unit
uint8_t reserved[3] ;
uint8_t control ;
} scsi_test_unit_ready_t;
TU_VERIFY_STATIC(sizeof(scsi_test_unit_ready_t) == 6, "size is not correct");
/// SCSI Inquiry Command
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_INQUIRY
uint8_t reserved1 ;
uint8_t page_code ;
uint8_t reserved2 ;
uint8_t alloc_length ; ///< specifies the maximum number of bytes that USB host has allocated in the Data-In Buffer. An allocation length of zero specifies that no data shall be transferred.
uint8_t control ;
} scsi_inquiry_t, scsi_request_sense_t;
TU_VERIFY_STATIC(sizeof(scsi_inquiry_t) == 6, "size is not correct");
/// SCSI Inquiry Response Data
typedef struct TU_ATTR_PACKED
{
uint8_t peripheral_device_type : 5;
uint8_t peripheral_qualifier : 3;
uint8_t : 7;
uint8_t is_removable : 1;
uint8_t version;
uint8_t response_data_format : 4;
uint8_t hierarchical_support : 1;
uint8_t normal_aca : 1;
uint8_t : 2;
uint8_t additional_length;
uint8_t protect : 1;
uint8_t : 2;
uint8_t third_party_copy : 1;
uint8_t target_port_group_support : 2;
uint8_t access_control_coordinator : 1;
uint8_t scc_support : 1;
uint8_t addr16 : 1;
uint8_t : 3;
uint8_t multi_port : 1;
uint8_t : 1; // vendor specific
uint8_t enclosure_service : 1;
uint8_t : 1;
uint8_t : 1; // vendor specific
uint8_t cmd_que : 1;
uint8_t : 2;
uint8_t sync : 1;
uint8_t wbus16 : 1;
uint8_t : 2;
uint8_t vendor_id[8] ; ///< 8 bytes of ASCII data identifying the vendor of the product.
uint8_t product_id[16]; ///< 16 bytes of ASCII data defined by the vendor.
uint8_t product_rev[4]; ///< 4 bytes of ASCII data defined by the vendor.
} scsi_inquiry_resp_t;
TU_VERIFY_STATIC(sizeof(scsi_inquiry_resp_t) == 36, "size is not correct");
typedef struct TU_ATTR_PACKED
{
uint8_t response_code : 7; ///< 70h - current errors, Fixed Format 71h - deferred errors, Fixed Format
uint8_t valid : 1;
uint8_t reserved;
uint8_t sense_key : 4;
uint8_t : 1;
uint8_t ili : 1; ///< Incorrect length indicator
uint8_t end_of_medium : 1;
uint8_t filemark : 1;
uint32_t information;
uint8_t add_sense_len;
uint32_t command_specific_info;
uint8_t add_sense_code;
uint8_t add_sense_qualifier;
uint8_t field_replaceable_unit_code;
uint8_t sense_key_specific[3]; ///< sense key specific valid bit is bit 7 of key[0], aka MSB in Big Endian layout
} scsi_sense_fixed_resp_t;
TU_VERIFY_STATIC(sizeof(scsi_sense_fixed_resp_t) == 18, "size is not correct");
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_MODE_SENSE_6
uint8_t : 3;
uint8_t disable_block_descriptor : 1;
uint8_t : 4;
uint8_t page_code : 6;
uint8_t page_control : 2;
uint8_t subpage_code;
uint8_t alloc_length;
uint8_t control;
} scsi_mode_sense6_t;
TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_t) == 6, "size is not correct");
// This is only a Mode parameter header(6).
typedef struct TU_ATTR_PACKED
{
uint8_t data_len;
uint8_t medium_type;
uint8_t reserved : 7;
bool write_protected : 1;
uint8_t block_descriptor_len;
} scsi_mode_sense6_resp_t;
TU_VERIFY_STATIC( sizeof(scsi_mode_sense6_resp_t) == 4, "size is not correct");
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code; ///< SCSI OpCode for \ref SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL
uint8_t reserved[3];
uint8_t prohibit_removal;
uint8_t control;
} scsi_prevent_allow_medium_removal_t;
TU_VERIFY_STATIC( sizeof(scsi_prevent_allow_medium_removal_t) == 6, "size is not correct");
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code;
uint8_t immded : 1;
uint8_t : 7;
uint8_t TU_RESERVED;
uint8_t power_condition_mod : 4;
uint8_t : 4;
uint8_t start : 1;
uint8_t load_eject : 1;
uint8_t no_flush : 1;
uint8_t : 1;
uint8_t power_condition : 4;
uint8_t control;
} scsi_start_stop_unit_t;
TU_VERIFY_STATIC( sizeof(scsi_start_stop_unit_t) == 6, "size is not correct");
//--------------------------------------------------------------------+
// SCSI MMC
//--------------------------------------------------------------------+
/// SCSI Read Format Capacity: Write Capacity
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code;
uint8_t reserved[6];
uint16_t alloc_length;
uint8_t control;
} scsi_read_format_capacity_t;
TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_t) == 10, "size is not correct");
typedef struct TU_ATTR_PACKED{
uint8_t reserved[3];
uint8_t list_length; /// must be 8*n, length in bytes of formattable capacity descriptor followed it.
uint32_t block_num; /// Number of Logical Blocks
uint8_t descriptor_type; // 00: reserved, 01 unformatted media , 10 Formatted media, 11 No media present
uint8_t reserved2;
uint16_t block_size_u16;
} scsi_read_format_capacity_data_t;
TU_VERIFY_STATIC( sizeof(scsi_read_format_capacity_data_t) == 12, "size is not correct");
//--------------------------------------------------------------------+
// SCSI Block Command (SBC-3)
// NOTE: All data in SCSI command are in Big Endian
//--------------------------------------------------------------------+
/// SCSI Read Capacity 10 Command: Read Capacity
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code ; ///< SCSI OpCode for \ref SCSI_CMD_READ_CAPACITY_10
uint8_t reserved1 ;
uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command
uint16_t reserved2 ;
uint8_t partial_medium_indicator ;
uint8_t control ;
} scsi_read_capacity10_t;
TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_t) == 10, "size is not correct");
/// SCSI Read Capacity 10 Response Data
typedef struct {
uint32_t last_lba ; ///< The last Logical Block Address of the device
uint32_t block_size ; ///< Block size in bytes
} scsi_read_capacity10_resp_t;
TU_VERIFY_STATIC(sizeof(scsi_read_capacity10_resp_t) == 8, "size is not correct");
/// SCSI Read 10 Command
typedef struct TU_ATTR_PACKED
{
uint8_t cmd_code ; ///< SCSI OpCode
uint8_t reserved ; // has LUN according to wiki
uint32_t lba ; ///< The first Logical Block Address (LBA) accessed by this command
uint8_t reserved2 ;
uint16_t block_count ; ///< Number of Blocks used by this command
uint8_t control ;
} scsi_read10_t, scsi_write10_t;
TU_VERIFY_STATIC(sizeof(scsi_read10_t) == 10, "size is not correct");
TU_VERIFY_STATIC(sizeof(scsi_write10_t) == 10, "size is not correct");
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MSC_H_ */

View File

@ -0,0 +1,162 @@
/*
* 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.
*/
#ifndef _TUSB_MSC_DEVICE_H_
#define _TUSB_MSC_DEVICE_H_
#include "common/tusb_common.h"
#include "msc.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#if !defined(CFG_TUD_MSC_EP_BUFSIZE) & defined(CFG_TUD_MSC_BUFSIZE)
// TODO warn user to use new name later on
// #warning CFG_TUD_MSC_BUFSIZE is renamed to CFG_TUD_MSC_EP_BUFSIZE, please update to use the new name
#define CFG_TUD_MSC_EP_BUFSIZE CFG_TUD_MSC_BUFSIZE
#endif
#ifndef CFG_TUD_MSC_EP_BUFSIZE
#error CFG_TUD_MSC_EP_BUFSIZE must be defined, value of a block size should work well, the more the better
#endif
TU_VERIFY_STATIC(CFG_TUD_MSC_EP_BUFSIZE < UINT16_MAX, "Size is not correct");
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Set SCSI sense response
bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier);
//--------------------------------------------------------------------+
// Application Callbacks (WEAK is optional)
//--------------------------------------------------------------------+
// Invoked when received SCSI READ10 command
// - Address = lba * BLOCK_SIZE + offset
// - offset is only needed if CFG_TUD_MSC_EP_BUFSIZE is smaller than BLOCK_SIZE.
//
// - Application fill the buffer (up to bufsize) with address contents and return number of read byte. If
// - read < bufsize : These bytes are transferred first and callback invoked again for remaining data.
//
// - read == 0 : Indicate application is not ready yet e.g disk I/O busy.
// Callback invoked again with the same parameters later on.
//
// - read < 0 : Indicate application error e.g invalid address. This request will be STALLed
// and return failed status in command status wrapper phase.
int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize);
// Invoked when received SCSI WRITE10 command
// - Address = lba * BLOCK_SIZE + offset
// - offset is only needed if CFG_TUD_MSC_EP_BUFSIZE is smaller than BLOCK_SIZE.
//
// - Application write data from buffer to address contents (up to bufsize) and return number of written byte. If
// - write < bufsize : callback invoked again with remaining data later on.
//
// - write == 0 : Indicate application is not ready yet e.g disk I/O busy.
// Callback invoked again with the same parameters later on.
//
// - write < 0 : Indicate application error e.g invalid address. This request will be STALLed
// and return failed status in command status wrapper phase.
//
// TODO change buffer to const uint8_t*
int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize);
// Invoked when received SCSI_CMD_INQUIRY
// Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively
void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]);
// Invoked when received Test Unit Ready command.
// return true allowing host to read/write this LUN e.g SD card inserted
bool tud_msc_test_unit_ready_cb(uint8_t lun);
// Invoked when received SCSI_CMD_READ_CAPACITY_10 and SCSI_CMD_READ_FORMAT_CAPACITY to determine the disk size
// Application update block count and block size
void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size);
/**
* Invoked when received an SCSI command not in built-in list below.
* - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE
* - READ10 and WRITE10 has their own callbacks
*
* \param[in] lun Logical unit number
* \param[in] scsi_cmd SCSI command contents which application must examine to response accordingly
* \param[out] buffer Buffer for SCSI Data Stage.
* - For INPUT: application must fill this with response.
* - For OUTPUT it holds the Data from host
* \param[in] bufsize Buffer's length.
*
* \return Actual bytes processed, can be zero for no-data command.
* \retval negative Indicate error e.g unsupported command, tinyusb will \b STALL the corresponding
* endpoint and return failed status in command status wrapper phase.
*/
int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize);
/*------------- Optional callbacks -------------*/
// Invoked when received GET_MAX_LUN request, required for multiple LUNs implementation
TU_ATTR_WEAK uint8_t tud_msc_get_maxlun_cb(void);
// Invoked when received Start Stop Unit command
// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage
// - Start = 1 : active mode, if load_eject = 1 : load disk storage
TU_ATTR_WEAK bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject);
// Invoked when received REQUEST_SENSE
TU_ATTR_WEAK int32_t tud_msc_request_sense_cb(uint8_t lun, void* buffer, uint16_t bufsize);
// Invoked when Read10 command is complete
TU_ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun);
// Invoke when Write10 command is complete, can be used to flush flash caching
TU_ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun);
// Invoked when command in tud_msc_scsi_cb is complete
TU_ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]);
// Invoked to check if device is writable as part of SCSI WRITE10
TU_ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void mscd_init (void);
void mscd_reset (uint8_t rhport);
uint16_t mscd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool mscd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * p_request);
bool mscd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MSC_DEVICE_H_ */

View File

@ -0,0 +1,119 @@
/*
* 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.
*/
#ifndef _TUSB_MSC_HOST_H_
#define _TUSB_MSC_HOST_H_
#include "msc.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUH_MSC_MAXLUN
#define CFG_TUH_MSC_MAXLUN 4
#endif
typedef bool (*tuh_msc_complete_cb_t)(uint8_t dev_addr, msc_cbw_t const* cbw, msc_csw_t const* csw);
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Check if device supports MassStorage interface.
// This function true after tuh_msc_mounted_cb() and false after tuh_msc_unmounted_cb()
bool tuh_msc_mounted(uint8_t dev_addr);
// Check if the interface is currently ready or busy transferring data
bool tuh_msc_ready(uint8_t dev_addr);
// Get Max Lun
uint8_t tuh_msc_get_maxlun(uint8_t dev_addr);
// Get number of block
uint32_t tuh_msc_get_block_count(uint8_t dev_addr, uint8_t lun);
// Get block size in bytes
uint32_t tuh_msc_get_block_size(uint8_t dev_addr, uint8_t lun);
// Perform a full SCSI command (cbw, data, csw) in non-blocking manner.
// Complete callback is invoked when SCSI op is complete.
// return true if success, false if there is already pending operation.
bool tuh_msc_scsi_command(uint8_t dev_addr, msc_cbw_t const* cbw, void* data, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Inquiry command
// Complete callback is invoked when SCSI op is complete.
bool tuh_msc_inquiry(uint8_t dev_addr, uint8_t lun, scsi_inquiry_resp_t* response, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Test Unit Ready command
// Complete callback is invoked when SCSI op is complete.
bool tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Request Sense 10 command
// Complete callback is invoked when SCSI op is complete.
bool tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, void *resposne, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Read 10 command. Read n blocks starting from LBA to buffer
// Complete callback is invoked when SCSI op is complete.
bool tuh_msc_read10(uint8_t dev_addr, uint8_t lun, void * buffer, uint32_t lba, uint16_t block_count, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Write 10 command. Write n blocks starting from LBA to device
// Complete callback is invoked when SCSI op is complete.
bool tuh_msc_write10(uint8_t dev_addr, uint8_t lun, void const * buffer, uint32_t lba, uint16_t block_count, tuh_msc_complete_cb_t complete_cb);
// Perform SCSI Read Capacity 10 command
// Complete callback is invoked when SCSI op is complete.
// Note: during enumeration, host stack already carried out this request. Application can retrieve capacity by
// simply call tuh_msc_get_block_count() and tuh_msc_get_block_size()
bool tuh_msc_read_capacity(uint8_t dev_addr, uint8_t lun, scsi_read_capacity10_resp_t* response, tuh_msc_complete_cb_t complete_cb);
//------------- Application Callback -------------//
// Invoked when a device with MassStorage interface is mounted
TU_ATTR_WEAK void tuh_msc_mount_cb(uint8_t dev_addr);
// Invoked when a device with MassStorage interface is unmounted
TU_ATTR_WEAK void tuh_msc_umount_cb(uint8_t dev_addr);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void msch_init (void);
bool msch_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *desc_itf, uint16_t max_len);
bool msch_set_config (uint8_t dev_addr, uint8_t itf_num);
void msch_close (uint8_t dev_addr);
bool msch_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MSC_HOST_H_ */

View File

@ -0,0 +1,69 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_NCM_H_
#define _TUSB_NCM_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
// Table 4.3 Data Class Interface Protocol Codes
typedef enum
{
NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK = 0x01
} ncm_data_interface_protocol_code_t;
// Table 6.2 Class-Specific Request Codes for Network Control Model subclass
typedef enum
{
NCM_SET_ETHERNET_MULTICAST_FILTERS = 0x40,
NCM_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41,
NCM_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42,
NCM_SET_ETHERNET_PACKET_FILTER = 0x43,
NCM_GET_ETHERNET_STATISTIC = 0x44,
NCM_GET_NTB_PARAMETERS = 0x80,
NCM_GET_NET_ADDRESS = 0x81,
NCM_SET_NET_ADDRESS = 0x82,
NCM_GET_NTB_FORMAT = 0x83,
NCM_SET_NTB_FORMAT = 0x84,
NCM_GET_NTB_INPUT_SIZE = 0x85,
NCM_SET_NTB_INPUT_SIZE = 0x86,
NCM_GET_MAX_DATAGRAM_SIZE = 0x87,
NCM_SET_MAX_DATAGRAM_SIZE = 0x88,
NCM_GET_CRC_MODE = 0x89,
NCM_SET_CRC_MODE = 0x8A,
} ncm_request_code_t;
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,118 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Peter Lawrence
* 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.
*/
#ifndef _TUSB_NET_DEVICE_H_
#define _TUSB_NET_DEVICE_H_
#include "class/cdc/cdc.h"
#if CFG_TUD_ECM_RNDIS && CFG_TUD_NCM
#error "Cannot enable both ECM_RNDIS and NCM network drivers"
#endif
#include "ncm.h"
/* declared here, NOT in usb_descriptors.c, so that the driver can intelligently ZLP as needed */
#define CFG_TUD_NET_ENDPOINT_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
/* Maximum Transmission Unit (in bytes) of the network, including Ethernet header */
#ifndef CFG_TUD_NET_MTU
#define CFG_TUD_NET_MTU 1514
#endif
#ifndef CFG_TUD_NCM_IN_NTB_MAX_SIZE
#define CFG_TUD_NCM_IN_NTB_MAX_SIZE 3200
#endif
#ifndef CFG_TUD_NCM_OUT_NTB_MAX_SIZE
#define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 3200
#endif
#ifndef CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB
#define CFG_TUD_NCM_MAX_DATAGRAMS_PER_NTB 8
#endif
#ifndef CFG_TUD_NCM_ALIGNMENT
#define CFG_TUD_NCM_ALIGNMENT 4
#endif
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// indicate to network driver that client has finished with the packet provided to network_recv_cb()
void tud_network_recv_renew(void);
// poll network driver for its ability to accept another packet to transmit
bool tud_network_can_xmit(uint16_t size);
// if network_can_xmit() returns true, network_xmit() can be called once
void tud_network_xmit(void *ref, uint16_t arg);
//--------------------------------------------------------------------+
// Application Callbacks (WEAK is optional)
//--------------------------------------------------------------------+
// client must provide this: return false if the packet buffer was not accepted
bool tud_network_recv_cb(const uint8_t *src, uint16_t size);
// client must provide this: copy from network stack packet pointer to dst
uint16_t tud_network_xmit_cb(uint8_t *dst, void *ref, uint16_t arg);
//------------- ECM/RNDIS -------------//
// client must provide this: initialize any network state back to the beginning
void tud_network_init_cb(void);
// client must provide this: 48-bit MAC address
// TODO removed later since it is not part of tinyusb stack
extern const uint8_t tud_network_mac_address[6];
//------------- NCM -------------//
// callback to client providing optional indication of internal state of network driver
void tud_network_link_state_cb(bool state);
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void netd_init (void);
void netd_reset (uint8_t rhport);
uint16_t netd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool netd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
void netd_report (uint8_t *buf, uint16_t len);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_NET_DEVICE_H_ */

View File

@ -0,0 +1,316 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 N Conrad
*
* 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.
*/
#ifndef _TUSB_USBTMC_H__
#define _TUSB_USBTMC_H__
#include "common/tusb_common.h"
/* Implements USBTMC Revision 1.0, April 14, 2003
String descriptors must have a "LANGID=0x409"/US English string.
Characters must be 0x20 (' ') to 0x7E ('~') ASCII,
But MUST not contain: "/:?\*
Also must not have leading or trailing space (' ')
Device descriptor must state USB version 0x0200 or greater
If USB488DeviceCapabilites.D2 = 1 (SR1), then there must be a INT endpoint.
*/
#define USBTMC_VERSION 0x0100
#define USBTMC_488_VERSION 0x0100
typedef enum {
USBTMC_MSGID_DEV_DEP_MSG_OUT = 1u,
USBTMC_MSGID_DEV_DEP_MSG_IN = 2u,
USBTMC_MSGID_VENDOR_SPECIFIC_MSG_OUT = 126u,
USBTMC_MSGID_VENDOR_SPECIFIC_IN = 127u,
USBTMC_MSGID_USB488_TRIGGER = 128u,
} usbtmc_msgid_enum;
/// \brief Message header (For BULK OUT and BULK IN); 4 bytes
typedef struct TU_ATTR_PACKED
{
uint8_t MsgID ; ///< Message type ID (usbtmc_msgid_enum)
uint8_t bTag ; ///< Transfer ID 1<=bTag<=255
uint8_t bTagInverse ; ///< Complement of the tag
uint8_t _reserved ; ///< Must be 0x00
} usbtmc_msg_header_t;
typedef struct TU_ATTR_PACKED
{
usbtmc_msg_header_t header;
uint8_t data[8];
} usbtmc_msg_generic_t;
/* Uses on the bulk-out endpoint: */
// Next 8 bytes are message-specific
typedef struct TU_ATTR_PACKED {
usbtmc_msg_header_t header ; ///< Header
uint32_t TransferSize ; ///< Transfer size; LSB first
struct TU_ATTR_PACKED
{
unsigned int EOM : 1 ; ///< EOM set on last byte
} bmTransferAttributes;
uint8_t _reserved[3];
} usbtmc_msg_request_dev_dep_out;
TU_VERIFY_STATIC(sizeof(usbtmc_msg_request_dev_dep_out) == 12u, "struct wrong length");
// Next 8 bytes are message-specific
typedef struct TU_ATTR_PACKED
{
usbtmc_msg_header_t header ; ///< Header
uint32_t TransferSize ; ///< Transfer size; LSB first
struct TU_ATTR_PACKED
{
unsigned int TermCharEnabled : 1 ; ///< "The Bulk-IN transfer must terminate on the specified TermChar."; CAPABILITIES must list TermChar
} bmTransferAttributes;
uint8_t TermChar;
uint8_t _reserved[2];
} usbtmc_msg_request_dev_dep_in;
TU_VERIFY_STATIC(sizeof(usbtmc_msg_request_dev_dep_in) == 12u, "struct wrong length");
/* Bulk-in headers */
typedef struct TU_ATTR_PACKED
{
usbtmc_msg_header_t header;
uint32_t TransferSize;
struct TU_ATTR_PACKED
{
uint8_t EOM: 1; ///< Last byte of transfer is the end of the message
uint8_t UsingTermChar: 1; ///< Support TermChar && Request.TermCharEnabled && last char in transfer is TermChar
} bmTransferAttributes;
uint8_t _reserved[3];
} usbtmc_msg_dev_dep_msg_in_header_t;
TU_VERIFY_STATIC(sizeof(usbtmc_msg_dev_dep_msg_in_header_t) == 12u, "struct wrong length");
/* Unsupported vendor things.... Are these ever used?*/
typedef struct TU_ATTR_PACKED
{
usbtmc_msg_header_t header ; ///< Header
uint32_t TransferSize ; ///< Transfer size; LSB first
uint8_t _reserved[4];
} usbtmc_msg_request_vendor_specific_out;
TU_VERIFY_STATIC(sizeof(usbtmc_msg_request_vendor_specific_out) == 12u, "struct wrong length");
typedef struct TU_ATTR_PACKED
{
usbtmc_msg_header_t header ; ///< Header
uint32_t TransferSize ; ///< Transfer size; LSB first
uint8_t _reserved[4];
} usbtmc_msg_request_vendor_specific_in;
TU_VERIFY_STATIC(sizeof(usbtmc_msg_request_vendor_specific_in) == 12u, "struct wrong length");
// Control request type should use tusb_control_request_t
/*
typedef struct TU_ATTR_PACKED {
struct {
unsigned int Recipient : 5 ; ///< EOM set on last byte
unsigned int Type : 2 ; ///< EOM set on last byte
unsigned int DirectionToHost : 1 ; ///< 0 is OUT, 1 is IN
} bmRequestType;
uint8_t bRequest ; ///< If bmRequestType.Type = Class, see usmtmc_request_type_enum
uint16_t wValue ;
uint16_t wIndex ;
uint16_t wLength ; // Number of bytes in data stage
} usbtmc_class_specific_control_req;
*/
// bulk-in protocol errors
enum {
USBTMC_BULK_IN_ERR_INCOMPLETE_HEADER = 1u,
USBTMC_BULK_IN_ERR_UNSUPPORTED = 2u,
USBTMC_BULK_IN_ERR_BAD_PARAMETER = 3u,
USBTMC_BULK_IN_ERR_DATA_TOO_SHORT = 4u,
USBTMC_BULK_IN_ERR_DATA_TOO_LONG = 5u,
};
// bult-in halt errors
enum {
USBTMC_BULK_IN_ERR = 1u, ///< receives a USBTMC command message that expects a response while a
/// Bulk-IN transfer is in progress
};
typedef enum {
USBTMC_bREQUEST_INITIATE_ABORT_BULK_OUT = 1u,
USBTMC_bREQUEST_CHECK_ABORT_BULK_OUT_STATUS = 2u,
USBTMC_bREQUEST_INITIATE_ABORT_BULK_IN = 3u,
USBTMC_bREQUEST_CHECK_ABORT_BULK_IN_STATUS = 4u,
USBTMC_bREQUEST_INITIATE_CLEAR = 5u,
USBTMC_bREQUEST_CHECK_CLEAR_STATUS = 6u,
USBTMC_bREQUEST_GET_CAPABILITIES = 7u,
USBTMC_bREQUEST_INDICATOR_PULSE = 64u, // Optional
/****** USBTMC 488 *************/
USB488_bREQUEST_READ_STATUS_BYTE = 128u,
USB488_bREQUEST_REN_CONTROL = 160u,
USB488_bREQUEST_GO_TO_LOCAL = 161u,
USB488_bREQUEST_LOCAL_LOCKOUT = 162u,
} usmtmc_request_type_enum;
typedef enum {
USBTMC_STATUS_SUCCESS = 0x01,
USBTMC_STATUS_PENDING = 0x02,
USBTMC_STATUS_FAILED = 0x80,
USBTMC_STATUS_TRANSFER_NOT_IN_PROGRESS = 0x81,
USBTMC_STATUS_SPLIT_NOT_IN_PROGRESS = 0x82,
USBTMC_STATUS_SPLIT_IN_PROGRESS = 0x83
} usbtmc_status_enum;
/************************************************************
* Control Responses
*/
typedef struct TU_ATTR_PACKED {
uint8_t USBTMC_status; ///< usbtmc_status_enum
uint8_t _reserved;
uint16_t bcdUSBTMC; ///< USBTMC_VERSION
struct TU_ATTR_PACKED
{
unsigned int listenOnly :1;
unsigned int talkOnly :1;
unsigned int supportsIndicatorPulse :1;
} bmIntfcCapabilities;
struct TU_ATTR_PACKED
{
unsigned int canEndBulkInOnTermChar :1;
} bmDevCapabilities;
uint8_t _reserved2[6];
uint8_t _reserved3[12];
} usbtmc_response_capabilities_t;
TU_VERIFY_STATIC(sizeof(usbtmc_response_capabilities_t) == 0x18, "struct wrong length");
typedef struct TU_ATTR_PACKED
{
uint8_t USBTMC_status;
struct TU_ATTR_PACKED
{
unsigned int BulkInFifoBytes :1;
} bmClear;
} usbtmc_get_clear_status_rsp_t;
TU_VERIFY_STATIC(sizeof(usbtmc_get_clear_status_rsp_t) == 2u, "struct wrong length");
// Used for both abort bulk IN and bulk OUT
typedef struct TU_ATTR_PACKED
{
uint8_t USBTMC_status;
uint8_t bTag;
} usbtmc_initiate_abort_rsp_t;
TU_VERIFY_STATIC(sizeof(usbtmc_get_clear_status_rsp_t) == 2u, "struct wrong length");
// Used for both check_abort_bulk_in_status and check_abort_bulk_out_status
typedef struct TU_ATTR_PACKED
{
uint8_t USBTMC_status;
struct TU_ATTR_PACKED
{
unsigned int BulkInFifoBytes : 1; ///< Has queued data or a short packet that is queued
} bmAbortBulkIn;
uint8_t _reserved[2]; ///< Must be zero
uint32_t NBYTES_RXD_TXD;
} usbtmc_check_abort_bulk_rsp_t;
TU_VERIFY_STATIC(sizeof(usbtmc_check_abort_bulk_rsp_t) == 8u, "struct wrong length");
typedef struct TU_ATTR_PACKED
{
uint8_t USBTMC_status; ///< usbtmc_status_enum
uint8_t _reserved;
uint16_t bcdUSBTMC; ///< USBTMC_VERSION
struct TU_ATTR_PACKED
{
unsigned int listenOnly :1;
unsigned int talkOnly :1;
unsigned int supportsIndicatorPulse :1;
} bmIntfcCapabilities;
struct TU_ATTR_PACKED
{
unsigned int canEndBulkInOnTermChar :1;
} bmDevCapabilities;
uint8_t _reserved2[6];
uint16_t bcdUSB488;
struct TU_ATTR_PACKED
{
unsigned int is488_2 :1;
unsigned int supportsREN_GTL_LLO :1;
unsigned int supportsTrigger :1;
} bmIntfcCapabilities488;
struct TU_ATTR_PACKED
{
unsigned int SCPI :1;
unsigned int SR1 :1;
unsigned int RL1 :1;
unsigned int DT1 :1;
} bmDevCapabilities488;
uint8_t _reserved3[8];
} usbtmc_response_capabilities_488_t;
TU_VERIFY_STATIC(sizeof(usbtmc_response_capabilities_488_t) == 0x18, "struct wrong length");
typedef struct TU_ATTR_PACKED
{
uint8_t USBTMC_status;
uint8_t bTag;
uint8_t statusByte;
} usbtmc_read_stb_rsp_488_t;
TU_VERIFY_STATIC(sizeof(usbtmc_read_stb_rsp_488_t) == 3u, "struct wrong length");
typedef struct TU_ATTR_PACKED
{
struct TU_ATTR_PACKED
{
unsigned int bTag : 7;
unsigned int one : 1;
} bNotify1;
uint8_t StatusByte;
} usbtmc_read_stb_interrupt_488_t;
TU_VERIFY_STATIC(sizeof(usbtmc_read_stb_interrupt_488_t) == 2u, "struct wrong length");
#endif

View File

@ -0,0 +1,116 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 N Conrad
*
* 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.
*/
#ifndef CLASS_USBTMC_USBTMC_DEVICE_H_
#define CLASS_USBTMC_USBTMC_DEVICE_H_
#include "usbtmc.h"
// Enable 488 mode by default
#if !defined(CFG_TUD_USBTMC_ENABLE_488)
#define CFG_TUD_USBTMC_ENABLE_488 (1)
#endif
// USB spec says that full-speed must be 8,16,32, or 64.
// However, this driver implementation requires it to be >=32
#define USBTMCD_MAX_PACKET_SIZE (64u)
/***********************************************
* Functions to be implemeted by the class implementation
*/
// In order to proceed, app must call call tud_usbtmc_start_bus_read(rhport) during or soon after:
// * tud_usbtmc_open_cb
// * tud_usbtmc_msg_data_cb
// * tud_usbtmc_msgBulkIn_complete_cb
// * tud_usbtmc_msg_trigger_cb
// * (successful) tud_usbtmc_check_abort_bulk_out_cb
// * (successful) tud_usbtmc_check_abort_bulk_in_cb
// * (successful) tud_usmtmc_bulkOut_clearFeature_cb
#if (CFG_TUD_USBTMC_ENABLE_488)
usbtmc_response_capabilities_488_t const * tud_usbtmc_get_capabilities_cb(void);
#else
usbtmc_response_capabilities_t const * tud_usbtmc_get_capabilities_cb(void);
#endif
void tud_usbtmc_open_cb(uint8_t interface_id);
bool tud_usbtmc_msgBulkOut_start_cb(usbtmc_msg_request_dev_dep_out const * msgHeader);
// transfer_complete does not imply that a message is complete.
bool tud_usbtmc_msg_data_cb( void *data, size_t len, bool transfer_complete);
void tud_usbtmc_bulkOut_clearFeature_cb(void); // Notice to clear and abort the pending BULK out transfer
bool tud_usbtmc_msgBulkIn_request_cb(usbtmc_msg_request_dev_dep_in const * request);
bool tud_usbtmc_msgBulkIn_complete_cb(void);
void tud_usbtmc_bulkIn_clearFeature_cb(void); // Notice to clear and abort the pending BULK out transfer
bool tud_usbtmc_initiate_abort_bulk_in_cb(uint8_t *tmcResult);
bool tud_usbtmc_initiate_abort_bulk_out_cb(uint8_t *tmcResult);
bool tud_usbtmc_initiate_clear_cb(uint8_t *tmcResult);
bool tud_usbtmc_check_abort_bulk_in_cb(usbtmc_check_abort_bulk_rsp_t *rsp);
bool tud_usbtmc_check_abort_bulk_out_cb(usbtmc_check_abort_bulk_rsp_t *rsp);
bool tud_usbtmc_check_clear_cb(usbtmc_get_clear_status_rsp_t *rsp);
// Indicator pulse should be 0.5 to 1.0 seconds long
TU_ATTR_WEAK bool tud_usbtmc_indicator_pulse_cb(tusb_control_request_t const * msg, uint8_t *tmcResult);
#if (CFG_TUD_USBTMC_ENABLE_488)
uint8_t tud_usbtmc_get_stb_cb(uint8_t *tmcResult);
TU_ATTR_WEAK bool tud_usbtmc_msg_trigger_cb(usbtmc_msg_generic_t* msg);
//TU_ATTR_WEAK bool tud_usbtmc_app_go_to_local_cb();
#endif
/*******************************************
* Called from app
*
* We keep a reference to the buffer, so it MUST not change until the app is
* notified that the transfer is complete.
******************************************/
bool tud_usbtmc_transmit_dev_msg_data(
const void * data, size_t len,
bool endOfMessage, bool usingTermChar);
bool tud_usbtmc_start_bus_read(void);
/* "callbacks" from USB device core */
uint16_t usbtmcd_open_cb(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
void usbtmcd_reset_cb(uint8_t rhport);
bool usbtmcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
bool usbtmcd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
void usbtmcd_init_cb(void);
/************************************************************
* USBTMC Descriptor Templates
*************************************************************/
#endif /* CLASS_USBTMC_USBTMC_DEVICE_H_ */

View File

@ -0,0 +1,145 @@
/*
* 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.
*/
#ifndef _TUSB_VENDOR_DEVICE_H_
#define _TUSB_VENDOR_DEVICE_H_
#include "common/tusb_common.h"
#ifndef CFG_TUD_VENDOR_EPSIZE
#define CFG_TUD_VENDOR_EPSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Interfaces)
//--------------------------------------------------------------------+
bool tud_vendor_n_mounted (uint8_t itf);
uint32_t tud_vendor_n_available (uint8_t itf);
uint32_t tud_vendor_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
bool tud_vendor_n_peek (uint8_t itf, uint8_t* ui8);
void tud_vendor_n_read_flush (uint8_t itf);
uint32_t tud_vendor_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
uint32_t tud_vendor_n_write_available (uint8_t itf);
static inline
uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str);
uint32_t tud_vendor_n_flush (uint8_t itf);
//--------------------------------------------------------------------+
// Application API (Single Port)
//--------------------------------------------------------------------+
static inline bool tud_vendor_mounted (void);
static inline uint32_t tud_vendor_available (void);
static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize);
static inline bool tud_vendor_peek (uint8_t* ui8);
static inline void tud_vendor_read_flush (void);
static inline uint32_t tud_vendor_write (void const* buffer, uint32_t bufsize);
static inline uint32_t tud_vendor_write_str (char const* str);
static inline uint32_t tud_vendor_write_available (void);
static inline uint32_t tud_vendor_flush (void);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when received new data
TU_ATTR_WEAK void tud_vendor_rx_cb(uint8_t itf);
// Invoked when last rx transfer finished
TU_ATTR_WEAK void tud_vendor_tx_cb(uint8_t itf, uint32_t sent_bytes);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str)
{
return tud_vendor_n_write(itf, str, strlen(str));
}
static inline bool tud_vendor_mounted (void)
{
return tud_vendor_n_mounted(0);
}
static inline uint32_t tud_vendor_available (void)
{
return tud_vendor_n_available(0);
}
static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize)
{
return tud_vendor_n_read(0, buffer, bufsize);
}
static inline bool tud_vendor_peek (uint8_t* ui8)
{
return tud_vendor_n_peek(0, ui8);
}
static inline void tud_vendor_read_flush(void)
{
tud_vendor_n_read_flush(0);
}
static inline uint32_t tud_vendor_write (void const* buffer, uint32_t bufsize)
{
return tud_vendor_n_write(0, buffer, bufsize);
}
static inline uint32_t tud_vendor_write_str (char const* str)
{
return tud_vendor_n_write_str(0, str);
}
static inline uint32_t tud_vendor_write_available (void)
{
return tud_vendor_n_write_available(0);
}
static inline uint32_t tud_vendor_flush (void)
{
return tud_vendor_n_flush(0);
}
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void vendord_init(void);
void vendord_reset(uint8_t rhport);
uint16_t vendord_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_VENDOR_DEVICE_H_ */

View File

@ -0,0 +1,67 @@
/*
* 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.
*/
#ifndef _TUSB_VENDOR_HOST_H_
#define _TUSB_VENDOR_HOST_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
pipe_handle_t pipe_in;
pipe_handle_t pipe_out;
}custom_interface_info_t;
//--------------------------------------------------------------------+
// USBH-CLASS DRIVER API
//--------------------------------------------------------------------+
static inline bool tusbh_custom_is_mounted(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id)
{
(void) vendor_id; // TODO check this later
(void) product_id;
// return (tusbh_device_get_mounted_class_flag(dev_addr) & TU_BIT(TUSB_CLASS_MAPPED_INDEX_END-1) ) != 0;
return false;
}
bool tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length);
bool tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void cush_init(void);
bool cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length);
void cush_isr(pipe_handle_t pipe_hdl, xfer_result_t event);
void cush_close(uint8_t dev_addr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_VENDOR_HOST_H_ */

View File

@ -0,0 +1,480 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Koji KITAYAMA
*
* 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.
*/
#ifndef TUSB_VIDEO_H_
#define TUSB_VIDEO_H_
#include "common/tusb_common.h"
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_PRIMARIES_UNDEFINED = 0x00,
VIDEO_COLOR_PRIMARIES_BT709, // sRGB (default)
VIDEO_COLOR_PRIMARIES_BT470_2M,
VIDEO_COLOR_PRIMARIES_BT470_2BG,
VIDEO_COLOR_PRIMARIES_SMPTE170M,
VIDEO_COLOR_PRIMARIES_SMPTE240M,
} video_color_primaries_t;
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_XFER_CH_UNDEFINED = 0x00,
VIDEO_COLOR_XFER_CH_BT709, // default
VIDEO_COLOR_XFER_CH_BT470_2M,
VIDEO_COLOR_XFER_CH_BT470_2BG,
VIDEO_COLOR_XFER_CH_SMPTE170M,
VIDEO_COLOR_XFER_CH_SMPTE240M,
VIDEO_COLOR_XFER_CH_LINEAR,
VIDEO_COLOR_XFER_CH_SRGB,
} video_color_transfer_characteristics_t;
// Table 3-19 Color Matching Descriptor
typedef enum {
VIDEO_COLOR_COEF_UNDEFINED = 0x00,
VIDEO_COLOR_COEF_BT709,
VIDEO_COLOR_COEF_FCC,
VIDEO_COLOR_COEF_BT470_2BG,
VIDEO_COLOR_COEF_SMPTE170M, // BT.601 default
VIDEO_COLOR_COEF_SMPTE240M,
} video_color_matrix_coefficients_t;
/* 4.2.1.2 Request Error Code Control */
typedef enum {
VIDEO_ERROR_NONE = 0, /* The request succeeded. */
VIDEO_ERROR_NOT_READY,
VIDEO_ERROR_WRONG_STATE,
VIDEO_ERROR_POWER,
VIDEO_ERROR_OUT_OF_RANGE,
VIDEO_ERROR_INVALID_UNIT,
VIDEO_ERROR_INVALID_CONTROL,
VIDEO_ERROR_INVALID_REQUEST,
VIDEO_ERROR_INVALID_VALUE_WITHIN_RANGE,
VIDEO_ERROR_UNKNOWN = 0xFF,
} video_error_code_t;
/* A.2 Interface Subclass */
typedef enum {
VIDEO_SUBCLASS_UNDEFINED = 0x00,
VIDEO_SUBCLASS_CONTROL,
VIDEO_SUBCLASS_STREAMING,
VIDEO_SUBCLASS_INTERFACE_COLLECTION,
} video_subclass_type_t;
/* A.3 Interface Protocol */
typedef enum {
VIDEO_ITF_PROTOCOL_UNDEFINED = 0x00,
VIDEO_ITF_PROTOCOL_15,
} video_interface_protocol_code_t;
/* A.5 Class-Specific VideoControl Interface Descriptor Subtypes */
typedef enum {
VIDEO_CS_ITF_VC_UNDEFINED = 0x00,
VIDEO_CS_ITF_VC_HEADER,
VIDEO_CS_ITF_VC_INPUT_TERMINAL,
VIDEO_CS_ITF_VC_OUTPUT_TERMINAL,
VIDEO_CS_ITF_VC_SELECTOR_UNIT,
VIDEO_CS_ITF_VC_PROCESSING_UNIT,
VIDEO_CS_ITF_VC_EXTENSION_UNIT,
VIDEO_CS_ITF_VC_ENCODING_UNIT,
VIDEO_CS_ITF_VC_MAX,
} video_cs_vc_interface_subtype_t;
/* A.6 Class-Specific VideoStreaming Interface Descriptor Subtypes */
typedef enum {
VIDEO_CS_ITF_VS_UNDEFINED = 0x00,
VIDEO_CS_ITF_VS_INPUT_HEADER = 0x01,
VIDEO_CS_ITF_VS_OUTPUT_HEADER = 0x02,
VIDEO_CS_ITF_VS_STILL_IMAGE_FRAME = 0x03,
VIDEO_CS_ITF_VS_FORMAT_UNCOMPRESSED = 0x04,
VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED = 0x05,
VIDEO_CS_ITF_VS_FORMAT_MJPEG = 0x06,
VIDEO_CS_ITF_VS_FRAME_MJPEG = 0x07,
VIDEO_CS_ITF_VS_FORMAT_MPEG2TS = 0x0A,
VIDEO_CS_ITF_VS_FORMAT_DV = 0x0C,
VIDEO_CS_ITF_VS_COLORFORMAT = 0x0D,
VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED = 0x10,
VIDEO_CS_ITF_VS_FRAME_FRAME_BASED = 0x11,
VIDEO_CS_ITF_VS_FORMAT_STREAM_BASED = 0x12,
VIDEO_CS_ITF_VS_FORMAT_H264 = 0x13,
VIDEO_CS_ITF_VS_FRAME_H264 = 0x14,
VIDEO_CS_ITF_VS_FORMAT_H264_SIMULCAST = 0x15,
VIDEO_CS_ITF_VS_FORMAT_VP8 = 0x16,
VIDEO_CS_ITF_VS_FRAME_VP8 = 0x17,
VIDEO_CS_ITF_VS_FORMAT_VP8_SIMULCAST = 0x18,
} video_cs_vs_interface_subtype_t;
/* A.7. Class-Specific Endpoint Descriptor Subtypes */
typedef enum {
VIDEO_CS_EP_UNDEFINED = 0x00,
VIDEO_CS_EP_GENERAL,
VIDEO_CS_EP_ENDPOINT,
VIDEO_CS_EP_INTERRUPT
} video_cs_ep_subtype_t;
/* A.8 Class-Specific Request Codes */
typedef enum {
VIDEO_REQUEST_UNDEFINED = 0x00,
VIDEO_REQUEST_SET_CUR = 0x01,
VIDEO_REQUEST_SET_CUR_ALL = 0x11,
VIDEO_REQUEST_GET_CUR = 0x81,
VIDEO_REQUEST_GET_MIN = 0x82,
VIDEO_REQUEST_GET_MAX = 0x83,
VIDEO_REQUEST_GET_RES = 0x84,
VIDEO_REQUEST_GET_LEN = 0x85,
VIDEO_REQUEST_GET_INFO = 0x86,
VIDEO_REQUEST_GET_DEF = 0x87,
VIDEO_REQUEST_GET_CUR_ALL = 0x91,
VIDEO_REQUEST_GET_MIN_ALL = 0x92,
VIDEO_REQUEST_GET_MAX_ALL = 0x93,
VIDEO_REQUEST_GET_RES_ALL = 0x94,
VIDEO_REQUEST_GET_DEF_ALL = 0x97
} video_control_request_t;
/* A.9.1 VideoControl Interface Control Selectors */
typedef enum {
VIDEO_VC_CTL_UNDEFINED = 0x00,
VIDEO_VC_CTL_VIDEO_POWER_MODE,
VIDEO_VC_CTL_REQUEST_ERROR_CODE,
} video_interface_control_selector_t;
/* A.9.8 VideoStreaming Interface Control Selectors */
typedef enum {
VIDEO_VS_CTL_UNDEFINED = 0x00,
VIDEO_VS_CTL_PROBE,
VIDEO_VS_CTL_COMMIT,
VIDEO_VS_CTL_STILL_PROBE,
VIDEO_VS_CTL_STILL_COMMIT,
VIDEO_VS_CTL_STILL_IMAGE_TRIGGER,
VIDEO_VS_CTL_STREAM_ERROR_CODE,
VIDEO_VS_CTL_GENERATE_KEY_FRAME,
VIDEO_VS_CTL_UPDATE_FRAME_SEGMENT,
VIDEO_VS_CTL_SYNCH_DELAY_CONTROL,
} video_interface_streaming_selector_t;
/* B. Terminal Types */
typedef enum {
// Terminal
VIDEO_TT_VENDOR_SPECIFIC = 0x0100,
VIDEO_TT_STREAMING = 0x0101,
// Input
VIDEO_ITT_VENDOR_SPECIFIC = 0x0200,
VIDEO_ITT_CAMERA = 0x0201,
VIDEO_ITT_MEDIA_TRANSPORT_INPUT = 0x0202,
// Output
VIDEO_OTT_VENDOR_SPECIFIC = 0x0300,
VIDEO_OTT_DISPLAY = 0x0301,
VIDEO_OTT_MEDIA_TRANSPORT_OUTPUT = 0x0302,
// External
VIDEO_ETT_VENDOR_SPEIFIC = 0x0400,
VIDEO_ETT_COMPOSITE_CONNECTOR = 0x0401,
VIDEO_ETT_SVIDEO_CONNECTOR = 0x0402,
VIDEO_ETT_COMPONENT_CONNECTOR = 0x0403,
} video_terminal_type_t;
//--------------------------------------------------------------------+
// Descriptors
//--------------------------------------------------------------------+
/* 2.3.4.2 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint16_t bcdUVC;
uint16_t wTotalLength;
uint32_t dwClockFrequency;
uint8_t bInCollection;
uint8_t baInterfaceNr[];
} tusb_desc_cs_video_ctl_itf_hdr_t;
/* 2.4.3.3 */
typedef struct TU_ATTR_PACKED {
uint8_t bHeaderLength;
union {
uint8_t bmHeaderInfo;
struct {
uint8_t FrameID: 1;
uint8_t EndOfFrame: 1;
uint8_t PresentationTime: 1;
uint8_t SourceClockReference: 1;
uint8_t PayloadSpecific: 1;
uint8_t StillImage: 1;
uint8_t Error: 1;
uint8_t EndOfHeader: 1;
};
};
} tusb_video_payload_header_t;
/* 3.9.2.1 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
uint8_t bmInfo;
uint8_t bTerminalLink;
uint8_t bStillCaptureMethod;
uint8_t bTriggerSupport;
uint8_t bTriggerUsage;
uint8_t bControlSize;
uint8_t bmaControls[];
} tusb_desc_cs_video_stm_itf_in_hdr_t;
/* 3.9.2.2 */
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
uint8_t bTerminalLink;
uint8_t bControlSize;
uint8_t bmaControls[];
} tusb_desc_cs_video_stm_itf_out_hdr_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bNumFormats;
uint16_t wTotalLength;
uint8_t bEndpointAddress;
union {
struct {
uint8_t bmInfo;
uint8_t bTerminalLink;
uint8_t bStillCaptureMethod;
uint8_t bTriggerSupport;
uint8_t bTriggerUsage;
uint8_t bControlSize;
uint8_t bmaControls[];
} input;
struct {
uint8_t bEndpointAddress;
uint8_t bTerminalLink;
uint8_t bControlSize;
uint8_t bmaControls[];
} output;
};
} tusb_desc_cs_video_stm_itf_hdr_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint8_t bNumFrameDescriptors;
uint8_t guidFormat[16];
uint8_t bBitsPerPixel;
uint8_t bDefaultFrameIndex;
uint8_t bAspectRatioX;
uint8_t bAspectRatioY;
uint8_t bmInterlaceFlags;
uint8_t bCopyProtect;
} tusb_desc_cs_video_fmt_uncompressed_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFrameIndex;
uint8_t bmCapabilities;
uint16_t wWidth;
uint16_t wHeight;
uint32_t dwMinBitRate;
uint32_t dwMaxBitRate;
uint32_t dwMaxVideoFrameBufferSize; /* deprecated */
uint32_t dwDefaultFrameInterval;
uint8_t bFrameIntervalType;
uint32_t dwFrameInterval[];
} tusb_desc_cs_video_frm_uncompressed_t;
//--------------------------------------------------------------------+
// Requests
//--------------------------------------------------------------------+
/* 4.3.1.1 */
typedef struct TU_ATTR_PACKED {
union {
uint8_t bmHint;
struct TU_ATTR_PACKED {
uint16_t dwFrameInterval: 1;
uint16_t wKeyFrameRatel : 1;
uint16_t wPFrameRate : 1;
uint16_t wCompQuality : 1;
uint16_t wCompWindowSize: 1;
uint16_t : 0;
} Hint;
};
uint8_t bFormatIndex;
uint8_t bFrameIndex;
uint32_t dwFrameInterval;
uint16_t wKeyFrameRate;
uint16_t wPFrameRate;
uint16_t wCompQuality;
uint16_t wCompWindowSize;
uint16_t wDelay;
uint32_t dwMaxVideoFrameSize;
uint32_t dwMaxPayloadTransferSize;
uint32_t dwClockFrequency;
union {
uint8_t bmFramingInfo;
struct TU_ATTR_PACKED {
uint8_t FrameID : 1;
uint8_t EndOfFrame: 1;
uint8_t EndOfSlice: 1;
uint8_t : 0;
} FramingInfo;
};
uint8_t bPreferedVersion;
uint8_t bMinVersion;
uint8_t bMaxVersion;
uint8_t bUsage;
uint8_t bBitDepthLuma;
uint8_t bmSettings;
uint8_t bMaxNumberOfRefFramesPlus1;
uint16_t bmRateControlModes;
uint64_t bmLayoutPerStream;
} video_probe_and_commit_control_t;
TU_VERIFY_STATIC( sizeof(video_probe_and_commit_control_t) == 48, "size is not correct");
#define TUD_VIDEO_DESC_IAD_LEN 8
#define TUD_VIDEO_DESC_STD_VC_LEN 9
#define TUD_VIDEO_DESC_CS_VC_LEN 12
#define TUD_VIDEO_DESC_INPUT_TERM_LEN 8
#define TUD_VIDEO_DESC_OUTPUT_TERM_LEN 9
#define TUD_VIDEO_DESC_CAMERA_TERM_LEN 18
#define TUD_VIDEO_DESC_STD_VS_LEN 9
#define TUD_VIDEO_DESC_CS_VS_IN_LEN 13
#define TUD_VIDEO_DESC_CS_VS_OUT_LEN 9
#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN 27
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN 38
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN 26
#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN 6
/* 2.2 compression formats */
#define TUD_VIDEO_GUID_YUY2 0x59,0x55,0x59,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_NV12 0x4E,0x56,0x31,0x32,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_M420 0x4D,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_GUID_I420 0x49,0x34,0x32,0x30,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_DESC_IAD(_firstitfs, _nitfs, _stridx) \
TUD_VIDEO_DESC_IAD_LEN, TUSB_DESC_INTERFACE_ASSOCIATION, \
_firstitfs, _nitfs, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_INTERFACE_COLLECTION, \
VIDEO_ITF_PROTOCOL_UNDEFINED, _stridx
#define TUD_VIDEO_DESC_STD_VC(_itfnum, _nEPs, _stridx) \
TUD_VIDEO_DESC_STD_VC_LEN, TUSB_DESC_INTERFACE, _itfnum, /* fixed to zero */ 0x00, \
_nEPs, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_CONTROL, VIDEO_ITF_PROTOCOL_15, _stridx
/* 3.7.2 */
#define TUD_VIDEO_DESC_CS_VC(_bcdUVC, _totallen, _clkfreq, ...) \
TUD_VIDEO_DESC_CS_VC_LEN + (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_HEADER, \
U16_TO_U8S_LE(_bcdUVC), U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VC_LEN + (TU_ARGS_NUM(__VA_ARGS__))), \
U32_TO_U8S_LE(_clkfreq), TU_ARGS_NUM(__VA_ARGS__), __VA_ARGS__
/* 3.7.2.1 */
#define TUD_VIDEO_DESC_INPUT_TERM(_tid, _tt, _at, _stridx) \
TUD_VIDEO_DESC_INPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_INPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(_tt), _at, _stridx
/* 3.7.2.2 */
#define TUD_VIDEO_DESC_OUTPUT_TERM(_tid, _tt, _at, _srcid, _stridx) \
TUD_VIDEO_DESC_OUTPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_OUTPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(_tt), _at, _srcid, _stridx
/* 3.7.2.3 */
#define TUD_VIDEO_DESC_CAMERA_TERM(_tid, _at, _stridx, _focal_min, _focal_max, _focal, _ctls) \
TUD_VIDEO_DESC_CAMERA_TERM_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VC_INPUT_TERMINAL, \
_tid, U16_TO_U8S_LE(VIDEO_ITT_CAMERA), _at, _stridx, \
U16_TO_U8S_LE(_focal_min), U16_TO_U8S_LE(_focal_max), U16_TO_U8S_LE(_focal), 3, \
TU_U32_BYTE0(_ctls), TU_U32_BYTE1(_ctls), TU_U32_BYTE2(_ctls)
/* 3.9.1 */
#define TUD_VIDEO_DESC_STD_VS(_itfnum, _alt, _epn, _stridx) \
TUD_VIDEO_DESC_STD_VS_LEN, TUSB_DESC_INTERFACE, _itfnum, _alt, \
_epn, TUSB_CLASS_VIDEO, VIDEO_SUBCLASS_STREAMING, VIDEO_ITF_PROTOCOL_15, _stridx
/* 3.9.2.1 */
#define TUD_VIDEO_DESC_CS_VS_INPUT(_numfmt, _totallen, _ep, _inf, _termlnk, _sticaptmeth, _trgspt, _trgusg, ...) \
TUD_VIDEO_DESC_CS_VS_IN_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, \
VIDEO_CS_ITF_VS_INPUT_HEADER, _numfmt, \
U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VS_IN_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__))), \
_ep, _inf, _termlnk, _sticaptmeth, _trgspt, _trgusg, (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* 3.9.2.2 */
#define TUD_VIDEO_DESC_CS_VS_OUTPUT(_numfmt, _totallen, _ep, _inf, _termlnk, ...) \
TUD_VIDEO_DESC_CS_VS_OUT_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__)), TUSB_DESC_CS_INTERFACE, \
VIDEO_CS_ITF_VS_OUTPUT_HEADER, _numfmt, \
U16_TO_U8S_LE((_totallen) + TUD_VIDEO_DESC_CS_VS_OUT_LEN + (_numfmt) * (TU_ARGS_NUM(__VA_ARGS__))), \
_ep, _inf, _termlnk, (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* Uncompressed 3.1.1 */
#define TUD_VIDEO_GUID(_g0,_g1,_g2,_g3,_g4,_g5,_g6,_g7,_g8,_g9,_g10,_g11,_g12,_g13,_g14,_g15) _g0,_g1,_g2,_g3,_g4,_g5,_g6,_g7,_g8,_g9,_g10,_g11,_g12,_g13,_g14,_g15
#define TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR(_fmtidx, _numfrmdesc, \
_guid, _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp) \
TUD_VIDEO_DESC_CS_VS_FMT_UNCOMPR_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FORMAT_UNCOMPRESSED, \
_fmtidx, _numfrmdesc, TUD_VIDEO_GUID(_guid), \
_bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp
/* Uncompressed 3.1.2 Table 3-3 */
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, _minfrminterval, _maxfrminterval, _frmintervalstep) \
TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_CONT_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED, \
_frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \
U32_TO_U8S_LE(_maxfrmbufsz), U32_TO_U8S_LE(_frminterval), 0, \
U32_TO_U8S_LE(_minfrminterval), U32_TO_U8S_LE(_maxfrminterval), U32_TO_U8S_LE(_frmintervalstep)
/* Uncompressed 3.1.2 Table 3-4 */
#define TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, ...) \
TUD_VIDEO_DESC_CS_VS_FRM_UNCOMPR_DISC_LEN + (TU_ARGS_NUM(__VA_ARGS__)) * 4, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_UNCOMPRESSED, \
_frmidx, _cap, U16_TO_U8S_LE(_width), U16_TO_U8S_LE(_height), U32_TO_U8S_LE(_minbr), U32_TO_U8S_LE(_maxbr), \
U32_TO_U8S_LE(_maxfrmbufsz), U32_TO_U8S_LE(_frminterval), (TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__
/* 3.9.2.6 */
#define TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING(_color, _trns, _mat) \
TUD_VIDEO_DESC_CS_VS_COLOR_MATCHING_LEN, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_COLORFORMAT, \
_color, _trns, _mat
/* 3.10.1.1 */
#define TUD_VIDEO_DESC_EP_ISO(_ep, _epsize, _ep_interval) \
7, TUSB_DESC_ENDPOINT, _ep, TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_ASYNCHRONOUS,\
U16_TO_U8S_LE(_epsize), _ep_interval
/* 3.10.1.2 */
#define TUD_VIDEO_DESC_EP_BULK(_ep, _epsize, _ep_interval) \
7, TUSB_DESC_ENDPOINT, _ep, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), _ep_interval
#endif

View File

@ -0,0 +1,97 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
* Copyright (c) 2021 Koji KITAYAMA
*
* 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.
*/
#ifndef TUSB_VIDEO_DEVICE_H_
#define TUSB_VIDEO_DEVICE_H_
#include "common/tusb_common.h"
#include "video.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Ports)
// CFG_TUD_VIDEO > 1
//--------------------------------------------------------------------+
/** Return true if streaming
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index */
bool tud_video_n_streaming(uint_fast8_t ctl_idx, uint_fast8_t stm_idx);
/** Transfer a frame
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @param[in] buffer Frame buffer. The caller must not use this buffer until the operation is completed.
* @param[in] bufsize Byte size of the frame buffer */
bool tud_video_n_frame_xfer(uint_fast8_t ctl_idx, uint_fast8_t stm_idx, void *buffer, size_t bufsize);
/*------------- Optional callbacks -------------*/
/** Invoked when compeletion of a frame transfer
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index */
TU_ATTR_WEAK void tud_video_frame_xfer_complete_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
/** Invoked when SET_POWER_MODE request received
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @return video_error_code_t */
TU_ATTR_WEAK int tud_video_power_mode_cb(uint_fast8_t ctl_idx, uint8_t power_mod);
/** Invoked when VS_COMMIT_CONTROL(SET_CUR) request received
*
* @param[in] ctl_idx Destination control interface index
* @param[in] stm_idx Destination streaming interface index
* @param[in] parameters Video streaming parameters
* @return video_error_code_t */
TU_ATTR_WEAK int tud_video_commit_cb(uint_fast8_t ctl_idx, uint_fast8_t stm_idx,
video_probe_and_commit_control_t const *parameters);
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void videod_init (void);
void videod_reset (uint8_t rhport);
uint16_t videod_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool videod_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool videod_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,262 @@
/*
* 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.
*/
#ifndef _TUSB_COMMON_H_
#define _TUSB_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Macros Helper
//--------------------------------------------------------------------+
#define TU_ARRAY_SIZE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) )
#define TU_MIN(_x, _y) ( ( (_x) < (_y) ) ? (_x) : (_y) )
#define TU_MAX(_x, _y) ( ( (_x) > (_y) ) ? (_x) : (_y) )
#define TU_U16(_high, _low) ((uint16_t) (((_high) << 8) | (_low)))
#define TU_U16_HIGH(_u16) ((uint8_t) (((_u16) >> 8) & 0x00ff))
#define TU_U16_LOW(_u16) ((uint8_t) ((_u16) & 0x00ff))
#define U16_TO_U8S_BE(_u16) TU_U16_HIGH(_u16), TU_U16_LOW(_u16)
#define U16_TO_U8S_LE(_u16) TU_U16_LOW(_u16), TU_U16_HIGH(_u16)
#define TU_U32_BYTE3(_u32) ((uint8_t) ((((uint32_t) _u32) >> 24) & 0x000000ff)) // MSB
#define TU_U32_BYTE2(_u32) ((uint8_t) ((((uint32_t) _u32) >> 16) & 0x000000ff))
#define TU_U32_BYTE1(_u32) ((uint8_t) ((((uint32_t) _u32) >> 8) & 0x000000ff))
#define TU_U32_BYTE0(_u32) ((uint8_t) (((uint32_t) _u32) & 0x000000ff)) // LSB
#define U32_TO_U8S_BE(_u32) TU_U32_BYTE3(_u32), TU_U32_BYTE2(_u32), TU_U32_BYTE1(_u32), TU_U32_BYTE0(_u32)
#define U32_TO_U8S_LE(_u32) TU_U32_BYTE0(_u32), TU_U32_BYTE1(_u32), TU_U32_BYTE2(_u32), TU_U32_BYTE3(_u32)
#define TU_BIT(n) (1UL << (n))
#define TU_GENMASK(h, l) ( (UINT32_MAX << (l)) & (UINT32_MAX >> (31 - (h))) )
//--------------------------------------------------------------------+
// Includes
//--------------------------------------------------------------------+
// Standard Headers
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
// Tinyusb Common Headers
#include "tusb_option.h"
#include "tusb_compiler.h"
#include "tusb_verify.h"
#include "tusb_types.h"
#include "tusb_debug.h"
#include "tusb_timeout.h" // TODO remove
//--------------------------------------------------------------------+
// Internal Inline Functions
//--------------------------------------------------------------------+
//------------- Mem -------------//
#define tu_memclr(buffer, size) memset((buffer), 0, (size))
#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var)))
//------------- Bytes -------------//
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_u32(uint8_t b3, uint8_t b2, uint8_t b1, uint8_t b0)
{
return ( ((uint32_t) b3) << 24) | ( ((uint32_t) b2) << 16) | ( ((uint32_t) b1) << 8) | b0;
}
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u16(uint8_t high, uint8_t low)
{
return (uint16_t) ((((uint16_t) high) << 8) | low);
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte3(uint32_t ui32) { return TU_U32_BYTE3(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte2(uint32_t ui32) { return TU_U32_BYTE2(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte1(uint32_t ui32) { return TU_U32_BYTE1(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u32_byte0(uint32_t ui32) { return TU_U32_BYTE0(ui32); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u32_high16(uint32_t ui32) { return (uint16_t) (ui32 >> 16); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_u32_low16 (uint32_t ui32) { return (uint16_t) (ui32 & 0x0000ffffu); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_high(uint16_t ui16) { return TU_U16_HIGH(ui16); }
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_u16_low (uint16_t ui16) { return TU_U16_LOW(ui16); }
//------------- Bits -------------//
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_bit_set (uint32_t value, uint8_t pos) { return value | TU_BIT(pos); }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_bit_clear(uint32_t value, uint8_t pos) { return value & (~TU_BIT(pos)); }
TU_ATTR_ALWAYS_INLINE static inline bool tu_bit_test (uint32_t value, uint8_t pos) { return (value & TU_BIT(pos)) ? true : false; }
//------------- Min -------------//
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_min8 (uint8_t x, uint8_t y ) { return (x < y) ? x : y; }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_min16 (uint16_t x, uint16_t y) { return (x < y) ? x : y; }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_min32 (uint32_t x, uint32_t y) { return (x < y) ? x : y; }
//------------- Max -------------//
TU_ATTR_ALWAYS_INLINE static inline uint8_t tu_max8 (uint8_t x, uint8_t y ) { return (x > y) ? x : y; }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_max16 (uint16_t x, uint16_t y) { return (x > y) ? x : y; }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_max32 (uint32_t x, uint32_t y) { return (x > y) ? x : y; }
//------------- Align -------------//
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_align(uint32_t value, uint32_t alignment)
{
return value & ((uint32_t) ~(alignment-1));
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); }
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); }
//------------- Mathematics -------------//
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_div_ceil(uint32_t v, uint32_t d) { return (v + d -1)/d; }
/// inclusive range checking TODO remove
TU_ATTR_ALWAYS_INLINE static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper)
{
return (lower <= value) && (value <= upper);
}
// log2 of a value is its MSB's position
// TODO use clz TODO remove
static inline uint8_t tu_log2(uint32_t value)
{
uint8_t result = 0;
while (value >>= 1) { result++; }
return result;
}
//------------- Unaligned Access -------------//
#if TUP_ARCH_STRICT_ALIGN
// Rely on compiler to generate correct code for unaligned access
typedef struct { uint16_t val; } TU_ATTR_PACKED tu_unaligned_uint16_t;
typedef struct { uint32_t val; } TU_ATTR_PACKED tu_unaligned_uint32_t;
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32(const void* mem)
{
tu_unaligned_uint32_t const* ua32 = (tu_unaligned_uint32_t const*) mem;
return ua32->val;
}
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32(void* mem, uint32_t value)
{
tu_unaligned_uint32_t* ua32 = (tu_unaligned_uint32_t*) mem;
ua32->val = value;
}
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16(const void* mem)
{
tu_unaligned_uint16_t const* ua16 = (tu_unaligned_uint16_t const*) mem;
return ua16->val;
}
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16(void* mem, uint16_t value)
{
tu_unaligned_uint16_t* ua16 = (tu_unaligned_uint16_t*) mem;
ua16->val = value;
}
#elif TUP_MCU_STRICT_ALIGN
// MCU such as LPC_IP3511 Highspeed cannot access unaligned memory on USB_RAM although it is ARM M4.
// We have to manually pick up bytes since tu_unaligned_uint32_t will still generate unaligned code
// NOTE: volatile cast to memory to prevent compiler to optimize and generate unaligned code
// TODO Big Endian may need minor changes
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32(const void* mem)
{
volatile uint8_t const* buf8 = (uint8_t const*) mem;
return tu_u32(buf8[3], buf8[2], buf8[1], buf8[0]);
}
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32(void* mem, uint32_t value)
{
volatile uint8_t* buf8 = (uint8_t*) mem;
buf8[0] = tu_u32_byte0(value);
buf8[1] = tu_u32_byte1(value);
buf8[2] = tu_u32_byte2(value);
buf8[3] = tu_u32_byte3(value);
}
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16(const void* mem)
{
volatile uint8_t const* buf8 = (uint8_t const*) mem;
return tu_u16(buf8[1], buf8[0]);
}
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16(void* mem, uint16_t value)
{
volatile uint8_t* buf8 = (uint8_t*) mem;
buf8[0] = tu_u16_low(value);
buf8[1] = tu_u16_high(value);
}
#else
// MCU that could access unaligned memory natively
TU_ATTR_ALWAYS_INLINE static inline uint32_t tu_unaligned_read32 (const void* mem) { return *((uint32_t const *) mem); }
TU_ATTR_ALWAYS_INLINE static inline uint16_t tu_unaligned_read16 (const void* mem) { return *((uint16_t const *) mem); }
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write32 (void* mem, uint32_t value ) { *((uint32_t*) mem) = value; }
TU_ATTR_ALWAYS_INLINE static inline void tu_unaligned_write16 (void* mem, uint16_t value ) { *((uint16_t*) mem) = value; }
#endif
// To be removed
//------------- Binary constant -------------//
#if defined(__GNUC__) && !defined(__CC_ARM)
#define TU_BIN8(x) ((uint8_t) (0b##x))
#define TU_BIN16(b1, b2) ((uint16_t) (0b##b1##b2))
#define TU_BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
#else
// internal macro of B8, B16, B32
#define _B8__(x) (((x&0x0000000FUL)?1:0) \
+((x&0x000000F0UL)?2:0) \
+((x&0x00000F00UL)?4:0) \
+((x&0x0000F000UL)?8:0) \
+((x&0x000F0000UL)?16:0) \
+((x&0x00F00000UL)?32:0) \
+((x&0x0F000000UL)?64:0) \
+((x&0xF0000000UL)?128:0))
#define TU_BIN8(d) ((uint8_t) _B8__(0x##d##UL))
#define TU_BIN16(dmsb,dlsb) (((uint16_t)TU_BIN8(dmsb)<<8) + TU_BIN8(dlsb))
#define TU_BIN32(dmsb,db2,db3,dlsb) \
(((uint32_t)TU_BIN8(dmsb)<<24) \
+ ((uint32_t)TU_BIN8(db2)<<16) \
+ ((uint32_t)TU_BIN8(db3)<<8) \
+ TU_BIN8(dlsb))
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_COMMON_H_ */

View File

@ -0,0 +1,264 @@
/*
* 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_Common
* \defgroup Group_Compiler Compiler
* \brief Group_Compiler brief
* @{ */
#ifndef _TUSB_COMPILER_H_
#define _TUSB_COMPILER_H_
#define TU_TOKEN(x) x
#define TU_STRING(x) #x ///< stringify without expand
#define TU_XSTRING(x) TU_STRING(x) ///< expand then stringify
#define TU_STRCAT(a, b) a##b ///< concat without expand
#define TU_STRCAT3(a, b, c) a##b##c ///< concat without expand
#define TU_XSTRCAT(a, b) TU_STRCAT(a, b) ///< expand then concat
#define TU_XSTRCAT3(a, b, c) TU_STRCAT3(a, b, c) ///< expand then concat 3 tokens
#define TU_INCLUDE_PATH(_dir,_file) TU_XSTRING( TU_TOKEN(_dir)TU_TOKEN(_file) )
#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
#define _TU_COUNTER_ __COUNTER__
#else
#define _TU_COUNTER_ __LINE__
#endif
// Compile-time Assert
#if defined (__cplusplus) && __cplusplus >= 201103L
#define TU_VERIFY_STATIC static_assert
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
#define TU_VERIFY_STATIC _Static_assert
#elif defined(__CCRX__)
#define TU_VERIFY_STATIC(const_expr, _mess) typedef char TU_XSTRCAT(Line, __LINE__)[(const_expr) ? 1 : 0];
#else
#define TU_VERIFY_STATIC(const_expr, _mess) enum { TU_XSTRCAT(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) }
#endif
// for declaration of reserved field, make use of _TU_COUNTER_
#define TU_RESERVED TU_XSTRCAT(reserved, _TU_COUNTER_)
#define TU_LITTLE_ENDIAN (0x12u)
#define TU_BIG_ENDIAN (0x21u)
/*------------------------------------------------------------------*/
/* Count number of arguments of __VA_ARGS__
* - reference https://stackoverflow.com/questions/2124339/c-preprocessor-va-args-number-of-arguments
* - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th)
* - _RSEQ_N() is reverse sequential to N to add padding to have
* Nth position is the same as the number of arguments
* - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma)
*------------------------------------------------------------------*/
#if !defined(__CCRX__)
#define TU_ARGS_NUM(...) _TU_NARG(_0, ##__VA_ARGS__,_RSEQ_N())
#else
#define TU_ARGS_NUM(...) _TU_NARG(_0, __VA_ARGS__,_RSEQ_N())
#endif
#define _TU_NARG(...) _GET_NTH_ARG(__VA_ARGS__)
#define _GET_NTH_ARG( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define _RSEQ_N() \
62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
// Apply an macro X to each of the arguments with an separated of choice
#define TU_ARGS_APPLY(_X, _s, ...) TU_XSTRCAT(_TU_ARGS_APPLY_, TU_ARGS_NUM(__VA_ARGS__))(_X, _s, __VA_ARGS__)
#define _TU_ARGS_APPLY_1(_X, _s, _a1) _X(_a1)
#define _TU_ARGS_APPLY_2(_X, _s, _a1, _a2) _X(_a1) _s _X(_a2)
#define _TU_ARGS_APPLY_3(_X, _s, _a1, _a2, _a3) _X(_a1) _s _TU_ARGS_APPLY_2(_X, _s, _a2, _a3)
#define _TU_ARGS_APPLY_4(_X, _s, _a1, _a2, _a3, _a4) _X(_a1) _s _TU_ARGS_APPLY_3(_X, _s, _a2, _a3, _a4)
#define _TU_ARGS_APPLY_5(_X, _s, _a1, _a2, _a3, _a4, _a5) _X(_a1) _s _TU_ARGS_APPLY_4(_X, _s, _a2, _a3, _a4, _a5)
#define _TU_ARGS_APPLY_6(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6) _X(_a1) _s _TU_ARGS_APPLY_5(_X, _s, _a2, _a3, _a4, _a5, _a6)
#define _TU_ARGS_APPLY_7(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6, _a7) _X(_a1) _s _TU_ARGS_APPLY_6(_X, _s, _a2, _a3, _a4, _a5, _a6, _a7)
#define _TU_ARGS_APPLY_8(_X, _s, _a1, _a2, _a3, _a4, _a5, _a6, _a7, _a8) _X(_a1) _s _TU_ARGS_APPLY_7(_X, _s, _a2, _a3, _a4, _a5, _a6, _a7, _a8)
//--------------------------------------------------------------------+
// Compiler porting with Attribute and Endian
//--------------------------------------------------------------------+
// TODO refactor since __attribute__ is supported across many compiler
#if defined(__GNUC__)
#define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes)))
#define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name)))
#define TU_ATTR_PACKED __attribute__ ((packed))
#define TU_ATTR_WEAK __attribute__ ((weak))
#define TU_ATTR_ALWAYS_INLINE __attribute__ ((always_inline))
#define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used
#define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused
#define TU_ATTR_USED __attribute__ ((used)) // Function/Variable is meant to be used
#define TU_ATTR_PACKED_BEGIN
#define TU_ATTR_PACKED_END
#define TU_ATTR_BIT_FIELD_ORDER_BEGIN
#define TU_ATTR_BIT_FIELD_ORDER_END
// Endian conversion use well-known host to network (big endian) naming
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
#endif
#define TU_BSWAP16(u16) (__builtin_bswap16(u16))
#define TU_BSWAP32(u32) (__builtin_bswap32(u32))
#ifndef __ARMCC_VERSION
// List of obsolete callback function that is renamed and should not be defined.
// Put it here since only gcc support this pragma
#pragma GCC poison tud_vendor_control_request_cb
#endif
#elif defined(__TI_COMPILER_VERSION__)
#define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes)))
#define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name)))
#define TU_ATTR_PACKED __attribute__ ((packed))
#define TU_ATTR_WEAK __attribute__ ((weak))
#define TU_ATTR_ALWAYS_INLINE __attribute__ ((always_inline))
#define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used
#define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused
#define TU_ATTR_USED __attribute__ ((used))
#define TU_ATTR_PACKED_BEGIN
#define TU_ATTR_PACKED_END
#define TU_ATTR_BIT_FIELD_ORDER_BEGIN
#define TU_ATTR_BIT_FIELD_ORDER_END
// __BYTE_ORDER is defined in the TI ARM compiler, but not MSP430 (which is little endian)
#if ((__BYTE_ORDER__) == (__ORDER_LITTLE_ENDIAN__)) || defined(__MSP430__)
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
#endif
#define TU_BSWAP16(u16) (__builtin_bswap16(u16))
#define TU_BSWAP32(u32) (__builtin_bswap32(u32))
#elif defined(__ICCARM__)
#include <intrinsics.h>
#define TU_ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes)))
#define TU_ATTR_SECTION(sec_name) __attribute__ ((section(#sec_name)))
#define TU_ATTR_PACKED __attribute__ ((packed))
#define TU_ATTR_WEAK __attribute__ ((weak))
#define TU_ATTR_ALWAYS_INLINE __attribute__ ((always_inline))
#define TU_ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess))) // warn if function with this attribute is used
#define TU_ATTR_UNUSED __attribute__ ((unused)) // Function/Variable is meant to be possibly unused
#define TU_ATTR_USED __attribute__ ((used)) // Function/Variable is meant to be used
#define TU_ATTR_PACKED_BEGIN
#define TU_ATTR_PACKED_END
#define TU_ATTR_BIT_FIELD_ORDER_BEGIN
#define TU_ATTR_BIT_FIELD_ORDER_END
// Endian conversion use well-known host to network (big endian) naming
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
#endif
#define TU_BSWAP16(u16) (__iar_builtin_REV16(u16))
#define TU_BSWAP32(u32) (__iar_builtin_REV(u32))
#elif defined(__CCRX__)
#define TU_ATTR_ALIGNED(Bytes)
#define TU_ATTR_SECTION(sec_name)
#define TU_ATTR_PACKED
#define TU_ATTR_WEAK
#define TU_ATTR_ALWAYS_INLINE
#define TU_ATTR_DEPRECATED(mess)
#define TU_ATTR_UNUSED
#define TU_ATTR_USED
#define TU_ATTR_PACKED_BEGIN _Pragma("pack")
#define TU_ATTR_PACKED_END _Pragma("packoption")
#define TU_ATTR_BIT_FIELD_ORDER_BEGIN _Pragma("bit_order right")
#define TU_ATTR_BIT_FIELD_ORDER_END _Pragma("bit_order")
// Endian conversion use well-known host to network (big endian) naming
#if defined(__LIT)
#define TU_BYTE_ORDER TU_LITTLE_ENDIAN
#else
#define TU_BYTE_ORDER TU_BIG_ENDIAN
#endif
#define TU_BSWAP16(u16) ((unsigned short)_builtin_revw((unsigned long)u16))
#define TU_BSWAP32(u32) (_builtin_revl(u32))
#else
#error "Compiler attribute porting is required"
#endif
#if (TU_BYTE_ORDER == TU_LITTLE_ENDIAN)
#define tu_htons(u16) (TU_BSWAP16(u16))
#define tu_ntohs(u16) (TU_BSWAP16(u16))
#define tu_htonl(u32) (TU_BSWAP32(u32))
#define tu_ntohl(u32) (TU_BSWAP32(u32))
#define tu_htole16(u16) (u16)
#define tu_le16toh(u16) (u16)
#define tu_htole32(u32) (u32)
#define tu_le32toh(u32) (u32)
#elif (TU_BYTE_ORDER == TU_BIG_ENDIAN)
#define tu_htons(u16) (u16)
#define tu_ntohs(u16) (u16)
#define tu_htonl(u32) (u32)
#define tu_ntohl(u32) (u32)
#define tu_htole16(u16) (TU_BSWAP16(u16))
#define tu_le16toh(u16) (TU_BSWAP16(u16))
#define tu_htole32(u32) (TU_BSWAP32(u32))
#define tu_le32toh(u32) (TU_BSWAP32(u32))
#else
#error Byte order is undefined
#endif
#endif /* _TUSB_COMPILER_H_ */
/// @}

View File

@ -0,0 +1,174 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2022, 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.
*/
#ifndef _TUSB_DEBUG_H_
#define _TUSB_DEBUG_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Debug
//--------------------------------------------------------------------+
// CFG_TUSB_DEBUG for debugging
// 0 : no debug
// 1 : print error
// 2 : print warning
// 3 : print info
#if CFG_TUSB_DEBUG
// Enum to String for debugging purposes
#if CFG_TUSB_DEBUG >= 2
extern char const* const tu_str_speed[];
extern char const* const tu_str_std_request[];
#endif
void tu_print_mem(void const *buf, uint32_t count, uint8_t indent);
#ifdef CFG_TUSB_DEBUG_PRINTF
extern int CFG_TUSB_DEBUG_PRINTF(const char *format, ...);
#define tu_printf CFG_TUSB_DEBUG_PRINTF
#else
#define tu_printf printf
#endif
static inline void tu_print_var(uint8_t const* buf, uint32_t bufsize)
{
for(uint32_t i=0; i<bufsize; i++) tu_printf("%02X ", buf[i]);
}
// Log with Level
#define TU_LOG(n, ...) TU_XSTRCAT(TU_LOG, n)(__VA_ARGS__)
#define TU_LOG_MEM(n, ...) TU_XSTRCAT3(TU_LOG, n, _MEM)(__VA_ARGS__)
#define TU_LOG_VAR(n, ...) TU_XSTRCAT3(TU_LOG, n, _VAR)(__VA_ARGS__)
#define TU_LOG_INT(n, ...) TU_XSTRCAT3(TU_LOG, n, _INT)(__VA_ARGS__)
#define TU_LOG_HEX(n, ...) TU_XSTRCAT3(TU_LOG, n, _HEX)(__VA_ARGS__)
#define TU_LOG_LOCATION() tu_printf("%s: %d:\r\n", __PRETTY_FUNCTION__, __LINE__)
#define TU_LOG_FAILED() tu_printf("%s: %d: Failed\r\n", __PRETTY_FUNCTION__, __LINE__)
// Log Level 1: Error
#define TU_LOG1 tu_printf
#define TU_LOG1_MEM tu_print_mem
#define TU_LOG1_VAR(_x) tu_print_var((uint8_t const*)(_x), sizeof(*(_x)))
#define TU_LOG1_INT(_x) tu_printf(#_x " = %ld\r\n", (unsigned long) (_x) )
#define TU_LOG1_HEX(_x) tu_printf(#_x " = %lX\r\n", (unsigned long) (_x) )
// Log Level 2: Warn
#if CFG_TUSB_DEBUG >= 2
#define TU_LOG2 TU_LOG1
#define TU_LOG2_MEM TU_LOG1_MEM
#define TU_LOG2_VAR TU_LOG1_VAR
#define TU_LOG2_INT TU_LOG1_INT
#define TU_LOG2_HEX TU_LOG1_HEX
#endif
// Log Level 3: Info
#if CFG_TUSB_DEBUG >= 3
#define TU_LOG3 TU_LOG1
#define TU_LOG3_MEM TU_LOG1_MEM
#define TU_LOG3_VAR TU_LOG1_VAR
#define TU_LOG3_INT TU_LOG1_INT
#define TU_LOG3_HEX TU_LOG1_HEX
#endif
typedef struct
{
uint32_t key;
const char* data;
} tu_lookup_entry_t;
typedef struct
{
uint16_t count;
tu_lookup_entry_t const* items;
} tu_lookup_table_t;
static inline const char* tu_lookup_find(tu_lookup_table_t const* p_table, uint32_t key)
{
static char not_found[11];
for(uint16_t i=0; i<p_table->count; i++)
{
if (p_table->items[i].key == key) return p_table->items[i].data;
}
// not found return the key value in hex
snprintf(not_found, sizeof(not_found), "0x%08lX", (unsigned long) key);
return not_found;
}
#endif // CFG_TUSB_DEBUG
#ifndef TU_LOG
#define TU_LOG(n, ...)
#define TU_LOG_MEM(n, ...)
#define TU_LOG_VAR(n, ...)
#define TU_LOG_INT(n, ...)
#define TU_LOG_HEX(n, ...)
#define TU_LOG_LOCATION()
#define TU_LOG_FAILED()
#endif
// TODO replace all TU_LOGn with TU_LOG(n)
#define TU_LOG0(...)
#define TU_LOG0_MEM(...)
#define TU_LOG0_VAR(...)
#define TU_LOG0_INT(...)
#define TU_LOG0_HEX(...)
#ifndef TU_LOG1
#define TU_LOG1(...)
#define TU_LOG1_MEM(...)
#define TU_LOG1_VAR(...)
#define TU_LOG1_INT(...)
#define TU_LOG1_HEX(...)
#endif
#ifndef TU_LOG2
#define TU_LOG2(...)
#define TU_LOG2_MEM(...)
#define TU_LOG2_VAR(...)
#define TU_LOG2_INT(...)
#define TU_LOG2_HEX(...)
#endif
#ifndef TU_LOG3
#define TU_LOG3(...)
#define TU_LOG3_MEM(...)
#define TU_LOG3_VAR(...)
#define TU_LOG3_INT(...)
#define TU_LOG3_HEX(...)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DEBUG_H_ */

View File

@ -0,0 +1,151 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
* Copyright (c) 2020 Reinhard Panhuber - rework to unmasked pointers
*
* 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.
*/
#ifndef _TUSB_FIFO_H_
#define _TUSB_FIFO_H_
#ifdef __cplusplus
extern "C" {
#endif
// Due to the use of unmasked pointers, this FIFO does not suffer from loosing
// one item slice. Furthermore, write and read operations are completely
// decoupled as write and read functions do not modify a common state. Henceforth,
// writing or reading from the FIFO within an ISR is safe as long as no other
// process (thread or ISR) interferes.
// Also, this FIFO is ready to be used in combination with a DMA as the write and
// read pointers can be updated from within a DMA ISR. Overflows are detectable
// within a certain number (see tu_fifo_overflow()).
#include "common/tusb_common.h"
// mutex is only needed for RTOS
// for OS None, we don't get preempted
#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE)
#if CFG_FIFO_MUTEX
#include "osal/osal.h"
#define tu_fifo_mutex_t osal_mutex_t
#endif
typedef struct
{
uint8_t* buffer ; ///< buffer pointer
uint16_t depth ; ///< max items
uint16_t item_size ; ///< size of each item
bool overwritable ;
uint16_t non_used_index_space ; ///< required for non-power-of-two buffer length
uint16_t max_pointer_idx ; ///< maximum absolute pointer index
volatile uint16_t wr_idx ; ///< write pointer
volatile uint16_t rd_idx ; ///< read pointer
#if CFG_FIFO_MUTEX
tu_fifo_mutex_t mutex_wr;
tu_fifo_mutex_t mutex_rd;
#endif
} tu_fifo_t;
typedef struct
{
uint16_t len_lin ; ///< linear length in item size
uint16_t len_wrap ; ///< wrapped length in item size
void * ptr_lin ; ///< linear part start pointer
void * ptr_wrap ; ///< wrapped part start pointer
} tu_fifo_buffer_info_t;
#define TU_FIFO_INIT(_buffer, _depth, _type, _overwritable) \
{ \
.buffer = _buffer, \
.depth = _depth, \
.item_size = sizeof(_type), \
.overwritable = _overwritable, \
.non_used_index_space = UINT16_MAX - (2*(_depth)-1), \
.max_pointer_idx = 2*(_depth)-1, \
}
#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) \
uint8_t _name##_buf[_depth*sizeof(_type)]; \
tu_fifo_t _name = TU_FIFO_INIT(_name##_buf, _depth, _type, _overwritable)
bool tu_fifo_set_overwritable(tu_fifo_t *f, bool overwritable);
bool tu_fifo_clear(tu_fifo_t *f);
bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable);
#if CFG_FIFO_MUTEX
TU_ATTR_ALWAYS_INLINE static inline
void tu_fifo_config_mutex(tu_fifo_t *f, tu_fifo_mutex_t write_mutex_hdl, tu_fifo_mutex_t read_mutex_hdl)
{
f->mutex_wr = write_mutex_hdl;
f->mutex_rd = read_mutex_hdl;
}
#endif
bool tu_fifo_write (tu_fifo_t* f, void const * p_data);
uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t n);
uint16_t tu_fifo_write_n_const_addr_full_words (tu_fifo_t* f, const void * data, uint16_t n);
bool tu_fifo_read (tu_fifo_t* f, void * p_buffer);
uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t n);
uint16_t tu_fifo_read_n_const_addr_full_words (tu_fifo_t* f, void * buffer, uint16_t n);
bool tu_fifo_peek (tu_fifo_t* f, void * p_buffer);
uint16_t tu_fifo_peek_n (tu_fifo_t* f, void * p_buffer, uint16_t n);
uint16_t tu_fifo_count (tu_fifo_t* f);
uint16_t tu_fifo_remaining (tu_fifo_t* f);
bool tu_fifo_empty (tu_fifo_t* f);
bool tu_fifo_full (tu_fifo_t* f);
bool tu_fifo_overflowed (tu_fifo_t* f);
void tu_fifo_correct_read_pointer (tu_fifo_t* f);
TU_ATTR_ALWAYS_INLINE static inline
uint16_t tu_fifo_depth(tu_fifo_t* f)
{
return f->depth;
}
// Pointer modifications intended to be used in combinations with DMAs.
// USE WITH CARE - NO SAFTY CHECKS CONDUCTED HERE! NOT MUTEX PROTECTED!
void tu_fifo_advance_write_pointer(tu_fifo_t *f, uint16_t n);
void tu_fifo_advance_read_pointer (tu_fifo_t *f, uint16_t n);
// If you want to read/write from/to the FIFO by use of a DMA, you may need to conduct two copies
// to handle a possible wrapping part. These functions deliver a pointer to start
// reading/writing from/to and a valid linear length along which no wrap occurs.
void tu_fifo_get_read_info (tu_fifo_t *f, tu_fifo_buffer_info_t *info);
void tu_fifo_get_write_info(tu_fifo_t *f, tu_fifo_buffer_info_t *info);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_FIFO_H_ */

View File

@ -0,0 +1,285 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef TUSB_MCU_H_
#define TUSB_MCU_H_
//--------------------------------------------------------------------+
// Port Specific
// TUP stand for TinyUSB Port (can be renamed)
//--------------------------------------------------------------------+
//------------- Unaligned Memory Access -------------//
// ARMv7+ (M3-M7, M23-M33) can access unaligned memory
#if (defined(__ARM_ARCH) && (__ARM_ARCH >= 7))
#define TUP_ARCH_STRICT_ALIGN 0
#else
#define TUP_ARCH_STRICT_ALIGN 1
#endif
/* USB Controller Attributes for Device, Host or MCU (both)
* - ENDPOINT_MAX: max (logical) number of endpoint
* - ENDPOINT_EXCLUSIVE_NUMBER: endpoint number with different direction IN and OUT aren't allowed,
* e.g EP1 OUT & EP1 IN cannot exist together
* - RHPORT_HIGHSPEED: mask to indicate which port support highspeed mode (without external PHY)
* bit0 for port0 and so on.
*/
//------------- NXP -------------//
#if TU_CHECK_MCU(OPT_MCU_LPC11UXX, OPT_MCU_LPC13XX, OPT_MCU_LPC15XX)
#define TUP_DCD_ENDPOINT_MAX 5
#elif TU_CHECK_MCU(OPT_MCU_LPC175X_6X, OPT_MCU_LPC177X_8X, OPT_MCU_LPC40XX)
#define TUP_DCD_ENDPOINT_MAX 16
#define TUP_USBIP_OHCI
#elif TU_CHECK_MCU(OPT_MCU_LPC18XX, OPT_MCU_LPC43XX)
// TODO USB0 has 6, USB1 has 4
#define TUP_USBIP_CHIPIDEA_HS
#define TUP_USBIP_EHCI
#define TUP_DCD_ENDPOINT_MAX 6
#define TUP_RHPORT_HIGHSPEED 0x01 // Port0 HS, Port1 FS
#elif TU_CHECK_MCU(OPT_MCU_LPC51UXX)
#define TUP_DCD_ENDPOINT_MAX 5
#elif TU_CHECK_MCU(OPT_MCU_LPC54XXX)
// TODO USB0 has 5, USB1 has 6
#define TUP_DCD_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_LPC55XX)
// TODO USB0 has 5, USB1 has 6
#define TUP_DCD_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_MIMXRT10XX)
#define TUP_USBIP_CHIPIDEA_HS
#define TUP_USBIP_EHCI
#define TUP_DCD_ENDPOINT_MAX 8
#define TUP_RHPORT_HIGHSPEED 0x03 // Port0 HS, Port1 HS
#elif TU_CHECK_MCU(OPT_MCU_MKL25ZXX, OPT_MCU_K32L2BXX)
#define TUP_DCD_ENDPOINT_MAX 16
#elif TU_CHECK_MCU(OPT_MCU_MM32F327X)
#define TUP_DCD_ENDPOINT_MAX 16
//------------- Nordic -------------//
#elif TU_CHECK_MCU(OPT_MCU_NRF5X)
// 8 CBI + 1 ISO
#define TUP_DCD_ENDPOINT_MAX 9
//------------- Microchip -------------//
#elif TU_CHECK_MCU(OPT_MCU_SAMD21, OPT_MCU_SAMD51, OPT_MCU_SAME5X) || \
TU_CHECK_MCU(OPT_MCU_SAMD11, OPT_MCU_SAML21, OPT_MCU_SAML22)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_SAMG)
#define TUP_DCD_ENDPOINT_MAX 6
#define TUP_DCD_ENDPOINT_EXCLUSIVE_NUMBER
#elif TU_CHECK_MCU(OPT_MCU_SAMX7X)
#define TUP_DCD_ENDPOINT_MAX 10
#define TUP_RHPORT_HIGHSPEED 0x01
#define TUP_DCD_ENDPOINT_EXCLUSIVE_NUMBER
#elif TU_CHECK_MCU(OPT_MCU_PIC32MZ)
#define TUP_DCD_ENDPOINT_MAX 8
#define TUP_DCD_ENDPOINT_EXCLUSIVE_NUMBER
//------------- ST -------------//
#elif TU_CHECK_MCU(OPT_MCU_STM32F0)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32F1)
#if defined (STM32F105x8) || defined (STM32F105xB) || defined (STM32F105xC) || \
defined (STM32F107xB) || defined (STM32F107xC)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
#define TUP_DCD_ENDPOINT_MAX 4
#else
#define TUP_DCD_ENDPOINT_MAX 8
#endif
#elif TU_CHECK_MCU(OPT_MCU_STM32F2)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
// FS has 4 ep, HS has 5 ep
#define TUP_DCD_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_STM32F3)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32F4)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
// For most mcu, FS has 4, HS has 6. TODO 446/469/479 HS has 9
#define TUP_DCD_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_STM32F7)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
// FS has 6, HS has 9
#define TUP_DCD_ENDPOINT_MAX 9
// MCU with on-chip HS Phy
#if defined(STM32F723xx) || defined(STM32F730xx) || defined(STM32F733xx)
#define TUP_RHPORT_HIGHSPEED 0x02 // Port 0: FS, Port 1: HS
#endif
#elif TU_CHECK_MCU(OPT_MCU_STM32H7)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
#define TUP_DCD_ENDPOINT_MAX 9
#elif TU_CHECK_MCU(OPT_MCU_STM32G4)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32L0, OPT_MCU_STM32L1)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_STM32L4)
#if defined (STM32L475xx) || defined (STM32L476xx) || \
defined (STM32L485xx) || defined (STM32L486xx) || defined (STM32L496xx) || \
defined (STM32L4A6xx) || defined (STM32L4P5xx) || defined (STM32L4Q5xx) || \
defined (STM32L4R5xx) || defined (STM32L4R7xx) || defined (STM32L4R9xx) || \
defined (STM32L4S5xx) || defined (STM32L4S7xx) || defined (STM32L4S9xx)
#define TUP_USBIP_DWC2
#define TUP_USBIP_DWC2_STM32
#define TUP_DCD_ENDPOINT_MAX 6
#else
#define TUP_DCD_ENDPOINT_MAX 8
#endif
#elif TU_CHECK_MCU(OPT_MCU_STM32WB)
#define TUP_DCD_ENDPOINT_MAX 8
//------------- Sony -------------//
#elif TU_CHECK_MCU(OPT_MCU_CXD56)
#define TUP_DCD_ENDPOINT_MAX 7
#define TUP_RHPORT_HIGHSPEED 0x01
#define TUP_DCD_ENDPOINT_EXCLUSIVE_NUMBER
//------------- TI -------------//
#elif TU_CHECK_MCU(OPT_MCU_MSP430x5xx)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_MSP432E4, OPT_MCU_TM4C123, OPT_MCU_TM4C129)
#define TUP_DCD_ENDPOINT_MAX 8
//------------- ValentyUSB -------------//
#elif TU_CHECK_MCU(OPT_MCU_VALENTYUSB_EPTRI)
#define TUP_DCD_ENDPOINT_MAX 16
//------------- Nuvoton -------------//
#elif TU_CHECK_MCU(OPT_MCU_NUC121, OPT_MCU_NUC126)
#define TUP_DCD_ENDPOINT_MAX 8
#elif TU_CHECK_MCU(OPT_MCU_NUC120)
#define TUP_DCD_ENDPOINT_MAX 6
#elif TU_CHECK_MCU(OPT_MCU_NUC505)
#define TUP_DCD_ENDPOINT_MAX 12
#define TUP_RHPORT_HIGHSPEED 0x01
//------------- Espressif -------------//
#elif TU_CHECK_MCU(OPT_MCU_ESP32S2, OPT_MCU_ESP32S3)
#define TUP_USBIP_DWC2
#define TUP_DCD_ENDPOINT_MAX 6
//------------- Dialog -------------//
#elif TU_CHECK_MCU(OPT_MCU_DA1469X)
#define TUP_DCD_ENDPOINT_MAX 4
//------------- Raspberry Pi -------------//
#elif TU_CHECK_MCU(OPT_MCU_RP2040)
#define TUP_DCD_ENDPOINT_MAX 16
//------------- Silabs -------------//
#elif TU_CHECK_MCU(OPT_MCU_EFM32GG)
#define TUP_USBIP_DWC2
#define TUP_DCD_ENDPOINT_MAX 7
//------------- Renesas -------------//
#elif TU_CHECK_MCU(OPT_MCU_RX63X, OPT_MCU_RX65X, OPT_MCU_RX72N)
#define TUP_DCD_ENDPOINT_MAX 10
//------------- GigaDevice -------------//
#elif TU_CHECK_MCU(OPT_MCU_GD32VF103)
#define TUP_USBIP_DWC2
#define TUP_DCD_ENDPOINT_MAX 4
//------------- Broadcom -------------//
#elif TU_CHECK_MCU(OPT_MCU_BCM2711, OPT_MCU_BCM2835, OPT_MCU_BCM2837)
#define TUP_USBIP_DWC2
#define TUP_DCD_ENDPOINT_MAX 8
#define TUP_RHPORT_HIGHSPEED 0x01
//------------- Broadcom -------------//
#elif TU_CHECK_MCU(OPT_MCU_XMC4000)
#define TUP_USBIP_DWC2
#define TUP_DCD_ENDPOINT_MAX 8
//------------- BridgeTek -------------//
#elif TU_CHECK_MCU(OPT_MCU_FT90X)
#define TUP_DCD_ENDPOINT_MAX 8
#define TUP_RHPORT_HIGHSPEED 0x01
#elif TU_CHECK_MCU(OPT_MCU_FT93X)
#define TUP_DCD_ENDPOINT_MAX 16
#define TUP_RHPORT_HIGHSPEED 0x01
//------------ Allwinner -------------//
#elif TU_CHECK_MCU(OPT_MCU_F1C100S)
#define TUP_DCD_ENDPOINT_MAX 4
#endif
//--------------------------------------------------------------------+
// Default Values
//--------------------------------------------------------------------+
#ifndef TUP_DCD_ENDPOINT_MAX
#warning "TUP_DCD_ENDPOINT_MAX is not defined for this MCU, default to 8"
#define TUP_DCD_ENDPOINT_MAX 8
#endif
// Default to fullspeed if not defined
#ifndef TUP_RHPORT_HIGHSPEED
#define TUP_RHPORT_HIGHSPEED 0x00
#endif
#endif

View File

@ -0,0 +1,65 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2022, 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.
*/
#ifndef _TUSB_PRIVATE_H_
#define _TUSB_PRIVATE_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct TU_ATTR_PACKED
{
volatile uint8_t busy : 1;
volatile uint8_t stalled : 1;
volatile uint8_t claimed : 1;
}tu_edpt_state_t;
//--------------------------------------------------------------------+
// Internal Helper used by Host and Device Stack
//--------------------------------------------------------------------+
// Check if endpoint descriptor is valid per USB specs
bool tu_edpt_validate(tusb_desc_endpoint_t const * desc_ep, tusb_speed_t speed);
// Bind all endpoint of a interface descriptor to class driver
void tu_edpt_bind_driver(uint8_t ep2drv[][2], tusb_desc_interface_t const* p_desc, uint16_t desc_len, uint8_t driver_id);
// Calculate total length of n interfaces (depending on IAD)
uint16_t tu_desc_get_interface_total_len(tusb_desc_interface_t const* desc_itf, uint8_t itf_count, uint16_t max_len);
// Claim an endpoint with provided mutex
bool tu_edpt_claim(tu_edpt_state_t* ep_state, osal_mutex_t mutex);
// Release an endpoint with provided mutex
bool tu_edpt_release(tu_edpt_state_t* ep_state, osal_mutex_t mutex);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_PRIVATE_H_ */

View File

@ -0,0 +1,80 @@
/*
* 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_Common Common Files
* \defgroup Group_TimeoutTimer timeout timer
* @{ */
#ifndef _TUSB_TIMEOUT_H_
#define _TUSB_TIMEOUT_H_
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint32_t start;
uint32_t interval;
}tu_timeout_t;
#if 0
extern uint32_t tusb_hal_millis(void);
static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec)
{
tt->interval = msec;
tt->start = tusb_hal_millis();
}
static inline bool tu_timeout_expired(tu_timeout_t* tt)
{
return ( tusb_hal_millis() - tt->start ) >= tt->interval;
}
// For used with periodic event to prevent drift
static inline void tu_timeout_reset(tu_timeout_t* tt)
{
tt->start += tt->interval;
}
static inline void tu_timeout_restart(tu_timeout_t* tt)
{
tt->start = tusb_hal_millis();
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_TIMEOUT_H_ */
/** @} */

View File

@ -0,0 +1,541 @@
/*
* 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_usb_definitions
* \defgroup USBDef_Type USB Types
* @{ */
#ifndef _TUSB_TYPES_H_
#define _TUSB_TYPES_H_
#include <stdbool.h>
#include <stdint.h>
#include "tusb_compiler.h"
#ifdef __cplusplus
extern "C" {
#endif
/*------------------------------------------------------------------*/
/* CONSTANTS
*------------------------------------------------------------------*/
/// defined base on EHCI specs value for Endpoint Speed
typedef enum
{
TUSB_SPEED_FULL = 0,
TUSB_SPEED_LOW = 1,
TUSB_SPEED_HIGH = 2,
TUSB_SPEED_INVALID = 0xff,
}tusb_speed_t;
/// defined base on USB Specs Endpoint's bmAttributes
typedef enum
{
TUSB_XFER_CONTROL = 0 ,
TUSB_XFER_ISOCHRONOUS ,
TUSB_XFER_BULK ,
TUSB_XFER_INTERRUPT
}tusb_xfer_type_t;
typedef enum
{
TUSB_DIR_OUT = 0,
TUSB_DIR_IN = 1,
TUSB_DIR_IN_MASK = 0x80
}tusb_dir_t;
/// Isochronous End Point Attributes
typedef enum
{
TUSB_ISO_EP_ATT_NO_SYNC = 0x00,
TUSB_ISO_EP_ATT_ASYNCHRONOUS = 0x04,
TUSB_ISO_EP_ATT_ADAPTIVE = 0x08,
TUSB_ISO_EP_ATT_SYNCHRONOUS = 0x0C,
TUSB_ISO_EP_ATT_DATA = 0x00, ///< Data End Point
TUSB_ISO_EP_ATT_EXPLICIT_FB = 0x10, ///< Feedback End Point
TUSB_ISO_EP_ATT_IMPLICIT_FB = 0x20, ///< Data endpoint that also serves as an implicit feedback
}tusb_iso_ep_attribute_t;
/// USB Descriptor Types
typedef enum
{
TUSB_DESC_DEVICE = 0x01,
TUSB_DESC_CONFIGURATION = 0x02,
TUSB_DESC_STRING = 0x03,
TUSB_DESC_INTERFACE = 0x04,
TUSB_DESC_ENDPOINT = 0x05,
TUSB_DESC_DEVICE_QUALIFIER = 0x06,
TUSB_DESC_OTHER_SPEED_CONFIG = 0x07,
TUSB_DESC_INTERFACE_POWER = 0x08,
TUSB_DESC_OTG = 0x09,
TUSB_DESC_DEBUG = 0x0A,
TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B,
TUSB_DESC_BOS = 0x0F,
TUSB_DESC_DEVICE_CAPABILITY = 0x10,
TUSB_DESC_FUNCTIONAL = 0x21,
// Class Specific Descriptor
TUSB_DESC_CS_DEVICE = 0x21,
TUSB_DESC_CS_CONFIGURATION = 0x22,
TUSB_DESC_CS_STRING = 0x23,
TUSB_DESC_CS_INTERFACE = 0x24,
TUSB_DESC_CS_ENDPOINT = 0x25,
TUSB_DESC_SUPERSPEED_ENDPOINT_COMPANION = 0x30,
TUSB_DESC_SUPERSPEED_ISO_ENDPOINT_COMPANION = 0x31
}tusb_desc_type_t;
typedef enum
{
TUSB_REQ_GET_STATUS = 0 ,
TUSB_REQ_CLEAR_FEATURE = 1 ,
TUSB_REQ_RESERVED = 2 ,
TUSB_REQ_SET_FEATURE = 3 ,
TUSB_REQ_RESERVED2 = 4 ,
TUSB_REQ_SET_ADDRESS = 5 ,
TUSB_REQ_GET_DESCRIPTOR = 6 ,
TUSB_REQ_SET_DESCRIPTOR = 7 ,
TUSB_REQ_GET_CONFIGURATION = 8 ,
TUSB_REQ_SET_CONFIGURATION = 9 ,
TUSB_REQ_GET_INTERFACE = 10 ,
TUSB_REQ_SET_INTERFACE = 11 ,
TUSB_REQ_SYNCH_FRAME = 12
}tusb_request_code_t;
typedef enum
{
TUSB_REQ_FEATURE_EDPT_HALT = 0,
TUSB_REQ_FEATURE_REMOTE_WAKEUP = 1,
TUSB_REQ_FEATURE_TEST_MODE = 2
}tusb_request_feature_selector_t;
typedef enum
{
TUSB_REQ_TYPE_STANDARD = 0,
TUSB_REQ_TYPE_CLASS,
TUSB_REQ_TYPE_VENDOR,
TUSB_REQ_TYPE_INVALID
} tusb_request_type_t;
typedef enum
{
TUSB_REQ_RCPT_DEVICE =0,
TUSB_REQ_RCPT_INTERFACE,
TUSB_REQ_RCPT_ENDPOINT,
TUSB_REQ_RCPT_OTHER
} tusb_request_recipient_t;
// https://www.usb.org/defined-class-codes
typedef enum
{
TUSB_CLASS_UNSPECIFIED = 0 ,
TUSB_CLASS_AUDIO = 1 ,
TUSB_CLASS_CDC = 2 ,
TUSB_CLASS_HID = 3 ,
TUSB_CLASS_RESERVED_4 = 4 ,
TUSB_CLASS_PHYSICAL = 5 ,
TUSB_CLASS_IMAGE = 6 ,
TUSB_CLASS_PRINTER = 7 ,
TUSB_CLASS_MSC = 8 ,
TUSB_CLASS_HUB = 9 ,
TUSB_CLASS_CDC_DATA = 10 ,
TUSB_CLASS_SMART_CARD = 11 ,
TUSB_CLASS_RESERVED_12 = 12 ,
TUSB_CLASS_CONTENT_SECURITY = 13 ,
TUSB_CLASS_VIDEO = 14 ,
TUSB_CLASS_PERSONAL_HEALTHCARE = 15 ,
TUSB_CLASS_AUDIO_VIDEO = 16 ,
TUSB_CLASS_DIAGNOSTIC = 0xDC ,
TUSB_CLASS_WIRELESS_CONTROLLER = 0xE0 ,
TUSB_CLASS_MISC = 0xEF ,
TUSB_CLASS_APPLICATION_SPECIFIC = 0xFE ,
TUSB_CLASS_VENDOR_SPECIFIC = 0xFF
}tusb_class_code_t;
typedef enum
{
MISC_SUBCLASS_COMMON = 2
}misc_subclass_type_t;
typedef enum
{
MISC_PROTOCOL_IAD = 1
}misc_protocol_type_t;
typedef enum
{
APP_SUBCLASS_USBTMC = 0x03,
APP_SUBCLASS_DFU_RUNTIME = 0x01
} app_subclass_type_t;
typedef enum
{
DEVICE_CAPABILITY_WIRELESS_USB = 0x01,
DEVICE_CAPABILITY_USB20_EXTENSION = 0x02,
DEVICE_CAPABILITY_SUPERSPEED_USB = 0x03,
DEVICE_CAPABILITY_CONTAINER_id = 0x04,
DEVICE_CAPABILITY_PLATFORM = 0x05,
DEVICE_CAPABILITY_POWER_DELIVERY = 0x06,
DEVICE_CAPABILITY_BATTERY_INFO = 0x07,
DEVICE_CAPABILITY_PD_CONSUMER_PORT = 0x08,
DEVICE_CAPABILITY_PD_PROVIDER_PORT = 0x09,
DEVICE_CAPABILITY_SUPERSPEED_PLUS = 0x0A,
DEVICE_CAPABILITY_PRECESION_TIME_MEASUREMENT = 0x0B,
DEVICE_CAPABILITY_WIRELESS_USB_EXT = 0x0C,
DEVICE_CAPABILITY_BILLBOARD = 0x0D,
DEVICE_CAPABILITY_AUTHENTICATION = 0x0E,
DEVICE_CAPABILITY_BILLBOARD_EX = 0x0F,
DEVICE_CAPABILITY_CONFIGURATION_SUMMARY = 0x10
}device_capability_type_t;
enum {
TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = TU_BIT(5),
TUSB_DESC_CONFIG_ATT_SELF_POWERED = TU_BIT(6),
};
#define TUSB_DESC_CONFIG_POWER_MA(x) ((x)/2)
typedef enum
{
XFER_RESULT_SUCCESS,
XFER_RESULT_FAILED,
XFER_RESULT_STALLED,
XFER_RESULT_TIMEOUT,
XFER_RESULT_INVALID
}xfer_result_t;
enum // TODO remove
{
DESC_OFFSET_LEN = 0,
DESC_OFFSET_TYPE = 1
};
enum
{
INTERFACE_INVALID_NUMBER = 0xff
};
typedef enum
{
MS_OS_20_SET_HEADER_DESCRIPTOR = 0x00,
MS_OS_20_SUBSET_HEADER_CONFIGURATION = 0x01,
MS_OS_20_SUBSET_HEADER_FUNCTION = 0x02,
MS_OS_20_FEATURE_COMPATBLE_ID = 0x03,
MS_OS_20_FEATURE_REG_PROPERTY = 0x04,
MS_OS_20_FEATURE_MIN_RESUME_TIME = 0x05,
MS_OS_20_FEATURE_MODEL_ID = 0x06,
MS_OS_20_FEATURE_CCGP_DEVICE = 0x07,
MS_OS_20_FEATURE_VENDOR_REVISION = 0x08
} microsoft_os_20_type_t;
enum
{
CONTROL_STAGE_IDLE,
CONTROL_STAGE_SETUP,
CONTROL_STAGE_DATA,
CONTROL_STAGE_ACK
};
//--------------------------------------------------------------------+
// USB Descriptors
//--------------------------------------------------------------------+
// Start of all packed definitions for compiler without per-type packed
TU_ATTR_PACKED_BEGIN
TU_ATTR_BIT_FIELD_ORDER_BEGIN
/// USB Device Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< DEVICE Descriptor Type.
uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant.
uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific.
uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis.
uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64.
uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF).
uint16_t idProduct ; ///< Product ID (assigned by the manufacturer).
uint16_t bcdDevice ; ///< Device release number in binary-coded decimal.
uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer.
uint8_t iProduct ; ///< Index of string descriptor describing product.
uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number.
uint8_t bNumConfigurations ; ///< Number of possible configurations.
} tusb_desc_device_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_device_t) == 18, "size is not correct");
// USB Binary Device Object Store (BOS) Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type
uint16_t wTotalLength ; ///< Total length of data returned for this descriptor
uint8_t bNumDeviceCaps ; ///< Number of device capability descriptors in the BOS
} tusb_desc_bos_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_bos_t) == 5, "size is not correct");
/// USB Configuration Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type
uint16_t wTotalLength ; ///< Total length of data returned for this configuration. Includes the combined length of all descriptors (configuration, interface, endpoint, and class- or vendor-specific) returned for this configuration.
uint8_t bNumInterfaces ; ///< Number of interfaces supported by this configuration
uint8_t bConfigurationValue ; ///< Value to use as an argument to the SetConfiguration() request to select this configuration.
uint8_t iConfiguration ; ///< Index of string descriptor describing this configuration
uint8_t bmAttributes ; ///< Configuration characteristics \n D7: Reserved (set to one)\n D6: Self-powered \n D5: Remote Wakeup \n D4...0: Reserved (reset to zero) \n D7 is reserved and must be set to one for historical reasons. \n A device configuration that uses power from the bus and a local source reports a non-zero value in bMaxPower to indicate the amount of bus power required and sets D6. The actual power source at runtime may be determined using the GetStatus(DEVICE) request (see USB 2.0 spec Section 9.4.5). \n If a device configuration supports remote wakeup, D5 is set to one.
uint8_t bMaxPower ; ///< Maximum power consumption of the USB device from the bus in this specific configuration when the device is fully operational. Expressed in 2 mA units (i.e., 50 = 100 mA).
} tusb_desc_configuration_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_configuration_t) == 9, "size is not correct");
/// USB Interface Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< INTERFACE Descriptor Type
uint8_t bInterfaceNumber ; ///< Number of this interface. Zero-based value identifying the index in the array of concurrent interfaces supported by this configuration.
uint8_t bAlternateSetting ; ///< Value used to select this alternate setting for the interface identified in the prior field
uint8_t bNumEndpoints ; ///< Number of endpoints used by this interface (excluding endpoint zero). If this value is zero, this interface only uses the Default Control Pipe.
uint8_t bInterfaceClass ; ///< Class code (assigned by the USB-IF). \li A value of zero is reserved for future standardization. \li If this field is set to FFH, the interface class is vendor-specific. \li All other values are reserved for assignment by the USB-IF.
uint8_t bInterfaceSubClass ; ///< Subclass code (assigned by the USB-IF). \n These codes are qualified by the value of the bInterfaceClass field. \li If the bInterfaceClass field is reset to zero, this field must also be reset to zero. \li If the bInterfaceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
uint8_t bInterfaceProtocol ; ///< Protocol code (assigned by the USB). \n These codes are qualified by the value of the bInterfaceClass and the bInterfaceSubClass fields. If an interface supports class-specific requests, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use a class-specific protocol on this interface. \li If this field is set to FFH, the device uses a vendor-specific protocol for this interface.
uint8_t iInterface ; ///< Index of string descriptor describing this interface
} tusb_desc_interface_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_interface_t) == 9, "size is not correct");
/// USB Endpoint Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; // Size of this descriptor in bytes
uint8_t bDescriptorType ; // ENDPOINT Descriptor Type
uint8_t bEndpointAddress ; // The address of the endpoint
struct TU_ATTR_PACKED {
uint8_t xfer : 2; // Control, ISO, Bulk, Interrupt
uint8_t sync : 2; // None, Asynchronous, Adaptive, Synchronous
uint8_t usage : 2; // Data, Feedback, Implicit feedback
uint8_t : 2;
} bmAttributes;
uint16_t wMaxPacketSize ; // Bit 10..0 : max packet size, bit 12..11 additional transaction per highspeed micro-frame
uint8_t bInterval ; // Polling interval, in frames or microframes depending on the operating speed
} tusb_desc_endpoint_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_endpoint_t) == 7, "size is not correct");
/// USB Other Speed Configuration Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
uint16_t wTotalLength ; ///< Total length of data returned
uint8_t bNumInterfaces ; ///< Number of interfaces supported by this speed configuration
uint8_t bConfigurationValue ; ///< Value to use to select configuration
uint8_t iConfiguration ; ///< Index of string descriptor
uint8_t bmAttributes ; ///< Same as Configuration descriptor
uint8_t bMaxPower ; ///< Same as Configuration descriptor
} tusb_desc_other_speed_t;
/// USB Device Qualifier Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Device Qualifier Type
uint16_t bcdUSB ; ///< USB specification version number (e.g., 0200H for V2.00)
uint8_t bDeviceClass ; ///< Class Code
uint8_t bDeviceSubClass ; ///< SubClass Code
uint8_t bDeviceProtocol ; ///< Protocol Code
uint8_t bMaxPacketSize0 ; ///< Maximum packet size for other speed
uint8_t bNumConfigurations ; ///< Number of Other-speed Configurations
uint8_t bReserved ; ///< Reserved for future use, must be zero
} tusb_desc_device_qualifier_t;
TU_VERIFY_STATIC( sizeof(tusb_desc_device_qualifier_t) == 10, "size is not correct");
/// USB Interface Association Descriptor (IAD ECN)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
uint8_t bFirstInterface ; ///< Index of the first associated interface.
uint8_t bInterfaceCount ; ///< Total number of associated interfaces.
uint8_t bFunctionClass ; ///< Interface class ID.
uint8_t bFunctionSubClass ; ///< Interface subclass ID.
uint8_t bFunctionProtocol ; ///< Interface protocol ID.
uint8_t iFunction ; ///< Index of the string descriptor describing the interface association.
} tusb_desc_interface_assoc_t;
// USB String Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< Descriptor Type
uint16_t unicode_string[];
} tusb_desc_string_t;
// USB Binary Device Object Store (BOS)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength;
uint8_t bDescriptorType ;
uint8_t bDevCapabilityType;
uint8_t bReserved;
uint8_t PlatformCapabilityUUID[16];
uint8_t CapabilityData[];
} tusb_desc_bos_platform_t;
// USB WebuSB URL Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bScheme;
char url[];
} tusb_desc_webusb_url_t;
// DFU Functional Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength;
uint8_t bDescriptorType;
union {
struct TU_ATTR_PACKED {
uint8_t bitCanDnload : 1;
uint8_t bitCanUpload : 1;
uint8_t bitManifestationTolerant : 1;
uint8_t bitWillDetach : 1;
uint8_t reserved : 4;
} bmAttributes;
uint8_t bAttributes;
};
uint16_t wDetachTimeOut;
uint16_t wTransferSize;
uint16_t bcdDFUVersion;
} tusb_desc_dfu_functional_t;
/*------------------------------------------------------------------*/
/* Types
*------------------------------------------------------------------*/
typedef struct TU_ATTR_PACKED{
union {
struct TU_ATTR_PACKED {
uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
uint8_t type : 2; ///< Request type tusb_request_type_t.
uint8_t direction : 1; ///< Direction type. tusb_dir_t
} bmRequestType_bit;
uint8_t bmRequestType;
};
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} tusb_control_request_t;
TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "size is not correct");
TU_ATTR_PACKED_END // End of all packed definitions
TU_ATTR_BIT_FIELD_ORDER_END
//--------------------------------------------------------------------+
// Endpoint helper
//--------------------------------------------------------------------+
// Get direction from Endpoint address
static inline tusb_dir_t tu_edpt_dir(uint8_t addr)
{
return (addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
}
// Get Endpoint number from address
static inline uint8_t tu_edpt_number(uint8_t addr)
{
return (uint8_t)(addr & (~TUSB_DIR_IN_MASK));
}
static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir)
{
return (uint8_t)(num | (dir ? TUSB_DIR_IN_MASK : 0));
}
static inline uint16_t tu_edpt_packet_size(tusb_desc_endpoint_t const* desc_ep)
{
return tu_le16toh(desc_ep->wMaxPacketSize) & TU_GENMASK(10, 0);
}
//--------------------------------------------------------------------+
// Descriptor helper
//--------------------------------------------------------------------+
static inline uint8_t const * tu_desc_next(void const* desc)
{
uint8_t const* desc8 = (uint8_t const*) desc;
return desc8 + desc8[DESC_OFFSET_LEN];
}
static inline uint8_t tu_desc_type(void const* desc)
{
return ((uint8_t const*) desc)[DESC_OFFSET_TYPE];
}
static inline uint8_t tu_desc_len(void const* desc)
{
return ((uint8_t const*) desc)[DESC_OFFSET_LEN];
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_TYPES_H_ */
/** @} */

View File

@ -0,0 +1,153 @@
/*
* 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.
*/
#ifndef TUSB_VERIFY_H_
#define TUSB_VERIFY_H_
#include <stdbool.h>
#include <stdint.h>
#include "tusb_option.h"
#include "tusb_compiler.h"
/*------------------------------------------------------------------*/
/* This file use an advanced macro technique to mimic the default parameter
* as C++ for the sake of code simplicity. Beware of a headache macro
* manipulation that you are told to stay away.
*
* This contains macros for both VERIFY and ASSERT:
*
* VERIFY: Used when there is an error condition which is not the
* fault of the MCU. For example, bounds checking on data
* sent to the micro over USB should use this function.
* Another example is checking for buffer overflows, where
* returning from the active function causes a NAK.
*
* ASSERT: Used for error conditions that are caused by MCU firmware
* bugs. This is used to discover bugs in the code more
* quickly. One example would be adding assertions in library
* function calls to confirm a function's (untainted)
* parameters are valid.
*
* The difference in behavior is that ASSERT triggers a breakpoint while
* verify does not.
*
* #define TU_VERIFY(cond) if(cond) return false;
* #define TU_VERIFY(cond,ret) if(cond) return ret;
*
* #define TU_VERIFY_HDLR(cond,handler) if(cond) {handler; return false;}
* #define TU_VERIFY_HDLR(cond,ret,handler) if(cond) {handler; return ret;}
*
* #define TU_ASSERT(cond) if(cond) {_MESS_FAILED(); TU_BREAKPOINT(), return false;}
* #define TU_ASSERT(cond,ret) if(cond) {_MESS_FAILED(); TU_BREAKPOINT(), return ret;}
*
*------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TU_VERIFY Helper
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG
#include <stdio.h>
#define _MESS_FAILED() tu_printf("%s %d: ASSERT FAILED\r\n", __func__, __LINE__)
#else
#define _MESS_FAILED() do {} while (0)
#endif
// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7, M33
#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__)
#define TU_BREAKPOINT() do \
{ \
volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \
if ( (*ARM_CM_DHCSR) & 1UL ) __asm("BKPT #0\n"); /* Only halt mcu if debugger is attached */ \
} while(0)
#elif defined(__riscv)
#define TU_BREAKPOINT() do { __asm("ebreak\n"); } while(0)
#else
#define TU_BREAKPOINT() do {} while (0)
#endif
/*------------------------------------------------------------------*/
/* Macro Generator
*------------------------------------------------------------------*/
// Helper to implement optional parameter for TU_VERIFY Macro family
#define GET_3RD_ARG(arg1, arg2, arg3, ...) arg3
#define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4
/*------------- Generator for TU_VERIFY and TU_VERIFY_HDLR -------------*/
#define TU_VERIFY_DEFINE(_cond, _handler, _ret) do \
{ \
if ( !(_cond) ) { _handler; return _ret; } \
} while(0)
/*------------------------------------------------------------------*/
/* TU_VERIFY
* - TU_VERIFY_1ARGS : return false if failed
* - TU_VERIFY_2ARGS : return provided value if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, , false)
#define TU_VERIFY_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, , _ret)
#define TU_VERIFY(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_2ARGS, TU_VERIFY_1ARGS, UNUSED)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* TU_VERIFY WITH HANDLER
* - TU_VERIFY_HDLR_2ARGS : execute handler, return false if failed
* - TU_VERIFY_HDLR_3ARGS : execute handler, return provided error if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_HDLR_2ARGS(_cond, _handler) TU_VERIFY_DEFINE(_cond, _handler, false)
#define TU_VERIFY_HDLR_3ARGS(_cond, _handler, _ret) TU_VERIFY_DEFINE(_cond, _handler, _ret)
#define TU_VERIFY_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_HDLR_3ARGS, TU_VERIFY_HDLR_2ARGS,UNUSED)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* ASSERT
* basically TU_VERIFY with TU_BREAKPOINT() as handler
* - 1 arg : return false if failed
* - 2 arg : return error if failed
*------------------------------------------------------------------*/
#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), false)
#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), _ret)
#ifndef TU_ASSERT
#define TU_ASSERT(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS,UNUSED)(__VA_ARGS__)
#endif
/*------------------------------------------------------------------*/
/* ASSERT HDLR
*------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif /* TUSB_VERIFY_H_ */

View File

@ -0,0 +1,192 @@
/*
* 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.
*/
#ifndef _TUSB_DCD_H_
#define _TUSB_DCD_H_
#include "common/tusb_common.h"
#include "osal/osal.h"
#include "common/tusb_fifo.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUD_ENDPPOINT_MAX
#define CFG_TUD_ENDPPOINT_MAX TUP_DCD_ENDPOINT_MAX
#endif
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF PROTYPES
//--------------------------------------------------------------------+
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
{
// BUS RESET
struct {
tusb_speed_t speed;
} bus_reset;
// SETUP_RECEIVED
tusb_control_request_t setup_received;
// XFER_COMPLETE
struct {
uint8_t ep_addr;
uint8_t result;
uint32_t len;
}xfer_complete;
// 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");
//--------------------------------------------------------------------+
// Controller API
//--------------------------------------------------------------------+
// Initialize controller to device mode
void dcd_init (uint8_t rhport);
// Interrupt Handler
#if __GNUC__ && !defined(__ARMCC_VERSION)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"
#endif
void dcd_int_handler(uint8_t rhport);
#if __GNUC__ && !defined(__ARMCC_VERSION)
#pragma GCC diagnostic pop
#endif
// 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);
// Wake up host
void dcd_remote_wakeup(uint8_t rhport);
// Connect by enabling internal pull-up resistor on D+/D-
void dcd_connect(uint8_t rhport) TU_ATTR_WEAK;
// Disconnect by disabling internal pull-up resistor on D+/D-
void dcd_disconnect(uint8_t rhport) TU_ATTR_WEAK;
//--------------------------------------------------------------------+
// 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 * desc_ep);
// Close all non-control endpoints, cancel all pending transfers if any.
// Invoked when switching from a non-zero Configuration by SET_CONFIGURE therefore
// required for multiple configuration support.
void dcd_edpt_close_all (uint8_t rhport);
// Close an endpoint.
// Since it is weak, caller must TU_ASSERT this function's existence before calling it.
void dcd_edpt_close (uint8_t rhport, uint8_t ep_addr) TU_ATTR_WEAK;
// 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);
// Submit an transfer using fifo, When complete dcd_event_xfer_complete() is invoked to notify the stack
// This API is optional, may be useful for register-based for transferring data.
bool dcd_edpt_xfer_fifo (uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes) TU_ATTR_WEAK;
// Stall endpoint, any queuing transfer should be removed from endpoint
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
// clear stall, data toggle is also reset to DATA0
// This API never calls with control endpoints, since it is auto cleared when receiving setup packet
void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr);
//--------------------------------------------------------------------+
// Event API (implemented by 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 bus reset event
extern void dcd_event_bus_reset (uint8_t rhport, tusb_speed_t speed, 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_ */

View File

@ -0,0 +1,853 @@
/*
* 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.
*/
#ifndef _TUSB_USBD_H_
#define _TUSB_USBD_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Init device stack
bool tud_init (uint8_t rhport);
// Check if device stack is already initialized
bool tud_inited(void);
// Task function should be called in main/rtos loop
void tud_task (void);
// Check if there is pending events need proccessing by tud_task()
bool tud_task_event_ready(void);
// Interrupt handler, name alias to DCD
extern void dcd_int_handler(uint8_t rhport);
#define tud_int_handler dcd_int_handler
// Get current bus speed
tusb_speed_t tud_speed_get(void);
// Check if device is connected (may not mounted/configured yet)
// True if just got out of Bus Reset and received the very first data from host
bool tud_connected(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
TU_ATTR_ALWAYS_INLINE 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);
// Enable pull-up resistor on D+ D-
// Return false on unsupported MCUs
bool tud_disconnect(void);
// Disable pull-up resistor on D+ D-
// Return false on unsupported MCUs
bool tud_connect(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 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 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 DEVICE QUALIFIER DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete.
// device_qualifier descriptor describes information about a high-speed capable device that would
// change if the device were operating at the other speed. If not highspeed capable stall this request.
TU_ATTR_WEAK uint8_t const* tud_descriptor_device_qualifier_cb(void);
// Invoked when received GET OTHER SEED CONFIGURATION DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
// Configuration descriptor in the other speed e.g if high speed then this is for full speed and vice versa
TU_ATTR_WEAK uint8_t const* tud_descriptor_other_speed_configuration_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_xfer_cb(uint8_t rhport, uint8_t stage, 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 Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_CONFIG_DESC_LEN (9)
// Config number, interface count, string index, total length, attribute, power in mA
#define TUD_CONFIG_DESCRIPTOR(config_num, _itfcount, _stridx, _total_len, _attribute, _power_ma) \
9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, config_num, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2
//--------------------------------------------------------------------+
// CDC Descriptor Templates
//--------------------------------------------------------------------+
// 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_NONE, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_NONE, _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 Descriptor Templates
//--------------------------------------------------------------------+
// 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 Descriptor Templates
//--------------------------------------------------------------------+
// 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) ? (uint8_t)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) ? (uint8_t)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 Descriptor Templates
// Note: MIDI v1.0 is based on Audio v1.0
//--------------------------------------------------------------------+
#define TUD_MIDI_DESC_HEAD_LEN (9 + 9 + 9 + 7)
#define TUD_MIDI_DESC_HEAD(_itfnum, _stridx, _numcables) \
/* Audio Control (AC) Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_FUNC_PROTOCOL_CODE_UNDEF, _stridx,\
/* AC Header */\
9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_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_FUNC_PROTOCOL_CODE_UNDEF, 0,\
/* MS Header */\
7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(7 + (_numcables) * TUD_MIDI_DESC_JACK_LEN)
#define TUD_MIDI_JACKID_IN_EMB(_cablenum) \
(uint8_t)(((_cablenum) - 1) * 4 + 1)
#define TUD_MIDI_JACKID_IN_EXT(_cablenum) \
(uint8_t)(((_cablenum) - 1) * 4 + 2)
#define TUD_MIDI_JACKID_OUT_EMB(_cablenum) \
(uint8_t)(((_cablenum) - 1) * 4 + 3)
#define TUD_MIDI_JACKID_OUT_EXT(_cablenum) \
(uint8_t)(((_cablenum) - 1) * 4 + 4)
#define TUD_MIDI_DESC_JACK_LEN (6 + 6 + 9 + 9)
#define TUD_MIDI_DESC_JACK(_cablenum) \
/* MS In Jack (Embedded) */\
6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, TUD_MIDI_JACKID_IN_EMB(_cablenum), 0,\
/* MS In Jack (External) */\
6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, TUD_MIDI_JACKID_IN_EXT(_cablenum), 0,\
/* MS Out Jack (Embedded), connected to In Jack External */\
9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, TUD_MIDI_JACKID_OUT_EMB(_cablenum), 1, TUD_MIDI_JACKID_IN_EXT(_cablenum), 1, 0,\
/* MS Out Jack (External), connected to In Jack Embedded */\
9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, TUD_MIDI_JACKID_OUT_EXT(_cablenum), 1, TUD_MIDI_JACKID_IN_EMB(_cablenum), 1, 0
#define TUD_MIDI_DESC_EP_LEN(_numcables) (9 + 4 + (_numcables))
#define TUD_MIDI_DESC_EP(_epout, _epsize, _numcables) \
/* Endpoint: Note Audio v1.0's endpoint has 9 bytes instead of 7 */\
9, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0, 0, 0, \
/* MS Endpoint (connected to embedded jack) */\
(uint8_t)(4 + (_numcables)), TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, _numcables
// Length of template descriptor (88 bytes)
#define TUD_MIDI_DESC_LEN (TUD_MIDI_DESC_HEAD_LEN + TUD_MIDI_DESC_JACK_LEN + TUD_MIDI_DESC_EP_LEN(1) * 2)
// 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) \
TUD_MIDI_DESC_HEAD(_itfnum, _stridx, 1),\
TUD_MIDI_DESC_JACK(1),\
TUD_MIDI_DESC_EP(_epout, _epsize, 1),\
TUD_MIDI_JACKID_IN_EMB(1),\
TUD_MIDI_DESC_EP(_epin, _epsize, 1),\
TUD_MIDI_JACKID_OUT_EMB(1)
//--------------------------------------------------------------------+
// Audio v2.0 Descriptor Templates
//--------------------------------------------------------------------+
/* Standard Interface Association Descriptor (IAD) */
#define TUD_AUDIO_DESC_IAD_LEN 8
#define TUD_AUDIO_DESC_IAD(_firstitfs, _nitfs, _stridx) \
TUD_AUDIO_DESC_IAD_LEN, TUSB_DESC_INTERFACE_ASSOCIATION, _firstitfs, _nitfs, TUSB_CLASS_AUDIO, AUDIO_FUNCTION_SUBCLASS_UNDEFINED, AUDIO_FUNC_PROTOCOL_CODE_V2, _stridx
/* Standard AC Interface Descriptor(4.7.1) */
#define TUD_AUDIO_DESC_STD_AC_LEN 9
#define TUD_AUDIO_DESC_STD_AC(_itfnum, _nEPs, _stridx) /* _nEPs is 0 or 1 */\
TUD_AUDIO_DESC_STD_AC_LEN, TUSB_DESC_INTERFACE, _itfnum, /* fixed to zero */ 0x00, _nEPs, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_INT_PROTOCOL_CODE_V2, _stridx
/* Class-Specific AC Interface Header Descriptor(4.7.2) */
#define TUD_AUDIO_DESC_CS_AC_LEN 9
#define TUD_AUDIO_DESC_CS_AC(_bcdADC, _category, _totallen, _ctrl) /* _bcdADC : Audio Device Class Specification Release Number in Binary-Coded Decimal, _category : see audio_function_t, _totallen : Total number of bytes returned for the class-specific AudioControl interface i.e. Clock Source, Unit and Terminal descriptors - Do not include TUD_AUDIO_DESC_CS_AC_LEN, we already do this here*/ \
TUD_AUDIO_DESC_CS_AC_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_HEADER, U16_TO_U8S_LE(_bcdADC), _category, U16_TO_U8S_LE(_totallen + TUD_AUDIO_DESC_CS_AC_LEN), _ctrl
/* Clock Source Descriptor(4.7.2.1) */
#define TUD_AUDIO_DESC_CLK_SRC_LEN 8
#define TUD_AUDIO_DESC_CLK_SRC(_clkid, _attr, _ctrl, _assocTerm, _stridx) \
TUD_AUDIO_DESC_CLK_SRC_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_CLOCK_SOURCE, _clkid, _attr, _ctrl, _assocTerm, _stridx
/* Input Terminal Descriptor(4.7.2.4) */
#define TUD_AUDIO_DESC_INPUT_TERM_LEN 17
#define TUD_AUDIO_DESC_INPUT_TERM(_termid, _termtype, _assocTerm, _clkid, _nchannelslogical, _channelcfg, _idxchannelnames, _ctrl, _stridx) \
TUD_AUDIO_DESC_INPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_INPUT_TERMINAL, _termid, U16_TO_U8S_LE(_termtype), _assocTerm, _clkid, _nchannelslogical, U32_TO_U8S_LE(_channelcfg), _idxchannelnames, U16_TO_U8S_LE(_ctrl), _stridx
/* Output Terminal Descriptor(4.7.2.5) */
#define TUD_AUDIO_DESC_OUTPUT_TERM_LEN 12
#define TUD_AUDIO_DESC_OUTPUT_TERM(_termid, _termtype, _assocTerm, _srcid, _clkid, _ctrl, _stridx) \
TUD_AUDIO_DESC_OUTPUT_TERM_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_OUTPUT_TERMINAL, _termid, U16_TO_U8S_LE(_termtype), _assocTerm, _srcid, _clkid, U16_TO_U8S_LE(_ctrl), _stridx
/* Feature Unit Descriptor(4.7.2.8) */
// 1 - Channel
#define TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN 6+(1+1)*4
#define TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL(_unitid, _srcid, _ctrlch0master, _ctrlch1, _stridx) \
TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_FEATURE_UNIT, _unitid, _srcid, U32_TO_U8S_LE(_ctrlch0master), U32_TO_U8S_LE(_ctrlch1), _stridx
// 2 - Channels
#define TUD_AUDIO_DESC_FEATURE_UNIT_TWO_CHANNEL_LEN (6+(2+1)*4)
#define TUD_AUDIO_DESC_FEATURE_UNIT_TWO_CHANNEL(_unitid, _srcid, _ctrlch0master, _ctrlch1, _ctrlch2, _stridx) \
TUD_AUDIO_DESC_FEATURE_UNIT_TWO_CHANNEL_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_FEATURE_UNIT, _unitid, _srcid, U32_TO_U8S_LE(_ctrlch0master), U32_TO_U8S_LE(_ctrlch1), U32_TO_U8S_LE(_ctrlch2), _stridx
// 4 - Channels
#define TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL_LEN (6+(4+1)*4)
#define TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL(_unitid, _srcid, _ctrlch0master, _ctrlch1, _ctrlch2, _ctrlch3, _ctrlch4, _stridx) \
TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AC_INTERFACE_FEATURE_UNIT, _unitid, _srcid, U32_TO_U8S_LE(_ctrlch0master), U32_TO_U8S_LE(_ctrlch1), U32_TO_U8S_LE(_ctrlch2), U32_TO_U8S_LE(_ctrlch3), U32_TO_U8S_LE(_ctrlch4), _stridx
// For more channels, add definitions here
/* Standard AS Interface Descriptor(4.9.1) */
#define TUD_AUDIO_DESC_STD_AS_INT_LEN 9
#define TUD_AUDIO_DESC_STD_AS_INT(_itfnum, _altset, _nEPs, _stridx) \
TUD_AUDIO_DESC_STD_AS_INT_LEN, TUSB_DESC_INTERFACE, _itfnum, _altset, _nEPs, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_STREAMING, AUDIO_INT_PROTOCOL_CODE_V2, _stridx
/* Class-Specific AS Interface Descriptor(4.9.2) */
#define TUD_AUDIO_DESC_CS_AS_INT_LEN 16
#define TUD_AUDIO_DESC_CS_AS_INT(_termid, _ctrl, _formattype, _formats, _nchannelsphysical, _channelcfg, _stridx) \
TUD_AUDIO_DESC_CS_AS_INT_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AS_INTERFACE_AS_GENERAL, _termid, _ctrl, _formattype, U32_TO_U8S_LE(_formats), _nchannelsphysical, U32_TO_U8S_LE(_channelcfg), _stridx
/* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */
#define TUD_AUDIO_DESC_TYPE_I_FORMAT_LEN 6
#define TUD_AUDIO_DESC_TYPE_I_FORMAT(_subslotsize, _bitresolution) /* _subslotsize is number of bytes per sample (i.e. subslot) and can be 1,2,3, or 4 */\
TUD_AUDIO_DESC_TYPE_I_FORMAT_LEN, TUSB_DESC_CS_INTERFACE, AUDIO_CS_AS_INTERFACE_FORMAT_TYPE, AUDIO_FORMAT_TYPE_I, _subslotsize, _bitresolution
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */
#define TUD_AUDIO_DESC_STD_AS_ISO_EP_LEN 7
#define TUD_AUDIO_DESC_STD_AS_ISO_EP(_ep, _attr, _maxEPsize, _interval) \
TUD_AUDIO_DESC_STD_AS_ISO_EP_LEN, TUSB_DESC_ENDPOINT, _ep, _attr, U16_TO_U8S_LE(_maxEPsize), _interval
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */
#define TUD_AUDIO_DESC_CS_AS_ISO_EP_LEN 8
#define TUD_AUDIO_DESC_CS_AS_ISO_EP(_attr, _ctrl, _lockdelayunit, _lockdelay) \
TUD_AUDIO_DESC_CS_AS_ISO_EP_LEN, TUSB_DESC_CS_ENDPOINT, AUDIO_CS_EP_SUBTYPE_GENERAL, _attr, _ctrl, _lockdelayunit, U16_TO_U8S_LE(_lockdelay)
/* Standard AS Isochronous Feedback Endpoint Descriptor(4.10.2.1) */
#define TUD_AUDIO_DESC_STD_AS_ISO_FB_EP_LEN 7
#define TUD_AUDIO_DESC_STD_AS_ISO_FB_EP(_ep, _interval) \
TUD_AUDIO_DESC_STD_AS_ISO_FB_EP_LEN, TUSB_DESC_ENDPOINT, _ep, (TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_NO_SYNC | TUSB_ISO_EP_ATT_EXPLICIT_FB), U16_TO_U8S_LE(4), _interval
// AUDIO simple descriptor (UAC2) for 1 microphone input
// - 1 Input Terminal, 1 Feature Unit (Mute and Volume Control), 1 Output Terminal, 1 Clock Source
#define TUD_AUDIO_MIC_ONE_CH_DESC_LEN (TUD_AUDIO_DESC_IAD_LEN\
+ TUD_AUDIO_DESC_STD_AC_LEN\
+ TUD_AUDIO_DESC_CS_AC_LEN\
+ TUD_AUDIO_DESC_CLK_SRC_LEN\
+ TUD_AUDIO_DESC_INPUT_TERM_LEN\
+ TUD_AUDIO_DESC_OUTPUT_TERM_LEN\
+ TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_CS_AS_INT_LEN\
+ TUD_AUDIO_DESC_TYPE_I_FORMAT_LEN\
+ TUD_AUDIO_DESC_STD_AS_ISO_EP_LEN\
+ TUD_AUDIO_DESC_CS_AS_ISO_EP_LEN)
#define TUD_AUDIO_MIC_ONE_CH_DESC_N_AS_INT 1 // Number of AS interfaces
#define TUD_AUDIO_MIC_ONE_CH_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epin, _epsize) \
/* Standard Interface Association Descriptor (IAD) */\
TUD_AUDIO_DESC_IAD(/*_firstitfs*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00),\
/* Standard AC Interface Descriptor(4.7.1) */\
TUD_AUDIO_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx),\
/* Class-Specific AC Interface Header Descriptor(4.7.2) */\
TUD_AUDIO_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO_FUNC_MICROPHONE, /*_totallen*/ TUD_AUDIO_DESC_CLK_SRC_LEN+TUD_AUDIO_DESC_INPUT_TERM_LEN+TUD_AUDIO_DESC_OUTPUT_TERM_LEN+TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN, /*_ctrl*/ AUDIO_CS_AS_INTERFACE_CTRL_LATENCY_POS),\
/* Clock Source Descriptor(4.7.2.1) */\
TUD_AUDIO_DESC_CLK_SRC(/*_clkid*/ 0x04, /*_attr*/ AUDIO_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO_CTRL_R << AUDIO_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ 0x01, /*_stridx*/ 0x00),\
/* Input Terminal Descriptor(4.7.2.4) */\
TUD_AUDIO_DESC_INPUT_TERM(/*_termid*/ 0x01, /*_termtype*/ AUDIO_TERM_TYPE_IN_GENERIC_MIC, /*_assocTerm*/ 0x03, /*_clkid*/ 0x04, /*_nchannelslogical*/ 0x01, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ AUDIO_CTRL_R << AUDIO_IN_TERM_CTRL_CONNECTOR_POS, /*_stridx*/ 0x00),\
/* Output Terminal Descriptor(4.7.2.5) */\
TUD_AUDIO_DESC_OUTPUT_TERM(/*_termid*/ 0x03, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x01, /*_srcid*/ 0x02, /*_clkid*/ 0x04, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00),\
/* Feature Unit Descriptor(4.7.2.8) */\
TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL(/*_unitid*/ 0x02, /*_srcid*/ 0x01, /*_ctrlch0master*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 1 - alternate interface for data streaming */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00),\
/* Class-Specific AS Interface Descriptor(4.9.2) */\
TUD_AUDIO_DESC_CS_AS_INT(/*_termid*/ 0x03, /*_ctrl*/ AUDIO_CTRL_NONE, /*_formattype*/ AUDIO_FORMAT_TYPE_I, /*_formats*/ AUDIO_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ 0x01, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00),\
/* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */\
TUD_AUDIO_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample),\
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */\
TUD_AUDIO_DESC_STD_AS_ISO_EP(/*_ep*/ _epin, /*_attr*/ (TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_ASYNCHRONOUS | TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ TUD_OPT_HIGH_SPEED ? 0x04 : 0x01),\
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */\
TUD_AUDIO_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO_CTRL_NONE, /*_lockdelayunit*/ AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000)
// AUDIO simple descriptor (UAC2) for 4 microphone input
// - 1 Input Terminal, 1 Feature Unit (Mute and Volume Control), 1 Output Terminal, 1 Clock Source
#define TUD_AUDIO_MIC_FOUR_CH_DESC_LEN (TUD_AUDIO_DESC_IAD_LEN\
+ TUD_AUDIO_DESC_STD_AC_LEN\
+ TUD_AUDIO_DESC_CS_AC_LEN\
+ TUD_AUDIO_DESC_CLK_SRC_LEN\
+ TUD_AUDIO_DESC_INPUT_TERM_LEN\
+ TUD_AUDIO_DESC_OUTPUT_TERM_LEN\
+ TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_CS_AS_INT_LEN\
+ TUD_AUDIO_DESC_TYPE_I_FORMAT_LEN\
+ TUD_AUDIO_DESC_STD_AS_ISO_EP_LEN\
+ TUD_AUDIO_DESC_CS_AS_ISO_EP_LEN)
#define TUD_AUDIO_MIC_FOUR_CH_DESC_N_AS_INT 1 // Number of AS interfaces
#define TUD_AUDIO_MIC_FOUR_CH_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epin, _epsize) \
/* Standard Interface Association Descriptor (IAD) */\
TUD_AUDIO_DESC_IAD(/*_firstitfs*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00),\
/* Standard AC Interface Descriptor(4.7.1) */\
TUD_AUDIO_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx),\
/* Class-Specific AC Interface Header Descriptor(4.7.2) */\
TUD_AUDIO_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO_FUNC_MICROPHONE, /*_totallen*/ TUD_AUDIO_DESC_CLK_SRC_LEN+TUD_AUDIO_DESC_INPUT_TERM_LEN+TUD_AUDIO_DESC_OUTPUT_TERM_LEN+TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL_LEN, /*_ctrl*/ AUDIO_CS_AS_INTERFACE_CTRL_LATENCY_POS),\
/* Clock Source Descriptor(4.7.2.1) */\
TUD_AUDIO_DESC_CLK_SRC(/*_clkid*/ 0x04, /*_attr*/ AUDIO_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO_CTRL_R << AUDIO_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ 0x01, /*_stridx*/ 0x00),\
/* Input Terminal Descriptor(4.7.2.4) */\
TUD_AUDIO_DESC_INPUT_TERM(/*_termid*/ 0x01, /*_termtype*/ AUDIO_TERM_TYPE_IN_GENERIC_MIC, /*_assocTerm*/ 0x03, /*_clkid*/ 0x04, /*_nchannelslogical*/ 0x04, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ AUDIO_CTRL_R << AUDIO_IN_TERM_CTRL_CONNECTOR_POS, /*_stridx*/ 0x00),\
/* Output Terminal Descriptor(4.7.2.5) */\
TUD_AUDIO_DESC_OUTPUT_TERM(/*_termid*/ 0x03, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x01, /*_srcid*/ 0x02, /*_clkid*/ 0x04, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00),\
/* Feature Unit Descriptor(4.7.2.8) */\
TUD_AUDIO_DESC_FEATURE_UNIT_FOUR_CHANNEL(/*_unitid*/ 0x02, /*_srcid*/ 0x01, /*_ctrlch0master*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch3*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch4*/ AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 1 - alternate interface for data streaming */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum)+1), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00),\
/* Class-Specific AS Interface Descriptor(4.9.2) */\
TUD_AUDIO_DESC_CS_AS_INT(/*_termid*/ 0x03, /*_ctrl*/ AUDIO_CTRL_NONE, /*_formattype*/ AUDIO_FORMAT_TYPE_I, /*_formats*/ AUDIO_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ 0x04, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00),\
/* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */\
TUD_AUDIO_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample),\
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */\
TUD_AUDIO_DESC_STD_AS_ISO_EP(/*_ep*/ _epin, /*_attr*/ (TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_ASYNCHRONOUS | TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ TUD_OPT_HIGH_SPEED ? 0x04 : 0x01),\
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */\
TUD_AUDIO_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO_CTRL_NONE, /*_lockdelayunit*/ AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000)
// AUDIO simple descriptor (UAC2) for mono speaker
// - 1 Input Terminal, 2 Feature Unit (Mute and Volume Control), 3 Output Terminal, 4 Clock Source
#define TUD_AUDIO_SPEAKER_MONO_FB_DESC_LEN (TUD_AUDIO_DESC_IAD_LEN\
+ TUD_AUDIO_DESC_STD_AC_LEN\
+ TUD_AUDIO_DESC_CS_AC_LEN\
+ TUD_AUDIO_DESC_CLK_SRC_LEN\
+ TUD_AUDIO_DESC_INPUT_TERM_LEN\
+ TUD_AUDIO_DESC_OUTPUT_TERM_LEN\
+ TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_STD_AS_INT_LEN\
+ TUD_AUDIO_DESC_CS_AS_INT_LEN\
+ TUD_AUDIO_DESC_TYPE_I_FORMAT_LEN\
+ TUD_AUDIO_DESC_STD_AS_ISO_EP_LEN\
+ TUD_AUDIO_DESC_CS_AS_ISO_EP_LEN\
+ TUD_AUDIO_DESC_STD_AS_ISO_FB_EP_LEN)
#define TUD_AUDIO_SPEAKER_MONO_FB_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epout, _epsize, _epfb) \
/* Standard Interface Association Descriptor (IAD) */\
TUD_AUDIO_DESC_IAD(/*_firstitfs*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00),\
/* Standard AC Interface Descriptor(4.7.1) */\
TUD_AUDIO_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx),\
/* Class-Specific AC Interface Header Descriptor(4.7.2) */\
TUD_AUDIO_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO_FUNC_DESKTOP_SPEAKER, /*_totallen*/ TUD_AUDIO_DESC_CLK_SRC_LEN+TUD_AUDIO_DESC_INPUT_TERM_LEN+TUD_AUDIO_DESC_OUTPUT_TERM_LEN+TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL_LEN, /*_ctrl*/ AUDIO_CS_AS_INTERFACE_CTRL_LATENCY_POS),\
/* Clock Source Descriptor(4.7.2.1) */\
TUD_AUDIO_DESC_CLK_SRC(/*_clkid*/ 0x04, /*_attr*/ AUDIO_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO_CTRL_R << AUDIO_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ 0x01, /*_stridx*/ 0x00),\
/* Input Terminal Descriptor(4.7.2.4) */\
TUD_AUDIO_DESC_INPUT_TERM(/*_termid*/ 0x01, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_clkid*/ 0x04, /*_nchannelslogical*/ 0x01, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ 0 * (AUDIO_CTRL_R << AUDIO_IN_TERM_CTRL_CONNECTOR_POS), /*_stridx*/ 0x00),\
/* Output Terminal Descriptor(4.7.2.5) */\
TUD_AUDIO_DESC_OUTPUT_TERM(/*_termid*/ 0x03, /*_termtype*/ AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER, /*_assocTerm*/ 0x01, /*_srcid*/ 0x02, /*_clkid*/ 0x04, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00),\
/* Feature Unit Descriptor(4.7.2.8) */\
TUD_AUDIO_DESC_FEATURE_UNIT_ONE_CHANNEL(/*_unitid*/ 0x02, /*_srcid*/ 0x01, /*_ctrlch0master*/ 0 * (AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS), /*_ctrlch1*/ 0 * (AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO_CTRL_RW << AUDIO_FEATURE_UNIT_CTRL_VOLUME_POS), /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00),\
/* Standard AS Interface Descriptor(4.9.1) */\
/* Interface 1, Alternate 1 - alternate interface for data streaming */\
TUD_AUDIO_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x01, /*_nEPs*/ 0x02, /*_stridx*/ 0x00),\
/* Class-Specific AS Interface Descriptor(4.9.2) */\
TUD_AUDIO_DESC_CS_AS_INT(/*_termid*/ 0x01, /*_ctrl*/ AUDIO_CTRL_NONE, /*_formattype*/ AUDIO_FORMAT_TYPE_I, /*_formats*/ AUDIO_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ 0x01, /*_channelcfg*/ AUDIO_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00),\
/* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */\
TUD_AUDIO_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample),\
/* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */\
TUD_AUDIO_DESC_STD_AS_ISO_EP(/*_ep*/ _epout, /*_attr*/ (TUSB_XFER_ISOCHRONOUS | TUSB_ISO_EP_ATT_ASYNCHRONOUS | TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ TUD_OPT_HIGH_SPEED ? 0x04 : 0x01),\
/* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */\
TUD_AUDIO_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO_CTRL_NONE, /*_lockdelayunit*/ AUDIO_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000),\
/* Standard AS Isochronous Feedback Endpoint Descriptor(4.10.2.1) */\
TUD_AUDIO_DESC_STD_AS_ISO_FB_EP(/*_ep*/ _epfb, /*_interval*/ 1)\
// Calculate wMaxPacketSize of Endpoints
#define TUD_AUDIO_EP_SIZE(_maxFrequency, _nBytesPerSample, _nChannels) \
((((_maxFrequency + (TUD_OPT_HIGH_SPEED ? 7999 : 999)) / (TUD_OPT_HIGH_SPEED ? 8000 : 1000)) + 1) * _nBytesPerSample * _nChannels)
//--------------------------------------------------------------------+
// USBTMC/USB488 Descriptor Templates
//--------------------------------------------------------------------+
#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 Descriptor Templates
//--------------------------------------------------------------------+
#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 Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_DFU_APP_CLASS (TUSB_CLASS_APPLICATION_SPECIFIC)
#define TUD_DFU_APP_SUBCLASS (APP_SUBCLASS_DFU_RUNTIME)
// 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)
//--------------------------------------------------------------------+
// DFU Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 9 bytes + number of alternatives * 9
#define TUD_DFU_DESC_LEN(_alt_count) (9 + (_alt_count) * 9)
// Interface number, Alternate count, starting string index, attributes, detach timeout, transfer size
// Note: Alternate count must be numberic or macro, string index is increased by one for each Alt interface
#define TUD_DFU_DESCRIPTOR(_itfnum, _alt_count, _stridx, _attr, _timeout, _xfer_size) \
TU_XSTRCAT(_TUD_DFU_ALT_,_alt_count)(_itfnum, 0, _stridx), \
/* Function */ \
9, DFU_DESC_FUNCTIONAL, _attr, U16_TO_U8S_LE(_timeout), U16_TO_U8S_LE(_xfer_size), U16_TO_U8S_LE(0x0101)
#define _TUD_DFU_ALT(_itfnum, _alt, _stridx) \
/* Interface */ \
9, TUSB_DESC_INTERFACE, _itfnum, _alt, 0, TUD_DFU_APP_CLASS, TUD_DFU_APP_SUBCLASS, DFU_PROTOCOL_DFU, _stridx
#define _TUD_DFU_ALT_1(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx)
#define _TUD_DFU_ALT_2(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_1(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_3(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_2(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_4(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_3(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_5(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_4(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_6(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_5(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_7(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_6(_itfnum, _alt_count+1, _stridx+1)
#define _TUD_DFU_ALT_8(_itfnum, _alt_count, _stridx) \
_TUD_DFU_ALT(_itfnum, _alt_count, _stridx), \
_TUD_DFU_ALT_7(_itfnum, _alt_count+1, _stridx+1)
//--------------------------------------------------------------------+
// CDC-ECM Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor: 71 bytes
#define TUD_CDC_ECM_DESC_LEN (8+9+5+5+13+7+9+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) \
/* Interface Association */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL, 0, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ETHERNET_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 (default inactive) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 0, TUSB_CLASS_CDC_DATA, 0, 0, 0,\
/* CDC Data Interface (alternative active) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 1, 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 Descriptor Templates
//--------------------------------------------------------------------+
#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 0xFF /* CDC_COMM_PROTOCOL_MICROSOFT_RNDIS */
#else
/* Windows 7+ */
#define TUD_RNDIS_ITF_CLASS TUSB_CLASS_WIRELESS_CONTROLLER
#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
//--------------------------------------------------------------------+
// Bluetooth Radio Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_BT_APP_CLASS (TUSB_CLASS_WIRELESS_CONTROLLER)
#define TUD_BT_APP_SUBCLASS 0x01
#define TUD_BT_PROTOCOL_PRIMARY_CONTROLLER 0x01
#define TUD_BT_PROTOCOL_AMP_CONTROLLER 0x02
#ifndef CFG_TUD_BTH_ISO_ALT_COUNT
#define CFG_TUD_BTH_ISO_ALT_COUNT 0
#endif
// Length of template descriptor: 38 bytes + number of ISO alternatives * 23
#define TUD_BTH_DESC_LEN (8 + 9 + 7 + 7 + 7 + (CFG_TUD_BTH_ISO_ALT_COUNT) * (9 + 7 + 7))
/* Primary Interface */
#define TUD_BTH_PRI_ITF(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size) \
9, TUSB_DESC_INTERFACE, _itfnum, 0, 3, TUD_BT_APP_CLASS, TUD_BT_APP_SUBCLASS, TUD_BT_PROTOCOL_PRIMARY_CONTROLLER, _stridx, \
/* Endpoint In for events */ \
7, TUSB_DESC_ENDPOINT, _ep_evt, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_evt_size), _ep_evt_interval, \
/* Endpoint In for ACL data */ \
7, TUSB_DESC_ENDPOINT, _ep_in, TUSB_XFER_BULK, U16_TO_U8S_LE(_ep_size), 1, \
/* Endpoint Out for ACL data */ \
7, TUSB_DESC_ENDPOINT, _ep_out, TUSB_XFER_BULK, U16_TO_U8S_LE(_ep_size), 1
#define TUD_BTH_ISO_ITF(_itfnum, _alt, _ep_in, _ep_out, _n) ,\
/* Interface with 2 endpoints */ \
9, TUSB_DESC_INTERFACE, _itfnum, _alt, 2, TUD_BT_APP_CLASS, TUD_BT_APP_SUBCLASS, TUD_BT_PROTOCOL_PRIMARY_CONTROLLER, 0, \
/* Isochronous endpoints */ \
7, TUSB_DESC_ENDPOINT, _ep_in, TUSB_XFER_ISOCHRONOUS, U16_TO_U8S_LE(_n), 1, \
7, TUSB_DESC_ENDPOINT, _ep_out, TUSB_XFER_ISOCHRONOUS, U16_TO_U8S_LE(_n), 1
#define _FIRST(a, ...) a
#define _REST(a, ...) __VA_ARGS__
#define TUD_BTH_ISO_ITF_0(_itfnum, ...)
#define TUD_BTH_ISO_ITF_1(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 1, _ep_in, _ep_out, _FIRST(__VA_ARGS__))
#define TUD_BTH_ISO_ITF_2(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 2, _ep_in, _ep_out, _FIRST(__VA_ARGS__)) \
TUD_BTH_ISO_ITF_1(_itfnum, _ep_in, _ep_out, _REST(__VA_ARGS__))
#define TUD_BTH_ISO_ITF_3(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 3, _ep_in, _ep_out, _FIRST(__VA_ARGS__)) \
TUD_BTH_ISO_ITF_2(_itfnum, _ep_in, _ep_out, _REST(__VA_ARGS__))
#define TUD_BTH_ISO_ITF_4(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 4, _ep_in, _ep_out, _FIRST(__VA_ARGS__)) \
TUD_BTH_ISO_ITF_3(_itfnum, _ep_in, _ep_out, _REST(__VA_ARGS__))
#define TUD_BTH_ISO_ITF_5(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 5, _ep_in, _ep_out, _FIRST(__VA_ARGS__)) \
TUD_BTH_ISO_ITF_4(_itfnum, _ep_in, _ep_out, _REST(__VA_ARGS__))
#define TUD_BTH_ISO_ITF_6(_itfnum, _ep_in, _ep_out, ...) TUD_BTH_ISO_ITF(_itfnum, (CFG_TUD_BTH_ISO_ALT_COUNT) - 6, _ep_in, _ep_out, _FIRST(__VA_ARGS__)) \
TUD_BTH_ISO_ITF_5(_itfnum, _ep_in, _ep_out, _REST(__VA_ARGS__))
#define TUD_BTH_ISO_ITFS(_itfnum, _ep_in, _ep_out, ...) \
TU_XSTRCAT(TUD_BTH_ISO_ITF_, CFG_TUD_BTH_ISO_ALT_COUNT)(_itfnum, _ep_in, _ep_out, __VA_ARGS__)
// BT Primary controller descriptor
// Interface number, string index, attributes, event endpoint, event endpoint size, interval, data in, data out, data endpoint size, iso endpoint sizes
// TODO BTH should also use IAD like CDC for composite device
#define TUD_BTH_DESCRIPTOR(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size,...) \
/* Interface Associate */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUD_BT_APP_CLASS, TUD_BT_APP_SUBCLASS, TUD_BT_PROTOCOL_PRIMARY_CONTROLLER, 0,\
TUD_BTH_PRI_ITF(_itfnum, _stridx, _ep_evt, _ep_evt_size, _ep_evt_interval, _ep_in, _ep_out, _ep_size) \
TUD_BTH_ISO_ITFS(_itfnum + 1, _ep_in + 1, _ep_out + 1, __VA_ARGS__)
//--------------------------------------------------------------------+
// CDC-NCM Descriptor Templates
//--------------------------------------------------------------------+
// Length of template descriptor
#define TUD_CDC_NCM_DESC_LEN (8+9+5+5+13+6+7+9+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_NCM_DESCRIPTOR(_itfnum, _desc_stridx, _mac_stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize, _maxsegmentsize) \
/* Interface Association */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_NETWORK_CONTROL_MODEL, 0, _desc_stridx,\
/* CDC-NCM Header */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0110),\
/* CDC-NCM Union */\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_UNION, _itfnum, (uint8_t)((_itfnum) + 1),\
/* CDC-NCM 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, \
/* CDC-NCM Functional Descriptor */\
6, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_NCM, U16_TO_U8S_LE(0x0100), 0, \
/* Endpoint Notification */\
7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 50,\
/* CDC Data Interface (default inactive) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 0, 0, TUSB_CLASS_CDC_DATA, 0, NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK, 0,\
/* CDC Data Interface (alternative active) */\
9, TUSB_DESC_INTERFACE, (uint8_t)((_itfnum)+1), 1, 2, TUSB_CLASS_CDC_DATA, 0, NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK, 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
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_USBD_H_ */
/** @} */

View File

@ -0,0 +1,117 @@
/*
* 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.
*/
#ifndef USBD_PVT_H_
#define USBD_PVT_H_
#include "osal/osal.h"
#include "common/tusb_fifo.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver API
//--------------------------------------------------------------------+
typedef struct
{
#if CFG_TUSB_DEBUG >= 2
char const* name;
#endif
void (* init ) (void);
void (* reset ) (uint8_t rhport);
uint16_t (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t max_len);
bool (* control_xfer_cb ) (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
void (* sof ) (uint8_t rhport); /* optional */
} usbd_class_driver_t;
// Invoked when initializing device stack to get additional class drivers.
// Can optionally implemented by application to extend/overwrite class driver support.
// Note: The drivers array must be accessible at all time when stack is active
usbd_class_driver_t const* usbd_app_driver_get_cb(uint8_t* driver_count) TU_ATTR_WEAK;
typedef bool (*usbd_control_xfer_cb_t)(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request);
void usbd_int_set(bool enabled);
//--------------------------------------------------------------------+
// USBD Endpoint API
//--------------------------------------------------------------------+
// Open an endpoint
bool usbd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * desc_ep);
// Close an endpoint
void usbd_edpt_close(uint8_t rhport, uint8_t ep_addr);
// Submit a usb transfer
bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
// Submit a usb ISO transfer by use of a FIFO (ring buffer) - all bytes in FIFO get transmitted
bool usbd_edpt_xfer_fifo(uint8_t rhport, uint8_t ep_addr, tu_fifo_t * ff, uint16_t total_bytes);
// Claim an endpoint before submitting a transfer.
// If caller does not make any transfer, it must release endpoint for others.
bool usbd_edpt_claim(uint8_t rhport, uint8_t ep_addr);
// Release claimed endpoint without submitting a transfer
bool usbd_edpt_release(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint is busy transferring
bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr);
// Stall endpoint
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr);
// Clear stalled endpoint
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint is stalled
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr);
// Check if endpoint is ready (not busy and not stalled)
TU_ATTR_ALWAYS_INLINE static inline
bool usbd_edpt_ready(uint8_t rhport, uint8_t ep_addr)
{
return !usbd_edpt_busy(rhport, ep_addr) && !usbd_edpt_stalled(rhport, ep_addr);
}
/*------------------------------------------------------------------*/
/* Helper
*------------------------------------------------------------------*/
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);
void usbd_defer_func( osal_task_func_t func, void* param, bool in_isr );
#ifdef __cplusplus
}
#endif
#endif /* USBD_PVT_H_ */

View File

@ -0,0 +1,179 @@
/*
* 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.
*/
#ifndef _TUSB_HCD_H_
#define _TUSB_HCD_H_
#include "common/tusb_common.h"
#include "osal/osal.h"
#include "common/tusb_fifo.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUH_ENDPOINT_MAX
#define CFG_TUH_ENDPOINT_MAX (CFG_TUH_HUB + CFG_TUH_HID*2 + CFG_TUH_MSC*2 + CFG_TUH_CDC*3)
// #ifdef TUP_HCD_ENDPOINT_MAX
// #define CFG_TUH_ENDPPOINT_MAX TUP_HCD_ENDPOINT_MAX
// #else
// #define
// #endif
#endif
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef enum
{
HCD_EVENT_DEVICE_ATTACH,
HCD_EVENT_DEVICE_REMOVE,
HCD_EVENT_XFER_COMPLETE,
// Not an HCD event, just a convenient way to defer ISR function
USBH_EVENT_FUNC_CALL,
HCD_EVENT_COUNT
} hcd_eventid_t;
typedef struct
{
uint8_t rhport;
uint8_t event_id;
uint8_t dev_addr;
union
{
// Attach, Remove
struct {
uint8_t hub_addr;
uint8_t hub_port;
uint8_t speed;
} connection;
// XFER_COMPLETE
struct {
uint8_t ep_addr;
uint8_t result;
uint32_t len;
} xfer_complete;
// FUNC_CALL
struct {
void (*func) (void*);
void* param;
}func_call;
};
} hcd_event_t;
typedef struct
{
uint8_t rhport;
uint8_t hub_addr;
uint8_t hub_port;
uint8_t speed;
} hcd_devtree_info_t;
//--------------------------------------------------------------------+
// Controller API
//--------------------------------------------------------------------+
// Initialize controller to host mode
bool hcd_init(uint8_t rhport);
// Interrupt Handler
void hcd_int_handler(uint8_t rhport);
// Enable USB interrupt
void hcd_int_enable (uint8_t rhport);
// Disable USB interrupt
void hcd_int_disable(uint8_t rhport);
// Get frame number (1ms)
uint32_t hcd_frame_number(uint8_t rhport);
//--------------------------------------------------------------------+
// Port API
//--------------------------------------------------------------------+
// Get the current connect status of roothub port
bool hcd_port_connect_status(uint8_t rhport);
// Reset USB bus on the port
void hcd_port_reset(uint8_t rhport);
// TODO implement later
void hcd_port_reset_end(uint8_t rhport);
// Get port link speed
tusb_speed_t hcd_port_speed_get(uint8_t rhport);
// HCD closes all opened endpoints belong to this device
void hcd_device_close(uint8_t rhport, uint8_t dev_addr);
//--------------------------------------------------------------------+
// Endpoints API
//--------------------------------------------------------------------+
bool hcd_setup_send(uint8_t rhport, uint8_t dev_addr, uint8_t const setup_packet[8]);
bool hcd_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * ep_desc);
bool hcd_edpt_xfer(uint8_t rhport, uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t buflen);
bool hcd_edpt_clear_stall(uint8_t dev_addr, uint8_t ep_addr);
//--------------------------------------------------------------------+
// USBH implemented API
//--------------------------------------------------------------------+
// Get device tree information of a device
// USB device tree can be complicated and manged by USBH, this help HCD to retrieve
// needed topology info to carry out its work
extern void hcd_devtree_get_info(uint8_t dev_addr, hcd_devtree_info_t* devtree_info);
//------------- Event API -------------//
// Called by HCD to notify stack
extern void hcd_event_handler(hcd_event_t const* event, bool in_isr);
// Helper to send device attach event
extern void hcd_event_device_attach(uint8_t rhport, bool in_isr);
// Helper to send device removal event
extern void hcd_event_device_remove(uint8_t rhport, bool in_isr);
// Helper to send USB transfer event
extern void hcd_event_xfer_complete(uint8_t dev_addr, uint8_t ep_addr, uint32_t xferred_bytes, xfer_result_t result, bool in_isr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HCD_H_ */

View File

@ -0,0 +1,219 @@
/*
* 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_class
* \defgroup ClassDriver_Hub Hub (Host only)
* \details Like most PC's OS, Hub support is completely hidden from Application. In fact, application cannot determine whether
* a device is mounted directly via roothub or via a hub's port. All Hub-related procedures are performed and managed
* by tinyusb stack. Unless you are trying to develop the stack itself, there are nothing else can be used by Application.
* \note Due to my laziness, only 1-level of Hub is supported. In other way, the stack cannot mount a hub via another hub.
* @{
*/
#ifndef _TUSB_HUB_H_
#define _TUSB_HUB_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//D1...D0: Logical Power Switching Mode
//00: Ganged power switching (all portspower at
//once)
//01: Individual port power switching
//1X: Reserved. Used only on 1.0 compliant hubs
//that implement no power switching
//D2: Identifies a Compound Device
//0: Hub is not part of a compound device.
//1: Hub is part of a compound device.
//D4...D3: Over-current Protection Mode
//00: Global Over-current Protection. The hub
//reports over-current as a summation of all
//portscurrent draw, without a breakdown of
//individual port over-current status.
//01: Individual Port Over-current Protection. The
//hub reports over-current on a per-port basis.
//Each port has an over-current status.
//1X: No Over-current Protection. This option is
//allowed only for bus-powered hubs that do not
//implement over-current protection.
//
//D6...D5: TT Think TIme
//00: TT requires at most 8 FS bit times of inter
//transaction gap on a full-/low-speed
//downstream bus.
//01: TT requires at most 16 FS bit times.
//10: TT requires at most 24 FS bit times.
//11: TT requires at most 32 FS bit times.
//D7: Port Indicators Supported
//0: Port Indicators are not supported on its
//downstream facing ports and the
//PORT_INDICATOR request has no effect.
//1: Port Indicators are supported on its
//downstream facing ports and the
//PORT_INDICATOR request controls the
//indicators. See Section 11.5.3.
//D15...D8: Reserved
typedef struct TU_ATTR_PACKED{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
uint8_t bNbrPorts;
uint16_t wHubCharacteristics;
uint8_t bPwrOn2PwrGood;
uint8_t bHubContrCurrent;
uint8_t DeviceRemovable; // bitmap each bit for a port (from bit1)
uint8_t PortPwrCtrlMask; // just for compatibility, should be 0xff
} descriptor_hub_desc_t;
TU_VERIFY_STATIC( sizeof(descriptor_hub_desc_t) == 9, "size is not correct");
enum {
HUB_REQUEST_GET_STATUS = 0 ,
HUB_REQUEST_CLEAR_FEATURE = 1 ,
HUB_REQUEST_SET_FEATURE = 3 ,
HUB_REQUEST_GET_DESCRIPTOR = 6 ,
HUB_REQUEST_SET_DESCRIPTOR = 7 ,
HUB_REQUEST_CLEAR_TT_BUFFER = 8 ,
HUB_REQUEST_RESET_TT = 9 ,
HUB_REQUEST_GET_TT_STATE = 10 ,
HUB_REQUEST_STOP_TT = 11
};
enum {
HUB_FEATURE_HUB_LOCAL_POWER_CHANGE = 0,
HUB_FEATURE_HUB_OVER_CURRENT_CHANGE
};
enum{
HUB_FEATURE_PORT_CONNECTION = 0,
HUB_FEATURE_PORT_ENABLE = 1,
HUB_FEATURE_PORT_SUSPEND = 2,
HUB_FEATURE_PORT_OVER_CURRENT = 3,
HUB_FEATURE_PORT_RESET = 4,
HUB_FEATURE_PORT_POWER = 8,
HUB_FEATURE_PORT_LOW_SPEED = 9,
HUB_FEATURE_PORT_CONNECTION_CHANGE = 16,
HUB_FEATURE_PORT_ENABLE_CHANGE = 17,
HUB_FEATURE_PORT_SUSPEND_CHANGE = 18,
HUB_FEATURE_PORT_OVER_CURRENT_CHANGE = 19,
HUB_FEATURE_PORT_RESET_CHANGE = 20,
HUB_FEATURE_PORT_TEST = 21,
HUB_FEATURE_PORT_INDICATOR = 22
};
// data in response of HUB_REQUEST_GET_STATUS, wIndex = 0 (hub)
typedef struct {
union{
struct TU_ATTR_PACKED {
uint16_t local_power_source : 1;
uint16_t over_current : 1;
uint16_t : 14;
};
uint16_t value;
} status, change;
} hub_status_response_t;
TU_VERIFY_STATIC( sizeof(hub_status_response_t) == 4, "size is not correct");
// data in response of HUB_REQUEST_GET_STATUS, wIndex = Port num
typedef struct {
union {
struct TU_ATTR_PACKED {
uint16_t connection : 1;
uint16_t port_enable : 1;
uint16_t suspend : 1;
uint16_t over_current : 1;
uint16_t reset : 1;
uint16_t : 3;
uint16_t port_power : 1;
uint16_t low_speed : 1;
uint16_t high_speed : 1;
uint16_t port_test_mode : 1;
uint16_t port_indicator_control : 1;
uint16_t TU_RESERVED : 3;
};
uint16_t value;
} status, change;
} hub_port_status_response_t;
TU_VERIFY_STATIC( sizeof(hub_port_status_response_t) == 4, "size is not correct");
// Clear feature
bool hub_port_clear_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Set feature
bool hub_port_set_feature (uint8_t hub_addr, uint8_t hub_port, uint8_t feature,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get port status
bool hub_port_get_status (uint8_t hub_addr, uint8_t hub_port, void* resp,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get status from Interrupt endpoint
bool hub_edpt_status_xfer(uint8_t dev_addr);
// Reset a port
static inline bool hub_port_reset(uint8_t hub_addr, uint8_t hub_port,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg)
{
return hub_port_set_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET, complete_cb, user_arg);
}
// Clear Reset Change
static inline bool hub_port_clear_reset_change(uint8_t hub_addr, uint8_t hub_port,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg)
{
return hub_port_clear_feature(hub_addr, hub_port, HUB_FEATURE_PORT_RESET_CHANGE, complete_cb, user_arg);
}
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void hub_init (void);
bool hub_open (uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const *itf_desc, uint16_t max_len);
bool hub_set_config (uint8_t dev_addr, uint8_t itf_num);
bool hub_xfer_cb (uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void hub_close (uint8_t dev_addr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HUB_H_ */
/** @} */

View File

@ -0,0 +1,208 @@
/*
* 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.
*/
#ifndef _TUSB_USBH_H_
#define _TUSB_USBH_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "common/tusb_common.h"
#include "hcd.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
// forward declaration
struct tuh_control_xfer_s;
typedef struct tuh_control_xfer_s tuh_control_xfer_t;
typedef bool (*tuh_control_xfer_cb_t)(uint8_t daddr, tuh_control_xfer_t const * xfer, xfer_result_t result);
struct tuh_control_xfer_s
{
tusb_control_request_t request TU_ATTR_ALIGNED(4);
uint8_t* buffer;
tuh_control_xfer_cb_t complete_cb;
uintptr_t user_arg;
};
//--------------------------------------------------------------------+
// APPLICATION CALLBACK
//--------------------------------------------------------------------+
//TU_ATTR_WEAK uint8_t tuh_attach_cb (tusb_desc_device_t const *desc_device);
// Invoked when device is mounted (configured)
TU_ATTR_WEAK void tuh_mount_cb (uint8_t daddr);
/// Invoked when device is unmounted (bus reset/unplugged)
TU_ATTR_WEAK void tuh_umount_cb(uint8_t daddr);
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
// Init host stack
bool tuh_init(uint8_t rhport);
// Check if host stack is already initialized
bool tuh_inited(void);
// Task function should be called in main/rtos loop
void tuh_task(void);
// Interrupt handler, name alias to HCD
extern void hcd_int_handler(uint8_t rhport);
#define tuh_int_handler hcd_int_handler
bool tuh_vid_pid_get(uint8_t daddr, uint16_t* vid, uint16_t* pid);
tusb_speed_t tuh_speed_get(uint8_t daddr);
// Check if device is connected and configured
bool tuh_mounted(uint8_t daddr);
// Check if device is suspended
TU_ATTR_ALWAYS_INLINE
static inline bool tuh_suspended(uint8_t daddr)
{
// TODO implement suspend & resume on host
(void) daddr;
return false;
}
// Check if device is ready to communicate with
TU_ATTR_ALWAYS_INLINE
static inline bool tuh_ready(uint8_t daddr)
{
return tuh_mounted(daddr) && !tuh_suspended(daddr);
}
// Carry out a control transfer
// true on success, false if there is on-going control transfer or incorrect parameters
// Blocking if complete callback is NULL, in this case 'user_arg' must contain xfer_result_t variable
bool tuh_control_xfer (uint8_t daddr, tuh_control_xfer_t const* xfer);
// Sync (blocking) version of tuh_control_xfer()
// return transfer result
uint8_t tuh_control_xfer_sync(uint8_t daddr, tuh_control_xfer_t const* xfer, uint32_t timeout_ms);
// Set Configuration (control transfer)
// config_num = 0 will un-configure device. Note: config_num = config_descriptor_index + 1
// true on success, false if there is on-going control transfer or incorrect parameters
// Blocking if complete callback is NULL, in this case 'user_arg' must contain xfer_result_t variable
bool tuh_configuration_set(uint8_t daddr, uint8_t config_num,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
//--------------------------------------------------------------------+
// Descriptors Asynchronous (non-blocking)
//--------------------------------------------------------------------+
// Get an descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get(uint8_t daddr, uint8_t type, uint8_t index, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get device descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_device(uint8_t daddr, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get configuration descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_configuration(uint8_t daddr, uint8_t index, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get HID report descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_hid_report(uint8_t daddr, uint8_t itf_num, uint8_t desc_type, uint8_t index, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get string descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
// Blocking if complete callback is NULL, in this case 'user_arg' must contain xfer_result_t variable
bool tuh_descriptor_get_string(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get manufacturer string descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_manufacturer_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get product string descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_product_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
// Get serial string descriptor (control transfer)
// true on success, false if there is on-going control transfer or incorrect parameters
bool tuh_descriptor_get_serial_string(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len,
tuh_control_xfer_cb_t complete_cb, uintptr_t user_arg);
//--------------------------------------------------------------------+
// Descriptors Synchronous (blocking)
//--------------------------------------------------------------------+
// Sync (blocking) version of tuh_descriptor_get()
// return transfer result
uint8_t tuh_descriptor_get_sync(uint8_t daddr, uint8_t type, uint8_t index, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_device()
// return transfer result
uint8_t tuh_descriptor_get_device_sync(uint8_t daddr, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_configuration()
// return transfer result
uint8_t tuh_descriptor_get_configuration_sync(uint8_t daddr, uint8_t index, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_hid_report()
// return transfer result
uint8_t tuh_descriptor_get_hid_report_sync(uint8_t daddr, uint8_t itf_num, uint8_t desc_type, uint8_t index, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_string()
// return transfer result
uint8_t tuh_descriptor_get_string_sync(uint8_t daddr, uint8_t index, uint16_t language_id, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_manufacturer_string()
// return transfer result
uint8_t tuh_descriptor_get_manufacturer_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_product_string()
// return transfer result
uint8_t tuh_descriptor_get_product_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, uint8_t timeout_ms);
// Sync (blocking) version of tuh_descriptor_get_serial_string()
// return transfer result
uint8_t tuh_descriptor_get_serial_string_sync(uint8_t daddr, uint16_t language_id, void* buffer, uint16_t len, uint8_t timeout_ms);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,86 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_USBH_CLASSDRIVER_H_
#define _TUSB_USBH_CLASSDRIVER_H_
#include "osal/osal.h"
#include "common/tusb_fifo.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver API
//--------------------------------------------------------------------+
typedef struct {
#if CFG_TUSB_DEBUG >= 2
char const* name;
#endif
void (* const init )(void);
bool (* const open )(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const * itf_desc, uint16_t max_len);
bool (* const set_config )(uint8_t dev_addr, uint8_t itf_num);
bool (* const xfer_cb )(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
void (* const close )(uint8_t dev_addr);
} usbh_class_driver_t;
// Call by class driver to tell USBH that it has complete the enumeration
void usbh_driver_set_config_complete(uint8_t dev_addr, uint8_t itf_num);
uint8_t usbh_get_rhport(uint8_t dev_addr);
uint8_t* usbh_get_enum_buf(void);
void usbh_int_set(bool enabled);
//--------------------------------------------------------------------+
// USBH Endpoint API
//--------------------------------------------------------------------+
// Open an endpoint
bool usbh_edpt_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_endpoint_t const * desc_ep);
// Submit a usb transfer
bool usbh_edpt_xfer(uint8_t dev_addr, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
// Claim an endpoint before submitting a transfer.
// If caller does not make any transfer, it must release endpoint for others.
bool usbh_edpt_claim(uint8_t dev_addr, uint8_t ep_addr);
// Release claimed endpoint without submitting a transfer
bool usbh_edpt_release(uint8_t dev_addr, uint8_t ep_addr);
// Check if endpoint transferring is complete
bool usbh_edpt_busy(uint8_t dev_addr, uint8_t ep_addr);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,89 @@
/*
* 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.
*/
#ifndef _TUSB_OSAL_H_
#define _TUSB_OSAL_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "common/tusb_common.h"
// Return immediately
#define OSAL_TIMEOUT_NOTIMEOUT (0)
// Default timeout
#define OSAL_TIMEOUT_NORMAL (10)
// Wait forever
#define OSAL_TIMEOUT_WAIT_FOREVER (UINT32_MAX)
#define OSAL_TIMEOUT_CONTROL_XFER OSAL_TIMEOUT_WAIT_FOREVER
typedef void (*osal_task_func_t)( void * );
#if CFG_TUSB_OS == OPT_OS_NONE
#include "osal_none.h"
#elif CFG_TUSB_OS == OPT_OS_FREERTOS
#include "osal_freertos.h"
#elif CFG_TUSB_OS == OPT_OS_MYNEWT
#include "osal_mynewt.h"
#elif CFG_TUSB_OS == OPT_OS_PICO
#include "osal_pico.h"
#elif CFG_TUSB_OS == OPT_OS_RTTHREAD
#include "osal_rtthread.h"
#elif CFG_TUSB_OS == OPT_OS_RTX4
#include "osal_rtx4.h"
#elif CFG_TUSB_OS == OPT_OS_CUSTOM
#include "tusb_os_custom.h" // implemented by application
#else
#error OS is not supported yet
#endif
//--------------------------------------------------------------------+
// OSAL Porting API
// Should be implemented as static inline function in osal_port.h header
/*
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef);
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr);
static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec);
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl); // TODO removed
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef);
static inline bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec);
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl);
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef);
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data);
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr);
static inline bool osal_queue_empty(osal_queue_t qhdl);
*/
//--------------------------------------------------------------------+
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_H_ */

View File

@ -0,0 +1,174 @@
/*
* 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.
*/
#ifndef _TUSB_OSAL_FREERTOS_H_
#define _TUSB_OSAL_FREERTOS_H_
// FreeRTOS Headers
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,FreeRTOS.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,semphr.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,queue.h)
#include TU_INCLUDE_PATH(CFG_TUSB_OS_INC_PATH,task.h)
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
vTaskDelay( pdMS_TO_TICKS(msec) );
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef StaticSemaphore_t osal_semaphore_def_t;
typedef SemaphoreHandle_t osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
return xSemaphoreCreateBinaryStatic(semdef);
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
if ( !in_isr )
{
return xSemaphoreGive(sem_hdl) != 0;
}
else
{
BaseType_t xHigherPriorityTaskWoken;
BaseType_t res = xSemaphoreGiveFromISR(sem_hdl, &xHigherPriorityTaskWoken);
#if CFG_TUSB_MCU == OPT_MCU_ESP32S2 || CFG_TUSB_MCU == OPT_MCU_ESP32S3
// not needed after https://github.com/espressif/esp-idf/commit/c5fd79547ac9b7bae06fa660e9f814d18d3390b7
if ( xHigherPriorityTaskWoken ) portYIELD_FROM_ISR();
#else
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
#endif
return res != 0;
}
}
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? portMAX_DELAY : pdMS_TO_TICKS(msec);
return xSemaphoreTake(sem_hdl, ticks);
}
static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl)
{
xQueueReset(sem_hdl);
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef StaticSemaphore_t osal_mutex_def_t;
typedef SemaphoreHandle_t osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
return xSemaphoreCreateMutexStatic(mdef);
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return osal_semaphore_wait(mutex_hdl, msec);
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return xSemaphoreGive(mutex_hdl);
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
static _type _name##_##buf[_depth];\
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf };
typedef struct
{
uint16_t depth;
uint16_t item_sz;
void* buf;
StaticQueue_t sq;
}osal_queue_def_t;
typedef QueueHandle_t osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
return xQueueCreateStatic(qdef->depth, qdef->item_sz, (uint8_t*) qdef->buf, &qdef->sq);
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data)
{
return xQueueReceive(qhdl, data, portMAX_DELAY);
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr)
{
if ( !in_isr )
{
return xQueueSendToBack(qhdl, data, OSAL_TIMEOUT_WAIT_FOREVER) != 0;
}
else
{
BaseType_t xHigherPriorityTaskWoken;
BaseType_t res = xQueueSendToBackFromISR(qhdl, data, &xHigherPriorityTaskWoken);
#if CFG_TUSB_MCU == OPT_MCU_ESP32S2 || CFG_TUSB_MCU == OPT_MCU_ESP32S3
// not needed after https://github.com/espressif/esp-idf/commit/c5fd79547ac9b7bae06fa660e9f814d18d3390b7
if ( xHigherPriorityTaskWoken ) portYIELD_FROM_ISR();
#else
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
#endif
return res != 0;
}
}
static inline bool osal_queue_empty(osal_queue_t qhdl)
{
return uxQueueMessagesWaiting(qhdl) == 0;
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,174 @@
/*
* 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.
*/
#ifndef OSAL_MYNEWT_H_
#define OSAL_MYNEWT_H_
#include "os/os.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
os_time_delay( os_time_ms_to_ticks32(msec) );
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef struct os_sem osal_semaphore_def_t;
typedef struct os_sem* osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
return (os_sem_init(semdef, 0) == OS_OK) ? (osal_semaphore_t) semdef : NULL;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
(void) in_isr;
return os_sem_release(sem_hdl) == OS_OK;
}
static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? OS_TIMEOUT_NEVER : os_time_ms_to_ticks32(msec);
return os_sem_pend(sem_hdl, ticks) == OS_OK;
}
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
{
// TODO implement later
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef struct os_mutex osal_mutex_def_t;
typedef struct os_mutex* osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
return (os_mutex_init(mdef) == OS_OK) ? (osal_mutex_t) mdef : NULL;
}
static inline bool osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? OS_TIMEOUT_NEVER : os_time_ms_to_ticks32(msec);
return os_mutex_pend(mutex_hdl, ticks) == OS_OK;
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return os_mutex_release(mutex_hdl) == OS_OK;
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
static _type _name##_##buf[_depth];\
static struct os_event _name##_##evbuf[_depth];\
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf, .evbuf = _name##_##evbuf};\
typedef struct
{
uint16_t depth;
uint16_t item_sz;
void* buf;
void* evbuf;
struct os_mempool mpool;
struct os_mempool epool;
struct os_eventq evq;
}osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
if ( OS_OK != os_mempool_init(&qdef->mpool, qdef->depth, qdef->item_sz, qdef->buf, "usbd queue") ) return NULL;
if ( OS_OK != os_mempool_init(&qdef->epool, qdef->depth, sizeof(struct os_event), qdef->evbuf, "usbd evqueue") ) return NULL;
os_eventq_init(&qdef->evq);
return (osal_queue_t) qdef;
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data)
{
struct os_event* ev;
ev = os_eventq_get(&qhdl->evq);
memcpy(data, ev->ev_arg, qhdl->item_sz); // copy message
os_memblock_put(&qhdl->mpool, ev->ev_arg); // put back mem block
os_memblock_put(&qhdl->epool, ev); // put back ev block
return true;
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr)
{
(void) in_isr;
// get a block from mem pool for data
void* ptr = os_memblock_get(&qhdl->mpool);
if (!ptr) return false;
memcpy(ptr, data, qhdl->item_sz);
// get a block from event pool to put into queue
struct os_event* ev = (struct os_event*) os_memblock_get(&qhdl->epool);
if (!ev)
{
os_memblock_put(&qhdl->mpool, ptr);
return false;
}
tu_memclr(ev, sizeof(struct os_event));
ev->ev_arg = ptr;
os_eventq_put(&qhdl->evq, ev);
return true;
}
static inline bool osal_queue_empty(osal_queue_t qhdl)
{
return STAILQ_EMPTY(&qhdl->evq.evq_list);
}
#ifdef __cplusplus
}
#endif
#endif /* OSAL_MYNEWT_H_ */

View File

@ -0,0 +1,179 @@
/*
* 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.
*/
#ifndef _TUSB_OSAL_NONE_H_
#define _TUSB_OSAL_NONE_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// Binary Semaphore API
//--------------------------------------------------------------------+
typedef struct
{
volatile uint16_t count;
}osal_semaphore_def_t;
typedef osal_semaphore_def_t* osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
semdef->count = 0;
return semdef;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
(void) in_isr;
sem_hdl->count++;
return true;
}
// TODO blocking for now
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
{
(void) msec;
while (sem_hdl->count == 0) { }
sem_hdl->count--;
return true;
}
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
{
sem_hdl->count = 0;
}
//--------------------------------------------------------------------+
// MUTEX API
// Within tinyusb, mutex is never used in ISR context
//--------------------------------------------------------------------+
typedef osal_semaphore_def_t osal_mutex_def_t;
typedef osal_semaphore_t osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
mdef->count = 1;
return mdef;
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return osal_semaphore_wait(mutex_hdl, msec);
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return osal_semaphore_post(mutex_hdl, false);
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
#include "common/tusb_fifo.h"
typedef struct
{
void (*interrupt_set)(bool);
tu_fifo_t ff;
}osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
// _int_set is used as mutex in OS NONE (disable/enable USB ISR)
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
uint8_t _name##_buf[_depth*sizeof(_type)]; \
osal_queue_def_t _name = { \
.interrupt_set = _int_set, \
.ff = TU_FIFO_INIT(_name##_buf, _depth, _type, false) \
}
// lock queue by disable USB interrupt
static inline void _osal_q_lock(osal_queue_t qhdl)
{
// disable dcd/hcd interrupt
qhdl->interrupt_set(false);
}
// unlock queue
static inline void _osal_q_unlock(osal_queue_t qhdl)
{
// enable dcd/hcd interrupt
qhdl->interrupt_set(true);
}
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
tu_fifo_clear(&qdef->ff);
return (osal_queue_t) qdef;
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data)
{
_osal_q_lock(qhdl);
bool success = tu_fifo_read(&qhdl->ff, data);
_osal_q_unlock(qhdl);
return success;
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr)
{
if (!in_isr) {
_osal_q_lock(qhdl);
}
bool success = tu_fifo_write(&qhdl->ff, data);
if (!in_isr) {
_osal_q_unlock(qhdl);
}
TU_ASSERT(success);
return success;
}
static inline bool osal_queue_empty(osal_queue_t qhdl)
{
// Skip queue lock/unlock since this function is primarily called
// with interrupt disabled before going into low power mode
return tu_fifo_empty(&qhdl->ff);
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_NONE_H_ */

View File

@ -0,0 +1,187 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
*
* 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.
*/
#ifndef _TUSB_OSAL_PICO_H_
#define _TUSB_OSAL_PICO_H_
#include "pico/time.h"
#include "pico/sem.h"
#include "pico/mutex.h"
#include "pico/critical_section.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
sleep_ms(msec);
}
//--------------------------------------------------------------------+
// Binary Semaphore API
//--------------------------------------------------------------------+
typedef struct semaphore osal_semaphore_def_t, *osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
sem_init(semdef, 0, 255);
return semdef;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
(void) in_isr;
sem_release(sem_hdl);
return true;
}
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
{
return sem_acquire_timeout_ms(sem_hdl, msec);
}
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
{
sem_reset(sem_hdl, 0);
}
//--------------------------------------------------------------------+
// MUTEX API
// Within tinyusb, mutex is never used in ISR context
//--------------------------------------------------------------------+
typedef struct mutex osal_mutex_def_t, *osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
mutex_init(mdef);
return mdef;
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return mutex_enter_timeout_ms(mutex_hdl, msec);
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
mutex_exit(mutex_hdl);
return true;
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
#include "common/tusb_fifo.h"
#if CFG_TUH_ENABLED
extern void hcd_int_disable(uint8_t rhport);
extern void hcd_int_enable(uint8_t rhport);
#endif
typedef struct
{
tu_fifo_t ff;
struct critical_section critsec; // osal_queue may be used in IRQs, so need critical section
} osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
uint8_t _name##_buf[_depth*sizeof(_type)]; \
osal_queue_def_t _name = { \
.ff = TU_FIFO_INIT(_name##_buf, _depth, _type, false) \
}
// lock queue by disable USB interrupt
static inline void _osal_q_lock(osal_queue_t qhdl)
{
critical_section_enter_blocking(&qhdl->critsec);
}
// unlock queue
static inline void _osal_q_unlock(osal_queue_t qhdl)
{
critical_section_exit(&qhdl->critsec);
}
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
critical_section_init(&qdef->critsec);
tu_fifo_clear(&qdef->ff);
return (osal_queue_t) qdef;
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data)
{
// TODO: revisit... docs say that mutexes are never used from IRQ context,
// however osal_queue_recieve may be. therefore my assumption is that
// the fifo mutex is not populated for queues used from an IRQ context
//assert(!qhdl->ff.mutex);
_osal_q_lock(qhdl);
bool success = tu_fifo_read(&qhdl->ff, data);
_osal_q_unlock(qhdl);
return success;
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr)
{
// TODO: revisit... docs say that mutexes are never used from IRQ context,
// however osal_queue_recieve may be. therefore my assumption is that
// the fifo mutex is not populated for queues used from an IRQ context
//assert(!qhdl->ff.mutex);
(void) in_isr;
_osal_q_lock(qhdl);
bool success = tu_fifo_write(&qhdl->ff, data);
_osal_q_unlock(qhdl);
TU_ASSERT(success);
return success;
}
static inline bool osal_queue_empty(osal_queue_t qhdl)
{
// TODO: revisit; whether this is true or not currently, tu_fifo_empty is a single
// volatile read.
// Skip queue lock/unlock since this function is primarily called
// with interrupt disabled before going into low power mode
return tu_fifo_empty(&qhdl->ff);
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_PICO_H_ */

View File

@ -0,0 +1,130 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 tfx2001 (2479727366@qq.com)
*
* 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.
*/
#ifndef _TUSB_OSAL_RTTHREAD_H_
#define _TUSB_OSAL_RTTHREAD_H_
// RT-Thread Headers
#include "rtthread.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec) {
rt_thread_mdelay(msec);
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef struct rt_semaphore osal_semaphore_def_t;
typedef rt_sem_t osal_semaphore_t;
static inline osal_semaphore_t
osal_semaphore_create(osal_semaphore_def_t *semdef) {
rt_sem_init(semdef, "tusb", 0, RT_IPC_FLAG_FIFO);
return semdef;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) {
(void) in_isr;
return rt_sem_release(sem_hdl) == RT_EOK;
}
static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec) {
return rt_sem_take(sem_hdl, rt_tick_from_millisecond(msec)) == RT_EOK;
}
static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl) {
// TODO: implement
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef struct rt_mutex osal_mutex_def_t;
typedef rt_mutex_t osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t *mdef) {
rt_mutex_init(mdef, "tusb", RT_IPC_FLAG_FIFO);
return mdef;
}
static inline bool osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec) {
return rt_mutex_take(mutex_hdl, rt_tick_from_millisecond(msec)) == RT_EOK;
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl) {
return rt_mutex_release(mutex_hdl) == RT_EOK;
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
static _type _name##_##buf[_depth]; \
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf };
typedef struct {
uint16_t depth;
uint16_t item_sz;
void *buf;
struct rt_messagequeue sq;
} osal_queue_def_t;
typedef rt_mq_t osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t *qdef) {
rt_mq_init(&(qdef->sq), "tusb", qdef->buf, qdef->item_sz,
qdef->item_sz * qdef->depth, RT_IPC_FLAG_FIFO);
return &(qdef->sq);
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void *data) {
return rt_mq_recv(qhdl, data, qhdl->msg_size, RT_WAITING_FOREVER) == RT_EOK;
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const *data, bool in_isr) {
(void) in_isr;
return rt_mq_send(qhdl, (void *)data, qhdl->msg_size) == RT_EOK;
}
static inline bool osal_queue_empty(osal_queue_t qhdl) {
return (qhdl->entry) == 0;
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_RTTHREAD_H_ */

View File

@ -0,0 +1,170 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Tian Yunhao (t123yh)
* 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.
*/
#ifndef _TUSB_OSAL_RTX4_H_
#define _TUSB_OSAL_RTX4_H_
#include <rtl.h>
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
uint16_t hi = msec >> 16;
uint16_t lo = msec;
while (hi--) {
os_dly_wait(0xFFFE);
}
os_dly_wait(lo);
}
static inline uint16_t msec2wait(uint32_t msec) {
if (msec == OSAL_TIMEOUT_WAIT_FOREVER)
return 0xFFFF;
else if (msec >= 0xFFFE)
return 0xFFFE;
else
return msec;
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef OS_SEM osal_semaphore_def_t;
typedef OS_ID osal_semaphore_t;
static inline OS_ID osal_semaphore_create(osal_semaphore_def_t* semdef) {
os_sem_init(semdef, 0);
return semdef;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr) {
if ( !in_isr ) {
os_sem_send(sem_hdl);
} else {
isr_sem_send(sem_hdl);
}
return true;
}
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec) {
return os_sem_wait(sem_hdl, msec2wait(msec)) != OS_R_TMO;
}
static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl) {
// TODO: implement
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef OS_MUT osal_mutex_def_t;
typedef OS_ID osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
os_mut_init(mdef);
return mdef;
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return os_mut_wait(mutex_hdl, msec2wait(msec)) != OS_R_TMO;
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return os_mut_release(mutex_hdl) == OS_R_OK;
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_int_set, _name, _depth, _type) \
os_mbx_declare(_name##__mbox, _depth); \
_declare_box(_name##__pool, sizeof(_type), _depth); \
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .pool = _name##__pool, .mbox = _name##__mbox };
typedef struct
{
uint16_t depth;
uint16_t item_sz;
U32* pool;
U32* mbox;
}osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
os_mbx_init(qdef->mbox, (qdef->depth + 4) * 4);
_init_box(qdef->pool, ((qdef->item_sz+3)/4)*(qdef->depth) + 3, qdef->item_sz);
return qdef;
}
static inline bool osal_queue_receive(osal_queue_t qhdl, void* data)
{
void* buf;
os_mbx_wait(qhdl->mbox, &buf, 0xFFFF);
memcpy(data, buf, qhdl->item_sz);
_free_box(qhdl->pool, buf);
return true;
}
static inline bool osal_queue_send(osal_queue_t qhdl, void const * data, bool in_isr)
{
void* buf = _alloc_box(qhdl->pool);
memcpy(buf, data, qhdl->item_sz);
if ( !in_isr )
{
os_mbx_send(qhdl->mbox, buf, 0xFFFF);
}
else
{
isr_mbx_send(qhdl->mbox, buf);
}
return true;
}
static inline bool osal_queue_empty(osal_queue_t qhdl)
{
return os_mbx_check(qhdl->mbox) == qhdl->depth;
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,50 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _CI_HS_IMXRT_H_
#define _CI_HS_IMXRT_H_
#include "fsl_device_registers.h"
static const ci_hs_controller_t _ci_controller[] =
{
// RT1010 and RT1020 only has 1 USB controller
#if FSL_FEATURE_SOC_USBHS_COUNT == 1
{ .reg_base = USB_BASE , .irqnum = USB_OTG1_IRQn, .ep_count = 8 }
#else
{ .reg_base = USB1_BASE, .irqnum = USB_OTG1_IRQn, .ep_count = 8 },
{ .reg_base = USB2_BASE, .irqnum = USB_OTG2_IRQn, .ep_count = 8 }
#endif
};
#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#endif

View File

@ -0,0 +1,45 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _CI_HS_LPC18_43_H_
#define _CI_HS_LPC18_43_H_
// LPCOpen for 18xx & 43xx
#include "chip.h"
static const ci_hs_controller_t _ci_controller[] =
{
{ .reg_base = LPC_USB0_BASE, .irqnum = USB0_IRQn, .ep_count = 6 },
{ .reg_base = LPC_USB1_BASE, .irqnum = USB1_IRQn, .ep_count = 4 }
};
#define CI_DCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_DCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#define CI_HCD_INT_ENABLE(_p) NVIC_EnableIRQ (_ci_controller[_p].irqnum)
#define CI_HCD_INT_DISABLE(_p) NVIC_DisableIRQ(_ci_controller[_p].irqnum)
#endif

View File

@ -0,0 +1,144 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef CI_HS_TYPE_H_
#define CI_HS_TYPE_H_
#ifdef __cplusplus
extern "C" {
#endif
// USBCMD
enum {
USBCMD_RUN_STOP = TU_BIT(0),
USBCMD_RESET = TU_BIT(1),
USBCMD_SETUP_TRIPWIRE = TU_BIT(13),
USBCMD_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoints linked list. This bit is set and cleared by software during the process of adding a new dTD
// Interrupt Threshold bit 23:16
};
// PORTSC1
#define PORTSC1_PORT_SPEED_POS 26
enum {
PORTSC1_CURRENT_CONNECT_STATUS = TU_BIT(0),
PORTSC1_FORCE_PORT_RESUME = TU_BIT(6),
PORTSC1_SUSPEND = TU_BIT(7),
PORTSC1_FORCE_FULL_SPEED = TU_BIT(24),
PORTSC1_PORT_SPEED = TU_BIT(26) | TU_BIT(27)
};
// OTGSC
enum {
OTGSC_VBUS_DISCHARGE = TU_BIT(0),
OTGSC_VBUS_CHARGE = TU_BIT(1),
// OTGSC_HWASSIST_AUTORESET = TU_BIT(2),
OTGSC_OTG_TERMINATION = TU_BIT(3), ///< Must set to 1 when OTG go to device mode
OTGSC_DATA_PULSING = TU_BIT(4),
OTGSC_ID_PULLUP = TU_BIT(5),
// OTGSC_HWASSIT_DATA_PULSE = TU_BIT(6),
// OTGSC_HWASSIT_BDIS_ACONN = TU_BIT(7),
OTGSC_ID = TU_BIT(8), ///< 0 = A device, 1 = B Device
OTGSC_A_VBUS_VALID = TU_BIT(9),
OTGSC_A_SESSION_VALID = TU_BIT(10),
OTGSC_B_SESSION_VALID = TU_BIT(11),
OTGSC_B_SESSION_END = TU_BIT(12),
OTGSC_1MS_TOGGLE = TU_BIT(13),
OTGSC_DATA_BUS_PULSING_STATUS = TU_BIT(14),
};
// USBMode
enum {
USBMODE_CM_DEVICE = 2,
USBMODE_CM_HOST = 3,
USBMODE_SLOM = TU_BIT(3),
USBMODE_SDIS = TU_BIT(4),
USBMODE_VBUS_POWER_SELECT = TU_BIT(5), // Need to be enabled for LPC18XX/43XX in host mode
};
// Device Registers
typedef struct
{
//------------- ID + HW Parameter Registers-------------//
volatile uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX
//------------- Capability Registers-------------//
volatile uint8_t CAPLENGTH; ///< Capability Registers Length
volatile uint8_t TU_RESERVED[1];
volatile uint16_t HCIVERSION; ///< Host Controller Interface Version
volatile uint32_t HCSPARAMS; ///< Host Controller Structural Parameters
volatile uint32_t HCCPARAMS; ///< Host Controller Capability Parameters
volatile uint32_t TU_RESERVED[5];
volatile uint16_t DCIVERSION; ///< Device Controller Interface Version
volatile uint8_t TU_RESERVED[2];
volatile uint32_t DCCPARAMS; ///< Device Controller Capability Parameters
volatile uint32_t TU_RESERVED[6];
//------------- Operational Registers -------------//
volatile uint32_t USBCMD; ///< USB Command Register
volatile uint32_t USBSTS; ///< USB Status Register
volatile uint32_t USBINTR; ///< Interrupt Enable Register
volatile uint32_t FRINDEX; ///< USB Frame Index
volatile uint32_t TU_RESERVED;
volatile uint32_t DEVICEADDR; ///< Device Address
volatile uint32_t ENDPTLISTADDR; ///< Endpoint List Address
volatile uint32_t TU_RESERVED;
volatile uint32_t BURSTSIZE; ///< Programmable Burst Size
volatile uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning
uint32_t TU_RESERVED[4];
volatile uint32_t ENDPTNAK; ///< Endpoint NAK
volatile uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable
volatile uint32_t TU_RESERVED;
volatile uint32_t PORTSC1; ///< Port Status & Control
volatile uint32_t TU_RESERVED[7];
volatile uint32_t OTGSC; ///< On-The-Go Status & control
volatile uint32_t USBMODE; ///< USB Device Mode
volatile uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status
volatile uint32_t ENDPTPRIME; ///< Endpoint Prime
volatile uint32_t ENDPTFLUSH; ///< Endpoint Flush
volatile uint32_t ENDPTSTAT; ///< Endpoint Status
volatile uint32_t ENDPTCOMPLETE; ///< Endpoint Complete
volatile uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7
} ci_hs_regs_t;
typedef struct
{
uint32_t reg_base;
uint32_t irqnum;
uint8_t ep_count; // Max bi-directional Endpoints
}ci_hs_controller_t;
#ifdef __cplusplus
}
#endif
#endif /* CI_HS_TYPE_H_ */

View File

@ -0,0 +1,420 @@
/*
* 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.
*/
#ifndef _TUSB_EHCI_H_
#define _TUSB_EHCI_H_
/* Abbreviation
* HC: Host Controller
* HCD: Host Controller Driver
* QHD: Queue Head for non-ISO transfer
* QTD: Queue Transfer Descriptor for non-ISO transfer
* ITD: Iso Transfer Descriptor for highspeed
* SITD: Split ISO Transfer Descriptor for full-speed
* SMASK: Start Split mask for Slipt Transaction
* CMASK: Complete Split mask for Slipt Transaction
*/
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// EHCI CONFIGURATION & CONSTANTS
//--------------------------------------------------------------------+
// TODO merge OHCI with EHCI
enum {
EHCI_MAX_ITD = 4,
EHCI_MAX_SITD = 16
};
//--------------------------------------------------------------------+
// EHCI Data Structure
//--------------------------------------------------------------------+
enum
{
EHCI_QTYPE_ITD = 0 ,
EHCI_QTYPE_QHD ,
EHCI_QTYPE_SITD ,
EHCI_QTYPE_FSTN
};
/// EHCI PID
enum
{
EHCI_PID_OUT = 0 ,
EHCI_PID_IN ,
EHCI_PID_SETUP
};
/// Link pointer
typedef union {
uint32_t address;
struct {
uint32_t terminate : 1;
uint32_t type : 2;
};
}ehci_link_t;
/// Queue Element Transfer Descriptor
/// Qtd is used to declare overlay in ehci_qhd_t -> cannot be declared with TU_ATTR_ALIGNED(32)
typedef struct
{
// Word 0: Next QTD Pointer
ehci_link_t next;
// Word 1: Alternate Next QTD Pointer (not used)
union{
ehci_link_t alternate;
struct {
uint32_t : 5;
uint32_t used : 1;
uint32_t : 10;
uint32_t expected_bytes : 16;
};
};
// Word 2: qTQ Token
volatile uint32_t ping_err : 1 ; ///< For Highspeed: 0 Out, 1 Ping. Full/Slow used as error indicator
volatile uint32_t non_hs_split_state : 1 ; ///< Used by HC to track the state of split transaction
volatile uint32_t non_hs_missed_uframe : 1 ; ///< HC misses a complete split transaction
volatile uint32_t xact_err : 1 ; ///< Error (Timeout, CRC, Bad PID ... )
volatile uint32_t babble_err : 1 ; ///< Babble detected, also set Halted bit to 1
volatile uint32_t buffer_err : 1 ; ///< Data overrun/underrun error
volatile uint32_t halted : 1 ; ///< Serious error or STALL received
volatile uint32_t active : 1 ; ///< Start transfer, clear by HC when complete
uint32_t pid : 2 ; ///< 0: OUT, 1: IN, 2 Setup
volatile uint32_t err_count : 2 ; ///< Error Counter of consecutive errors
volatile uint32_t current_page : 3 ; ///< Index into the qTD buffer pointer list
uint32_t int_on_complete : 1 ; ///< Interrupt on complete
volatile uint32_t total_bytes : 15 ; ///< Transfer bytes, decreased during transaction
volatile uint32_t data_toggle : 1 ; ///< Data Toogle bit
/// Buffer Page Pointer List, Each element in the list is a 4K page aligned, physical memory address. The lower 12 bits in each pointer are reserved (except for the first one) as each memory pointer must reference the start of a 4K page
uint32_t buffer[5];
} ehci_qtd_t;
TU_VERIFY_STATIC( sizeof(ehci_qtd_t) == 32, "size is not correct" );
/// Queue Head
typedef struct TU_ATTR_ALIGNED(32)
{
// Word 0: Next QHD
ehci_link_t next;
// Word 1: Endpoint Characteristics
uint32_t dev_addr : 7 ; ///< device address
uint32_t fl_inactive_next_xact : 1 ; ///< Only valid for Periodic with Full/Slow speed
uint32_t ep_number : 4 ; ///< EP number
uint32_t ep_speed : 2 ; ///< 0: Full, 1: Low, 2: High
uint32_t data_toggle_control : 1 ; ///< 0: use DT in qHD, 1: use DT in qTD
uint32_t head_list_flag : 1 ; ///< Head of the queue
uint32_t max_packet_size : 11 ; ///< Max packet size
uint32_t fl_ctrl_ep_flag : 1 ; ///< 1 if is Full/Low speed control endpoint
uint32_t nak_reload : 4 ; ///< Used by HC
// Word 2: Endpoint Capabilities
uint32_t int_smask : 8 ; ///< Interrupt Schedule Mask
uint32_t fl_int_cmask : 8 ; ///< Split Completion Mask for Full/Slow speed
uint32_t fl_hub_addr : 7 ; ///< Hub Address for Full/Slow speed
uint32_t fl_hub_port : 7 ; ///< Hub Port for Full/Slow speed
uint32_t mult : 2 ; ///< Transaction per micro frame
// Word 3: Current qTD Pointer
volatile uint32_t qtd_addr;
// Word 4-11: Transfer Overlay
volatile ehci_qtd_t qtd_overlay;
//--------------------------------------------------------------------+
/// Due to the fact QHD is 32 bytes aligned but occupies only 48 bytes
/// thus there are 16 bytes padding free that we can make use of.
//--------------------------------------------------------------------+
uint8_t used;
uint8_t removing; // removed from asyn list, waiting for async advance
uint8_t pid;
uint8_t interval_ms; // polling interval in frames (or milisecond)
uint16_t total_xferred_bytes; // number of bytes xferred until a qtd with ioc bit set
uint8_t reserved2[2];
ehci_qtd_t * volatile p_qtd_list_head; // head of the scheduled TD list
ehci_qtd_t * volatile p_qtd_list_tail; // tail of the scheduled TD list
} ehci_qhd_t;
TU_VERIFY_STATIC( sizeof(ehci_qhd_t) == 64, "size is not correct" );
/// Highspeed Isochronous Transfer Descriptor (section 3.3)
typedef struct TU_ATTR_ALIGNED(32) {
// Word 0: Next Link Pointer
ehci_link_t next;
// Word 1-8: iTD Transaction Status and Control List
struct {
// iTD Control
volatile uint32_t offset : 12 ; ///< This field is a value that is an offset, expressed in bytes, from the beginning of a buffer.
volatile uint32_t page_select : 3 ; ///< These bits are set by software to indicate which of the buffer page pointers the offset field in this slot should be concatenated to produce the starting memory address for this transaction. The valid range of values for this field is 0 to 6
uint32_t int_on_complete : 1 ; ///< If this bit is set to a one, it specifies that when this transaction completes, the Host Controller should issue an interrupt at the next interrupt threshold
volatile uint32_t length : 12 ; ///< For an OUT, this field is the number of data bytes the host controller will send during the transaction. The host controller is not required to update this field to reflect the actual number of bytes transferred during the transfer
///< For an IN, the initial value of the field is the number of bytes the host expects the endpoint to deliver. During the status update, the host controller writes back the number of bytes successfully received. The value in this register is the actual byte count
// iTD Status
volatile uint32_t error : 1 ; ///< Set to a one by the Host Controller during status update in the case where the host did not receive a valid response from the device (Timeout, CRC, Bad PID, etc.). This bit may only be set for isochronous IN transactions.
volatile uint32_t babble_err : 1 ; ///< Set to a 1 by the Host Controller during status update when a babble is detected during the transaction
volatile uint32_t buffer_err : 1 ; ///< Set to a 1 by the Host Controller during status update to indicate that the Host Controller is unable to keep up with the reception of incoming data (overrun) or is unable to supply data fast enough during transmission (underrun).
volatile uint32_t active : 1 ; ///< Set to 1 by software to enable the execution of an isochronous transaction by the Host Controller
} xact[8];
// Word 9-15 Buffer Page Pointer List (Plus)
uint32_t BufferPointer[7];
// // FIXME: Store meta data into buffer pointer reserved for saving memory
// /*---------- HCD Area ----------*/
// uint32_t used;
// uint32_t IhdIdx;
// uint32_t reserved[6];
} ehci_itd_t;
TU_VERIFY_STATIC( sizeof(ehci_itd_t) == 64, "size is not correct" );
/// Split (Full-Speed) Isochronous Transfer Descriptor
typedef struct TU_ATTR_ALIGNED(32)
{
// Word 0: Next Link Pointer
ehci_link_t next;
// Word 1: siTD Endpoint Characteristics
uint32_t dev_addr : 7; ///< This field selects the specific device serving as the data source or sink.
uint32_t : 1; ///< reserved
uint32_t ep_number : 4; ///< This 4-bit field selects the particular endpoint number on the device serving as the data source or sink.
uint32_t : 4; ///< This field is reserved and should be set to zero.
uint32_t hub_addr : 7; ///< This field holds the device address of the transaction translators hub.
uint32_t : 1; ///< reserved
uint32_t port_number : 7; ///< This field is the port number of the recipient transaction translator.
uint32_t direction : 1; ///< 0 = OUT; 1 = IN. This field encodes whether the full-speed transaction should be an IN or OUT.
// Word 2: Micro-frame Schedule Control
uint8_t int_smask ; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute complete-split transactions
uint8_t fl_int_cmask; ///< This field (along with the Activeand SplitX-statefields in the Statusbyte) are used to determine during which micro-frames the host controller should execute start-split transactions.
uint16_t reserved ; ///< reserved
// Word 3: siTD Transfer Status and Control
// Status [7:0] TODO indentical to qTD Token'status --> refractor later
volatile uint32_t : 1 ; // reserved
volatile uint32_t split_state : 1 ;
volatile uint32_t missed_uframe : 1 ;
volatile uint32_t xact_err : 1 ;
volatile uint32_t babble_err : 1 ;
volatile uint32_t buffer_err : 1 ;
volatile uint32_t error : 1 ;
volatile uint32_t active : 1 ;
// Micro-frame Schedule Control
volatile uint32_t cmask_progress : 8 ; ///< This field is used by the host controller to record which split-completes have been executed. See Section 4.12.3.3.2 for behavioral requirements.
volatile uint32_t total_bytes : 10 ; ///< This field is initialized by software to the total number of bytes expected in this transfer. Maximum value is 1023
volatile uint32_t : 4 ; ///< reserved
volatile uint32_t page_select : 1 ; ///< Used to indicate which data page pointer should be concatenated with the CurrentOffsetfield to construct a data buffer pointer
uint32_t int_on_complete : 1 ; ///< Do not interrupt when transaction is complete. 1 = Do interrupt when transaction is complete
uint32_t : 0 ; // padding to the end of current storage unit
/// Word 4-5: Buffer Pointer List
uint32_t buffer[2]; // buffer[1] TP: Transaction Position - T-Count: Transaction Count
// union{
// uint32_t BufferPointer1;
// struct {
// volatile uint32_t TCount : 3;
// volatile uint32_t TPosition : 2;
// };
// };
/*---------- Word 6 ----------*/
ehci_link_t back;
/// SITD is 32-byte aligned but occupies only 28 --> 4 bytes for storing extra data
uint8_t used;
uint8_t ihd_idx;
uint8_t reserved2[2];
} ehci_sitd_t;
TU_VERIFY_STATIC( sizeof(ehci_sitd_t) == 32, "size is not correct" );
//--------------------------------------------------------------------+
// EHCI Operational Register
//--------------------------------------------------------------------+
enum ehci_interrupt_mask_{
EHCI_INT_MASK_USB = TU_BIT(0),
EHCI_INT_MASK_ERROR = TU_BIT(1),
EHCI_INT_MASK_PORT_CHANGE = TU_BIT(2),
EHCI_INT_MASK_FRAMELIST_ROLLOVER = TU_BIT(3),
EHCI_INT_MASK_PCI_HOST_SYSTEM_ERROR = TU_BIT(4),
EHCI_INT_MASK_ASYNC_ADVANCE = TU_BIT(5),
EHCI_INT_MASK_NXP_SOF = TU_BIT(7),
EHCI_INT_MASK_NXP_ASYNC = TU_BIT(18),
EHCI_INT_MASK_NXP_PERIODIC = TU_BIT(19),
EHCI_INT_MASK_ALL =
EHCI_INT_MASK_USB | EHCI_INT_MASK_ERROR | EHCI_INT_MASK_PORT_CHANGE |
EHCI_INT_MASK_FRAMELIST_ROLLOVER | EHCI_INT_MASK_PCI_HOST_SYSTEM_ERROR |
EHCI_INT_MASK_ASYNC_ADVANCE | EHCI_INT_MASK_NXP_SOF |
EHCI_INT_MASK_NXP_ASYNC | EHCI_INT_MASK_NXP_PERIODIC
};
enum ehci_usbcmd_pos_ {
EHCI_USBCMD_POS_RUN_STOP = 0,
EHCI_USBCMD_POS_FRAMELIST_SIZE = 2,
EHCI_USBCMD_POS_PERIOD_ENABLE = 4,
EHCI_USBCMD_POS_ASYNC_ENABLE = 5,
EHCI_USBCMD_POS_NXP_FRAMELIST_SIZE_MSB = 15,
EHCI_USBCMD_POS_INTERRUPT_THRESHOLD = 16
};
enum ehci_portsc_change_mask_{
EHCI_PORTSC_MASK_CURRENT_CONNECT_STATUS = TU_BIT(0),
EHCI_PORTSC_MASK_CONNECT_STATUS_CHANGE = TU_BIT(1),
EHCI_PORTSC_MASK_PORT_EANBLED = TU_BIT(2),
EHCI_PORTSC_MASK_PORT_ENABLE_CHAGNE = TU_BIT(3),
EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE = TU_BIT(5),
EHCI_PORTSC_MASK_PORT_RESET = TU_BIT(8),
EHCI_PORTSC_MASK_ALL =
EHCI_PORTSC_MASK_CONNECT_STATUS_CHANGE |
EHCI_PORTSC_MASK_PORT_ENABLE_CHAGNE |
EHCI_PORTSC_MASK_OVER_CURRENT_CHANGE
};
typedef volatile struct
{
union {
uint32_t command;
struct {
uint32_t run_stop : 1 ; ///< 1=Run. 0=Stop
uint32_t reset : 1 ; ///< SW write 1 to reset HC, clear by HC when complete
uint32_t framelist_size : 2 ; ///< Frame List size 0: 1024, 1: 512, 2: 256
uint32_t periodic_enable : 1 ; ///< This bit controls whether the host controller skips processing the Periodic Schedule. Values mean: 0b Do not process the Periodic Schedule 1b Use the PERIODICLISTBASE register to access the Periodic Schedule.
uint32_t async_enable : 1 ; ///< This bit controls whether the host controller skips processing the Asynchronous Schedule. Values mean: 0b Do not process the Asynchronous Schedule 1b Use the ASYNCLISTADDR register to access the Asynchronous Schedule.
uint32_t async_adv_doorbell : 1 ; ///< Tell HC to interrupt next time it advances async list. Clear by HC
uint32_t light_reset : 1 ; ///< Reset HC without affecting ports state
uint32_t async_park_count : 2 ; ///< not used by tinyusb
uint32_t : 1 ;
uint32_t async_park_enable : 1 ; ///< Enable park mode, not used by tinyusb
uint32_t : 3 ;
uint32_t nxp_framelist_size_msb : 1 ; ///< NXP customized : Bit 2 of the Frame List Size bits \n 011b: 128 elements \n 100b: 64 elements \n 101b: 32 elements \n 110b: 16 elements \n 111b: 8 elements
uint32_t int_threshold : 8 ; ///< Default 08h. Interrupt rate in unit of micro frame
}command_bm;
};
union {
uint32_t status;
struct {
uint32_t usb : 1 ; ///< qTD with IOC is retired
uint32_t usb_error : 1 ; ///< qTD retired due to error
uint32_t port_change_detect : 1 ; ///< Set when PortOwner or ForcePortResume change from 0 -> 1
uint32_t framelist_rollover : 1 ; ///< R/WC The Host Controller sets this bit to a one when the Frame List Index(see Section 2.3.4) rolls over from its maximum value to zero. The exact value at which the rollover occurs depends on the frame list size. For example, if the frame list size (as programmed in the Frame List Sizefield of the USBCMD register) is 1024, the Frame Index Registerrolls over every time FRINDEX[13] toggles. Similarly, if the size is 512, the Host Controller sets this bit to a one every time FRINDEX[12] toggles.
uint32_t pci_host_system_error : 1 ; ///< R/WC (not used by NXP) The Host Controller sets this bit to 1 when a serious error occurs during a host system access involving the Host Controller module. In a PCI system, conditions that set this bit to 1 include PCI Parity error, PCI Master Abort, and PCI Target Abort. When this error occurs, the Host Controller clears the Run/Stop bit in the Command register to prevent further execution of the scheduled TDs.
uint32_t async_adv : 1 ; ///< Async Advance interrupt
uint32_t : 1 ;
uint32_t nxp_int_sof : 1 ; ///< NXP customized: this bit will be set every 125us and can be used by host controller driver as a time base.
uint32_t : 4 ;
uint32_t hc_halted : 1 ; ///< Opposite value to run_stop bit.
uint32_t reclamation : 1 ; ///< Used to detect empty async shecudle
uint32_t periodic_status : 1 ; ///< Periodic schedule status
uint32_t async_status : 1 ; ///< Async schedule status
uint32_t : 2 ;
uint32_t nxp_int_async : 1 ; ///< NXP customized: This bit is set by the Host Controller when the cause of an interrupt is a completion of a USB transaction where the Transfer Descriptor (TD) has an interrupt on complete (IOC) bit set andthe TD was from the asynchronous schedule. This bit is also set by the Host when a short packet is detected andthe packet is on the asynchronous schedule.
uint32_t nxp_int_period : 1 ; ///< NXP customized: This bit is set by the Host Controller when the cause of an interrupt is a completion of a USB transaction where the Transfer Descriptor (TD) has an interrupt on complete (IOC) bit set andthe TD was from the periodic schedule.
uint32_t : 12 ;
}status_bm;
};
union{
uint32_t inten;
struct {
uint32_t usb : 1 ;
uint32_t usb_error : 1 ;
uint32_t port_change_detect : 1 ;
uint32_t framelist_rollover : 1 ;
uint32_t pci_host_system_error : 1 ;
uint32_t async_adv : 1 ;
uint32_t : 1 ;
uint32_t nxp_int_sof : 1 ;
uint32_t : 10 ;
uint32_t nxp_int_async : 1 ;
uint32_t nxp_int_period : 1 ;
uint32_t : 12 ;
}inten_bm;
};
uint32_t frame_index ; ///< Micro frame counter
uint32_t ctrl_ds_seg ; ///< Control Data Structure Segment
uint32_t periodic_list_base ; ///< Beginning address of perodic frame list
uint32_t async_list_addr ; ///< Address of next async QHD to be executed
uint32_t nxp_tt_control ; ///< nxp embedded transaction translator (reserved by EHCI specs)
uint32_t reserved[8] ;
uint32_t config_flag ; ///< not used by NXP
union {
uint32_t portsc ; ///< port status and control
struct {
uint32_t current_connect_status : 1; ///< 0: No device, 1: Device is present on port
uint32_t connect_status_change : 1; ///< Change in Current Connect Status
uint32_t port_enabled : 1; ///< Ports can only be enabled by HC as a part of the reset and enable. SW can write 0 to disable
uint32_t port_enable_change : 1; ///< Port Enabled has changed
uint32_t over_current_active : 1; ///< Port has an over-current condition
uint32_t over_current_change : 1; ///< Change to Over-current Active
uint32_t force_port_resume : 1; ///< Resume detected/driven on port. This functionality defined for manipulating this bit depends on the value of the Suspend bit.
uint32_t suspend : 1; ///< Port in suspend state
uint32_t port_reset : 1; ///< 1=Port is in Reset. 0=Port is not in Reset
uint32_t nxp_highspeed_status : 1; ///< NXP customized: 0=connected to the port is not in High-speed mode, 1=connected to the port is in High-speed mode
uint32_t line_status : 2; ///< D+/D- state: 00: SE0, 10: J-state, 01: K-state
uint32_t port_power : 1; ///< 0= power off, 1= power on
uint32_t port_owner : 1; ///< not used by NXP
uint32_t port_indicator_control : 2; ///< 00b: off, 01b: Amber, 10b: green, 11b: undefined
uint32_t port_test_control : 4; ///< Port test mode, not used by tinyusb
uint32_t wake_on_connect_enable : 1; ///< Enables device connects as wake-up events
uint32_t wake_on_disconnect_enable : 1; ///< Enables device disconnects as wake-up events
uint32_t wake_on_over_current_enable : 1; ///< Enables over-current conditions as wake-up events
uint32_t nxp_phy_clock_disable : 1; ///< NXP customized: the PHY can be put into Low Power Suspend Clock Disable when the downstream device has been put into suspend mode or when no downstream device is connected. Low power suspend is completely under the control of software. 0: enable PHY clock, 1: disable PHY clock
uint32_t nxp_port_force_fullspeed : 1; ///< NXP customized: Writing this bit to a 1 will force the port to only connect at Full Speed. It disables the chirp sequence that allowsthe port to identify itself as High Speed. This is useful for testing FS configurations with a HS host, hub or device.
uint32_t TU_RESERVED : 1;
uint32_t nxp_port_speed : 2; ///< NXP customized: This register field indicates the speed atwhich the port is operating. For HS mode operation in the host controllerand HS/FS operation in the device controller the port routing steers data to the Protocol engine. For FS and LS mode operation in the host controller, the port routing steers data to the Protocol Engine w/ Embedded Transaction Translator. 0x0: Fullspeed, 0x1: Lowspeed, 0x2: Highspeed
uint32_t TU_RESERVED : 4;
}portsc_bm;
};
}ehci_registers_t;
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_EHCI_H_ */

View File

@ -0,0 +1,45 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_EHCI_API_H_
#define _TUSB_EHCI_API_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// API Implemented by EHCI
//--------------------------------------------------------------------+
// Initialize EHCI driver
bool ehci_init(uint8_t rhport, uint32_t capability_reg, uint32_t operatial_reg);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,40 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_MUSB_MSP432E_H_
#define _TUSB_MUSB_MSP432E_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "msp.h"
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,45 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_MUSB_TM4C_H_
#define _TUSB_MUSB_TM4C_H_
#ifdef __cplusplus
extern "C" {
#endif
#if CFG_TUSB_MCU == OPT_MCU_TM4C123
#include "TM4C123.h"
//#elif CFG_TUSB_MCU == OPT_MCU_TM4C129
#else
#error "Unsupported MCUs"
#endif
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,931 @@
/*******************************************************************************
* Copyright (C) 2019 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*******************************************************************************/
/*******************************************************************************
USBHS Peripheral Library Register Defintions
File Name:
usbhs_registers.h
Summary:
USBHS PLIB Register Defintions
Description:
This file contains the constants and defintions which are required by the
the USBHS library.
*******************************************************************************/
#ifndef __USBHS_REGISTERS_H__
#define __USBHS_REGISTERS_H__
#include <p32xxxx.h>
#include <stdint.h>
/*****************************************
* Module Register Offsets.
*****************************************/
#define USBHS_REG_FADDR 0x000
#define USBHS_REG_POWER 0x001
#define USBHS_REG_INTRTX 0x002
#define USBHS_REG_INTRRX 0x004
#define USBHS_REG_INTRTXE 0x006
#define USBHS_REG_INTRRXE 0x008
#define USBHS_REG_INTRUSB 0x00A
#define USBHS_REG_INTRUSBE 0x00B
#define USBHS_REG_FRAME 0x00C
#define USBHS_REG_INDEX 0x00E
#define USBHS_REG_TESTMODE 0x00F
/*******************************************************
* Endpoint Control Status Registers (CSR). These values
* should be added to either the 0x10 to access the
* register through Indexed CSR. To access the actual
* CSR, see ahead in this header file.
******************************************************/
#define USBHS_REG_EP_TXMAXP 0x000
#define USBHS_REG_EP_CSR0L 0x002
#define USBHS_REG_EP_CSR0H 0x003
#define USBHS_REG_EP_TXCSRL 0x002
#define USBHS_REG_EP_TXCSRH 0x003
#define USBHS_REG_EP_RXMAXP 0x004
#define USBHS_REG_EP_RXCSRL 0x006
#define USBHS_REG_EP_RXCSRH 0x007
#define USBHS_REG_EP_COUNT0 0x008
#define USBHS_REG_EP_RXCOUNT 0x008
#define USBHS_REG_EP_TYPE0 0x01A
#define USBHS_REG_EP_TXTYPE 0x01A
#define USBHS_REG_EP_NAKLIMIT0 0x01B
#define USBHS_REG_EP_TXINTERVAL 0x01B
#define USBHS_REG_EP_RXTYPE 0x01C
#define USBHS_REG_EP_RXINTERVAL 0x01D
#define USBHS_REG_EP_CONFIGDATA 0x01F
#define USBHS_REG_EP_FIFOSIZE 0x01F
#define USBHS_HOST_EP0_SETUPKT_SET 0x8
#define USBHS_HOST_EP0_TXPKTRDY_SET 0x2
#define USBHS_SOFT_RST_NRST_SET 0x1
#define USBHS_SOFT_RST_NRSTX_SET 0x2
#define USBHS_EP0_DEVICE_SERVICED_RXPKTRDY 0x40
#define USBHS_EP0_DEVICE_DATAEND 0x08
#define USBHS_EP0_DEVICE_TXPKTRDY 0x02
#define USBHS_EP0_HOST_STATUS_STAGE_START 0x40
#define USBHS_EP0_HOST_REQPKT 0x20
#define USBHS_EP0_HOST_TXPKTRDY 0x02
#define USBHS_EP0_HOST_RXPKTRDY 0x01
#define USBHS_EP_DEVICE_TX_SENT_STALL 0x20
#define USBHS_EP_DEVICE_TX_SEND_STALL 0x10
#define USBHS_EP_DEVICE_RX_SENT_STALL 0x40
#define USBHS_EP_DEVICE_RX_SEND_STALL 0x20
/* FADDR - Device Function Address */
typedef union
{
struct __attribute__((packed))
{
unsigned FUNC:7;
unsigned :1;
};
uint8_t w;
} __USBHS_FADDR_t;
/* POWER - Control Resume and Suspend signalling */
typedef union
{
struct __attribute__((packed))
{
unsigned SUSPEN:1;
unsigned SUSPMODE:1;
unsigned RESUME:1;
unsigned RESET:1;
unsigned HSMODE:1;
unsigned HSEN:1;
unsigned SOFTCONN:1;
unsigned ISOUPD:1;
};
struct
{
uint8_t w;
};
} __USBHS_POWER_t;
/* INTRTXE - Transmit endpoint interrupt enable */
typedef union
{
struct __attribute__((packed))
{
unsigned EP0IE:1;
unsigned EP1TXIE:1;
unsigned EP2TXIE:1;
unsigned EP3TXIE:1;
unsigned EP4TXIE:1;
unsigned EP5TXIE:1;
unsigned EP6TXIE:1;
unsigned EP7TXIE:1;
unsigned :8;
};
struct
{
uint16_t w;
};
} __USBHS_INTRTXE_t;
/* INTRRXE - Receive endpoint interrupt enable */
typedef union
{
struct __attribute__((packed))
{
unsigned :1;
unsigned EP1RXIE:1;
unsigned EP2RXIE:1;
unsigned EP3RXIE:1;
unsigned EP4RXIE:1;
unsigned EP5RXIE:1;
unsigned EP6RXIE:1;
unsigned EP7RXIE:1;
unsigned :8;
};
struct
{
uint16_t w;
};
} __USBHS_INTRRXE_t;
/* INTRUSBE - General USB Interrupt enable */
typedef union
{
struct __attribute__((packed))
{
unsigned SUSPIE:1;
unsigned RESUMEIE:1;
unsigned RESETIE:1;
unsigned SOFIE:1;
unsigned CONNIE:1;
unsigned DISCONIE:1;
unsigned SESSRQIE:1;
unsigned VBUSERRIE:1;
};
struct
{
uint8_t w;
};
} __USBHS_INTRUSBE_t;
/* FRAME - Frame number */
typedef union
{
struct __attribute__((packed))
{
unsigned RFRMNUM:11;
unsigned :5;
};
struct
{
uint16_t w;
};
} __USBHS_FRAME_t;
/* INDEX - Endpoint index */
typedef union
{
struct __attribute__((packed))
{
unsigned ENDPOINT:4;
unsigned :4;
};
struct
{
uint8_t w;
};
} __USBHS_INDEX_t;
/* TESTMODE - Test mode register */
typedef union
{
struct __attribute__((packed))
{
unsigned NAK:1;
unsigned TESTJ:1;
unsigned TESTK:1;
unsigned PACKET:1;
unsigned FORCEHS:1;
unsigned FORCEFS:1;
unsigned FIFOACC:1;
unsigned FORCEHST:1;
};
struct
{
uint8_t w;
};
} __USBHS_TESTMODE_t;
/* COUNT0 - Indicates the amount of data received in endpoint 0 */
typedef union
{
struct __attribute__((packed))
{
unsigned RXCNT:7;
unsigned :1;
};
struct
{
uint8_t w;
};
} __USBHS_COUNT0_t;
/* TYPE0 - Operating speed of target device */
typedef union
{
struct __attribute__((packed))
{
unsigned :6;
unsigned SPEED:2;
};
struct
{
uint8_t w;
};
} __USBHS_TYPE0_t;
/* DEVCTL - Module control register */
typedef union
{
struct __attribute__((packed))
{
unsigned SESSION:1;
unsigned HOSTREQ:1;
unsigned HOSTMODE:1;
unsigned VBUS:2;
unsigned LSDEV:1;
unsigned FSDEV:1;
unsigned BDEV:1;
};
struct
{
uint8_t w;
};
} __USBHS_DEVCTL_t;
/* CSR0L Device - Endpoint Device Mode Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned RXPKTRDY:1;
unsigned TXPKTRDY:1;
unsigned SENTSTALL:1;
unsigned DATAEND:1;
unsigned SETUPEND:1;
unsigned SENDSTALL:1;
unsigned SVCRPR:1;
unsigned SVSSETEND:1;
};
struct
{
uint8_t w;
};
} __USBHS_CSR0L_DEVICE_t;
/* CSR0L Host - Endpoint Host Mode Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned RXPKTRDY:1;
unsigned TXPKTRDY:1;
unsigned RXSTALL:1;
unsigned SETUPPKT:1;
unsigned ERROR:1;
unsigned REQPKT:1;
unsigned STATPKT:1;
unsigned NAKTMOUT:1;
};
struct
{
uint8_t w;
};
} __USBHS_CSR0L_HOST_t;
/* TXCSRL Device - Endpoint Transmit Control Status Register Low */
typedef union
{
struct __attribute__((packed))
{
unsigned TXPKTRDY:1;
unsigned FIFOONE:1;
unsigned UNDERRUN:1;
unsigned FLUSH:1;
unsigned SENDSTALL:1;
unsigned SENTSTALL:1;
unsigned CLRDT:1;
unsigned INCOMPTX:1;
};
struct
{
uint8_t w;
};
} __USBHS_TXCSRL_DEVICE_t;
/* TXCSRL Host - Endpoint Transmit Control Status Register Low */
typedef union
{
struct __attribute__((packed))
{
unsigned TXPKTRDY:1;
unsigned FIFONE:1;
unsigned ERROR:1;
unsigned FLUSH:1;
unsigned SETUPPKT:1;
unsigned RXSTALL:1;
unsigned CLRDT:1;
unsigned INCOMPTX:1;
};
struct
{
uint8_t w;
};
} __USBHS_TXCSRL_HOST_t;
/* TXCSRH Device - Endpoint Transmit Control Status Register High */
typedef union
{
struct __attribute__((packed))
{
unsigned :2;
unsigned DMAREQMD:1;
unsigned FRCDATTG:1;
unsigned DMAREQENL:1;
unsigned MODE:1;
unsigned ISO:1;
unsigned AUTOSET:1;
};
struct
{
uint8_t w;
};
} __USBHS_TXCSRH_DEVICE_t;
/* TXCSRH Host - Endpoint Transmit Control Status Register High */
typedef union
{
struct __attribute__((packed))
{
unsigned DATATGGL:1;
unsigned DTWREN:1;
unsigned DMAREQMD:1;
unsigned FRCDATTG:1;
unsigned DMAREQEN:1;
unsigned MODE:1;
unsigned :1;
unsigned AUOTSET:1;
};
struct
{
uint8_t w;
};
} __USBHS_TXCSRH_HOST_t;
/* CSR0H Device - Endpoint 0 Control Status Register High */
typedef union
{
struct __attribute__((packed))
{
unsigned FLSHFIFO:1;
unsigned :7;
};
struct
{
uint8_t w;
};
} __USBHS_CSR0H_DEVICE_t;
/* CSR0H Host - Endpoint 0 Control Status Register High */
typedef union
{
struct __attribute__((packed))
{
unsigned FLSHFIFO:1;
unsigned DATATGGL:1;
unsigned DTWREN:1;
unsigned DISPING:1;
unsigned :4;
};
struct
{
uint8_t w;
};
} __USBHS_CSR0H_HOST_t;
/* RXMAXP - Receive Endpoint Max packet size. */
typedef union
{
struct __attribute__((packed))
{
unsigned RXMAXP:11;
unsigned MULT:5;
};
struct
{
uint16_t w;
};
} __USBHS_RXMAXP_t;
/* RXCSRL Device - Receive endpoint Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned RXPKTRDY:1;
unsigned FIFOFULL:1;
unsigned OVERRUN:1;
unsigned DATAERR:1;
unsigned FLUSH:1;
unsigned SENDSTALL:1;
unsigned SENTSTALL:1;
unsigned CLRDT:1;
};
struct
{
uint8_t w;
};
} __USBHS_RXCSRL_DEVICE_t;
/* RXCSRL Host - Receive endpoint Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned RXPKTRDY:1;
unsigned FIFOFULL:1;
unsigned ERROR:1;
unsigned DERRNAKT:1;
unsigned FLUSH:1;
unsigned REQPKT:1;
unsigned RXSTALL:1;
unsigned CLRDT:1;
};
struct
{
uint8_t w;
};
} __USBHS_RXCSRL_HOST_t;
/* RXCSRH Device - Receive endpoint Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned INCOMPRX:1;
unsigned :2;
unsigned DMAREQMODE:1;
unsigned DISNYET:1;
unsigned DMAREQEN:1;
unsigned ISO:1;
unsigned AUTOCLR:1;
};
struct
{
uint8_t w;
};
} __USBHS_RXCSRH_DEVICE_t;
/* RXCSRH Host - Receive endpoint Control Status Register */
typedef union
{
struct __attribute__((packed))
{
unsigned INCOMPRX:1;
unsigned DATATGGL:1;
unsigned DATATWEN:1;
unsigned DMAREQMD:1;
unsigned PIDERR:1;
unsigned DMAREQEN:1;
unsigned AUTORQ:1;
unsigned AUOTCLR:1;
};
struct
{
uint8_t w;
};
} __USBHS_RXCSRH_HOST_t;
/* RXCOUNT - Amount of data pending in RX FIFO */
typedef union
{
struct __attribute__((packed))
{
unsigned RXCNT:14;
unsigned :2;
};
struct
{
uint16_t w;
};
} __USBHS_RXCOUNT_t;
/* TXTYPE - Specifies the target transmit endpoint */
typedef union
{
struct __attribute__((packed))
{
unsigned TEP:4;
unsigned PROTOCOL:2;
unsigned SPEED:2;
};
struct
{
uint8_t w;
};
} __USBHS_TXTYPE_t;
/* RXTYPE - Specifies the target receive endpoint */
typedef union
{
struct __attribute__((packed))
{
unsigned TEP:4;
unsigned PROTOCOL:2;
unsigned SPEED:2;
};
struct
{
uint8_t w;
};
} __USBHS_RXTYPE_t;
/* TXINTERVAL - Defines the polling interval */
typedef struct
{
uint8_t TXINTERV;
} __USBHS_TXINTERVAL_t;
/* RXINTERVAL - Defines the polling interval */
typedef struct
{
uint8_t RXINTERV;
} __USBHS_RXINTERVAL_t;
/* TXMAXP - Maximum amount of data that can be transferred through a TX endpoint
* */
typedef union
{
struct __attribute__((packed))
{
unsigned TXMAXP:11;
unsigned MULT:5;
};
uint16_t w;
} __USBHS_TXMAXP_t;
/* TXFIFOSZ - Size of the transmit endpoint FIFO */
typedef struct __attribute__((packed))
{
unsigned TXFIFOSZ:4;
unsigned TXDPB:1;
unsigned :3;
} __USBHS_TXFIFOSZ_t;
/* RXFIFOSZ - Size of the receive endpoint FIFO */
typedef struct __attribute__((packed))
{
unsigned RXFIFOSZ:4;
unsigned RXDPB:1;
unsigned :3;
} __USBHS_RXFIFOSZ_t;
/* TXFIFOADD - Start address of the transmit endpoint FIFO */
typedef union
{
struct __attribute__((packed))
{
unsigned TXFIFOAD:13;
unsigned :3;
};
uint16_t w;
} __USBHS_TXFIFOADD_t;
/* RXFIFOADD - Start address of the receive endpoint FIFO */
typedef union
{
struct __attribute__((packed))
{
unsigned RXFIFOAD:13;
unsigned :3;
};
uint16_t w;
} __USBHS_RXFIFOADD_t;
/* SOFTRST - Asserts NRSTO and NRSTOX */
typedef union
{
struct __attribute__((packed))
{
unsigned NRST:1;
unsigned NRSTX:1;
unsigned :6;
};
uint8_t w;
} __USBHS_SOFTRST_t;
/* TXFUNCADDR - Target address of transmit endpoint */
typedef union
{
struct __attribute__((packed))
{
unsigned TXFADDR:7;
unsigned :1;
};
uint8_t w;
} __USBHS_TXFUNCADDR_t;
/* RXFUNCADDR - Target address of receive endpoint */
typedef union
{
struct __attribute__((packed))
{
unsigned RXFADDR:7;
unsigned :1;
};
uint8_t w;
} __USBHS_RXFUNCADDR_t;
/* TXHUBADDR - Address of the hub to which the target transmit device endpoint
* is connected */
typedef union
{
struct __attribute__((packed))
{
unsigned TXHUBADDR:7;
unsigned MULTTRAN:1;
};
uint8_t w;
} __USBHS_TXHUBADDR_t;
/* RXHUBADDR - Address of the hub to which the target receive device endpoint is
* connected */
typedef union
{
struct __attribute__((packed))
{
unsigned RXHUBADDR:7;
unsigned MULTTRAN:1;
};
uint8_t w;
} __USBHS_RXHUBADDR_t;
/* TXHUBPORT - Address of the hub to which the target transmit device endpoint
* is connected. */
typedef union
{
struct __attribute__((packed))
{
unsigned TXHUBPRT:7;
unsigned :1;
};
uint8_t w;
} __USBHS_TXHUBPORT_t;
/* RXHUBPORT - Address of the hub to which the target receive device endpoint
* is connected. */
typedef union
{
struct __attribute__((packed))
{
unsigned RXHUBPRT:7;
unsigned :1;
};
uint8_t w;
} __USBHS_RXHUBPORT_t;
/* DMACONTROL - Configures a DMA channel */
typedef union
{
struct __attribute__((packed))
{
unsigned DMAEN:1;
unsigned DMADIR:1;
unsigned DMAMODE:1;
unsigned DMAIE:1;
unsigned DMAEP:4;
unsigned DMAERR:1;
unsigned DMABRSTM:2;
unsigned:21;
};
uint32_t w;
} __USBHS_DMACNTL_t;
/* Endpoint Control and Status Register Set */
typedef struct __attribute__((packed))
{
volatile __USBHS_TXMAXP_t TXMAXPbits;
union
{
struct
{
union
{
volatile __USBHS_CSR0L_DEVICE_t CSR0L_DEVICEbits;
volatile __USBHS_CSR0L_HOST_t CSR0L_HOSTbits;
};
union
{
volatile __USBHS_CSR0H_DEVICE_t CSR0H_DEVICEbits;
volatile __USBHS_CSR0H_HOST_t CSR0H_HOSTbits;
};
};
struct
{
union
{
volatile __USBHS_TXCSRL_DEVICE_t TXCSRL_DEVICEbits;
volatile __USBHS_TXCSRL_HOST_t TXCSRL_HOSTbits;
};
union
{
volatile __USBHS_TXCSRH_DEVICE_t TXCSRH_DEVICEbits;
volatile __USBHS_TXCSRH_HOST_t TXCSRH_HOSTbits;
};
};
};
volatile __USBHS_RXMAXP_t RXMAXPbits;
union
{
volatile __USBHS_RXCSRL_DEVICE_t RXCSRL_DEVICEbits;
volatile __USBHS_RXCSRL_HOST_t RXCSRL_HOSTbits;
};
union
{
volatile __USBHS_RXCSRH_DEVICE_t RXCSRH_DEVICEbits;
volatile __USBHS_RXCSRH_HOST_t RXCSRH_HOSTbits;
};
union
{
volatile __USBHS_COUNT0_t COUNT0bits;
volatile __USBHS_RXCOUNT_t RXCOUNTbits;
};
union
{
volatile __USBHS_TYPE0_t TYPE0bits;
volatile __USBHS_TXTYPE_t TXTYPEbits;
};
union
{
volatile uint8_t NAKLIMIT0;
volatile __USBHS_TXINTERVAL_t TXINTERVALbits;
};
volatile __USBHS_RXTYPE_t RXTYPEbits;
volatile __USBHS_RXINTERVAL_t RXINTERVALbits;
unsigned :8;
union
{
volatile uint8_t CONFIGDATA;
volatile uint8_t FIFOSIZE;
};
} __USBHS_EPCSR_t;
/* Set of registers that configure the multi-point option */
typedef struct __attribute__((packed))
{
volatile __USBHS_TXFUNCADDR_t TXFUNCADDRbits;
unsigned :8;
volatile __USBHS_TXHUBADDR_t TXHUBADDRbits;
volatile __USBHS_TXHUBPORT_t TXHUBPORTbits;
volatile __USBHS_RXFUNCADDR_t RXFUNCADDRbits;
unsigned :8;
volatile __USBHS_RXHUBADDR_t RXHUBADDRbits;
volatile __USBHS_RXHUBPORT_t RXHUBPORTbits;
} __USBHS_TARGET_ADDR_t;
/* Set of registers that configure the DMA channel */
typedef struct __attribute__((packed))
{
volatile __USBHS_DMACNTL_t DMACNTLbits;
volatile uint32_t DMAADDR;
volatile uint32_t DMACOUNT;
volatile uint32_t pad;
} __USBHS_DMA_CHANNEL_t;
/* USBHS module register set */
typedef struct __attribute__((aligned(4),packed))
{
volatile __USBHS_FADDR_t FADDRbits;
volatile __USBHS_POWER_t POWERbits;
volatile uint16_t INTRTX;
volatile uint16_t INTRRX;
volatile __USBHS_INTRTXE_t INTRTXEbits;
volatile __USBHS_INTRRXE_t INTRRXEbits;
volatile uint8_t INTRUSB;
volatile __USBHS_INTRUSBE_t INTRUSBEbits;
volatile __USBHS_FRAME_t FRAMEbits;
volatile __USBHS_INDEX_t INDEXbits;
volatile __USBHS_TESTMODE_t TESTMODEbits;
volatile __USBHS_EPCSR_t INDEXED_EPCSR;
volatile uint32_t FIFO[16];
volatile __USBHS_DEVCTL_t DEVCTLbits;
volatile uint8_t MISC;
volatile __USBHS_TXFIFOSZ_t TXFIFOSZbits;
volatile __USBHS_RXFIFOSZ_t RXFIFOSZbits;
volatile __USBHS_TXFIFOADD_t TXFIFOADDbits;
volatile __USBHS_RXFIFOADD_t RXFIFOADDbits;
volatile uint32_t VCONTROL;
volatile uint16_t HWVERS;
volatile uint8_t padding1[10];
volatile uint8_t EPINFO;
volatile uint8_t RAMINFO;
volatile uint8_t LINKINFO;
volatile uint8_t VPLEN;
volatile uint8_t HS_EOF1;
volatile uint8_t FS_EOF1;
volatile uint8_t LS_EOF1;
volatile __USBHS_SOFTRST_t SOFTRSTbits;
volatile __USBHS_TARGET_ADDR_t TADDR[16];
volatile __USBHS_EPCSR_t EPCSR[16];
volatile uint32_t DMA_INTR;
volatile __USBHS_DMA_CHANNEL_t DMA_CHANNEL[8];
volatile uint32_t RQPKTXOUNT[16];
} usbhs_registers_t;
#endif

View File

@ -0,0 +1,152 @@
/*
* 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.
*/
#ifndef _TUSB_DCD_LPC17_40_H_
#define _TUSB_DCD_LPC17_40_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Register Interface
//--------------------------------------------------------------------+
//------------- USB Interrupt USBIntSt -------------//
//enum {
// DCD_USB_REQ_LOW_PRIO_MASK = TU_BIT(0),
// DCD_USB_REQ_HIGH_PRIO_MASK = TU_BIT(1),
// DCD_USB_REQ_DMA_MASK = TU_BIT(2),
// DCD_USB_REQ_NEED_CLOCK_MASK = TU_BIT(8),
// DCD_USB_REQ_ENABLE_MASK = TU_BIT(31)
//};
//------------- Device Interrupt USBDevInt -------------//
enum {
DEV_INT_FRAME_MASK = TU_BIT(0),
DEV_INT_ENDPOINT_FAST_MASK = TU_BIT(1),
DEV_INT_ENDPOINT_SLOW_MASK = TU_BIT(2),
DEV_INT_DEVICE_STATUS_MASK = TU_BIT(3),
DEV_INT_COMMAND_CODE_EMPTY_MASK = TU_BIT(4),
DEV_INT_COMMAND_DATA_FULL_MASK = TU_BIT(5),
DEV_INT_RX_ENDPOINT_PACKET_MASK = TU_BIT(6),
DEV_INT_TX_ENDPOINT_PACKET_MASK = TU_BIT(7),
DEV_INT_ENDPOINT_REALIZED_MASK = TU_BIT(8),
DEV_INT_ERROR_MASK = TU_BIT(9)
};
//------------- DMA Interrupt USBDMAInt-------------//
enum {
DMA_INT_END_OF_XFER_MASK = TU_BIT(0),
DMA_INT_NEW_DD_REQUEST_MASK = TU_BIT(1),
DMA_INT_ERROR_MASK = TU_BIT(2)
};
//------------- USBCtrl -------------//
enum {
USBCTRL_READ_ENABLE_MASK = TU_BIT(0),
USBCTRL_WRITE_ENABLE_MASK = TU_BIT(1),
};
//------------- USBRxPLen -------------//
enum {
USBRXPLEN_PACKET_LENGTH_MASK = (TU_BIT(10)-1),
USBRXPLEN_DATA_VALID_MASK = TU_BIT(10),
USBRXPLEN_PACKET_READY_MASK = TU_BIT(11),
};
//------------- SIE Command Code -------------//
typedef enum
{
SIE_CMDPHASE_WRITE = 1,
SIE_CMDPHASE_READ = 2,
SIE_CMDPHASE_COMMAND = 5
} sie_cmdphase_t;
enum {
// device commands
SIE_CMDCODE_SET_ADDRESS = 0xd0,
SIE_CMDCODE_CONFIGURE_DEVICE = 0xd8,
SIE_CMDCODE_SET_MODE = 0xf3,
SIE_CMDCODE_READ_FRAME_NUMBER = 0xf5,
SIE_CMDCODE_READ_TEST_REGISTER = 0xfd,
SIE_CMDCODE_DEVICE_STATUS = 0xfe,
SIE_CMDCODE_GET_ERROR = 0xff,
SIE_CMDCODE_READ_ERROR_STATUS = 0xfb,
// endpoint commands
SIE_CMDCODE_ENDPOINT_SELECT = 0x00, // + endpoint index
SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT = 0x40, // + endpoint index, should use USBEpIntClr instead
SIE_CMDCODE_ENDPOINT_SET_STATUS = 0x40, // + endpoint index
SIE_CMDCODE_BUFFER_CLEAR = 0xf2,
SIE_CMDCODE_BUFFER_VALIDATE = 0xfa
};
//------------- SIE Device Status (get/set from SIE_CMDCODE_DEVICE_STATUS) -------------//
enum {
SIE_DEV_STATUS_CONNECT_STATUS_MASK = TU_BIT(0),
SIE_DEV_STATUS_CONNECT_CHANGE_MASK = TU_BIT(1),
SIE_DEV_STATUS_SUSPEND_MASK = TU_BIT(2),
SIE_DEV_STATUS_SUSPEND_CHANGE_MASK = TU_BIT(3),
SIE_DEV_STATUS_RESET_MASK = TU_BIT(4)
};
//------------- SIE Select Endpoint Command -------------//
enum {
SIE_SELECT_ENDPOINT_FULL_EMPTY_MASK = TU_BIT(0), // 0: empty, 1 full. IN endpoint checks empty, OUT endpoint check full
SIE_SELECT_ENDPOINT_STALL_MASK = TU_BIT(1),
SIE_SELECT_ENDPOINT_SETUP_RECEIVED_MASK = TU_BIT(2), // clear by SIE_CMDCODE_ENDPOINT_SELECT_CLEAR_INTERRUPT
SIE_SELECT_ENDPOINT_PACKET_OVERWRITTEN_MASK = TU_BIT(3), // previous packet is overwritten by a SETUP packet
SIE_SELECT_ENDPOINT_NAK_MASK = TU_BIT(4), // last packet response is NAK (auto clear by an ACK)
SIE_SELECT_ENDPOINT_BUFFER1_FULL_MASK = TU_BIT(5),
SIE_SELECT_ENDPOINT_BUFFER2_FULL_MASK = TU_BIT(6)
};
typedef enum
{
SIE_SET_ENDPOINT_STALLED_MASK = TU_BIT(0),
SIE_SET_ENDPOINT_DISABLED_MASK = TU_BIT(5),
SIE_SET_ENDPOINT_RATE_FEEDBACK_MASK = TU_BIT(6),
SIE_SET_ENDPOINT_CONDITION_STALLED_MASK = TU_BIT(7),
}sie_endpoint_set_status_mask_t;
//------------- DMA Descriptor Status -------------//
enum {
DD_STATUS_NOT_SERVICED = 0,
DD_STATUS_BEING_SERVICED,
DD_STATUS_NORMAL,
DD_STATUS_DATA_UNDERUN, // short packet
DD_STATUS_DATA_OVERRUN,
DD_STATUS_SYSTEM_ERROR
};
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,136 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef COMMON_TRANSDIMENSION_H_
#define COMMON_TRANSDIMENSION_H_
#ifdef __cplusplus
extern "C" {
#endif
// USBCMD
enum {
USBCMD_RUN_STOP = TU_BIT(0),
USBCMD_RESET = TU_BIT(1),
USBCMD_SETUP_TRIPWIRE = TU_BIT(13),
USBCMD_ADD_QTD_TRIPWIRE = TU_BIT(14) ///< This bit is used as a semaphore to ensure the to proper addition of a new dTD to an active (primed) endpoints linked list. This bit is set and cleared by software during the process of adding a new dTD
// Interrupt Threshold bit 23:16
};
// PORTSC1
#define PORTSC1_PORT_SPEED_POS 26
enum {
PORTSC1_CURRENT_CONNECT_STATUS = TU_BIT(0),
PORTSC1_FORCE_PORT_RESUME = TU_BIT(6),
PORTSC1_SUSPEND = TU_BIT(7),
PORTSC1_FORCE_FULL_SPEED = TU_BIT(24),
PORTSC1_PORT_SPEED = TU_BIT(26) | TU_BIT(27)
};
// OTGSC
enum {
OTGSC_VBUS_DISCHARGE = TU_BIT(0),
OTGSC_VBUS_CHARGE = TU_BIT(1),
// OTGSC_HWASSIST_AUTORESET = TU_BIT(2),
OTGSC_OTG_TERMINATION = TU_BIT(3), ///< Must set to 1 when OTG go to device mode
OTGSC_DATA_PULSING = TU_BIT(4),
OTGSC_ID_PULLUP = TU_BIT(5),
// OTGSC_HWASSIT_DATA_PULSE = TU_BIT(6),
// OTGSC_HWASSIT_BDIS_ACONN = TU_BIT(7),
OTGSC_ID = TU_BIT(8), ///< 0 = A device, 1 = B Device
OTGSC_A_VBUS_VALID = TU_BIT(9),
OTGSC_A_SESSION_VALID = TU_BIT(10),
OTGSC_B_SESSION_VALID = TU_BIT(11),
OTGSC_B_SESSION_END = TU_BIT(12),
OTGSC_1MS_TOGGLE = TU_BIT(13),
OTGSC_DATA_BUS_PULSING_STATUS = TU_BIT(14),
};
// USBMode
enum {
USBMODE_CM_DEVICE = 2,
USBMODE_CM_HOST = 3,
USBMODE_SLOM = TU_BIT(3),
USBMODE_SDIS = TU_BIT(4),
USBMODE_VBUS_POWER_SELECT = TU_BIT(5), // Need to be enabled for LPC18XX/43XX in host mode
};
// Device Registers
typedef struct
{
//------------- ID + HW Parameter Registers-------------//
__I uint32_t TU_RESERVED[64]; ///< For iMX RT10xx, but not used by LPC18XX/LPC43XX
//------------- Capability Registers-------------//
__I uint8_t CAPLENGTH; ///< Capability Registers Length
__I uint8_t TU_RESERVED[1];
__I uint16_t HCIVERSION; ///< Host Controller Interface Version
__I uint32_t HCSPARAMS; ///< Host Controller Structural Parameters
__I uint32_t HCCPARAMS; ///< Host Controller Capability Parameters
__I uint32_t TU_RESERVED[5];
__I uint16_t DCIVERSION; ///< Device Controller Interface Version
__I uint8_t TU_RESERVED[2];
__I uint32_t DCCPARAMS; ///< Device Controller Capability Parameters
__I uint32_t TU_RESERVED[6];
//------------- Operational Registers -------------//
__IO uint32_t USBCMD; ///< USB Command Register
__IO uint32_t USBSTS; ///< USB Status Register
__IO uint32_t USBINTR; ///< Interrupt Enable Register
__IO uint32_t FRINDEX; ///< USB Frame Index
__I uint32_t TU_RESERVED;
__IO uint32_t DEVICEADDR; ///< Device Address
__IO uint32_t ENDPTLISTADDR; ///< Endpoint List Address
__I uint32_t TU_RESERVED;
__IO uint32_t BURSTSIZE; ///< Programmable Burst Size
__IO uint32_t TXFILLTUNING; ///< TX FIFO Fill Tuning
uint32_t TU_RESERVED[4];
__IO uint32_t ENDPTNAK; ///< Endpoint NAK
__IO uint32_t ENDPTNAKEN; ///< Endpoint NAK Enable
__I uint32_t TU_RESERVED;
__IO uint32_t PORTSC1; ///< Port Status & Control
__I uint32_t TU_RESERVED[7];
__IO uint32_t OTGSC; ///< On-The-Go Status & control
__IO uint32_t USBMODE; ///< USB Device Mode
__IO uint32_t ENDPTSETUPSTAT; ///< Endpoint Setup Status
__IO uint32_t ENDPTPRIME; ///< Endpoint Prime
__IO uint32_t ENDPTFLUSH; ///< Endpoint Flush
__I uint32_t ENDPTSTAT; ///< Endpoint Status
__IO uint32_t ENDPTCOMPLETE; ///< Endpoint Complete
__IO uint32_t ENDPTCTRL[8]; ///< Endpoint Control 0 - 7
} dcd_registers_t, hcd_registers_t;
#ifdef __cplusplus
}
#endif
#endif /* COMMON_TRANSDIMENSION_H_ */

View File

@ -0,0 +1,278 @@
/*
* 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.
*/
#ifndef _TUSB_OHCI_H_
#define _TUSB_OHCI_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// OHCI CONFIGURATION & CONSTANTS
//--------------------------------------------------------------------+
#define HOST_HCD_XFER_INTERRUPT // TODO interrupt is used widely, should always be enalbed
#define OHCI_PERIODIC_LIST (defined HOST_HCD_XFER_INTERRUPT || defined HOST_HCD_XFER_ISOCHRONOUS)
// TODO merge OHCI with EHCI
enum {
OHCI_MAX_ITD = 4
};
#define ED_MAX (CFG_TUH_DEVICE_MAX*CFG_TUH_ENDPOINT_MAX)
#define GTD_MAX ED_MAX
//--------------------------------------------------------------------+
// OHCI Data Structure
//--------------------------------------------------------------------+
typedef struct {
uint32_t interrupt_table[32];
volatile uint16_t frame_number;
volatile uint16_t frame_pad;
volatile uint32_t done_head;
uint8_t reserved[116+4]; // TODO try to make use of this area if possible, extra 4 byte to make the whole struct size = 256
}ohci_hcca_t; // TU_ATTR_ALIGNED(256)
TU_VERIFY_STATIC( sizeof(ohci_hcca_t) == 256, "size is not correct" );
typedef struct {
uint32_t reserved[2];
volatile uint32_t next;
uint32_t reserved2;
}ohci_td_item_t;
typedef struct TU_ATTR_ALIGNED(16)
{
// Word 0
uint32_t used : 1;
uint32_t index : 4; // endpoint index the td belongs to, or device address in case of control xfer
uint32_t expected_bytes : 13; // TODO available for hcd
uint32_t buffer_rounding : 1;
uint32_t pid : 2;
uint32_t delay_interrupt : 3;
volatile uint32_t data_toggle : 2;
volatile uint32_t error_count : 2;
volatile uint32_t condition_code : 4;
// Word 1
volatile uint8_t* current_buffer_pointer;
// Word 2 : next TD
volatile uint32_t next;
// Word 3
uint8_t* buffer_end;
} ohci_gtd_t;
TU_VERIFY_STATIC( sizeof(ohci_gtd_t) == 16, "size is not correct" );
typedef struct TU_ATTR_ALIGNED(16)
{
// Word 0
uint32_t dev_addr : 7;
uint32_t ep_number : 4;
uint32_t pid : 2;
uint32_t speed : 1;
uint32_t skip : 1;
uint32_t is_iso : 1;
uint32_t max_packet_size : 11;
// HCD: make use of 5 reserved bits
uint32_t used : 1;
uint32_t is_interrupt_xfer : 1;
uint32_t is_stalled : 1;
uint32_t : 2;
// Word 1
uint32_t td_tail;
// Word 2
volatile union {
uint32_t address;
struct {
uint32_t halted : 1;
uint32_t toggle : 1;
uint32_t : 30;
};
}td_head;
// Word 3: next ED
uint32_t next;
} ohci_ed_t;
TU_VERIFY_STATIC( sizeof(ohci_ed_t) == 16, "size is not correct" );
typedef struct TU_ATTR_ALIGNED(32)
{
/*---------- Word 1 ----------*/
uint32_t starting_frame : 16;
uint32_t : 5; // can be used
uint32_t delay_interrupt : 3;
uint32_t frame_count : 3;
uint32_t : 1; // can be used
volatile uint32_t condition_code : 4;
/*---------- Word 2 ----------*/
uint32_t buffer_page0; // 12 lsb bits can be used
/*---------- Word 3 ----------*/
volatile uint32_t next;
/*---------- Word 4 ----------*/
uint32_t buffer_end;
/*---------- Word 5-8 ----------*/
volatile uint16_t offset_packetstatus[8];
} ochi_itd_t;
TU_VERIFY_STATIC( sizeof(ochi_itd_t) == 32, "size is not correct" );
// structure with member alignment required from large to small
typedef struct TU_ATTR_ALIGNED(256)
{
ohci_hcca_t hcca;
ohci_ed_t bulk_head_ed; // static bulk head (dummy)
ohci_ed_t period_head_ed; // static periodic list head (dummy)
// control endpoints has reserved resources
struct {
ohci_ed_t ed;
ohci_gtd_t gtd;
}control[CFG_TUH_DEVICE_MAX+CFG_TUH_HUB+1];
// ochi_itd_t itd[OHCI_MAX_ITD]; // itd requires alignment of 32
ohci_ed_t ed_pool[ED_MAX];
ohci_gtd_t gtd_pool[GTD_MAX];
volatile uint16_t frame_number_hi;
} ohci_data_t;
//--------------------------------------------------------------------+
// OHCI Operational Register
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// OHCI Data Organization
//--------------------------------------------------------------------+
typedef volatile struct
{
uint32_t revision;
union {
uint32_t control;
struct {
uint32_t control_bulk_service_ratio : 2;
uint32_t periodic_list_enable : 1;
uint32_t isochronous_enable : 1;
uint32_t control_list_enable : 1;
uint32_t bulk_list_enable : 1;
uint32_t hc_functional_state : 2;
uint32_t interrupt_routing : 1;
uint32_t remote_wakeup_connected : 1;
uint32_t remote_wakeup_enale : 1;
uint32_t TU_RESERVED : 21;
}control_bit;
};
union {
uint32_t command_status;
struct {
uint32_t controller_reset : 1;
uint32_t control_list_filled : 1;
uint32_t bulk_list_filled : 1;
uint32_t ownership_change_request : 1;
uint32_t : 12;
uint32_t scheduling_overrun_count : 2;
}command_status_bit;
};
uint32_t interrupt_status;
uint32_t interrupt_enable;
uint32_t interrupt_disable;
uint32_t hcca;
uint32_t period_current_ed;
uint32_t control_head_ed;
uint32_t control_current_ed;
uint32_t bulk_head_ed;
uint32_t bulk_current_ed;
uint32_t done_head;
uint32_t frame_interval;
uint32_t frame_remaining;
uint32_t frame_number;
uint32_t periodic_start;
uint32_t lowspeed_threshold;
uint32_t rh_descriptorA;
uint32_t rh_descriptorB;
union {
uint32_t rh_status;
struct {
uint32_t local_power_status : 1; // read Local Power Status; write: Clear Global Power
uint32_t over_current_indicator : 1;
uint32_t : 13;
uint32_t device_remote_wakeup_enable : 1;
uint32_t local_power_status_change : 1;
uint32_t over_current_indicator_change : 1;
uint32_t : 13;
uint32_t clear_remote_wakeup_enable : 1;
}rh_status_bit;
};
union {
uint32_t rhport_status[2]; // TODO NXP OHCI controller only has 2 ports
struct {
uint32_t current_connect_status : 1;
uint32_t port_enable_status : 1;
uint32_t port_suspend_status : 1;
uint32_t port_over_current_indicator : 1;
uint32_t port_reset_status : 1;
uint32_t : 3;
uint32_t port_power_status : 1;
uint32_t low_speed_device_attached : 1;
uint32_t : 6;
uint32_t connect_status_change : 1;
uint32_t port_enable_status_change : 1;
uint32_t port_suspend_status_change : 1;
uint32_t port_over_current_indicator_change : 1;
uint32_t port_reset_status_change : 1;
uint32_t TU_RESERVED : 11;
}rhport_status_bit[2];
};
}ohci_registers_t;
TU_VERIFY_STATIC( sizeof(ohci_registers_t) == 0x5c, "size is not correct");
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OHCI_H_ */

View File

@ -0,0 +1,96 @@
#ifndef RP2040_COMMON_H_
#define RP2040_COMMON_H_
#if defined(RP2040_USB_HOST_MODE) && defined(RP2040_USB_DEVICE_MODE)
#error TinyUSB device and host mode not supported at the same time
#endif
#include "common/tusb_common.h"
#include "pico.h"
#include "hardware/structs/usb.h"
#include "hardware/irq.h"
#include "hardware/resets.h"
#if defined(PICO_RP2040_USB_DEVICE_ENUMERATION_FIX) && !defined(TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX)
#define TUD_OPT_RP2040_USB_DEVICE_ENUMERATION_FIX PICO_RP2040_USB_DEVICE_ENUMERATION_FIX
#endif
#define pico_info(...) TU_LOG(2, __VA_ARGS__)
#define pico_trace(...) TU_LOG(3, __VA_ARGS__)
// Hardware information per endpoint
typedef struct hw_endpoint
{
// Is this a valid struct
bool configured;
// Transfer direction (i.e. IN is rx for host but tx for device)
// allows us to common up transfer functions
bool rx;
uint8_t ep_addr;
uint8_t next_pid;
// Endpoint control register
io_rw_32 *endpoint_control;
// Buffer control register
io_rw_32 *buffer_control;
// Buffer pointer in usb dpram
uint8_t *hw_data_buf;
// Current transfer information
bool active;
uint16_t remaining_len;
uint16_t xferred_len;
// User buffer in main memory
uint8_t *user_buf;
// Data needed from EP descriptor
uint16_t wMaxPacketSize;
// Interrupt, bulk, etc
uint8_t transfer_type;
#if CFG_TUH_ENABLED
// Only needed for host
uint8_t dev_addr;
// If interrupt endpoint
uint8_t interrupt_num;
#endif
} hw_endpoint_t;
void rp2040_usb_init(void);
void hw_endpoint_xfer_start(struct hw_endpoint *ep, uint8_t *buffer, uint16_t total_len);
bool hw_endpoint_xfer_continue(struct hw_endpoint *ep);
void hw_endpoint_reset_transfer(struct hw_endpoint *ep);
void _hw_endpoint_buffer_control_update32(struct hw_endpoint *ep, uint32_t and_mask, uint32_t or_mask);
static inline uint32_t _hw_endpoint_buffer_control_get_value32(struct hw_endpoint *ep) {
return *ep->buffer_control;
}
static inline void _hw_endpoint_buffer_control_set_value32(struct hw_endpoint *ep, uint32_t value) {
return _hw_endpoint_buffer_control_update32(ep, 0, value);
}
static inline void _hw_endpoint_buffer_control_set_mask32(struct hw_endpoint *ep, uint32_t value) {
return _hw_endpoint_buffer_control_update32(ep, ~value, value);
}
static inline void _hw_endpoint_buffer_control_clear_mask32(struct hw_endpoint *ep, uint32_t value) {
return _hw_endpoint_buffer_control_update32(ep, ~value, 0);
}
static inline uintptr_t hw_data_offset(uint8_t *buf)
{
// Remove usb base from buffer pointer
return (uintptr_t)buf ^ (uintptr_t)usb_dpram;
}
extern const char *ep_dir_string[];
#endif

View File

@ -0,0 +1,422 @@
/**
******************************************************************************
* @file dcd_stm32f0_pvt_st.h
* @brief DCD utilities from ST code
******************************************************************************
* @attention
*
* <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
* <h2><center>&copy; parts COPYRIGHT(c) N Conrad</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**********/
// This file contains source copied from ST's HAL, and thus should have their copyright statement.
// PMA_LENGTH is PMA buffer size in bytes.
// On 512-byte devices, access with a stride of two words (use every other 16-bit address)
// On 1024-byte devices, access with a stride of one word (use every 16-bit address)
#ifndef PORTABLE_ST_STM32F0_DCD_STM32F0_FSDEV_PVT_ST_H_
#define PORTABLE_ST_STM32F0_DCD_STM32F0_FSDEV_PVT_ST_H_
#if defined(STM32F042x6) || \
defined(STM32F070x6) || defined(STM32F070xB) || \
defined(STM32F072xB) || \
defined(STM32F078xx)
#include "stm32f0xx.h"
#define PMA_LENGTH (1024u)
// F0x2 models are crystal-less
// All have internal D+ pull-up
// 070RB: 2 x 16 bits/word memory LPM Support, BCD Support
// PMA dedicated to USB (no sharing with CAN)
#elif defined(STM32F1_FSDEV)
#include "stm32f1xx.h"
#define PMA_LENGTH (512u)
// NO internal Pull-ups
// *B, and *C: 2 x 16 bits/word
// F1 names this differently from the rest
#define USB_CNTR_LPMODE USB_CNTR_LP_MODE
#elif defined(STM32F302xB) || defined(STM32F302xC) || \
defined(STM32F303xB) || defined(STM32F303xC) || \
defined(STM32F373xC)
#include "stm32f3xx.h"
#define PMA_LENGTH (512u)
// NO internal Pull-ups
// *B, and *C: 1 x 16 bits/word
// PMA dedicated to USB (no sharing with CAN)
#elif defined(STM32F302x6) || defined(STM32F302x8) || \
defined(STM32F302xD) || defined(STM32F302xE) || \
defined(STM32F303xD) || defined(STM32F303xE)
#include "stm32f3xx.h"
#define PMA_LENGTH (1024u)
// NO internal Pull-ups
// *6, *8, *D, and *E: 2 x 16 bits/word LPM Support
// When CAN clock is enabled, USB can use first 768 bytes ONLY.
#elif CFG_TUSB_MCU == OPT_MCU_STM32L0
#include "stm32l0xx.h"
#define PMA_LENGTH (1024u)
#elif CFG_TUSB_MCU == OPT_MCU_STM32L1
#include "stm32l1xx.h"
#define PMA_LENGTH (512u)
#elif CFG_TUSB_MCU == OPT_MCU_STM32G4
#include "stm32g4xx.h"
#define PMA_LENGTH (1024u)
#elif CFG_TUSB_MCU == OPT_MCU_STM32WB
#include "stm32wbxx.h"
#define PMA_LENGTH (1024u)
/* ST provided header has incorrect value */
#undef USB_PMAADDR
#define USB_PMAADDR USB1_PMAADDR
#else
#error You are using an untested or unimplemented STM32 variant. Please update the driver.
// This includes L1x0, L1x1, L1x2, L4x2 and L4x3, G1x1, G1x3, and G1x4
#endif
// For purposes of accessing the packet
#if ((PMA_LENGTH) == 512u)
#define PMA_STRIDE (2u)
#elif ((PMA_LENGTH) == 1024u)
#define PMA_STRIDE (1u)
#endif
// And for type-safety create a new macro for the volatile address of PMAADDR
// The compiler should warn us if we cast it to a non-volatile type?
// Volatile is also needed to prevent the optimizer from changing access to 32-bit (as 32-bit access is forbidden)
static __IO uint16_t * const pma = (__IO uint16_t*)USB_PMAADDR;
// prototypes
static inline __IO uint16_t* pcd_ep_rx_cnt_ptr(USB_TypeDef * USBx, uint32_t bEpNum);
static inline __IO uint16_t* pcd_ep_tx_cnt_ptr(USB_TypeDef * USBx, uint32_t bEpNum);
static inline void pcd_set_endpoint(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wRegValue);
/* SetENDPOINT */
static inline void pcd_set_endpoint(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wRegValue)
{
__O uint16_t *reg = (__O uint16_t *)((&USBx->EP0R) + bEpNum*2u);
*reg = (uint16_t)wRegValue;
}
/* GetENDPOINT */
static inline uint16_t pcd_get_endpoint(USB_TypeDef * USBx, uint32_t bEpNum) {
__I uint16_t *reg = (__I uint16_t *)((&USBx->EP0R) + bEpNum*2u);
return *reg;
}
static inline void pcd_set_eptype(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wType)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= (uint32_t)USB_EP_T_MASK;
regVal |= wType;
regVal |= USB_EP_CTR_RX | USB_EP_CTR_TX; // These clear on write0, so must set high
pcd_set_endpoint(USBx, bEpNum, regVal);
}
static inline uint32_t pcd_get_eptype(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EP_T_FIELD;
return regVal;
}
/**
* @brief Clears bit CTR_RX / CTR_TX in the endpoint register.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @retval None
*/
static inline void pcd_clear_rx_ep_ctr(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPREG_MASK;
regVal &= ~USB_EP_CTR_RX;
regVal |= USB_EP_CTR_TX; // preserve CTR_TX (clears on writing 0)
pcd_set_endpoint(USBx, bEpNum, regVal);
}
static inline void pcd_clear_tx_ep_ctr(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPREG_MASK;
regVal &= ~USB_EP_CTR_TX;
regVal |= USB_EP_CTR_RX; // preserve CTR_RX (clears on writing 0)
pcd_set_endpoint(USBx, bEpNum,regVal);
}
/**
* @brief gets counter of the tx buffer.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @retval Counter value
*/
static inline uint32_t pcd_get_ep_tx_cnt(USB_TypeDef * USBx, uint32_t bEpNum)
{
__I uint16_t *regPtr = pcd_ep_tx_cnt_ptr(USBx, bEpNum);
return *regPtr & 0x3ffU;
}
static inline uint32_t pcd_get_ep_rx_cnt(USB_TypeDef * USBx, uint32_t bEpNum)
{
__I uint16_t *regPtr = pcd_ep_rx_cnt_ptr(USBx, bEpNum);
return *regPtr & 0x3ffU;
}
/**
* @brief Sets counter of rx buffer with no. of blocks.
* @param dwReg Register
* @param wCount Counter.
* @param wNBlocks no. of Blocks.
* @retval None
*/
static inline void pcd_set_ep_cnt_rx_reg(__O uint16_t * pdwReg, size_t wCount) {
uint32_t wNBlocks;
if(wCount > 62u)
{
wNBlocks = wCount >> 5u;
if((wCount & 0x1fU) == 0u)
{
wNBlocks--;
}
wNBlocks = wNBlocks << 10u;
wNBlocks |= 0x8000u; // Mark block size as 32byte
*pdwReg = (uint16_t)wNBlocks;
}
else
{
wNBlocks = wCount >> 1u;
if((wCount & 0x1U) != 0u)
{
wNBlocks++;
}
*pdwReg = (uint16_t)((wNBlocks) << 10u);
}
}
/**
* @brief Sets address in an endpoint register.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @param bAddr Address.
* @retval None
*/
static inline void pcd_set_ep_address(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t bAddr)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPREG_MASK;
regVal |= bAddr;
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX;
pcd_set_endpoint(USBx, bEpNum,regVal);
}
static inline __IO uint16_t * pcd_btable_word_ptr(USB_TypeDef * USBx, size_t x)
{
size_t total_word_offset = (((USBx)->BTABLE)>>1) + x;
total_word_offset *= PMA_STRIDE;
return &(pma[total_word_offset]);
}
// Pointers to the PMA table entries (using the ARM address space)
static inline __IO uint16_t* pcd_ep_tx_address_ptr(USB_TypeDef * USBx, uint32_t bEpNum)
{
return pcd_btable_word_ptr(USBx,(bEpNum)*4u + 0u);
}
static inline __IO uint16_t* pcd_ep_tx_cnt_ptr(USB_TypeDef * USBx, uint32_t bEpNum)
{
return pcd_btable_word_ptr(USBx,(bEpNum)*4u + 1u);
}
static inline __IO uint16_t* pcd_ep_rx_address_ptr(USB_TypeDef * USBx, uint32_t bEpNum)
{
return pcd_btable_word_ptr(USBx,(bEpNum)*4u + 2u);
}
static inline __IO uint16_t* pcd_ep_rx_cnt_ptr(USB_TypeDef * USBx, uint32_t bEpNum)
{
return pcd_btable_word_ptr(USBx,(bEpNum)*4u + 3u);
}
static inline void pcd_set_ep_tx_cnt(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wCount)
{
*pcd_ep_tx_cnt_ptr(USBx, bEpNum) = (uint16_t)wCount;
}
static inline void pcd_set_ep_rx_cnt(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wCount)
{
__IO uint16_t *pdwReg = pcd_ep_rx_cnt_ptr((USBx),(bEpNum));
pcd_set_ep_cnt_rx_reg(pdwReg, wCount);
}
/**
* @brief sets the status for tx transfer (bits STAT_TX[1:0]).
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @param wState new state
* @retval None
*/
static inline void pcd_set_ep_tx_status(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wState)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPTX_DTOGMASK;
/* toggle first bit ? */
if((USB_EPTX_DTOG1 & (wState))!= 0U)
{
regVal ^= USB_EPTX_DTOG1;
}
/* toggle second bit ? */
if((USB_EPTX_DTOG2 & ((uint32_t)(wState)))!= 0U)
{
regVal ^= USB_EPTX_DTOG2;
}
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX;
pcd_set_endpoint(USBx, bEpNum, regVal);
} /* pcd_set_ep_tx_status */
/**
* @brief sets the status for rx transfer (bits STAT_TX[1:0])
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @param wState new state
* @retval None
*/
static inline void pcd_set_ep_rx_status(USB_TypeDef * USBx, uint32_t bEpNum, uint32_t wState)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPRX_DTOGMASK;
/* toggle first bit ? */
if((USB_EPRX_DTOG1 & wState)!= 0U)
{
regVal ^= USB_EPRX_DTOG1;
}
/* toggle second bit ? */
if((USB_EPRX_DTOG2 & wState)!= 0U)
{
regVal ^= USB_EPRX_DTOG2;
}
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX;
pcd_set_endpoint(USBx, bEpNum, regVal);
} /* pcd_set_ep_rx_status */
static inline uint32_t pcd_get_ep_rx_status(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
return (regVal & USB_EPRX_STAT) >> (12u);
} /* pcd_get_ep_rx_status */
/**
* @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @retval None
*/
static inline void pcd_rx_dtog(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPREG_MASK;
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_RX;
pcd_set_endpoint(USBx, bEpNum, regVal);
}
static inline void pcd_tx_dtog(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPREG_MASK;
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_TX;
pcd_set_endpoint(USBx, bEpNum, regVal);
}
/**
* @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @retval None
*/
static inline void pcd_clear_rx_dtog(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
if((regVal & USB_EP_DTOG_RX) != 0)
{
pcd_rx_dtog(USBx,bEpNum);
}
}
static inline void pcd_clear_tx_dtog(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
if((regVal & USB_EP_DTOG_TX) != 0)
{
pcd_tx_dtog(USBx,bEpNum);
}
}
/**
* @brief set & clear EP_KIND bit.
* @param USBx USB peripheral instance register address.
* @param bEpNum Endpoint Number.
* @retval None
*/
static inline void pcd_set_ep_kind(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal |= USB_EP_KIND;
regVal &= USB_EPREG_MASK;
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX;
pcd_set_endpoint(USBx, bEpNum, regVal);
}
static inline void pcd_clear_ep_kind(USB_TypeDef * USBx, uint32_t bEpNum)
{
uint32_t regVal = pcd_get_endpoint(USBx, bEpNum);
regVal &= USB_EPKIND_MASK;
regVal |= USB_EP_CTR_RX|USB_EP_CTR_TX;
pcd_set_endpoint(USBx, bEpNum, regVal);
}
// This checks if the device has "LPM"
#if defined(USB_ISTR_L1REQ)
#define USB_ISTR_L1REQ_FORCED (USB_ISTR_L1REQ)
#else
#define USB_ISTR_L1REQ_FORCED ((uint16_t)0x0000U)
#endif
#define USB_ISTR_ALL_EVENTS (USB_ISTR_PMAOVR | USB_ISTR_ERR | USB_ISTR_WKUP | USB_ISTR_SUSP | \
USB_ISTR_RESET | USB_ISTR_SOF | USB_ISTR_ESOF | USB_ISTR_L1REQ_FORCED )
// Number of endpoints in hardware
#define STFSDEV_EP_COUNT (8u)
#endif /* PORTABLE_ST_STM32F0_DCD_STM32F0_FSDEV_PVT_ST_H_ */

View File

@ -0,0 +1,643 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Koji KITAYAMA
* Copyright (c) 2021 Tian Yunhao (t123yh)
* Copyright (c) 2021 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.
*/
#ifndef _TUSB_MUSB_DEF
#define _TUSB_MUSB_DEF
#define USBC_Readb(reg) (*(volatile unsigned char *)(reg))
#define USBC_Readw(reg) (*(volatile unsigned short *)(reg))
#define USBC_Readl(reg) (*(volatile unsigned long *)(reg))
#define USBC_Writeb(value, reg) (*(volatile unsigned char *)(reg) = (value))
#define USBC_Writew(value, reg) (*(volatile unsigned short *)(reg) = (value))
#define USBC_Writel(value, reg) (*(volatile unsigned long *)(reg) = (value))
#define USBC_SetBit_Mask_b(reg,mask) do { \
unsigned char _r = USBC_Readb(reg); \
_r |= (unsigned char)(mask); \
USBC_Writeb(_r,reg); \
}while(0)
#define USBC_SetBit_Mask_w(reg,mask) do { \
unsigned short _r = USBC_Readw(reg); \
_r |= (unsigned short)(mask); \
USBC_Writew(_r,reg); \
}while(0)
#define USBC_SetBit_Mask_l(reg,mask) do { \
unsigned int _r = USBC_Readl(reg); \
_r |= (unsigned int)(mask); \
USBC_Writel(_r,reg); \
}while(0)
#define USBC_ClrBit_Mask_b(reg,mask) do { \
unsigned char _r = USBC_Readb(reg); \
_r &= (~(unsigned char)(mask)); \
USBC_Writeb(_r,reg); \
}while(0);
#define USBC_ClrBit_Mask_w(reg,mask) do { \
unsigned short _r = USBC_Readw(reg); \
_r &= (~(unsigned short)(mask)); \
USBC_Writew(_r,reg); \
}while(0)
#define USBC_ClrBit_Mask_l(reg,mask) do { \
unsigned int _r = USBC_Readl(reg); \
_r &= (~(unsigned int)(mask)); \
USBC_Writel(_r,reg); \
}while(0)
#define USBC_REG_test_bit_b(bp, reg) (USBC_Readb(reg) & (1 << (bp)))
#define USBC_REG_test_bit_w(bp, reg) (USBC_Readw(reg) & (1 << (bp)))
#define USBC_REG_test_bit_l(bp, reg) (USBC_Readl(reg) & (1 << (bp)))
#define USBC_REG_set_bit_b(bp, reg) (USBC_Writeb((USBC_Readb(reg) | (1 << (bp))) , (reg)))
#define USBC_REG_set_bit_w(bp, reg) (USBC_Writew((USBC_Readw(reg) | (1 << (bp))) , (reg)))
#define USBC_REG_set_bit_l(bp, reg) (USBC_Writel((USBC_Readl(reg) | (1 << (bp))) , (reg)))
#define USBC_REG_clear_bit_b(bp, reg) (USBC_Writeb((USBC_Readb(reg) & (~ (1 << (bp)))) , (reg)))
#define USBC_REG_clear_bit_w(bp, reg) (USBC_Writew((USBC_Readw(reg) & (~ (1 << (bp)))) , (reg)))
#define USBC_REG_clear_bit_l(bp, reg) (USBC_Writel((USBC_Readl(reg) & (~ (1 << (bp)))) , (reg)))
#define SW_UDC_EPNUMS 3
#define SUNXI_SRAMC_BASE 0x01c00000
//---------------------------------------------------------------
// reg base
//---------------------------------------------------------------
#define USBC0_BASE 0x01c13000
#define USBC1_BASE 0x01c14000
#define USBC2_BASE 0x01c1E000
//Some reg whithin musb
#define USBPHY_CLK_REG 0x01c200CC
#define USBPHY_CLK_RST_BIT 0
#define USBPHY_CLK_GAT_BIT 1
#define BUS_CLK_RST_REG 0x01c202c0 //Bus Clock Reset Register Bit24 : USB CLK RST
#define BUS_RST_USB_BIT 24
#define BUS_CLK_GATE0_REG 0x01c20060 //Bus Clock Gating Register Bit24 : USB CLK GATE 0: Mask 1 : Pass
#define BUS_CLK_USB_BIT 24
//#define USB_INTR
#define NDMA_CFG_REG
//-----------------------------------------------------------------------
// musb reg offset
//-----------------------------------------------------------------------
#define USBC_REG_o_FADDR 0x0098
#define USBC_REG_o_PCTL 0x0040
#define USBC_REG_o_INTTx 0x0044
#define USBC_REG_o_INTRx 0x0046
#define USBC_REG_o_INTTxE 0x0048
#define USBC_REG_o_INTRxE 0x004A
#define USBC_REG_o_INTUSB 0x004C
#define USBC_REG_o_INTUSBE 0x0050
#define USBC_REG_o_FRNUM 0x0054
#define USBC_REG_o_EPIND 0x0042
#define USBC_REG_o_TMCTL 0x007C
#define USBC_REG_o_TXMAXP 0x0080
#define USBC_REG_o_CSR0 0x0082
#define USBC_REG_o_TXCSR 0x0082
#define USBC_REG_o_RXMAXP 0x0084
#define USBC_REG_o_RXCSR 0x0086
#define USBC_REG_o_COUNT0 0x0088
#define USBC_REG_o_RXCOUNT 0x0088
#define USBC_REG_o_EP0TYPE 0x008C
#define USBC_REG_o_TXTYPE 0x008C
#define USBC_REG_o_NAKLIMIT0 0x008D
#define USBC_REG_o_TXINTERVAL 0x008D
#define USBC_REG_o_RXTYPE 0x008E
#define USBC_REG_o_RXINTERVAL 0x008F
//#define USBC_REG_o_CONFIGDATA 0x001F //
#define USBC_REG_o_EPFIFO0 0x0000
#define USBC_REG_o_EPFIFO1 0x0004
#define USBC_REG_o_EPFIFO2 0x0008
#define USBC_REG_o_EPFIFO3 0x000C
#define USBC_REG_o_EPFIFO4 0x0010
#define USBC_REG_o_EPFIFO5 0x0014
#define USBC_REG_o_EPFIFOx(n) (0x0000 + (n<<2))
#define USBC_REG_o_DEVCTL 0x0041
#define USBC_REG_o_TXFIFOSZ 0x0090
#define USBC_REG_o_RXFIFOSZ 0x0094
#define USBC_REG_o_TXFIFOAD 0x0092
#define USBC_REG_o_RXFIFOAD 0x0096
#define USBC_REG_o_VEND0 0x0043
#define USBC_REG_o_VEND1 0x007D
#define USBC_REG_o_VEND3 0x007E
//#define USBC_REG_o_PHYCTL 0x006C
#define USBC_REG_o_EPINFO 0x0078
#define USBC_REG_o_RAMINFO 0x0079
#define USBC_REG_o_LINKINFO 0x007A
#define USBC_REG_o_VPLEN 0x007B
#define USBC_REG_o_HSEOF 0x007C
#define USBC_REG_o_FSEOF 0x007D
#define USBC_REG_o_LSEOF 0x007E
//new
#define USBC_REG_o_FADDR0 0x0098
#define USBC_REG_o_HADDR0 0x009A
#define USBC_REG_o_HPORT0 0x009B
#define USBC_REG_o_TXFADDRx 0x0098
#define USBC_REG_o_TXHADDRx 0x009A
#define USBC_REG_o_TXHPORTx 0x009B
#define USBC_REG_o_RXFADDRx 0x009C
#define USBC_REG_o_RXHADDRx 0x009E
#define USBC_REG_o_RXHPORTx 0x009F
#define USBC_REG_o_RPCOUNT 0x008A
//new
#define USBC_REG_o_ISCR 0x0400
#define USBC_REG_o_PHYCTL 0x0404
#define USBC_REG_o_PHYBIST 0x0408
#define USBC_REG_o_PHYTUNE 0x040c
#define USBC_REG_o_CSR 0x0410
#define USBC_REG_o_PMU_IRQ 0x0800
//-----------------------------------------------------------------------
// registers
//-----------------------------------------------------------------------
#define USBC_REG_FADDR(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_FADDR )
#define USBC_REG_PCTL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_PCTL )
#define USBC_REG_INTTx(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTTx )
#define USBC_REG_INTRx(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTRx )
#define USBC_REG_INTTxE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTTxE )
#define USBC_REG_INTRxE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTRxE )
#define USBC_REG_INTUSB(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTUSB )
#define USBC_REG_INTUSBE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_INTUSBE )
#define USBC_REG_FRNUM(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_FRNUM )
#define USBC_REG_EPIND(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPIND )
#define USBC_REG_TMCTL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TMCTL )
#define USBC_REG_TXMAXP(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXMAXP )
#define USBC_REG_CSR0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_CSR0 )
#define USBC_REG_TXCSR(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXCSR )
#define USBC_REG_RXMAXP(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXMAXP )
#define USBC_REG_RXCSR(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXCSR )
#define USBC_REG_COUNT0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_COUNT0 )
#define USBC_REG_RXCOUNT(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXCOUNT )
#define USBC_REG_EP0TYPE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EP0TYPE )
#define USBC_REG_TXTYPE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXTYPE )
#define USBC_REG_NAKLIMIT0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_NAKLIMIT0 )
#define USBC_REG_TXINTERVAL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXINTERVAL )
#define USBC_REG_RXTYPE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXTYPE )
#define USBC_REG_RXINTERVAL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXINTERVAL )
//#define USBC_REG_CONFIGDATA(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_CONFIGDATA )
#define USBC_REG_EPFIFO0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO0 )
#define USBC_REG_EPFIFO1(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO1 )
#define USBC_REG_EPFIFO2(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO2 )
#define USBC_REG_EPFIFO3(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO3 )
#define USBC_REG_EPFIFO4(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO4 )
#define USBC_REG_EPFIFO5(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPFIFO5 )
#define USBC_REG_EPFIFOx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_EPFIFOx(n) )
#define USBC_REG_DEVCTL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_DEVCTL )
#define USBC_REG_TXFIFOSZ(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXFIFOSZ )
#define USBC_REG_RXFIFOSZ(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXFIFOSZ )
#define USBC_REG_TXFIFOAD(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_TXFIFOAD )
#define USBC_REG_RXFIFOAD(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RXFIFOAD )
#define USBC_REG_VEND0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_VEND0 )
#define USBC_REG_VEND1(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_VEND1 )
#define USBC_REG_EPINFO(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_EPINFO )
#define USBC_REG_RAMINFO(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_RAMINFO )
#define USBC_REG_LINKINFO(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_LINKINFO )
#define USBC_REG_VPLEN(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_VPLEN )
#define USBC_REG_HSEOF(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_HSEOF )
#define USBC_REG_FSEOF(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_FSEOF )
#define USBC_REG_LSEOF(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_LSEOF )
#define USBC_REG_FADDR0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_FADDR0 )
#define USBC_REG_HADDR0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_HADDR0 )
#define USBC_REG_HPORT0(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_HPORT0 )
#define USBC_REG_TXFADDRx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_TXFADDRx )
#define USBC_REG_TXHADDRx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_TXHADDRx )
#define USBC_REG_TXHPORTx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_TXHPORTx )
#define USBC_REG_RXFADDRx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_RXFADDRx )
#define USBC_REG_RXHADDRx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_RXHADDRx )
#define USBC_REG_RXHPORTx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_RXHPORTx )
#define USBC_REG_RPCOUNTx(usbc_base_addr, n) ((usbc_base_addr) + USBC_REG_o_RPCOUNT )
#define USBC_REG_ISCR(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_ISCR )
#define USBC_REG_PHYCTL(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_PHYCTL )
#define USBC_REG_PHYBIST(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_PHYBIST )
#define USBC_REG_PHYTUNE(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_PHYTUNE )
#define USBC_REG_PMU_IRQ(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_PMU_IRQ )
#define USBC_REG_CSR(usbc_base_addr) ((usbc_base_addr) + USBC_REG_o_CSR)
//-----------------------------------------------------------------------
// bit position
//-----------------------------------------------------------------------
/* USB Power Control for Host only */
#define USBC_BP_POWER_H_HIGH_SPEED_EN 5
#define USBC_BP_POWER_H_HIGH_SPEED_FLAG 4
#define USBC_BP_POWER_H_RESET 3
#define USBC_BP_POWER_H_RESUME 2
#define USBC_BP_POWER_H_SUSPEND 1
#define USBC_BP_POWER_H_SUEPEND_EN 0
/* USB Power Control for device only */
#define USBC_BP_POWER_D_ISO_UPDATE_EN 7
#define USBC_BP_POWER_D_SOFT_CONNECT 6
#define USBC_BP_POWER_D_HIGH_SPEED_EN 5
#define USBC_BP_POWER_D_HIGH_SPEED_FLAG 4
#define USBC_BP_POWER_D_RESET_FLAG 3
#define USBC_BP_POWER_D_RESUME 2
#define USBC_BP_POWER_D_SUSPEND 1
#define USBC_BP_POWER_D_ENABLE_SUSPENDM 0
/* interrupt flags for ep0 and the Tx ep1~4 */
#define USBC_BP_INTTx_FLAG_EP5 5
#define USBC_BP_INTTx_FLAG_EP4 4
#define USBC_BP_INTTx_FLAG_EP3 3
#define USBC_BP_INTTx_FLAG_EP2 2
#define USBC_BP_INTTx_FLAG_EP1 1
#define USBC_BP_INTTx_FLAG_EP0 0
/* interrupt flags for Rx ep1~4 */
#define USBC_BP_INTRx_FLAG_EP5 5
#define USBC_BP_INTRx_FLAG_EP4 4
#define USBC_BP_INTRx_FLAG_EP3 3
#define USBC_BP_INTRx_FLAG_EP2 2
#define USBC_BP_INTRx_FLAG_EP1 1
/* interrupt enable for Tx ep0~4 */
#define USBC_BP_INTTxE_EN_EP5 5
#define USBC_BP_INTTxE_EN_EP4 4
#define USBC_BP_INTTxE_EN_EP3 3
#define USBC_BP_INTTxE_EN_EP2 2
#define USBC_BP_INTTxE_EN_EP1 1
#define USBC_BP_INTTxE_EN_EP0 0
/* interrupt enable for Rx ep1~4 */
#define USBC_BP_INTRxE_EN_EP5 5
#define USBC_BP_INTRxE_EN_EP4 4
#define USBC_BP_INTRxE_EN_EP3 3
#define USBC_BP_INTRxE_EN_EP2 2
#define USBC_BP_INTRxE_EN_EP1 1
/* USB interrupt */
#define USBC_BP_INTUSB_VBUS_ERROR 7
#define USBC_BP_INTUSB_SESSION_REQ 6
#define USBC_BP_INTUSB_DISCONNECT 5
#define USBC_BP_INTUSB_CONNECT 4
#define USBC_BP_INTUSB_SOF 3
#define USBC_BP_INTUSB_RESET 2
#define USBC_BP_INTUSB_RESUME 1
#define USBC_BP_INTUSB_SUSPEND 0
/* USB interrupt enable */
#define USBC_BP_INTUSBE_EN_VBUS_ERROR 7
#define USBC_BP_INTUSBE_EN_SESSION_REQ 6
#define USBC_BP_INTUSBE_EN_DISCONNECT 5
#define USBC_BP_INTUSBE_EN_CONNECT 4
#define USBC_BP_INTUSBE_EN_SOF 3
#define USBC_BP_INTUSBE_EN_RESET 2
#define USBC_BP_INTUSBE_EN_RESUME 1
#define USBC_BP_INTUSBE_EN_SUSPEND 0
/* Test Mode Control */
#define USBC_BP_TMCTL_FORCE_HOST 7
#define USBC_BP_TMCTL_FIFO_ACCESS 6
#define USBC_BP_TMCTL_FORCE_FS 5
#define USBC_BP_TMCTL_FORCE_HS 4
#define USBC_BP_TMCTL_TEST_PACKET 3
#define USBC_BP_TMCTL_TEST_K 2
#define USBC_BP_TMCTL_TEST_J 1
#define USBC_BP_TMCTL_TEST_SE0_NAK 0
/* Tx Max packet */
#define USBC_BP_TXMAXP_PACKET_COUNT 11
#define USBC_BP_TXMAXP_MAXIMUM_PAYLOAD 0
/* Control and Status Register for ep0 for Host only */
#define USBC_BP_CSR0_H_DisPing 11
#define USBC_BP_CSR0_H_FlushFIFO 8
#define USBC_BP_CSR0_H_NAK_Timeout 7
#define USBC_BP_CSR0_H_StatusPkt 6
#define USBC_BP_CSR0_H_ReqPkt 5
#define USBC_BP_CSR0_H_Error 4
#define USBC_BP_CSR0_H_SetupPkt 3
#define USBC_BP_CSR0_H_RxStall 2
#define USBC_BP_CSR0_H_TxPkRdy 1
#define USBC_BP_CSR0_H_RxPkRdy 0
/* Control and Status Register for ep0 for device only */
#define USBC_BP_CSR0_D_FLUSH_FIFO 8
#define USBC_BP_CSR0_D_SERVICED_SETUP_END 7
#define USBC_BP_CSR0_D_SERVICED_RX_PKT_READY 6
#define USBC_BP_CSR0_D_SEND_STALL 5
#define USBC_BP_CSR0_D_SETUP_END 4
#define USBC_BP_CSR0_D_DATA_END 3
#define USBC_BP_CSR0_D_SENT_STALL 2
#define USBC_BP_CSR0_D_TX_PKT_READY 1
#define USBC_BP_CSR0_D_RX_PKT_READY 0
/* Tx ep Control and Status Register for Host only */
#define USBC_BP_TXCSR_H_AUTOSET 15
#define USBC_BP_TXCSR_H_RESERVED 14
#define USBC_BP_TXCSR_H_MODE 13
#define USBC_BP_TXCSR_H_DMA_REQ_EN 12
#define USBC_BP_TXCSR_H_FORCE_DATA_TOGGLE 11
#define USBC_BP_TXCSR_H_DMA_REQ_MODE 10
#define USBC_BP_TXCSR_H_NAK_TIMEOUT 7
#define USBC_BP_TXCSR_H_CLEAR_DATA_TOGGLE 6
#define USBC_BP_TXCSR_H_TX_STALL 5
#define USBC_BP_TXCSR_H_FLUSH_FIFO 3
#define USBC_BP_TXCSR_H_ERROR 2
#define USBC_BP_TXCSR_H_FIFO_NOT_EMPTY 1
#define USBC_BP_TXCSR_H_TX_READY 0
/* Tx ep Control and Status Register for Device only */
#define USBC_BP_TXCSR_D_AUTOSET 15
#define USBC_BP_TXCSR_D_ISO 14
#define USBC_BP_TXCSR_D_MODE 13
#define USBC_BP_TXCSR_D_DMA_REQ_EN 12
#define USBC_BP_TXCSR_D_FORCE_DATA_TOGGLE 11
#define USBC_BP_TXCSR_D_DMA_REQ_MODE 10
#define USBC_BP_TXCSR_D_INCOMPLETE 7
#define USBC_BP_TXCSR_D_CLEAR_DATA_TOGGLE 6
#define USBC_BP_TXCSR_D_SENT_STALL 5
#define USBC_BP_TXCSR_D_SEND_STALL 4
#define USBC_BP_TXCSR_D_FLUSH_FIFO 3
#define USBC_BP_TXCSR_D_UNDER_RUN 2
#define USBC_BP_TXCSR_D_FIFO_NOT_EMPTY 1
#define USBC_BP_TXCSR_D_TX_READY 0
/* Rx Max Packet */
#define USBC_BP_RXMAXP_PACKET_COUNT 11
#define USBC_BP_RXMAXP_MAXIMUM_PAYLOAD 0
/* Rx ep Control and Status Register for Host only */
#define USBC_BP_RXCSR_H_AUTO_CLEAR 15
#define USBC_BP_RXCSR_H_AUTO_REQ 14
#define USBC_BP_RXCSR_H_DMA_REQ_EN 13
#define USBC_BP_RXCSR_H_PID_ERROR 12
#define USBC_BP_RXCSR_H_DMA_REQ_MODE 11
#define USBC_BP_RXCSR_H_INCOMPLETE 8
#define USBC_BP_RXCSR_H_CLEAR_DATA_TOGGLE 7
#define USBC_BP_RXCSR_H_RX_STALL 6
#define USBC_BP_RXCSR_H_REQ_PACKET 5
#define USBC_BP_RXCSR_H_FLUSH_FIFO 4
#define USBC_BP_RXCSR_H_NAK_TIMEOUT 3
#define USBC_BP_RXCSR_H_ERROR 2
#define USBC_BP_RXCSR_H_FIFO_FULL 1
#define USBC_BP_RXCSR_H_RX_PKT_READY 0
/* Rx ep Control and Status Register for Device only */
#define USBC_BP_RXCSR_D_AUTO_CLEAR 15
#define USBC_BP_RXCSR_D_ISO 14
#define USBC_BP_RXCSR_D_DMA_REQ_EN 13
#define USBC_BP_RXCSR_D_DISABLE_NYET 12
#define USBC_BP_RXCSR_D_DMA_REQ_MODE 11
#define USBC_BP_RXCSR_D_INCOMPLETE 8
#define USBC_BP_RXCSR_D_CLEAR_DATA_TOGGLE 7
#define USBC_BP_RXCSR_D_SENT_STALL 6
#define USBC_BP_RXCSR_D_SEND_STALL 5
#define USBC_BP_RXCSR_D_FLUSH_FIFO 4
#define USBC_BP_RXCSR_D_DATA_ERROR 3
#define USBC_BP_RXCSR_D_OVERRUN 2
#define USBC_BP_RXCSR_D_FIFO_FULL 1
#define USBC_BP_RXCSR_D_RX_PKT_READY 0
/* Tx Type Register for host only */
#define USBC_BP_TXTYPE_SPEED 6 //new
#define USBC_BP_TXTYPE_PROROCOL 4
#define USBC_BP_TXTYPE_TARGET_EP_NUM 0
/* Rx Type Register for host only */
#define USBC_BP_RXTYPE_SPEED 6 //new
#define USBC_BP_RXTYPE_PROROCOL 4
#define USBC_BP_RXTYPE_TARGET_EP_NUM 0
/* Core Configueation */
#define USBC_BP_CONFIGDATA_MPRXE 7
#define USBC_BP_CONFIGDATA_MPTXE 6
#define USBC_BP_CONFIGDATA_BIGENDIAN 5
#define USBC_BP_CONFIGDATA_HBRXE 4
#define USBC_BP_CONFIGDATA_HBTXE 3
#define USBC_BP_CONFIGDATA_DYNFIFO_SIZING 2
#define USBC_BP_CONFIGDATA_SOFTCONE 1
#define USBC_BP_CONFIGDATA_UTMI_DATAWIDTH 0
/* OTG Device Control */
#define USBC_BP_DEVCTL_B_DEVICE 7
#define USBC_BP_DEVCTL_FS_DEV 6
#define USBC_BP_DEVCTL_LS_DEV 5
#define USBC_BP_DEVCTL_VBUS 3
#define USBC_BP_DEVCTL_HOST_MODE 2
#define USBC_BP_DEVCTL_HOST_REQ 1
#define USBC_BP_DEVCTL_SESSION 0
/* Tx EP FIFO size control */
#define USBC_BP_TXFIFOSZ_DPB 4
#define USBC_BP_TXFIFOSZ_SZ 0
/* Rx EP FIFO size control */
#define USBC_BP_RXFIFOSZ_DPB 4
#define USBC_BP_RXFIFOSZ_SZ 0
/* vendor0 */
#define USBC_BP_VEND0_DRQ_SEL 1
#define USBC_BP_VEND0_BUS_SEL 0
/* hub address */
#define USBC_BP_HADDR_MULTI_TT 7
/* Interface Status and Control */
#define USBC_BP_ISCR_VBUS_VALID_FROM_DATA 30
#define USBC_BP_ISCR_VBUS_VALID_FROM_VBUS 29
#define USBC_BP_ISCR_EXT_ID_STATUS 28
#define USBC_BP_ISCR_EXT_DM_STATUS 27
#define USBC_BP_ISCR_EXT_DP_STATUS 26
#define USBC_BP_ISCR_MERGED_VBUS_STATUS 25
#define USBC_BP_ISCR_MERGED_ID_STATUS 24
#define USBC_BP_ISCR_ID_PULLUP_EN 17
#define USBC_BP_ISCR_DPDM_PULLUP_EN 16
#define USBC_BP_ISCR_FORCE_ID 14
#define USBC_BP_ISCR_FORCE_VBUS_VALID 12
#define USBC_BP_ISCR_VBUS_VALID_SRC 10
#define USBC_BP_ISCR_HOSC_EN 7
#define USBC_BP_ISCR_VBUS_CHANGE_DETECT 6
#define USBC_BP_ISCR_ID_CHANGE_DETECT 5
#define USBC_BP_ISCR_DPDM_CHANGE_DETECT 4
#define USBC_BP_ISCR_IRQ_ENABLE 3
#define USBC_BP_ISCR_VBUS_CHANGE_DETECT_EN 2
#define USBC_BP_ISCR_ID_CHANGE_DETECT_EN 1
#define USBC_BP_ISCR_DPDM_CHANGE_DETECT_EN 0
#define SUNXI_EHCI_AHB_ICHR8_EN (1 << 10)
#define SUNXI_EHCI_AHB_INCR4_BURST_EN (1 << 9)
#define SUNXI_EHCI_AHB_INCRX_ALIGN_EN (1 << 8)
#define SUNXI_EHCI_ULPI_BYPASS_EN (1 << 0)
//-----------------------------------------------------------------------
// <20>Զ<EFBFBD><D4B6><EFBFBD>
//-----------------------------------------------------------------------
/* usb<73><62>Դ<EFBFBD><D4B4><EFBFBD><EFBFBD> */
#define USBC_MAX_CTL_NUM 1
#define USBC_MAX_EP_NUM 3 //ep0~2, ep<65>ĸ<EFBFBD><C4B8><EFBFBD>
#define USBC_MAX_FIFO_SIZE (2 * 1024)
/* usb OTG mode */
#define USBC_OTG_HOST 0
#define USBC_OTG_DEVICE 1
/* usb device type */
#define USBC_DEVICE_HSDEV 0
#define USBC_DEVICE_FSDEV 1
#define USBC_DEVICE_LSDEV 2
/* usb transfer type */
#define USBC_TS_TYPE_IDLE 0
#define USBC_TS_TYPE_CTRL 1
#define USBC_TS_TYPE_ISO 2
#define USBC_TS_TYPE_INT 3
#define USBC_TS_TYPE_BULK 4
/* usb transfer mode */
#define USBC_TS_MODE_UNKOWN 0
#define USBC_TS_MODE_LS 1
#define USBC_TS_MODE_FS 2
#define USBC_TS_MODE_HS 3
/* usb Vbus status */
#define USBC_VBUS_STATUS_BELOW_SESSIONEND 0
#define USBC_VBUS_STATUS_ABOVE_SESSIONEND_BELOW_AVALID 1
#define USBC_VBUS_STATUS_ABOVE_AVALID_BELOW_VBUSVALID 2
#define USBC_VBUS_STATUS_ABOVE_VBUSVALID 3
/* usb io type */
#define USBC_IO_TYPE_PIO 0
#define USBC_IO_TYPE_DMA 1
/* usb ep type */
#define USBC_EP_TYPE_IDLE 0
#define USBC_EP_TYPE_EP0 1
#define USBC_EP_TYPE_TX 2
#define USBC_EP_TYPE_RX 3
/* usb id type */
#define USBC_ID_TYPE_DISABLE 0
#define USBC_ID_TYPE_HOST 1
#define USBC_ID_TYPE_DEVICE 2
/* usb vbus valid type */
#define USBC_VBUS_TYPE_DISABLE 0
#define USBC_VBUS_TYPE_LOW 1
#define USBC_VBUS_TYPE_HIGH 2
/* usb a valid source */
#define USBC_A_VALID_SOURCE_UTMI_AVALID 0
#define USBC_A_VALID_SOURCE_UTMI_VBUS 1
/* usb device switch */
#define USBC_DEVICE_SWITCH_OFF 0
#define USBC_DEVICE_SWITCH_ON 1
/* usb fifo config mode */
#define USBC_FIFO_MODE_4K 0
#define USBC_FIFO_MODE_8K 1
/*
**************************************************
* usb interrupt mask
*
**************************************************
*/
/* interrupt flags for ep0 and the Tx ep1~4 */
#define USBC_INTTx_FLAG_EP5 (1 << USBC_BP_INTTx_FLAG_EP5)
#define USBC_INTTx_FLAG_EP4 (1 << USBC_BP_INTTx_FLAG_EP4)
#define USBC_INTTx_FLAG_EP3 (1 << USBC_BP_INTTx_FLAG_EP3)
#define USBC_INTTx_FLAG_EP2 (1 << USBC_BP_INTTx_FLAG_EP2)
#define USBC_INTTx_FLAG_EP1 (1 << USBC_BP_INTTx_FLAG_EP1)
#define USBC_INTTx_FLAG_EP0 (1 << USBC_BP_INTTx_FLAG_EP0)
/* interrupt flags for Rx ep1~4 */
#define USBC_INTRx_FLAG_EP5 (1 << USBC_BP_INTRx_FLAG_EP5)
#define USBC_INTRx_FLAG_EP4 (1 << USBC_BP_INTRx_FLAG_EP4)
#define USBC_INTRx_FLAG_EP3 (1 << USBC_BP_INTRx_FLAG_EP3)
#define USBC_INTRx_FLAG_EP2 (1 << USBC_BP_INTRx_FLAG_EP2)
#define USBC_INTRx_FLAG_EP1 (1 << USBC_BP_INTRx_FLAG_EP1)
/* USB interrupt */
#define USBC_INTUSB_VBUS_ERROR (1 << USBC_BP_INTUSB_VBUS_ERROR)
#define USBC_INTUSB_SESSION_REQ (1 << USBC_BP_INTUSB_SESSION_REQ)
#define USBC_INTUSB_DISCONNECT (1 << USBC_BP_INTUSB_DISCONNECT)
#define USBC_INTUSB_CONNECT (1 << USBC_BP_INTUSB_CONNECT)
#define USBC_INTUSB_SOF (1 << USBC_BP_INTUSB_SOF)
#define USBC_INTUSB_RESET (1 << USBC_BP_INTUSB_RESET)
#define USBC_INTUSB_RESUME (1 << USBC_BP_INTUSB_RESUME)
#define USBC_INTUSB_SUSPEND (1 << USBC_BP_INTUSB_SUSPEND)
#define USB_CSRL0_NAKTO 0x00000080 // NAK Timeout
#define USB_CSRL0_SETENDC 0x00000080 // Setup End Clear
#define USB_CSRL0_STATUS 0x00000040 // STATUS Packet
#define USB_CSRL0_RXRDYC 0x00000040 // RXRDY Clear
#define USB_CSRL0_REQPKT 0x00000020 // Request Packet
#define USB_CSRL0_STALL 0x00000020 // Send Stall
#define USB_CSRL0_SETEND 0x00000010 // Setup End
#define USB_CSRL0_ERROR 0x00000010 // Error
#define USB_CSRL0_DATAEND 0x00000008 // Data End
#define USB_CSRL0_SETUP 0x00000008 // Setup Packet
#define USB_CSRL0_STALLED 0x00000004 // Endpoint Stalled
#define USB_CSRL0_TXRDY 0x00000002 // Transmit Packet Ready
#define USB_CSRL0_RXRDY 0x00000001 // Receive Packet Ready
#define USB_RXFIFOSZ_DPB 0x00000010 // Double Packet Buffer Support
#define USB_RXFIFOSZ_SIZE_M 0x0000000F // Max Packet Size
#define USB_TXFIFOSZ_DPB 0x00000010 // Double Packet Buffer Support
#define USB_TXFIFOSZ_SIZE_M 0x0000000F // Max Packet Size
#endif

View File

@ -0,0 +1,88 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _TUSB_DWC2_BCM_H_
#define _TUSB_DWC2_BCM_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "broadcom/defines.h"
#include "broadcom/interrupts.h"
#include "broadcom/caches.h"
#define DWC2_REG_BASE USB_OTG_GLOBAL_BASE
#define DWC2_EP_MAX 8
#define DWC2_EP_FIFO_SIZE 4096
#define dcache_clean(_addr, _size) data_clean(_addr, _size)
#define dcache_invalidate(_addr, _size) data_invalidate(_addr, _size)
#define dcache_clean_invalidate(_addr, _size) data_clean_and_invalidate(_addr, _size)
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
BP_EnableIRQ(USB_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
BP_DisableIRQ(USB_IRQn);
}
static inline void dwc2_remote_wakeup_delay(void)
{
// try to delay for 1 ms
// TODO implement later
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,87 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Rafael Silva (@perigoso)
* Copyright (c) 2021, 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.
*/
#ifndef _DWC2_EFM32_H_
#define _DWC2_EFM32_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "em_device.h"
// EFM32 has custom control register before DWC registers
#define DWC2_REG_BASE (USB_BASE + offsetof(USB_TypeDef, GOTGCTL))
#define DWC2_EP_MAX 7
#define DWC2_EP_FIFO_SIZE 2048
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB_IRQn);
}
static inline void dwc2_remote_wakeup_delay(void)
{
// try to delay for 1 ms
// uint32_t count = SystemCoreClock / 1000;
// while ( count-- ) __NOP();
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// Enable PHY
USB->ROUTE = USB_ROUTE_PHYPEN;
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// EFM32 Manual: turn around must be 5 (reset & default value)
// dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (5u << GUSBCFG_TRDT_Pos);
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,94 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _DWC2_ESP32_H_
#define _DWC2_ESP32_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_intr_alloc.h"
#include "soc/periph_defs.h"
//#include "soc/usb_periph.h"
#define DWC2_REG_BASE 0x60080000UL
#define DWC2_EP_MAX 5 // USB_OUT_EP_NUM
#define DWC2_EP_FIFO_SIZE 1024
// #define EP_FIFO_NUM 5
static intr_handle_t usb_ih;
static void dcd_int_handler_wrap(void* arg)
{
(void) arg;
dcd_int_handler(0);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable (uint8_t rhport)
{
(void) rhport;
esp_intr_alloc(ETS_USB_INTR_SOURCE, ESP_INTR_FLAG_LOWMED, dcd_int_handler_wrap, NULL, &usb_ih);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
esp_intr_free(usb_ih);
}
static inline void dwc2_remote_wakeup_delay(void)
{
vTaskDelay(pdMS_TO_TICKS(1));
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
#ifdef __cplusplus
}
#endif
#endif /* _DWC2_ESP32_H_ */

View File

@ -0,0 +1,100 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef DWC2_GD32_H_
#define DWC2_GD32_H_
#ifdef __cplusplus
extern "C" {
#endif
#define DWC2_REG_BASE 0x50000000UL
#define DWC2_EP_MAX 4
#define DWC2_EP_FIFO_SIZE 1280
#define RHPORT_IRQn 86
extern uint32_t SystemCoreClock;
// The GD32VF103 is a RISC-V MCU, which implements the ECLIC Core-Local
// Interrupt Controller by Nuclei. It is nearly API compatible to the
// NVIC used by ARM MCUs.
#define ECLIC_INTERRUPT_ENABLE_BASE 0xD2001001UL
TU_ATTR_ALWAYS_INLINE
static inline void __eclic_enable_interrupt (uint32_t irq) {
*(volatile uint8_t*)(ECLIC_INTERRUPT_ENABLE_BASE + (irq * 4)) = 1;
}
TU_ATTR_ALWAYS_INLINE
static inline void __eclic_disable_interrupt (uint32_t irq){
*(volatile uint8_t*)(ECLIC_INTERRUPT_ENABLE_BASE + (irq * 4)) = 0;
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
__eclic_enable_interrupt(RHPORT_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
__eclic_disable_interrupt(RHPORT_IRQn);
}
static inline void dwc2_remote_wakeup_delay(void)
{
// try to delay for 1 ms
uint32_t count = SystemCoreClock / 1000;
while ( count-- ) __asm volatile ("nop");
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// nothing to do
}
#ifdef __cplusplus
}
#endif
#endif /* DWC2_GD32_H_ */

View File

@ -0,0 +1,205 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, 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.
*/
#ifndef _DWC2_STM32_H_
#define _DWC2_STM32_H_
#ifdef __cplusplus
extern "C" {
#endif
// EP_MAX : Max number of bi-directional endpoints including EP0
// EP_FIFO_SIZE : Size of dedicated USB SRAM
#if CFG_TUSB_MCU == OPT_MCU_STM32F1
#include "stm32f1xx.h"
#define EP_MAX_FS 4
#define EP_FIFO_SIZE_FS 1280
#elif CFG_TUSB_MCU == OPT_MCU_STM32F2
#include "stm32f2xx.h"
#define EP_MAX_FS USB_OTG_FS_MAX_IN_ENDPOINTS
#define EP_FIFO_SIZE_FS USB_OTG_FS_TOTAL_FIFO_SIZE
#elif CFG_TUSB_MCU == OPT_MCU_STM32F4
#include "stm32f4xx.h"
#define EP_MAX_FS USB_OTG_FS_MAX_IN_ENDPOINTS
#define EP_FIFO_SIZE_FS USB_OTG_FS_TOTAL_FIFO_SIZE
#define EP_MAX_HS USB_OTG_HS_MAX_IN_ENDPOINTS
#define EP_FIFO_SIZE_HS USB_OTG_HS_TOTAL_FIFO_SIZE
#elif CFG_TUSB_MCU == OPT_MCU_STM32H7
#include "stm32h7xx.h"
#define EP_MAX_FS 9
#define EP_FIFO_SIZE_FS 4096
#define EP_MAX_HS 9
#define EP_FIFO_SIZE_HS 4096
#elif CFG_TUSB_MCU == OPT_MCU_STM32F7
#include "stm32f7xx.h"
#define EP_MAX_FS 6
#define EP_FIFO_SIZE_FS 1280
#define EP_MAX_HS 9
#define EP_FIFO_SIZE_HS 4096
#elif CFG_TUSB_MCU == OPT_MCU_STM32L4
#include "stm32l4xx.h"
#define EP_MAX_FS 6
#define EP_FIFO_SIZE_FS 1280
#else
#error "Unsupported MCUs"
#endif
// On STM32 we associate Port0 to OTG_FS, and Port1 to OTG_HS
#if TUD_OPT_RHPORT == 0
#define DWC2_REG_BASE USB_OTG_FS_PERIPH_BASE
#define DWC2_EP_MAX EP_MAX_FS
#define DWC2_EP_FIFO_SIZE EP_FIFO_SIZE_FS
#define RHPORT_IRQn OTG_FS_IRQn
#else
#define DWC2_REG_BASE USB_OTG_HS_PERIPH_BASE
#define DWC2_EP_MAX EP_MAX_HS
#define DWC2_EP_FIFO_SIZE EP_FIFO_SIZE_HS
#define RHPORT_IRQn OTG_HS_IRQn
#endif
extern uint32_t SystemCoreClock;
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(RHPORT_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(RHPORT_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_remote_wakeup_delay(void)
{
// try to delay for 1 ms
uint32_t count = SystemCoreClock / 1000;
while ( count-- ) __NOP();
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
if ( hs_phy_type == HS_PHY_TYPE_NONE )
{
// Enable on-chip FS PHY
dwc2->stm32_gccfg |= STM32_GCCFG_PWRDWN;
}else
{
// Disable FS PHY
dwc2->stm32_gccfg &= ~STM32_GCCFG_PWRDWN;
// Enable on-chip HS PHY
if (hs_phy_type == HS_PHY_TYPE_UTMI || hs_phy_type == HS_PHY_TYPE_UTMI_ULPI)
{
#ifdef USB_HS_PHYC
// Enable UTMI HS PHY
dwc2->stm32_gccfg |= STM32_GCCFG_PHYHSEN;
// Enable LDO
USB_HS_PHYC->USB_HS_PHYC_LDO |= USB_HS_PHYC_LDO_ENABLE;
// Wait until LDO ready
while ( 0 == (USB_HS_PHYC->USB_HS_PHYC_LDO & USB_HS_PHYC_LDO_STATUS) ) {}
uint32_t phyc_pll = 0;
// TODO Try to get HSE_VALUE from registers instead of depending CFLAGS
switch ( HSE_VALUE )
{
case 12000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_12MHZ ; break;
case 12500000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_12_5MHZ ; break;
case 16000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_16MHZ ; break;
case 24000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_24MHZ ; break;
case 25000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_25MHZ ; break;
case 32000000: phyc_pll = USB_HS_PHYC_PLL1_PLLSEL_Msk ; break; // Value not defined in header
default:
TU_ASSERT(false, );
}
USB_HS_PHYC->USB_HS_PHYC_PLL = phyc_pll;
// Control the tuning interface of the High Speed PHY
// Use magic value (USB_HS_PHYC_TUNE_VALUE) from ST driver for F7
USB_HS_PHYC->USB_HS_PHYC_TUNE |= 0x00000F13U;
// Enable PLL internal PHY
USB_HS_PHYC->USB_HS_PHYC_PLL |= USB_HS_PHYC_PLL_PLLEN;
#endif
}
}
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
// used to set turnaround time for fullspeed, nothing to do in highspeed mode
if ( hs_phy_type == HS_PHY_TYPE_NONE )
{
// Turnaround timeout depends on the AHB clock dictated by STM32 Reference Manual
uint32_t turnaround;
if ( SystemCoreClock >= 32000000u )
turnaround = 0x6u;
else if ( SystemCoreClock >= 27500000u )
turnaround = 0x7u;
else if ( SystemCoreClock >= 24000000u )
turnaround = 0x8u;
else if ( SystemCoreClock >= 21800000u )
turnaround = 0x9u;
else if ( SystemCoreClock >= 20000000u )
turnaround = 0xAu;
else if ( SystemCoreClock >= 18500000u )
turnaround = 0xBu;
else if ( SystemCoreClock >= 17200000u )
turnaround = 0xCu;
else if ( SystemCoreClock >= 16000000u )
turnaround = 0xDu;
else if ( SystemCoreClock >= 15000000u )
turnaround = 0xEu;
else
turnaround = 0xFu;
dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (turnaround << GUSBCFG_TRDT_Pos);
}
}
#ifdef __cplusplus
}
#endif
#endif /* _DWC2_STM32_H_ */

View File

@ -0,0 +1,87 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021 Rafael Silva (@perigoso)
* Copyright (c) 2021, 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.
*/
#ifndef _DWC2_XMC_H_
#define _DWC2_XMC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "xmc_device.h"
// XMC has custom control register before DWC registers
#define DWC2_REG_BASE USB0_BASE
#define DWC2_EP_MAX 7
#define DWC2_EP_FIFO_SIZE 2048
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB0_0_IRQn);
}
TU_ATTR_ALWAYS_INLINE
static inline void dwc2_dcd_int_disable (uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB0_0_IRQn);
}
static inline void dwc2_remote_wakeup_delay(void)
{
// try to delay for 1 ms
// uint32_t count = SystemCoreClock / 1000;
// while ( count-- ) __NOP();
}
// MCU specific PHY init, called BEFORE core reset
static inline void dwc2_phy_init(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// Enable PHY
//USB->ROUTE = USB_ROUTE_PHYPEN;
}
// MCU specific PHY update, it is called AFTER init() and core reset
static inline void dwc2_phy_update(dwc2_regs_t * dwc2, uint8_t hs_phy_type)
{
(void) dwc2;
(void) hs_phy_type;
// XMC Manual: turn around must be 5 (reset & default value)
// dwc2->gusbcfg = (dwc2->gusbcfg & ~GUSBCFG_TRDT_Msk) | (5u << GUSBCFG_TRDT_Pos);
}
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,39 @@
/*
* 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.
*/
#ifndef _TUSB_DCD_VALENTYUSB_EPTRI_H_
#define _TUSB_DCD_VALENTYUSB_EPTRI_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DCD_VALENTYUSB_EPTRI_H_ */

View File

@ -0,0 +1,136 @@
/*
* 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.
*/
#ifndef _TUSB_H_
#define _TUSB_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "common/tusb_common.h"
#include "osal/osal.h"
#include "common/tusb_fifo.h"
//------------- HOST -------------//
#if CFG_TUH_ENABLED
#include "host/usbh.h"
#if CFG_TUH_HID
#include "class/hid/hid_host.h"
#endif
#if CFG_TUH_MSC
#include "class/msc/msc_host.h"
#endif
#if CFG_TUH_CDC
#include "class/cdc/cdc_host.h"
#endif
#if CFG_TUH_VENDOR
#include "class/vendor/vendor_host.h"
#endif
#endif
//------------- DEVICE -------------//
#if CFG_TUD_ENABLED
#include "device/usbd.h"
#if CFG_TUD_HID
#include "class/hid/hid_device.h"
#endif
#if CFG_TUD_CDC
#include "class/cdc/cdc_device.h"
#endif
#if CFG_TUD_MSC
#include "class/msc/msc_device.h"
#endif
#if CFG_TUD_AUDIO
#include "class/audio/audio_device.h"
#endif
#if CFG_TUD_VIDEO
#include "class/video/video_device.h"
#endif
#if CFG_TUD_MIDI
#include "class/midi/midi_device.h"
#endif
#if CFG_TUD_VENDOR
#include "class/vendor/vendor_device.h"
#endif
#if CFG_TUD_USBTMC
#include "class/usbtmc/usbtmc_device.h"
#endif
#if CFG_TUD_DFU_RUNTIME
#include "class/dfu/dfu_rt_device.h"
#endif
#if CFG_TUD_DFU
#include "class/dfu/dfu_device.h"
#endif
#if CFG_TUD_ECM_RNDIS || CFG_TUD_NCM
#include "class/net/net_device.h"
#endif
#if CFG_TUD_BTH
#include "class/bth/bth_device.h"
#endif
#endif
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
// Initialize device/host stack
// Note: when using with RTOS, this should be called after scheduler/kernel is started.
// Otherwise it could cause kernel issue since USB IRQ handler does use RTOS queue API.
bool tusb_init(void);
// Check if stack is initialized
bool tusb_inited(void);
// TODO
// bool tusb_teardown(void);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_H_ */

View File

@ -0,0 +1,404 @@
/*
* 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.
*/
#ifndef _TUSB_OPTION_H_
#define _TUSB_OPTION_H_
#include "common/tusb_compiler.h"
#define TUSB_VERSION_MAJOR 0
#define TUSB_VERSION_MINOR 13
#define TUSB_VERSION_REVISION 0
#define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION)
//--------------------------------------------------------------------+
// Supported MCUs
// CFG_TUSB_MCU must be defined to one of following value
//--------------------------------------------------------------------+
#define OPT_MCU_NONE 0
// LPC
#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx
#define OPT_MCU_LPC13XX 2 ///< NXP LPC13xx
#define OPT_MCU_LPC15XX 3 ///< NXP LPC15xx
#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x
#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x
#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx
#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx
#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx
#define OPT_MCU_LPC51UXX 9 ///< NXP LPC51U6x
#define OPT_MCU_LPC54XXX 10 ///< NXP LPC54xxx
#define OPT_MCU_LPC55XX 11 ///< NXP LPC55xx
// NRF
#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series
// SAM
#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21
#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51
#define OPT_MCU_SAMG 202 ///< MicroChip SAMDG series
#define OPT_MCU_SAME5X 203 ///< MicroChip SAM E5x
#define OPT_MCU_SAMD11 204 ///< MicroChip SAMD11
#define OPT_MCU_SAML22 205 ///< MicroChip SAML22
#define OPT_MCU_SAML21 206 ///< MicroChip SAML21
#define OPT_MCU_SAMX7X 207 ///< MicroChip SAME70, S70, V70, V71 family
// STM32
#define OPT_MCU_STM32F0 300 ///< ST F0
#define OPT_MCU_STM32F1 301 ///< ST F1
#define OPT_MCU_STM32F2 302 ///< ST F2
#define OPT_MCU_STM32F3 303 ///< ST F3
#define OPT_MCU_STM32F4 304 ///< ST F4
#define OPT_MCU_STM32F7 305 ///< ST F7
#define OPT_MCU_STM32H7 306 ///< ST H7
#define OPT_MCU_STM32L1 308 ///< ST L1
#define OPT_MCU_STM32L0 307 ///< ST L0
#define OPT_MCU_STM32L4 309 ///< ST L4
#define OPT_MCU_STM32G0 310 ///< ST G0
#define OPT_MCU_STM32G4 311 ///< ST G4
#define OPT_MCU_STM32WB 312 ///< ST WB
// Sony
#define OPT_MCU_CXD56 400 ///< SONY CXD56
// TI
#define OPT_MCU_MSP430x5xx 500 ///< TI MSP430x5xx
#define OPT_MCU_MSP432E4 510 ///< TI MSP432E4xx
#define OPT_MCU_TM4C123 511 ///< TI Tiva-C 123x
#define OPT_MCU_TM4C129 512 ///< TI Tiva-C 129x
// ValentyUSB eptri
#define OPT_MCU_VALENTYUSB_EPTRI 600 ///< Fomu eptri config
// NXP iMX RT
#define OPT_MCU_MIMXRT10XX 700 ///< NXP iMX RT10xx
// Nuvoton
#define OPT_MCU_NUC121 800
#define OPT_MCU_NUC126 801
#define OPT_MCU_NUC120 802
#define OPT_MCU_NUC505 803
// Espressif
#define OPT_MCU_ESP32S2 900 ///< Espressif ESP32-S2
#define OPT_MCU_ESP32S3 901 ///< Espressif ESP32-S3
// Dialog
#define OPT_MCU_DA1469X 1000 ///< Dialog Semiconductor DA1469x
// Raspberry Pi
#define OPT_MCU_RP2040 1100 ///< Raspberry Pi RP2040
// NXP Kinetis
#define OPT_MCU_MKL25ZXX 1200 ///< NXP MKL25Zxx
#define OPT_MCU_K32L2BXX 1201 ///< NXP K32L2Bxx
// Silabs
#define OPT_MCU_EFM32GG 1300 ///< Silabs EFM32GG
// Renesas RX
#define OPT_MCU_RX63X 1400 ///< Renesas RX63N/631
#define OPT_MCU_RX65X 1401 ///< Renesas RX65N/RX651
#define OPT_MCU_RX72N 1402 ///< Renesas RX72N
// Mind Motion
#define OPT_MCU_MM32F327X 1500 ///< Mind Motion MM32F327
// GigaDevice
#define OPT_MCU_GD32VF103 1600 ///< GigaDevice GD32VF103
// Broadcom
#define OPT_MCU_BCM2711 1700 ///< Broadcom BCM2711
#define OPT_MCU_BCM2835 1701 ///< Broadcom BCM2835
#define OPT_MCU_BCM2837 1702 ///< Broadcom BCM2837
// Infineon
#define OPT_MCU_XMC4000 1800 ///< Infineon XMC4000
// PIC
#define OPT_MCU_PIC32MZ 1900 ///< MicroChip PIC32MZ family
// BridgeTek
#define OPT_MCU_FT90X 2000 ///< BridgeTek FT90x
#define OPT_MCU_FT93X 2001 ///< BridgeTek FT93x
// Allwinner
#define OPT_MCU_F1C100S 2100 ///< Allwinner F1C100s family
// Helper to check if configured MCU is one of listed
// Apply _TU_CHECK_MCU with || as separator to list of input
#define _TU_CHECK_MCU(_m) (CFG_TUSB_MCU == _m)
#define TU_CHECK_MCU(...) (TU_ARGS_APPLY(_TU_CHECK_MCU, ||, __VA_ARGS__))
//--------------------------------------------------------------------+
// Supported OS
//--------------------------------------------------------------------+
#define OPT_OS_NONE 1 ///< No RTOS
#define OPT_OS_FREERTOS 2 ///< FreeRTOS
#define OPT_OS_MYNEWT 3 ///< Mynewt OS
#define OPT_OS_CUSTOM 4 ///< Custom OS is implemented by application
#define OPT_OS_PICO 5 ///< Raspberry Pi Pico SDK
#define OPT_OS_RTTHREAD 6 ///< RT-Thread
#define OPT_OS_RTX4 7 ///< Keil RTX 4
// Allow to use command line to change the config name/location
#ifdef CFG_TUSB_CONFIG_FILE
#include CFG_TUSB_CONFIG_FILE
#else
#include "tusb_config.h"
#endif
#include "common/tusb_mcu.h"
//--------------------------------------------------------------------
// RootHub Mode Configuration
// CFG_TUSB_RHPORTx_MODE contains operation mode and speed for that port
//--------------------------------------------------------------------
// Low byte is operational mode
#define OPT_MODE_NONE 0x0000 ///< Disabled
#define OPT_MODE_DEVICE 0x0001 ///< Device Mode
#define OPT_MODE_HOST 0x0002 ///< Host Mode
// High byte is max operational speed (corresponding to tusb_speed_t)
#define OPT_MODE_DEFAULT_SPEED 0x0000 ///< Default (max) speed supported by MCU
#define OPT_MODE_LOW_SPEED 0x0100 ///< Low Speed
#define OPT_MODE_FULL_SPEED 0x0200 ///< Full Speed
#define OPT_MODE_HIGH_SPEED 0x0400 ///< High Speed
#define OPT_MODE_SPEED_MASK 0xff00
#ifndef CFG_TUSB_RHPORT0_MODE
#define CFG_TUSB_RHPORT0_MODE OPT_MODE_NONE
#endif
#ifndef CFG_TUSB_RHPORT1_MODE
#define CFG_TUSB_RHPORT1_MODE OPT_MODE_NONE
#endif
#if (((CFG_TUSB_RHPORT0_MODE) & OPT_MODE_HOST ) && ((CFG_TUSB_RHPORT1_MODE) & OPT_MODE_HOST )) || \
(((CFG_TUSB_RHPORT0_MODE) & OPT_MODE_DEVICE) && ((CFG_TUSB_RHPORT1_MODE) & OPT_MODE_DEVICE))
#error "TinyUSB currently does not support same modes on more than 1 roothub port"
#endif
//------------- Roothub as Device -------------//
#if (CFG_TUSB_RHPORT0_MODE) & OPT_MODE_DEVICE
#define TUD_RHPORT_MODE (CFG_TUSB_RHPORT0_MODE)
#define TUD_OPT_RHPORT 0
#elif (CFG_TUSB_RHPORT1_MODE) & OPT_MODE_DEVICE
#define TUD_RHPORT_MODE (CFG_TUSB_RHPORT1_MODE)
#define TUD_OPT_RHPORT 1
#else
#define TUD_RHPORT_MODE OPT_MODE_NONE
#define TUD_OPT_RHPORT -1
#endif
#define CFG_TUD_ENABLED (TUD_RHPORT_MODE & OPT_MODE_DEVICE)
#if CFG_TUD_ENABLED
#define TUD_OPT_HIGH_SPEED ((TUD_RHPORT_MODE & OPT_MODE_SPEED_MASK) ? (TUD_RHPORT_MODE & OPT_MODE_HIGH_SPEED) : (TUP_RHPORT_HIGHSPEED & (1 << TUD_OPT_RHPORT)))
#else
#define TUD_OPT_HIGH_SPEED 0
#endif
//------------- Roothub as Host -------------//
#if (CFG_TUSB_RHPORT0_MODE) & OPT_MODE_HOST
#define TUH_RHPORT_MODE (CFG_TUSB_RHPORT0_MODE)
#define TUH_OPT_RHPORT 0
#elif (CFG_TUSB_RHPORT1_MODE) & OPT_MODE_HOST
#define TUH_RHPORT_MODE (CFG_TUSB_RHPORT1_MODE)
#define TUH_OPT_RHPORT 1
#else
#define TUH_RHPORT_MODE OPT_MODE_NONE
#define TUH_OPT_RHPORT -1
#endif
#define CFG_TUH_ENABLED ( TUH_RHPORT_MODE & OPT_MODE_HOST )
// For backward compatible
#define TUSB_OPT_DEVICE_ENABLED CFG_TUD_ENABLED
#define TUSB_OPT_HOST_ENABLED CFG_TUH_ENABLED
// TODO move later
// TUP_MCU_STRICT_ALIGN will overwrite TUP_ARCH_STRICT_ALIGN.
// In case TUP_MCU_STRICT_ALIGN = 1 and TUP_ARCH_STRICT_ALIGN =0, we will not reply on compiler
// to generate unaligned access code.
// LPC_IP3511 Highspeed cannot access unaligned memory on USB_RAM
#if TUD_OPT_HIGH_SPEED && (CFG_TUSB_MCU == OPT_MCU_LPC54XXX || CFG_TUSB_MCU == OPT_MCU_LPC55XX)
#define TUP_MCU_STRICT_ALIGN 1
#else
#define TUP_MCU_STRICT_ALIGN 0
#endif
//--------------------------------------------------------------------+
// COMMON OPTIONS
//--------------------------------------------------------------------+
// Debug enable to print out error message
#ifndef CFG_TUSB_DEBUG
#define CFG_TUSB_DEBUG 0
#endif
// place data in accessible RAM for usb controller
#ifndef CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_SECTION
#endif
// alignment requirement of buffer used for endpoint transferring
#ifndef CFG_TUSB_MEM_ALIGN
#define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4)
#endif
// OS selection
#ifndef CFG_TUSB_OS
#define CFG_TUSB_OS OPT_OS_NONE
#endif
#ifndef CFG_TUSB_OS_INC_PATH
#define CFG_TUSB_OS_INC_PATH
#endif
// mutex is only needed for RTOS TODO also required with multiple core MCUs
#define TUSB_OPT_MUTEX (CFG_TUSB_OS != OPT_OS_NONE)
//--------------------------------------------------------------------
// DEVICE OPTIONS
//--------------------------------------------------------------------
#ifndef CFG_TUD_ENDPOINT0_SIZE
#define CFG_TUD_ENDPOINT0_SIZE 64
#endif
#ifndef CFG_TUD_CDC
#define CFG_TUD_CDC 0
#endif
#ifndef CFG_TUD_MSC
#define CFG_TUD_MSC 0
#endif
#ifndef CFG_TUD_HID
#define CFG_TUD_HID 0
#endif
#ifndef CFG_TUD_AUDIO
#define CFG_TUD_AUDIO 0
#endif
#ifndef CFG_TUD_VIDEO
#define CFG_TUD_VIDEO 0
#endif
#ifndef CFG_TUD_MIDI
#define CFG_TUD_MIDI 0
#endif
#ifndef CFG_TUD_VENDOR
#define CFG_TUD_VENDOR 0
#endif
#ifndef CFG_TUD_USBTMC
#define CFG_TUD_USBTMC 0
#endif
#ifndef CFG_TUD_DFU_RUNTIME
#define CFG_TUD_DFU_RUNTIME 0
#endif
#ifndef CFG_TUD_DFU
#define CFG_TUD_DFU 0
#endif
#ifndef CFG_TUD_BTH
#define CFG_TUD_BTH 0
#endif
#ifndef CFG_TUD_ECM_RNDIS
#ifdef CFG_TUD_NET
#warning "CFG_TUD_NET is renamed to CFG_TUD_ECM_RNDIS"
#define CFG_TUD_ECM_RNDIS CFG_TUD_NET
#else
#define CFG_TUD_ECM_RNDIS 0
#endif
#endif
#ifndef CFG_TUD_NCM
#define CFG_TUD_NCM 0
#endif
//--------------------------------------------------------------------
// HOST OPTIONS
//--------------------------------------------------------------------
#if CFG_TUH_ENABLED
#ifndef CFG_TUH_DEVICE_MAX
#define CFG_TUH_DEVICE_MAX 1
#endif
#ifndef CFG_TUH_ENUMERATION_BUFSIZE
#define CFG_TUH_ENUMERATION_BUFSIZE 256
#endif
#endif // CFG_TUH_ENABLED
//------------- CLASS -------------//
#ifndef CFG_TUH_HUB
#define CFG_TUH_HUB 0
#endif
#ifndef CFG_TUH_CDC
#define CFG_TUH_CDC 0
#endif
#ifndef CFG_TUH_HID
#define CFG_TUH_HID 0
#endif
#ifndef CFG_TUH_MIDI
#define CFG_TUH_MIDI 0
#endif
#ifndef CFG_TUH_MSC
#define CFG_TUH_MSC 0
#endif
#ifndef CFG_TUH_VENDOR
#define CFG_TUH_VENDOR 0
#endif
//------------------------------------------------------------------
// Configuration Validation
//------------------------------------------------------------------
#if CFG_TUD_ENDPOINT0_SIZE > 64
#error Control Endpoint Max Packet Size cannot be larger than 64
#endif
#endif /* _TUSB_OPTION_H_ */
/** @} */