1
0
Fork 0
mirror of https://github.com/betaflight/betaflight.git synced 2025-07-16 21:05:35 +03:00

PICO: Adding tinyUSB library

This commit is contained in:
blckmn 2025-01-12 07:56:01 +11:00
parent 1774693395
commit 0109f50909
1507 changed files with 299535 additions and 0 deletions

View file

@ -0,0 +1,960 @@
/*
* 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 = 0x80000000u,
} 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 = 0x80000000u,
} 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.
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_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.
uint8_t iChannelNames ; ///< Index of a string descriptor, describing the name of the first logical channel.
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]; \
}
// 6.1 Interrupt Data Message Format
typedef struct TU_ATTR_PACKED
{
uint8_t bInfo;
uint8_t bAttribute;
union
{
uint16_t wValue;
struct
{
uint8_t wValue_cn_or_mcn;
uint8_t wValue_cs;
};
};
union
{
uint16_t wIndex;
struct
{
uint8_t wIndex_ep_or_int;
uint8_t wIndex_entity_id;
};
};
} audio_interrupt_data_t;
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,723 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2020 Ha Thach (tinyusb.org)
* Copyright (c) 2020 Reinhard Panhuber
* Copyright (c) 2023 HiFiPhile
*
* 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
// (For TYPE-I format only) Flow control is necessary to allow IN ep send correct amount of data, unless it's a virtual device where data is perfectly synchronized to USB clock.
#ifndef CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL
#define CFG_TUD_AUDIO_EP_IN_FLOW_CONTROL 1
#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().
// Can be override by tud_audio_feedback_format_correction_cb()
#ifndef CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION
#define CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION 0 // 0 or 1
#endif
// Enable/disable interrupt EP (required for notifying host of control changes)
#ifndef CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP
#define CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP 0 // Feedback - 0 or 1
#endif
// Audio control interrupt EP - 6 Bytes according to UAC 2 specification (p. 74)
#define CFG_TUD_AUDIO_INTERRUPT_EP_SZ 6
// 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 / sample_sz) * sample_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_ENABLE_INTERRUPT_EP
bool tud_audio_int_n_write (uint8_t func_id, const audio_interrupt_data_t * data);
#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_ENABLE_INTERRUPT_EP
static inline bool tud_audio_int_write (const audio_interrupt_data_t * data);
#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
//--------------------------------------------------------------------+
#if CFG_TUD_AUDIO_ENABLE_EP_IN
bool tud_audio_tx_done_pre_load_cb(uint8_t rhport, uint8_t func_id, uint8_t ep_in, uint8_t cur_alt_setting);
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
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);
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
void tud_audio_fb_done_cb(uint8_t func_id);
// Note about feedback calculation
//
// Option 1 - AUDIO_FEEDBACK_METHOD_FIFO_COUNT
// Feedback value is calculated within the audio driver by regulating the FIFO level to half fill.
// Advantage: No ISR interrupt is enabled, hence the CPU need not to handle an ISR every 1ms or 125us and thus less CPU load, well tested
// (Windows, Linux, OSX) with a reliable result so far.
// Disadvantage: A FIFO of minimal 4 frames is needed to compensate for jitter, an average delay of 2 frames is introduced.
//
// Option 2 - AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED / AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT
// Feedback value is calculated within the audio driver by use of SOF interrupt. The driver needs information about the master clock f_m from
// which the audio sample frequency f_s is derived, f_s itself, and the cycle count of f_m at time of the SOF interrupt (e.g. by use of a hardware counter).
// See tud_audio_set_fb_params() and tud_audio_feedback_update()
// Advantage: Reduced jitter in the feedback value computation, hence, the receive FIFO can be smaller and thus a smaller delay is possible.
// Disadvantage: higher CPU load due to SOF ISR handling every frame i.e. 1ms or 125us. (The most critical point is the reading of the cycle counter value of f_m.
// It is read from within the SOF ISR - see: audiod_sof() -, hence, the ISR must has a high priority such that no software dependent "random" delay i.e. jitter is introduced).
// Long-term drift could occur since error is accumulated.
//
// Option 3 - manual
// Determined by the user itself and set by use of tud_audio_n_fb_set(). The feedback value may be determined e.g. from some fill status of some FIFO buffer.
// Advantage: No ISR interrupt is enabled, hence the CPU need not to handle an ISR every 1ms or 125us and thus less CPU load.
// Disadvantage: typically a larger FIFO is needed to compensate for jitter (e.g. 6 frames), i.e. a larger delay is introduced.
// 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 or tud_audio_feedback_format_correction_cb()
// return true, 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 it seems the
// driver can work with either format.
//
// Feedback value can be determined from within the SOF ISR of the audio driver. This should reduce jitter. If the feature is used, the user can not set the feedback value.
//
// Determine feedback value - The feedback method is described in 5.12.4.2 of the USB 2.0 spec
// Boiled down, the feedback value Ff = n_samples / (micro)frame.
// Since an accuracy of less than 1 Sample / second is desired, at least n_frames = ceil(2^K * f_s / f_m) frames need to be measured, where K = 10 for full speed and K = 13
// for high speed, f_s is the sampling frequency e.g. 48 kHz and f_m is the cpu clock frequency e.g. 100 MHz (or any other master clock whose clock count is available and locked to f_s)
// The update interval in the (4.10.2.1) Feedback Endpoint Descriptor must be less or equal to 2^(K - P), where P = min( ceil(log2(f_m / f_s)), K)
// feedback = n_cycles / n_frames * f_s / f_m in 16.16 format, where n_cycles are the number of main clock cycles within fb_n_frames
bool tud_audio_n_fb_set(uint8_t func_id, uint32_t feedback);
// Update feedback value with passed MCLK cycles since last time this update function is called.
// Typically called within tud_audio_sof_isr(). Required tud_audio_feedback_params_cb() is implemented
// This function will also call tud_audio_feedback_set()
// return feedback value in 16.16 for reference (0 for error)
// Example :
// binterval=3 (4ms); FS = 48kHz; MCLK = 12.288MHz
// In 4 SOF MCLK counted 49152 cycles
uint32_t tud_audio_feedback_update(uint8_t func_id, uint32_t cycles);
enum {
AUDIO_FEEDBACK_METHOD_DISABLED,
AUDIO_FEEDBACK_METHOD_FREQUENCY_FIXED,
AUDIO_FEEDBACK_METHOD_FREQUENCY_FLOAT,
AUDIO_FEEDBACK_METHOD_FREQUENCY_POWER_OF_2, // For driver internal use only
AUDIO_FEEDBACK_METHOD_FIFO_COUNT
};
typedef struct {
uint8_t method;
uint32_t sample_freq; // sample frequency in Hz
union {
struct {
uint32_t mclk_freq; // Main clock frequency in Hz i.e. master clock to which sample clock is based on
}frequency;
};
}audio_feedback_params_t;
// Invoked when needed to set feedback parameters
void tud_audio_feedback_params_cb(uint8_t func_id, uint8_t alt_itf, audio_feedback_params_t* feedback_param);
// Callback in ISR context, invoked periodically according to feedback endpoint bInterval.
// Could be used to compute and update feedback value, should be placed in RAM if possible
// frame_number : current SOF count
// interval_shift: number of bit shift i.e log2(interval) from Feedback endpoint descriptor
TU_ATTR_FAST_FUNC void tud_audio_feedback_interval_isr(uint8_t func_id, uint32_t frame_number, uint8_t interval_shift);
// (Full-Speed only) Callback to set feedback format correction is applied or not,
// default to CFG_TUD_AUDIO_ENABLE_FEEDBACK_FORMAT_CORRECTION if not implemented.
bool tud_audio_feedback_format_correction_cb(uint8_t func_id);
#endif // CFG_TUD_AUDIO_ENABLE_EP_OUT && CFG_TUD_AUDIO_ENABLE_FEEDBACK_EP
#if CFG_TUD_AUDIO_ENABLE_INTERRUPT_EP
void tud_audio_int_done_cb(uint8_t rhport);
#endif
// Invoked when audio set interface request received
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
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
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
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
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
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
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
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_ENABLE_INTERRUPT_EP
static inline bool tud_audio_int_write(const audio_interrupt_data_t * data)
{
return tud_audio_int_n_write(0, data);
}
#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);
bool audiod_deinit (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);
void audiod_sof_isr (uint8_t rhport, uint32_t frame_count);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_AUDIO_DEVICE_H_ */
/** @} */
/** @} */

View file

@ -0,0 +1,296 @@
/*
* 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.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_BTH)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "bth_device.h"
#include <device/usbd_pvt.h>
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t itf_num;
uint8_t ep_ev;
uint8_t ep_acl_in;
uint16_t ep_acl_in_pkt_sz;
uint8_t ep_acl_out;
uint8_t ep_voice[2]; // Not used yet
uint8_t ep_voice_size[2][CFG_TUD_BTH_ISO_ALT_COUNT];
// Previous amount of bytes sent when issuing ZLP
uint32_t prev_xferred_bytes;
} btd_interface_t;
typedef struct {
TUD_EPBUF_DEF(epout_buf, CFG_TUD_BTH_DATA_EPSIZE);
TUD_EPBUF_TYPE_DEF(bt_hci_cmd_t, hci_cmd);
} btd_epbuf_t;
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static btd_interface_t _btd_itf;
CFG_TUD_MEM_SECTION static btd_epbuf_t _btd_epbuf;
static bool bt_tx_data(uint8_t ep, void *data, uint16_t len)
{
uint8_t const rhport = 0;
// skip if previous transfer not complete
TU_VERIFY(!usbd_edpt_busy(rhport, ep));
TU_ASSERT(usbd_edpt_xfer(rhport, ep, data, len));
return true;
}
//--------------------------------------------------------------------+
// READ API
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// WRITE API
//--------------------------------------------------------------------+
bool tud_bt_event_send(void *event, uint16_t event_len)
{
return bt_tx_data(_btd_itf.ep_ev, event, event_len);
}
bool tud_bt_acl_data_send(void *event, uint16_t event_len)
{
return bt_tx_data(_btd_itf.ep_acl_in, event, event_len);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void btd_init(void) {
tu_memclr(&_btd_itf, sizeof(_btd_itf));
}
bool btd_deinit(void) {
return true;
}
void btd_reset(uint8_t rhport)
{
(void)rhport;
}
uint16_t btd_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_t max_len)
{
tusb_desc_endpoint_t const *desc_ep;
uint16_t drv_len = 0;
// Size of single alternative of ISO interface
const uint16_t iso_alt_itf_size = sizeof(tusb_desc_interface_t) + 2 * sizeof(tusb_desc_endpoint_t);
// Size of hci interface
const uint16_t hci_itf_size = sizeof(tusb_desc_interface_t) + 3 * sizeof(tusb_desc_endpoint_t);
// Ensure this is BT Primary Controller
TU_VERIFY(TUSB_CLASS_WIRELESS_CONTROLLER == itf_desc->bInterfaceClass &&
TUD_BT_APP_SUBCLASS == itf_desc->bInterfaceSubClass &&
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER == itf_desc->bInterfaceProtocol, 0);
TU_ASSERT(itf_desc->bNumEndpoints == 3 && max_len >= hci_itf_size);
_btd_itf.itf_num = itf_desc->bInterfaceNumber;
desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(itf_desc);
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType && TUSB_XFER_INTERRUPT == desc_ep->bmAttributes.xfer, 0);
TU_ASSERT(usbd_edpt_open(rhport, desc_ep), 0);
_btd_itf.ep_ev = desc_ep->bEndpointAddress;
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
// Open endpoint pair
TU_ASSERT(usbd_open_edpt_pair(rhport, (uint8_t const *)desc_ep, 2,
TUSB_XFER_BULK, &_btd_itf.ep_acl_out,
&_btd_itf.ep_acl_in),
0);
// Save acl in endpoint max packet size
tusb_desc_endpoint_t const *desc_ep_acl_in = desc_ep;
for (size_t p = 0; p < 2; p++) {
if (tu_edpt_dir(desc_ep_acl_in->bEndpointAddress) == TUSB_DIR_IN) {
_btd_itf.ep_acl_in_pkt_sz = tu_edpt_packet_size(desc_ep_acl_in);
break;
}
desc_ep_acl_in = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep_acl_in);
}
itf_desc = (tusb_desc_interface_t const *)tu_desc_next(tu_desc_next(desc_ep));
// Prepare for incoming data from host
TU_ASSERT(usbd_edpt_xfer(rhport, _btd_itf.ep_acl_out, _btd_epbuf.epout_buf, CFG_TUD_BTH_DATA_EPSIZE), 0);
drv_len = hci_itf_size;
// Ensure this is still BT Primary Controller
TU_ASSERT(TUSB_CLASS_WIRELESS_CONTROLLER == itf_desc->bInterfaceClass &&
TUD_BT_APP_SUBCLASS == itf_desc->bInterfaceSubClass &&
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER == itf_desc->bInterfaceProtocol, 0);
TU_ASSERT(itf_desc->bNumEndpoints == 2 && max_len >= iso_alt_itf_size + drv_len);
uint8_t dir;
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(itf_desc);
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT, 0);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
_btd_itf.ep_voice[dir] = desc_ep->bEndpointAddress;
// Store endpoint size for alternative
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
drv_len += iso_alt_itf_size;
for (int i = 1; i < CFG_TUD_BTH_ISO_ALT_COUNT && drv_len + iso_alt_itf_size <= max_len; ++i) {
// Make sure rest of alternatives matches
itf_desc = (tusb_desc_interface_t const *)tu_desc_next(desc_ep);
if (itf_desc->bDescriptorType != TUSB_DESC_INTERFACE ||
TUSB_CLASS_WIRELESS_CONTROLLER != itf_desc->bInterfaceClass ||
TUD_BT_APP_SUBCLASS != itf_desc->bInterfaceSubClass ||
TUD_BT_PROTOCOL_PRIMARY_CONTROLLER != itf_desc->bInterfaceProtocol)
{
// Not an Iso interface instance
break;
}
TU_ASSERT(itf_desc->bAlternateSetting < CFG_TUD_BTH_ISO_ALT_COUNT, 0);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(itf_desc);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
desc_ep = (tusb_desc_endpoint_t const *)tu_desc_next(desc_ep);
dir = tu_edpt_dir(desc_ep->bEndpointAddress);
// Verify that alternative endpoint are same as first ones
TU_ASSERT(desc_ep->bDescriptorType == TUSB_DESC_ENDPOINT &&
_btd_itf.ep_voice[dir] == desc_ep->bEndpointAddress, 0);
_btd_itf.ep_voice_size[dir][itf_desc->bAlternateSetting] = (uint8_t) tu_edpt_packet_size(desc_ep);
drv_len += iso_alt_itf_size;
}
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool btd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request)
{
(void)rhport;
if ( stage == CONTROL_STAGE_SETUP )
{
if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS &&
request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_DEVICE)
{
// HCI command packet addressing for single function Primary Controllers
// also compatible with historical mode if enabled
TU_VERIFY((request->bRequest == 0 && request->wValue == 0 && request->wIndex == 0) ||
(CFG_TUD_BTH_HISTORICAL_COMPATIBLE && request->bRequest == 0xe0));
}
else if (request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE)
{
if (request->bRequest == TUSB_REQ_SET_INTERFACE && _btd_itf.itf_num + 1 == request->wIndex)
{
// TODO: Set interface it would involve changing size of endpoint size
}
else
{
// HCI command packet for Primary Controller function in a composite device
TU_VERIFY(request->bRequest == 0 && request->wValue == 0 && request->wIndex == _btd_itf.itf_num);
}
}
else return false;
return tud_control_xfer(rhport, request, &_btd_epbuf.hci_cmd, sizeof(bt_hci_cmd_t));
}
else if ( stage == CONTROL_STAGE_DATA )
{
// Handle class request only
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
if (tud_bt_hci_cmd_cb) {
tud_bt_hci_cmd_cb(&_btd_epbuf.hci_cmd, tu_min16(request->wLength, sizeof(bt_hci_cmd_t)));
}
}
return true;
}
bool btd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result,
uint32_t xferred_bytes) {
// received new data from host
if (ep_addr == _btd_itf.ep_acl_out)
{
if (tud_bt_acl_data_received_cb) tud_bt_acl_data_received_cb(_btd_epbuf.epout_buf, xferred_bytes);
// prepare for next data
TU_ASSERT(usbd_edpt_xfer(rhport, _btd_itf.ep_acl_out, _btd_epbuf.epout_buf, CFG_TUD_BTH_DATA_EPSIZE));
}
else if (ep_addr == _btd_itf.ep_ev)
{
if (tud_bt_event_sent_cb) tud_bt_event_sent_cb((uint16_t)xferred_bytes);
}
else if (ep_addr == _btd_itf.ep_acl_in)
{
if ((result == XFER_RESULT_SUCCESS) && (xferred_bytes > 0) &&
((xferred_bytes & (_btd_itf.ep_acl_in_pkt_sz - 1)) == 0)) {
// Save number of transferred bytes
_btd_itf.prev_xferred_bytes = xferred_bytes;
// Send zero-length packet
tud_bt_acl_data_send(NULL, 0);
} else if (tud_bt_acl_data_sent_cb) {
if (xferred_bytes == 0) {
xferred_bytes = _btd_itf.prev_xferred_bytes;
_btd_itf.prev_xferred_bytes = 0;
}
tud_bt_acl_data_sent_cb((uint16_t)xferred_bytes);
}
}
return true;
}
#endif

View file

@ -0,0 +1,117 @@
/*
* 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
// Allow BTH class to work in historically compatibility mode where the bRequest is always 0xe0.
// See Bluetooth Core v5.3, Vol. 4, Part B, Section 2.2
#ifndef CFG_TUD_BTH_HISTORICAL_COMPATIBLE
#define CFG_TUD_BTH_HISTORICAL_COMPATIBLE 0
#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);
bool btd_deinit (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,424 @@
/*
* 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
* @{ */
//--------------------------------------------------------------------+
// 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;
typedef enum {
CDC_CONTROL_LINE_STATE_DTR = 0x01,
CDC_CONTROL_LINE_STATE_RTS = 0x02,
} cdc_control_line_state_t;
typedef enum {
CDC_LINE_CODING_STOP_BITS_1 = 0, // 1 bit
CDC_LINE_CODING_STOP_BITS_1_5 = 1, // 1.5 bits
CDC_LINE_CODING_STOP_BITS_2 = 2, // 2 bits
} cdc_line_coding_stopbits_t;
// TODO Backward compatible for typos. Maybe removed in the future release
#define CDC_LINE_CONDING_STOP_BITS_1 CDC_LINE_CODING_STOP_BITS_1
#define CDC_LINE_CONDING_STOP_BITS_1_5 CDC_LINE_CODING_STOP_BITS_1_5
#define CDC_LINE_CONDING_STOP_BITS_2 CDC_LINE_CODING_STOP_BITS_2
typedef enum {
CDC_LINE_CODING_PARITY_NONE = 0,
CDC_LINE_CODING_PARITY_ODD = 1,
CDC_LINE_CODING_PARITY_EVEN = 2,
CDC_LINE_CODING_PARITY_MARK = 3,
CDC_LINE_CODING_PARITY_SPACE = 4,
} cdc_line_coding_parity_t;
//--------------------------------------------------------------------+
// Management Element 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_RESERVED0 : 2;
uint32_t TU_RESERVED1 : 16;
uint32_t TU_RESERVED2 : 8;
} 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 dtr : 1;
uint16_t rts : 1;
uint16_t : 6;
uint16_t : 8;
} 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,510 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_CDC)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "cdc_device.h"
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUD_CDC_LOG_LEVEL
#define CFG_TUD_CDC_LOG_LEVEL CFG_TUD_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_CDC_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#define BULK_PACKET_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
typedef struct {
uint8_t itf_num;
uint8_t ep_notif;
uint8_t ep_in;
uint8_t ep_out;
// Bit 0: DTR (Data Terminal Ready), Bit 1: RTS (Request to Send)
uint8_t line_state;
/*------------- From this point, data is not cleared by bus reset -------------*/
char wanted_char;
TU_ATTR_ALIGNED(4) cdc_line_coding_t line_coding;
// FIFO
tu_fifo_t rx_ff;
tu_fifo_t tx_ff;
uint8_t rx_ff_buf[CFG_TUD_CDC_RX_BUFSIZE];
uint8_t tx_ff_buf[CFG_TUD_CDC_TX_BUFSIZE];
OSAL_MUTEX_DEF(rx_ff_mutex);
OSAL_MUTEX_DEF(tx_ff_mutex);
} cdcd_interface_t;
#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char)
typedef struct {
TUD_EPBUF_DEF(epout, CFG_TUD_CDC_EP_BUFSIZE);
TUD_EPBUF_DEF(epin, CFG_TUD_CDC_EP_BUFSIZE);
} cdcd_epbuf_t;
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC];
CFG_TUD_MEM_SECTION static cdcd_epbuf_t _cdcd_epbuf[CFG_TUD_CDC];
static tud_cdc_configure_fifo_t _cdcd_fifo_cfg;
static bool _prep_out_transaction(uint8_t itf) {
const uint8_t rhport = 0;
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
cdcd_epbuf_t* p_epbuf = &_cdcd_epbuf[itf];
// Skip if usb is not ready yet
TU_VERIFY(tud_ready() && p_cdc->ep_out);
uint16_t available = tu_fifo_remaining(&p_cdc->rx_ff);
// Prepare for incoming data but only allow what we can store in the ring buffer.
// TODO Actually we can still carry out the transfer, keeping count of received bytes
// and slowly move it to the FIFO when read().
// This pre-check reduces endpoint claiming
TU_VERIFY(available >= CFG_TUD_CDC_EP_BUFSIZE);
// claim endpoint
TU_VERIFY(usbd_edpt_claim(rhport, p_cdc->ep_out));
// fifo can be changed before endpoint is claimed
available = tu_fifo_remaining(&p_cdc->rx_ff);
if (available >= CFG_TUD_CDC_EP_BUFSIZE) {
return usbd_edpt_xfer(rhport, p_cdc->ep_out, p_epbuf->epout, CFG_TUD_CDC_EP_BUFSIZE);
} else {
// Release endpoint since we don't make any transfer
usbd_edpt_release(rhport, p_cdc->ep_out);
return false;
}
}
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
bool tud_cdc_configure_fifo(const tud_cdc_configure_fifo_t* cfg) {
TU_VERIFY(cfg);
_cdcd_fifo_cfg = (*cfg);
return true;
}
bool tud_cdc_n_ready(uint8_t itf) {
return tud_ready() && _cdcd_itf[itf].ep_in != 0 && _cdcd_itf[itf].ep_out != 0;
}
bool tud_cdc_n_connected(uint8_t itf) {
// DTR (bit 0) active is considered as connected
return tud_ready() && tu_bit_test(_cdcd_itf[itf].line_state, 0);
}
uint8_t tud_cdc_n_get_line_state(uint8_t itf) {
return _cdcd_itf[itf].line_state;
}
void tud_cdc_n_get_line_coding(uint8_t itf, cdc_line_coding_t* coding) {
(*coding) = _cdcd_itf[itf].line_coding;
}
void tud_cdc_n_set_wanted_char(uint8_t itf, char wanted) {
_cdcd_itf[itf].wanted_char = wanted;
}
//--------------------------------------------------------------------+
// READ API
//--------------------------------------------------------------------+
uint32_t tud_cdc_n_available(uint8_t itf) {
return tu_fifo_count(&_cdcd_itf[itf].rx_ff);
}
uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize) {
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
uint32_t num_read = tu_fifo_read_n(&p_cdc->rx_ff, buffer, (uint16_t) TU_MIN(bufsize, UINT16_MAX));
_prep_out_transaction(itf);
return num_read;
}
bool tud_cdc_n_peek(uint8_t itf, uint8_t* chr) {
return tu_fifo_peek(&_cdcd_itf[itf].rx_ff, chr);
}
void tud_cdc_n_read_flush(uint8_t itf) {
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
tu_fifo_clear(&p_cdc->rx_ff);
_prep_out_transaction(itf);
}
//--------------------------------------------------------------------+
// WRITE API
//--------------------------------------------------------------------+
uint32_t tud_cdc_n_write(uint8_t itf, const void* buffer, uint32_t bufsize) {
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
uint16_t ret = tu_fifo_write_n(&p_cdc->tx_ff, buffer, (uint16_t) TU_MIN(bufsize, UINT16_MAX));
// flush if queue more than packet size
if (tu_fifo_count(&p_cdc->tx_ff) >= BULK_PACKET_SIZE
#if CFG_TUD_CDC_TX_BUFSIZE < BULK_PACKET_SIZE
|| tu_fifo_full(&p_cdc->tx_ff) // check full if fifo size is less than packet size
#endif
) {
tud_cdc_n_write_flush(itf);
}
return ret;
}
uint32_t tud_cdc_n_write_flush(uint8_t itf) {
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
cdcd_epbuf_t* p_epbuf = &_cdcd_epbuf[itf];
// Skip if usb is not ready yet
TU_VERIFY(tud_ready(), 0);
// No data to send
if (!tu_fifo_count(&p_cdc->tx_ff)) {
return 0;
}
const uint8_t rhport = 0;
// Claim the endpoint
TU_VERIFY(usbd_edpt_claim(rhport, p_cdc->ep_in), 0);
// Pull data from FIFO
const uint16_t count = tu_fifo_read_n(&p_cdc->tx_ff, p_epbuf->epin, CFG_TUD_CDC_EP_BUFSIZE);
if (count) {
TU_ASSERT(usbd_edpt_xfer(rhport, p_cdc->ep_in, p_epbuf->epin, count), 0);
return count;
} else {
// Release endpoint since we don't make any transfer
// Note: data is dropped if terminal is not connected
usbd_edpt_release(rhport, p_cdc->ep_in);
return 0;
}
}
uint32_t tud_cdc_n_write_available(uint8_t itf) {
return tu_fifo_remaining(&_cdcd_itf[itf].tx_ff);
}
bool tud_cdc_n_write_clear(uint8_t itf) {
return tu_fifo_clear(&_cdcd_itf[itf].tx_ff);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void cdcd_init(void) {
tu_memclr(_cdcd_itf, sizeof(_cdcd_itf));
tu_memclr(&_cdcd_fifo_cfg, sizeof(_cdcd_fifo_cfg));
for (uint8_t i = 0; i < CFG_TUD_CDC; i++) {
cdcd_interface_t* p_cdc = &_cdcd_itf[i];
p_cdc->wanted_char = (char) -1;
// default line coding is : stop bit = 1, parity = none, data bits = 8
p_cdc->line_coding.bit_rate = 115200;
p_cdc->line_coding.stop_bits = 0;
p_cdc->line_coding.parity = 0;
p_cdc->line_coding.data_bits = 8;
// Config RX fifo
tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, TU_ARRAY_SIZE(p_cdc->rx_ff_buf), 1, false);
// Config TX fifo as overwritable at initialization and will be changed to non-overwritable
// if terminal supports DTR bit. Without DTR we do not know if data is actually polled by terminal.
// In this way, the most current data is prioritized.
tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, TU_ARRAY_SIZE(p_cdc->tx_ff_buf), 1, true);
#if OSAL_MUTEX_REQUIRED
osal_mutex_t mutex_rd = osal_mutex_create(&p_cdc->rx_ff_mutex);
osal_mutex_t mutex_wr = osal_mutex_create(&p_cdc->tx_ff_mutex);
TU_ASSERT(mutex_rd != NULL && mutex_wr != NULL, );
tu_fifo_config_mutex(&p_cdc->rx_ff, NULL, mutex_rd);
tu_fifo_config_mutex(&p_cdc->tx_ff, mutex_wr, NULL);
#endif
}
}
bool cdcd_deinit(void) {
#if OSAL_MUTEX_REQUIRED
for(uint8_t i=0; i<CFG_TUD_CDC; i++) {
cdcd_interface_t* p_cdc = &_cdcd_itf[i];
osal_mutex_t mutex_rd = p_cdc->rx_ff.mutex_rd;
osal_mutex_t mutex_wr = p_cdc->tx_ff.mutex_wr;
if (mutex_rd) {
osal_mutex_delete(mutex_rd);
tu_fifo_config_mutex(&p_cdc->rx_ff, NULL, NULL);
}
if (mutex_wr) {
osal_mutex_delete(mutex_wr);
tu_fifo_config_mutex(&p_cdc->tx_ff, NULL, NULL);
}
}
#endif
return true;
}
void cdcd_reset(uint8_t rhport) {
(void) rhport;
for (uint8_t i = 0; i < CFG_TUD_CDC; i++) {
cdcd_interface_t* p_cdc = &_cdcd_itf[i];
tu_memclr(p_cdc, ITF_MEM_RESET_SIZE);
if (!_cdcd_fifo_cfg.rx_persistent) {
tu_fifo_clear(&p_cdc->rx_ff);
}
if (!_cdcd_fifo_cfg.tx_persistent) {
tu_fifo_clear(&p_cdc->tx_ff);
}
tu_fifo_set_overwritable(&p_cdc->tx_ff, true);
}
}
uint16_t cdcd_open(uint8_t rhport, const tusb_desc_interface_t* itf_desc, uint16_t max_len) {
// Only support ACM subclass
TU_VERIFY( TUSB_CLASS_CDC == itf_desc->bInterfaceClass &&
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass, 0);
// Find available interface
cdcd_interface_t* p_cdc;
uint8_t cdc_id;
for (cdc_id = 0; cdc_id < CFG_TUD_CDC; cdc_id++) {
p_cdc = &_cdcd_itf[cdc_id];
if (p_cdc->ep_in == 0) {
break;
}
}
TU_ASSERT(cdc_id < CFG_TUD_CDC, 0);
//------------- Control Interface -------------//
p_cdc->itf_num = itf_desc->bInterfaceNumber;
uint16_t drv_len = sizeof(tusb_desc_interface_t);
const uint8_t* p_desc = tu_desc_next(itf_desc);
// Communication Functional Descriptors
while (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len) {
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
if (TUSB_DESC_ENDPOINT == tu_desc_type(p_desc)) {
// notification endpoint
const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc;
TU_ASSERT(usbd_edpt_open(rhport, desc_ep), 0);
p_cdc->ep_notif = desc_ep->bEndpointAddress;
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
//------------- Data Interface (if any) -------------//
if ((TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) &&
(TUSB_CLASS_CDC_DATA == ((const tusb_desc_interface_t*) p_desc)->bInterfaceClass)) {
// next to endpoint descriptor
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
// Open endpoint pair
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in), 0);
drv_len += 2 * sizeof(tusb_desc_endpoint_t);
}
// Prepare for incoming data
_prep_out_transaction(cdc_id);
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool cdcd_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
// Handle class request only
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
uint8_t itf;
cdcd_interface_t* p_cdc;
// Identify which interface to use
for (itf = 0; itf < CFG_TUD_CDC; itf++) {
p_cdc = &_cdcd_itf[itf];
if (p_cdc->itf_num == request->wIndex) {
break;
}
}
TU_VERIFY(itf < CFG_TUD_CDC);
switch (request->bRequest) {
case CDC_REQUEST_SET_LINE_CODING:
if (stage == CONTROL_STAGE_SETUP) {
TU_LOG_DRV(" Set Line Coding\r\n");
tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
} else if (stage == CONTROL_STAGE_ACK) {
if (tud_cdc_line_coding_cb) {
tud_cdc_line_coding_cb(itf, &p_cdc->line_coding);
}
}
break;
case CDC_REQUEST_GET_LINE_CODING:
if (stage == CONTROL_STAGE_SETUP) {
TU_LOG_DRV(" Get Line Coding\r\n");
tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
}
break;
case CDC_REQUEST_SET_CONTROL_LINE_STATE:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_status(rhport, request);
} else if (stage == CONTROL_STAGE_ACK) {
// CDC PSTN v1.2 section 6.3.12
// Bit 0: Indicates if DTE is present or not.
// This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR (Data Terminal Ready)
// Bit 1: Carrier control for half-duplex modems.
// This signal corresponds to V.24 signal 105 and RS-232 signal RTS (Request to Send)
bool const dtr = tu_bit_test(request->wValue, 0);
bool const rts = tu_bit_test(request->wValue, 1);
p_cdc->line_state = (uint8_t) request->wValue;
// Disable fifo overwriting if DTR bit is set
tu_fifo_set_overwritable(&p_cdc->tx_ff, !dtr);
TU_LOG_DRV(" Set Control Line State: DTR = %d, RTS = %d\r\n", dtr, rts);
// Invoke callback
if (tud_cdc_line_state_cb) {
tud_cdc_line_state_cb(itf, dtr, rts);
}
}
break;
case CDC_REQUEST_SEND_BREAK:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_status(rhport, request);
} else if (stage == CONTROL_STAGE_ACK) {
TU_LOG_DRV(" Send Break\r\n");
if (tud_cdc_send_break_cb) {
tud_cdc_send_break_cb(itf, request->wValue);
}
}
break;
default:
return false; // stall unsupported request
}
return true;
}
bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void) result;
uint8_t itf;
cdcd_interface_t* p_cdc;
// Identify which interface to use
for (itf = 0; itf < CFG_TUD_CDC; itf++) {
p_cdc = &_cdcd_itf[itf];
if ((ep_addr == p_cdc->ep_out) || (ep_addr == p_cdc->ep_in)) {
break;
}
}
TU_ASSERT(itf < CFG_TUD_CDC);
cdcd_epbuf_t* p_epbuf = &_cdcd_epbuf[itf];
// Received new data
if (ep_addr == p_cdc->ep_out) {
tu_fifo_write_n(&p_cdc->rx_ff, p_epbuf->epout, (uint16_t) xferred_bytes);
// Check for wanted char and invoke callback if needed
if (tud_cdc_rx_wanted_cb && (((signed char) p_cdc->wanted_char) != -1)) {
for (uint32_t i = 0; i < xferred_bytes; i++) {
if ((p_cdc->wanted_char == p_epbuf->epout[i]) && !tu_fifo_empty(&p_cdc->rx_ff)) {
tud_cdc_rx_wanted_cb(itf, p_cdc->wanted_char);
}
}
}
// invoke receive callback (if there is still data)
if (tud_cdc_rx_cb && !tu_fifo_empty(&p_cdc->rx_ff)) {
tud_cdc_rx_cb(itf);
}
// prepare for OUT transaction
_prep_out_transaction(itf);
}
// Data sent to host, we continue to fetch from tx fifo to send.
// Note: This will cause incorrect baudrate set in line coding.
// Though maybe the baudrate is not really important !!!
if (ep_addr == p_cdc->ep_in) {
// invoke transmit callback to possibly refill tx fifo
if (tud_cdc_tx_complete_cb) {
tud_cdc_tx_complete_cb(itf);
}
if (0 == tud_cdc_n_write_flush(itf)) {
// If there is no data left, a ZLP should be sent if
// xferred_bytes is multiple of EP Packet size and not zero
if (!tu_fifo_count(&p_cdc->tx_ff) && xferred_bytes && (0 == (xferred_bytes & (BULK_PACKET_SIZE - 1)))) {
if (usbd_edpt_claim(rhport, p_cdc->ep_in)) {
usbd_edpt_xfer(rhport, p_cdc->ep_in, NULL, 0);
}
}
}
}
// nothing to do with notif endpoint for now
return true;
}
#endif

View file

@ -0,0 +1,226 @@
/*
* 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 "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
//--------------------------------------------------------------------+
// Driver Configuration
//--------------------------------------------------------------------+
typedef struct TU_ATTR_PACKED {
uint8_t rx_persistent : 1; // keep rx fifo on bus reset or disconnect
uint8_t tx_persistent : 1; // keep tx fifo on bus reset or disconnect
} tud_cdc_configure_fifo_t;
// Configure CDC FIFOs behavior
bool tud_cdc_configure_fifo(tud_cdc_configure_fifo_t const* cfg);
//--------------------------------------------------------------------+
// Application API (Multiple Ports) i.e. CFG_TUD_CDC > 1
//--------------------------------------------------------------------+
// Check if interface is ready
bool tud_cdc_n_ready(uint8_t itf);
// 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
TU_ATTR_ALWAYS_INLINE 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;
}
// Clear the received FIFO
void tud_cdc_n_read_flush(uint8_t itf);
// Get a byte from FIFO 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
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_n_write_char(uint8_t itf, char ch) {
return tud_cdc_n_write(itf, &ch, 1);
}
// Write a null-terminated string
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_n_write_str(uint8_t itf, char const* str) {
return tud_cdc_n_write(itf, str, strlen(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)
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline bool tud_cdc_ready(void) {
return tud_cdc_n_ready(0);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_cdc_connected(void) {
return tud_cdc_n_connected(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t tud_cdc_get_line_state(void) {
return tud_cdc_n_get_line_state(0);
}
TU_ATTR_ALWAYS_INLINE static inline void tud_cdc_get_line_coding(cdc_line_coding_t* coding) {
tud_cdc_n_get_line_coding(0, coding);
}
TU_ATTR_ALWAYS_INLINE static inline void tud_cdc_set_wanted_char(char wanted) {
tud_cdc_n_set_wanted_char(0, wanted);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_available(void) {
return tud_cdc_n_available(0);
}
TU_ATTR_ALWAYS_INLINE static inline int32_t tud_cdc_read_char(void) {
return tud_cdc_n_read_char(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_read(void* buffer, uint32_t bufsize) {
return tud_cdc_n_read(0, buffer, bufsize);
}
TU_ATTR_ALWAYS_INLINE static inline void tud_cdc_read_flush(void) {
tud_cdc_n_read_flush(0);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_cdc_peek(uint8_t* ui8) {
return tud_cdc_n_peek(0, ui8);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_write_char(char ch) {
return tud_cdc_n_write_char(0, ch);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_write(void const* buffer, uint32_t bufsize) {
return tud_cdc_n_write(0, buffer, bufsize);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_write_str(char const* str) {
return tud_cdc_n_write_str(0, str);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_write_flush(void) {
return tud_cdc_n_write_flush(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_cdc_write_available(void) {
return tud_cdc_n_write_available(0);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_cdc_write_clear(void) {
return tud_cdc_n_write_clear(0);
}
//--------------------------------------------------------------------+
// 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 a TX is complete and therefore 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
// \param[in] itf interface for which send break was received.
// \param[in] duration_ms the length of time, in milliseconds, of the break signal. If a value of FFFFh, then the
// device will send a break until another SendBreak request is received with value 0000h.
TU_ATTR_WEAK void tud_cdc_send_break_cb(uint8_t itf, uint16_t duration_ms);
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void cdcd_init (void);
bool cdcd_deinit (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_ */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,205 @@
/*
* 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
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
// Set Line Control state on enumeration/mounted: DTR ( bit 0), RTS (bit 1)
#ifndef CFG_TUH_CDC_LINE_CONTROL_ON_ENUM
#define CFG_TUH_CDC_LINE_CONTROL_ON_ENUM 0
#endif
// Set Line Coding on enumeration/mounted, value for cdc_line_coding_t
//#ifndef CFG_TUH_CDC_LINE_CODING_ON_ENUM
//#define CFG_TUH_CDC_LINE_CODING_ON_ENUM { 115200, CDC_LINE_CODING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 }
//#endif
// RX FIFO size
#ifndef CFG_TUH_CDC_RX_BUFSIZE
#define CFG_TUH_CDC_RX_BUFSIZE USBH_EPSIZE_BULK_MAX
#endif
// RX Endpoint size
#ifndef CFG_TUH_CDC_RX_EPSIZE
#define CFG_TUH_CDC_RX_EPSIZE USBH_EPSIZE_BULK_MAX
#endif
// TX FIFO size
#ifndef CFG_TUH_CDC_TX_BUFSIZE
#define CFG_TUH_CDC_TX_BUFSIZE USBH_EPSIZE_BULK_MAX
#endif
// TX Endpoint size
#ifndef CFG_TUH_CDC_TX_EPSIZE
#define CFG_TUH_CDC_TX_EPSIZE USBH_EPSIZE_BULK_MAX
#endif
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Get Interface index from device address + interface number
// return TUSB_INDEX_INVALID_8 (0xFF) if not found
uint8_t tuh_cdc_itf_get_index(uint8_t daddr, uint8_t itf_num);
// Get Interface information
// return true if index is correct and interface is currently mounted
bool tuh_cdc_itf_get_info(uint8_t idx, tuh_itf_info_t* info);
// Check if a interface is mounted
bool tuh_cdc_mounted(uint8_t idx);
// Get current DTR status
bool tuh_cdc_get_dtr(uint8_t idx);
// Get current RTS status
bool tuh_cdc_get_rts(uint8_t idx);
// Check if interface is connected (DTR active)
TU_ATTR_ALWAYS_INLINE static inline bool tuh_cdc_connected(uint8_t idx) {
return tuh_cdc_get_dtr(idx);
}
// Get local (saved/cached) version of line coding.
// This function should return correct values if tuh_cdc_set_line_coding() / tuh_cdc_get_line_coding()
// are invoked previously or CFG_TUH_CDC_LINE_CODING_ON_ENUM is defined.
// NOTE: This function does not make any USB transfer request to device.
bool tuh_cdc_get_local_line_coding(uint8_t idx, cdc_line_coding_t* line_coding);
//--------------------------------------------------------------------+
// Write API
//--------------------------------------------------------------------+
// Get the number of bytes available for writing
uint32_t tuh_cdc_write_available(uint8_t idx);
// Write to cdc interface
uint32_t tuh_cdc_write(uint8_t idx, void const* buffer, uint32_t bufsize);
// Force sending data if possible, return number of forced bytes
uint32_t tuh_cdc_write_flush(uint8_t idx);
// Clear the transmit FIFO
bool tuh_cdc_write_clear(uint8_t idx);
//--------------------------------------------------------------------+
// Read API
//--------------------------------------------------------------------+
// Get the number of bytes available for reading
uint32_t tuh_cdc_read_available(uint8_t idx);
// Read from cdc interface
uint32_t tuh_cdc_read (uint8_t idx, void* buffer, uint32_t bufsize);
// Get a byte from RX FIFO without removing it
bool tuh_cdc_peek(uint8_t idx, uint8_t* ch);
// Clear the received FIFO
bool tuh_cdc_read_clear (uint8_t idx);
//--------------------------------------------------------------------+
// Control Endpoint (Request) API
// Each Function will make a USB control transfer request to/from device
// - If complete_cb is provided, the function will return immediately and invoke
// the callback when request is complete.
// - If complete_cb is NULL, the function will block until request is complete.
// - In this case, user_data should be pointed to xfer_result_t to hold the transfer result.
// - The function will return true if transfer is successful, false otherwise.
//--------------------------------------------------------------------+
// Request to Set Control Line State: DTR (bit 0), RTS (bit 1)
bool tuh_cdc_set_control_line_state(uint8_t idx, uint16_t line_state, tuh_xfer_cb_t complete_cb, uintptr_t user_data);
// Request to set baudrate
bool tuh_cdc_set_baudrate(uint8_t idx, uint32_t baudrate, tuh_xfer_cb_t complete_cb, uintptr_t user_data);
// Request to set data format
bool tuh_cdc_set_data_format(uint8_t idx, uint8_t stop_bits, uint8_t parity, uint8_t data_bits, tuh_xfer_cb_t complete_cb, uintptr_t user_data);
// Request to Set Line Coding = baudrate + data format
// Note: only implemented by ACM and CH34x, not supported by FTDI and CP210x yet
bool tuh_cdc_set_line_coding(uint8_t idx, cdc_line_coding_t const* line_coding, tuh_xfer_cb_t complete_cb, uintptr_t user_data);
// Request to Get Line Coding (ACM only)
// Should only use if tuh_cdc_set_line_coding() / tuh_cdc_get_line_coding() never got invoked and
// CFG_TUH_CDC_LINE_CODING_ON_ENUM is not defined
// bool tuh_cdc_get_line_coding(uint8_t idx, cdc_line_coding_t* coding);
// Connect by set both DTR, RTS
TU_ATTR_ALWAYS_INLINE static inline
bool tuh_cdc_connect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
return tuh_cdc_set_control_line_state(idx, CDC_CONTROL_LINE_STATE_DTR | CDC_CONTROL_LINE_STATE_RTS, complete_cb, user_data);
}
// Disconnect by clear both DTR, RTS
TU_ATTR_ALWAYS_INLINE static inline
bool tuh_cdc_disconnect(uint8_t idx, tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
return tuh_cdc_set_control_line_state(idx, 0x00, complete_cb, user_data);
}
//--------------------------------------------------------------------+
// CDC APPLICATION CALLBACKS
//--------------------------------------------------------------------+
// Invoked when a device with CDC interface is mounted
// idx is index of cdc interface in the internal pool.
TU_ATTR_WEAK extern void tuh_cdc_mount_cb(uint8_t idx);
// Invoked when a device with CDC interface is unmounted
TU_ATTR_WEAK extern void tuh_cdc_umount_cb(uint8_t idx);
// Invoked when received new data
TU_ATTR_WEAK extern void tuh_cdc_rx_cb(uint8_t idx);
// Invoked when a TX is complete and therefore space becomes available in TX buffer
TU_ATTR_WEAK extern void tuh_cdc_tx_complete_cb(uint8_t idx);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
bool cdch_init (void);
bool cdch_deinit (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,289 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUH_ENABLED && CFG_TUH_CDC && CFG_TUH_CDC_RNDIS)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "common/tusb_common.h"
#include "cdc_host.h"
#include "cdc_rndis_host.h"
#if 0 // TODO remove subtask related macros later
// Sub Task
#define OSAL_SUBTASK_BEGIN
#define OSAL_SUBTASK_END return TUSB_ERROR_NONE;
#define STASK_RETURN(_error) return _error;
#define STASK_INVOKE(_subtask, _status) (_status) = _subtask
#define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED)
#endif
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#define RNDIS_MSG_PAYLOAD_MAX (1024*4)
CFG_TUH_MEM_SECTION static uint8_t msg_notification[CFG_TUH_DEVICE_MAX][8];
CFG_TUH_MEM_SECTION CFG_TUH_MEM_ALIGN static uint8_t msg_payload[RNDIS_MSG_PAYLOAD_MAX];
static rndish_data_t rndish_data[CFG_TUH_DEVICE_MAX];
// TODO Microsoft requires message length for any get command must be at least 4096 bytes
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static tusb_error_t rndis_body_subtask(void);
static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc,
uint8_t * p_mess, uint32_t mess_length,
uint8_t *p_response );
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
tusb_error_t tusbh_cdc_rndis_get_mac_addr(uint8_t dev_addr, uint8_t mac_address[6])
{
TU_ASSERT( tusbh_cdc_rndis_is_mounted(dev_addr), TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED);
TU_VERIFY( mac_address, TUSB_ERROR_INVALID_PARA);
memcpy(mac_address, rndish_data[dev_addr-1].mac_address, 6);
return TUSB_ERROR_NONE;
}
//--------------------------------------------------------------------+
// IMPLEMENTATION
//--------------------------------------------------------------------+
// To enable the TASK_ASSERT style (quick return on false condition) in a real RTOS, a task must act as a wrapper
// and is used mainly to call subtasks. Within a subtask return statement can be called freely, the task with
// forever loop cannot have any return at all.
OSAL_TASK_FUNCTION(cdch_rndis_task) (void* param;)
{
OSAL_TASK_BEGIN
rndis_body_subtask();
OSAL_TASK_END
}
static tusb_error_t rndis_body_subtask(void)
{
static uint8_t relative_addr;
OSAL_SUBTASK_BEGIN
for (relative_addr = 0; relative_addr < CFG_TUH_DEVICE_MAX; relative_addr++)
{
}
osal_task_delay(100);
OSAL_SUBTASK_END
}
//--------------------------------------------------------------------+
// RNDIS-CDC Driver API
//--------------------------------------------------------------------+
void rndish_init(void)
{
tu_memclr(rndish_data, sizeof(rndish_data_t)*CFG_TUH_DEVICE_MAX);
//------------- Task creation -------------//
//------------- semaphore creation for notification pipe -------------//
for(uint8_t i=0; i<CFG_TUH_DEVICE_MAX; i++)
{
rndish_data[i].sem_notification_hdl = osal_semaphore_create( OSAL_SEM_REF(rndish_data[i].semaphore_notification) );
}
}
void rndish_close(uint8_t dev_addr)
{
osal_semaphore_reset( rndish_data[dev_addr-1].sem_notification_hdl );
// tu_memclr(&rndish_data[dev_addr-1], sizeof(rndish_data_t)); TODO need to move semaphore & its handle out before memclr
}
static rndis_msg_initialize_t const msg_init =
{
.type = RNDIS_MSG_INITIALIZE,
.length = sizeof(rndis_msg_initialize_t),
.request_id = 1, // TODO should use some magic number
.major_version = 1,
.minor_version = 0,
.max_xfer_size = 0x4000 // TODO mimic windows
};
static rndis_msg_query_t const msg_query_permanent_addr =
{
.type = RNDIS_MSG_QUERY,
.length = sizeof(rndis_msg_query_t)+6,
.request_id = 1,
.oid = RNDIS_OID_802_3_PERMANENT_ADDRESS,
.buffer_length = 6,
.buffer_offset = 20,
};
static rndis_msg_set_t const msg_set_packet_filter =
{
.type = RNDIS_MSG_SET,
.length = sizeof(rndis_msg_set_t)+4,
.request_id = 1,
.oid = RNDIS_OID_GEN_CURRENT_PACKET_FILTER,
.buffer_length = 4,
.buffer_offset = 20,
};
tusb_error_t rndish_open_subtask(uint8_t dev_addr, cdch_data_t *p_cdc)
{
tusb_error_t error;
OSAL_SUBTASK_BEGIN
//------------- Message Initialize -------------//
memcpy(msg_payload, &msg_init, sizeof(rndis_msg_initialize_t));
STASK_INVOKE(
send_message_get_response_subtask( dev_addr, p_cdc,
msg_payload, sizeof(rndis_msg_initialize_t),
msg_payload),
error
);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
// TODO currently not support multiple data packets per xfer
rndis_msg_initialize_cmplt_t * const p_init_cmpt = (rndis_msg_initialize_cmplt_t *) msg_payload;
STASK_ASSERT(p_init_cmpt->type == RNDIS_MSG_INITIALIZE_CMPLT && p_init_cmpt->status == RNDIS_STATUS_SUCCESS &&
p_init_cmpt->max_packet_per_xfer == 1 && p_init_cmpt->max_xfer_size <= RNDIS_MSG_PAYLOAD_MAX);
rndish_data[dev_addr-1].max_xfer_size = p_init_cmpt->max_xfer_size;
//------------- Message Query 802.3 Permanent Address -------------//
memcpy(msg_payload, &msg_query_permanent_addr, sizeof(rndis_msg_query_t));
tu_memclr(msg_payload + sizeof(rndis_msg_query_t), 6); // 6 bytes for MAC address
STASK_INVOKE(
send_message_get_response_subtask( dev_addr, p_cdc,
msg_payload, sizeof(rndis_msg_query_t) + 6,
msg_payload),
error
);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
rndis_msg_query_cmplt_t * const p_query_cmpt = (rndis_msg_query_cmplt_t *) msg_payload;
STASK_ASSERT(p_query_cmpt->type == RNDIS_MSG_QUERY_CMPLT && p_query_cmpt->status == RNDIS_STATUS_SUCCESS);
memcpy(rndish_data[dev_addr-1].mac_address, msg_payload + 8 + p_query_cmpt->buffer_offset, 6);
//------------- Set OID_GEN_CURRENT_PACKET_FILTER to (DIRECTED | MULTICAST | BROADCAST) -------------//
memcpy(msg_payload, &msg_set_packet_filter, sizeof(rndis_msg_set_t));
tu_memclr(msg_payload + sizeof(rndis_msg_set_t), 4); // 4 bytes for filter flags
((rndis_msg_set_t*) msg_payload)->oid_buffer[0] = (RNDIS_PACKET_TYPE_DIRECTED | RNDIS_PACKET_TYPE_MULTICAST | RNDIS_PACKET_TYPE_BROADCAST);
STASK_INVOKE(
send_message_get_response_subtask( dev_addr, p_cdc,
msg_payload, sizeof(rndis_msg_set_t) + 4,
msg_payload),
error
);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
rndis_msg_set_cmplt_t * const p_set_cmpt = (rndis_msg_set_cmplt_t *) msg_payload;
STASK_ASSERT(p_set_cmpt->type == RNDIS_MSG_SET_CMPLT && p_set_cmpt->status == RNDIS_STATUS_SUCCESS);
tusbh_cdc_rndis_mounted_cb(dev_addr);
OSAL_SUBTASK_END
}
void rndish_xfer_isr(cdch_data_t *p_cdc, pipe_handle_t pipe_hdl, xfer_result_t event, uint32_t xferred_bytes)
{
if ( pipehandle_is_equal(pipe_hdl, p_cdc->pipe_notification) )
{
osal_semaphore_post( rndish_data[pipe_hdl.dev_addr-1].sem_notification_hdl );
}
}
//--------------------------------------------------------------------+
// INTERNAL & HELPER
//--------------------------------------------------------------------+
static tusb_error_t send_message_get_response_subtask( uint8_t dev_addr, cdch_data_t *p_cdc,
uint8_t * p_mess, uint32_t mess_length,
uint8_t *p_response)
{
tusb_error_t error;
OSAL_SUBTASK_BEGIN
//------------- Send RNDIS Control Message -------------//
STASK_INVOKE(
usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_OUT, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE),
CDC_REQUEST_SEND_ENCAPSULATED_COMMAND, 0, p_cdc->interface_number,
mess_length, p_mess),
error
);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
//------------- waiting for Response Available notification -------------//
(void) usbh_edpt_xfer(p_cdc->pipe_notification, msg_notification[dev_addr-1], 8);
osal_semaphore_wait(rndish_data[dev_addr-1].sem_notification_hdl, OSAL_TIMEOUT_NORMAL, &error);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
STASK_ASSERT(msg_notification[dev_addr-1][0] == 1);
//------------- Get RNDIS Message Initialize Complete -------------//
STASK_INVOKE(
usbh_control_xfer_subtask( dev_addr, bm_request_type(TUSB_DIR_IN, TUSB_REQ_TYPE_CLASS, TUSB_REQ_RCPT_INTERFACE),
CDC_REQUEST_GET_ENCAPSULATED_RESPONSE, 0, p_cdc->interface_number,
RNDIS_MSG_PAYLOAD_MAX, p_response),
error
);
if ( TUSB_ERROR_NONE != error ) STASK_RETURN(error);
OSAL_SUBTASK_END
}
//static tusb_error_t send_process_msg_initialize_subtask(uint8_t dev_addr, cdch_data_t *p_cdc)
//{
// tusb_error_t error;
//
// OSAL_SUBTASK_BEGIN
//
// *((rndis_msg_initialize_t*) msg_payload) = (rndis_msg_initialize_t)
// {
// .type = RNDIS_MSG_INITIALIZE,
// .length = sizeof(rndis_msg_initialize_t),
// .request_id = 1, // TODO should use some magic number
// .major_version = 1,
// .minor_version = 0,
// .max_xfer_size = 0x4000 // TODO mimic windows
// };
//
//
//
// OSAL_SUBTASK_END
//}
#endif

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,84 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Heiko Kuester
*
* 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 _CH34X_H_
#define _CH34X_H_
// There is no official documentation for the CH34x (CH340, CH341) chips. Reference can be found
// - https://github.com/WCHSoftGroup/ch341ser_linux
// - https://github.com/torvalds/linux/blob/master/drivers/usb/serial/ch341.c
// - https://github.com/freebsd/freebsd-src/blob/main/sys/dev/usb/serial/uchcom.c
// set line_coding @ enumeration
#ifdef CFG_TUH_CDC_LINE_CODING_ON_ENUM
#define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X CFG_TUH_CDC_LINE_CODING_ON_ENUM
#else // this default is necessary to work properly
#define CFG_TUH_CDC_LINE_CODING_ON_ENUM_CH34X { 9600, CDC_LINE_CONDING_STOP_BITS_1, CDC_LINE_CODING_PARITY_NONE, 8 }
#endif
// USB requests
#define CH34X_REQ_READ_VERSION 0x5F // dec 95
#define CH34X_REQ_WRITE_REG 0x9A // dec 154
#define CH34X_REQ_READ_REG 0x95 // dec 149
#define CH34X_REQ_SERIAL_INIT 0xA1 // dec 161
#define CH34X_REQ_MODEM_CTRL 0xA4 // dev 164
// registers
#define CH34X_REG_BREAK 0x05
#define CH34X_REG_PRESCALER 0x12
#define CH34X_REG_DIVISOR 0x13
#define CH34X_REG_LCR 0x18
#define CH34X_REG_LCR2 0x25
#define CH34X_REG_MCR_MSR 0x06
#define CH34X_REG_MCR_MSR2 0x07
#define CH34X_NBREAK_BITS 0x01
#define CH341_REG_0x0F 0x0F // undocumented register
#define CH341_REG_0x2C 0x2C // undocumented register
#define CH341_REG_0x27 0x27 // hardware flow control (cts/rts)
#define CH34X_REG16_DIVISOR_PRESCALER TU_U16(CH34X_REG_DIVISOR, CH34X_REG_PRESCALER)
#define CH32X_REG16_LCR2_LCR TU_U16(CH34X_REG_LCR2, CH34X_REG_LCR)
// modem control bits
#define CH34X_BIT_RTS ( 1 << 6 )
#define CH34X_BIT_DTR ( 1 << 5 )
// line control bits
#define CH34X_LCR_ENABLE_RX 0x80
#define CH34X_LCR_ENABLE_TX 0x40
#define CH34X_LCR_MARK_SPACE 0x20
#define CH34X_LCR_PAR_EVEN 0x10
#define CH34X_LCR_ENABLE_PAR 0x08
#define CH34X_LCR_PAR_MASK 0x38 // all parity bits
#define CH34X_LCR_STOP_BITS_2 0x04
#define CH34X_LCR_CS8 0x03
#define CH34X_LCR_CS7 0x02
#define CH34X_LCR_CS6 0x01
#define CH34X_LCR_CS5 0x00
#define CH34X_LCR_CS_MASK 0x03 // all CSx bits
#endif /* _CH34X_H_ */

View file

@ -0,0 +1,62 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Ha Thach (thach@tinyusb.org) for Adafruit Industries
*
* 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.
*/
#ifndef TUSB_CP210X_H
#define TUSB_CP210X_H
// Protocol details can be found at AN571: CP210x Virtual COM Port Interface
// https://www.silabs.com/documents/public/application-notes/AN571.pdf
#define TU_CP210X_VID 0x10C4
/* Config request codes */
#define CP210X_IFC_ENABLE 0x00
#define CP210X_SET_BAUDDIV 0x01
#define CP210X_GET_BAUDDIV 0x02
#define CP210X_SET_LINE_CTL 0x03 // Set parity, data bits, stop bits
#define CP210X_GET_LINE_CTL 0x04
#define CP210X_SET_BREAK 0x05
#define CP210X_IMM_CHAR 0x06
#define CP210X_SET_MHS 0x07 // Set DTR, RTS
#define CP210X_GET_MDMSTS 0x08 // Get modem status (DTR, RTS, CTS, DSR, RI, DCD)
#define CP210X_SET_XON 0x09
#define CP210X_SET_XOFF 0x0A
#define CP210X_SET_EVENTMASK 0x0B
#define CP210X_GET_EVENTMASK 0x0C
#define CP210X_SET_CHAR 0x0D
#define CP210X_GET_CHARS 0x0E
#define CP210X_GET_PROPS 0x0F
#define CP210X_GET_COMM_STATUS 0x10
#define CP210X_RESET 0x11
#define CP210X_PURGE 0x12
#define CP210X_SET_FLOW 0x13
#define CP210X_GET_FLOW 0x14
#define CP210X_EMBED_EVENTS 0x15
#define CP210X_GET_EVENTSTATE 0x16
#define CP210X_SET_CHARS 0x19
#define CP210X_GET_BAUDRATE 0x1D
#define CP210X_SET_BAUDRATE 0x1E
#define CP210X_VENDOR_SPECIFIC 0xFF // GPIO, Recipient must be Device
#endif //TUSB_CP210X_H

View file

@ -0,0 +1,246 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2023 Ha Thach (thach@tinyusb.org) for Adafruit Industries
*
* 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.
*/
#ifndef TUSB_FTDI_SIO_H
#define TUSB_FTDI_SIO_H
// VID for matching FTDI devices
#define TU_FTDI_VID 0x0403
// Commands
#define FTDI_SIO_RESET 0 /* Reset the port */
#define FTDI_SIO_MODEM_CTRL 1 /* Set the modem control register */
#define FTDI_SIO_SET_FLOW_CTRL 2 /* Set flow control register */
#define FTDI_SIO_SET_BAUD_RATE 3 /* Set baud rate */
#define FTDI_SIO_SET_DATA 4 /* Set the data characteristics of the port */
#define FTDI_SIO_GET_MODEM_STATUS 5 /* Retrieve current value of modem status register */
#define FTDI_SIO_SET_EVENT_CHAR 6 /* Set the event character */
#define FTDI_SIO_SET_ERROR_CHAR 7 /* Set the error character */
#define FTDI_SIO_SET_LATENCY_TIMER 9 /* Set the latency timer */
#define FTDI_SIO_GET_LATENCY_TIMER 0x0a /* Get the latency timer */
#define FTDI_SIO_SET_BITMODE 0x0b /* Set bitbang mode */
#define FTDI_SIO_READ_PINS 0x0c /* Read immediate value of pins */
#define FTDI_SIO_READ_EEPROM 0x90 /* Read EEPROM */
/* FTDI_SIO_RESET */
#define FTDI_SIO_RESET_SIO 0
#define FTDI_SIO_RESET_PURGE_RX 1
#define FTDI_SIO_RESET_PURGE_TX 2
/*
* BmRequestType: 0100 0000B
* bRequest: FTDI_SIO_RESET
* wValue: Control Value
* 0 = Reset SIO
* 1 = Purge RX buffer
* 2 = Purge TX buffer
* wIndex: Port
* wLength: 0
* Data: None
*
* The Reset SIO command has this effect:
*
* Sets flow control set to 'none'
* Event char = $0D
* Event trigger = disabled
* Purge RX buffer
* Purge TX buffer
* Clear DTR
* Clear RTS
* baud and data format not reset
*
* The Purge RX and TX buffer commands affect nothing except the buffers
*
*/
/* FTDI_SIO_MODEM_CTRL */
/*
* BmRequestType: 0100 0000B
* bRequest: FTDI_SIO_MODEM_CTRL
* wValue: ControlValue (see below)
* wIndex: Port
* wLength: 0
* Data: None
*
* NOTE: If the device is in RTS/CTS flow control, the RTS set by this
* command will be IGNORED without an error being returned
* Also - you can not set DTR and RTS with one control message
*/
#define FTDI_SIO_SET_DTR_MASK 0x1
#define FTDI_SIO_SET_DTR_HIGH ((FTDI_SIO_SET_DTR_MASK << 8) | 1)
#define FTDI_SIO_SET_DTR_LOW ((FTDI_SIO_SET_DTR_MASK << 8) | 0)
#define FTDI_SIO_SET_RTS_MASK 0x2
#define FTDI_SIO_SET_RTS_HIGH ((FTDI_SIO_SET_RTS_MASK << 8) | 2)
#define FTDI_SIO_SET_RTS_LOW ((FTDI_SIO_SET_RTS_MASK << 8) | 0)
/*
* ControlValue
* B0 DTR state
* 0 = reset
* 1 = set
* B1 RTS state
* 0 = reset
* 1 = set
* B2..7 Reserved
* B8 DTR state enable
* 0 = ignore
* 1 = use DTR state
* B9 RTS state enable
* 0 = ignore
* 1 = use RTS state
* B10..15 Reserved
*/
/* FTDI_SIO_SET_FLOW_CTRL */
#define FTDI_SIO_DISABLE_FLOW_CTRL 0x0
#define FTDI_SIO_RTS_CTS_HS (0x1 << 8)
#define FTDI_SIO_DTR_DSR_HS (0x2 << 8)
#define FTDI_SIO_XON_XOFF_HS (0x4 << 8)
/*
* BmRequestType: 0100 0000b
* bRequest: FTDI_SIO_SET_FLOW_CTRL
* wValue: Xoff/Xon
* wIndex: Protocol/Port - hIndex is protocol / lIndex is port
* wLength: 0
* Data: None
*
* hIndex protocol is:
* B0 Output handshaking using RTS/CTS
* 0 = disabled
* 1 = enabled
* B1 Output handshaking using DTR/DSR
* 0 = disabled
* 1 = enabled
* B2 Xon/Xoff handshaking
* 0 = disabled
* 1 = enabled
*
* A value of zero in the hIndex field disables handshaking
*
* If Xon/Xoff handshaking is specified, the hValue field should contain the
* XOFF character and the lValue field contains the XON character.
*/
/* FTDI_SIO_SET_BAUD_RATE */
/*
* BmRequestType: 0100 0000B
* bRequest: FTDI_SIO_SET_BAUDRATE
* wValue: BaudDivisor value - see below
* wIndex: Port
* wLength: 0
* Data: None
* The BaudDivisor values are calculated as follows (too complicated):
*/
/* FTDI_SIO_SET_DATA */
#define FTDI_SIO_SET_DATA_PARITY_NONE (0x0 << 8)
#define FTDI_SIO_SET_DATA_PARITY_ODD (0x1 << 8)
#define FTDI_SIO_SET_DATA_PARITY_EVEN (0x2 << 8)
#define FTDI_SIO_SET_DATA_PARITY_MARK (0x3 << 8)
#define FTDI_SIO_SET_DATA_PARITY_SPACE (0x4 << 8)
#define FTDI_SIO_SET_DATA_STOP_BITS_1 (0x0 << 11)
#define FTDI_SIO_SET_DATA_STOP_BITS_15 (0x1 << 11)
#define FTDI_SIO_SET_DATA_STOP_BITS_2 (0x2 << 11)
#define FTDI_SIO_SET_BREAK (0x1 << 14)
/*
* BmRequestType: 0100 0000B
* bRequest: FTDI_SIO_SET_DATA
* wValue: Data characteristics (see below)
* wIndex: Port
* wLength: 0
* Data: No
*
* Data characteristics
*
* B0..7 Number of data bits
* B8..10 Parity
* 0 = None
* 1 = Odd
* 2 = Even
* 3 = Mark
* 4 = Space
* B11..13 Stop Bits
* 0 = 1
* 1 = 1.5
* 2 = 2
* B14
* 1 = TX ON (break)
* 0 = TX OFF (normal state)
* B15 Reserved
*
*/
/*
* DATA FORMAT
*
* IN Endpoint
*
* The device reserves the first two bytes of data on this endpoint to contain
* the current values of the modem and line status registers. In the absence of
* data, the device generates a message consisting of these two status bytes
* every 40 ms
*
* Byte 0: Modem Status
*
* Offset Description
* B0 Reserved - must be 1
* B1 Reserved - must be 0
* B2 Reserved - must be 0
* B3 Reserved - must be 0
* B4 Clear to Send (CTS)
* B5 Data Set Ready (DSR)
* B6 Ring Indicator (RI)
* B7 Receive Line Signal Detect (RLSD)
*
* Byte 1: Line Status
*
* Offset Description
* B0 Data Ready (DR)
* B1 Overrun Error (OE)
* B2 Parity Error (PE)
* B3 Framing Error (FE)
* B4 Break Interrupt (BI)
* B5 Transmitter Holding Register (THRE)
* B6 Transmitter Empty (TEMT)
* B7 Error in RCVR FIFO
*
*/
#define FTDI_RS0_CTS (1 << 4)
#define FTDI_RS0_DSR (1 << 5)
#define FTDI_RS0_RI (1 << 6)
#define FTDI_RS0_RLSD (1 << 7)
#define FTDI_RS_DR 1
#define FTDI_RS_OE (1<<1)
#define FTDI_RS_PE (1<<2)
#define FTDI_RS_FE (1<<3)
#define FTDI_RS_BI (1<<4)
#define FTDI_RS_THRE (1<<5)
#define FTDI_RS_TEMT (1<<6)
#define FTDI_RS_FIFO (1<<7)
#endif //TUSB_FTDI_SIO_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,417 @@
/*
* 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.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_DFU)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "dfu_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUD_DFU_LOG_LEVEL
#define CFG_TUD_DFU_LOG_LEVEL CFG_TUD_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_DFU_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
typedef struct {
uint8_t attrs;
uint8_t alt;
dfu_state_t state;
dfu_status_t status;
bool flashing_in_progress;
uint16_t block;
uint16_t length;
} dfu_state_ctx_t;
// Only a single dfu state is allowed
static dfu_state_ctx_t _dfu_ctx;
CFG_TUD_MEM_SECTION static struct {
TUD_EPBUF_DEF(transfer_buf, CFG_TUD_DFU_XFER_BUFSIZE);
} _dfu_epbuf;
static void reset_state(void) {
_dfu_ctx.state = DFU_IDLE;
_dfu_ctx.status = DFU_STATUS_OK;
_dfu_ctx.flashing_in_progress = false;
}
static bool reply_getstatus(uint8_t rhport, const tusb_control_request_t* request, dfu_state_t state, dfu_status_t status, uint32_t timeout);
static bool process_download_get_status(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request);
static bool process_manifest_get_status(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request);
//--------------------------------------------------------------------+
// Debug
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG >= 2
tu_static tu_lookup_entry_t const _dfu_request_lookup[] = {
{ .key = DFU_REQUEST_DETACH , .data = "DETACH" },
{ .key = DFU_REQUEST_DNLOAD , .data = "DNLOAD" },
{ .key = DFU_REQUEST_UPLOAD , .data = "UPLOAD" },
{ .key = DFU_REQUEST_GETSTATUS, .data = "GETSTATUS" },
{ .key = DFU_REQUEST_CLRSTATUS, .data = "CLRSTATUS" },
{ .key = DFU_REQUEST_GETSTATE , .data = "GETSTATE" },
{ .key = DFU_REQUEST_ABORT , .data = "ABORT" },
};
tu_static tu_lookup_table_t const _dfu_request_table = {
.count = TU_ARRAY_SIZE(_dfu_request_lookup),
.items = _dfu_request_lookup
};
tu_static tu_lookup_entry_t const _dfu_state_lookup[] = {
{ .key = APP_IDLE , .data = "APP_IDLE" },
{ .key = APP_DETACH , .data = "APP_DETACH" },
{ .key = DFU_IDLE , .data = "IDLE" },
{ .key = DFU_DNLOAD_SYNC , .data = "DNLOAD_SYNC" },
{ .key = DFU_DNBUSY , .data = "DNBUSY" },
{ .key = DFU_DNLOAD_IDLE , .data = "DNLOAD_IDLE" },
{ .key = DFU_MANIFEST_SYNC , .data = "MANIFEST_SYNC" },
{ .key = DFU_MANIFEST , .data = "MANIFEST" },
{ .key = DFU_MANIFEST_WAIT_RESET, .data = "MANIFEST_WAIT_RESET" },
{ .key = DFU_UPLOAD_IDLE , .data = "UPLOAD_IDLE" },
{ .key = DFU_ERROR , .data = "ERROR" },
};
tu_static tu_lookup_table_t const _dfu_state_table = {
.count = TU_ARRAY_SIZE(_dfu_state_lookup),
.items = _dfu_state_lookup
};
tu_static tu_lookup_entry_t const _dfu_status_lookup[] = {
{ .key = DFU_STATUS_OK , .data = "OK" },
{ .key = DFU_STATUS_ERR_TARGET , .data = "errTARGET" },
{ .key = DFU_STATUS_ERR_FILE , .data = "errFILE" },
{ .key = DFU_STATUS_ERR_WRITE , .data = "errWRITE" },
{ .key = DFU_STATUS_ERR_ERASE , .data = "errERASE" },
{ .key = DFU_STATUS_ERR_CHECK_ERASED , .data = "errCHECK_ERASED" },
{ .key = DFU_STATUS_ERR_PROG , .data = "errPROG" },
{ .key = DFU_STATUS_ERR_VERIFY , .data = "errVERIFY" },
{ .key = DFU_STATUS_ERR_ADDRESS , .data = "errADDRESS" },
{ .key = DFU_STATUS_ERR_NOTDONE , .data = "errNOTDONE" },
{ .key = DFU_STATUS_ERR_FIRMWARE , .data = "errFIRMWARE" },
{ .key = DFU_STATUS_ERR_VENDOR , .data = "errVENDOR" },
{ .key = DFU_STATUS_ERR_USBR , .data = "errUSBR" },
{ .key = DFU_STATUS_ERR_POR , .data = "errPOR" },
{ .key = DFU_STATUS_ERR_UNKNOWN , .data = "errUNKNOWN" },
{ .key = DFU_STATUS_ERR_STALLEDPKT , .data = "errSTALLEDPKT" },
};
tu_static tu_lookup_table_t const _dfu_status_table = {
.count = TU_ARRAY_SIZE(_dfu_status_lookup),
.items = _dfu_status_lookup
};
#endif
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void dfu_moded_reset(uint8_t rhport) {
(void) rhport;
_dfu_ctx.attrs = 0;
_dfu_ctx.alt = 0;
reset_state();
}
void dfu_moded_init(void) {
dfu_moded_reset(0);
}
bool dfu_moded_deinit(void) {
return true;
}
uint16_t dfu_moded_open(uint8_t rhport, const tusb_desc_interface_t* itf_desc, uint16_t max_len) {
(void) rhport;
//------------- Interface (with Alt) descriptor -------------//
const uint8_t itf_num = itf_desc->bInterfaceNumber;
uint8_t alt_count = 0;
uint16_t drv_len = 0;
TU_VERIFY(itf_desc->bInterfaceSubClass == TUD_DFU_APP_SUBCLASS && itf_desc->bInterfaceProtocol == DFU_PROTOCOL_DFU, 0);
while(itf_desc->bInterfaceSubClass == TUD_DFU_APP_SUBCLASS && itf_desc->bInterfaceProtocol == DFU_PROTOCOL_DFU) {
TU_ASSERT(max_len > drv_len, 0);
// Alternate must have the same interface number
TU_ASSERT(itf_desc->bInterfaceNumber == itf_num, 0);
// Alt should increase by one every time
TU_ASSERT(itf_desc->bAlternateSetting == alt_count, 0);
alt_count++;
drv_len += tu_desc_len(itf_desc);
itf_desc = (const tusb_desc_interface_t*) tu_desc_next(itf_desc);
}
//------------- DFU Functional descriptor -------------//
const tusb_desc_dfu_functional_t*func_desc = (const tusb_desc_dfu_functional_t*) itf_desc;
TU_ASSERT(tu_desc_type(func_desc) == TUSB_DESC_FUNCTIONAL, 0);
drv_len += sizeof(tusb_desc_dfu_functional_t);
_dfu_ctx.attrs = func_desc->bAttributes;
// CFG_TUD_DFU_XFER_BUFSIZE has to be set to the buffer size used in TUD_DFU_DESCRIPTOR
const uint16_t transfer_size = tu_le16toh( tu_unaligned_read16((const uint8_t*) func_desc + offsetof(tusb_desc_dfu_functional_t, wTransferSize)) );
TU_ASSERT(transfer_size <= CFG_TUD_DFU_XFER_BUFSIZE, drv_len);
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool dfu_moded_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE);
TU_LOG_DRV(" DFU State : %s, Status: %s\r\n", tu_lookup_find(&_dfu_state_table, _dfu_ctx.state), tu_lookup_find(&_dfu_status_table, _dfu_ctx.status));
if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) {
// Standard request include GET/SET_INTERFACE
switch (request->bRequest) {
case TUSB_REQ_SET_INTERFACE:
if (stage == CONTROL_STAGE_SETUP) {
// Switch Alt interface and reset state machine
_dfu_ctx.alt = (uint8_t)request->wValue;
reset_state();
return tud_control_status(rhport, request);
}
break;
case TUSB_REQ_GET_INTERFACE:
if (stage == CONTROL_STAGE_SETUP) {
return tud_control_xfer(rhport, request, &_dfu_ctx.alt, 1);
}
break;
// unsupported request
default: return false;
}
} else if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) {
TU_LOG_DRV(" DFU Request: %s\r\n", tu_lookup_find(&_dfu_request_table, request->bRequest));
// Class request
switch (request->bRequest) {
case DFU_REQUEST_DETACH:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_status(rhport, request);
} else if (stage == CONTROL_STAGE_ACK) {
if (tud_dfu_detach_cb) {
tud_dfu_detach_cb();
}
}
break;
case DFU_REQUEST_CLRSTATUS:
if (stage == CONTROL_STAGE_SETUP) {
reset_state();
tud_control_status(rhport, request);
}
break;
case DFU_REQUEST_GETSTATE:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_xfer(rhport, request, &_dfu_ctx.state, 1);
}
break;
case DFU_REQUEST_ABORT:
if (stage == CONTROL_STAGE_SETUP) {
reset_state();
tud_control_status(rhport, request);
} else if (stage == CONTROL_STAGE_ACK) {
if (tud_dfu_abort_cb) {
tud_dfu_abort_cb(_dfu_ctx.alt);
}
}
break;
case DFU_REQUEST_UPLOAD:
if (stage == CONTROL_STAGE_SETUP) {
TU_VERIFY(_dfu_ctx.attrs & DFU_ATTR_CAN_UPLOAD);
TU_VERIFY(tud_dfu_upload_cb);
TU_VERIFY(request->wLength <= CFG_TUD_DFU_XFER_BUFSIZE);
const uint16_t xfer_len = tud_dfu_upload_cb(_dfu_ctx.alt, request->wValue, _dfu_epbuf.transfer_buf,
request->wLength);
return tud_control_xfer(rhport, request, _dfu_epbuf.transfer_buf, xfer_len);
}
break;
case DFU_REQUEST_DNLOAD:
if (stage == CONTROL_STAGE_SETUP) {
TU_VERIFY(_dfu_ctx.attrs & DFU_ATTR_CAN_DOWNLOAD);
TU_VERIFY(_dfu_ctx.state == DFU_IDLE || _dfu_ctx.state == DFU_DNLOAD_IDLE);
TU_VERIFY(request->wLength <= CFG_TUD_DFU_XFER_BUFSIZE);
// set to true for both download and manifest
_dfu_ctx.flashing_in_progress = true;
// save block and length for flashing
_dfu_ctx.block = request->wValue;
_dfu_ctx.length = request->wLength;
if (request->wLength) {
// Download with payload -> transition to DOWNLOAD SYNC
_dfu_ctx.state = DFU_DNLOAD_SYNC;
return tud_control_xfer(rhport, request, _dfu_epbuf.transfer_buf, request->wLength);
} else {
// Download is complete -> transition to MANIFEST SYNC
_dfu_ctx.state = DFU_MANIFEST_SYNC;
return tud_control_status(rhport, request);
}
}
break;
case DFU_REQUEST_GETSTATUS:
switch (_dfu_ctx.state) {
case DFU_DNLOAD_SYNC:
return process_download_get_status(rhport, stage, request);
break;
case DFU_MANIFEST_SYNC:
return process_manifest_get_status(rhport, stage, request);
break;
default:
if (stage == CONTROL_STAGE_SETUP) {
return reply_getstatus(rhport, request, _dfu_ctx.state, _dfu_ctx.status, 0);
}
break;
}
break;
default: return false; // stall unsupported request
}
} else {
return false; // unsupported request
}
return true;
}
void tud_dfu_finish_flashing(uint8_t status) {
_dfu_ctx.flashing_in_progress = false;
if (status == DFU_STATUS_OK) {
if (_dfu_ctx.state == DFU_DNBUSY) {
_dfu_ctx.state = DFU_DNLOAD_SYNC;
} else if (_dfu_ctx.state == DFU_MANIFEST) {
_dfu_ctx.state = (_dfu_ctx.attrs & DFU_ATTR_MANIFESTATION_TOLERANT)
? DFU_MANIFEST_SYNC
: DFU_MANIFEST_WAIT_RESET;
}
} else {
// failed while flashing, move to dfuError
_dfu_ctx.state = DFU_ERROR;
_dfu_ctx.status = (dfu_status_t)status;
}
}
static bool process_download_get_status(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
if (stage == CONTROL_STAGE_SETUP) {
// only transition to next state on CONTROL_STAGE_ACK
dfu_state_t next_state;
uint32_t timeout;
if (_dfu_ctx.flashing_in_progress) {
next_state = DFU_DNBUSY;
timeout = tud_dfu_get_timeout_cb(_dfu_ctx.alt, (uint8_t)next_state);
} else {
next_state = DFU_DNLOAD_IDLE;
timeout = 0;
}
return reply_getstatus(rhport, request, next_state, _dfu_ctx.status, timeout);
} else if (stage == CONTROL_STAGE_ACK) {
if (_dfu_ctx.flashing_in_progress) {
_dfu_ctx.state = DFU_DNBUSY;
tud_dfu_download_cb(_dfu_ctx.alt, _dfu_ctx.block, _dfu_epbuf.transfer_buf, _dfu_ctx.length);
} else {
_dfu_ctx.state = DFU_DNLOAD_IDLE;
}
}
return true;
}
static bool process_manifest_get_status(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
if (stage == CONTROL_STAGE_SETUP) {
// only transition to next state on CONTROL_STAGE_ACK
dfu_state_t next_state;
uint32_t timeout;
if (_dfu_ctx.flashing_in_progress) {
next_state = DFU_MANIFEST;
timeout = tud_dfu_get_timeout_cb(_dfu_ctx.alt, next_state);
} else {
next_state = DFU_IDLE;
timeout = 0;
}
return reply_getstatus(rhport, request, next_state, _dfu_ctx.status, timeout);
} else if (stage == CONTROL_STAGE_ACK) {
if (_dfu_ctx.flashing_in_progress) {
_dfu_ctx.state = DFU_MANIFEST;
tud_dfu_manifest_cb(_dfu_ctx.alt);
} else {
_dfu_ctx.state = DFU_IDLE;
}
}
return true;
}
static bool reply_getstatus(uint8_t rhport, const tusb_control_request_t* request, dfu_state_t state,
dfu_status_t status, uint32_t timeout) {
dfu_status_response_t resp;
resp.bStatus = (uint8_t)status;
resp.bwPollTimeout[0] = TU_U32_BYTE0(timeout);
resp.bwPollTimeout[1] = TU_U32_BYTE1(timeout);
resp.bwPollTimeout[2] = TU_U32_BYTE2(timeout);
resp.bState = (uint8_t)state;
resp.iString = 0;
return tud_control_xfer(rhport, request, &resp, sizeof(dfu_status_response_t));
}
#endif

View file

@ -0,0 +1,99 @@
/*
* 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);
bool dfu_moded_deinit(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,137 @@
/*
* 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.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_DFU_RUNTIME)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "dfu_rt_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUD_DFU_RUNTIME_LOG_LEVEL
#define CFG_TUD_DFU_RUNTIME_LOG_LEVEL CFG_TUD_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_DFU_RUNTIME_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void dfu_rtd_init(void) {
}
bool dfu_rtd_deinit(void) {
return true;
}
void dfu_rtd_reset(uint8_t rhport) {
(void) rhport;
}
uint16_t dfu_rtd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len)
{
(void) rhport;
(void) max_len;
// Ensure this is DFU Runtime
TU_VERIFY((itf_desc->bInterfaceSubClass == TUD_DFU_APP_SUBCLASS) &&
(itf_desc->bInterfaceProtocol == DFU_PROTOCOL_RT), 0);
uint8_t const * p_desc = tu_desc_next( itf_desc );
uint16_t drv_len = sizeof(tusb_desc_interface_t);
if ( TUSB_DESC_FUNCTIONAL == tu_desc_type(p_desc) )
{
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool dfu_rtd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
// nothing to do with DATA or ACK stage
if ( stage != CONTROL_STAGE_SETUP ) return true;
TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE);
// dfu-util will try to claim the interface with SET_INTERFACE request before sending DFU request
if ( TUSB_REQ_TYPE_STANDARD == request->bmRequestType_bit.type &&
TUSB_REQ_SET_INTERFACE == request->bRequest )
{
tud_control_status(rhport, request);
return true;
}
// Handle class request only from here
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
switch (request->bRequest)
{
case DFU_REQUEST_DETACH:
{
TU_LOG_DRV(" DFU RT Request: DETACH\r\n");
tud_control_status(rhport, request);
tud_dfu_runtime_reboot_to_dfu_cb();
}
break;
case DFU_REQUEST_GETSTATUS:
{
TU_LOG_DRV(" DFU RT Request: GETSTATUS\r\n");
dfu_status_response_t resp;
// Status = OK, Poll timeout is ignored during RT, State = APP_IDLE, IString = 0
TU_VERIFY(tu_memset_s(&resp, sizeof(resp), 0x00, sizeof(resp))==0);
tud_control_xfer(rhport, request, &resp, sizeof(dfu_status_response_t));
}
break;
default:
{
TU_LOG_DRV(" DFU RT Unexpected Request: %d\r\n", request->bRequest);
return false; // stall unsupported request
}
}
return true;
}
#endif

View file

@ -0,0 +1,55 @@
/*
* 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);
bool dfu_rtd_deinit(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,412 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_HID)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "hid_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out; // optional Out endpoint
uint8_t itf_protocol; // Boot mouse or keyboard
uint16_t report_desc_len;
uint8_t protocol_mode; // Boot (0) or Report protocol (1)
uint8_t idle_rate; // up to application to handle idle rate
// TODO save hid descriptor since host can specifically request this after enumeration
// Note: HID descriptor may be not available from application after enumeration
const tusb_hid_descriptor_hid_t*hid_descriptor;
} hidd_interface_t;
typedef struct {
TUD_EPBUF_DEF(ctrl , CFG_TUD_HID_EP_BUFSIZE);
TUD_EPBUF_DEF(epin , CFG_TUD_HID_EP_BUFSIZE);
TUD_EPBUF_DEF(epout, CFG_TUD_HID_EP_BUFSIZE);
} hidd_epbuf_t;
static hidd_interface_t _hidd_itf[CFG_TUD_HID];
CFG_TUD_MEM_SECTION static hidd_epbuf_t _hidd_epbuf[CFG_TUD_HID];
/*------------- Helpers -------------*/
TU_ATTR_ALWAYS_INLINE static inline uint8_t get_index_by_itfnum(uint8_t itf_num) {
for (uint8_t i = 0; i < CFG_TUD_HID; i++) {
if (itf_num == _hidd_itf[i].itf_num) {
return i;
}
}
return 0xFF;
}
//--------------------------------------------------------------------+
// Weak stubs: invoked if no strong implementation is available
//--------------------------------------------------------------------+
TU_ATTR_WEAK void tud_hid_set_protocol_cb(uint8_t instance, uint8_t protocol) {
(void) instance;
(void) protocol;
}
TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t instance, uint8_t idle_rate) {
(void) instance;
(void) idle_rate;
return true;
}
TU_ATTR_WEAK void tud_hid_report_complete_cb(uint8_t instance, uint8_t const* report, uint16_t len) {
(void) instance;
(void) report;
(void) len;
}
// Invoked when a transfer wasn't successful
TU_ATTR_WEAK void tud_hid_report_failed_cb(uint8_t instance, hid_report_type_t report_type, uint8_t const* report, uint16_t xferred_bytes) {
(void) instance;
(void) report_type;
(void) report;
(void) xferred_bytes;
}
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
bool tud_hid_n_ready(uint8_t instance) {
uint8_t const rhport = 0;
uint8_t const ep_in = _hidd_itf[instance].ep_in;
return tud_ready() && (ep_in != 0) && !usbd_edpt_busy(rhport, ep_in);
}
bool tud_hid_n_report(uint8_t instance, uint8_t report_id, void const *report, uint16_t len) {
TU_VERIFY(instance < CFG_TUD_HID);
const uint8_t rhport = 0;
hidd_interface_t *p_hid = &_hidd_itf[instance];
hidd_epbuf_t *p_epbuf = &_hidd_epbuf[instance];
// claim endpoint
TU_VERIFY(usbd_edpt_claim(rhport, p_hid->ep_in));
// prepare data
if (report_id) {
p_epbuf->epin[0] = report_id;
TU_VERIFY(0 == tu_memcpy_s(p_epbuf->epin + 1, CFG_TUD_HID_EP_BUFSIZE - 1, report, len));
len++;
} else {
TU_VERIFY(0 == tu_memcpy_s(p_epbuf->epin, CFG_TUD_HID_EP_BUFSIZE, report, len));
}
return usbd_edpt_xfer(rhport, p_hid->ep_in, p_epbuf->epin, len);
}
uint8_t tud_hid_n_interface_protocol(uint8_t instance) {
return _hidd_itf[instance].itf_protocol;
}
uint8_t tud_hid_n_get_protocol(uint8_t instance) {
return _hidd_itf[instance].protocol_mode;
}
bool tud_hid_n_keyboard_report(uint8_t instance, uint8_t report_id, uint8_t modifier, const uint8_t keycode[6]) {
hid_keyboard_report_t report;
report.modifier = modifier;
report.reserved = 0;
if (keycode) {
memcpy(report.keycode, keycode, sizeof(report.keycode));
} else {
tu_memclr(report.keycode, 6);
}
return tud_hid_n_report(instance, report_id, &report, sizeof(report));
}
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) {
hid_mouse_report_t report = {
.buttons = buttons,
.x = x,
.y = y,
.wheel = vertical,
.pan = horizontal
};
return tud_hid_n_report(instance, report_id, &report, sizeof(report));
}
bool tud_hid_n_abs_mouse_report(uint8_t instance, uint8_t report_id,
uint8_t buttons, int16_t x, int16_t y, int8_t vertical, int8_t horizontal) {
hid_abs_mouse_report_t report = {
.buttons = buttons,
.x = x,
.y = y,
.wheel = vertical,
.pan = horizontal
};
return tud_hid_n_report(instance, report_id, &report, sizeof(report));
}
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) {
hid_gamepad_report_t report = {
.x = x,
.y = y,
.z = z,
.rz = rz,
.rx = rx,
.ry = ry,
.hat = hat,
.buttons = buttons,
};
return tud_hid_n_report(instance, report_id, &report, sizeof(report));
}
//--------------------------------------------------------------------+
// USBD-CLASS API
//--------------------------------------------------------------------+
void hidd_init(void) {
hidd_reset(0);
}
bool hidd_deinit(void) {
return true;
}
void hidd_reset(uint8_t rhport) {
(void)rhport;
tu_memclr(_hidd_itf, sizeof(_hidd_itf));
}
uint16_t hidd_open(uint8_t rhport, tusb_desc_interface_t const *desc_itf, uint16_t max_len) {
TU_VERIFY(TUSB_CLASS_HID == desc_itf->bInterfaceClass, 0);
// len = interface + hid + n*endpoints
uint16_t const drv_len = (uint16_t) (sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) +
desc_itf->bNumEndpoints * sizeof(tusb_desc_endpoint_t));
TU_ASSERT(max_len >= drv_len, 0);
// Find available interface
hidd_interface_t *p_hid;
uint8_t hid_id;
for (hid_id = 0; hid_id < CFG_TUD_HID; hid_id++) {
p_hid = &_hidd_itf[hid_id];
if (p_hid->ep_in == 0) {
break;
}
}
TU_ASSERT(hid_id < CFG_TUD_HID, 0);
hidd_epbuf_t *p_epbuf = &_hidd_epbuf[hid_id];
uint8_t const *p_desc = (uint8_t const *)desc_itf;
//------------- HID descriptor -------------//
p_desc = tu_desc_next(p_desc);
TU_ASSERT(HID_DESC_TYPE_HID == tu_desc_type(p_desc), 0);
p_hid->hid_descriptor = (tusb_hid_descriptor_hid_t const *)p_desc;
//------------- Endpoint Descriptor -------------//
p_desc = tu_desc_next(p_desc);
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, desc_itf->bNumEndpoints, TUSB_XFER_INTERRUPT, &p_hid->ep_out, &p_hid->ep_in), 0);
if (desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT) {
p_hid->itf_protocol = desc_itf->bInterfaceProtocol;
}
p_hid->protocol_mode = HID_PROTOCOL_REPORT; // Per Specs: default is report mode
p_hid->itf_num = desc_itf->bInterfaceNumber;
// Use offsetof to avoid pointer to the odd/misaligned address
p_hid->report_desc_len = tu_unaligned_read16((uint8_t const *)p_hid->hid_descriptor + offsetof(tusb_hid_descriptor_hid_t, wReportLength));
// Prepare for output endpoint
if (p_hid->ep_out) {
TU_ASSERT(usbd_edpt_xfer(rhport, p_hid->ep_out, p_epbuf->epout, CFG_TUD_HID_EP_BUFSIZE), drv_len);
}
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool hidd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) {
TU_VERIFY(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_INTERFACE);
uint8_t const hid_itf = get_index_by_itfnum((uint8_t)request->wIndex);
TU_VERIFY(hid_itf < CFG_TUD_HID);
hidd_interface_t *p_hid = &_hidd_itf[hid_itf];
hidd_epbuf_t *p_epbuf = &_hidd_epbuf[hid_itf];
if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) {
//------------- STD Request -------------//
if (stage == CONTROL_STAGE_SETUP) {
uint8_t const desc_type = tu_u16_high(request->wValue);
// uint8_t const desc_index = tu_u16_low (request->wValue);
if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_HID) {
TU_VERIFY(p_hid->hid_descriptor);
TU_VERIFY(tud_control_xfer(rhport, request, (void *)(uintptr_t)p_hid->hid_descriptor, p_hid->hid_descriptor->bLength));
} else if (request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT) {
uint8_t const *desc_report = tud_hid_descriptor_report_cb(hid_itf);
tud_control_xfer(rhport, request, (void *)(uintptr_t)desc_report, p_hid->report_desc_len);
} else {
return false; // stall unsupported request
}
}
} else if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS) {
//------------- Class Specific Request -------------//
switch (request->bRequest) {
case HID_REQ_CONTROL_GET_REPORT:
if (stage == CONTROL_STAGE_SETUP) {
uint8_t const report_type = tu_u16_high(request->wValue);
uint8_t const report_id = tu_u16_low(request->wValue);
uint8_t* report_buf = p_epbuf->ctrl;
uint16_t req_len = tu_min16(request->wLength, CFG_TUD_HID_EP_BUFSIZE);
uint16_t xferlen = 0;
// If host request a specific Report ID, add ID to as 1 byte of response
if ((report_id != HID_REPORT_TYPE_INVALID) && (req_len > 1)) {
*report_buf++ = report_id;
req_len--;
xferlen++;
}
xferlen += tud_hid_get_report_cb(hid_itf, report_id, (hid_report_type_t) report_type, report_buf, req_len);
TU_ASSERT(xferlen > 0);
tud_control_xfer(rhport, request, p_epbuf->ctrl, xferlen);
}
break;
case HID_REQ_CONTROL_SET_REPORT:
if (stage == CONTROL_STAGE_SETUP) {
TU_VERIFY(request->wLength <= CFG_TUD_HID_EP_BUFSIZE);
tud_control_xfer(rhport, request, p_epbuf->ctrl, request->wLength);
} else if (stage == CONTROL_STAGE_ACK) {
uint8_t const report_type = tu_u16_high(request->wValue);
uint8_t const report_id = tu_u16_low(request->wValue);
uint8_t const* report_buf = p_epbuf->ctrl;
uint16_t report_len = tu_min16(request->wLength, CFG_TUD_HID_EP_BUFSIZE);
// If host request a specific Report ID, extract report ID in buffer before invoking callback
if ((report_id != HID_REPORT_TYPE_INVALID) && (report_len > 1) && (report_id == report_buf[0])) {
report_buf++;
report_len--;
}
tud_hid_set_report_cb(hid_itf, report_id, (hid_report_type_t) report_type, report_buf, report_len);
}
break;
case HID_REQ_CONTROL_SET_IDLE:
if (stage == CONTROL_STAGE_SETUP) {
p_hid->idle_rate = tu_u16_high(request->wValue);
TU_VERIFY(tud_hid_set_idle_cb(hid_itf, p_hid->idle_rate)); // stall if false
tud_control_status(rhport, request);
}
break;
case HID_REQ_CONTROL_GET_IDLE:
if (stage == CONTROL_STAGE_SETUP) {
// TODO idle rate of report
tud_control_xfer(rhport, request, &p_hid->idle_rate, 1);
}
break;
case HID_REQ_CONTROL_GET_PROTOCOL:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_xfer(rhport, request, &p_hid->protocol_mode, 1);
}
break;
case HID_REQ_CONTROL_SET_PROTOCOL:
if (stage == CONTROL_STAGE_SETUP) {
tud_control_status(rhport, request);
} else if (stage == CONTROL_STAGE_ACK) {
p_hid->protocol_mode = (uint8_t) request->wValue;
tud_hid_set_protocol_cb(hid_itf, p_hid->protocol_mode);
}
break;
default:
return false; // stall unsupported request
}
} else {
return false; // stall unsupported request
}
return true;
}
bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
uint8_t instance;
hidd_interface_t *p_hid;
// Identify which interface to use
for (instance = 0; instance < CFG_TUD_HID; instance++) {
p_hid = &_hidd_itf[instance];
if ((ep_addr == p_hid->ep_out) || (ep_addr == p_hid->ep_in)) {
break;
}
}
TU_ASSERT(instance < CFG_TUD_HID);
hidd_epbuf_t *p_epbuf = &_hidd_epbuf[instance];
if (ep_addr == p_hid->ep_in) {
// Input report
if (XFER_RESULT_SUCCESS == result) {
tud_hid_report_complete_cb(instance, p_epbuf->epin, (uint16_t) xferred_bytes);
} else {
tud_hid_report_failed_cb(instance, HID_REPORT_TYPE_INPUT, p_epbuf->epin, (uint16_t) xferred_bytes);
}
} else {
// Output report
if (XFER_RESULT_SUCCESS == result) {
tud_hid_set_report_cb(instance, 0, HID_REPORT_TYPE_OUTPUT, p_epbuf->epout, (uint16_t)xferred_bytes);
} else {
tud_hid_report_failed_cb(instance, HID_REPORT_TYPE_OUTPUT, p_epbuf->epout, (uint16_t) xferred_bytes);
}
// prepare for new transfer
TU_ASSERT(usbd_edpt_xfer(rhport, p_hid->ep_out, p_epbuf->epout, CFG_TUD_HID_EP_BUFSIZE));
}
return true;
}
#endif

View file

@ -0,0 +1,631 @@
/*
* 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) i.e. 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, uint16_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, const 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);
// ABSOLUTE MOUSE: convenient helper to send absolute mouse report if application
// use template layout report as defined by hid_abs_mouse_report_t
bool tud_hid_n_abs_mouse_report(uint8_t instance, uint8_t report_id, uint8_t buttons, int16_t x, int16_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)
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_ready(void) {
return tud_hid_n_ready(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t tud_hid_interface_protocol(void) {
return tud_hid_n_interface_protocol(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint8_t tud_hid_get_protocol(void) {
return tud_hid_n_get_protocol(0);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_report(uint8_t report_id, void const* report, uint16_t len) {
return tud_hid_n_report(0, report_id, report, len);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, const uint8_t keycode[6]) {
return tud_hid_n_keyboard_report(0, report_id, modifier, keycode);
}
TU_ATTR_ALWAYS_INLINE 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);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_hid_abs_mouse_report(uint8_t report_id, uint8_t buttons, int16_t x, int16_t y, int8_t vertical, int8_t horizontal) {
return tud_hid_n_abs_mouse_report(0, report_id, buttons, x, y, vertical, horizontal);
}
TU_ATTR_ALWAYS_INLINE 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);
}
//--------------------------------------------------------------------+
// Application Callbacks
//--------------------------------------------------------------------+
// 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 = OUTPUT)
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)
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).
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
void tud_hid_report_complete_cb(uint8_t instance, uint8_t const* report, uint16_t len);
// Invoked when a transfer wasn't successful
void tud_hid_report_failed_cb(uint8_t instance, hid_report_type_t report_type, uint8_t const* report, uint16_t xferred_bytes);
/* --------------------------------------------------------------------+
* 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 (Shift, 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 \
// Absolute Mouse Report Descriptor Template
#define TUD_HID_REPORT_DESC_ABSMOUSE(...) \
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 absolute position [0, 32767] */ \
HID_USAGE ( HID_USAGE_DESKTOP_X ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_Y ) ,\
HID_LOGICAL_MIN ( 0x00 ) ,\
HID_LOGICAL_MAX_N( 0x7FFF, 2 ) ,\
HID_REPORT_SIZE ( 16 ) ,\
HID_REPORT_COUNT ( 2 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* Vertical 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 \
// FIDO U2F Authenticator Descriptor Template
// - 1st parameter is report size, which is 64 bytes maximum in U2F
// - 2nd parameter is HID_REPORT_ID(n) (optional)
#define TUD_HID_REPORT_DESC_FIDO_U2F(report_size, ...) \
HID_USAGE_PAGE_N ( HID_USAGE_PAGE_FIDO, 2 ) ,\
HID_USAGE ( HID_USAGE_FIDO_U2FHID ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
/* Report ID if any */ \
__VA_ARGS__ \
/* Usage Data In */ \
HID_USAGE ( HID_USAGE_FIDO_DATA_IN ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX_N ( 0xff, 2 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_REPORT_COUNT ( report_size ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* Usage Data Out */ \
HID_USAGE ( HID_USAGE_FIDO_DATA_OUT ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
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 \
// 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 \
// HID Lighting and Illumination Report Descriptor Template
// - 1st parameter is report id (required)
// Creates 6 report ids for lighting HID usages in the following order:
// report_id+0: HID_USAGE_LIGHTING_LAMP_ARRAY_ATTRIBUTES_REPORT
// report_id+1: HID_USAGE_LIGHTING_LAMP_ATTRIBUTES_REQUEST_REPORT
// report_id+2: HID_USAGE_LIGHTING_LAMP_ATTRIBUTES_RESPONSE_REPORT
// report_id+3: HID_USAGE_LIGHTING_LAMP_MULTI_UPDATE_REPORT
// report_id+4: HID_USAGE_LIGHTING_LAMP_RANGE_UPDATE_REPORT
// report_id+5: HID_USAGE_LIGHTING_LAMP_ARRAY_CONTROL_REPORT
#define TUD_HID_REPORT_DESC_LIGHTING(report_id) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_LIGHTING_AND_ILLUMINATION ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ARRAY ),\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ),\
/* Lamp Array Attributes Report */ \
HID_REPORT_ID (report_id ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ARRAY_ATTRIBUTES_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_COUNT ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 65535, 3 ),\
HID_REPORT_SIZE ( 16 ),\
HID_REPORT_COUNT ( 1 ),\
HID_FEATURE ( HID_CONSTANT | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_BOUNDING_BOX_WIDTH_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_BOUNDING_BOX_HEIGHT_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_BOUNDING_BOX_DEPTH_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ARRAY_KIND ),\
HID_USAGE ( HID_USAGE_LIGHTING_MIN_UPDATE_INTERVAL_IN_MICROSECONDS ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 2147483647, 3 ),\
HID_REPORT_SIZE ( 32 ),\
HID_REPORT_COUNT ( 5 ),\
HID_FEATURE ( HID_CONSTANT | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
/* Lamp Attributes Request Report */ \
HID_REPORT_ID ( report_id + 1 ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ATTRIBUTES_REQUEST_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ID ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 65535, 3 ),\
HID_REPORT_SIZE ( 16 ),\
HID_REPORT_COUNT ( 1 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
/* Lamp Attributes Response Report */ \
HID_REPORT_ID ( report_id + 2 ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ATTRIBUTES_RESPONSE_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ID ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 65535, 3 ),\
HID_REPORT_SIZE ( 16 ),\
HID_REPORT_COUNT ( 1 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_POSITION_X_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_POSITION_Y_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_POSITION_Z_IN_MICROMETERS ),\
HID_USAGE ( HID_USAGE_LIGHTING_UPDATE_LATENCY_IN_MICROSECONDS ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_PURPOSES ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 2147483647, 3 ),\
HID_REPORT_SIZE ( 32 ),\
HID_REPORT_COUNT ( 5 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_LEVEL_COUNT ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_LEVEL_COUNT ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_LEVEL_COUNT ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_LEVEL_COUNT ),\
HID_USAGE ( HID_USAGE_LIGHTING_IS_PROGRAMMABLE ),\
HID_USAGE ( HID_USAGE_LIGHTING_INPUT_BINDING ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 255, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 6 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
/* Lamp Multi-Update Report */ \
HID_REPORT_ID ( report_id + 3 ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_MULTI_UPDATE_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_COUNT ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_UPDATE_FLAGS ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX ( 8 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 2 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ID ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 65535, 3 ),\
HID_REPORT_SIZE ( 16 ),\
HID_REPORT_COUNT ( 8 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 255, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 32 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
/* Lamp Range Update Report */ \
HID_REPORT_ID ( report_id + 4 ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_RANGE_UPDATE_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_UPDATE_FLAGS ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX ( 8 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 1 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ID_START ),\
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ID_END ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 65535, 3 ),\
HID_REPORT_SIZE ( 16 ),\
HID_REPORT_COUNT ( 2 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_USAGE ( HID_USAGE_LIGHTING_RED_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_GREEN_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_BLUE_UPDATE_CHANNEL ),\
HID_USAGE ( HID_USAGE_LIGHTING_INTENSITY_UPDATE_CHANNEL ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX_N ( 255, 2 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 4 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
/* Lamp Array Control Report */ \
HID_REPORT_ID ( report_id + 5 ) \
HID_USAGE ( HID_USAGE_LIGHTING_LAMP_ARRAY_CONTROL_REPORT ),\
HID_COLLECTION ( HID_COLLECTION_LOGICAL ),\
HID_USAGE ( HID_USAGE_LIGHTING_AUTONOMOUS_MODE ),\
HID_LOGICAL_MIN ( 0 ),\
HID_LOGICAL_MAX ( 1 ),\
HID_REPORT_SIZE ( 8 ),\
HID_REPORT_COUNT ( 1 ),\
HID_FEATURE ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ),\
HID_COLLECTION_END ,\
HID_COLLECTION_END \
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void hidd_init (void);
bool hidd_deinit (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

View file

@ -0,0 +1,764 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUH_ENABLED && CFG_TUH_HID)
#include "host/usbh.h"
#include "host/usbh_pvt.h"
#include "hid_host.h"
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUH_HID_LOG_LEVEL
#define CFG_TUH_HID_LOG_LEVEL CFG_TUH_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_HID_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t daddr;
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
bool mounted; // Enumeration is complete
uint8_t itf_protocol; // None, Keyboard, Mouse
uint8_t protocol_mode; // Boot (0) or Report protocol (1)
uint8_t report_desc_type;
uint16_t report_desc_len;
uint16_t epin_size;
uint16_t epout_size;
} hidh_interface_t;
typedef struct {
TUH_EPBUF_DEF(epin, CFG_TUH_HID_EPIN_BUFSIZE);
TUH_EPBUF_DEF(epout, CFG_TUH_HID_EPOUT_BUFSIZE);
} hidh_epbuf_t;
static hidh_interface_t _hidh_itf[CFG_TUH_HID];
CFG_TUH_MEM_SECTION static hidh_epbuf_t _hidh_epbuf[CFG_TUH_HID];
static uint8_t _hidh_default_protocol = HID_PROTOCOL_BOOT;
//--------------------------------------------------------------------+
// Helper
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline hidh_interface_t* get_hid_itf(uint8_t daddr, uint8_t idx) {
TU_ASSERT(daddr > 0 && idx < CFG_TUH_HID, NULL);
hidh_interface_t* p_hid = &_hidh_itf[idx];
return (p_hid->daddr == daddr) ? p_hid : NULL;
}
TU_ATTR_ALWAYS_INLINE static inline hidh_epbuf_t* get_hid_epbuf(uint8_t idx) {
return &_hidh_epbuf[idx];
}
// Get instance ID by endpoint address
static uint8_t get_idx_by_epaddr(uint8_t daddr, uint8_t ep_addr) {
for (uint8_t idx = 0; idx < CFG_TUH_HID; idx++) {
hidh_interface_t const* p_hid = &_hidh_itf[idx];
if (p_hid->daddr == daddr &&
(p_hid->ep_in == ep_addr || p_hid->ep_out == ep_addr)) {
return idx;
}
}
return TUSB_INDEX_INVALID_8;
}
static hidh_interface_t* find_new_itf(void) {
for (uint8_t i = 0; i < CFG_TUH_HID; i++) {
if (_hidh_itf[i].daddr == 0) return &_hidh_itf[i];
}
return NULL;
}
//--------------------------------------------------------------------+
// Interface API
//--------------------------------------------------------------------+
uint8_t tuh_hid_itf_get_count(uint8_t daddr) {
uint8_t count = 0;
for (uint8_t i = 0; i < CFG_TUH_HID; i++) {
if (_hidh_itf[i].daddr == daddr) count++;
}
return count;
}
uint8_t tuh_hid_itf_get_total_count(void) {
uint8_t count = 0;
for (uint8_t i = 0; i < CFG_TUH_HID; i++) {
if (_hidh_itf[i].daddr != 0) count++;
}
return count;
}
bool tuh_hid_mounted(uint8_t daddr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
return p_hid->mounted;
}
bool tuh_hid_itf_get_info(uint8_t daddr, uint8_t idx, tuh_itf_info_t* info) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid && info);
info->daddr = daddr;
// re-construct descriptor
tusb_desc_interface_t* desc = &info->desc;
desc->bLength = sizeof(tusb_desc_interface_t);
desc->bDescriptorType = TUSB_DESC_INTERFACE;
desc->bInterfaceNumber = p_hid->itf_num;
desc->bAlternateSetting = 0;
desc->bNumEndpoints = (uint8_t) ((p_hid->ep_in ? 1u : 0u) + (p_hid->ep_out ? 1u : 0u));
desc->bInterfaceClass = TUSB_CLASS_HID;
desc->bInterfaceSubClass = (p_hid->itf_protocol ? HID_SUBCLASS_BOOT : HID_SUBCLASS_NONE);
desc->bInterfaceProtocol = p_hid->itf_protocol;
desc->iInterface = 0; // not used yet
return true;
}
uint8_t tuh_hid_itf_get_index(uint8_t daddr, uint8_t itf_num) {
for (uint8_t idx = 0; idx < CFG_TUH_HID; idx++) {
hidh_interface_t const* p_hid = &_hidh_itf[idx];
if (p_hid->daddr == daddr && p_hid->itf_num == itf_num) return idx;
}
return TUSB_INDEX_INVALID_8;
}
uint8_t tuh_hid_interface_protocol(uint8_t daddr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
return p_hid ? p_hid->itf_protocol : 0;
}
//--------------------------------------------------------------------+
// Control Endpoint API
//--------------------------------------------------------------------+
uint8_t tuh_hid_get_protocol(uint8_t daddr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
return p_hid ? p_hid->protocol_mode : 0;
}
static void set_protocol_complete(tuh_xfer_t* xfer) {
uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex);
uint8_t const daddr = xfer->daddr;
uint8_t const idx = tuh_hid_itf_get_index(daddr, itf_num);
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid,);
if (XFER_RESULT_SUCCESS == xfer->result) {
p_hid->protocol_mode = (uint8_t) tu_le16toh(xfer->setup->wValue);
}
if (tuh_hid_set_protocol_complete_cb) {
tuh_hid_set_protocol_complete_cb(daddr, idx, p_hid->protocol_mode);
}
}
void tuh_hid_set_default_protocol(uint8_t protocol) {
_hidh_default_protocol = protocol;
}
static bool _hidh_set_protocol(uint8_t daddr, uint8_t itf_num, uint8_t protocol,
tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
TU_LOG_DRV("HID Set Protocol = %d\r\n", protocol);
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_OUT
},
.bRequest = HID_REQ_CONTROL_SET_PROTOCOL,
.wValue = protocol,
.wIndex = itf_num,
.wLength = 0
};
tuh_xfer_t xfer = {
.daddr = daddr,
.ep_addr = 0,
.setup = &request,
.buffer = NULL,
.complete_cb = complete_cb,
.user_data = user_data
};
return tuh_control_xfer(&xfer);
}
bool tuh_hid_set_protocol(uint8_t daddr, uint8_t idx, uint8_t protocol) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid && p_hid->itf_protocol != HID_ITF_PROTOCOL_NONE);
return _hidh_set_protocol(daddr, p_hid->itf_num, protocol, set_protocol_complete, 0);
}
static void get_report_complete(tuh_xfer_t* xfer) {
TU_LOG_DRV("HID Get Report complete\r\n");
if (tuh_hid_get_report_complete_cb) {
uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex);
uint8_t const idx = tuh_hid_itf_get_index(xfer->daddr, itf_num);
uint8_t const report_type = tu_u16_high(xfer->setup->wValue);
uint8_t const report_id = tu_u16_low(xfer->setup->wValue);
tuh_hid_get_report_complete_cb(xfer->daddr, idx, report_id, report_type,
(xfer->result == XFER_RESULT_SUCCESS) ? xfer->setup->wLength : 0);
}
}
bool tuh_hid_get_report(uint8_t daddr, uint8_t idx, uint8_t report_id, uint8_t report_type, void* report, uint16_t len) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
TU_LOG_DRV("HID Get Report: id = %u, type = %u, len = %u\r\n", report_id, report_type, len);
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = HID_REQ_CONTROL_GET_REPORT,
.wValue = tu_htole16(tu_u16(report_type, report_id)),
.wIndex = tu_htole16((uint16_t) p_hid->itf_num),
.wLength = len
};
tuh_xfer_t xfer = {
.daddr = daddr,
.ep_addr = 0,
.setup = &request,
.buffer = report,
.complete_cb = get_report_complete,
.user_data = 0
};
return tuh_control_xfer(&xfer);
}
static void set_report_complete(tuh_xfer_t* xfer) {
TU_LOG_DRV("HID Set Report complete\r\n");
if (tuh_hid_set_report_complete_cb) {
uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex);
uint8_t const idx = tuh_hid_itf_get_index(xfer->daddr, itf_num);
uint8_t const report_type = tu_u16_high(xfer->setup->wValue);
uint8_t const report_id = tu_u16_low(xfer->setup->wValue);
tuh_hid_set_report_complete_cb(xfer->daddr, idx, report_id, report_type,
(xfer->result == XFER_RESULT_SUCCESS) ? xfer->setup->wLength : 0);
}
}
bool tuh_hid_set_report(uint8_t daddr, uint8_t idx, uint8_t report_id, uint8_t report_type, void* report, uint16_t len) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
TU_LOG_DRV("HID Set Report: id = %u, type = %u, len = %u\r\n", report_id, report_type, len);
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_OUT
},
.bRequest = HID_REQ_CONTROL_SET_REPORT,
.wValue = tu_htole16(tu_u16(report_type, report_id)),
.wIndex = tu_htole16((uint16_t) p_hid->itf_num),
.wLength = len
};
tuh_xfer_t xfer = {
.daddr = daddr,
.ep_addr = 0,
.setup = &request,
.buffer = report,
.complete_cb = set_report_complete,
.user_data = 0
};
return tuh_control_xfer(&xfer);
}
static bool _hidh_set_idle(uint8_t daddr, uint8_t itf_num, uint16_t idle_rate,
tuh_xfer_cb_t complete_cb, uintptr_t user_data) {
// SET IDLE request, device can stall if not support this request
TU_LOG_DRV("HID Set Idle \r\n");
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_OUT
},
.bRequest = HID_REQ_CONTROL_SET_IDLE,
.wValue = tu_htole16(idle_rate),
.wIndex = tu_htole16((uint16_t) itf_num),
.wLength = 0
};
tuh_xfer_t xfer = {
.daddr = daddr,
.ep_addr = 0,
.setup = &request,
.buffer = NULL,
.complete_cb = complete_cb,
.user_data = user_data
};
return tuh_control_xfer(&xfer);
}
//--------------------------------------------------------------------+
// Interrupt Endpoint API
//--------------------------------------------------------------------+
// Check if HID interface is ready to receive report
bool tuh_hid_receive_ready(uint8_t dev_addr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(dev_addr, idx);
TU_VERIFY(p_hid);
return !usbh_edpt_busy(dev_addr, p_hid->ep_in);
}
bool tuh_hid_receive_report(uint8_t daddr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
hidh_epbuf_t* epbuf = get_hid_epbuf(idx);
// claim endpoint
TU_VERIFY(usbh_edpt_claim(daddr, p_hid->ep_in));
if (!usbh_edpt_xfer(daddr, p_hid->ep_in, epbuf->epin, p_hid->epin_size)) {
usbh_edpt_release(daddr, p_hid->ep_in);
return false;
}
return true;
}
bool tuh_hid_receive_abort(uint8_t dev_addr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(dev_addr, idx);
TU_VERIFY(p_hid);
return tuh_edpt_abort_xfer(dev_addr, p_hid->ep_in);
}
bool tuh_hid_send_ready(uint8_t dev_addr, uint8_t idx) {
hidh_interface_t* p_hid = get_hid_itf(dev_addr, idx);
TU_VERIFY(p_hid);
return !usbh_edpt_busy(dev_addr, p_hid->ep_out);
}
bool tuh_hid_send_report(uint8_t daddr, uint8_t idx, uint8_t report_id, const void* report, uint16_t len) {
TU_LOG_DRV("HID Send Report %d\r\n", report_id);
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
hidh_epbuf_t* epbuf = get_hid_epbuf(idx);
if (p_hid->ep_out == 0) {
// This HID does not have an out endpoint (other than control)
return false;
} else if (len > CFG_TUH_HID_EPOUT_BUFSIZE ||
(report_id != 0 && len > (CFG_TUH_HID_EPOUT_BUFSIZE - 1))) {
// ep_out buffer is not large enough to hold contents
return false;
}
// claim endpoint
TU_VERIFY(usbh_edpt_claim(daddr, p_hid->ep_out));
if (report_id == 0) {
// No report ID in transmission
memcpy(&epbuf->epout[0], report, len);
} else {
epbuf->epout[0] = report_id;
memcpy(&epbuf->epout[1], report, len);
++len; // 1 more byte for report_id
}
TU_LOG3_MEM(p_hid->epout_buf, len, 2);
if (!usbh_edpt_xfer(daddr, p_hid->ep_out, epbuf->epout, len)) {
usbh_edpt_release(daddr, p_hid->ep_out);
return false;
}
return true;
}
//--------------------------------------------------------------------+
// USBH API
//--------------------------------------------------------------------+
bool hidh_init(void) {
TU_LOG_DRV("sizeof(hidh_interface_t) = %u\r\n", sizeof(hidh_interface_t));
tu_memclr(_hidh_itf, sizeof(_hidh_itf));
return true;
}
bool hidh_deinit(void) {
return true;
}
bool hidh_xfer_cb(uint8_t daddr, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void) result;
uint8_t const dir = tu_edpt_dir(ep_addr);
uint8_t const idx = get_idx_by_epaddr(daddr, ep_addr);
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid);
hidh_epbuf_t* epbuf = get_hid_epbuf(idx);
if (dir == TUSB_DIR_IN) {
TU_LOG_DRV(" Get Report callback (%u, %u)\r\n", daddr, idx);
TU_LOG3_MEM(p_hid->epin_buf, xferred_bytes, 2);
tuh_hid_report_received_cb(daddr, idx, epbuf->epin, (uint16_t) xferred_bytes);
} else {
if (tuh_hid_report_sent_cb) {
tuh_hid_report_sent_cb(daddr, idx, epbuf->epout, (uint16_t) xferred_bytes);
}
}
return true;
}
void hidh_close(uint8_t daddr) {
for (uint8_t i = 0; i < CFG_TUH_HID; i++) {
hidh_interface_t* p_hid = &_hidh_itf[i];
if (p_hid->daddr == daddr) {
TU_LOG_DRV(" HIDh close addr = %u index = %u\r\n", daddr, i);
if (tuh_hid_umount_cb) tuh_hid_umount_cb(daddr, i);
tu_memclr(p_hid, sizeof(hidh_interface_t));
}
}
}
//--------------------------------------------------------------------+
// Enumeration
//--------------------------------------------------------------------+
bool hidh_open(uint8_t rhport, uint8_t daddr, tusb_desc_interface_t const* desc_itf, uint16_t max_len) {
(void) rhport;
(void) max_len;
TU_VERIFY(TUSB_CLASS_HID == desc_itf->bInterfaceClass);
TU_LOG_DRV("[%u] HID opening Interface %u\r\n", daddr, desc_itf->bInterfaceNumber);
// len = interface + hid + n*endpoints
uint16_t const drv_len = (uint16_t) (sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) +
desc_itf->bNumEndpoints * sizeof(tusb_desc_endpoint_t));
TU_ASSERT(max_len >= drv_len);
uint8_t const* p_desc = (uint8_t const*) desc_itf;
//------------- HID descriptor -------------//
p_desc = tu_desc_next(p_desc);
tusb_hid_descriptor_hid_t const* desc_hid = (tusb_hid_descriptor_hid_t const*) p_desc;
TU_ASSERT(HID_DESC_TYPE_HID == desc_hid->bDescriptorType);
hidh_interface_t* p_hid = find_new_itf();
TU_ASSERT(p_hid); // not enough interface, try to increase CFG_TUH_HID
p_hid->daddr = daddr;
//------------- Endpoint Descriptors -------------//
p_desc = tu_desc_next(p_desc);
tusb_desc_endpoint_t const* desc_ep = (tusb_desc_endpoint_t const*) p_desc;
for (int i = 0; i < desc_itf->bNumEndpoints; i++) {
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_ep->bDescriptorType);
TU_ASSERT(tuh_edpt_open(daddr, desc_ep));
if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) {
p_hid->ep_in = desc_ep->bEndpointAddress;
p_hid->epin_size = tu_edpt_packet_size(desc_ep);
} else {
p_hid->ep_out = desc_ep->bEndpointAddress;
p_hid->epout_size = tu_edpt_packet_size(desc_ep);
}
p_desc = tu_desc_next(p_desc);
desc_ep = (tusb_desc_endpoint_t const*) p_desc;
}
p_hid->itf_num = desc_itf->bInterfaceNumber;
// Assume bNumDescriptors = 1
p_hid->report_desc_type = desc_hid->bReportType;
p_hid->report_desc_len = tu_unaligned_read16(&desc_hid->wReportLength);
// Per HID Specs: default is Report protocol, though we will force Boot protocol when set_config
p_hid->protocol_mode = _hidh_default_protocol;
if (HID_SUBCLASS_BOOT == desc_itf->bInterfaceSubClass) {
p_hid->itf_protocol = desc_itf->bInterfaceProtocol;
}
return true;
}
//--------------------------------------------------------------------+
// Set Configure
//--------------------------------------------------------------------+
enum {
CONFG_SET_IDLE,
CONFIG_SET_PROTOCOL,
CONFIG_GET_REPORT_DESC,
CONFIG_COMPLETE
};
static void config_driver_mount_complete(uint8_t daddr, uint8_t idx, uint8_t const* desc_report, uint16_t desc_len);
static void process_set_config(tuh_xfer_t* xfer);
bool hidh_set_config(uint8_t daddr, uint8_t itf_num) {
tusb_control_request_t request;
request.wIndex = tu_htole16((uint16_t) itf_num);
tuh_xfer_t xfer;
xfer.daddr = daddr;
xfer.result = XFER_RESULT_SUCCESS;
xfer.setup = &request;
xfer.user_data = CONFG_SET_IDLE;
// fake request to kick-off the set config process
process_set_config(&xfer);
return true;
}
static void process_set_config(tuh_xfer_t* xfer) {
// Stall is a valid response for SET_IDLE, sometime SET_PROTOCOL as well
// therefore we could ignore its result
if (!(xfer->setup->bRequest == HID_REQ_CONTROL_SET_IDLE ||
xfer->setup->bRequest == HID_REQ_CONTROL_SET_PROTOCOL)) {
TU_ASSERT(xfer->result == XFER_RESULT_SUCCESS,);
}
uintptr_t const state = xfer->user_data;
uint8_t const itf_num = (uint8_t) tu_le16toh(xfer->setup->wIndex);
uint8_t const daddr = xfer->daddr;
uint8_t const idx = tuh_hid_itf_get_index(daddr, itf_num);
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid,);
switch (state) {
case CONFG_SET_IDLE: {
// Idle rate = 0 mean only report when there is changes
const uint16_t idle_rate = 0;
const uintptr_t next_state = (p_hid->itf_protocol != HID_ITF_PROTOCOL_NONE)
? CONFIG_SET_PROTOCOL : CONFIG_GET_REPORT_DESC;
_hidh_set_idle(daddr, itf_num, idle_rate, process_set_config, next_state);
break;
}
case CONFIG_SET_PROTOCOL:
_hidh_set_protocol(daddr, p_hid->itf_num, _hidh_default_protocol, process_set_config, CONFIG_GET_REPORT_DESC);
break;
case CONFIG_GET_REPORT_DESC:
// Get Report Descriptor if possible
// using usbh enumeration buffer since report descriptor can be very long
if (p_hid->report_desc_len > CFG_TUH_ENUMERATION_BUFSIZE) {
TU_LOG_DRV("HID Skip Report Descriptor since it is too large %u bytes\r\n", p_hid->report_desc_len);
// Driver is mounted without report descriptor
config_driver_mount_complete(daddr, idx, NULL, 0);
} else {
tuh_descriptor_get_hid_report(daddr, itf_num, p_hid->report_desc_type, 0,
usbh_get_enum_buf(), p_hid->report_desc_len,
process_set_config, CONFIG_COMPLETE);
}
break;
case CONFIG_COMPLETE: {
uint8_t const* desc_report = usbh_get_enum_buf();
uint16_t const desc_len = tu_le16toh(xfer->setup->wLength);
config_driver_mount_complete(daddr, idx, desc_report, desc_len);
break;
}
default:
break;
}
}
static void config_driver_mount_complete(uint8_t daddr, uint8_t idx, uint8_t const* desc_report, uint16_t desc_len) {
hidh_interface_t* p_hid = get_hid_itf(daddr, idx);
TU_VERIFY(p_hid,);
p_hid->mounted = true;
// enumeration is complete
if (tuh_hid_mount_cb) tuh_hid_mount_cb(daddr, idx, desc_report, desc_len);
// notify usbh that driver enumeration is complete
usbh_driver_set_config_complete(daddr, p_hid->itf_num);
}
//--------------------------------------------------------------------+
// Report Descriptor Parser
//--------------------------------------------------------------------+
uint8_t tuh_hid_parse_report_descriptor(tuh_hid_report_info_t* report_info_arr, uint8_t arr_count,
uint8_t const* desc_report, uint16_t desc_len) {
// Report Item 6.2.2.2 USB HID 1.11
union TU_ATTR_PACKED {
uint8_t byte;
struct TU_ATTR_PACKED {
uint8_t size : 2;
uint8_t type : 2;
uint8_t tag : 4;
};
} header;
tu_memclr(report_info_arr, arr_count * sizeof(tuh_hid_report_info_t));
uint8_t report_num = 0;
tuh_hid_report_info_t* info = report_info_arr;
// current parsed report count & size from descriptor
// uint8_t ri_report_count = 0;
// uint8_t ri_report_size = 0;
uint8_t ri_collection_depth = 0;
while (desc_len && report_num < arr_count) {
header.byte = *desc_report++;
desc_len--;
uint8_t const tag = header.tag;
uint8_t const type = header.type;
uint8_t const size = header.size;
uint8_t const data8 = desc_report[0];
TU_LOG(3, "tag = %d, type = %d, size = %d, data = ", tag, type, size);
for (uint32_t i = 0; i < size; i++) {
TU_LOG(3, "%02X ", desc_report[i]);
}
TU_LOG(3, "\r\n");
switch (type) {
case RI_TYPE_MAIN:
switch (tag) {
case RI_MAIN_INPUT: break;
case RI_MAIN_OUTPUT: break;
case RI_MAIN_FEATURE: break;
case RI_MAIN_COLLECTION:
ri_collection_depth++;
break;
case RI_MAIN_COLLECTION_END:
ri_collection_depth--;
if (ri_collection_depth == 0) {
info++;
report_num++;
}
break;
default:break;
}
break;
case RI_TYPE_GLOBAL:
switch (tag) {
case RI_GLOBAL_USAGE_PAGE:
// only take in account the "usage page" before REPORT ID
if (ri_collection_depth == 0) memcpy(&info->usage_page, desc_report, size);
break;
case RI_GLOBAL_LOGICAL_MIN: break;
case RI_GLOBAL_LOGICAL_MAX: break;
case RI_GLOBAL_PHYSICAL_MIN: break;
case RI_GLOBAL_PHYSICAL_MAX: break;
case RI_GLOBAL_REPORT_ID:
info->report_id = data8;
break;
case RI_GLOBAL_REPORT_SIZE:
// ri_report_size = data8;
break;
case RI_GLOBAL_REPORT_COUNT:
// ri_report_count = data8;
break;
case RI_GLOBAL_UNIT_EXPONENT: break;
case RI_GLOBAL_UNIT: break;
case RI_GLOBAL_PUSH: break;
case RI_GLOBAL_POP: break;
default: break;
}
break;
case RI_TYPE_LOCAL:
switch (tag) {
case RI_LOCAL_USAGE:
// only take in account the "usage" before starting REPORT ID
if (ri_collection_depth == 0) info->usage = data8;
break;
case RI_LOCAL_USAGE_MIN: break;
case RI_LOCAL_USAGE_MAX: break;
case RI_LOCAL_DESIGNATOR_INDEX: break;
case RI_LOCAL_DESIGNATOR_MIN: break;
case RI_LOCAL_DESIGNATOR_MAX: break;
case RI_LOCAL_STRING_INDEX: break;
case RI_LOCAL_STRING_MIN: break;
case RI_LOCAL_STRING_MAX: break;
case RI_LOCAL_DELIMITER: break;
default: break;
}
break;
// error
default: break;
}
desc_report += size;
desc_len -= size;
}
for (uint8_t i = 0; i < report_num; i++) {
info = report_info_arr + i;
TU_LOG_DRV("%u: id = %u, usage_page = %u, usage = %u\r\n", i, info->report_id, info->usage_page, info->usage);
}
return report_num;
}
#endif

View file

@ -0,0 +1,185 @@
/*
* 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 total number of mounted HID interfaces of a device
uint8_t tuh_hid_itf_get_count(uint8_t dev_addr);
// Get all mounted interfaces across devices
uint8_t tuh_hid_itf_get_total_count(void);
// backward compatible rename
#define tuh_hid_instance_count tuh_hid_itf_get_count
// Get Interface information
bool tuh_hid_itf_get_info(uint8_t daddr, uint8_t idx, tuh_itf_info_t* itf_info);
// Get Interface index from device address + interface number
// return TUSB_INDEX_INVALID_8 (0xFF) if not found
uint8_t tuh_hid_itf_get_index(uint8_t daddr, uint8_t itf_num);
// 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 idx);
// Check if HID interface is mounted
bool tuh_hid_mounted(uint8_t dev_addr, uint8_t idx);
// Parse report descriptor into array of report_info struct and return number of reports.
// For complicated report, application should write its own parser.
TU_ATTR_UNUSED 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);
//--------------------------------------------------------------------+
// 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 idx);
// Device by default is enumerated in Boot protocol for simplicity. Application
// can use this to modify the default protocol for next enumeration.
void tuh_hid_set_default_protocol(uint8_t protocol);
// 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 idx, uint8_t protocol);
// Get Report using control endpoint
// report_type is either Input, Output or Feature, (value from hid_report_type_t)
bool tuh_hid_get_report(uint8_t dev_addr, uint8_t idx, uint8_t report_id, uint8_t report_type, void* report, uint16_t len);
// Set Report using control endpoint
// report_type is either Input, Output or Feature, (value from hid_report_type_t)
bool tuh_hid_set_report(uint8_t dev_addr, uint8_t idx, uint8_t report_id, uint8_t report_type,
void* report, uint16_t len);
//--------------------------------------------------------------------+
// Interrupt Endpoint API
//--------------------------------------------------------------------+
// Check if HID interface is ready to receive report
bool tuh_hid_receive_ready(uint8_t dev_addr, uint8_t idx);
// 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 idx);
// Abort receiving report on Interrupt Endpoint
bool tuh_hid_receive_abort(uint8_t dev_addr, uint8_t idx);
// Check if HID interface is ready to send report
bool tuh_hid_send_ready(uint8_t dev_addr, uint8_t idx);
// 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.
bool tuh_hid_send_report(uint8_t dev_addr, uint8_t idx, uint8_t report_id, const void* 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
TU_ATTR_WEAK void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t idx, 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 idx);
// 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 idx, 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 idx, uint8_t const* report, uint16_t len);
// Invoked when Get 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_get_report_complete_cb(uint8_t dev_addr, uint8_t idx, uint8_t report_id, uint8_t report_type, 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 idx, 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 idx, uint8_t protocol);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
bool hidh_init(void);
bool hidh_deinit(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_OFF = 8,
MIDI_CIN_NOTE_ON = 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,561 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_MIDI)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "midi_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t buffer[4];
uint8_t index;
uint8_t total;
} midid_stream_t;
typedef struct {
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
// For Stream read()/write() API
// Messages are always 4 bytes long, queue them for reading and writing so the
// callers can use the Stream interface with single-byte read/write calls.
midid_stream_t stream_write;
midid_stream_t stream_read;
/*------------- From this point, data is not cleared by bus reset -------------*/
// FIFO
tu_fifo_t rx_ff;
tu_fifo_t tx_ff;
uint8_t rx_ff_buf[CFG_TUD_MIDI_RX_BUFSIZE];
uint8_t tx_ff_buf[CFG_TUD_MIDI_TX_BUFSIZE];
#if CFG_FIFO_MUTEX
osal_mutex_def_t rx_ff_mutex;
osal_mutex_def_t tx_ff_mutex;
#endif
} midid_interface_t;
#define ITF_MEM_RESET_SIZE offsetof(midid_interface_t, rx_ff)
// Endpoint Transfer buffer
CFG_TUD_MEM_SECTION static struct {
TUD_EPBUF_DEF(epin, CFG_TUD_MIDI_EP_BUFSIZE);
TUD_EPBUF_DEF(epout, CFG_TUD_MIDI_EP_BUFSIZE);
} _midid_epbuf[CFG_TUD_MIDI];
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static midid_interface_t _midid_itf[CFG_TUD_MIDI];
bool tud_midi_n_mounted (uint8_t itf) {
midid_interface_t* midi = &_midid_itf[itf];
return midi->ep_in && midi->ep_out;
}
static void _prep_out_transaction(uint8_t idx) {
const uint8_t rhport = 0;
midid_interface_t* p_midi = &_midid_itf[idx];
uint16_t available = tu_fifo_remaining(&p_midi->rx_ff);
// Prepare for incoming data but only allow what we can store in the ring buffer.
// TODO Actually we can still carry out the transfer, keeping count of received bytes
// and slowly move it to the FIFO when read().
// This pre-check reduces endpoint claiming
TU_VERIFY(available >= CFG_TUD_MIDI_EP_BUFSIZE, );
// claim endpoint
TU_VERIFY(usbd_edpt_claim(rhport, p_midi->ep_out), );
// fifo can be changed before endpoint is claimed
available = tu_fifo_remaining(&p_midi->rx_ff);
if ( available >= CFG_TUD_MIDI_EP_BUFSIZE ) {
usbd_edpt_xfer(rhport, p_midi->ep_out, _midid_epbuf[idx].epout, CFG_TUD_MIDI_EP_BUFSIZE);
}else
{
// Release endpoint since we don't make any transfer
usbd_edpt_release(rhport, p_midi->ep_out);
}
}
//--------------------------------------------------------------------+
// READ API
//--------------------------------------------------------------------+
uint32_t tud_midi_n_available(uint8_t itf, uint8_t cable_num)
{
(void) cable_num;
midid_interface_t* midi = &_midid_itf[itf];
const midid_stream_t* stream = &midi->stream_read;
// when using with packet API stream total & index are both zero
return tu_fifo_count(&midi->rx_ff) + (uint8_t) (stream->total - stream->index);
}
uint32_t tud_midi_n_stream_read(uint8_t itf, uint8_t cable_num, void* buffer, uint32_t bufsize)
{
(void) cable_num;
TU_VERIFY(bufsize, 0);
uint8_t* buf8 = (uint8_t*) buffer;
midid_interface_t* midi = &_midid_itf[itf];
midid_stream_t* stream = &midi->stream_read;
uint32_t total_read = 0;
while( bufsize )
{
// Get new packet from fifo, then set packet expected bytes
if ( stream->total == 0 )
{
// return if there is no more data from fifo
if ( !tud_midi_n_packet_read(itf, stream->buffer) ) return total_read;
uint8_t const code_index = stream->buffer[0] & 0x0f;
// MIDI 1.0 Table 4-1: Code Index Number Classifications
switch(code_index)
{
case MIDI_CIN_MISC:
case MIDI_CIN_CABLE_EVENT:
// These are reserved and unused, possibly issue somewhere, skip this packet
return 0;
break;
case MIDI_CIN_SYSEX_END_1BYTE:
case MIDI_CIN_1BYTE_DATA:
stream->total = 1;
break;
case MIDI_CIN_SYSCOM_2BYTE :
case MIDI_CIN_SYSEX_END_2BYTE :
case MIDI_CIN_PROGRAM_CHANGE :
case MIDI_CIN_CHANNEL_PRESSURE :
stream->total = 2;
break;
default:
stream->total = 3;
break;
}
}
// Copy data up to bufsize
uint8_t const count = (uint8_t) tu_min32(stream->total - stream->index, bufsize);
// Skip the header (1st byte) in the buffer
TU_VERIFY(0 == tu_memcpy_s(buf8, bufsize, stream->buffer + 1 + stream->index, count));
total_read += count;
stream->index += count;
buf8 += count;
bufsize -= count;
// complete current event packet, reset stream
if ( stream->total == stream->index )
{
stream->index = 0;
stream->total = 0;
}
}
return total_read;
}
bool tud_midi_n_packet_read (uint8_t itf, uint8_t packet[4])
{
midid_interface_t* midi = &_midid_itf[itf];
TU_VERIFY(midi->ep_out);
const uint32_t num_read = tu_fifo_read_n(&midi->rx_ff, packet, 4);
_prep_out_transaction(itf);
return (num_read == 4);
}
//--------------------------------------------------------------------+
// WRITE API
//--------------------------------------------------------------------+
static uint32_t write_flush(uint8_t idx) {
midid_interface_t* midi = &_midid_itf[idx];
if (!tu_fifo_count(&midi->tx_ff)) {
return 0; // No data to send
}
const uint8_t rhport = 0;
// skip if previous transfer not complete
TU_VERIFY( usbd_edpt_claim(rhport, midi->ep_in), 0 );
uint16_t count = tu_fifo_read_n(&midi->tx_ff, _midid_epbuf[idx].epin, CFG_TUD_MIDI_EP_BUFSIZE);
if (count) {
TU_ASSERT( usbd_edpt_xfer(rhport, midi->ep_in, _midid_epbuf[idx].epin, count), 0 );
return count;
}else {
// Release endpoint since we don't make any transfer
usbd_edpt_release(rhport, midi->ep_in);
return 0;
}
}
uint32_t tud_midi_n_stream_write(uint8_t itf, uint8_t cable_num, const uint8_t* buffer, uint32_t bufsize)
{
midid_interface_t* midi = &_midid_itf[itf];
TU_VERIFY(midi->ep_in, 0);
midid_stream_t* stream = &midi->stream_write;
uint32_t i = 0;
while ( (i < bufsize) && (tu_fifo_remaining(&midi->tx_ff) >= 4) )
{
const uint8_t data = buffer[i];
i++;
if ( stream->index == 0 )
{
//------------- New event packet -------------//
const uint8_t msg = data >> 4;
stream->index = 2;
stream->buffer[1] = data;
// Check to see if we're still in a SysEx transmit.
if ( ((stream->buffer[0]) & 0xF) == MIDI_CIN_SYSEX_START )
{
if ( data == MIDI_STATUS_SYSEX_END )
{
stream->buffer[0] = (uint8_t) ((cable_num << 4) | MIDI_CIN_SYSEX_END_1BYTE);
stream->total = 2;
}
else
{
stream->total = 4;
}
}
else if ( (msg >= 0x8 && msg <= 0xB) || msg == 0xE )
{
// Channel Voice Messages
stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg);
stream->total = 4;
}
else if ( msg == 0xC || msg == 0xD)
{
// Channel Voice Messages, two-byte variants (Program Change and Channel Pressure)
stream->buffer[0] = (uint8_t) ((cable_num << 4) | msg);
stream->total = 3;
}
else if ( msg == 0xf )
{
// System message
if ( data == MIDI_STATUS_SYSEX_START )
{
stream->buffer[0] = MIDI_CIN_SYSEX_START;
stream->total = 4;
}
else if ( data == MIDI_STATUS_SYSCOM_TIME_CODE_QUARTER_FRAME || data == MIDI_STATUS_SYSCOM_SONG_SELECT )
{
stream->buffer[0] = MIDI_CIN_SYSCOM_2BYTE;
stream->total = 3;
}
else if ( data == MIDI_STATUS_SYSCOM_SONG_POSITION_POINTER )
{
stream->buffer[0] = MIDI_CIN_SYSCOM_3BYTE;
stream->total = 4;
}
else
{
stream->buffer[0] = MIDI_CIN_SYSEX_END_1BYTE;
stream->total = 2;
}
stream->buffer[0] |= (uint8_t)(cable_num << 4);
}
else
{
// Pack individual bytes if we don't support packing them into words.
stream->buffer[0] = (uint8_t) (cable_num << 4 | 0xf);
stream->buffer[2] = 0;
stream->buffer[3] = 0;
stream->index = 2;
stream->total = 2;
}
}
else
{
//------------- On-going (buffering) packet -------------//
TU_ASSERT(stream->index < 4, i);
stream->buffer[stream->index] = data;
stream->index++;
// See if this byte ends a SysEx.
if ( (stream->buffer[0] & 0xF) == MIDI_CIN_SYSEX_START && data == MIDI_STATUS_SYSEX_END )
{
stream->buffer[0] = (uint8_t) ((cable_num << 4) | (MIDI_CIN_SYSEX_START + (stream->index - 1)));
stream->total = stream->index;
}
}
// Send out packet
if ( stream->index == stream->total )
{
// zeroes unused bytes
for (uint8_t idx = stream->total; idx < 4; idx++) {
stream->buffer[idx] = 0;
}
const uint16_t count = tu_fifo_write_n(&midi->tx_ff, stream->buffer, 4);
// complete current event packet, reset stream
stream->index = stream->total = 0;
// FIFO overflown, since we already check fifo remaining. It is probably race condition
TU_ASSERT(count == 4, i);
}
}
write_flush(itf);
return i;
}
bool tud_midi_n_packet_write (uint8_t itf, const uint8_t packet[4]) {
midid_interface_t* midi = &_midid_itf[itf];
TU_VERIFY(midi->ep_in);
if (tu_fifo_remaining(&midi->tx_ff) < 4) {
return false;
}
tu_fifo_write_n(&midi->tx_ff, packet, 4);
write_flush(itf);
return true;
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void midid_init(void) {
tu_memclr(_midid_itf, sizeof(_midid_itf));
for (uint8_t i = 0; i < CFG_TUD_MIDI; i++) {
midid_interface_t* midi = &_midid_itf[i];
// config fifo
tu_fifo_config(&midi->rx_ff, midi->rx_ff_buf, CFG_TUD_MIDI_RX_BUFSIZE, 1, false); // true, true
tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, false); // OBVS.
#if CFG_FIFO_MUTEX
osal_mutex_t mutex_rd = osal_mutex_create(&midi->rx_ff_mutex);
osal_mutex_t mutex_wr = osal_mutex_create(&midi->tx_ff_mutex);
TU_ASSERT(mutex_wr != NULL && mutex_wr != NULL, );
tu_fifo_config_mutex(&midi->rx_ff, NULL, mutex_rd);
tu_fifo_config_mutex(&midi->tx_ff, mutex_wr, NULL);
#endif
}
}
bool midid_deinit(void) {
#if CFG_FIFO_MUTEX
for(uint8_t i=0; i<CFG_TUD_MIDI; i++) {
midid_interface_t* midi = &_midid_itf[i];
osal_mutex_t mutex_rd = midi->rx_ff.mutex_rd;
osal_mutex_t mutex_wr = midi->tx_ff.mutex_wr;
if (mutex_rd) {
osal_mutex_delete(mutex_rd);
tu_fifo_config_mutex(&midi->rx_ff, NULL, NULL);
}
if (mutex_wr) {
osal_mutex_delete(mutex_wr);
tu_fifo_config_mutex(&midi->tx_ff, NULL, NULL);
}
}
#endif
return true;
}
void midid_reset(uint8_t rhport)
{
(void) rhport;
for(uint8_t i=0; i<CFG_TUD_MIDI; i++)
{
midid_interface_t* midi = &_midid_itf[i];
tu_memclr(midi, ITF_MEM_RESET_SIZE);
tu_fifo_clear(&midi->rx_ff);
tu_fifo_clear(&midi->tx_ff);
}
}
uint16_t midid_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len)
{
// 1st Interface is Audio Control v1
TU_VERIFY(TUSB_CLASS_AUDIO == desc_itf->bInterfaceClass &&
AUDIO_SUBCLASS_CONTROL == desc_itf->bInterfaceSubClass &&
AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_itf->bInterfaceProtocol, 0);
uint16_t drv_len = tu_desc_len(desc_itf);
const uint8_t* p_desc = tu_desc_next(desc_itf);
// Skip Class Specific descriptors
while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len )
{
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// 2nd Interface is MIDI Streaming
TU_VERIFY(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0);
const tusb_desc_interface_t* desc_midi = (const tusb_desc_interface_t*) p_desc;
TU_VERIFY(TUSB_CLASS_AUDIO == desc_midi->bInterfaceClass &&
AUDIO_SUBCLASS_MIDI_STREAMING == desc_midi->bInterfaceSubClass &&
AUDIO_FUNC_PROTOCOL_CODE_UNDEF == desc_midi->bInterfaceProtocol, 0);
// Find available interface
midid_interface_t * p_midi = NULL;
uint8_t idx;
for(idx=0; idx<CFG_TUD_MIDI; idx++) {
if ( _midid_itf[idx].ep_in == 0 && _midid_itf[idx].ep_out == 0 ) {
p_midi = &_midid_itf[idx];
break;
}
}
TU_ASSERT(p_midi);
p_midi->itf_num = desc_midi->bInterfaceNumber;
(void) p_midi->itf_num;
// next descriptor
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
// Find and open endpoint descriptors
uint8_t found_endpoints = 0;
while ( (found_endpoints < desc_midi->bNumEndpoints) && (drv_len <= max_len) )
{
if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
{
TU_ASSERT(usbd_edpt_open(rhport, (const tusb_desc_endpoint_t*) p_desc), 0);
uint8_t ep_addr = ((const tusb_desc_endpoint_t*) p_desc)->bEndpointAddress;
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN)
{
p_midi->ep_in = ep_addr;
} else {
p_midi->ep_out = ep_addr;
}
// Class Specific MIDI Stream endpoint descriptor
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
found_endpoints += 1;
}
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// Prepare for incoming data
_prep_out_transaction(idx);
return drv_len;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool midid_control_xfer_cb(uint8_t rhport, uint8_t stage, const tusb_control_request_t* request) {
(void) rhport; (void) stage; (void) request;
return false; // driver doesn't support any request yet
}
bool midid_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
{
(void) result;
(void) rhport;
uint8_t idx;
midid_interface_t* p_midi;
// Identify which interface to use
for (idx = 0; idx < CFG_TUD_MIDI; idx++) {
p_midi = &_midid_itf[idx];
if ((ep_addr == p_midi->ep_out) || (ep_addr == p_midi->ep_in)) {
break;
}
}
TU_ASSERT(idx < CFG_TUD_MIDI);
// receive new data
if (ep_addr == p_midi->ep_out) {
tu_fifo_write_n(&p_midi->rx_ff, _midid_epbuf[idx].epout, (uint16_t)xferred_bytes);
// invoke receive callback if available
if (tud_midi_rx_cb) {
tud_midi_rx_cb(idx);
}
// prepare for next
// TODO for now ep_out is not used by public API therefore there is no race condition,
// and does not need to claim like ep_in
_prep_out_transaction(idx);
} else if (ep_addr == p_midi->ep_in) {
if (0 == write_flush(idx)) {
// If there is no data left, a ZLP should be sent if
// xferred_bytes is multiple of EP size and not zero
if (!tu_fifo_count(&p_midi->tx_ff) && xferred_bytes && (0 == (xferred_bytes % CFG_TUD_MIDI_EP_BUFSIZE))) {
if (usbd_edpt_claim(rhport, p_midi->ep_in)) {
usbd_edpt_xfer(rhport, p_midi->ep_in, NULL, 0);
}
}
}
}
return true;
}
#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 _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);
bool midid_deinit (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 floppy disk & should not used with highspeed or device other than floppy
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 dCSWDataResidue the 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 that the 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, ///< Indicates 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 ///< Indicates 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,860 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_MSC)
#include "device/dcd.h" // for faking dcd_event_xfer_complete
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "msc_device.h"
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUD_MSC_LOG_LEVEL
#define CFG_TUD_MSC_LOG_LEVEL CFG_TUD_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_MSC_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
enum {
MSC_STAGE_CMD = 0,
MSC_STAGE_DATA,
MSC_STAGE_STATUS,
MSC_STAGE_STATUS_SENT,
MSC_STAGE_NEED_RESET,
};
typedef struct {
TU_ATTR_ALIGNED(4) msc_cbw_t cbw;
TU_ATTR_ALIGNED(4) msc_csw_t csw;
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
// Bulk Only Transfer (BOT) Protocol
uint8_t stage;
uint32_t total_len; // byte to be transferred, can be smaller than total_bytes in cbw
uint32_t xferred_len; // numbered of bytes transferred so far in the Data Stage
// Sense Response Data
uint8_t sense_key;
uint8_t add_sense_code;
uint8_t add_sense_qualifier;
}mscd_interface_t;
static mscd_interface_t _mscd_itf;
CFG_TUD_MEM_SECTION static struct {
TUD_EPBUF_DEF(buf, CFG_TUD_MSC_EP_BUFSIZE);
} _mscd_epbuf;
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize);
static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc);
static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc);
static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes);
TU_ATTR_ALWAYS_INLINE static inline bool is_data_in(uint8_t dir) {
return tu_bit_test(dir, 7);
}
static inline bool send_csw(uint8_t rhport, mscd_interface_t* p_msc) {
// Data residue is always = host expect - actual transferred
p_msc->csw.data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len;
p_msc->stage = MSC_STAGE_STATUS_SENT;
memcpy(_mscd_epbuf.buf, &p_msc->csw, sizeof(msc_csw_t));
return usbd_edpt_xfer(rhport, p_msc->ep_in , _mscd_epbuf.buf, sizeof(msc_csw_t));
}
static inline bool prepare_cbw(uint8_t rhport, mscd_interface_t* p_msc) {
p_msc->stage = MSC_STAGE_CMD;
return usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_epbuf.buf, sizeof(msc_cbw_t));
}
static void fail_scsi_op(uint8_t rhport, mscd_interface_t* p_msc, uint8_t status) {
msc_cbw_t const * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
p_csw->status = status;
p_csw->data_residue = p_msc->cbw.total_bytes - p_msc->xferred_len;
p_msc->stage = MSC_STAGE_STATUS;
// failed but sense key is not set: default to Illegal Request
if (p_msc->sense_key == 0) {
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
}
// If there is data stage and not yet complete, stall it
if (p_cbw->total_bytes && p_csw->data_residue) {
if (is_data_in(p_cbw->dir)) {
usbd_edpt_stall(rhport, p_msc->ep_in);
} else {
usbd_edpt_stall(rhport, p_msc->ep_out);
}
}
}
static inline uint32_t rdwr10_get_lba(uint8_t const command[]) {
// use offsetof to avoid pointer to the odd/unaligned address
const uint32_t lba = tu_unaligned_read32(command + offsetof(scsi_write10_t, lba));
return tu_ntohl(lba); // lba is in Big Endian
}
static inline uint16_t rdwr10_get_blockcount(msc_cbw_t const* cbw) {
uint16_t const block_count = tu_unaligned_read16(cbw->command + offsetof(scsi_write10_t, block_count));
return tu_ntohs(block_count);
}
static inline uint16_t rdwr10_get_blocksize(msc_cbw_t const* cbw) {
// first extract block count in the command
uint16_t const block_count = rdwr10_get_blockcount(cbw);
if (block_count == 0) {
return 0; // invalid block count
}
return (uint16_t) (cbw->total_bytes / block_count);
}
static uint8_t rdwr10_validate_cmd(msc_cbw_t const* cbw) {
uint8_t status = MSC_CSW_STATUS_PASSED;
uint16_t const block_count = rdwr10_get_blockcount(cbw);
if (cbw->total_bytes == 0) {
if (block_count) {
TU_LOG_DRV(" SCSI case 2 (Hn < Di) or case 3 (Hn < Do) \r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
} else {
// no data transfer, only exist in complaint test suite
}
} else {
if (SCSI_CMD_READ_10 == cbw->command[0] && !is_data_in(cbw->dir)) {
TU_LOG_DRV(" SCSI case 10 (Ho <> Di)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
} else if (SCSI_CMD_WRITE_10 == cbw->command[0] && is_data_in(cbw->dir)) {
TU_LOG_DRV(" SCSI case 8 (Hi <> Do)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
} else if (0 == block_count) {
TU_LOG_DRV(" SCSI case 4 Hi > Dn (READ10) or case 9 Ho > Dn (WRITE10) \r\n");
status = MSC_CSW_STATUS_FAILED;
} else if (cbw->total_bytes / block_count == 0) {
TU_LOG_DRV(" Computed block size = 0. SCSI case 7 Hi < Di (READ10) or case 13 Ho < Do (WRIT10)\r\n");
status = MSC_CSW_STATUS_PHASE_ERROR;
}
}
return status;
}
//--------------------------------------------------------------------+
// Debug
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG >= CFG_TUD_MSC_LOG_LEVEL
TU_ATTR_UNUSED tu_static tu_lookup_entry_t const _msc_scsi_cmd_lookup[] = {
{ .key = SCSI_CMD_TEST_UNIT_READY , .data = "Test Unit Ready" },
{ .key = SCSI_CMD_INQUIRY , .data = "Inquiry" },
{ .key = SCSI_CMD_MODE_SELECT_6 , .data = "Mode_Select 6" },
{ .key = SCSI_CMD_MODE_SENSE_6 , .data = "Mode_Sense 6" },
{ .key = SCSI_CMD_START_STOP_UNIT , .data = "Start Stop Unit" },
{ .key = SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL , .data = "Prevent/Allow Medium Removal" },
{ .key = SCSI_CMD_READ_CAPACITY_10 , .data = "Read Capacity10" },
{ .key = SCSI_CMD_REQUEST_SENSE , .data = "Request Sense" },
{ .key = SCSI_CMD_READ_FORMAT_CAPACITY , .data = "Read Format Capacity" },
{ .key = SCSI_CMD_READ_10 , .data = "Read10" },
{ .key = SCSI_CMD_WRITE_10 , .data = "Write10" }
};
TU_ATTR_UNUSED tu_static tu_lookup_table_t const _msc_scsi_cmd_table = {
.count = TU_ARRAY_SIZE(_msc_scsi_cmd_lookup),
.items = _msc_scsi_cmd_lookup
};
#endif
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier) {
(void) lun;
_mscd_itf.sense_key = sense_key;
_mscd_itf.add_sense_code = add_sense_code;
_mscd_itf.add_sense_qualifier = add_sense_qualifier;
return true;
}
static inline void set_sense_medium_not_present(uint8_t lun) {
// default sense is NOT READY, MEDIUM NOT PRESENT
tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x3A, 0x00);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void mscd_init(void) {
tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
}
bool mscd_deinit(void) {
return true; // nothing to do
}
void mscd_reset(uint8_t rhport) {
(void) rhport;
tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
}
uint16_t mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len) {
// only support SCSI's BOT protocol
TU_VERIFY(TUSB_CLASS_MSC == itf_desc->bInterfaceClass &&
MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass &&
MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol, 0);
uint16_t const drv_len = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
TU_ASSERT(max_len >= drv_len, 0); // Max length must be at least 1 interface + 2 endpoints
mscd_interface_t * p_msc = &_mscd_itf;
p_msc->itf_num = itf_desc->bInterfaceNumber;
// Open endpoint pair
TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in), 0);
// Prepare for Command Block Wrapper
TU_ASSERT(prepare_cbw(rhport, p_msc), drv_len);
return drv_len;
}
static void proc_bot_reset(mscd_interface_t* p_msc) {
p_msc->stage = MSC_STAGE_CMD;
p_msc->total_len = 0;
p_msc->xferred_len = 0;
p_msc->sense_key = 0;
p_msc->add_sense_code = 0;
p_msc->add_sense_qualifier = 0;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool mscd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request) {
if (stage != CONTROL_STAGE_SETUP) {
return true; // nothing to do with DATA & ACK stage
}
mscd_interface_t* p_msc = &_mscd_itf;
// Clear Endpoint Feature (stall) for recovery
if ( TUSB_REQ_TYPE_STANDARD == request->bmRequestType_bit.type &&
TUSB_REQ_RCPT_ENDPOINT == request->bmRequestType_bit.recipient &&
TUSB_REQ_CLEAR_FEATURE == request->bRequest &&
TUSB_REQ_FEATURE_EDPT_HALT == request->wValue ) {
uint8_t const ep_addr = tu_u16_low(request->wIndex);
if (p_msc->stage == MSC_STAGE_NEED_RESET) {
// reset recovery is required to recover from this stage
// Clear Stall request cannot resolve this -> continue to stall endpoint
usbd_edpt_stall(rhport, ep_addr);
} else {
if (ep_addr == p_msc->ep_in) {
if (p_msc->stage == MSC_STAGE_STATUS) {
// resume sending SCSI status if we are in this stage previously before stalled
TU_ASSERT(send_csw(rhport, p_msc));
}
} else if (ep_addr == p_msc->ep_out) {
if (p_msc->stage == MSC_STAGE_CMD) {
// part of reset recovery (probably due to invalid CBW) -> prepare for new command
// Note: skip if already queued previously
if (usbd_edpt_ready(rhport, p_msc->ep_out)) {
TU_ASSERT(prepare_cbw(rhport, p_msc));
}
}
}
}
return true;
}
// From this point only handle class request only
TU_VERIFY(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
switch ( request->bRequest ) {
case MSC_REQ_RESET:
TU_LOG_DRV(" MSC BOT Reset\r\n");
TU_VERIFY(request->wValue == 0 && request->wLength == 0);
proc_bot_reset(p_msc); // driver state reset
tud_control_status(rhport, request);
break;
case MSC_REQ_GET_MAX_LUN: {
TU_LOG_DRV(" MSC Get Max Lun\r\n");
TU_VERIFY(request->wValue == 0 && request->wLength == 1);
uint8_t maxlun = 1;
if (tud_msc_get_maxlun_cb) {
maxlun = tud_msc_get_maxlun_cb();
}
TU_VERIFY(maxlun);
maxlun--; // MAX LUN is minus 1 by specs
tud_control_xfer(rhport, request, &maxlun, 1);
break;
}
default: return false; // stall unsupported request
}
return true;
}
bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) {
(void) event;
mscd_interface_t* p_msc = &_mscd_itf;
msc_cbw_t * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
switch (p_msc->stage) {
case MSC_STAGE_CMD:
//------------- new CBW received -------------//
// Complete IN while waiting for CMD is usually Status of previous SCSI op, ignore it
if (ep_addr != p_msc->ep_out) {
return true;
}
const uint32_t signature = tu_le32toh(tu_unaligned_read32(_mscd_epbuf.buf));
if (!(xferred_bytes == sizeof(msc_cbw_t) && signature == MSC_CBW_SIGNATURE)) {
// BOT 6.6.1 If CBW is not valid stall both endpoints until reset recovery
TU_LOG_DRV(" SCSI CBW is not valid\r\n");
p_msc->stage = MSC_STAGE_NEED_RESET;
usbd_edpt_stall(rhport, p_msc->ep_in);
usbd_edpt_stall(rhport, p_msc->ep_out);
return false;
}
memcpy(p_cbw, _mscd_epbuf.buf, sizeof(msc_cbw_t));
TU_LOG_DRV(" SCSI Command [Lun%u]: %s\r\n", p_cbw->lun, tu_lookup_find(&_msc_scsi_cmd_table, p_cbw->command[0]));
//TU_LOG_MEM(MSC_DEBUG, p_cbw, xferred_bytes, 2);
p_csw->signature = MSC_CSW_SIGNATURE;
p_csw->tag = p_cbw->tag;
p_csw->data_residue = 0;
p_csw->status = MSC_CSW_STATUS_PASSED;
/*------------- Parse command and prepare DATA -------------*/
p_msc->stage = MSC_STAGE_DATA;
p_msc->total_len = p_cbw->total_bytes;
p_msc->xferred_len = 0;
// Read10 or Write10
if ((SCSI_CMD_READ_10 == p_cbw->command[0]) || (SCSI_CMD_WRITE_10 == p_cbw->command[0])) {
uint8_t const status = rdwr10_validate_cmd(p_cbw);
if (status != MSC_CSW_STATUS_PASSED) {
fail_scsi_op(rhport, p_msc, status);
} else if (p_cbw->total_bytes) {
if (SCSI_CMD_READ_10 == p_cbw->command[0]) {
proc_read10_cmd(rhport, p_msc);
} else {
proc_write10_cmd(rhport, p_msc);
}
} else {
// no data transfer, only exist in complaint test suite
p_msc->stage = MSC_STAGE_STATUS;
}
} else {
// For other SCSI commands
// 1. OUT : queue transfer (invoke app callback after done)
// 2. IN & Zero: Process if is built-in, else Invoke app callback. Skip DATA if zero length
if ((p_cbw->total_bytes > 0) && !is_data_in(p_cbw->dir)) {
if (p_cbw->total_bytes > CFG_TUD_MSC_EP_BUFSIZE) {
TU_LOG_DRV(" SCSI reject non READ10/WRITE10 with large data\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else {
// Didn't check for case 9 (Ho > Dn), which requires examining scsi command first
// but it is OK to just receive data then responded with failed status
TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_epbuf.buf, (uint16_t) p_msc->total_len));
}
} else {
// First process if it is a built-in commands
int32_t resplen = proc_builtin_scsi(p_cbw->lun, p_cbw->command, _mscd_epbuf.buf, CFG_TUD_MSC_EP_BUFSIZE);
// Invoke user callback if not built-in
if ((resplen < 0) && (p_msc->sense_key == 0)) {
resplen = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_epbuf.buf, (uint16_t)p_msc->total_len);
}
if (resplen < 0) {
// unsupported command
TU_LOG_DRV(" SCSI unsupported or failed command\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else if (resplen == 0) {
if (p_cbw->total_bytes) {
// 6.7 The 13 Cases: case 4 (Hi > Dn)
// TU_LOG(MSC_DEBUG, " SCSI case 4 (Hi > Dn): %lu\r\n", p_cbw->total_bytes);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else {
// case 1 Hn = Dn: all good
p_msc->stage = MSC_STAGE_STATUS;
}
} else {
if (p_cbw->total_bytes == 0) {
// 6.7 The 13 Cases: case 2 (Hn < Di)
// TU_LOG(MSC_DEBUG, " SCSI case 2 (Hn < Di): %lu\r\n", p_cbw->total_bytes);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else {
// cannot return more than host expect
p_msc->total_len = tu_min32((uint32_t)resplen, p_cbw->total_bytes);
TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_epbuf.buf, (uint16_t) p_msc->total_len));
}
}
}
}
break;
case MSC_STAGE_DATA:
TU_LOG_DRV(" SCSI Data [Lun%u]\r\n", p_cbw->lun);
//TU_LOG_MEM(MSC_DEBUG, _mscd_epbuf.buf, xferred_bytes, 2);
if (SCSI_CMD_READ_10 == p_cbw->command[0]) {
p_msc->xferred_len += xferred_bytes;
if ( p_msc->xferred_len >= p_msc->total_len ) {
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
}else {
proc_read10_cmd(rhport, p_msc);
}
} else if (SCSI_CMD_WRITE_10 == p_cbw->command[0]) {
proc_write10_new_data(rhport, p_msc, xferred_bytes);
} else {
p_msc->xferred_len += xferred_bytes;
// OUT transfer, invoke callback if needed
if ( !is_data_in(p_cbw->dir) ) {
int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_epbuf.buf, (uint16_t) p_msc->total_len);
if ( cb_result < 0 ) {
// unsupported command
TU_LOG_DRV(" SCSI unsupported command\r\n");
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
}else {
// TODO haven't implement this scenario any further yet
}
}
if ( p_msc->xferred_len >= p_msc->total_len ) {
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
} else {
// This scenario with command that take more than one transfer is already rejected at Command stage
TU_BREAKPOINT();
}
}
break;
case MSC_STAGE_STATUS:
// processed immediately after this switch, supposedly to be empty
break;
case MSC_STAGE_STATUS_SENT:
// Wait for the Status phase to complete
if ((ep_addr == p_msc->ep_in) && (xferred_bytes == sizeof(msc_csw_t))) {
TU_LOG_DRV(" SCSI Status [Lun%u] = %u\r\n", p_cbw->lun, p_csw->status);
// TU_LOG_MEM(MSC_DEBUG, p_csw, xferred_bytes, 2);
// Invoke complete callback if defined
// Note: There is racing issue with samd51 + qspi flash testing with arduino
// if complete_cb() is invoked after queuing the status.
switch (p_cbw->command[0]) {
case SCSI_CMD_READ_10:
if (tud_msc_read10_complete_cb) {
tud_msc_read10_complete_cb(p_cbw->lun);
}
break;
case SCSI_CMD_WRITE_10:
if (tud_msc_write10_complete_cb) {
tud_msc_write10_complete_cb(p_cbw->lun);
}
break;
default:
if (tud_msc_scsi_complete_cb) {
tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command);
}
break;
}
TU_ASSERT(prepare_cbw(rhport, p_msc));
} else {
// Any xfer ended here is consider unknown error, ignore it
TU_LOG1(" Warning expect SCSI Status but received unknown data\r\n");
}
break;
default: break;
}
if (p_msc->stage == MSC_STAGE_STATUS) {
// skip status if epin is currently stalled, will do it when received Clear Stall request
if (!usbd_edpt_stalled(rhport, p_msc->ep_in)) {
if ((p_cbw->total_bytes > p_msc->xferred_len) && is_data_in(p_cbw->dir)) {
// 6.7 The 13 Cases: case 5 (Hi > Di): STALL before status
// TU_LOG(MSC_DEBUG, " SCSI case 5 (Hi > Di): %lu > %lu\r\n", p_cbw->total_bytes, p_msc->xferred_len);
usbd_edpt_stall(rhport, p_msc->ep_in);
} else {
TU_ASSERT(send_csw(rhport, p_msc));
}
}
#if TU_CHECK_MCU(OPT_MCU_CXD56)
// WORKAROUND: cxd56 has its own nuttx usb stack which does not forward Set/ClearFeature(Endpoint) to DCD.
// There is no way for us to know when EP is un-stall, therefore we will unconditionally un-stall here and
// hope everything will work
if ( usbd_edpt_stalled(rhport, p_msc->ep_in) ) {
usbd_edpt_clear_stall(rhport, p_msc->ep_in);
send_csw(rhport, p_msc);
}
#endif
}
return true;
}
/*------------------------------------------------------------------*/
/* SCSI Command Process
*------------------------------------------------------------------*/
// return response's length (copied to buffer). Negative if it is not an built-in command or indicate Failed status (CSW)
// In case of a failed status, sense key must be set for reason of failure
static int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buffer, uint32_t bufsize) {
(void)bufsize; // TODO refractor later
int32_t resplen;
mscd_interface_t* p_msc = &_mscd_itf;
switch (scsi_cmd[0]) {
case SCSI_CMD_TEST_UNIT_READY:
resplen = 0;
if (!tud_msc_test_unit_ready_cb(lun)) {
// Failed status response
resplen = -1;
// set default sense if not set by callback
if (p_msc->sense_key == 0) {
set_sense_medium_not_present(lun);
}
}
break;
case SCSI_CMD_START_STOP_UNIT:
resplen = 0;
if (tud_msc_start_stop_cb) {
scsi_start_stop_unit_t const* start_stop = (scsi_start_stop_unit_t const*)scsi_cmd;
if (!tud_msc_start_stop_cb(lun, start_stop->power_condition, start_stop->start, start_stop->load_eject)) {
// Failed status response
resplen = -1;
// set default sense if not set by callback
if (p_msc->sense_key == 0) {
set_sense_medium_not_present(lun);
}
}
}
break;
case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL:
resplen = 0;
if (tud_msc_prevent_allow_medium_removal_cb) {
scsi_prevent_allow_medium_removal_t const* prevent_allow = (scsi_prevent_allow_medium_removal_t const*)scsi_cmd;
if (!tud_msc_prevent_allow_medium_removal_cb(lun, prevent_allow->prohibit_removal, prevent_allow->control)) {
// Failed status response
resplen = -1;
// set default sense if not set by callback
if (p_msc->sense_key == 0) {
set_sense_medium_not_present(lun);
}
}
}
break;
case SCSI_CMD_READ_CAPACITY_10: {
uint32_t block_count;
uint32_t block_size;
uint16_t block_size_u16;
tud_msc_capacity_cb(lun, &block_count, &block_size_u16);
block_size = (uint32_t)block_size_u16;
// Invalid block size/count from callback, possibly unit is not ready
// stall this request, set sense key to NOT READY
if (block_count == 0 || block_size == 0) {
resplen = -1;
// set default sense if not set by callback
if (p_msc->sense_key == 0) {
set_sense_medium_not_present(lun);
}
} else {
scsi_read_capacity10_resp_t read_capa10;
read_capa10.last_lba = tu_htonl(block_count-1);
read_capa10.block_size = tu_htonl(block_size);
resplen = sizeof(read_capa10);
TU_VERIFY(0 == tu_memcpy_s(buffer, bufsize, &read_capa10, (size_t) resplen));
}
}
break;
case SCSI_CMD_READ_FORMAT_CAPACITY: {
scsi_read_format_capacity_data_t read_fmt_capa =
{
.list_length = 8,
.block_num = 0,
.descriptor_type = 2, // formatted media
.block_size_u16 = 0
};
uint32_t block_count;
uint16_t block_size;
tud_msc_capacity_cb(lun, &block_count, &block_size);
// Invalid block size/count from callback, possibly unit is not ready
// stall this request, set sense key to NOT READY
if (block_count == 0 || block_size == 0) {
resplen = -1;
// set default sense if not set by callback
if (p_msc->sense_key == 0) {
set_sense_medium_not_present(lun);
}
} else {
read_fmt_capa.block_num = tu_htonl(block_count);
read_fmt_capa.block_size_u16 = tu_htons(block_size);
resplen = sizeof(read_fmt_capa);
TU_VERIFY(0 == tu_memcpy_s(buffer, bufsize, &read_fmt_capa, (size_t) resplen));
}
}
break;
case SCSI_CMD_INQUIRY: {
scsi_inquiry_resp_t inquiry_rsp =
{
.is_removable = 1,
.version = 2,
.response_data_format = 2,
.additional_length = sizeof(scsi_inquiry_resp_t) - 5,
};
// vendor_id, product_id, product_rev is space padded string
memset(inquiry_rsp.vendor_id , ' ', sizeof(inquiry_rsp.vendor_id));
memset(inquiry_rsp.product_id , ' ', sizeof(inquiry_rsp.product_id));
memset(inquiry_rsp.product_rev, ' ', sizeof(inquiry_rsp.product_rev));
tud_msc_inquiry_cb(lun, inquiry_rsp.vendor_id, inquiry_rsp.product_id, inquiry_rsp.product_rev);
resplen = sizeof(inquiry_rsp);
TU_VERIFY(0 == tu_memcpy_s(buffer, bufsize, &inquiry_rsp, (size_t) resplen));
}
break;
case SCSI_CMD_MODE_SENSE_6: {
scsi_mode_sense6_resp_t mode_resp =
{
.data_len = 3,
.medium_type = 0,
.write_protected = false,
.reserved = 0,
.block_descriptor_len = 0 // no block descriptor are included
};
bool writable = true;
if (tud_msc_is_writable_cb) {
writable = tud_msc_is_writable_cb(lun);
}
mode_resp.write_protected = !writable;
resplen = sizeof(mode_resp);
TU_VERIFY(0 == tu_memcpy_s(buffer, bufsize, &mode_resp, (size_t) resplen));
}
break;
case SCSI_CMD_REQUEST_SENSE: {
scsi_sense_fixed_resp_t sense_rsp =
{
.response_code = 0x70, // current, fixed format
.valid = 1
};
sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8;
sense_rsp.sense_key = (uint8_t)(p_msc->sense_key & 0x0F);
sense_rsp.add_sense_code = p_msc->add_sense_code;
sense_rsp.add_sense_qualifier = p_msc->add_sense_qualifier;
resplen = sizeof(sense_rsp);
TU_VERIFY(0 == tu_memcpy_s(buffer, bufsize, &sense_rsp, (size_t) resplen));
// request sense callback could overwrite the sense data
if (tud_msc_request_sense_cb) {
resplen = tud_msc_request_sense_cb(lun, buffer, (uint16_t)bufsize);
}
// Clear sense data after copy
tud_msc_set_sense(lun, 0, 0, 0);
}
break;
default: resplen = -1;
break;
}
return resplen;
}
static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc) {
msc_cbw_t const* p_cbw = &p_msc->cbw;
// block size already verified not zero
uint16_t const block_sz = rdwr10_get_blocksize(p_cbw);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
// remaining bytes capped at class buffer
int32_t nbytes = (int32_t)tu_min32(CFG_TUD_MSC_EP_BUFSIZE, p_cbw->total_bytes - p_msc->xferred_len);
// Application can consume smaller bytes
uint32_t const offset = p_msc->xferred_len % block_sz;
nbytes = tud_msc_read10_cb(p_cbw->lun, lba, offset, _mscd_epbuf.buf, (uint32_t)nbytes);
if (nbytes < 0) {
// negative means error -> endpoint is stalled & status in CSW set to failed
TU_LOG_DRV(" tud_msc_read10_cb() return -1\r\n");
// set sense
set_sense_medium_not_present(p_cbw->lun);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else if (nbytes == 0) {
// zero means not ready -> simulate an transfer complete so that this driver callback will fired again
dcd_event_xfer_complete(rhport, p_msc->ep_in, 0, XFER_RESULT_SUCCESS, false);
} else {
TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_in, _mscd_epbuf.buf, (uint16_t) nbytes),);
}
}
static void proc_write10_cmd(uint8_t rhport, mscd_interface_t* p_msc) {
msc_cbw_t const* p_cbw = &p_msc->cbw;
bool writable = true;
if (tud_msc_is_writable_cb) {
writable = tud_msc_is_writable_cb(p_cbw->lun);
}
if (!writable) {
// Not writable, complete this SCSI op with error
// Sense = Write protected
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
return;
}
// remaining bytes capped at class buffer
uint16_t nbytes = (uint16_t)tu_min32(CFG_TUD_MSC_EP_BUFSIZE, p_cbw->total_bytes - p_msc->xferred_len);
// Write10 callback will be called later when usb transfer complete
TU_ASSERT(usbd_edpt_xfer(rhport, p_msc->ep_out, _mscd_epbuf.buf, nbytes),);
}
// process new data arrived from WRITE10
static void proc_write10_new_data(uint8_t rhport, mscd_interface_t* p_msc, uint32_t xferred_bytes) {
msc_cbw_t const* p_cbw = &p_msc->cbw;
// block size already verified not zero
uint16_t const block_sz = rdwr10_get_blocksize(p_cbw);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
// Invoke callback to consume new data
uint32_t const offset = p_msc->xferred_len % block_sz;
int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, offset, _mscd_epbuf.buf, xferred_bytes);
if (nbytes < 0) {
// negative means error -> failed this scsi op
TU_LOG_DRV(" tud_msc_write10_cb() return -1\r\n");
// update actual byte before failed
p_msc->xferred_len += xferred_bytes;
// Set sense
set_sense_medium_not_present(p_cbw->lun);
fail_scsi_op(rhport, p_msc, MSC_CSW_STATUS_FAILED);
} else {
// Application consume less than what we got (including zero)
if ((uint32_t)nbytes < xferred_bytes) {
uint32_t const left_over = xferred_bytes - (uint32_t)nbytes;
if (nbytes > 0) {
p_msc->xferred_len += (uint16_t)nbytes;
memmove(_mscd_epbuf.buf, _mscd_epbuf.buf + nbytes, left_over);
}
// simulate an transfer complete with adjusted parameters --> callback will be invoked with adjusted parameter
dcd_event_xfer_complete(rhport, p_msc->ep_out, left_over, XFER_RESULT_SUCCESS, false);
} else {
// Application consume all bytes in our buffer
p_msc->xferred_len += xferred_bytes;
if (p_msc->xferred_len >= p_msc->total_len) {
// Data Stage is complete
p_msc->stage = MSC_STAGE_STATUS;
} else {
// prepare to receive more data from host
proc_write10_cmd(rhport, p_msc);
}
}
}
}
#endif

View file

@ -0,0 +1,166 @@
/*
* 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 we receive the Prevent / Allow Medium Removal command
TU_ATTR_WEAK bool tud_msc_prevent_allow_medium_removal_cb(uint8_t lun, uint8_t prohibit_removal, uint8_t control);
// 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);
bool mscd_deinit (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,510 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if CFG_TUH_ENABLED && CFG_TUH_MSC
#include "host/usbh.h"
#include "host/usbh_pvt.h"
#include "msc_host.h"
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUH_MSC_LOG_LEVEL
#define CFG_TUH_MSC_LOG_LEVEL CFG_TUH_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUH_MSC_LOG_LEVEL, __VA_ARGS__)
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
enum {
MSC_STAGE_IDLE = 0,
MSC_STAGE_CMD,
MSC_STAGE_DATA,
MSC_STAGE_STATUS,
};
typedef struct {
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
uint8_t max_lun;
volatile bool configured; // Receive SET_CONFIGURE
volatile bool mounted; // Enumeration is complete
// SCSI command data
uint8_t stage;
void* buffer;
tuh_msc_complete_cb_t complete_cb;
uintptr_t complete_arg;
struct {
uint32_t block_size;
uint32_t block_count;
} capacity[CFG_TUH_MSC_MAXLUN];
} msch_interface_t;
typedef struct {
TUH_EPBUF_TYPE_DEF(msc_cbw_t, cbw);
TUH_EPBUF_TYPE_DEF(msc_csw_t, csw);
} msch_epbuf_t;
static msch_interface_t _msch_itf[CFG_TUH_DEVICE_MAX];
CFG_TUH_MEM_SECTION static msch_epbuf_t _msch_epbuf[CFG_TUH_DEVICE_MAX];
TU_ATTR_ALWAYS_INLINE static inline msch_interface_t* get_itf(uint8_t daddr) {
return &_msch_itf[daddr - 1];
}
TU_ATTR_ALWAYS_INLINE static inline msch_epbuf_t* get_epbuf(uint8_t daddr) {
return &_msch_epbuf[daddr - 1];
}
//--------------------------------------------------------------------+
// PUBLIC API
//--------------------------------------------------------------------+
uint8_t tuh_msc_get_maxlun(uint8_t dev_addr) {
msch_interface_t* p_msc = get_itf(dev_addr);
return p_msc->max_lun;
}
uint32_t tuh_msc_get_block_count(uint8_t dev_addr, uint8_t lun) {
msch_interface_t* p_msc = get_itf(dev_addr);
return p_msc->capacity[lun].block_count;
}
uint32_t tuh_msc_get_block_size(uint8_t dev_addr, uint8_t lun) {
msch_interface_t* p_msc = get_itf(dev_addr);
return p_msc->capacity[lun].block_size;
}
bool tuh_msc_mounted(uint8_t dev_addr) {
msch_interface_t* p_msc = get_itf(dev_addr);
return p_msc->mounted;
}
bool tuh_msc_ready(uint8_t dev_addr) {
msch_interface_t* p_msc = get_itf(dev_addr);
return p_msc->mounted && !usbh_edpt_busy(dev_addr, p_msc->ep_in) && !usbh_edpt_busy(dev_addr, p_msc->ep_out);
}
//--------------------------------------------------------------------+
// PUBLIC API: SCSI COMMAND
//--------------------------------------------------------------------+
static inline void cbw_init(msc_cbw_t* cbw, uint8_t lun) {
tu_memclr(cbw, sizeof(msc_cbw_t));
cbw->signature = MSC_CBW_SIGNATURE;
cbw->tag = 0x54555342; // TUSB
cbw->lun = lun;
}
bool tuh_msc_scsi_command(uint8_t daddr, msc_cbw_t const* cbw, void* data,
tuh_msc_complete_cb_t complete_cb, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(daddr);
TU_VERIFY(p_msc->configured);
// claim endpoint
TU_VERIFY(usbh_edpt_claim(daddr, p_msc->ep_out));
msch_epbuf_t* epbuf = get_epbuf(daddr);
epbuf->cbw = *cbw;
p_msc->buffer = data;
p_msc->complete_cb = complete_cb;
p_msc->complete_arg = arg;
p_msc->stage = MSC_STAGE_CMD;
if (!usbh_edpt_xfer(daddr, p_msc->ep_out, (uint8_t*) &epbuf->cbw, sizeof(msc_cbw_t))) {
usbh_edpt_release(daddr, p_msc->ep_out);
return false;
}
return true;
}
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, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->configured);
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = sizeof(scsi_read_capacity10_resp_t);
cbw.dir = TUSB_DIR_IN_MASK;
cbw.cmd_len = sizeof(scsi_read_capacity10_t);
cbw.command[0] = SCSI_CMD_READ_CAPACITY_10;
return tuh_msc_scsi_command(dev_addr, &cbw, response, complete_cb, arg);
}
bool tuh_msc_inquiry(uint8_t dev_addr, uint8_t lun, scsi_inquiry_resp_t* response,
tuh_msc_complete_cb_t complete_cb, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->mounted);
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = sizeof(scsi_inquiry_resp_t);
cbw.dir = TUSB_DIR_IN_MASK;
cbw.cmd_len = sizeof(scsi_inquiry_t);
scsi_inquiry_t const cmd_inquiry = {
.cmd_code = SCSI_CMD_INQUIRY,
.alloc_length = sizeof(scsi_inquiry_resp_t)
};
memcpy(cbw.command, &cmd_inquiry, cbw.cmd_len);
return tuh_msc_scsi_command(dev_addr, &cbw, response, complete_cb, arg);
}
bool tuh_msc_test_unit_ready(uint8_t dev_addr, uint8_t lun, tuh_msc_complete_cb_t complete_cb, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->configured);
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = 0;
cbw.dir = TUSB_DIR_OUT;
cbw.cmd_len = sizeof(scsi_test_unit_ready_t);
cbw.command[0] = SCSI_CMD_TEST_UNIT_READY;
cbw.command[1] = lun; // according to wiki TODO need verification
return tuh_msc_scsi_command(dev_addr, &cbw, NULL, complete_cb, arg);
}
bool tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, void* response,
tuh_msc_complete_cb_t complete_cb, uintptr_t arg) {
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = 18; // TODO sense response
cbw.dir = TUSB_DIR_IN_MASK;
cbw.cmd_len = sizeof(scsi_request_sense_t);
scsi_request_sense_t const cmd_request_sense = {
.cmd_code = SCSI_CMD_REQUEST_SENSE,
.alloc_length = 18
};
memcpy(cbw.command, &cmd_request_sense, cbw.cmd_len);
return tuh_msc_scsi_command(dev_addr, &cbw, response, complete_cb, arg);
}
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, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->mounted);
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = block_count * p_msc->capacity[lun].block_size;
cbw.dir = TUSB_DIR_IN_MASK;
cbw.cmd_len = sizeof(scsi_read10_t);
scsi_read10_t const cmd_read10 = {
.cmd_code = SCSI_CMD_READ_10,
.lba = tu_htonl(lba),
.block_count = tu_htons(block_count)
};
memcpy(cbw.command, &cmd_read10, cbw.cmd_len);
return tuh_msc_scsi_command(dev_addr, &cbw, buffer, complete_cb, arg);
}
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, uintptr_t arg) {
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->mounted);
msc_cbw_t cbw;
cbw_init(&cbw, lun);
cbw.total_bytes = block_count * p_msc->capacity[lun].block_size;
cbw.dir = TUSB_DIR_OUT;
cbw.cmd_len = sizeof(scsi_write10_t);
scsi_write10_t const cmd_write10 = {
.cmd_code = SCSI_CMD_WRITE_10,
.lba = tu_htonl(lba),
.block_count = tu_htons(block_count)
};
memcpy(cbw.command, &cmd_write10, cbw.cmd_len);
return tuh_msc_scsi_command(dev_addr, &cbw, (void*) (uintptr_t) buffer, complete_cb, arg);
}
#if 0
// MSC interface Reset (not used now)
bool tuh_msc_reset(uint8_t dev_addr) {
tusb_control_request_t const new_request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_OUT
},
.bRequest = MSC_REQ_RESET,
.wValue = 0,
.wIndex = p_msc->itf_num,
.wLength = 0
};
TU_ASSERT( usbh_control_xfer( dev_addr, &new_request, NULL ) );
}
#endif
//--------------------------------------------------------------------+
// CLASS-USBH API
//--------------------------------------------------------------------+
bool msch_init(void) {
TU_LOG_DRV("sizeof(msch_interface_t) = %u\r\n", sizeof(msch_interface_t));
TU_LOG_DRV("sizeof(msch_epbuf_t) = %u\r\n", sizeof(msch_epbuf_t));
tu_memclr(_msch_itf, sizeof(_msch_itf));
return true;
}
bool msch_deinit(void) {
return true;
}
void msch_close(uint8_t dev_addr) {
TU_VERIFY(dev_addr <= CFG_TUH_DEVICE_MAX,);
msch_interface_t* p_msc = get_itf(dev_addr);
TU_VERIFY(p_msc->configured,);
TU_LOG_DRV(" MSCh close addr = %d\r\n", dev_addr);
// invoke Application Callback
if (p_msc->mounted) {
if (tuh_msc_umount_cb) {
tuh_msc_umount_cb(dev_addr);
}
}
tu_memclr(p_msc, sizeof(msch_interface_t));
}
bool msch_xfer_cb(uint8_t dev_addr, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes) {
msch_interface_t* p_msc = get_itf(dev_addr);
msch_epbuf_t* epbuf = get_epbuf(dev_addr);
msc_cbw_t const * cbw = &epbuf->cbw;
msc_csw_t * csw = &epbuf->csw;
switch (p_msc->stage) {
case MSC_STAGE_CMD:
// Must be Command Block
TU_ASSERT(ep_addr == p_msc->ep_out && event == XFER_RESULT_SUCCESS && xferred_bytes == sizeof(msc_cbw_t));
if (cbw->total_bytes && p_msc->buffer) {
// Data stage if any
p_msc->stage = MSC_STAGE_DATA;
uint8_t const ep_data = (cbw->dir & TUSB_DIR_IN_MASK) ? p_msc->ep_in : p_msc->ep_out;
TU_ASSERT(usbh_edpt_xfer(dev_addr, ep_data, p_msc->buffer, (uint16_t) cbw->total_bytes));
break;
}
TU_ATTR_FALLTHROUGH; // fallthrough to status stage
case MSC_STAGE_DATA:
// Status stage
p_msc->stage = MSC_STAGE_STATUS;
TU_ASSERT(usbh_edpt_xfer(dev_addr, p_msc->ep_in, (uint8_t*) csw, (uint16_t) sizeof(msc_csw_t)));
break;
case MSC_STAGE_STATUS:
// SCSI op is complete
p_msc->stage = MSC_STAGE_IDLE;
if (p_msc->complete_cb) {
tuh_msc_complete_data_t const cb_data = {
.cbw = cbw,
.csw = csw,
.scsi_data = p_msc->buffer,
.user_arg = p_msc->complete_arg
};
p_msc->complete_cb(dev_addr, &cb_data);
}
break;
// unknown state
default:
break;
}
return true;
}
//--------------------------------------------------------------------+
// MSC Enumeration
//--------------------------------------------------------------------+
static void config_get_maxlun_complete(tuh_xfer_t* xfer);
static bool config_test_unit_ready_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data);
static bool config_request_sense_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data);
static bool config_read_capacity_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data);
bool msch_open(uint8_t rhport, uint8_t dev_addr, tusb_desc_interface_t const* desc_itf, uint16_t max_len) {
(void) rhport;
TU_VERIFY (MSC_SUBCLASS_SCSI == desc_itf->bInterfaceSubClass &&
MSC_PROTOCOL_BOT == desc_itf->bInterfaceProtocol);
// msc driver length is fixed
uint16_t const drv_len = (uint16_t) (sizeof(tusb_desc_interface_t) +
desc_itf->bNumEndpoints * sizeof(tusb_desc_endpoint_t));
TU_ASSERT(drv_len <= max_len);
msch_interface_t* p_msc = get_itf(dev_addr);
tusb_desc_endpoint_t const* ep_desc = (tusb_desc_endpoint_t const*) tu_desc_next(desc_itf);
for (uint32_t i = 0; i < 2; i++) {
TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType && TUSB_XFER_BULK == ep_desc->bmAttributes.xfer);
TU_ASSERT(tuh_edpt_open(dev_addr, ep_desc));
if (TUSB_DIR_IN == tu_edpt_dir(ep_desc->bEndpointAddress)) {
p_msc->ep_in = ep_desc->bEndpointAddress;
} else {
p_msc->ep_out = ep_desc->bEndpointAddress;
}
ep_desc = (tusb_desc_endpoint_t const*) tu_desc_next(ep_desc);
}
p_msc->itf_num = desc_itf->bInterfaceNumber;
return true;
}
bool msch_set_config(uint8_t daddr, uint8_t itf_num) {
msch_interface_t* p_msc = get_itf(daddr);
TU_ASSERT(p_msc->itf_num == itf_num);
p_msc->configured = true;
//------------- Get Max Lun -------------//
TU_LOG_DRV("MSC Get Max Lun\r\n");
tusb_control_request_t const request = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = MSC_REQ_GET_MAX_LUN,
.wValue = 0,
.wIndex = itf_num,
.wLength = 1
};
uint8_t* enum_buf = usbh_get_enum_buf();
tuh_xfer_t xfer = {
.daddr = daddr,
.ep_addr = 0,
.setup = &request,
.buffer = enum_buf,
.complete_cb = config_get_maxlun_complete,
.user_data = 0
};
TU_ASSERT(tuh_control_xfer(&xfer));
return true;
}
static void config_get_maxlun_complete(tuh_xfer_t* xfer) {
uint8_t const daddr = xfer->daddr;
msch_interface_t* p_msc = get_itf(daddr);
// MAXLUN's response is minus 1 by specs, STALL means 1
if (XFER_RESULT_SUCCESS == xfer->result) {
uint8_t* enum_buf = usbh_get_enum_buf();
p_msc->max_lun = enum_buf[0] + 1;
} else {
p_msc->max_lun = 1;
}
TU_LOG_DRV(" Max LUN = %u\r\n", p_msc->max_lun);
// TODO multiple LUN support
TU_LOG_DRV("SCSI Test Unit Ready\r\n");
uint8_t const lun = 0;
tuh_msc_test_unit_ready(daddr, lun, config_test_unit_ready_complete, 0);
}
static bool config_test_unit_ready_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data) {
msc_cbw_t const* cbw = cb_data->cbw;
msc_csw_t const* csw = cb_data->csw;
uint8_t* enum_buf = usbh_get_enum_buf();
if (csw->status == 0) {
// Unit is ready, read its capacity
TU_LOG_DRV("SCSI Read Capacity\r\n");
tuh_msc_read_capacity(dev_addr, cbw->lun, (scsi_read_capacity10_resp_t*) (uintptr_t) enum_buf,
config_read_capacity_complete, 0);
} else {
// Note: During enumeration, some device fails Test Unit Ready and require a few retries
// with Request Sense to start working !!
// TODO limit number of retries
TU_LOG_DRV("SCSI Request Sense\r\n");
TU_ASSERT(tuh_msc_request_sense(dev_addr, cbw->lun, enum_buf, config_request_sense_complete, 0));
}
return true;
}
static bool config_request_sense_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data) {
msc_cbw_t const* cbw = cb_data->cbw;
msc_csw_t const* csw = cb_data->csw;
TU_ASSERT(csw->status == 0);
TU_ASSERT(tuh_msc_test_unit_ready(dev_addr, cbw->lun, config_test_unit_ready_complete, 0));
return true;
}
static bool config_read_capacity_complete(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data) {
msc_cbw_t const* cbw = cb_data->cbw;
msc_csw_t const* csw = cb_data->csw;
TU_ASSERT(csw->status == 0);
msch_interface_t* p_msc = get_itf(dev_addr);
uint8_t* enum_buf = usbh_get_enum_buf();
// Capacity response field: Block size and Last LBA are both Big-Endian
scsi_read_capacity10_resp_t* resp = (scsi_read_capacity10_resp_t*) (uintptr_t) enum_buf;
p_msc->capacity[cbw->lun].block_count = tu_ntohl(resp->last_lba) + 1;
p_msc->capacity[cbw->lun].block_size = tu_ntohl(resp->block_size);
// Mark enumeration is complete
p_msc->mounted = true;
if (tuh_msc_mount_cb) {
tuh_msc_mount_cb(dev_addr);
}
// notify usbh that driver enumeration is complete
usbh_driver_set_config_complete(dev_addr, p_msc->itf_num);
return true;
}
#endif

View file

@ -0,0 +1,132 @@
/*
* 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 struct {
msc_cbw_t const* cbw; // SCSI command
msc_csw_t const* csw; // SCSI status
void* scsi_data; // SCSI Data
uintptr_t user_arg; // user argument
}tuh_msc_complete_data_t;
typedef bool (*tuh_msc_complete_cb_t)(uint8_t dev_addr, tuh_msc_complete_data_t const* cb_data);
//--------------------------------------------------------------------+
// 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.
// NOTE: buffer must be accessible by USB/DMA controller, aligned correctly and multiple of cache line if enabled
bool tuh_msc_scsi_command(uint8_t daddr, msc_cbw_t const* cbw, void* data, tuh_msc_complete_cb_t complete_cb, uintptr_t arg);
// Perform SCSI Inquiry command
// Complete callback is invoked when SCSI op is complete.
// NOTE: response must be accessible by USB/DMA controller, aligned correctly and multiple of cache line if enabled
bool tuh_msc_inquiry(uint8_t dev_addr, uint8_t lun, scsi_inquiry_resp_t* response, tuh_msc_complete_cb_t complete_cb, uintptr_t arg);
// 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, uintptr_t arg);
// Perform SCSI Request Sense 10 command
// Complete callback is invoked when SCSI op is complete.
// NOTE: response must be accessible by USB/DMA controller, aligned correctly and multiple of cache line if enabled
bool tuh_msc_request_sense(uint8_t dev_addr, uint8_t lun, void *response, tuh_msc_complete_cb_t complete_cb, uintptr_t arg);
// Perform SCSI Read 10 command. Read n blocks starting from LBA to buffer
// Complete callback is invoked when SCSI op is complete.
// NOTE: buffer must be accessible by USB/DMA controller, aligned correctly and multiple of cache line if enabled
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, uintptr_t arg);
// Perform SCSI Write 10 command. Write n blocks starting from LBA to device
// Complete callback is invoked when SCSI op is complete.
// NOTE: buffer must be accessible by USB/DMA controller, aligned correctly and multiple of cache line if enabled
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, uintptr_t arg);
// 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, uintptr_t arg);
//------------- 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
//--------------------------------------------------------------------+
bool msch_init (void);
bool msch_deinit (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 daddr, 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

View file

@ -0,0 +1,401 @@
/*
* 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.
*/
#include "tusb_option.h"
#if ( CFG_TUD_ENABLED && CFG_TUD_ECM_RNDIS )
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "net_device.h"
#include "rndis_protocol.h"
extern void rndis_class_set_handler(uint8_t *data, int size); /* found in ./misc/networking/rndis_reports.c */
#define CFG_TUD_NET_PACKET_PREFIX_LEN sizeof(rndis_data_packet_t)
#define CFG_TUD_NET_PACKET_SUFFIX_LEN 0
#define NETD_PACKET_SIZE (CFG_TUD_NET_PACKET_PREFIX_LEN + CFG_TUD_NET_MTU + CFG_TUD_NET_PACKET_PREFIX_LEN)
#define NETD_CONTROL_SIZE 120
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t itf_num; // Index number of Management Interface, +1 for Data Interface
uint8_t itf_data_alt; // Alternate setting of Data Interface. 0 : inactive, 1 : active
uint8_t ep_notif;
uint8_t ep_in;
uint8_t ep_out;
bool ecm_mode;
// Endpoint descriptor use to open/close when receiving SetInterface
// TODO since configuration descriptor may not be long-lived memory, we should
// keep a copy of endpoint attribute instead
uint8_t const * ecm_desc_epdata;
} netd_interface_t;
typedef struct ecm_notify_struct {
tusb_control_request_t header;
uint32_t downlink, uplink;
} ecm_notify_t;
typedef struct {
TUD_EPBUF_DEF(rx, NETD_PACKET_SIZE);
TUD_EPBUF_DEF(tx, NETD_PACKET_SIZE);
TUD_EPBUF_DEF(notify, sizeof(ecm_notify_t));
TUD_EPBUF_DEF(ctrl, NETD_CONTROL_SIZE);
} netd_epbuf_t;
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
static netd_interface_t _netd_itf;
CFG_TUD_MEM_SECTION static netd_epbuf_t _netd_epbuf;
static bool can_xmit;
void tud_network_recv_renew(void) {
usbd_edpt_xfer(0, _netd_itf.ep_out, _netd_epbuf.rx, NETD_PACKET_SIZE);
}
static void do_in_xfer(uint8_t *buf, uint16_t len) {
can_xmit = false;
usbd_edpt_xfer(0, _netd_itf.ep_in, buf, len);
}
void netd_report(uint8_t *buf, uint16_t len) {
const uint8_t rhport = 0;
len = tu_min16(len, sizeof(ecm_notify_t));
TU_VERIFY(usbd_edpt_claim(rhport, _netd_itf.ep_notif), );
memcpy(_netd_epbuf.notify, buf, len);
usbd_edpt_xfer(rhport, _netd_itf.ep_notif, _netd_epbuf.notify, len);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void netd_init(void) {
tu_memclr(&_netd_itf, sizeof(_netd_itf));
}
bool netd_deinit(void) {
return true;
}
void netd_reset(uint8_t rhport) {
(void) rhport;
netd_init();
}
uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len) {
bool const is_rndis = (TUD_RNDIS_ITF_CLASS == itf_desc->bInterfaceClass &&
TUD_RNDIS_ITF_SUBCLASS == itf_desc->bInterfaceSubClass &&
TUD_RNDIS_ITF_PROTOCOL == itf_desc->bInterfaceProtocol);
bool const is_ecm = (TUSB_CLASS_CDC == itf_desc->bInterfaceClass &&
CDC_COMM_SUBCLASS_ETHERNET_CONTROL_MODEL == itf_desc->bInterfaceSubClass &&
0x00 == itf_desc->bInterfaceProtocol);
TU_VERIFY(is_rndis || is_ecm, 0);
// confirm interface hasn't already been allocated
TU_ASSERT(0 == _netd_itf.ep_notif, 0);
// sanity check the descriptor
_netd_itf.ecm_mode = is_ecm;
//------------- Management Interface -------------//
_netd_itf.itf_num = itf_desc->bInterfaceNumber;
uint16_t drv_len = sizeof(tusb_desc_interface_t);
uint8_t const * p_desc = tu_desc_next( itf_desc );
// Communication Functional Descriptors
while (TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) && drv_len <= max_len) {
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// notification endpoint (if any)
if (TUSB_DESC_ENDPOINT == tu_desc_type(p_desc)) {
TU_ASSERT(usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), 0);
_netd_itf.ep_notif = ((tusb_desc_endpoint_t const*)p_desc)->bEndpointAddress;
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
//------------- Data Interface -------------//
// - RNDIS Data followed immediately by a pair of endpoints
// - CDC-ECM data interface has 2 alternate settings
// - 0 : zero endpoints for inactive (default)
// - 1 : IN & OUT endpoints for active networking
TU_ASSERT(TUSB_DESC_INTERFACE == tu_desc_type(p_desc), 0);
do {
tusb_desc_interface_t const * data_itf_desc = (tusb_desc_interface_t const *) p_desc;
TU_ASSERT(TUSB_CLASS_CDC_DATA == data_itf_desc->bInterfaceClass, 0);
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
} while (_netd_itf.ecm_mode && (TUSB_DESC_INTERFACE == tu_desc_type(p_desc)) && (drv_len <= max_len));
// Pair of endpoints
TU_ASSERT(TUSB_DESC_ENDPOINT == tu_desc_type(p_desc), 0);
if (_netd_itf.ecm_mode) {
// ECM by default is in-active, save the endpoint attribute
// to open later when received setInterface
_netd_itf.ecm_desc_epdata = p_desc;
} else {
// Open endpoint pair for RNDIS
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &_netd_itf.ep_in), 0);
tud_network_init_cb();
// we are ready to transmit a packet
can_xmit = true;
// prepare for incoming packets
tud_network_recv_renew();
}
drv_len += 2*sizeof(tusb_desc_endpoint_t);
return drv_len;
}
static void ecm_report(bool nc) {
const ecm_notify_t ecm_notify_nc = {
.header = {
.bmRequestType = 0xA1,
.bRequest = 0, /* NETWORK_CONNECTION aka NetworkConnection */
.wValue = 1, /* Connected */
.wLength = 0,
},
};
const ecm_notify_t ecm_notify_csc = {
.header = {
.bmRequestType = 0xA1,
.bRequest = 0x2A, /* CONNECTION_SPEED_CHANGE aka ConnectionSpeedChange */
.wLength = 8,
},
.downlink = 9728000,
.uplink = 9728000,
};
ecm_notify_t notify = (nc) ? ecm_notify_nc : ecm_notify_csc;
notify.header.wIndex = _netd_itf.itf_num;
netd_report((uint8_t *)&notify, (nc) ? sizeof(notify.header) : sizeof(notify));
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool netd_control_xfer_cb (uint8_t rhport, uint8_t stage, tusb_control_request_t const * request) {
if (stage == CONTROL_STAGE_SETUP) {
switch (request->bmRequestType_bit.type) {
case TUSB_REQ_TYPE_STANDARD:
switch (request->bRequest) {
case TUSB_REQ_GET_INTERFACE: {
uint8_t const req_itfnum = (uint8_t)request->wIndex;
TU_VERIFY(_netd_itf.itf_num+1 == req_itfnum);
tud_control_xfer(rhport, request, &_netd_itf.itf_data_alt, 1);
}
break;
case TUSB_REQ_SET_INTERFACE: {
uint8_t const req_itfnum = (uint8_t)request->wIndex;
uint8_t const req_alt = (uint8_t)request->wValue;
// Only valid for Data Interface with Alternate is either 0 or 1
TU_VERIFY(_netd_itf.itf_num+1 == req_itfnum && req_alt < 2);
// ACM-ECM only: qequest to enable/disable network activities
TU_VERIFY(_netd_itf.ecm_mode);
_netd_itf.itf_data_alt = req_alt;
if (_netd_itf.itf_data_alt) {
// TODO since we don't actually close endpoint
// hack here to not re-open it
if (_netd_itf.ep_in == 0 && _netd_itf.ep_out == 0) {
TU_ASSERT(_netd_itf.ecm_desc_epdata);
TU_ASSERT(
usbd_open_edpt_pair(rhport, _netd_itf.ecm_desc_epdata, 2, TUSB_XFER_BULK, &_netd_itf.ep_out, &
_netd_itf.ep_in));
// TODO should be merge with RNDIS's after endpoint opened
// Also should have opposite callback for application to disable network !!
tud_network_init_cb();
can_xmit = true; // we are ready to transmit a packet
tud_network_recv_renew(); // prepare for incoming packets
}
} else {
// TODO close the endpoint pair
// For now pretend that we did, this should have no harm since host won't try to
// communicate with the endpoints again
// _netd_itf.ep_in = _netd_itf.ep_out = 0
}
tud_control_status(rhport, request);
}
break;
// unsupported request
default: return false;
}
break;
case TUSB_REQ_TYPE_CLASS:
TU_VERIFY(_netd_itf.itf_num == request->wIndex);
if (_netd_itf.ecm_mode) {
/* the only required CDC-ECM Management Element Request is SetEthernetPacketFilter */
if (0x43 /* SET_ETHERNET_PACKET_FILTER */ == request->bRequest) {
tud_control_xfer(rhport, request, NULL, 0);
ecm_report(true);
}
} else {
if (request->bmRequestType_bit.direction == TUSB_DIR_IN) {
rndis_generic_msg_t* rndis_msg = (rndis_generic_msg_t*)((void*)_netd_epbuf.ctrl);
uint32_t msglen = tu_le32toh(rndis_msg->MessageLength);
TU_ASSERT(msglen <= NETD_CONTROL_SIZE);
tud_control_xfer(rhport, request, _netd_epbuf.ctrl, (uint16_t)msglen);
} else {
tud_control_xfer(rhport, request, _netd_epbuf.ctrl, NETD_CONTROL_SIZE);
}
}
break;
// unsupported request
default: return false;
}
} else if (stage == CONTROL_STAGE_DATA) {
// Handle RNDIS class control OUT only
if (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS &&
request->bmRequestType_bit.direction == TUSB_DIR_OUT &&
_netd_itf.itf_num == request->wIndex) {
if (!_netd_itf.ecm_mode) {
rndis_class_set_handler(_netd_epbuf.ctrl, request->wLength);
}
}
}
return true;
}
static void handle_incoming_packet(uint32_t len) {
uint8_t* pnt = _netd_epbuf.rx;
uint32_t size = 0;
if (_netd_itf.ecm_mode) {
size = len;
} else {
rndis_data_packet_t* r = (rndis_data_packet_t*)((void*)pnt);
if (len >= sizeof(rndis_data_packet_t)) {
if ((r->MessageType == REMOTE_NDIS_PACKET_MSG) && (r->MessageLength <= len)) {
if ((r->DataOffset + offsetof(rndis_data_packet_t, DataOffset) + r->DataLength) <= len) {
pnt = &_netd_epbuf.rx[r->DataOffset + offsetof(rndis_data_packet_t, DataOffset)];
size = r->DataLength;
}
}
}
}
if (!tud_network_recv_cb(pnt, (uint16_t)size)) {
/* if a buffer was never handled by user code, we must renew on the user's behalf */
tud_network_recv_renew();
}
}
bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void)rhport;
(void)result;
/* new packet received */
if (ep_addr == _netd_itf.ep_out) {
handle_incoming_packet(xferred_bytes);
}
/* data transmission finished */
if (ep_addr == _netd_itf.ep_in) {
/* TinyUSB requires the class driver to implement ZLP (since ZLP usage is class-specific) */
if (xferred_bytes && (0 == (xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE))) {
do_in_xfer(NULL, 0); /* a ZLP is needed */
} else {
/* we're finally finished */
can_xmit = true;
}
}
if (_netd_itf.ecm_mode && (ep_addr == _netd_itf.ep_notif)) {
if (sizeof(tusb_control_request_t) == xferred_bytes) {
ecm_report(false);
}
}
return true;
}
bool tud_network_can_xmit(uint16_t size) {
(void)size;
return can_xmit;
}
void tud_network_xmit(void *ref, uint16_t arg) {
if (!can_xmit) {
return;
}
uint16_t len = (_netd_itf.ecm_mode) ? 0 : CFG_TUD_NET_PACKET_PREFIX_LEN;
uint8_t* data = _netd_epbuf.tx + len;
len += tud_network_xmit_cb(data, ref, arg);
if (!_netd_itf.ecm_mode) {
rndis_data_packet_t *hdr = (rndis_data_packet_t *) ((void*) _netd_epbuf.tx);
memset(hdr, 0, sizeof(rndis_data_packet_t));
hdr->MessageType = REMOTE_NDIS_PACKET_MSG;
hdr->MessageLength = len;
hdr->DataOffset = sizeof(rndis_data_packet_t) - offsetof(rndis_data_packet_t, DataOffset);
hdr->DataLength = len - sizeof(rndis_data_packet_t);
}
do_in_xfer(_netd_epbuf.tx, len);
}
#endif

View file

@ -0,0 +1,164 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2021, Ha Thach (tinyusb.org)
* Copyright (c) 2024, Hardy Griech
*
* 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"
// NTB buffers size for reception side, must be >> MTU to avoid TCP retransmission (driver issue ?)
// Linux use 2048 as minimal size
#ifndef CFG_TUD_NCM_OUT_NTB_MAX_SIZE
#define CFG_TUD_NCM_OUT_NTB_MAX_SIZE 3200
#endif
// NTB buffers size for reception side, must be > MTU
// Linux use 2048 as minimal size
#ifndef CFG_TUD_NCM_IN_NTB_MAX_SIZE
#define CFG_TUD_NCM_IN_NTB_MAX_SIZE 3200
#endif
// Number of NTB buffers for reception side
// Depending on the configuration, this parameter could be increased with the cost of additional RAM requirements
// On Full-Speed (RP2040) :
// 1 - good performance
// 2 - up to 30% more performance with iperf with small packets
// >2 - no performance gain
// On High-Speed (STM32F7) :
// No performance gain
#ifndef CFG_TUD_NCM_OUT_NTB_N
#define CFG_TUD_NCM_OUT_NTB_N 1
#endif
// Number of NTB buffers for transmission side
// Depending on the configuration, this parameter could be increased with the cost of additional RAM requirements
// On Full-Speed (RP2040) :
// 1 - good performance but SystemView shows lost events (on load test)
// 2 - up to 50% more performance with iperf with small packets, "tud_network_can_xmit: request blocked"
// happens from time to time with SystemView
// 3 - "tud_network_can_xmit: request blocked" never happens
// >3 - no performance gain
// On High-Speed (STM32F7) :
// No performance gain
#ifndef CFG_TUD_NCM_IN_NTB_N
#define CFG_TUD_NCM_IN_NTB_N 1
#endif
// How many datagrams it is allowed to put into an NTB for transmission side
#ifndef CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB
#define CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB 8
#endif
// This tells the host how many datagrams it is allowed to put into an NTB
#ifndef CFG_TUD_NCM_OUT_MAX_DATAGRAMS_PER_NTB
#define CFG_TUD_NCM_OUT_MAX_DATAGRAMS_PER_NTB 6
#endif
// 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;
#define NTH16_SIGNATURE 0x484D434E
#define NDP16_SIGNATURE_NCM0 0x304D434E
#define NDP16_SIGNATURE_NCM1 0x314D434E
typedef struct TU_ATTR_PACKED {
uint16_t wLength;
uint16_t bmNtbFormatsSupported;
uint32_t dwNtbInMaxSize;
uint16_t wNdbInDivisor;
uint16_t wNdbInPayloadRemainder;
uint16_t wNdbInAlignment;
uint16_t wReserved;
uint32_t dwNtbOutMaxSize;
uint16_t wNdbOutDivisor;
uint16_t wNdbOutPayloadRemainder;
uint16_t wNdbOutAlignment;
uint16_t wNtbOutMaxDatagrams;
} ntb_parameters_t;
typedef struct TU_ATTR_PACKED {
uint32_t dwSignature;
uint16_t wHeaderLength;
uint16_t wSequence;
uint16_t wBlockLength;
uint16_t wNdpIndex;
} nth16_t;
typedef struct TU_ATTR_PACKED {
uint16_t wDatagramIndex;
uint16_t wDatagramLength;
} ndp16_datagram_t;
typedef struct TU_ATTR_PACKED {
uint32_t dwSignature;
uint16_t wLength;
uint16_t wNextNdpIndex;
//ndp16_datagram_t datagram[];
} ndp16_t;
typedef union TU_ATTR_PACKED {
struct {
nth16_t nth;
ndp16_t ndp;
ndp16_datagram_t ndp_datagram[CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB + 1];
};
uint8_t data[CFG_TUD_NCM_IN_NTB_MAX_SIZE];
} xmit_ntb_t;
typedef union TU_ATTR_PACKED {
struct {
nth16_t nth;
// only the header is at a guaranteed position
};
uint8_t data[CFG_TUD_NCM_OUT_NTB_MAX_SIZE];
} recv_ntb_t;
typedef struct {
tusb_control_request_t header;
uint32_t downlink;
uint32_t uplink;
} ncm_notify_t;
#endif

View file

@ -0,0 +1,943 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
* Copyright (c) 2024 Hardy Griech
* Copyright (c) 2020 Jacob Berg Potter
* Copyright (c) 2020 Peter Lawrence
*
* 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.
*/
/**
* Small Glossary (from the spec)
* --------------
* Datagram - A collection of bytes forming a single item of information, passed as a unit from source to destination.
* NCM - Network Control Model
* NDP - NCM Datagram Pointer: NTB structure that delineates Datagrams (typically Ethernet frames) within an NTB
* NTB - NCM Transfer Block: a data structure for efficient USB encapsulation of one or more datagrams
* Each NTB is designed to be a single USB transfer
* NTH - NTB Header: a data structure at the front of each NTB, which provides the information needed to validate
* the NTB and begin decoding
*
* Some explanations
* -----------------
* - rhport is the USB port of the device, in most cases "0"
* - itf_data_alt if != 0 -> data xmit/recv are allowed (see spec)
* - ep_in IN endpoints take data from the device intended to go in to the host (the device transmits)
* - ep_out OUT endpoints send data out of the host to the device (the device receives)
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_NCM)
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "ncm.h"
#include "net_device.h"
// Level where CFG_TUSB_DEBUG must be at least for this driver is logged
#ifndef CFG_TUD_NCM_LOG_LEVEL
#define CFG_TUD_NCM_LOG_LEVEL CFG_TUD_LOG_LEVEL
#endif
#define TU_LOG_DRV(...) TU_LOG(CFG_TUD_NCM_LOG_LEVEL, __VA_ARGS__)
// Alignment must be 4
#define TUD_NCM_ALIGNMENT 4
// calculate alignment of xmit datagrams within an NTB
#define XMIT_ALIGN_OFFSET(x) ((TUD_NCM_ALIGNMENT - ((x) & (TUD_NCM_ALIGNMENT - 1))) & (TUD_NCM_ALIGNMENT - 1))
//-----------------------------------------------------------------------------
//
// Module global things
//
#define XMIT_NTB_N CFG_TUD_NCM_IN_NTB_N
#define RECV_NTB_N CFG_TUD_NCM_OUT_NTB_N
typedef struct {
// general
uint8_t ep_in; // endpoint for outgoing datagrams (naming is a little bit confusing)
uint8_t ep_out; // endpoint for incoming datagrams (naming is a little bit confusing)
uint8_t ep_notif; // endpoint for notifications
uint8_t itf_num; // interface number
uint8_t itf_data_alt; // ==0 -> no endpoints, i.e. no network traffic, ==1 -> normal operation with two endpoints (spec, chapter 5.3)
uint8_t rhport; // storage of \a rhport because some callbacks are done without it
// recv handling
recv_ntb_t *recv_free_ntb[RECV_NTB_N]; // free list of recv NTBs
recv_ntb_t *recv_ready_ntb[RECV_NTB_N]; // NTBs waiting for transmission to glue logic
recv_ntb_t *recv_tinyusb_ntb; // buffer for the running transfer TinyUSB -> driver
recv_ntb_t *recv_glue_ntb; // buffer for the running transfer driver -> glue logic
uint16_t recv_glue_ntb_datagram_ndx; // index into \a recv_glue_ntb_datagram
// xmit handling
xmit_ntb_t *xmit_free_ntb[XMIT_NTB_N]; // free list of xmit NTBs
xmit_ntb_t *xmit_ready_ntb[XMIT_NTB_N]; // NTBs waiting for transmission to TinyUSB
xmit_ntb_t *xmit_tinyusb_ntb; // buffer for the running transfer driver -> TinyUSB
xmit_ntb_t *xmit_glue_ntb; // buffer for the running transfer glue logic -> driver
uint16_t xmit_sequence; // NTB sequence counter
uint16_t xmit_glue_ntb_datagram_ndx; // index into \a xmit_glue_ntb_datagram
// notification handling
enum {
NOTIFICATION_SPEED,
NOTIFICATION_CONNECTED,
NOTIFICATION_DONE
} notification_xmit_state; // state of notification transmission
bool notification_xmit_is_running; // notification is currently transmitted
// misc
bool tud_network_recv_renew_active; // tud_network_recv_renew() is active (avoid recursive invocations)
bool tud_network_recv_renew_process_again; // tud_network_recv_renew() should process again
} ncm_interface_t;
typedef struct {
struct {
TUD_EPBUF_TYPE_DEF(recv_ntb_t, ntb);
} recv[RECV_NTB_N];
struct {
TUD_EPBUF_TYPE_DEF(xmit_ntb_t, ntb);
} xmit[XMIT_NTB_N];
TUD_EPBUF_TYPE_DEF(ncm_notify_t, epnotif);
} ncm_epbuf_t;
static ncm_interface_t ncm_interface;
CFG_TUD_MEM_SECTION static ncm_epbuf_t ncm_epbuf;
/**
* This is the NTB parameter structure
*
* \attention
* We are lucky, that byte order is correct
*/
TU_ATTR_ALIGNED(4) static const ntb_parameters_t ntb_parameters = {
.wLength = sizeof(ntb_parameters_t),
.bmNtbFormatsSupported = 0x01,// 16-bit NTB supported
.dwNtbInMaxSize = CFG_TUD_NCM_IN_NTB_MAX_SIZE,
.wNdbInDivisor = 1,
.wNdbInPayloadRemainder = 0,
.wNdbInAlignment = TUD_NCM_ALIGNMENT,
.wReserved = 0,
.dwNtbOutMaxSize = CFG_TUD_NCM_OUT_NTB_MAX_SIZE,
.wNdbOutDivisor = 1,
.wNdbOutPayloadRemainder = 0,
.wNdbOutAlignment = TUD_NCM_ALIGNMENT,
.wNtbOutMaxDatagrams = CFG_TUD_NCM_OUT_MAX_DATAGRAMS_PER_NTB,
};
// Some confusing remarks about wNtbOutMaxDatagrams...
// ==1 -> SystemView packets/s goes up to 2000 and events are lost during startup
// ==0 -> SystemView runs fine, iperf shows in wireshark a lot of error
// ==6 -> SystemView runs fine, iperf also
// >6 -> iperf starts to show errors
// -> 6 seems to be the best value. Why? Don't know, perhaps only on my system?
//
// iperf: for MSS in 100 200 400 800 1200 1450 1500; do iperf -c 192.168.14.1 -e -i 1 -M $MSS -l 8192 -P 1; sleep 2; done
// sysview: SYSTICKS_PER_SEC=35000, IDLE_US=1000, PRINT_MOD=1000
//
//-----------------------------------------------------------------------------
//
// everything about notifications
//
/**
* Transmit next notification to the host (if appropriate).
* Notifications are transferred to the host once during connection setup.
*/
static void notification_xmit(uint8_t rhport, bool force_next) {
TU_LOG_DRV("notification_xmit(%d, %d) - %d %d\n", force_next, rhport, ncm_interface.notification_xmit_state, ncm_interface.notification_xmit_is_running);
if (!force_next && ncm_interface.notification_xmit_is_running) {
return;
}
if (ncm_interface.notification_xmit_state == NOTIFICATION_SPEED) {
TU_LOG_DRV(" NOTIFICATION_SPEED\n");
ncm_notify_t notify_speed_change = {
.header = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = CDC_NOTIF_CONNECTION_SPEED_CHANGE,
.wValue = 0,
.wIndex = ncm_interface.itf_num,
.wLength = 8
}
};
if (tud_speed_get() == TUSB_SPEED_HIGH) {
notify_speed_change.downlink = 480000000;
notify_speed_change.uplink = 480000000;
} else {
notify_speed_change.downlink = 12000000;
notify_speed_change.uplink = 12000000;
}
uint16_t notif_len = sizeof(notify_speed_change.header) + notify_speed_change.header.wLength;
ncm_epbuf.epnotif = notify_speed_change;
usbd_edpt_xfer(rhport, ncm_interface.ep_notif, (uint8_t*) &ncm_epbuf.epnotif, notif_len);
ncm_interface.notification_xmit_state = NOTIFICATION_CONNECTED;
ncm_interface.notification_xmit_is_running = true;
} else if (ncm_interface.notification_xmit_state == NOTIFICATION_CONNECTED) {
TU_LOG_DRV(" NOTIFICATION_CONNECTED\n");
ncm_notify_t notify_connected = {
.header = {
.bmRequestType_bit = {
.recipient = TUSB_REQ_RCPT_INTERFACE,
.type = TUSB_REQ_TYPE_CLASS,
.direction = TUSB_DIR_IN
},
.bRequest = CDC_NOTIF_NETWORK_CONNECTION,
.wValue = 1 /* Connected */,
.wIndex = ncm_interface.itf_num,
.wLength = 0,
},
};
uint16_t notif_len = sizeof(notify_connected.header) + notify_connected.header.wLength;
ncm_epbuf.epnotif = notify_connected;
usbd_edpt_xfer(rhport, ncm_interface.ep_notif, (uint8_t *) &ncm_epbuf.epnotif, notif_len);
ncm_interface.notification_xmit_state = NOTIFICATION_DONE;
ncm_interface.notification_xmit_is_running = true;
} else {
TU_LOG_DRV(" NOTIFICATION_FINISHED\n");
}
} // notification_xmit
//-----------------------------------------------------------------------------
//
// everything about packet transmission (driver -> TinyUSB)
//
/**
* Put NTB into the transmitter free list.
*/
static void xmit_put_ntb_into_free_list(xmit_ntb_t *free_ntb) {
TU_LOG_DRV("xmit_put_ntb_into_free_list() - %p\n", ncm_interface.xmit_tinyusb_ntb);
if (free_ntb == NULL) { // can happen due to ZLPs
return;
}
for (int i = 0; i < XMIT_NTB_N; ++i) {
if (ncm_interface.xmit_free_ntb[i] == NULL) {
ncm_interface.xmit_free_ntb[i] = free_ntb;
return;
}
}
TU_LOG_DRV("(EE) xmit_put_ntb_into_free_list - no entry in free list\n");// this should not happen
} // xmit_put_ntb_into_free_list
/**
* Get an NTB from the free list
*/
static xmit_ntb_t *xmit_get_free_ntb(void) {
TU_LOG_DRV("xmit_get_free_ntb()\n");
for (int i = 0; i < XMIT_NTB_N; ++i) {
if (ncm_interface.xmit_free_ntb[i] != NULL) {
xmit_ntb_t *free = ncm_interface.xmit_free_ntb[i];
ncm_interface.xmit_free_ntb[i] = NULL;
return free;
}
}
return NULL;
} // xmit_get_free_ntb
/**
* Put a filled NTB into the ready list
*/
static void xmit_put_ntb_into_ready_list(xmit_ntb_t *ready_ntb) {
TU_LOG_DRV("xmit_put_ntb_into_ready_list(%p) %d\n", ready_ntb, ready_ntb->nth.wBlockLength);
for (int i = 0; i < XMIT_NTB_N; ++i) {
if (ncm_interface.xmit_ready_ntb[i] == NULL) {
ncm_interface.xmit_ready_ntb[i] = ready_ntb;
return;
}
}
TU_LOG_DRV("(EE) xmit_put_ntb_into_ready_list: ready list full\n");// this should not happen
} // xmit_put_ntb_into_ready_list
/**
* Get the next NTB from the ready list (and remove it from the list).
* If the ready list is empty, return NULL.
*/
static xmit_ntb_t *xmit_get_next_ready_ntb(void) {
xmit_ntb_t *r = NULL;
r = ncm_interface.xmit_ready_ntb[0];
memmove(ncm_interface.xmit_ready_ntb + 0, ncm_interface.xmit_ready_ntb + 1, sizeof(ncm_interface.xmit_ready_ntb) - sizeof(ncm_interface.xmit_ready_ntb[0]));
ncm_interface.xmit_ready_ntb[XMIT_NTB_N - 1] = NULL;
TU_LOG_DRV("recv_get_next_ready_ntb: %p\n", r);
return r;
} // xmit_get_next_ready_ntb
/**
* Transmit a ZLP if required
*
* \note
* Insertion of the ZLPs is a little bit different then described in the spec.
* But the below implementation actually works. Don't know if this is a spec
* or TinyUSB issue.
*
* \pre
* This must be called from netd_xfer_cb() so that ep_in is ready
*/
static bool xmit_insert_required_zlp(uint8_t rhport, uint32_t xferred_bytes) {
TU_LOG_DRV("xmit_insert_required_zlp(%d,%ld)\n", rhport, xferred_bytes);
if (xferred_bytes == 0 || xferred_bytes % CFG_TUD_NET_ENDPOINT_SIZE != 0) {
return false;
}
TU_ASSERT(ncm_interface.itf_data_alt == 1, false);
TU_ASSERT(!usbd_edpt_busy(rhport, ncm_interface.ep_in), false);
TU_LOG_DRV("xmit_insert_required_zlp! (%u)\n", (unsigned) xferred_bytes);
// start transmission of the ZLP
usbd_edpt_xfer(rhport, ncm_interface.ep_in, NULL, 0);
return true;
} // xmit_insert_required_zlp
/**
* Start transmission if it there is a waiting packet and if can be done from interface side.
*/
static void xmit_start_if_possible(uint8_t rhport) {
TU_LOG_DRV("xmit_start_if_possible()\n");
if (ncm_interface.xmit_tinyusb_ntb != NULL) {
TU_LOG_DRV(" !xmit_start_if_possible 1\n");
return;
}
if (ncm_interface.itf_data_alt != 1) {
TU_LOG_DRV("(EE) !xmit_start_if_possible 2\n");
return;
}
if (usbd_edpt_busy(rhport, ncm_interface.ep_in)) {
TU_LOG_DRV(" !xmit_start_if_possible 3\n");
return;
}
ncm_interface.xmit_tinyusb_ntb = xmit_get_next_ready_ntb();
if (ncm_interface.xmit_tinyusb_ntb == NULL) {
if (ncm_interface.xmit_glue_ntb == NULL || ncm_interface.xmit_glue_ntb_datagram_ndx == 0) {
// -> really nothing is waiting
return;
}
ncm_interface.xmit_tinyusb_ntb = ncm_interface.xmit_glue_ntb;
ncm_interface.xmit_glue_ntb = NULL;
}
#if CFG_TUD_NCM_LOG_LEVEL >= 3
{
uint16_t len = ncm_interface.xmit_tinyusb_ntb->nth.wBlockLength;
TU_LOG_BUF(3, ncm_interface.xmit_tinyusb_ntb->data[i], len);
}
#endif
if (ncm_interface.xmit_glue_ntb_datagram_ndx != 1) {
TU_LOG_DRV(">> %d %d\n", ncm_interface.xmit_tinyusb_ntb->nth.wBlockLength, ncm_interface.xmit_glue_ntb_datagram_ndx);
}
// Kick off an endpoint transfer
usbd_edpt_xfer(0, ncm_interface.ep_in, ncm_interface.xmit_tinyusb_ntb->data, ncm_interface.xmit_tinyusb_ntb->nth.wBlockLength);
} // xmit_start_if_possible
/**
* check if a new datagram fits into the current NTB
*/
static bool xmit_requested_datagram_fits_into_current_ntb(uint16_t datagram_size) {
TU_LOG_DRV("xmit_requested_datagram_fits_into_current_ntb(%d) - %p %p\n", datagram_size, ncm_interface.xmit_tinyusb_ntb, ncm_interface.xmit_glue_ntb);
if (ncm_interface.xmit_glue_ntb == NULL) {
return false;
}
if (ncm_interface.xmit_glue_ntb_datagram_ndx >= CFG_TUD_NCM_IN_MAX_DATAGRAMS_PER_NTB) {
return false;
}
if (ncm_interface.xmit_glue_ntb->nth.wBlockLength + datagram_size + XMIT_ALIGN_OFFSET(datagram_size) > CFG_TUD_NCM_OUT_NTB_MAX_SIZE) {
return false;
}
return true;
} // xmit_requested_datagram_fits_into_current_ntb
/**
* Setup an NTB for the glue logic
*/
static bool xmit_setup_next_glue_ntb(void) {
TU_LOG_DRV("xmit_setup_next_glue_ntb - %p\n", ncm_interface.xmit_glue_ntb);
if (ncm_interface.xmit_glue_ntb != NULL) {
// put NTB into waiting list (the new datagram did not fit in)
xmit_put_ntb_into_ready_list(ncm_interface.xmit_glue_ntb);
}
ncm_interface.xmit_glue_ntb = xmit_get_free_ntb();// get next buffer (if any)
if (ncm_interface.xmit_glue_ntb == NULL) {
TU_LOG_DRV(" xmit_setup_next_glue_ntb - nothing free\n");// should happen rarely
return false;
}
ncm_interface.xmit_glue_ntb_datagram_ndx = 0;
xmit_ntb_t *ntb = ncm_interface.xmit_glue_ntb;
// Fill in NTB header
ntb->nth.dwSignature = NTH16_SIGNATURE;
ntb->nth.wHeaderLength = sizeof(ntb->nth);
ntb->nth.wSequence = ncm_interface.xmit_sequence++;
ntb->nth.wBlockLength = sizeof(ntb->nth) + sizeof(ntb->ndp) + sizeof(ntb->ndp_datagram);
ntb->nth.wNdpIndex = sizeof(ntb->nth);
// Fill in NDP16 header and terminator
ntb->ndp.dwSignature = NDP16_SIGNATURE_NCM0;
ntb->ndp.wLength = sizeof(ntb->ndp) + sizeof(ntb->ndp_datagram);
ntb->ndp.wNextNdpIndex = 0;
memset(ntb->ndp_datagram, 0, sizeof(ntb->ndp_datagram));
return true;
} // xmit_setup_next_glue_ntb
//-----------------------------------------------------------------------------
//
// all the recv_*() stuff (TinyUSB -> driver -> glue logic)
//
/**
* Return pointer to an available receive buffer or NULL.
* Returned buffer (if any) has the size \a CFG_TUD_NCM_OUT_NTB_MAX_SIZE.
*/
static recv_ntb_t *recv_get_free_ntb(void) {
TU_LOG_DRV("recv_get_free_ntb()\n");
for (int i = 0; i < RECV_NTB_N; ++i) {
if (ncm_interface.recv_free_ntb[i] != NULL) {
recv_ntb_t *free = ncm_interface.recv_free_ntb[i];
ncm_interface.recv_free_ntb[i] = NULL;
return free;
}
}
return NULL;
} // recv_get_free_ntb
/**
* Get the next NTB from the ready list (and remove it from the list).
* If the ready list is empty, return NULL.
*/
static recv_ntb_t *recv_get_next_ready_ntb(void) {
recv_ntb_t *r = NULL;
r = ncm_interface.recv_ready_ntb[0];
memmove(ncm_interface.recv_ready_ntb + 0, ncm_interface.recv_ready_ntb + 1, sizeof(ncm_interface.recv_ready_ntb) - sizeof(ncm_interface.recv_ready_ntb[0]));
ncm_interface.recv_ready_ntb[RECV_NTB_N - 1] = NULL;
TU_LOG_DRV("recv_get_next_ready_ntb: %p\n", r);
return r;
} // recv_get_next_ready_ntb
/**
* Put NTB into the receiver free list.
*/
static void recv_put_ntb_into_free_list(recv_ntb_t *free_ntb) {
TU_LOG_DRV("recv_put_ntb_into_free_list(%p)\n", free_ntb);
for (int i = 0; i < RECV_NTB_N; ++i) {
if (ncm_interface.recv_free_ntb[i] == NULL) {
ncm_interface.recv_free_ntb[i] = free_ntb;
return;
}
}
TU_LOG_DRV("(EE) recv_put_ntb_into_free_list - no entry in free list\n");// this should not happen
} // recv_put_ntb_into_free_list
/**
* \a ready_ntb holds a validated NTB,
* put this buffer into the waiting list.
*/
static void recv_put_ntb_into_ready_list(recv_ntb_t *ready_ntb) {
TU_LOG_DRV("recv_put_ntb_into_ready_list(%p) %d\n", ready_ntb, ready_ntb->nth.wBlockLength);
for (int i = 0; i < RECV_NTB_N; ++i) {
if (ncm_interface.recv_ready_ntb[i] == NULL) {
ncm_interface.recv_ready_ntb[i] = ready_ntb;
return;
}
}
TU_LOG_DRV("(EE) recv_put_ntb_into_ready_list: ready list full\n");// this should not happen
} // recv_put_ntb_into_ready_list
/**
* If possible, start a new reception TinyUSB -> driver.
*/
static void recv_try_to_start_new_reception(uint8_t rhport) {
TU_LOG_DRV("recv_try_to_start_new_reception(%d)\n", rhport);
if (ncm_interface.itf_data_alt != 1) {
return;
}
if (ncm_interface.recv_tinyusb_ntb != NULL) {
return;
}
if (usbd_edpt_busy(rhport, ncm_interface.ep_out)) {
return;
}
ncm_interface.recv_tinyusb_ntb = recv_get_free_ntb();
if (ncm_interface.recv_tinyusb_ntb == NULL) {
return;
}
// initiate transfer
TU_LOG_DRV(" start reception\n");
bool r = usbd_edpt_xfer(rhport, ncm_interface.ep_out, ncm_interface.recv_tinyusb_ntb->data, CFG_TUD_NCM_OUT_NTB_MAX_SIZE);
if (!r) {
recv_put_ntb_into_free_list(ncm_interface.recv_tinyusb_ntb);
ncm_interface.recv_tinyusb_ntb = NULL;
}
} // recv_try_to_start_new_reception
/**
* Validate incoming datagram.
* \return true if valid
*
* \note
* \a ndp16->wNextNdpIndex != 0 is not supported
*/
static bool recv_validate_datagram(const recv_ntb_t *ntb, uint32_t len) {
const nth16_t *nth16 = &(ntb->nth);
TU_LOG_DRV("recv_validate_datagram(%p, %d)\n", ntb, (int) len);
// check header
if (nth16->wHeaderLength != sizeof(nth16_t)) {
TU_LOG_DRV("(EE) ill nth16 length: %d\n", nth16->wHeaderLength);
return false;
}
if (nth16->dwSignature != NTH16_SIGNATURE) {
TU_LOG_DRV("(EE) ill signature: 0x%08x\n", (unsigned) nth16->dwSignature);
return false;
}
if (len < sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)) {
TU_LOG_DRV("(EE) ill min len: %lu\n", len);
return false;
}
if (nth16->wBlockLength > len) {
TU_LOG_DRV("(EE) ill block length: %d > %lu\n", nth16->wBlockLength, len);
return false;
}
if (nth16->wBlockLength > CFG_TUD_NCM_OUT_NTB_MAX_SIZE) {
TU_LOG_DRV("(EE) ill block length2: %d > %d\n", nth16->wBlockLength, CFG_TUD_NCM_OUT_NTB_MAX_SIZE);
return false;
}
if (nth16->wNdpIndex < sizeof(nth16) || nth16->wNdpIndex > len - (sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t))) {
TU_LOG_DRV("(EE) ill position of first ndp: %d (%lu)\n", nth16->wNdpIndex, len);
return false;
}
// check (first) NDP(16)
const ndp16_t *ndp16 = (const ndp16_t *) (ntb->data + nth16->wNdpIndex);
if (ndp16->wLength < sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)) {
TU_LOG_DRV("(EE) ill ndp16 length: %d\n", ndp16->wLength);
return false;
}
if (ndp16->dwSignature != NDP16_SIGNATURE_NCM0 && ndp16->dwSignature != NDP16_SIGNATURE_NCM1) {
TU_LOG_DRV("(EE) ill signature: 0x%08x\n", (unsigned) ndp16->dwSignature);
return false;
}
if (ndp16->wNextNdpIndex != 0) {
TU_LOG_DRV("(EE) cannot handle wNextNdpIndex!=0 (%d)\n", ndp16->wNextNdpIndex);
return false;
}
const ndp16_datagram_t *ndp16_datagram = (const ndp16_datagram_t *) (ntb->data + nth16->wNdpIndex + sizeof(ndp16_t));
int ndx = 0;
uint16_t max_ndx = (uint16_t) ((ndp16->wLength - sizeof(ndp16_t)) / sizeof(ndp16_datagram_t));
if (max_ndx > 2) { // number of datagrams in NTB > 1
TU_LOG_DRV("<< %d (%d)\n", max_ndx - 1, ntb->nth.wBlockLength);
}
if (ndp16_datagram[max_ndx - 1].wDatagramIndex != 0 || ndp16_datagram[max_ndx - 1].wDatagramLength != 0) {
TU_LOG_DRV(" max_ndx != 0\n");
return false;
}
while (ndp16_datagram[ndx].wDatagramIndex != 0 && ndp16_datagram[ndx].wDatagramLength != 0) {
TU_LOG_DRV(" << %d %d\n", ndp16_datagram[ndx].wDatagramIndex, ndp16_datagram[ndx].wDatagramLength);
if (ndp16_datagram[ndx].wDatagramIndex > len) {
TU_LOG_DRV("(EE) ill start of datagram[%d]: %d (%lu)\n", ndx, ndp16_datagram[ndx].wDatagramIndex, len);
return false;
}
if (ndp16_datagram[ndx].wDatagramIndex + ndp16_datagram[ndx].wDatagramLength > len) {
TU_LOG_DRV("(EE) ill end of datagram[%d]: %d (%lu)\n", ndx, ndp16_datagram[ndx].wDatagramIndex + ndp16_datagram[ndx].wDatagramLength, len);
return false;
}
++ndx;
}
#if CFG_TUD_NCM_LOG_LEVEL >= 3
TU_LOG_BUF(3, ntb->data[i], len);
#endif
// -> ntb contains a valid packet structure
// ok... I did not check for garbage within the datagram indices...
return true;
} // recv_validate_datagram
/**
* Transfer the next (pending) datagram to the glue logic and return receive buffer if empty.
*/
static void recv_transfer_datagram_to_glue_logic(void) {
TU_LOG_DRV("recv_transfer_datagram_to_glue_logic()\n");
if (ncm_interface.recv_glue_ntb == NULL) {
ncm_interface.recv_glue_ntb = recv_get_next_ready_ntb();
TU_LOG_DRV(" new buffer for glue logic: %p\n", ncm_interface.recv_glue_ntb);
ncm_interface.recv_glue_ntb_datagram_ndx = 0;
}
if (ncm_interface.recv_glue_ntb != NULL) {
const ndp16_datagram_t *ndp16_datagram = (ndp16_datagram_t *) (ncm_interface.recv_glue_ntb->data + ncm_interface.recv_glue_ntb->nth.wNdpIndex + sizeof(ndp16_t));
if (ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx].wDatagramIndex == 0) {
TU_LOG_DRV("(EE) SOMETHING WENT WRONG 1\n");
} else if (ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx].wDatagramLength == 0) {
TU_LOG_DRV("(EE) SOMETHING WENT WRONG 2\n");
} else {
uint16_t datagramIndex = ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx].wDatagramIndex;
uint16_t datagramLength = ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx].wDatagramLength;
TU_LOG_DRV(" recv[%d] - %d %d\n", ncm_interface.recv_glue_ntb_datagram_ndx, datagramIndex, datagramLength);
if (tud_network_recv_cb(ncm_interface.recv_glue_ntb->data + datagramIndex, datagramLength)) {
// send datagram successfully to glue logic
TU_LOG_DRV(" OK\n");
datagramIndex = ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx + 1].wDatagramIndex;
datagramLength = ndp16_datagram[ncm_interface.recv_glue_ntb_datagram_ndx + 1].wDatagramLength;
if (datagramIndex != 0 && datagramLength != 0) {
// -> next datagram
++ncm_interface.recv_glue_ntb_datagram_ndx;
} else {
// end of datagrams reached
recv_put_ntb_into_free_list(ncm_interface.recv_glue_ntb);
ncm_interface.recv_glue_ntb = NULL;
}
}
}
}
} // recv_transfer_datagram_to_glue_logic
//-----------------------------------------------------------------------------
//
// all the tud_network_*() stuff (glue logic -> driver)
//
/**
* Check if the glue logic is allowed to call tud_network_xmit().
* This function also fetches a next buffer if required, so that tud_network_xmit() is ready for copy
* and transmission operation.
*/
bool tud_network_can_xmit(uint16_t size) {
TU_LOG_DRV("tud_network_can_xmit(%d)\n", size);
TU_ASSERT(size <= CFG_TUD_NCM_OUT_NTB_MAX_SIZE - (sizeof(nth16_t) + sizeof(ndp16_t) + 2 * sizeof(ndp16_datagram_t)), false);
if (xmit_requested_datagram_fits_into_current_ntb(size) || xmit_setup_next_glue_ntb()) {
// -> everything is fine
return true;
}
xmit_start_if_possible(ncm_interface.rhport);
TU_LOG_DRV("(II) tud_network_can_xmit: request blocked\n");// could happen if all xmit buffers are full (but should happen rarely)
return false;
} // tud_network_can_xmit
/**
* Put a datagram into a waiting NTB.
* If currently no transmission is started, then initiate transmission.
*/
void tud_network_xmit(void *ref, uint16_t arg) {
TU_LOG_DRV("tud_network_xmit(%p, %d)\n", ref, arg);
if (ncm_interface.xmit_glue_ntb == NULL) {
TU_LOG_DRV("(EE) tud_network_xmit: no buffer\n");// must not happen (really)
return;
}
xmit_ntb_t *ntb = ncm_interface.xmit_glue_ntb;
// copy new datagram to the end of the current NTB
uint16_t size = tud_network_xmit_cb(ntb->data + ntb->nth.wBlockLength, ref, arg);
// correct NTB internals
ntb->ndp_datagram[ncm_interface.xmit_glue_ntb_datagram_ndx].wDatagramIndex = ntb->nth.wBlockLength;
ntb->ndp_datagram[ncm_interface.xmit_glue_ntb_datagram_ndx].wDatagramLength = size;
ncm_interface.xmit_glue_ntb_datagram_ndx += 1;
ntb->nth.wBlockLength += (uint16_t) (size + XMIT_ALIGN_OFFSET(size));
if (ntb->nth.wBlockLength > CFG_TUD_NCM_OUT_NTB_MAX_SIZE) {
TU_LOG_DRV("(EE) tud_network_xmit: buffer overflow\n"); // must not happen (really)
return;
}
xmit_start_if_possible(ncm_interface.rhport);
} // tud_network_xmit
/**
* Keep the receive logic busy and transfer pending packets to the glue logic.
* Avoid recursive calls due to wrong expectations of the net glue logic,
* see https://github.com/hathach/tinyusb/issues/2711
*/
void tud_network_recv_renew(void) {
TU_LOG_DRV("tud_network_recv_renew()\n");
ncm_interface.tud_network_recv_renew_process_again = true;
if (ncm_interface.tud_network_recv_renew_active) {
TU_LOG_DRV("Re-entrant into tud_network_recv_renew, will process later\n");
return;
}
while (ncm_interface.tud_network_recv_renew_process_again) {
ncm_interface.tud_network_recv_renew_process_again = false;
// If the current function is called within recv_transfer_datagram_to_glue_logic,
// tud_network_recv_renew_process_again will become true, and the loop will run again
// Otherwise the loop will not run again
ncm_interface.tud_network_recv_renew_active = true;
recv_transfer_datagram_to_glue_logic();
ncm_interface.tud_network_recv_renew_active = false;
}
recv_try_to_start_new_reception(ncm_interface.rhport);
} // tud_network_recv_renew
/**
* Same as tud_network_recv_renew() but knows \a rhport
*/
static void tud_network_recv_renew_r(uint8_t rhport) {
TU_LOG_DRV("tud_network_recv_renew_r(%d)\n", rhport);
ncm_interface.rhport = rhport;
tud_network_recv_renew();
} // tud_network_recv_renew
//-----------------------------------------------------------------------------
//
// all the netd_*() stuff (interface TinyUSB -> driver)
//
/**
* Initialize the driver data structures.
* Might be called several times.
*/
void netd_init(void) {
TU_LOG_DRV("netd_init()\n");
memset(&ncm_interface, 0, sizeof(ncm_interface));
for (int i = 0; i < XMIT_NTB_N; ++i) {
ncm_interface.xmit_free_ntb[i] = &ncm_epbuf.xmit[i].ntb;
}
for (int i = 0; i < RECV_NTB_N; ++i) {
ncm_interface.recv_free_ntb[i] = &ncm_epbuf.recv[i].ntb;
}
} // netd_init
/**
* Deinit driver
*/
bool netd_deinit(void) {
return true;
}
/**
* Resets the port.
* In this driver this is the same as netd_init()
*/
void netd_reset(uint8_t rhport) {
(void) rhport;
netd_init();
} // netd_reset
/**
* Open the USB interface.
* - parse the USB descriptor \a TUD_CDC_NCM_DESCRIPTOR for itfnum and endpoints
* - a specific order of elements in the descriptor is tested.
*
* \note
* Actually all of the information could be read directly from \a itf_desc, because the
* structure and the values are well known. But we do it this way.
*
* \post
* - \a itf_num set
* - \a ep_notif, \a ep_in and \a ep_out are set
* - USB interface is open
*/
uint16_t netd_open(uint8_t rhport, tusb_desc_interface_t const *itf_desc, uint16_t max_len) {
TU_ASSERT(ncm_interface.ep_notif == 0, 0);// assure that the interface is only opened once
ncm_interface.itf_num = itf_desc->bInterfaceNumber;// management interface
// skip the two first entries and the following TUSB_DESC_CS_INTERFACE entries
uint16_t drv_len = sizeof(tusb_desc_interface_t);
uint8_t const *p_desc = tu_desc_next(itf_desc);
while (tu_desc_type(p_desc) == TUSB_DESC_CS_INTERFACE && drv_len <= max_len) {
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// get notification endpoint
TU_ASSERT(tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT, 0);
TU_ASSERT(usbd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), 0);
ncm_interface.ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
// skip the following TUSB_DESC_INTERFACE entries (which must be TUSB_CLASS_CDC_DATA)
while (tu_desc_type(p_desc) == TUSB_DESC_INTERFACE && drv_len <= max_len) {
tusb_desc_interface_t const *data_itf_desc = (tusb_desc_interface_t const *) p_desc;
TU_ASSERT(data_itf_desc->bInterfaceClass == TUSB_CLASS_CDC_DATA, 0);
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// a TUSB_DESC_ENDPOINT (actually two) must follow, open these endpoints
TU_ASSERT(tu_desc_type(p_desc) == TUSB_DESC_ENDPOINT, 0);
TU_ASSERT(usbd_open_edpt_pair(rhport, p_desc, 2, TUSB_XFER_BULK, &ncm_interface.ep_out, &ncm_interface.ep_in));
drv_len += 2 * sizeof(tusb_desc_endpoint_t);
return drv_len;
} // netd_open
/**
* Handle TinyUSB requests to process transfer events.
*/
bool netd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void) result;
if (ep_addr == ncm_interface.ep_out) {
// new NTB received
// - make the NTB valid
// - if ready transfer datagrams to the glue logic for further processing
// - if there is a free receive buffer, initiate reception
if (!recv_validate_datagram(ncm_interface.recv_tinyusb_ntb, xferred_bytes)) {
// verification failed: ignore NTB and return it to free
TU_LOG_DRV("(EE) VALIDATION FAILED. WHAT CAN WE DO IN THIS CASE?\n");
} else {
// packet ok -> put it into ready list
recv_put_ntb_into_ready_list(ncm_interface.recv_tinyusb_ntb);
}
ncm_interface.recv_tinyusb_ntb = NULL;
tud_network_recv_renew_r(rhport);
} else if (ep_addr == ncm_interface.ep_in) {
// transmission of an NTB finished
// - free the transmitted NTB buffer
// - insert ZLPs when necessary
// - if there is another transmit NTB waiting, try to start transmission
xmit_put_ntb_into_free_list(ncm_interface.xmit_tinyusb_ntb);
ncm_interface.xmit_tinyusb_ntb = NULL;
if (!xmit_insert_required_zlp(rhport, xferred_bytes)) {
xmit_start_if_possible(rhport);
}
} else if (ep_addr == ncm_interface.ep_notif) {
// next transfer on notification channel
notification_xmit(rhport, true);
}
return true;
} // netd_xfer_cb
/**
* Respond to TinyUSB control requests.
* At startup transmission of notification packets are done here.
*/
bool netd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) {
if (stage != CONTROL_STAGE_SETUP) {
return true;
}
switch (request->bmRequestType_bit.type) {
case TUSB_REQ_TYPE_STANDARD:
switch (request->bRequest) {
case TUSB_REQ_GET_INTERFACE: {
TU_VERIFY(ncm_interface.itf_num + 1 == request->wIndex, false);
tud_control_xfer(rhport, request, &ncm_interface.itf_data_alt, 1);
} break;
case TUSB_REQ_SET_INTERFACE: {
TU_VERIFY(ncm_interface.itf_num + 1 == request->wIndex && request->wValue < 2, false);
ncm_interface.itf_data_alt = (uint8_t) request->wValue;
if (ncm_interface.itf_data_alt == 1) {
tud_network_recv_renew_r(rhport);
notification_xmit(rhport, false);
}
tud_control_status(rhport, request);
} break;
// unsupported request
default:
return false;
}
break;
case TUSB_REQ_TYPE_CLASS:
TU_VERIFY(ncm_interface.itf_num == request->wIndex, false);
switch (request->bRequest) {
case NCM_GET_NTB_PARAMETERS: {
// transfer NTB parameters to host.
tud_control_xfer(rhport, request, (void *) (uintptr_t) &ntb_parameters, sizeof(ntb_parameters));
} break;
// unsupported request
default:
return false;
}
break;
// unsupported request
default:
return false;
}
return true;
} // netd_control_xfer_cb
#endif // ( CFG_TUD_ENABLED && CFG_TUD_NCM )

View file

@ -0,0 +1,105 @@
/*
* 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 <stdint.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
/* 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
// Table 4.3 Data Class Interface Protocol Codes
typedef enum
{
NCM_DATA_PROTOCOL_NETWORK_TRANSFER_BLOCK = 0x01
} ncm_data_interface_protocol_code_t;
#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 uint8_t tud_network_mac_address[6];
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void netd_init (void);
bool netd_deinit (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,343 @@
/*
* 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,
};
// built-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 {
// The last and first valid bNotify1 for use by the USBTMC class specification.
USBTMC_bNOTIFY1_USBTMC_FIRST = 0x00,
USBTMC_bNOTIFY1_USBTMC_LAST = 0x3F,
// The last and first valid bNotify1 for use by vendors.
USBTMC_bNOTIFY1_VENDOR_SPECIFIC_FIRST = 0x40,
USBTMC_bNOTIFY1_VENDOR_SPECIFIC_LAST = 0x7F,
// The last and first valid bNotify1 for use by USBTMC subclass specifications.
USBTMC_bNOTIFY1_SUBCLASS_FIRST = 0x80,
USBTMC_bNOTIFY1_SUBCLASS_LAST = 0xFF,
// From the USB488 Subclass Specification, Section 3.4.
USB488_bNOTIFY1_SRQ = 0x81,
} usbtmc_int_in_payload_format;
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 488 *************/
USB488_STATUS_INTERRUPT_IN_BUSY = 0x20
} 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
{
uint8_t listenOnly :1;
uint8_t talkOnly :1;
uint8_t supportsIndicatorPulse :1;
} bmIntfcCapabilities;
struct TU_ATTR_PACKED
{
uint8_t canEndBulkInOnTermChar :1;
} bmDevCapabilities;
uint8_t _reserved2[6];
uint16_t bcdUSB488;
struct TU_ATTR_PACKED
{
uint8_t supportsTrigger :1;
uint8_t supportsREN_GTL_LLO :1;
uint8_t is488_2 :1;
} bmIntfcCapabilities488;
struct TU_ATTR_PACKED
{
uint8_t DT1 :1;
uint8_t RL1 :1;
uint8_t SR1 :1;
uint8_t SCPI :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
{
uint8_t bNotify1; // Must be USB488_bNOTIFY1_SRQ
uint8_t StatusByte;
} usbtmc_srq_interrupt_488_t;
TU_VERIFY_STATIC(sizeof(usbtmc_srq_interrupt_488_t) == 2u, "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,923 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Nathan 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.
*/
/*
* This library is not fully reentrant, though it is reentrant from the view
* of either the application layer or the USB stack. Due to its locking,
* it is not safe to call its functions from interrupts.
*
* The one exception is that its functions may not be called from the application
* until the USB stack is initialized. This should not be a problem since the
* device shouldn't be sending messages until it receives a request from the
* host.
*/
/*
* In the case of single-CPU "no OS", this task is never preempted other than by
* interrupts, and the USBTMC code isn't called by interrupts, so all is OK. For "no OS",
* the mutex structure's main effect is to disable the USB interrupts.
* With an OS, this class driver uses the OSAL to perform locking. The code uses a single lock
* and does not call outside of this class with a lock held, so deadlocks won't happen.
*/
//Limitations:
// "vendor-specific" commands are not handled.
// Dealing with "termchar" must be handled by the application layer,
// though additional error checking is does in this module.
// talkOnly and listenOnly are NOT supported. They're not permitted
// in USB488, anyway.
/* Supported:
*
* Notification pulse
* Trigger
* Read status byte (both by interrupt endpoint and control message)
*
*/
// TODO:
// USBTMC 3.2.2 error conditions not strictly followed
// No local lock-out, REN, or GTL.
// Clear message available status byte at the correct time? (488 4.3.1.3)
// Ability to defer status byte transmission
// Transmission of status byte in response to USB488 SRQ condition
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_USBTMC)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "usbtmc_device.h"
#ifdef xDEBUG
#include "uart_util.h"
tu_static char logMsg[150];
#endif
// Buffer size must be an exact multiple of the max packet size for both
// bulk (up to 64 bytes for FS, 512 bytes for HS). In addation, this driver
// imposes a minimum buffer size of 32 bytes.
#define USBTMCD_BUFFER_SIZE (TUD_OPT_HIGH_SPEED ? 512 : 64)
// Interrupt endpoint buffer size, default to 2 bytes as USB488 specification.
#ifndef CFG_TUD_USBTMC_INT_EP_SIZE
#define CFG_TUD_USBTMC_INT_EP_SIZE 2
#endif
/*
* The state machine does not allow simultaneous reading and writing. This is
* consistent with USBTMC.
*/
typedef enum
{
STATE_CLOSED, // Endpoints have not yet been opened since USB reset
STATE_NAK, // Bulk-out endpoint is in NAK state.
STATE_IDLE, // Bulk-out endpoint is waiting for CMD.
STATE_RCV, // Bulk-out is receiving DEV_DEP message
STATE_TX_REQUESTED,
STATE_TX_INITIATED,
STATE_TX_SHORTED,
STATE_CLEARING,
STATE_ABORTING_BULK_IN,
STATE_ABORTING_BULK_IN_SHORTED, // aborting, and short packet has been queued for transmission
STATE_ABORTING_BULK_IN_ABORTED, // aborting, and short packet has been transmitted
STATE_ABORTING_BULK_OUT,
STATE_NUM_STATES
} usbtmcd_state_enum;
#if (CFG_TUD_USBTMC_ENABLE_488)
typedef usbtmc_response_capabilities_488_t usbtmc_capabilities_specific_t;
#else
typedef usbtmc_response_capabilities_t usbtmc_capabilities_specific_t;
#endif
typedef struct
{
volatile usbtmcd_state_enum state;
uint8_t itf_id;
uint8_t rhport;
uint8_t ep_bulk_in;
uint8_t ep_bulk_out;
uint8_t ep_int_in;
uint32_t ep_bulk_in_wMaxPacketSize;
uint32_t ep_bulk_out_wMaxPacketSize;
uint32_t transfer_size_remaining; // also used for requested length for bulk IN.
uint32_t transfer_size_sent; // To keep track of data bytes that have been queued in FIFO (not header bytes)
uint8_t lastBulkOutTag; // used for aborts (mostly)
uint8_t lastBulkInTag; // used for aborts (mostly)
uint8_t const * devInBuffer; // pointer to application-layer used for transmissions
usbtmc_capabilities_specific_t const * capabilities;
} usbtmc_interface_state_t;
typedef struct {
// IN buffer is only used for first packet, not the remainder in order to deal with prepending header
TUD_EPBUF_DEF(epin, USBTMCD_BUFFER_SIZE);
// OUT buffer receives one packet at a time
TUD_EPBUF_DEF(epout, USBTMCD_BUFFER_SIZE);
// Buffer int msg
TUD_EPBUF_DEF(epnotif, CFG_TUD_USBTMC_INT_EP_SIZE);
} usbtmc_epbuf_t;
static usbtmc_interface_state_t usbtmc_state = {
.itf_id = 0xFF,
};
CFG_TUD_MEM_SECTION static usbtmc_epbuf_t usbtmc_epbuf;
// We need all headers to fit in a single packet in this implementation, 32 bytes will fit all standard USBTMC headers
TU_VERIFY_STATIC(USBTMCD_BUFFER_SIZE >= 32u,"USBTMC dev buffer size too small");
static bool handle_devMsgOutStart(uint8_t rhport, void *data, size_t len);
static bool handle_devMsgOut(uint8_t rhport, void *data, size_t len, size_t packetLen);
#ifndef NDEBUG
tu_static uint8_t termChar;
#endif
tu_static uint8_t termCharRequested = false;
#if OSAL_MUTEX_REQUIRED
static OSAL_MUTEX_DEF(usbtmcLockBuffer);
#endif
osal_mutex_t usbtmcLock;
// Our own private lock, mostly for the state variable.
#define criticalEnter() do { (void) osal_mutex_lock(usbtmcLock,OSAL_TIMEOUT_WAIT_FOREVER); } while (0)
#define criticalLeave() do { (void) osal_mutex_unlock(usbtmcLock); } while (0)
static bool atomicChangeState(usbtmcd_state_enum expectedState, usbtmcd_state_enum newState)
{
bool ret = true;
criticalEnter();
usbtmcd_state_enum oldState = usbtmc_state.state;
if (oldState == expectedState)
{
usbtmc_state.state = newState;
}
else
{
ret = false;
}
criticalLeave();
return ret;
}
// 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.
// length of data is specified in the hdr.
// We can't just send the whole thing at once because we need to concatanate the
// header with the data.
bool tud_usbtmc_transmit_dev_msg_data(
const void * data, size_t len,
bool endOfMessage,
bool usingTermChar)
{
const unsigned int txBufLen = USBTMCD_BUFFER_SIZE;
#ifndef NDEBUG
TU_ASSERT(len > 0u);
TU_ASSERT(len <= usbtmc_state.transfer_size_remaining);
TU_ASSERT(usbtmc_state.transfer_size_sent == 0u);
if(usingTermChar)
{
TU_ASSERT(usbtmc_state.capabilities->bmDevCapabilities.canEndBulkInOnTermChar);
TU_ASSERT(termCharRequested);
TU_ASSERT(((uint8_t const*)data)[len-1u] == termChar);
}
#endif
TU_VERIFY(usbtmc_state.state == STATE_TX_REQUESTED);
usbtmc_msg_dev_dep_msg_in_header_t *hdr = (usbtmc_msg_dev_dep_msg_in_header_t*)usbtmc_epbuf.epin;
tu_varclr(hdr);
hdr->header.MsgID = USBTMC_MSGID_DEV_DEP_MSG_IN;
hdr->header.bTag = usbtmc_state.lastBulkInTag;
hdr->header.bTagInverse = (uint8_t)~(usbtmc_state.lastBulkInTag);
hdr->TransferSize = len;
hdr->bmTransferAttributes.EOM = endOfMessage;
hdr->bmTransferAttributes.UsingTermChar = usingTermChar;
// Copy in the header
const size_t headerLen = sizeof(*hdr);
const size_t dataLen = ((headerLen + hdr->TransferSize) <= txBufLen) ?
len : (txBufLen - headerLen);
const size_t packetLen = headerLen + dataLen;
memcpy((uint8_t*)(usbtmc_epbuf.epin) + headerLen, data, dataLen);
usbtmc_state.transfer_size_remaining = len - dataLen;
usbtmc_state.transfer_size_sent = dataLen;
usbtmc_state.devInBuffer = (uint8_t const*) data + (dataLen);
bool stateChanged =
atomicChangeState(STATE_TX_REQUESTED, (packetLen >= txBufLen) ? STATE_TX_INITIATED : STATE_TX_SHORTED);
TU_VERIFY(stateChanged);
TU_VERIFY(usbd_edpt_xfer(usbtmc_state.rhport, usbtmc_state.ep_bulk_in, usbtmc_epbuf.epin, (uint16_t)packetLen));
return true;
}
bool tud_usbtmc_transmit_notification_data(const void * data, size_t len)
{
#ifndef NDEBUG
TU_ASSERT(len > 0);
TU_ASSERT(usbtmc_state.ep_int_in != 0);
#endif
TU_VERIFY(usbd_edpt_busy(usbtmc_state.rhport, usbtmc_state.ep_int_in));
TU_VERIFY(tu_memcpy_s(usbtmc_epbuf.epnotif, CFG_TUD_USBTMC_INT_EP_SIZE, data, len) == 0);
TU_VERIFY(usbd_edpt_xfer(usbtmc_state.rhport, usbtmc_state.ep_int_in, usbtmc_epbuf.epnotif, (uint16_t)len));
return true;
}
void usbtmcd_init_cb(void)
{
usbtmc_state.capabilities = tud_usbtmc_get_capabilities_cb();
#ifndef NDEBUG
# if CFG_TUD_USBTMC_ENABLE_488
if (usbtmc_state.capabilities->bmIntfcCapabilities488.supportsTrigger) {
TU_ASSERT(&tud_usbtmc_msg_trigger_cb != NULL,);
}
// Per USB488 spec: table 8
TU_ASSERT(!usbtmc_state.capabilities->bmIntfcCapabilities.listenOnly,);
TU_ASSERT(!usbtmc_state.capabilities->bmIntfcCapabilities.talkOnly,);
# endif
if (usbtmc_state.capabilities->bmIntfcCapabilities.supportsIndicatorPulse) {
TU_ASSERT(&tud_usbtmc_indicator_pulse_cb != NULL,);
}
#endif
usbtmcLock = osal_mutex_create(&usbtmcLockBuffer);
}
bool usbtmcd_deinit(void) {
#if OSAL_MUTEX_REQUIRED
osal_mutex_delete(usbtmcLock);
#endif
return true;
}
uint16_t usbtmcd_open_cb(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t max_len)
{
(void)rhport;
uint16_t drv_len;
uint8_t const * p_desc;
uint8_t found_endpoints = 0;
TU_VERIFY(itf_desc->bInterfaceClass == TUD_USBTMC_APP_CLASS , 0);
TU_VERIFY(itf_desc->bInterfaceSubClass == TUD_USBTMC_APP_SUBCLASS, 0);
#ifndef NDEBUG
// Only 2 or 3 endpoints are allowed for USBTMC.
TU_ASSERT((itf_desc->bNumEndpoints == 2) || (itf_desc->bNumEndpoints ==3), 0);
#endif
TU_ASSERT(usbtmc_state.state == STATE_CLOSED, 0);
// Interface
drv_len = 0u;
p_desc = (uint8_t const *) itf_desc;
usbtmc_state.itf_id = itf_desc->bInterfaceNumber;
usbtmc_state.rhport = rhport;
while (found_endpoints < itf_desc->bNumEndpoints && drv_len <= max_len)
{
if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE])
{
tusb_desc_endpoint_t const *ep_desc = (tusb_desc_endpoint_t const *)p_desc;
switch(ep_desc->bmAttributes.xfer) {
case TUSB_XFER_BULK:
// Ensure buffer is an exact multiple of the maxPacketSize
TU_ASSERT((USBTMCD_BUFFER_SIZE % tu_edpt_packet_size(ep_desc)) == 0, 0);
if (tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN)
{
usbtmc_state.ep_bulk_in = ep_desc->bEndpointAddress;
usbtmc_state.ep_bulk_in_wMaxPacketSize = tu_edpt_packet_size(ep_desc);
} else {
usbtmc_state.ep_bulk_out = ep_desc->bEndpointAddress;
usbtmc_state.ep_bulk_out_wMaxPacketSize = tu_edpt_packet_size(ep_desc);
}
break;
case TUSB_XFER_INTERRUPT:
#ifndef NDEBUG
TU_ASSERT(tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN, 0);
TU_ASSERT(usbtmc_state.ep_int_in == 0, 0);
#endif
usbtmc_state.ep_int_in = ep_desc->bEndpointAddress;
break;
default:
TU_ASSERT(false, 0);
}
TU_ASSERT( usbd_edpt_open(rhport, ep_desc), 0);
found_endpoints++;
}
drv_len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
// bulk endpoints are required, but interrupt IN is optional
#ifndef NDEBUG
TU_ASSERT(usbtmc_state.ep_bulk_in != 0, 0);
TU_ASSERT(usbtmc_state.ep_bulk_out != 0, 0);
if (itf_desc->bNumEndpoints == 2)
{
TU_ASSERT(usbtmc_state.ep_int_in == 0, 0);
}
else if (itf_desc->bNumEndpoints == 3)
{
TU_ASSERT(usbtmc_state.ep_int_in != 0, 0);
}
#if (CFG_TUD_USBTMC_ENABLE_488)
if(usbtmc_state.capabilities->bmIntfcCapabilities488.is488_2 ||
usbtmc_state.capabilities->bmDevCapabilities488.SR1)
{
TU_ASSERT(usbtmc_state.ep_int_in != 0, 0);
}
#endif
#endif
atomicChangeState(STATE_CLOSED, STATE_NAK);
tud_usbtmc_open_cb(itf_desc->iInterface);
return drv_len;
}
// Tell USBTMC class to set its bulk-in EP to ACK so that it can
// receive USBTMC commands.
// Returns false if it was already in an ACK state or is busy
// processing a command (such as a clear). Returns true if it was
// in the NAK state and successfully transitioned to the ACK wait
// state.
bool tud_usbtmc_start_bus_read(void)
{
usbtmcd_state_enum oldState = usbtmc_state.state;
switch(oldState)
{
// These may transition to IDLE
case STATE_NAK:
case STATE_ABORTING_BULK_IN_ABORTED:
TU_VERIFY(atomicChangeState(oldState, STATE_IDLE));
break;
// When receiving, let it remain receiving
case STATE_RCV:
break;
default:
return false;
}
TU_VERIFY(usbd_edpt_xfer(usbtmc_state.rhport, usbtmc_state.ep_bulk_out, usbtmc_epbuf.epout, (uint16_t)usbtmc_state.ep_bulk_out_wMaxPacketSize));
return true;
}
void usbtmcd_reset_cb(uint8_t rhport)
{
(void)rhport;
usbtmc_capabilities_specific_t const * capabilities = tud_usbtmc_get_capabilities_cb();
criticalEnter();
tu_varclr(&usbtmc_state);
usbtmc_state.capabilities = capabilities;
usbtmc_state.itf_id = 0xFFu;
criticalLeave();
}
static bool handle_devMsgOutStart(uint8_t rhport, void *data, size_t len)
{
(void)rhport;
// return true upon failure, as we can assume error is being handled elsewhere.
TU_VERIFY(atomicChangeState(STATE_IDLE, STATE_RCV), true);
usbtmc_state.transfer_size_sent = 0u;
// must be a header, should have been confirmed before calling here.
usbtmc_msg_request_dev_dep_out *msg = (usbtmc_msg_request_dev_dep_out*)data;
usbtmc_state.transfer_size_remaining = msg->TransferSize;
TU_VERIFY(tud_usbtmc_msgBulkOut_start_cb(msg));
TU_VERIFY(handle_devMsgOut(rhport, (uint8_t*)data + sizeof(*msg), len - sizeof(*msg), len));
usbtmc_state.lastBulkOutTag = msg->header.bTag;
return true;
}
static bool handle_devMsgOut(uint8_t rhport, void *data, size_t len, size_t packetLen)
{
(void)rhport;
// return true upon failure, as we can assume error is being handled elsewhere.
TU_VERIFY(usbtmc_state.state == STATE_RCV,true);
bool shortPacket = (packetLen < usbtmc_state.ep_bulk_out_wMaxPacketSize);
// Packet is to be considered complete when we get enough data or at a short packet.
bool atEnd = false;
if(len >= usbtmc_state.transfer_size_remaining || shortPacket)
{
atEnd = true;
TU_VERIFY(atomicChangeState(STATE_RCV, STATE_NAK));
}
len = tu_min32(len, usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_remaining -= len;
usbtmc_state.transfer_size_sent += len;
// App may (should?) call the wait_for_bus() command at this point
if(!tud_usbtmc_msg_data_cb(data, len, atEnd))
{
// TODO: Go to an error state upon failure other than just stalling the EP?
return false;
}
return true;
}
static bool handle_devMsgIn(void *data, size_t len)
{
TU_VERIFY(len == sizeof(usbtmc_msg_request_dev_dep_in));
usbtmc_msg_request_dev_dep_in *msg = (usbtmc_msg_request_dev_dep_in*)data;
bool stateChanged = atomicChangeState(STATE_IDLE, STATE_TX_REQUESTED);
TU_VERIFY(stateChanged);
usbtmc_state.lastBulkInTag = msg->header.bTag;
usbtmc_state.transfer_size_remaining = msg->TransferSize;
usbtmc_state.transfer_size_sent = 0u;
termCharRequested = msg->bmTransferAttributes.TermCharEnabled;
#ifndef NDEBUG
termChar = msg->TermChar;
#endif
if(termCharRequested)
TU_VERIFY(usbtmc_state.capabilities->bmDevCapabilities.canEndBulkInOnTermChar);
TU_VERIFY(tud_usbtmc_msgBulkIn_request_cb(msg));
return true;
}
bool usbtmcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
{
TU_VERIFY(result == XFER_RESULT_SUCCESS);
//uart_tx_str_sync("TMC XFER CB\r\n");
if(usbtmc_state.state == STATE_CLEARING) {
return true; /* I think we can ignore everything here */
}
if(ep_addr == usbtmc_state.ep_bulk_out)
{
usbtmc_msg_generic_t *msg = NULL;
switch(usbtmc_state.state)
{
case STATE_IDLE:
{
TU_VERIFY(xferred_bytes >= sizeof(usbtmc_msg_generic_t));
msg = (usbtmc_msg_generic_t*)(usbtmc_epbuf.epout);
uint8_t invInvTag = (uint8_t)~(msg->header.bTagInverse);
TU_VERIFY(msg->header.bTag == invInvTag);
TU_VERIFY(msg->header.bTag != 0x00);
switch(msg->header.MsgID) {
case USBTMC_MSGID_DEV_DEP_MSG_OUT:
if(!handle_devMsgOutStart(rhport, msg, xferred_bytes))
{
usbd_edpt_stall(rhport, usbtmc_state.ep_bulk_out);
return false;
}
break;
case USBTMC_MSGID_DEV_DEP_MSG_IN:
TU_VERIFY(handle_devMsgIn(msg, xferred_bytes));
break;
#if (CFG_TUD_USBTMC_ENABLE_488)
case USBTMC_MSGID_USB488_TRIGGER:
// Spec says we halt the EP if we didn't declare we support it.
TU_VERIFY(usbtmc_state.capabilities->bmIntfcCapabilities488.supportsTrigger);
TU_VERIFY(tud_usbtmc_msg_trigger_cb(msg));
break;
#endif
case USBTMC_MSGID_VENDOR_SPECIFIC_MSG_OUT:
case USBTMC_MSGID_VENDOR_SPECIFIC_IN:
default:
usbd_edpt_stall(rhport, usbtmc_state.ep_bulk_out);
return false;
}
return true;
}
case STATE_RCV:
if(!handle_devMsgOut(rhport, usbtmc_epbuf.epout, xferred_bytes, xferred_bytes))
{
usbd_edpt_stall(rhport, usbtmc_state.ep_bulk_out);
return false;
}
return true;
case STATE_ABORTING_BULK_OUT:
// Should be stalled by now, shouldn't have received a packet.
return false;
case STATE_TX_REQUESTED:
case STATE_TX_INITIATED:
case STATE_ABORTING_BULK_IN:
case STATE_ABORTING_BULK_IN_SHORTED:
case STATE_ABORTING_BULK_IN_ABORTED:
default:
return false;
}
}
else if(ep_addr == usbtmc_state.ep_bulk_in)
{
switch(usbtmc_state.state) {
case STATE_TX_SHORTED:
TU_VERIFY(atomicChangeState(STATE_TX_SHORTED, STATE_NAK));
TU_VERIFY(tud_usbtmc_msgBulkIn_complete_cb());
break;
case STATE_TX_INITIATED:
if(usbtmc_state.transfer_size_remaining >= USBTMCD_BUFFER_SIZE)
{
// Copy buffer to ensure alignment correctness
memcpy(usbtmc_epbuf.epin, usbtmc_state.devInBuffer, USBTMCD_BUFFER_SIZE);
TU_VERIFY(usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_epbuf.epin, USBTMCD_BUFFER_SIZE));
usbtmc_state.devInBuffer += USBTMCD_BUFFER_SIZE;
usbtmc_state.transfer_size_remaining -= USBTMCD_BUFFER_SIZE;
usbtmc_state.transfer_size_sent += USBTMCD_BUFFER_SIZE;
}
else // last packet
{
size_t packetLen = usbtmc_state.transfer_size_remaining;
memcpy(usbtmc_epbuf.epin, usbtmc_state.devInBuffer, usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_sent += sizeof(usbtmc_state.transfer_size_remaining);
usbtmc_state.transfer_size_remaining = 0;
usbtmc_state.devInBuffer = NULL;
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_epbuf.epin, (uint16_t)packetLen) );
if(((packetLen % usbtmc_state.ep_bulk_in_wMaxPacketSize) != 0) || (packetLen == 0 ))
{
usbtmc_state.state = STATE_TX_SHORTED;
}
}
return true;
case STATE_ABORTING_BULK_IN:
// need to send short packet (ZLP?)
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_epbuf.epin,(uint16_t)0u));
usbtmc_state.state = STATE_ABORTING_BULK_IN_SHORTED;
return true;
case STATE_ABORTING_BULK_IN_SHORTED:
/* Done. :)*/
usbtmc_state.state = STATE_ABORTING_BULK_IN_ABORTED;
return true;
default:
TU_ASSERT(false);
}
}
else if (ep_addr == usbtmc_state.ep_int_in) {
if (tud_usbtmc_notification_complete_cb) {
TU_VERIFY(tud_usbtmc_notification_complete_cb());
}
return true;
}
return false;
}
// Invoked when a control transfer occurred on an interface of this class
// Driver response accordingly to the request and the transfer stage (setup/data/ack)
// return false to stall control endpoint (e.g unsupported request)
bool usbtmcd_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request)
{
// nothing to do with DATA and ACK stage
if ( stage != CONTROL_STAGE_SETUP ) return true;
uint8_t tmcStatusCode = USBTMC_STATUS_FAILED;
#if (CFG_TUD_USBTMC_ENABLE_488)
uint8_t bTag;
#endif
if((request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD) &&
(request->bmRequestType_bit.recipient == TUSB_REQ_RCPT_ENDPOINT) &&
(request->bRequest == TUSB_REQ_CLEAR_FEATURE) &&
(request->wValue == TUSB_REQ_FEATURE_EDPT_HALT))
{
uint32_t ep_addr = (request->wIndex);
// At this point, a transfer MAY be in progress. Based on USB spec, when clearing bulk EP HALT,
// the EP transfer buffer needs to be cleared and DTOG needs to be reset, even if
// the EP is not halted. The only USBD API interface to do this is to stall and then un-stall the EP.
if(ep_addr == usbtmc_state.ep_bulk_out)
{
criticalEnter();
usbd_edpt_stall(rhport, (uint8_t)ep_addr);
usbd_edpt_clear_stall(rhport, (uint8_t)ep_addr);
usbtmc_state.state = STATE_NAK; // USBD core has placed EP in NAK state for us
criticalLeave();
tud_usbtmc_bulkOut_clearFeature_cb();
}
else if (ep_addr == usbtmc_state.ep_bulk_in)
{
usbd_edpt_stall(rhport, (uint8_t)ep_addr);
usbd_edpt_clear_stall(rhport, (uint8_t)ep_addr);
tud_usbtmc_bulkIn_clearFeature_cb();
}
else if ((usbtmc_state.ep_int_in != 0) && (ep_addr == usbtmc_state.ep_int_in))
{
// Clearing interrupt in EP
usbd_edpt_stall(rhport, (uint8_t)ep_addr);
usbd_edpt_clear_stall(rhport, (uint8_t)ep_addr);
}
else
{
return false;
}
return true;
}
// Otherwise, we only handle class requests.
if(request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS)
{
return false;
}
// Verification that we own the interface is unneeded since it's been routed to us specifically.
switch(request->bRequest)
{
// USBTMC required requests
case USBTMC_bREQUEST_INITIATE_ABORT_BULK_OUT:
{
usbtmc_initiate_abort_rsp_t rsp = {
.bTag = usbtmc_state.lastBulkOutTag,
};
TU_VERIFY(request->bmRequestType == 0xA2); // in,class,interface
TU_VERIFY(request->wLength == sizeof(rsp));
TU_VERIFY(request->wIndex == usbtmc_state.ep_bulk_out);
// wValue is the requested bTag to abort
if(usbtmc_state.state != STATE_RCV)
{
rsp.USBTMC_status = USBTMC_STATUS_FAILED;
}
else if(usbtmc_state.lastBulkOutTag == (request->wValue & 0x7Fu))
{
rsp.USBTMC_status = USBTMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
}
else
{
rsp.USBTMC_status = USBTMC_STATUS_SUCCESS;
// Check if we've queued a short packet
criticalEnter();
usbtmc_state.state = STATE_ABORTING_BULK_OUT;
criticalLeave();
TU_VERIFY(tud_usbtmc_initiate_abort_bulk_out_cb(&(rsp.USBTMC_status)));
usbd_edpt_stall(rhport, usbtmc_state.ep_bulk_out);
}
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&rsp,sizeof(rsp)));
return true;
}
case USBTMC_bREQUEST_CHECK_ABORT_BULK_OUT_STATUS:
{
usbtmc_check_abort_bulk_rsp_t rsp = {
.USBTMC_status = USBTMC_STATUS_SUCCESS,
.NBYTES_RXD_TXD = usbtmc_state.transfer_size_sent
};
TU_VERIFY(request->bmRequestType == 0xA2); // in,class,EP
TU_VERIFY(request->wLength == sizeof(rsp));
TU_VERIFY(request->wIndex == usbtmc_state.ep_bulk_out);
TU_VERIFY(tud_usbtmc_check_abort_bulk_out_cb(&rsp));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&rsp,sizeof(rsp)));
return true;
}
case USBTMC_bREQUEST_INITIATE_ABORT_BULK_IN:
{
usbtmc_initiate_abort_rsp_t rsp = {
.bTag = usbtmc_state.lastBulkInTag,
};
TU_VERIFY(request->bmRequestType == 0xA2); // in,class,interface
TU_VERIFY(request->wLength == sizeof(rsp));
TU_VERIFY(request->wIndex == usbtmc_state.ep_bulk_in);
// wValue is the requested bTag to abort
if((usbtmc_state.state == STATE_TX_REQUESTED || usbtmc_state.state == STATE_TX_INITIATED) &&
usbtmc_state.lastBulkInTag == (request->wValue & 0x7Fu))
{
rsp.USBTMC_status = USBTMC_STATUS_SUCCESS;
usbtmc_state.transfer_size_remaining = 0u;
// Check if we've queued a short packet
criticalEnter();
usbtmc_state.state = ((usbtmc_state.transfer_size_sent % usbtmc_state.ep_bulk_in_wMaxPacketSize) == 0) ?
STATE_ABORTING_BULK_IN : STATE_ABORTING_BULK_IN_SHORTED;
criticalLeave();
if(usbtmc_state.transfer_size_sent == 0)
{
// Send short packet, nothing is in the buffer yet
TU_VERIFY( usbd_edpt_xfer(rhport, usbtmc_state.ep_bulk_in, usbtmc_epbuf.epin,(uint16_t)0u));
usbtmc_state.state = STATE_ABORTING_BULK_IN_SHORTED;
}
TU_VERIFY(tud_usbtmc_initiate_abort_bulk_in_cb(&(rsp.USBTMC_status)));
}
else if((usbtmc_state.state == STATE_TX_REQUESTED || usbtmc_state.state == STATE_TX_INITIATED))
{ // FIXME: Unsure how to check if the OUT endpoint fifo is non-empty....
rsp.USBTMC_status = USBTMC_STATUS_TRANSFER_NOT_IN_PROGRESS;
}
else
{
rsp.USBTMC_status = USBTMC_STATUS_FAILED;
}
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&rsp,sizeof(rsp)));
return true;
}
case USBTMC_bREQUEST_CHECK_ABORT_BULK_IN_STATUS:
{
TU_VERIFY(request->bmRequestType == 0xA2); // in,class,EP
TU_VERIFY(request->wLength == 8u);
usbtmc_check_abort_bulk_rsp_t rsp =
{
.USBTMC_status = USBTMC_STATUS_FAILED,
.bmAbortBulkIn =
{
.BulkInFifoBytes = (usbtmc_state.state != STATE_ABORTING_BULK_IN_ABORTED)
},
.NBYTES_RXD_TXD = usbtmc_state.transfer_size_sent,
};
TU_VERIFY(tud_usbtmc_check_abort_bulk_in_cb(&rsp));
criticalEnter();
switch(usbtmc_state.state)
{
case STATE_ABORTING_BULK_IN_ABORTED:
rsp.USBTMC_status = USBTMC_STATUS_SUCCESS;
usbtmc_state.state = STATE_IDLE;
break;
case STATE_ABORTING_BULK_IN:
case STATE_ABORTING_BULK_OUT:
rsp.USBTMC_status = USBTMC_STATUS_PENDING;
break;
default:
break;
}
criticalLeave();
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&rsp,sizeof(rsp)));
return true;
}
case USBTMC_bREQUEST_INITIATE_CLEAR:
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
TU_VERIFY(request->wLength == sizeof(tmcStatusCode));
// After receiving an INITIATE_CLEAR request, the device must Halt the Bulk-OUT endpoint, queue the
// control endpoint response shown in Table 31, and clear all input buffers and output buffers.
usbd_edpt_stall(rhport, usbtmc_state.ep_bulk_out);
usbtmc_state.transfer_size_remaining = 0;
criticalEnter();
usbtmc_state.state = STATE_CLEARING;
criticalLeave();
TU_VERIFY(tud_usbtmc_initiate_clear_cb(&tmcStatusCode));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&tmcStatusCode,sizeof(tmcStatusCode)));
return true;
}
case USBTMC_bREQUEST_CHECK_CLEAR_STATUS:
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
usbtmc_get_clear_status_rsp_t clearStatusRsp = {0};
TU_VERIFY(request->wLength == sizeof(clearStatusRsp));
if(usbd_edpt_busy(rhport, usbtmc_state.ep_bulk_in))
{
// Stuff stuck in TX buffer?
clearStatusRsp.bmClear.BulkInFifoBytes = 1;
clearStatusRsp.USBTMC_status = USBTMC_STATUS_PENDING;
}
else
{
// Let app check if it's clear
TU_VERIFY(tud_usbtmc_check_clear_cb(&clearStatusRsp));
}
if(clearStatusRsp.USBTMC_status == USBTMC_STATUS_SUCCESS)
{
criticalEnter();
usbtmc_state.state = STATE_IDLE;
criticalLeave();
}
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&clearStatusRsp,sizeof(clearStatusRsp)));
return true;
}
case USBTMC_bREQUEST_GET_CAPABILITIES:
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
TU_VERIFY(request->wLength == sizeof(*(usbtmc_state.capabilities)));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)(uintptr_t) usbtmc_state.capabilities, sizeof(*usbtmc_state.capabilities)));
return true;
}
// USBTMC Optional Requests
case USBTMC_bREQUEST_INDICATOR_PULSE: // Optional
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
TU_VERIFY(request->wLength == sizeof(tmcStatusCode));
TU_VERIFY(usbtmc_state.capabilities->bmIntfcCapabilities.supportsIndicatorPulse);
TU_VERIFY(tud_usbtmc_indicator_pulse_cb(request, &tmcStatusCode));
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&tmcStatusCode, sizeof(tmcStatusCode)));
return true;
}
#if (CFG_TUD_USBTMC_ENABLE_488)
// USB488 required requests
case USB488_bREQUEST_READ_STATUS_BYTE:
{
usbtmc_read_stb_rsp_488_t rsp;
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
TU_VERIFY(request->wLength == sizeof(rsp)); // in,class,interface
bTag = request->wValue & 0x7F;
TU_VERIFY(request->bmRequestType == 0xA1);
TU_VERIFY((request->wValue & (~0x7F)) == 0u); // Other bits are required to be zero (USB488v1.0 Table 11)
TU_VERIFY(bTag >= 0x02 && bTag <= 127);
TU_VERIFY(request->wIndex == usbtmc_state.itf_id);
TU_VERIFY(request->wLength == 0x0003);
rsp.bTag = (uint8_t)bTag;
if(usbtmc_state.ep_int_in != 0)
{
rsp.statusByte = 0x00; // Use interrupt endpoint, instead. Must be 0x00 (USB488v1.0 4.3.1.2)
if(usbd_edpt_busy(rhport, usbtmc_state.ep_int_in))
{
rsp.USBTMC_status = USB488_STATUS_INTERRUPT_IN_BUSY;
}
else
{
rsp.USBTMC_status = USBTMC_STATUS_SUCCESS;
usbtmc_read_stb_interrupt_488_t intMsg =
{
.bNotify1 = {
.one = 1,
.bTag = bTag & 0x7Fu,
},
.StatusByte = tud_usbtmc_get_stb_cb(&(rsp.USBTMC_status))
};
// Must be queued before control request response sent (USB488v1.0 4.3.1.2)
usbd_edpt_xfer(rhport, usbtmc_state.ep_int_in, (void*)&intMsg, sizeof(intMsg));
}
}
else
{
rsp.statusByte = tud_usbtmc_get_stb_cb(&(rsp.USBTMC_status));
}
TU_VERIFY(tud_control_xfer(rhport, request, (void*)&rsp, sizeof(rsp)));
return true;
}
// USB488 optional requests
case USB488_bREQUEST_REN_CONTROL:
case USB488_bREQUEST_GO_TO_LOCAL:
case USB488_bREQUEST_LOCAL_LOCKOUT:
{
TU_VERIFY(request->bmRequestType == 0xA1); // in,class,interface
return false;
}
#endif
default:
return false;
}
}
#endif /* CFG_TUD_TSMC */

View file

@ -0,0 +1,118 @@
/*
* 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
/***********************************************
* Functions to be implemented 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);
// The interrupt-IN endpoint buffer was transmitted to the host. Use
// tud_usbtmc_transmit_notification_data to send another notification.
TU_ATTR_WEAK bool tud_usbtmc_notification_complete_cb(void);
// 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);
// Buffers a notification to be sent to the host. The data starts
// with the bNotify1 field, see the USBTMC Specification, Table 13.
//
// If the previous notification data has not yet been sent, this
// returns false.
//
// Requires an interrupt endpoint in the interface.
bool tud_usbtmc_transmit_notification_data(const void * data, size_t len);
bool tud_usbtmc_start_bus_read(void);
/* "callbacks" from USB device core */
void usbtmcd_init_cb(void);
bool usbtmcd_deinit(void);
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);
#endif /* CLASS_USBTMC_USBTMC_DEVICE_H_ */

View file

@ -0,0 +1,284 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUD_ENABLED && CFG_TUD_VENDOR)
#include "device/usbd.h"
#include "device/usbd_pvt.h"
#include "vendor_device.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct {
uint8_t itf_num;
/*------------- From this point, data is not cleared by bus reset -------------*/
struct {
tu_edpt_stream_t stream;
#if CFG_TUD_VENDOR_TX_BUFSIZE > 0
uint8_t ff_buf[CFG_TUD_VENDOR_TX_BUFSIZE];
#endif
} tx;
struct {
tu_edpt_stream_t stream;
#if CFG_TUD_VENDOR_RX_BUFSIZE > 0
uint8_t ff_buf[CFG_TUD_VENDOR_RX_BUFSIZE];
#endif
} rx;
} vendord_interface_t;
#define ITF_MEM_RESET_SIZE (offsetof(vendord_interface_t, itf_num) + sizeof(((vendord_interface_t *)0)->itf_num))
static vendord_interface_t _vendord_itf[CFG_TUD_VENDOR];
typedef struct {
TUD_EPBUF_DEF(epout, CFG_TUD_VENDOR_EPSIZE);
TUD_EPBUF_DEF(epin, CFG_TUD_VENDOR_EPSIZE);
} vendord_epbuf_t;
CFG_TUD_MEM_SECTION static vendord_epbuf_t _vendord_epbuf[CFG_TUD_VENDOR];
//--------------------------------------------------------------------
// Application API
//--------------------------------------------------------------------
bool tud_vendor_n_mounted(uint8_t itf) {
TU_VERIFY(itf < CFG_TUD_VENDOR);
vendord_interface_t* p_itf = &_vendord_itf[itf];
return p_itf->rx.stream.ep_addr || p_itf->tx.stream.ep_addr;
}
//--------------------------------------------------------------------+
// Read API
//--------------------------------------------------------------------+
uint32_t tud_vendor_n_available(uint8_t itf) {
TU_VERIFY(itf < CFG_TUD_VENDOR, 0);
vendord_interface_t* p_itf = &_vendord_itf[itf];
return tu_edpt_stream_read_available(&p_itf->rx.stream);
}
bool tud_vendor_n_peek(uint8_t itf, uint8_t* u8) {
TU_VERIFY(itf < CFG_TUD_VENDOR);
vendord_interface_t* p_itf = &_vendord_itf[itf];
return tu_edpt_stream_peek(&p_itf->rx.stream, u8);
}
uint32_t tud_vendor_n_read (uint8_t itf, void* buffer, uint32_t bufsize) {
TU_VERIFY(itf < CFG_TUD_VENDOR, 0);
vendord_interface_t* p_itf = &_vendord_itf[itf];
const uint8_t rhport = 0;
return tu_edpt_stream_read(rhport, &p_itf->rx.stream, buffer, bufsize);
}
void tud_vendor_n_read_flush (uint8_t itf) {
TU_VERIFY(itf < CFG_TUD_VENDOR, );
vendord_interface_t* p_itf = &_vendord_itf[itf];
const uint8_t rhport = 0;
tu_edpt_stream_clear(&p_itf->rx.stream);
tu_edpt_stream_read_xfer(rhport, &p_itf->rx.stream);
}
//--------------------------------------------------------------------+
// Write API
//--------------------------------------------------------------------+
uint32_t tud_vendor_n_write (uint8_t itf, const void* buffer, uint32_t bufsize) {
TU_VERIFY(itf < CFG_TUD_VENDOR, 0);
vendord_interface_t* p_itf = &_vendord_itf[itf];
const uint8_t rhport = 0;
return tu_edpt_stream_write(rhport, &p_itf->tx.stream, buffer, (uint16_t) bufsize);
}
uint32_t tud_vendor_n_write_flush (uint8_t itf) {
TU_VERIFY(itf < CFG_TUD_VENDOR, 0);
vendord_interface_t* p_itf = &_vendord_itf[itf];
const uint8_t rhport = 0;
return tu_edpt_stream_write_xfer(rhport, &p_itf->tx.stream);
}
uint32_t tud_vendor_n_write_available (uint8_t itf) {
TU_VERIFY(itf < CFG_TUD_VENDOR, 0);
vendord_interface_t* p_itf = &_vendord_itf[itf];
const uint8_t rhport = 0;
return tu_edpt_stream_write_available(rhport, &p_itf->tx.stream);
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void vendord_init(void) {
tu_memclr(_vendord_itf, sizeof(_vendord_itf));
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) {
vendord_interface_t* p_itf = &_vendord_itf[i];
vendord_epbuf_t* p_epbuf = &_vendord_epbuf[i];
uint8_t* rx_ff_buf =
#if CFG_TUD_VENDOR_RX_BUFSIZE > 0
p_itf->rx.ff_buf;
#else
NULL;
#endif
tu_edpt_stream_init(&p_itf->rx.stream, false, false, false,
rx_ff_buf, CFG_TUD_VENDOR_RX_BUFSIZE,
p_epbuf->epout, CFG_TUD_VENDOR_EPSIZE);
uint8_t* tx_ff_buf =
#if CFG_TUD_VENDOR_TX_BUFSIZE > 0
p_itf->tx.ff_buf;
#else
NULL;
#endif
tu_edpt_stream_init(&p_itf->tx.stream, false, true, false,
tx_ff_buf, CFG_TUD_VENDOR_TX_BUFSIZE,
p_epbuf->epin, CFG_TUD_VENDOR_EPSIZE);
}
}
bool vendord_deinit(void) {
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) {
vendord_interface_t* p_itf = &_vendord_itf[i];
tu_edpt_stream_deinit(&p_itf->rx.stream);
tu_edpt_stream_deinit(&p_itf->tx.stream);
}
return true;
}
void vendord_reset(uint8_t rhport) {
(void) rhport;
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) {
vendord_interface_t* p_itf = &_vendord_itf[i];
tu_memclr(p_itf, ITF_MEM_RESET_SIZE);
tu_edpt_stream_clear(&p_itf->rx.stream);
tu_edpt_stream_clear(&p_itf->tx.stream);
tu_edpt_stream_close(&p_itf->rx.stream);
tu_edpt_stream_close(&p_itf->tx.stream);
}
}
uint16_t vendord_open(uint8_t rhport, const tusb_desc_interface_t* desc_itf, uint16_t max_len) {
TU_VERIFY(TUSB_CLASS_VENDOR_SPECIFIC == desc_itf->bInterfaceClass, 0);
const uint8_t* p_desc = tu_desc_next(desc_itf);
const uint8_t* desc_end = p_desc + max_len;
// Find available interface
vendord_interface_t* p_vendor = NULL;
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++) {
if (!tud_vendor_n_mounted(i)) {
p_vendor = &_vendord_itf[i];
break;
}
}
TU_VERIFY(p_vendor, 0);
p_vendor->itf_num = desc_itf->bInterfaceNumber;
uint8_t found_ep = 0;
while (found_ep < desc_itf->bNumEndpoints) {
// skip non-endpoint descriptors
while ( (TUSB_DESC_ENDPOINT != tu_desc_type(p_desc)) && (p_desc < desc_end) ) {
p_desc = tu_desc_next(p_desc);
}
if (p_desc >= desc_end) {
break;
}
const tusb_desc_endpoint_t* desc_ep = (const tusb_desc_endpoint_t*) p_desc;
TU_ASSERT(usbd_edpt_open(rhport, desc_ep));
found_ep++;
if (tu_edpt_dir(desc_ep->bEndpointAddress) == TUSB_DIR_IN) {
tu_edpt_stream_open(&p_vendor->tx.stream, desc_ep);
tud_vendor_n_write_flush((uint8_t)(p_vendor - _vendord_itf));
} else {
tu_edpt_stream_open(&p_vendor->rx.stream, desc_ep);
TU_ASSERT(tu_edpt_stream_read_xfer(rhport, &p_vendor->rx.stream) > 0, 0); // prepare for incoming data
}
p_desc = tu_desc_next(p_desc);
}
return (uint16_t) ((uintptr_t) p_desc - (uintptr_t) desc_itf);
}
bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes) {
(void) result;
uint8_t itf;
vendord_interface_t* p_vendor;
for (itf = 0; itf < CFG_TUD_VENDOR; itf++) {
p_vendor = &_vendord_itf[itf];
if ((ep_addr == p_vendor->rx.stream.ep_addr) || (ep_addr == p_vendor->tx.stream.ep_addr)) {
break;
}
}
TU_VERIFY(itf < CFG_TUD_VENDOR);
vendord_epbuf_t* p_epbuf = &_vendord_epbuf[itf];
if ( ep_addr == p_vendor->rx.stream.ep_addr ) {
// Received new data: put into stream's fifo
tu_edpt_stream_read_xfer_complete(&p_vendor->rx.stream, xferred_bytes);
// Invoked callback if any
if (tud_vendor_rx_cb) {
tud_vendor_rx_cb(itf, p_epbuf->epout, (uint16_t) xferred_bytes);
}
tu_edpt_stream_read_xfer(rhport, &p_vendor->rx.stream);
} else if ( ep_addr == p_vendor->tx.stream.ep_addr ) {
// Send complete
if (tud_vendor_tx_cb) {
tud_vendor_tx_cb(itf, (uint16_t) xferred_bytes);
}
#if CFG_TUD_VENDOR_TX_BUFSIZE > 0
// try to send more if possible
if ( 0 == tu_edpt_stream_write_xfer(rhport, &p_vendor->tx.stream) ) {
// If there is no data left, a ZLP should be sent if xferred_bytes is multiple of EP Packet size and not zero
tu_edpt_stream_write_zlp_if_needed(rhport, &p_vendor->tx.stream, xferred_bytes);
}
#endif
}
return true;
}
#endif

View file

@ -0,0 +1,144 @@
/*
* 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
// RX FIFO can be disabled by setting this value to 0
#ifndef CFG_TUD_VENDOR_RX_BUFSIZE
#define CFG_TUD_VENDOR_RX_BUFSIZE 64
#endif
// TX FIFO can be disabled by setting this value to 0
#ifndef CFG_TUD_VENDOR_TX_BUFSIZE
#define CFG_TUD_VENDOR_TX_BUFSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Interfaces) i.e CFG_TUD_VENDOR > 1
//--------------------------------------------------------------------+
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_flush (uint8_t itf);
uint32_t tud_vendor_n_write_available (uint8_t itf);
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str);
// backward compatible
#define tud_vendor_n_flush(itf) tud_vendor_n_write_flush(itf)
//--------------------------------------------------------------------+
// Application API (Single Port) i.e CFG_TUD_VENDOR = 1
//--------------------------------------------------------------------+
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_n_write_str(uint8_t itf, char const* str) {
return tud_vendor_n_write(itf, str, strlen(str));
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_mounted(void) {
return tud_vendor_n_mounted(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_available(void) {
return tud_vendor_n_available(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_read(void* buffer, uint32_t bufsize) {
return tud_vendor_n_read(0, buffer, bufsize);
}
TU_ATTR_ALWAYS_INLINE static inline bool tud_vendor_peek(uint8_t* ui8) {
return tud_vendor_n_peek(0, ui8);
}
TU_ATTR_ALWAYS_INLINE static inline void tud_vendor_read_flush(void) {
tud_vendor_n_read_flush(0);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write(void const* buffer, uint32_t bufsize) {
return tud_vendor_n_write(0, buffer, bufsize);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_str(char const* str) {
return tud_vendor_n_write_str(0, str);
}
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_flush(void) {
return tud_vendor_n_write_flush(0);
}
#if CFG_TUD_VENDOR_TX_BUFSIZE > 0
TU_ATTR_ALWAYS_INLINE static inline uint32_t tud_vendor_write_available(void) {
return tud_vendor_n_write_available(0);
}
#endif
// backward compatible
#define tud_vendor_flush() tud_vendor_write_flush()
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when received new data
TU_ATTR_WEAK void tud_vendor_rx_cb(uint8_t itf, uint8_t const* buffer, uint16_t bufsize);
// Invoked when last rx transfer finished
TU_ATTR_WEAK void tud_vendor_tx_cb(uint8_t itf, uint32_t sent_bytes);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void vendord_init(void);
bool vendord_deinit(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,146 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (CFG_TUH_ENABLED && CFG_TUH_VENDOR)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "host/usbh.h"
#include "vendor_host.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
custom_interface_info_t custom_interface[CFG_TUH_DEVICE_MAX];
static tusb_error_t cush_validate_paras(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length)
{
if ( !tusbh_custom_is_mounted(dev_addr, vendor_id, product_id) )
{
return TUSB_ERROR_DEVICE_NOT_READY;
}
TU_ASSERT( p_buffer != NULL && length != 0, TUSB_ERROR_INVALID_PARA);
return TUSB_ERROR_NONE;
}
//--------------------------------------------------------------------+
// APPLICATION API (need to check parameters)
//--------------------------------------------------------------------+
tusb_error_t tusbh_custom_read(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void * p_buffer, uint16_t length)
{
TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_buffer, length) );
if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_in) )
{
return TUSB_ERROR_INTERFACE_IS_BUSY;
}
(void) usbh_edpt_xfer( custom_interface[dev_addr-1].pipe_in, p_buffer, length);
return TUSB_ERROR_NONE;
}
tusb_error_t tusbh_custom_write(uint8_t dev_addr, uint16_t vendor_id, uint16_t product_id, void const * p_data, uint16_t length)
{
TU_ASSERT_ERR( cush_validate_paras(dev_addr, vendor_id, product_id, p_data, length) );
if ( !hcd_pipe_is_idle(custom_interface[dev_addr-1].pipe_out) )
{
return TUSB_ERROR_INTERFACE_IS_BUSY;
}
(void) usbh_edpt_xfer( custom_interface[dev_addr-1].pipe_out, p_data, length);
return TUSB_ERROR_NONE;
}
//--------------------------------------------------------------------+
// USBH-CLASS API
//--------------------------------------------------------------------+
void cush_init(void)
{
tu_memclr(&custom_interface, sizeof(custom_interface_info_t) * CFG_TUH_DEVICE_MAX);
}
tusb_error_t cush_open_subtask(uint8_t dev_addr, tusb_desc_interface_t const *p_interface_desc, uint16_t *p_length)
{
// FIXME quick hack to test lpc1k custom class with 2 bulk endpoints
uint8_t const *p_desc = (uint8_t const *) p_interface_desc;
p_desc = tu_desc_next(p_desc);
//------------- Bulk Endpoints Descriptor -------------//
for(uint32_t i=0; i<2; i++)
{
tusb_desc_endpoint_t const *p_endpoint = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT(TUSB_DESC_ENDPOINT == p_endpoint->bDescriptorType, TUSB_ERROR_INVALID_PARA);
pipe_handle_t * p_pipe_hdl = ( p_endpoint->bEndpointAddress & TUSB_DIR_IN_MASK ) ?
&custom_interface[dev_addr-1].pipe_in : &custom_interface[dev_addr-1].pipe_out;
*p_pipe_hdl = usbh_edpt_open(dev_addr, p_endpoint, TUSB_CLASS_VENDOR_SPECIFIC);
TU_ASSERT ( pipehandle_is_valid(*p_pipe_hdl), TUSB_ERROR_HCD_OPEN_PIPE_FAILED );
p_desc = tu_desc_next(p_desc);
}
(*p_length) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
return TUSB_ERROR_NONE;
}
void cush_isr(pipe_handle_t pipe_hdl, xfer_result_t event)
{
}
void cush_close(uint8_t dev_addr)
{
tusb_error_t err1, err2;
custom_interface_info_t * p_interface = &custom_interface[dev_addr-1];
// TODO re-consider to check pipe valid before calling pipe_close
if( pipehandle_is_valid( p_interface->pipe_in ) )
{
err1 = hcd_pipe_close( p_interface->pipe_in );
}
if ( pipehandle_is_valid( p_interface->pipe_out ) )
{
err2 = hcd_pipe_close( p_interface->pipe_out );
}
tu_memclr(p_interface, sizeof(custom_interface_info_t));
TU_ASSERT(err1 == TUSB_ERROR_NONE && err2 == TUSB_ERROR_NONE, (void) 0 );
}
#endif

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,697 @@
/*
* 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"
enum {
VIDEO_BCD_1_50 = 0x0150,
};
// 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, // 0x01
VIDEO_VC_CTL_REQUEST_ERROR_CODE, // 0x02
} video_interface_control_selector_t;
/* A.9.8 VideoStreaming Interface Control Selectors */
typedef enum {
VIDEO_VS_CTL_UNDEFINED = 0x00,
VIDEO_VS_CTL_PROBE, // 0x01
VIDEO_VS_CTL_COMMIT, // 0x02
VIDEO_VS_CTL_STILL_PROBE, // 0x03
VIDEO_VS_CTL_STILL_COMMIT, // 0x04
VIDEO_VS_CTL_STILL_IMAGE_TRIGGER, // 0x05
VIDEO_VS_CTL_STREAM_ERROR_CODE, // 0x06
VIDEO_VS_CTL_GENERATE_KEY_FRAME, // 0x07
VIDEO_VS_CTL_UPDATE_FRAME_SEGMENT, // 0x08
VIDEO_VS_CTL_SYNCH_DELAY_CONTROL, // 0x09
} 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;
//--------------------------------------------------------------------+
// Video Control (VC) Descriptors
//--------------------------------------------------------------------+
/* 2.3.4.2 */
#define tusb_desc_video_control_header_nitf_t(_nitf) \
struct TU_ATTR_PACKED { \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint8_t bDescriptorSubType; \
uint16_t bcdUVC; \
uint16_t wTotalLength; \
uint32_t dwClockFrequency; /* deprecated */ \
uint8_t bInCollection; \
uint8_t baInterfaceNr[_nitf]; \
}
typedef tusb_desc_video_control_header_nitf_t() tusb_desc_video_control_header_t;
typedef tusb_desc_video_control_header_nitf_t(1) tusb_desc_video_control_header_1itf_t;
typedef tusb_desc_video_control_header_nitf_t(2) tusb_desc_video_control_header_2itf_t;
typedef tusb_desc_video_control_header_nitf_t(3) tusb_desc_video_control_header_3itf_t;
typedef tusb_desc_video_control_header_nitf_t(4) tusb_desc_video_control_header_4itf_t;
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t iTerminal;
} tusb_desc_video_control_input_terminal_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_control_input_terminal_t) == 8, "size is not correct");
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t bSourceID;
uint8_t iTerminal;
} tusb_desc_video_control_output_terminal_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_control_output_terminal_t) == 9, "size is not correct");
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bTerminalID;
uint16_t wTerminalType;
uint8_t bAssocTerminal;
uint8_t iTerminal;
uint16_t wObjectiveFocalLengthMin;
uint16_t wObjectiveFocalLengthMax;
uint16_t wOcularFocalLength;
uint8_t bControlSize;
uint8_t bmControls[3];
} tusb_desc_video_control_camera_terminal_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_control_camera_terminal_t) == 18, "size is not correct");
//--------------------------------------------------------------------+
// Video Streaming (VS) Descriptors
//--------------------------------------------------------------------+
/* 3.9.2.1 */
#define tusb_desc_video_streaming_input_header_nbyte_t(_nb) \
struct TU_ATTR_PACKED { \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint8_t bDescriptorSubType; \
uint8_t bNumFormats; /* Number of video payload Format descriptors for this interface */ \
uint16_t wTotalLength; \
uint8_t bEndpointAddress; \
uint8_t bmInfo; /* Bit 0: dynamic format change supported */ \
uint8_t bTerminalLink; \
uint8_t bStillCaptureMethod; \
uint8_t bTriggerSupport; /* Hardware trigger supported */ \
uint8_t bTriggerUsage; \
uint8_t bControlSize; /* sizeof of each control item */ \
uint8_t bmaControls[_nb]; \
}
typedef tusb_desc_video_streaming_input_header_nbyte_t() tusb_desc_video_streaming_input_header_t;
typedef tusb_desc_video_streaming_input_header_nbyte_t(1) tusb_desc_video_streaming_input_header_1byte_t;
typedef tusb_desc_video_streaming_input_header_nbyte_t(2) tusb_desc_video_streaming_input_header_2byte_t;
typedef tusb_desc_video_streaming_input_header_nbyte_t(3) tusb_desc_video_streaming_input_header_3byte_t;
typedef tusb_desc_video_streaming_input_header_nbyte_t(4) tusb_desc_video_streaming_input_header_4byte_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_video_streaming_output_header_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_video_streaming_inout_header_t;
// 3.9.2.6 Color Matching Descriptor
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bColorPrimaries;
uint8_t bTransferCharacteristics;
uint8_t bMatrixCoefficients;
} tusb_desc_video_streaming_color_matching_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_streaming_color_matching_t) == 6, "size is not correct");
//--------------------------------------------------------------------+
// Format and Frame Descriptor
// Note: bFormatIndex & bFrameIndex are 1-based index
//--------------------------------------------------------------------+
//------------- Uncompressed -------------//
// Uncompressed payload specs: 3.1.1 format descriptor
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint8_t bNumFrameDescriptors; // Number of frame descriptors for this format
uint8_t guidFormat[16];
uint8_t bBitsPerPixel;
uint8_t bDefaultFrameIndex;
uint8_t bAspectRatioX;
uint8_t bAspectRatioY;
uint8_t bmInterlaceFlags;
uint8_t bCopyProtect;
} tusb_desc_video_format_uncompressed_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_format_uncompressed_t) == 27, "size is not correct");
// Uncompressed payload specs: 3.1.2 frame descriptor
#define tusb_desc_video_frame_uncompressed_nint_t(_nint) \
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 in 1.5 */ \
uint32_t dwDefaultFrameInterval; /* 100ns unit */\
uint8_t bFrameIntervalType; \
uint32_t dwFrameInterval[_nint]; \
}
typedef tusb_desc_video_frame_uncompressed_nint_t() tusb_desc_video_frame_uncompressed_t;
typedef tusb_desc_video_frame_uncompressed_nint_t(1) tusb_desc_video_frame_uncompressed_1int_t;
typedef tusb_desc_video_frame_uncompressed_nint_t(2) tusb_desc_video_frame_uncompressed_2int_t;
typedef tusb_desc_video_frame_uncompressed_nint_t(3) tusb_desc_video_frame_uncompressed_3int_t;
typedef tusb_desc_video_frame_uncompressed_nint_t(4) tusb_desc_video_frame_uncompressed_4int_t;
// continuous = 3 intervals: min, max, step
typedef tusb_desc_video_frame_uncompressed_3int_t tusb_desc_video_frame_uncompressed_continuous_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_frame_uncompressed_continuous_t) == 38, "size is not correct");
//------------- MJPEG -------------//
// MJPEG payload specs: 3.1.1 format descriptor
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint8_t bNumFrameDescriptors;
uint8_t bmFlags; // Bit 0: fixed size samples (1 = yes)
uint8_t bDefaultFrameIndex;
uint8_t bAspectRatioX;
uint8_t bAspectRatioY;
uint8_t bmInterlaceFlags;
uint8_t bCopyProtect;
} tusb_desc_video_format_mjpeg_t;
TU_VERIFY_STATIC(sizeof(tusb_desc_video_format_mjpeg_t) == 11, "size is not correct");
// MJPEG payload specs: 3.1.2 frame descriptor (same as uncompressed)
typedef tusb_desc_video_frame_uncompressed_t tusb_desc_video_frame_mjpeg_t;
typedef tusb_desc_video_frame_uncompressed_1int_t tusb_desc_video_frame_mjpeg_1int_t;
typedef tusb_desc_video_frame_uncompressed_2int_t tusb_desc_video_frame_mjpeg_2int_t;
typedef tusb_desc_video_frame_uncompressed_3int_t tusb_desc_video_frame_mjpeg_3int_t;
typedef tusb_desc_video_frame_uncompressed_4int_t tusb_desc_video_frame_mjpeg_4int_t;
// continuous = 3 intervals: min, max, step
typedef tusb_desc_video_frame_mjpeg_3int_t tusb_desc_video_frame_mjpeg_continuous_t;
//------------- DV -------------//
// DV payload specs: 3.1.1
typedef struct TU_ATTR_PACKED {
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bDescriptorSubType;
uint8_t bFormatIndex;
uint32_t dwMaxVideoFrameBufferSize; /* deprecated */
uint8_t bFormatType;
} tusb_desc_video_format_dv_t;
// Frame Based payload specs: 3.1.1
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;
uint8_t bVaribaleSize;
} tusb_desc_video_format_framebased_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 dwDefaultFrameInterval;
uint8_t bFrameIntervalType;
uint32_t dwBytesPerLine;
uint32_t dwFrameInterval[];
} tusb_desc_video_frame_framebased_t;
//--------------------------------------------------------------------+
// Requests
//--------------------------------------------------------------------+
/* 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;
/* 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_FMT_MJPEG_LEN 11
#define TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED_LEN 28
#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_FRM_MJPEG_CONT_LEN 38
#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_DISC_LEN 26
#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT_LEN 38
#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_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_GUID_H264 0x48,0x32,0x36,0x34,0x00,0x00,0x10,0x00,0x80,0x00,0x00,0xAA,0x00,0x38,0x9B,0x71
#define TUD_VIDEO_DESC_IAD(_firstitf, _nitfs, _stridx) \
TUD_VIDEO_DESC_IAD_LEN, TUSB_DESC_INTERFACE_ASSOCIATION, \
_firstitf, _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__
/* Motion-JPEG 3.1.1 Table 3-1 */
#define TUD_VIDEO_DESC_CS_VS_FMT_MJPEG(_fmtidx, _numfrmdesc, _fixed_sz, _frmidx, _asrx, _asry, _interlace, _cp) \
TUD_VIDEO_DESC_CS_VS_FMT_MJPEG_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FORMAT_MJPEG, \
_fmtidx, _numfrmdesc, _fixed_sz, _frmidx, _asrx, _asry, _interlace, _cp
/* Motion-JPEG 3.1.1 Table 3-2 and 3-3 */
#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_CONT(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, _minfrminterval, _maxfrminterval, _frmintervalstep) \
TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_CONT_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_MJPEG, \
_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)
/* Motion-JPEG 3.1.1 Table 3-2 and 3-4 */
#define TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_DISC(_frmidx, _cap, _width, _height, _minbr, _maxbr, _maxfrmbufsz, _frminterval, ...) \
TUD_VIDEO_DESC_CS_VS_FRM_MJPEG_DISC_LEN + (TU_ARGS_NUM(__VA_ARGS__)) * 4, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_MJPEG, \
_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__
/* Motion-Frame-Based 3.1.1 Table 3-1 */
#define TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED(_fmtidx, _numfrmdesc, _guid, _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp, _variablesize) \
TUD_VIDEO_DESC_CS_VS_FMT_FRAME_BASED_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FORMAT_FRAME_BASED, \
_fmtidx, _numfrmdesc, TUD_VIDEO_GUID(_guid), _bitsperpix, _frmidx, _asrx, _asry, _interlace, _cp, _variablesize
/* Motion-Frame-Based 3.1.1 Table 3-2 and 3-3 */
#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT(_frmidx, _cap, _width, _height, _minbr, _maxbr, _frminterval, _bytesperline, _minfrminterval, _maxfrminterval, _frmintervalstep) \
TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_CONT_LEN, TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_FRAME_BASED, \
_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(_frminterval), 0, U32_TO_U8S_LE(_bytesperline), \
U32_TO_U8S_LE(_minfrminterval), U32_TO_U8S_LE(_maxfrminterval), U32_TO_U8S_LE(_frmintervalstep)
/* Motion-Frame-Based 3.1.1 Table 3-2 and 3-4 */
#define TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_DISC(_frmidx, _cap, _width, _height, _minbr, _maxbr, _frminterval, _bytesperline, ...) \
TUD_VIDEO_DESC_CS_VS_FRM_FRAME_BASED_DISC_LEN + (TU_ARGS_NUM(__VA_ARGS__)) * 4, \
TUSB_DESC_CS_INTERFACE, VIDEO_CS_ITF_VS_FRAME_FRAME_BASED, \
_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(_frminterval), U32_TO_U8S_LE(_bytesperline), (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, (uint8_t) (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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,100 @@
/*
* 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
//--------------------------------------------------------------------+
bool tud_video_n_connected(uint_fast8_t ctl_idx);
/** 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);
bool videod_deinit (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