get msc & hid example work with metro m0 express

This commit is contained in:
hathach 2019-04-30 00:12:17 +07:00
parent ff2cb608a9
commit 9c07070580
63 changed files with 10420 additions and 8 deletions

View file

@ -0,0 +1,108 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach for Adafruit
*
* 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.
*/
#ifdef USBCON
#include "Arduino.h"
#include "Adafruit_TinyUSB_Core.h"
//--------------------------------------------------------------------+
// MACRO TYPEDEF CONSTANT ENUM DECLARATION
//--------------------------------------------------------------------+
// Serial is 64-bit DeviceID -> 16 chars len
uint16_t usb_desc_str_serial[1+16] = { TUD_DESC_STR_HEADER(16) };
// Init usb hardware when starting up. Softdevice is not enabled yet
static void usb_hardware_init(void)
{
#ifdef PIN_LED_TXL
// txLEDPulse = 0;
pinMode(PIN_LED_TXL, OUTPUT);
digitalWrite(PIN_LED_TXL, HIGH);
#endif
#ifdef PIN_LED_RXL
// rxLEDPulse = 0;
pinMode(PIN_LED_RXL, OUTPUT);
digitalWrite(PIN_LED_RXL, HIGH);
#endif
/* Enable USB clock */
#if defined(__SAMD51__)
MCLK->APBBMASK.reg |= MCLK_APBBMASK_USB;
MCLK->AHBMASK.reg |= MCLK_AHBMASK_USB;
// Set up the USB DP/DN pins
PORT->Group[0].PINCFG[PIN_PA24H_USB_DM].bit.PMUXEN = 1;
PORT->Group[0].PMUX[PIN_PA24H_USB_DM/2].reg &= ~(0xF << (4 * (PIN_PA24H_USB_DM & 0x01u)));
PORT->Group[0].PMUX[PIN_PA24H_USB_DM/2].reg |= MUX_PA24H_USB_DM << (4 * (PIN_PA24H_USB_DM & 0x01u));
PORT->Group[0].PINCFG[PIN_PA25H_USB_DP].bit.PMUXEN = 1;
PORT->Group[0].PMUX[PIN_PA25H_USB_DP/2].reg &= ~(0xF << (4 * (PIN_PA25H_USB_DP & 0x01u)));
PORT->Group[0].PMUX[PIN_PA25H_USB_DP/2].reg |= MUX_PA25H_USB_DP << (4 * (PIN_PA25H_USB_DP & 0x01u));
GCLK->PCHCTRL[USB_GCLK_ID].reg = GCLK_PCHCTRL_GEN_GCLK1_Val | (1 << GCLK_PCHCTRL_CHEN_Pos);
#else
PM->APBBMASK.reg |= PM_APBBMASK_USB;
// Set up the USB DP/DN pins
PORT->Group[0].PINCFG[PIN_PA24G_USB_DM].bit.PMUXEN = 1;
PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg &= ~(0xF << (4 * (PIN_PA24G_USB_DM & 0x01u)));
PORT->Group[0].PMUX[PIN_PA24G_USB_DM/2].reg |= MUX_PA24G_USB_DM << (4 * (PIN_PA24G_USB_DM & 0x01u));
PORT->Group[0].PINCFG[PIN_PA25G_USB_DP].bit.PMUXEN = 1;
PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg &= ~(0xF << (4 * (PIN_PA25G_USB_DP & 0x01u)));
PORT->Group[0].PMUX[PIN_PA25G_USB_DP/2].reg |= MUX_PA25G_USB_DP << (4 * (PIN_PA25G_USB_DP & 0x01u));
// Put Generic Clock Generator 0 as source for Generic Clock Multiplexer 6 (USB reference)
GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(6) | // Generic Clock Multiplexer 6
GCLK_CLKCTRL_GEN_GCLK0 | // Generic Clock Generator 0 is source
GCLK_CLKCTRL_CLKEN;
while (GCLK->STATUS.bit.SYNCBUSY)
;
#endif
}
void Adafruit_TinyUSB_Core_init(void)
{
// Create Serial string descriptor
// char tmp_serial[17];
// sprintf(tmp_serial, "%08lX%08lX", NRF_FICR->DEVICEID[1], NRF_FICR->DEVICEID[0]);
//
// for(uint8_t i=0; i<16; i++)
// {
// usb_desc_str_serial[1+i] = tmp_serial[i];
// }
USBDevice.addInterface( (Adafruit_USBD_Interface&) Serial);
USBDevice.setID(USB_VID, USB_PID);
USBDevice.begin();
usb_hardware_init();
// Init tinyusb stack
tusb_init();
}
#endif

View file

@ -0,0 +1,38 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach 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 ADAFRUIT_TINYUSB_CORE_H_
#define ADAFRUIT_TINYUSB_CORE_H_
#include "tusb.h"
#ifdef __cplusplus
#include "Adafruit_USBD_Device.h"
#include "Adafruit_USBD_CDC.h"
#endif
// Called by main.cpp to initialize usb device typically with CDC device for Serial
void Adafruit_TinyUSB_Core_init(void);
#endif /* ADAFRUIT_TINYUSB_CORE_H_ */

View file

@ -0,0 +1,142 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach 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.
*/
#ifdef USBCON
#include "Arduino.h"
#include <Reset.h> // Needed for auto-reset with 1200bps port touch
#include "Adafruit_USBD_CDC.h"
#define EPOUT 0x00
#define EPIN 0x80
Adafruit_USBD_CDC Serial;
Adafruit_USBD_CDC::Adafruit_USBD_CDC(void)
{
}
uint16_t Adafruit_USBD_CDC::getDescriptor(uint8_t* buf, uint16_t bufsize)
{
// CDC is mostly always existed for DFU
uint8_t desc[] = { TUD_CDC_DESCRIPTOR(0, 0, EPIN, 8, EPOUT, EPIN, 64) };
uint16_t const len = sizeof(desc);
if ( bufsize < len ) return 0;
memcpy(buf, desc, len);
return len;
}
// Baud and config is ignore in CDC
void Adafruit_USBD_CDC::begin (uint32_t baud)
{
}
void Adafruit_USBD_CDC::begin (uint32_t baud, uint8_t config)
{
}
void Adafruit_USBD_CDC::end(void)
{
// nothing to do
}
Adafruit_USBD_CDC::operator bool()
{
return tud_cdc_connected();
}
int Adafruit_USBD_CDC::available(void)
{
return tud_cdc_available();
}
int Adafruit_USBD_CDC::peek(void)
{
return tud_cdc_peek(0);
}
int Adafruit_USBD_CDC::read(void)
{
return (int) tud_cdc_read_char();
}
size_t Adafruit_USBD_CDC::readBytes(char *buffer, size_t length)
{
return tud_cdc_read(buffer, length);
}
void Adafruit_USBD_CDC::flush(void)
{
tud_cdc_write_flush();
}
size_t Adafruit_USBD_CDC::write(uint8_t ch)
{
return tud_cdc_write_char((char) ch);
}
size_t Adafruit_USBD_CDC::write(const uint8_t *buffer, size_t size)
{
size_t remain = size;
while ( remain && tud_cdc_connected() )
{
size_t wrcount = tud_cdc_write(buffer, remain);
remain -= wrcount;
buffer += wrcount;
// Write FIFO is full, flush and re-try
if ( remain )
{
tud_cdc_write_flush();
}
}
return size - remain;
}
extern "C"
{
// Invoked when cdc when line state changed e.g connected/disconnected
// Use to reset to DFU when disconnect with 1200 bps
void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
{
(void) itf; // interface ID, not used
// DTR = false is counted as disconnected
if ( !dtr )
{
cdc_line_coding_t coding;
tud_cdc_get_line_coding(&coding);
if ( coding.bit_rate == 1200 ) initiateReset(250);
}
}
}
#endif // NRF52840_XXAA

View file

@ -0,0 +1,61 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach 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 ADAFRUIT_USBD_CDC_H_
#define ADAFRUIT_USBD_CDC_H_
#include "Adafruit_USBD_Device.h"
#include "Stream.h"
class Adafruit_USBD_CDC : public Stream, Adafruit_USBD_Interface
{
public:
Adafruit_USBD_CDC(void);
// fron Adafruit_USBD_Interface
virtual uint16_t getDescriptor(uint8_t* buf, uint16_t bufsize);
void setPins(uint8_t pin_rx, uint8_t pin_tx) { (void) pin_rx; (void) pin_tx; }
void begin(uint32_t baud_count);
void begin(uint32_t baud, uint8_t config);
void end(void);
virtual int available(void);
virtual int peek(void);
virtual int read(void);
virtual void flush(void);
virtual size_t write(uint8_t);
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *buffer, size_t size) {
return write((const uint8_t *)buffer, size);
}
operator bool();
size_t readBytes(char *buffer, size_t length);
size_t readBytes(uint8_t *buffer, size_t length) { return readBytes((char *)buffer, length); }
};
extern Adafruit_USBD_CDC Serial;
#endif /* ADAFRUIT_USBD_CDC_H_ */

View file

@ -0,0 +1,187 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach 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.
*/
#ifdef USBCON
#include "Adafruit_USBD_Device.h"
extern "C"
{
extern uint16_t usb_desc_str_serial[1+16];
// array of pointer to string descriptors
uint16_t const * const string_desc_arr [] =
{
// 0: is supported language = English
TUD_DESC_STRCONV(0x0409),
// 1: Manufacturer
TUD_DESC_STRCONV('A','d','a','f','r','u','i','t',' ','I','n','d','u','s','t','r','i','e','s'),
// 2: Product
TUD_DESC_STRCONV('B','l','u','e','f','r','u','i','t',' ','n','R','F','5','2','8','4','0'),
// 3: Serials
usb_desc_str_serial,
// // 4: CDC Interface
// TUD_DESC_STRCONV('B','l','u','e','f','r','u','i','t',' ','S','e','r','i','a','l'),
//
// // 5: MSC Interface
// TUD_DESC_STRCONV('B','l','u','e','f','r','u','i','t',' ','U','F','2'),
};
// tud_desc_set is required by tinyusb stack
tud_desc_set_t tud_desc_set =
{
.device = NULL, // update later
.config = NULL, // update later
.string_arr = (uint8_t const **) string_desc_arr,
.string_count = sizeof(string_desc_arr)/sizeof(string_desc_arr[0]),
.hid_report = NULL // update later
};
} // extern C
Adafruit_USBD_Device USBDevice;
Adafruit_USBD_Device::Adafruit_USBD_Device(void)
{
tusb_desc_device_t desc_dev =
{
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
.bcdUSB = 0x0200,
#if CFG_TUD_CDC
// Use Interface Association Descriptor (IAD) for CDC
// As required by USB Specs IAD's subclass must be common class (2) and protocol must be IAD (1)
.bDeviceClass = TUSB_CLASS_MISC,
.bDeviceSubClass = MISC_SUBCLASS_COMMON,
.bDeviceProtocol = MISC_PROTOCOL_IAD,
#else
.bDeviceClass = 0x00,
.bDeviceSubClass = 0x00,
.bDeviceProtocol = 0x00,
#endif
.bMaxPacketSize0 = CFG_TUD_ENDOINT0_SIZE,
.idVendor = 0,
.idProduct = 0,
.bcdDevice = 0x0100,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
_desc_device = desc_dev;
tusb_desc_configuration_t dev_cfg =
{
.bLength = sizeof(tusb_desc_configuration_t),
.bDescriptorType = TUSB_DESC_CONFIGURATION,
// Total Length & Interface Number will be updated later
.wTotalLength = 0,
.bNumInterfaces = 0,
.bConfigurationValue = 1,
.iConfiguration = 0x00,
.bmAttributes = TU_BIT(7) | TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP,
.bMaxPower = TUSB_DESC_CONFIG_POWER_MA(100)
};
memcpy(_desc_cfg, &dev_cfg, sizeof(tusb_desc_configuration_t));
_desc_cfglen = sizeof(tusb_desc_configuration_t);
_itf_count = 0;
_epin_count = _epout_count = 1;
tud_desc_set.config = _desc_cfg;
tud_desc_set.device = &_desc_device;
}
// Add interface descriptor
// - Interface number will be updated to match current count
// - Endpoint number is updated to be unique
bool Adafruit_USBD_Device::addInterface(Adafruit_USBD_Interface& itf)
{
uint8_t* desc = _desc_cfg+_desc_cfglen;
uint16_t const len = itf.getDescriptor(desc, sizeof(_desc_cfg)-_desc_cfglen);
uint8_t* desc_end = desc+len;
if ( !len ) return false;
// Handle IAD
if ( desc[1] == TUSB_DESC_INTERFACE_ASSOCIATION )
{
// update starting interface
((tusb_desc_interface_assoc_t*) desc)->bFirstInterface = _itf_count;
desc += desc[0]; // next
}
while (desc < desc_end)
{
if (desc[1] == TUSB_DESC_INTERFACE)
{
// No alternate interface support
((tusb_desc_interface_t*) desc)->bInterfaceNumber = _itf_count++;
}else if (desc[1] == TUSB_DESC_ENDPOINT)
{
tusb_desc_endpoint_t* desc_ep = (tusb_desc_endpoint_t*) desc;
desc_ep->bEndpointAddress |= (desc_ep->bEndpointAddress & 0x80) ? _epin_count++ : _epout_count++;
}
if (desc[0] == 0) return false;
desc += desc[0]; // next
}
_desc_cfglen += len;
// Update config descriptor
tusb_desc_configuration_t* config = (tusb_desc_configuration_t*)_desc_cfg;
config->wTotalLength = _desc_cfglen;
config->bNumInterfaces = _itf_count;
return true;
}
void Adafruit_USBD_Device::setID(uint16_t vid, uint16_t pid)
{
_desc_device.idVendor = vid;
_desc_device.idProduct = pid;
}
bool Adafruit_USBD_Device::begin(void)
{
return true;
}
#endif

View file

@ -0,0 +1,65 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach 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 ADAFRUIT_USBD_DEVICE_H_
#define ADAFRUIT_USBD_DEVICE_H_
#include "tusb.h"
class Adafruit_USBD_Interface
{
public:
virtual uint16_t getDescriptor(uint8_t* buf, uint16_t bufsize) = 0;
};
class Adafruit_USBD_Device
{
private:
tusb_desc_device_t _desc_device;
uint8_t _desc_cfg[256];
uint16_t _desc_cfglen;
uint8_t _itf_count;
uint8_t _epin_count;
uint8_t _epout_count;
public:
Adafruit_USBD_Device(void);
bool addInterface(Adafruit_USBD_Interface& itf);
void setID(uint16_t vid, uint16_t pid);
bool begin(void);
bool mounted(void) { return tud_mounted(); }
bool suspended(void) { return tud_suspended(); }
bool ready(void) { return tud_ready(); }
bool remoteWakeup(void) { return tud_remote_wakeup(); }
};
extern Adafruit_USBD_Device USBDevice;
#endif /* ADAFRUIT_USBD_DEVICE_H_ */

View file

@ -0,0 +1,66 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_Audio Audio
* Currently only MIDI subclass is supported
* @{ */
#ifndef _TUSB_CDC_H__
#define _TUSB_CDC_H__
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
/// Audio Interface Subclass Codes
typedef enum
{
AUDIO_SUBCLASS_AUDIO_CONTROL = 0x01 , ///< Audio Control
AUDIO_SUBCLASS_AUDIO_STREAMING , ///< Audio Streaming
AUDIO_SUBCLASS_MIDI_STREAMING , ///< MIDI Streaming
} audio_subclass_type_t;
/// Audio Protocol Codes
typedef enum
{
AUDIO_PROTOCOL_V1 = 0x00, ///< Version 1.0
AUDIO_PROTOCOL_V2 = 0x20, ///< Version 2.0
AUDIO_PROTOCOL_V3 = 0x30, ///< Version 3.0
} audio_protocol_type_t;
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View file

@ -0,0 +1,401 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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 Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In)
typedef enum
{
CDC_PIPE_NOTIFICATION , ///< Notification pipe
CDC_PIPE_DATA_IN , ///< Data in pipe
CDC_PIPE_DATA_OUT , ///< Data out pipe
CDC_PIPE_ERROR , ///< Invalid Pipe ID
}cdc_pipeid_t;
//--------------------------------------------------------------------+
// CDC COMMUNICATION INTERFACE CLASS
//--------------------------------------------------------------------+
/// Communication Interface Subclass Codes
typedef enum
{
CDC_COMM_SUBCLASS_DIRECT_LINE_CONTROL_MODEL = 0x01 , ///< Direct Line Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL , ///< Abstract Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_TELEPHONE_CONTROL_MODEL , ///< Telephone Control Model [USBPSTN1.2]
CDC_COMM_SUBCLASS_MULTICHANNEL_CONTROL_MODEL , ///< Multi-Channel Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_CAPI_CONTROL_MODEL , ///< CAPI Control Model [USBISDN1.2]
CDC_COMM_SUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL , ///< Ethernet Networking Control Model [USBECM1.2]
CDC_COMM_SUBCLASS_ATM_NETWORKING_CONTROL_MODEL , ///< ATM Networking Control Model [USBATM1.2]
CDC_COMM_SUBCLASS_WIRELESS_HANDSET_CONTROL_MODEL , ///< Wireless Handset Control Model [USBWMC1.1]
CDC_COMM_SUBCLASS_DEVICE_MANAGEMENT , ///< Device Management [USBWMC1.1]
CDC_COMM_SUBCLASS_MOBILE_DIRECT_LINE_MODEL , ///< Mobile Direct Line Model [USBWMC1.1]
CDC_COMM_SUBCLASS_OBEX , ///< OBEX [USBWMC1.1]
CDC_COMM_SUBCLASS_ETHERNET_EMULATION_MODEL ///< Ethernet Emulation Model [USBEEM1.0]
} cdc_comm_sublcass_type_t;
/// Communication Interface Protocol Codes
typedef enum
{
CDC_COMM_PROTOCOL_NONE = 0x00 , ///< No specific protocol
CDC_COMM_PROTOCOL_ATCOMMAND , ///< AT Commands: V.250 etc
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101 , ///< AT Commands defined by PCCA-101
CDC_COMM_PROTOCOL_ATCOMMAND_PCCA_101_AND_ANNEXO , ///< AT Commands defined by PCCA-101 & Annex O
CDC_COMM_PROTOCOL_ATCOMMAND_GSM_707 , ///< AT Commands defined by GSM 07.07
CDC_COMM_PROTOCOL_ATCOMMAND_3GPP_27007 , ///< AT Commands defined by 3GPP 27.007
CDC_COMM_PROTOCOL_ATCOMMAND_CDMA , ///< AT Commands defined by TIA for CDMA
CDC_COMM_PROTOCOL_ETHERNET_EMULATION_MODEL ///< 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_type_t;
//--------------------------------------------------------------------+
// CDC DATA INTERFACE CLASS
//--------------------------------------------------------------------+
// SUBCLASS code of Data Interface is not used and should/must be zero
/// Data Interface Protocol Codes
typedef enum{
CDC_DATA_PROTOCOL_ISDN_BRI = 0x30, ///< Physical interface protocol for ISDN BRI
CDC_DATA_PROTOCOL_HDLC = 0x31, ///< HDLC
CDC_DATA_PROTOCOL_TRANSPARENT = 0x32, ///< Transparent
CDC_DATA_PROTOCOL_Q921_MANAGEMENT = 0x50, ///< Management protocol for Q.921 data link protocol
CDC_DATA_PROTOCOL_Q921_DATA_LINK = 0x51, ///< Data link protocol for Q.931
CDC_DATA_PROTOCOL_Q921_TEI_MULTIPLEXOR = 0x52, ///< TEI-multiplexor for Q.921 data link protocol
CDC_DATA_PROTOCOL_V42BIS_DATA_COMPRESSION = 0x90, ///< Data compression procedures
CDC_DATA_PROTOCOL_EURO_ISDN = 0x91, ///< Euro-ISDN protocol control
CDC_DATA_PROTOCOL_V24_RATE_ADAPTION_TO_ISDN = 0x92, ///< V.24 rate adaptation to ISDN
CDC_DATA_PROTOCOL_CAPI_COMMAND = 0x93, ///< CAPI Commands
CDC_DATA_PROTOCOL_HOST_BASED_DRIVER = 0xFD, ///< Host based driver. Note: This protocol code should only be used in messages between host and device to identify the host driver portion of a protocol stack.
CDC_DATA_PROTOCOL_IN_PROTOCOL_UNIT_FUNCTIONAL_DESCRIPTOR = 0xFE ///< The protocol(s) are described using a ProtocolUnit Functional Descriptors on Communications Class Interface
}cdc_data_protocol_type_t;
//--------------------------------------------------------------------+
// MANAGEMENT ELEMENT REQUEST (CONTROL ENDPOINT)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Request Codes
typedef enum
{
CDC_REQUEST_SEND_ENCAPSULATED_COMMAND = 0x00, ///< is used to issue a command in the format of the supported control protocol of the Communications Class interface
CDC_REQUEST_GET_ENCAPSULATED_RESPONSE = 0x01, ///< is used to request a response in the format of the supported control protocol of the Communications Class interface.
CDC_REQUEST_SET_COMM_FEATURE = 0x02,
CDC_REQUEST_GET_COMM_FEATURE = 0x03,
CDC_REQUEST_CLEAR_COMM_FEATURE = 0x04,
CDC_REQUEST_SET_AUX_LINE_STATE = 0x10,
CDC_REQUEST_SET_HOOK_STATE = 0x11,
CDC_REQUEST_PULSE_SETUP = 0x12,
CDC_REQUEST_SEND_PULSE = 0x13,
CDC_REQUEST_SET_PULSE_TIME = 0x14,
CDC_REQUEST_RING_AUX_JACK = 0x15,
CDC_REQUEST_SET_LINE_CODING = 0x20,
CDC_REQUEST_GET_LINE_CODING = 0x21,
CDC_REQUEST_SET_CONTROL_LINE_STATE = 0x22,
CDC_REQUEST_SEND_BREAK = 0x23,
CDC_REQUEST_SET_RINGER_PARMS = 0x30,
CDC_REQUEST_GET_RINGER_PARMS = 0x31,
CDC_REQUEST_SET_OPERATION_PARMS = 0x32,
CDC_REQUEST_GET_OPERATION_PARMS = 0x33,
CDC_REQUEST_SET_LINE_PARMS = 0x34,
CDC_REQUEST_GET_LINE_PARMS = 0x35,
CDC_REQUEST_DIAL_DIGITS = 0x36,
CDC_REQUEST_SET_UNIT_PARAMETER = 0x37,
CDC_REQUEST_GET_UNIT_PARAMETER = 0x38,
CDC_REQUEST_CLEAR_UNIT_PARAMETER = 0x39,
CDC_REQUEST_GET_PROFILE = 0x3A,
CDC_REQUEST_SET_ETHERNET_MULTICAST_FILTERS = 0x40,
CDC_REQUEST_SET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x41,
CDC_REQUEST_GET_ETHERNET_POWER_MANAGEMENT_PATTERN_FILTER = 0x42,
CDC_REQUEST_SET_ETHERNET_PACKET_FILTER = 0x43,
CDC_REQUEST_GET_ETHERNET_STATISTIC = 0x44,
CDC_REQUEST_SET_ATM_DATA_FORMAT = 0x50,
CDC_REQUEST_GET_ATM_DEVICE_STATISTICS = 0x51,
CDC_REQUEST_SET_ATM_DEFAULT_VC = 0x52,
CDC_REQUEST_GET_ATM_VC_STATISTICS = 0x53,
CDC_REQUEST_MDLM_SEMANTIC_MODEL = 0x60,
}cdc_management_request_t;
//--------------------------------------------------------------------+
// MANAGEMENT ELEMENENT NOTIFICATION (NOTIFICATION ENDPOINT)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Notification Codes
typedef enum
{
NETWORK_CONNECTION = 0x00, ///< This notification allows the device to notify the host about network connection status.
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.
AUX_JACK_HOOK_STATE = 0x08,
RING_DETECT = 0x09,
SERIAL_STATE = 0x20,
CALL_STATE_CHANGE = 0x28,
LINE_STATE_CHANGE = 0x29,
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
MDLM_SEMANTIC_MODEL_NOTIFICATION = 0x40,
}cdc_notification_request_t;
//--------------------------------------------------------------------+
// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE)
//--------------------------------------------------------------------+
/// Header Functional Descriptor (Communication Interface)
typedef struct 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_
uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal
}cdc_desc_func_header_t;
/// Union Functional Descriptor (Communication Interface)
typedef struct 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 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 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 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 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 : 0;
} bmCapabilities;
uint8_t bDataInterface;
}cdc_desc_func_call_management_t;
typedef struct 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 : 0;
}cdc_acm_capability_t;
TU_VERIFY_STATIC(sizeof(cdc_acm_capability_t) == 1, "mostly problem with compiler");
/// \brief Abstract Control Management Functional Descriptor
/// \details 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 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 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 : 0;
} 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 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 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 : 0;
} 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 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 : 0;
} bmCapabilities;
}cdc_desc_func_telephone_call_state_reporting_capabilities_t;
static inline uint8_t cdc_functional_desc_typeof(uint8_t const * p_desc)
{
return p_desc[2];
}
//--------------------------------------------------------------------+
// Requests
//--------------------------------------------------------------------+
typedef struct 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 ATTR_PACKED
{
uint16_t dte_is_present : 1; ///< Indicates to DCE if DTE is presentor not. This signal corresponds to V.24 signal 108/2 and RS-232 signal DTR.
uint16_t half_duplex_carrier_control : 1;
uint16_t : 14;
} cdc_line_control_state_t;
TU_VERIFY_STATIC(sizeof(cdc_line_control_state_t) == 2, "size is not correct");
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View file

@ -0,0 +1,408 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CDC)
#include "cdc_device.h"
#include "device/usbd_pvt.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
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;
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];
#if CFG_FIFO_MUTEX
osal_mutex_def_t rx_ff_mutex;
osal_mutex_def_t tx_ff_mutex;
#endif
// Endpoint Transfer buffer
CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_CDC_EPSIZE];
CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_CDC_EPSIZE];
}cdcd_interface_t;
#define ITF_MEM_RESET_SIZE offsetof(cdcd_interface_t, wanted_char)
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC] = { { 0 } };
// TODO will be replaced by dcd_edpt_busy()
bool pending_read_from_host;
static void _prep_out_transaction (uint8_t itf)
{
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
// skip if previous transfer not complete
// dcd_edpt_busy() doesn't work, probably transfer is complete but not properly handled by the stack
// if ( dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_out) ) return;
if (pending_read_from_host) return;
// Prepare for incoming data but only allow what we can store in the ring buffer.
uint16_t max_read = tu_fifo_remaining(&p_cdc->rx_ff);
if ( max_read >= CFG_TUD_CDC_EPSIZE )
{
dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE);
pending_read_from_host = true;
}
}
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
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);
}
char tud_cdc_n_read_char(uint8_t itf)
{
char ch;
return tud_cdc_n_read(itf, &ch, 1) ? ch : (-1);
}
uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize)
{
uint32_t num_read = tu_fifo_read_n(&_cdcd_itf[itf].rx_ff, buffer, bufsize);
_prep_out_transaction(itf);
return num_read;
}
char tud_cdc_n_peek(uint8_t itf, int pos)
{
char ch;
return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, &ch) ? ch : (-1);
}
void tud_cdc_n_read_flush (uint8_t itf)
{
tu_fifo_clear(&_cdcd_itf[itf].rx_ff);
_prep_out_transaction(itf);
}
//--------------------------------------------------------------------+
// WRITE API
//--------------------------------------------------------------------+
uint32_t tud_cdc_n_write_char(uint8_t itf, char ch)
{
return tud_cdc_n_write(itf, &ch, 1);
}
uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str)
{
return tud_cdc_n_write(itf, str, strlen(str));
}
uint32_t tud_cdc_n_write(uint8_t itf, void const* buffer, uint32_t bufsize)
{
uint16_t ret = tu_fifo_write_n(&_cdcd_itf[itf].tx_ff, buffer, bufsize);
#if 0 // TODO issue with circuitpython's REPL
// flush if queue more than endpoint size
if ( tu_fifo_count(&_cdcd_itf[itf].tx_ff) >= CFG_TUD_CDC_EPSIZE )
{
tud_cdc_n_write_flush(itf);
}
#endif
return ret;
}
bool tud_cdc_n_write_flush (uint8_t itf)
{
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
TU_VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, p_cdc->ep_in) ); // skip if previous transfer not complete
uint16_t count = tu_fifo_read_n(&_cdcd_itf[itf].tx_ff, p_cdc->epin_buf, CFG_TUD_CDC_EPSIZE);
if ( count )
{
TU_VERIFY( tud_cdc_n_connected(itf) ); // fifo is empty if not connected
TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_in, p_cdc->epin_buf, count) );
}
return true;
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void cdcd_init(void)
{
tu_memclr(_cdcd_itf, sizeof(_cdcd_itf));
for(uint8_t i=0; i<CFG_TUD_CDC; i++)
{
cdcd_interface_t* p_cdc = &_cdcd_itf[i];
p_cdc->wanted_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 fifo
tu_fifo_config(&p_cdc->rx_ff, p_cdc->rx_ff_buf, CFG_TUD_CDC_RX_BUFSIZE, 1, false);
tu_fifo_config(&p_cdc->tx_ff, p_cdc->tx_ff_buf, CFG_TUD_CDC_TX_BUFSIZE, 1, false);
#if CFG_FIFO_MUTEX
tu_fifo_config_mutex(&p_cdc->rx_ff, osal_mutex_create(&p_cdc->rx_ff_mutex));
tu_fifo_config_mutex(&p_cdc->tx_ff, osal_mutex_create(&p_cdc->tx_ff_mutex));
#endif
}
}
void cdcd_reset(uint8_t rhport)
{
(void) rhport;
for(uint8_t i=0; i<CFG_TUD_CDC; i++)
{
tu_memclr(&_cdcd_itf[i], ITF_MEM_RESET_SIZE);
tu_fifo_clear(&_cdcd_itf[i].rx_ff);
tu_fifo_clear(&_cdcd_itf[i].tx_ff);
}
}
bool cdcd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length)
{
// Only support ACM subclass
TU_ASSERT ( CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL == itf_desc->bInterfaceSubClass);
// Only support AT commands, no protocol and vendor specific commands.
TU_ASSERT(tu_within(CDC_COMM_PROTOCOL_NONE, itf_desc->bInterfaceProtocol, CDC_COMM_PROTOCOL_ATCOMMAND_CDMA) ||
itf_desc->bInterfaceProtocol == 0xff);
// Find available interface
cdcd_interface_t * p_cdc = NULL;
uint8_t cdc_id;
for(cdc_id=0; cdc_id<CFG_TUD_CDC; cdc_id++)
{
if ( _cdcd_itf[cdc_id].ep_in == 0 )
{
p_cdc = &_cdcd_itf[cdc_id];
break;
}
}
TU_ASSERT(p_cdc);
//------------- Control Interface -------------//
p_cdc->itf_num = itf_desc->bInterfaceNumber;
uint8_t const * p_desc = tu_desc_next( itf_desc );
(*p_length) = sizeof(tusb_desc_interface_t);
// Communication Functional Descriptors
while ( TUSB_DESC_CLASS_SPECIFIC == tu_desc_type(p_desc) )
{
(*p_length) += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
{
// notification endpoint if any
TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc) );
p_cdc->ep_notif = ((tusb_desc_endpoint_t const *) p_desc)->bEndpointAddress;
(*p_length) += p_desc[DESC_OFFSET_LEN];
p_desc = tu_desc_next(p_desc);
}
//------------- Data Interface (if any) -------------//
if ( (TUSB_DESC_INTERFACE == p_desc[DESC_OFFSET_TYPE]) &&
(TUSB_CLASS_CDC_DATA == ((tusb_desc_interface_t const *) p_desc)->bInterfaceClass) )
{
// next to endpoint descriptor
(*p_length) += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
// Open endpoint pair with usbd helper
tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_cdc->ep_out, &p_cdc->ep_in) );
(*p_length) += 2*sizeof(tusb_desc_endpoint_t);
}
// Prepare for incoming data
pending_read_from_host = false;
_prep_out_transaction(cdc_id);
return true;
}
// Invoked when class request DATA stage is finished.
// return false to stall control endpoint (e.g Host send non-sense DATA)
bool cdcd_control_request_complete(uint8_t rhport, tusb_control_request_t const * request)
{
(void) rhport;
//------------- Class Specific Request -------------//
TU_VERIFY (request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
// TODO Support multiple interfaces
uint8_t const itf = 0;
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
// Invoke callback
if ( CDC_REQUEST_SET_LINE_CODING == request->bRequest )
{
if ( tud_cdc_line_coding_cb ) tud_cdc_line_coding_cb(itf, &p_cdc->line_coding);
}
return true;
}
// Handle class control request
// return false to stall control endpoint (e.g unsupported request)
bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request)
{
//------------- Class Specific Request -------------//
TU_ASSERT(request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
// TODO Support multiple interfaces
uint8_t const itf = 0;
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
switch ( request->bRequest )
{
case CDC_REQUEST_SET_LINE_CODING:
usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
break;
case CDC_REQUEST_GET_LINE_CODING:
usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
break;
case CDC_REQUEST_SET_CONTROL_LINE_STATE:
// 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)
p_cdc->line_state = (uint8_t) request->wValue;
usbd_control_status(rhport, request);
// Invoke callback
if ( tud_cdc_line_state_cb) tud_cdc_line_state_cb(itf, TU_BIT_TEST(request->wValue, 0), TU_BIT_TEST(request->wValue, 1));
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) rhport;
(void) result;
// TODO Support multiple interfaces
uint8_t const itf = 0;
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
// receive new data
if ( ep_addr == p_cdc->ep_out )
{
for(uint32_t i=0; i<xferred_bytes; i++)
{
tu_fifo_write(&p_cdc->rx_ff, &p_cdc->epout_buf[i]);
// Check for wanted char and invoke callback if needed
if ( tud_cdc_rx_wanted_cb && ( ((signed char) p_cdc->wanted_char) != -1 ) && ( p_cdc->wanted_char == p_cdc->epout_buf[i] ) )
{
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_count(&p_cdc->rx_ff) ) tud_cdc_rx_cb(itf);
// prepare for OUT transaction
pending_read_from_host = false;
_prep_out_transaction(itf);
}
// nothing to do with in and notif endpoint for now
return true;
}
#endif

View file

@ -0,0 +1,114 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_CDC_DEVICE_H_
#define _TUSB_CDC_DEVICE_H_
#include "common/tusb_common.h"
#include "device/usbd.h"
#include "cdc.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUD_CDC_EPSIZE
#define CFG_TUD_CDC_EPSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup CDC_Serial Serial
* @{
* \defgroup CDC_Serial_Device Device
* @{ */
//--------------------------------------------------------------------+
// APPLICATION API (Multiple Interfaces)
// CFG_TUD_CDC > 1
//--------------------------------------------------------------------+
bool tud_cdc_n_connected (uint8_t itf);
uint8_t tud_cdc_n_get_line_state (uint8_t itf);
void tud_cdc_n_get_line_coding (uint8_t itf, cdc_line_coding_t* coding);
void tud_cdc_n_set_wanted_char (uint8_t itf, char wanted);
uint32_t tud_cdc_n_available (uint8_t itf);
char tud_cdc_n_read_char (uint8_t itf);
uint32_t tud_cdc_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
void tud_cdc_n_read_flush (uint8_t itf);
char tud_cdc_n_peek (uint8_t itf, int pos);
uint32_t tud_cdc_n_write_char (uint8_t itf, char ch);
uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str);
bool tud_cdc_n_write_flush (uint8_t itf);
//--------------------------------------------------------------------+
// APPLICATION API (Interface0)
//--------------------------------------------------------------------+
static inline bool tud_cdc_connected (void) { return tud_cdc_n_connected(0); }
static inline uint8_t tud_cdc_get_line_state (void) { return tud_cdc_n_get_line_state(0); }
static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding) { return tud_cdc_n_get_line_coding(0, coding);}
static inline void tud_cdc_set_wanted_char (char wanted) { tud_cdc_n_set_wanted_char(0, wanted); }
static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); }
static inline char tud_cdc_read_char (void) { return tud_cdc_n_read_char(0); }
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize) { return tud_cdc_n_read(0, buffer, bufsize); }
static inline void tud_cdc_read_flush (void) { tud_cdc_n_read_flush(0); }
static inline char tud_cdc_peek (int pos) { return tud_cdc_n_peek(0, pos); }
static inline uint32_t tud_cdc_write_char (char ch) { return tud_cdc_n_write_char(0, ch); }
static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize) { return tud_cdc_n_write(0, buffer, bufsize); }
static inline uint32_t tud_cdc_write_str (char const* str) { return tud_cdc_n_write_str(0, str); }
static inline bool tud_cdc_write_flush (void) { return tud_cdc_n_write_flush(0); }
//--------------------------------------------------------------------+
// APPLICATION CALLBACK API (WEAK is optional)
//--------------------------------------------------------------------+
ATTR_WEAK void tud_cdc_rx_cb(uint8_t itf);
ATTR_WEAK void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char);
ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts);
ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding);
/** @} */
/** @} */
//--------------------------------------------------------------------+
// INTERNAL USBD-CLASS DRIVER API
//--------------------------------------------------------------------+
void cdcd_init (void);
bool cdcd_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length);
bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * p_request);
bool cdcd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
void cdcd_reset (uint8_t rhport);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CDC_DEVICE_H_ */

View file

@ -0,0 +1,93 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_CUSTOM_CLASS)
#include "common/tusb_common.h"
#include "custom_device.h"
#include "device/usbd_pvt.h"
/*------------------------------------------------------------------*/
/* MACRO TYPEDEF CONSTANT ENUM
*------------------------------------------------------------------*/
/*------------------------------------------------------------------*/
/* VARIABLE DECLARATION
*------------------------------------------------------------------*/
typedef struct {
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
} cusd_interface_t;
static cusd_interface_t _cusd_itf;
/*------------------------------------------------------------------*/
/* FUNCTION DECLARATION
*------------------------------------------------------------------*/
void cusd_init(void)
{
tu_varclr(&_cusd_itf);
}
bool cusd_open(uint8_t rhport, tusb_desc_interface_t const * p_desc_itf, uint16_t *p_len)
{
cusd_interface_t* p_itf = &_cusd_itf;
// Open endpoint pair with usbd helper
tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next(p_desc_itf);
TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_itf->ep_out, &p_itf->ep_in) );
p_itf->itf_num = p_desc_itf->bInterfaceNumber;
(*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
// TODO Prepare for incoming data
// TU_ASSERT( dcd_edpt_xfer(rhport, p_itf->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
return true;
}
bool cusd_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
{
return false;
}
bool cusd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
{
return true;
}
void cusd_reset(uint8_t rhport)
{
}
#endif

View file

@ -0,0 +1,58 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_CUSTOM_DEVICE_H_
#define _TUSB_CUSTOM_DEVICE_H_
#include "common/tusb_common.h"
#include "device/usbd.h"
//--------------------------------------------------------------------+
// APPLICATION API (Multiple Root Ports)
// Should be used only with MCU that support more than 1 ports
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// APPLICATION API (Single Port)
// Should be used with MCU supporting only 1 USB port for code simplicity
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// APPLICATION CALLBACK API (WEAK is optional)
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void cusd_init(void);
bool cusd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool cusd_control_request_st(uint8_t rhport, tusb_control_request_t const * p_request);
bool cusd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
bool cusd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void cusd_reset(uint8_t rhport);
#endif /* _TUSB_CUSTOM_DEVICE_H_ */

View file

@ -0,0 +1,606 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_HID Human Interface Device (HID)
* @{ */
#ifndef _TUSB_HID_H_
#define _TUSB_HID_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Common Definitions
//--------------------------------------------------------------------+
/** \defgroup ClassDriver_HID_Common Common Definitions
* @{ */
/// HID Subclass
typedef enum
{
HID_SUBCLASS_NONE = 0, ///< No Subclass
HID_SUBCLASS_BOOT = 1 ///< Boot Interface Subclass
}hid_subclass_type_t;
/// HID Protocol
typedef enum
{
HID_PROTOCOL_NONE = 0, ///< None
HID_PROTOCOL_KEYBOARD = 1, ///< Keyboard
HID_PROTOCOL_MOUSE = 2 ///< Mouse
}hid_protocol_type_t;
/// HID Descriptor Type
typedef enum
{
HID_DESC_TYPE_HID = 0x21, ///< HID Descriptor
HID_DESC_TYPE_REPORT = 0x22, ///< Report Descriptor
HID_DESC_TYPE_PHYSICAL = 0x23 ///< Physical Descriptor
}hid_descriptor_type_t;
/// HID Request Report Type
typedef enum
{
HID_REPORT_TYPE_INPUT = 1, ///< Input
HID_REPORT_TYPE_OUTPUT, ///< Output
HID_REPORT_TYPE_FEATURE ///< Feature
}hid_report_type_t;
/// HID Class Specific Control Request
typedef enum
{
HID_REQ_CONTROL_GET_REPORT = 0x01, ///< Get Report
HID_REQ_CONTROL_GET_IDLE = 0x02, ///< Get Idle
HID_REQ_CONTROL_GET_PROTOCOL = 0x03, ///< Get Protocol
HID_REQ_CONTROL_SET_REPORT = 0x09, ///< Set Report
HID_REQ_CONTROL_SET_IDLE = 0x0a, ///< Set Idle
HID_REQ_CONTROL_SET_PROTOCOL = 0x0b ///< Set Protocol
}hid_request_type_t;
/// USB HID Descriptor
typedef struct ATTR_PACKED
{
uint8_t bLength; /**< Numeric expression that is the total size of the HID descriptor */
uint8_t bDescriptorType; /**< Constant name specifying type of HID descriptor. */
uint16_t bcdHID; /**< Numeric expression identifying the HID Class Specification release */
uint8_t bCountryCode; /**< Numeric expression identifying country code of the localized hardware. */
uint8_t bNumDescriptors; /**< Numeric expression specifying the number of class descriptors */
uint8_t bReportType; /**< Type of HID class report. */
uint16_t wReportLength; /**< the total size of the Report descriptor. */
} tusb_hid_descriptor_hid_t;
/// HID Country Code
typedef enum
{
HID_Local_NotSupported = 0 , ///< NotSupported
HID_Local_Arabic , ///< Arabic
HID_Local_Belgian , ///< Belgian
HID_Local_Canadian_Bilingual , ///< Canadian_Bilingual
HID_Local_Canadian_French , ///< Canadian_French
HID_Local_Czech_Republic , ///< Czech_Republic
HID_Local_Danish , ///< Danish
HID_Local_Finnish , ///< Finnish
HID_Local_French , ///< French
HID_Local_German , ///< German
HID_Local_Greek , ///< Greek
HID_Local_Hebrew , ///< Hebrew
HID_Local_Hungary , ///< Hungary
HID_Local_International , ///< International
HID_Local_Italian , ///< Italian
HID_Local_Japan_Katakana , ///< Japan_Katakana
HID_Local_Korean , ///< Korean
HID_Local_Latin_American , ///< Latin_American
HID_Local_Netherlands_Dutch , ///< Netherlands/Dutch
HID_Local_Norwegian , ///< Norwegian
HID_Local_Persian_Farsi , ///< Persian (Farsi)
HID_Local_Poland , ///< Poland
HID_Local_Portuguese , ///< Portuguese
HID_Local_Russia , ///< Russia
HID_Local_Slovakia , ///< Slovakia
HID_Local_Spanish , ///< Spanish
HID_Local_Swedish , ///< Swedish
HID_Local_Swiss_French , ///< Swiss/French
HID_Local_Swiss_German , ///< Swiss/German
HID_Local_Switzerland , ///< Switzerland
HID_Local_Taiwan , ///< Taiwan
HID_Local_Turkish_Q , ///< Turkish-Q
HID_Local_UK , ///< UK
HID_Local_US , ///< US
HID_Local_Yugoslavia , ///< Yugoslavia
HID_Local_Turkish_F ///< Turkish-F
} hid_country_code_t;
/** @} */
//--------------------------------------------------------------------+
// MOUSE
//--------------------------------------------------------------------+
/** \addtogroup ClassDriver_HID_Mouse Mouse
* @{ */
/// Standard HID Boot Protocol Mouse Report.
typedef struct ATTR_PACKED
{
uint8_t buttons; /**< buttons mask for currently pressed buttons in the mouse. */
int8_t x; /**< Current delta x movement of the mouse. */
int8_t y; /**< Current delta y movement on the mouse. */
int8_t wheel; /**< Current delta wheel movement on the mouse. */
// int8_t pan;
} hid_mouse_report_t;
/// Standard Mouse Buttons Bitmap
typedef enum
{
MOUSE_BUTTON_LEFT = TU_BIT(0), ///< Left button
MOUSE_BUTTON_RIGHT = TU_BIT(1), ///< Right button
MOUSE_BUTTON_MIDDLE = TU_BIT(2), ///< Middle button
MOUSE_BUTTON_BACKWARD = TU_BIT(3), ///< Backward button,
MOUSE_BUTTON_FORWARD = TU_BIT(4), ///< Forward button,
}hid_mouse_button_bm_t;
/// @}
//--------------------------------------------------------------------+
// Keyboard
//--------------------------------------------------------------------+
/** \addtogroup ClassDriver_HID_Keyboard Keyboard
* @{ */
/// Standard HID Boot Protocol Keyboard Report.
typedef struct ATTR_PACKED
{
uint8_t modifier; /**< Keyboard modifier (KEYBOARD_MODIFER_* masks). */
uint8_t reserved; /**< Reserved for OEM use, always set to 0. */
uint8_t keycode[6]; /**< Key codes of the currently pressed keys. */
} hid_keyboard_report_t;
/// Keyboard modifier codes bitmap
typedef enum
{
KEYBOARD_MODIFIER_LEFTCTRL = TU_BIT(0), ///< Left Control
KEYBOARD_MODIFIER_LEFTSHIFT = TU_BIT(1), ///< Left Shift
KEYBOARD_MODIFIER_LEFTALT = TU_BIT(2), ///< Left Alt
KEYBOARD_MODIFIER_LEFTGUI = TU_BIT(3), ///< Left Window
KEYBOARD_MODIFIER_RIGHTCTRL = TU_BIT(4), ///< Right Control
KEYBOARD_MODIFIER_RIGHTSHIFT = TU_BIT(5), ///< Right Shift
KEYBOARD_MODIFIER_RIGHTALT = TU_BIT(6), ///< Right Alt
KEYBOARD_MODIFIER_RIGHTGUI = TU_BIT(7) ///< Right Window
}hid_keyboard_modifier_bm_t;
typedef enum
{
KEYBOARD_LED_NUMLOCK = TU_BIT(0), ///< Num Lock LED
KEYBOARD_LED_CAPSLOCK = TU_BIT(1), ///< Caps Lock LED
KEYBOARD_LED_SCROLLLOCK = TU_BIT(2), ///< Scroll Lock LED
KEYBOARD_LED_COMPOSE = TU_BIT(3), ///< Composition Mode
KEYBOARD_LED_KANA = TU_BIT(4) ///< Kana mode
}hid_keyboard_led_bm_t;
/// @}
//--------------------------------------------------------------------+
// HID KEYCODE
//--------------------------------------------------------------------+
#define HID_KEY_NONE 0x00
#define HID_KEY_A 0x04
#define HID_KEY_B 0x05
#define HID_KEY_C 0x06
#define HID_KEY_D 0x07
#define HID_KEY_E 0x08
#define HID_KEY_F 0x09
#define HID_KEY_G 0x0A
#define HID_KEY_H 0x0B
#define HID_KEY_I 0x0C
#define HID_KEY_J 0x0D
#define HID_KEY_K 0x0E
#define HID_KEY_L 0x0F
#define HID_KEY_M 0x10
#define HID_KEY_N 0x11
#define HID_KEY_O 0x12
#define HID_KEY_P 0x13
#define HID_KEY_Q 0x14
#define HID_KEY_R 0x15
#define HID_KEY_S 0x16
#define HID_KEY_T 0x17
#define HID_KEY_U 0x18
#define HID_KEY_V 0x19
#define HID_KEY_W 0x1A
#define HID_KEY_X 0x1B
#define HID_KEY_Y 0x1C
#define HID_KEY_Z 0x1D
#define HID_KEY_1 0x1E
#define HID_KEY_2 0x1F
#define HID_KEY_3 0x20
#define HID_KEY_4 0x21
#define HID_KEY_5 0x22
#define HID_KEY_6 0x23
#define HID_KEY_7 0x24
#define HID_KEY_8 0x25
#define HID_KEY_9 0x26
#define HID_KEY_0 0x27
#define HID_KEY_RETURN 0x28
#define HID_KEY_ESCAPE 0x29
#define HID_KEY_BACKSPACE 0x2A
#define HID_KEY_TAB 0x2B
#define HID_KEY_SPACE 0x2C
#define HID_KEY_MINUS 0x2D
#define HID_KEY_EQUAL 0x2E
#define HID_KEY_BRACKET_LEFT 0x2F
#define HID_KEY_BRACKET_RIGHT 0x30
#define HID_KEY_BACKSLASH 0x31
#define HID_KEY_EUROPE_1 0x32
#define HID_KEY_SEMICOLON 0x33
#define HID_KEY_APOSTROPHE 0x34
#define HID_KEY_GRAVE 0x35
#define HID_KEY_COMMA 0x36
#define HID_KEY_PERIOD 0x37
#define HID_KEY_SLASH 0x38
#define HID_KEY_CAPS_LOCK 0x39
#define HID_KEY_F1 0x3A
#define HID_KEY_F2 0x3B
#define HID_KEY_F3 0x3C
#define HID_KEY_F4 0x3D
#define HID_KEY_F5 0x3E
#define HID_KEY_F6 0x3F
#define HID_KEY_F7 0x40
#define HID_KEY_F8 0x41
#define HID_KEY_F9 0x42
#define HID_KEY_F10 0x43
#define HID_KEY_F11 0x44
#define HID_KEY_F12 0x45
#define HID_KEY_PRINT_SCREEN 0x46
#define HID_KEY_SCROLL_LOCK 0x47
#define HID_KEY_PAUSE 0x48
#define HID_KEY_INSERT 0x49
#define HID_KEY_HOME 0x4A
#define HID_KEY_PAGE_UP 0x4B
#define HID_KEY_DELETE 0x4C
#define HID_KEY_END 0x4D
#define HID_KEY_PAGE_DOWN 0x4E
#define HID_KEY_ARROW_RIGHT 0x4F
#define HID_KEY_ARROW_LEFT 0x50
#define HID_KEY_ARROW_DOWN 0x51
#define HID_KEY_ARROW_UP 0x52
#define HID_KEY_NUM_LOCK 0x53
#define HID_KEY_KEYPAD_DIVIDE 0x54
#define HID_KEY_KEYPAD_MULTIPLY 0x55
#define HID_KEY_KEYPAD_SUBTRACT 0x56
#define HID_KEY_KEYPAD_ADD 0x57
#define HID_KEY_KEYPAD_ENTER 0x58
#define HID_KEY_KEYPAD_1 0x59
#define HID_KEY_KEYPAD_2 0x5A
#define HID_KEY_KEYPAD_3 0x5B
#define HID_KEY_KEYPAD_4 0x5C
#define HID_KEY_KEYPAD_5 0x5D
#define HID_KEY_KEYPAD_6 0x5E
#define HID_KEY_KEYPAD_7 0x5F
#define HID_KEY_KEYPAD_8 0x60
#define HID_KEY_KEYPAD_9 0x61
#define HID_KEY_KEYPAD_0 0x62
#define HID_KEY_KEYPAD_DECIMAL 0x63
#define HID_KEY_EUROPE_2 0x64
#define HID_KEY_APPLICATION 0x65
#define HID_KEY_POWER 0x66
#define HID_KEY_KEYPAD_EQUAL 0x67
#define HID_KEY_F13 0x68
#define HID_KEY_F14 0x69
#define HID_KEY_F15 0x6A
#define HID_KEY_CONTROL_LEFT 0xE0
#define HID_KEY_SHIFT_LEFT 0xE1
#define HID_KEY_ALT_LEFT 0xE2
#define HID_KEY_GUI_LEFT 0xE3
#define HID_KEY_CONTROL_RIGHT 0xE4
#define HID_KEY_SHIFT_RIGHT 0xE5
#define HID_KEY_ALT_RIGHT 0xE6
#define HID_KEY_GUI_RIGHT 0xE7
//--------------------------------------------------------------------+
// REPORT DESCRIPTOR
//--------------------------------------------------------------------+
//------------- ITEM & TAG -------------//
#define HID_REPORT_DATA_0(data)
#define HID_REPORT_DATA_1(data) , data
#define HID_REPORT_DATA_2(data) , U16_TO_U8S_LE(data)
#define HID_REPORT_DATA_3(data) , U32_TO_U8S_LE(data)
#define HID_REPORT_ITEM(data, tag, type, size) \
(((tag) << 4) | ((type) << 2) | (size)) HID_REPORT_DATA_##size(data)
#define RI_TYPE_MAIN 0
#define RI_TYPE_GLOBAL 1
#define RI_TYPE_LOCAL 2
//------------- MAIN ITEMS 6.2.2.4 -------------//
#define HID_INPUT(x) HID_REPORT_ITEM(x, 8, RI_TYPE_MAIN, 1)
#define HID_OUTPUT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_MAIN, 1)
#define HID_COLLECTION(x) HID_REPORT_ITEM(x, 10, RI_TYPE_MAIN, 1)
#define HID_FEATURE(x) HID_REPORT_ITEM(x, 11, RI_TYPE_MAIN, 1)
#define HID_COLLECTION_END HID_REPORT_ITEM(x, 12, RI_TYPE_MAIN, 0)
//------------- INPUT, OUTPUT, FEATURE 6.2.2.5 -------------//
#define HID_DATA (0<<0)
#define HID_CONSTANT (1<<0)
#define HID_ARRAY (0<<1)
#define HID_VARIABLE (1<<1)
#define HID_ABSOLUTE (0<<2)
#define HID_RELATIVE (1<<2)
#define HID_WRAP_NO (0<<3)
#define HID_WRAP (1<<3)
#define HID_LINEAR (0<<4)
#define HID_NONLINEAR (1<<4)
#define HID_PREFERRED_STATE (0<<5)
#define HID_PREFERRED_NO (1<<5)
#define HID_NO_NULL_POSITION (0<<6)
#define HID_NULL_STATE (1<<6)
#define HID_NON_VOLATILE (0<<7)
#define HID_VOLATILE (1<<7)
#define HID_BITFIELD (0<<8)
#define HID_BUFFERED_BYTES (1<<8)
//------------- COLLECTION ITEM 6.2.2.6 -------------//
enum {
HID_COLLECTION_PHYSICAL = 0,
HID_COLLECTION_APPLICATION,
HID_COLLECTION_LOGICAL,
HID_COLLECTION_REPORT,
HID_COLLECTION_NAMED_ARRAY,
HID_COLLECTION_USAGE_SWITCH,
HID_COLLECTION_USAGE_MODIFIER
};
//------------- GLOBAL ITEMS 6.2.2.7 -------------//
#define HID_USAGE_PAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, 1)
#define HID_USAGE_PAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_GLOBAL, n)
#define HID_LOGICAL_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, 1)
#define HID_LOGICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_GLOBAL, n)
#define HID_LOGICAL_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, 1)
#define HID_LOGICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_GLOBAL, n)
#define HID_PHYSICAL_MIN(x) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, 1)
#define HID_PHYSICAL_MIN_N(x, n) HID_REPORT_ITEM(x, 3, RI_TYPE_GLOBAL, n)
#define HID_PHYSICAL_MAX(x) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, 1)
#define HID_PHYSICAL_MAX_N(x, n) HID_REPORT_ITEM(x, 4, RI_TYPE_GLOBAL, n)
#define HID_UNIT_EXPONENT(x) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, 1)
#define HID_UNIT_EXPONENT_N(x, n) HID_REPORT_ITEM(x, 5, RI_TYPE_GLOBAL, n)
#define HID_UNIT(x) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, 1)
#define HID_UNIT_N(x, n) HID_REPORT_ITEM(x, 6, RI_TYPE_GLOBAL, n)
#define HID_REPORT_SIZE(x) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, 1)
#define HID_REPORT_SIZE_N(x, n) HID_REPORT_ITEM(x, 7, RI_TYPE_GLOBAL, n)
#define HID_REPORT_ID(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, 1)
#define HID_REPORT_ID_N(x) HID_REPORT_ITEM(x, 8, RI_TYPE_GLOBAL, n)
#define HID_REPORT_COUNT(x) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, 1)
#define HID_REPORT_COUNT_N(x, n) HID_REPORT_ITEM(x, 9, RI_TYPE_GLOBAL, n)
#define HID_PUSH HID_REPORT_ITEM(x, 10, RI_TYPE_GLOBAL, 0)
#define HID_POP HID_REPORT_ITEM(x, 11, RI_TYPE_GLOBAL, 0)
//------------- LOCAL ITEMS 6.2.2.8 -------------//
#define HID_USAGE(x) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, 1)
#define HID_USAGE_N(x, n) HID_REPORT_ITEM(x, 0, RI_TYPE_LOCAL, n)
#define HID_USAGE_MIN(x) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, 1)
#define HID_USAGE_MIN_N(x, n) HID_REPORT_ITEM(x, 1, RI_TYPE_LOCAL, n)
#define HID_USAGE_MAX(x) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, 1)
#define HID_USAGE_MAX_N(x, n) HID_REPORT_ITEM(x, 2, RI_TYPE_LOCAL, n)
//--------------------------------------------------------------------+
// Usage Table
//--------------------------------------------------------------------+
/// HID Usage Table - Table 1: Usage Page Summary
enum {
HID_USAGE_PAGE_DESKTOP = 0x01,
HID_USAGE_PAGE_SIMULATE = 0x02,
HID_USAGE_PAGE_VIRTUAL_REALITY = 0x03,
HID_USAGE_PAGE_SPORT = 0x04,
HID_USAGE_PAGE_GAME = 0x05,
HID_USAGE_PAGE_GENERIC_DEVICE = 0x06,
HID_USAGE_PAGE_KEYBOARD = 0x07,
HID_USAGE_PAGE_LED = 0x08,
HID_USAGE_PAGE_BUTTON = 0x09,
HID_USAGE_PAGE_ORDINAL = 0x0a,
HID_USAGE_PAGE_TELEPHONY = 0x0b,
HID_USAGE_PAGE_CONSUMER = 0x0c,
HID_USAGE_PAGE_DIGITIZER = 0x0d,
HID_USAGE_PAGE_PID = 0x0f,
HID_USAGE_PAGE_UNICODE = 0x10,
HID_USAGE_PAGE_ALPHA_DISPLAY = 0x14,
HID_USAGE_PAGE_MEDICAL = 0x40,
HID_USAGE_PAGE_MONITOR = 0x80, //0x80 - 0x83
HID_USAGE_PAGE_POWER = 0x84, // 0x084 - 0x87
HID_USAGE_PAGE_BARCODE_SCANNER = 0x8c,
HID_USAGE_PAGE_SCALE = 0x8d,
HID_USAGE_PAGE_MSR = 0x8e,
HID_USAGE_PAGE_CAMERA = 0x90,
HID_USAGE_PAGE_ARCADE = 0x91,
HID_USAGE_PAGE_VENDOR = 0xFFFF // 0xFF00 - 0xFFFF
};
/// HID Usage Table - Table 6: Generic Desktop Page
enum {
HID_USAGE_DESKTOP_POINTER = 0x01,
HID_USAGE_DESKTOP_MOUSE = 0x02,
HID_USAGE_DESKTOP_JOYSTICK = 0x04,
HID_USAGE_DESKTOP_GAMEPAD = 0x05,
HID_USAGE_DESKTOP_KEYBOARD = 0x06,
HID_USAGE_DESKTOP_KEYPAD = 0x07,
HID_USAGE_DESKTOP_MULTI_AXIS_CONTROLLER = 0x08,
HID_USAGE_DESKTOP_TABLET_PC_SYSTEM = 0x09,
HID_USAGE_DESKTOP_X = 0x30,
HID_USAGE_DESKTOP_Y = 0x31,
HID_USAGE_DESKTOP_Z = 0x32,
HID_USAGE_DESKTOP_RX = 0x33,
HID_USAGE_DESKTOP_RY = 0x34,
HID_USAGE_DESKTOP_RZ = 0x35,
HID_USAGE_DESKTOP_SLIDER = 0x36,
HID_USAGE_DESKTOP_DIAL = 0x37,
HID_USAGE_DESKTOP_WHEEL = 0x38,
HID_USAGE_DESKTOP_HAT_SWITCH = 0x39,
HID_USAGE_DESKTOP_COUNTED_BUFFER = 0x3a,
HID_USAGE_DESKTOP_BYTE_COUNT = 0x3b,
HID_USAGE_DESKTOP_MOTION_WAKEUP = 0x3c,
HID_USAGE_DESKTOP_START = 0x3d,
HID_USAGE_DESKTOP_SELECT = 0x3e,
HID_USAGE_DESKTOP_VX = 0x40,
HID_USAGE_DESKTOP_VY = 0x41,
HID_USAGE_DESKTOP_VZ = 0x42,
HID_USAGE_DESKTOP_VBRX = 0x43,
HID_USAGE_DESKTOP_VBRY = 0x44,
HID_USAGE_DESKTOP_VBRZ = 0x45,
HID_USAGE_DESKTOP_VNO = 0x46,
HID_USAGE_DESKTOP_FEATURE_NOTIFICATION = 0x47,
HID_USAGE_DESKTOP_RESOLUTION_MULTIPLIER = 0x48,
HID_USAGE_DESKTOP_SYSTEM_CONTROL = 0x80,
HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN = 0x81,
HID_USAGE_DESKTOP_SYSTEM_SLEEP = 0x82,
HID_USAGE_DESKTOP_SYSTEM_WAKE_UP = 0x83,
HID_USAGE_DESKTOP_SYSTEM_CONTEXT_MENU = 0x84,
HID_USAGE_DESKTOP_SYSTEM_MAIN_MENU = 0x85,
HID_USAGE_DESKTOP_SYSTEM_APP_MENU = 0x86,
HID_USAGE_DESKTOP_SYSTEM_MENU_HELP = 0x87,
HID_USAGE_DESKTOP_SYSTEM_MENU_EXIT = 0x88,
HID_USAGE_DESKTOP_SYSTEM_MENU_SELECT = 0x89,
HID_USAGE_DESKTOP_SYSTEM_MENU_RIGHT = 0x8A,
HID_USAGE_DESKTOP_SYSTEM_MENU_LEFT = 0x8B,
HID_USAGE_DESKTOP_SYSTEM_MENU_UP = 0x8C,
HID_USAGE_DESKTOP_SYSTEM_MENU_DOWN = 0x8D,
HID_USAGE_DESKTOP_SYSTEM_COLD_RESTART = 0x8E,
HID_USAGE_DESKTOP_SYSTEM_WARM_RESTART = 0x8F,
HID_USAGE_DESKTOP_DPAD_UP = 0x90,
HID_USAGE_DESKTOP_DPAD_DOWN = 0x91,
HID_USAGE_DESKTOP_DPAD_RIGHT = 0x92,
HID_USAGE_DESKTOP_DPAD_LEFT = 0x93,
HID_USAGE_DESKTOP_SYSTEM_DOCK = 0xA0,
HID_USAGE_DESKTOP_SYSTEM_UNDOCK = 0xA1,
HID_USAGE_DESKTOP_SYSTEM_SETUP = 0xA2,
HID_USAGE_DESKTOP_SYSTEM_BREAK = 0xA3,
HID_USAGE_DESKTOP_SYSTEM_DEBUGGER_BREAK = 0xA4,
HID_USAGE_DESKTOP_APPLICATION_BREAK = 0xA5,
HID_USAGE_DESKTOP_APPLICATION_DEBUGGER_BREAK = 0xA6,
HID_USAGE_DESKTOP_SYSTEM_SPEAKER_MUTE = 0xA7,
HID_USAGE_DESKTOP_SYSTEM_HIBERNATE = 0xA8,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INVERT = 0xB0,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_INTERNAL = 0xB1,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_EXTERNAL = 0xB2,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_BOTH = 0xB3,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_DUAL = 0xB4,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_TOGGLE_INT_EXT = 0xB5,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_SWAP_PRIMARY_SECONDARY = 0xB6,
HID_USAGE_DESKTOP_SYSTEM_DISPLAY_LCD_AUTOSCALE = 0xB7
};
/// HID Usage Table: Consumer Page (0x0C)
/// Only contains controls that supported by Windows (whole list is too long)
enum
{
// Generic Control
HID_USAGE_CONSUMER_CONTROL = 0x0001,
// Power Control
HID_USAGE_CONSUMER_POWER = 0x0030,
HID_USAGE_CONSUMER_RESET = 0x0031,
HID_USAGE_CONSUMER_SLEEP = 0x0032,
// Screen Brightness
HID_USAGE_CONSUMER_BRIGHTNESS_INCREMENT = 0x006F,
HID_USAGE_CONSUMER_BRIGHTNESS_DECREMENT = 0x0070,
// These HID usages operate only on mobile systems (battery powered) and
// require Windows 8 (build 8302 or greater).
HID_USAGE_CONSUMER_WIRELESS_RADIO_CONTROLS = 0x000C,
HID_USAGE_CONSUMER_WIRELESS_RADIO_BUTTONS = 0x00C6,
HID_USAGE_CONSUMER_WIRELESS_RADIO_LED = 0x00C7,
HID_USAGE_CONSUMER_WIRELESS_RADIO_SLIDER_SWITCH = 0x00C8,
// Media Control
HID_USAGE_CONSUMER_PLAY_PAUSE = 0x00CD,
HID_USAGE_CONSUMER_SCAN_NEXT = 0x00B5,
HID_USAGE_CONSUMER_SCAN_PREVIOUS = 0x00B6,
HID_USAGE_CONSUMER_STOP = 0x00B7,
HID_USAGE_CONSUMER_VOLUME = 0x00E0,
HID_USAGE_CONSUMER_MUTE = 0x00E2,
HID_USAGE_CONSUMER_BASS = 0x00E3,
HID_USAGE_CONSUMER_TREBLE = 0x00E4,
HID_USAGE_CONSUMER_BASS_BOOST = 0x00E5,
HID_USAGE_CONSUMER_VOLUME_INCREMENT = 0x00E9,
HID_USAGE_CONSUMER_VOLUME_DECREMENT = 0x00EA,
HID_USAGE_CONSUMER_BASS_INCREMENT = 0x0152,
HID_USAGE_CONSUMER_BASS_DECREMENT = 0x0153,
HID_USAGE_CONSUMER_TREBLE_INCREMENT = 0x0154,
HID_USAGE_CONSUMER_TREBLE_DECREMENT = 0x0155,
// Application Launcher
HID_USAGE_CONSUMER_AL_CONSUMER_CONTROL_CONFIGURATION = 0x0183,
HID_USAGE_CONSUMER_AL_EMAIL_READER = 0x018A,
HID_USAGE_CONSUMER_AL_CALCULATOR = 0x0192,
HID_USAGE_CONSUMER_AL_LOCAL_BROWSER = 0x0194,
// Browser/Explorer Specific
HID_USAGE_CONSUMER_AC_SEARCH = 0x0221,
HID_USAGE_CONSUMER_AC_HOME = 0x0223,
HID_USAGE_CONSUMER_AC_BACK = 0x0224,
HID_USAGE_CONSUMER_AC_FORWARD = 0x0225,
HID_USAGE_CONSUMER_AC_STOP = 0x0226,
HID_USAGE_CONSUMER_AC_REFRESH = 0x0227,
HID_USAGE_CONSUMER_AC_BOOKMARKS = 0x022A,
// Mouse Horizontal scroll
HID_USAGE_CONSUMER_AC_PAN = 0x0238,
};
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HID_H__ */
/// @}

View file

@ -0,0 +1,327 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_HID)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "common/tusb_common.h"
#include "hid_device.h"
#include "device/usbd_pvt.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
#ifndef CFG_TUD_HID_BUFSIZE
#define CFG_TUD_HID_BUFSIZE 16
#endif
typedef struct
{
uint8_t itf_num;
uint8_t ep_in;
uint8_t boot_protocol; // Boot mouse or keyboard
bool boot_mode;
uint16_t reprot_desc_len;
uint8_t idle_rate; // 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).
uint8_t mouse_button; // caching button for using with tud_hid_mouse_ API
CFG_TUSB_MEM_ALIGN uint8_t report_buf[CFG_TUD_HID_BUFSIZE];
}hidd_interface_t;
CFG_TUSB_MEM_SECTION static hidd_interface_t _hidd_itf[CFG_TUD_HID];
/*------------- Helpers -------------*/
static inline hidd_interface_t* get_interface_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 &_hidd_itf[i];
}
return NULL;
}
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
bool tud_hid_ready(void)
{
uint8_t itf = 0;
uint8_t const ep_in = _hidd_itf[itf].ep_in;
return tud_ready() && (ep_in != 0) && !dcd_edpt_busy(TUD_OPT_RHPORT, ep_in);
}
bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len)
{
TU_VERIFY( tud_hid_ready() && (len < CFG_TUD_HID_BUFSIZE) );
uint8_t itf = 0;
hidd_interface_t * p_hid = &_hidd_itf[itf];
// If report id = 0, skip ID field
if (report_id)
{
p_hid->report_buf[0] = report_id;
memcpy(p_hid->report_buf+1, report, len);
}else
{
memcpy(p_hid->report_buf, report, len);
}
// TODO skip duplication ? and or idle rate
return dcd_edpt_xfer(TUD_OPT_RHPORT, p_hid->ep_in, p_hid->report_buf, len + (report_id ? 1 : 0) );
}
bool tud_hid_boot_mode(void)
{
uint8_t itf = 0;
return _hidd_itf[itf].boot_mode;
}
//--------------------------------------------------------------------+
// KEYBOARD API
//--------------------------------------------------------------------+
bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6])
{
hid_keyboard_report_t report;
report.modifier = modifier;
if ( keycode )
{
memcpy(report.keycode, keycode, 6);
}else
{
tu_memclr(report.keycode, 6);
}
// TODO skip duplication ? and or idle rate
return tud_hid_report(report_id, &report, sizeof(report));
}
//--------------------------------------------------------------------+
// MOUSE APPLICATION API
//--------------------------------------------------------------------+
bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan)
{
(void) pan;
hid_mouse_report_t report =
{
.buttons = buttons,
.x = x,
.y = y,
.wheel = scroll,
//.pan = pan
};
uint8_t itf = 0;
_hidd_itf[itf].mouse_button = buttons;
return tud_hid_report(report_id, &report, sizeof(report));
}
bool tud_hid_mouse_move(uint8_t report_id, int8_t x, int8_t y)
{
uint8_t itf = 0;
uint8_t const button = _hidd_itf[itf].mouse_button;
return tud_hid_mouse_report(report_id, button, x, y, 0, 0);
}
bool tud_hid_mouse_scroll(uint8_t report_id, int8_t scroll, int8_t pan)
{
uint8_t itf = 0;
uint8_t const button = _hidd_itf[itf].mouse_button;
return tud_hid_mouse_report(report_id, button, 0, 0, scroll, pan);
}
//--------------------------------------------------------------------+
// USBD-CLASS API
//--------------------------------------------------------------------+
void hidd_init(void)
{
hidd_reset(TUD_OPT_RHPORT);
}
void hidd_reset(uint8_t rhport)
{
(void) rhport;
tu_memclr(_hidd_itf, sizeof(_hidd_itf));
}
bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * desc_itf, uint16_t *p_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);
//------------- Endpoint Descriptor -------------//
p_desc = tu_desc_next(p_desc);
tusb_desc_endpoint_t const *desc_edpt = (tusb_desc_endpoint_t const *) p_desc;
TU_ASSERT(TUSB_DESC_ENDPOINT == desc_edpt->bDescriptorType);
TU_ASSERT(dcd_edpt_open(rhport, desc_edpt));
// TODO support multiple HID interface
uint8_t itf = 0;
hidd_interface_t * p_hid = &_hidd_itf[itf];
if ( desc_itf->bInterfaceSubClass == HID_SUBCLASS_BOOT ) p_hid->boot_protocol = desc_itf->bInterfaceProtocol;
p_hid->boot_mode = false; // default mode is REPORT
p_hid->itf_num = desc_itf->bInterfaceNumber;
p_hid->ep_in = desc_edpt->bEndpointAddress;
p_hid->reprot_desc_len = desc_hid->wReportLength;
*p_len = sizeof(tusb_desc_interface_t) + sizeof(tusb_hid_descriptor_hid_t) + desc_itf->bNumEndpoints*sizeof(tusb_desc_endpoint_t);
return true;
}
// Handle class control request
// return false to stall control endpoint (e.g unsupported request)
bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
{
hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex );
TU_ASSERT(p_hid);
if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_STANDARD)
{
//------------- STD Request -------------//
uint8_t const desc_type = tu_u16_high(p_request->wValue);
uint8_t const desc_index = tu_u16_low (p_request->wValue);
(void) desc_index;
if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT)
{
usbd_control_xfer(rhport, p_request, (void*) tud_desc_set.hid_report, p_hid->reprot_desc_len);
}else
{
return false; // stall unsupported request
}
}
else if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS)
{
//------------- Class Specific Request -------------//
switch( p_request->bRequest )
{
case HID_REQ_CONTROL_GET_REPORT:
{
// wValue = Report Type | Report ID
uint8_t const report_type = tu_u16_high(p_request->wValue);
uint8_t const report_id = tu_u16_low(p_request->wValue);
uint16_t xferlen = tud_hid_get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength);
TU_ASSERT( xferlen > 0 );
usbd_control_xfer(rhport, p_request, p_hid->report_buf, xferlen);
}
break;
case HID_REQ_CONTROL_SET_REPORT:
usbd_control_xfer(rhport, p_request, p_hid->report_buf, p_request->wLength);
break;
case HID_REQ_CONTROL_SET_IDLE:
// TODO idle rate of report
p_hid->idle_rate = tu_u16_high(p_request->wValue);
usbd_control_status(rhport, p_request);
break;
case HID_REQ_CONTROL_GET_IDLE:
// TODO idle rate of report
usbd_control_xfer(rhport, p_request, &p_hid->idle_rate, 1);
break;
case HID_REQ_CONTROL_GET_PROTOCOL:
{
uint8_t protocol = 1-p_hid->boot_mode; // 0 is Boot, 1 is Report protocol
usbd_control_xfer(rhport, p_request, &protocol, 1);
}
break;
case HID_REQ_CONTROL_SET_PROTOCOL:
p_hid->boot_mode = 1 - p_request->wValue; // 0 is Boot, 1 is Report protocol
if (tud_hid_mode_changed_cb) tud_hid_mode_changed_cb(p_hid->boot_mode);
usbd_control_status(rhport, p_request);
break;
default: return false; // stall unsupported request
}
}else
{
return false; // stall unsupported request
}
return true;
}
// Invoked when class request DATA stage is finished.
// return false to stall control endpoint (e.g Host send non-sense DATA)
bool hidd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request)
{
(void) rhport;
hidd_interface_t* p_hid = get_interface_by_itfnum( (uint8_t) p_request->wIndex );
TU_ASSERT(p_hid);
if (p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS &&
p_request->bRequest == HID_REQ_CONTROL_SET_REPORT)
{
// wValue = Report Type | Report ID
uint8_t const report_type = tu_u16_high(p_request->wValue);
uint8_t const report_id = tu_u16_low(p_request->wValue);
tud_hid_set_report_cb(report_id, (hid_report_type_t) report_type, p_hid->report_buf, p_request->wLength);
}
return true;
}
bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
{
// nothing to do
(void) rhport;
(void) ep_addr;
(void) event;
(void) xferred_bytes;
return true;
}
#endif

View file

@ -0,0 +1,436 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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 "common/tusb_common.h"
#include "device/usbd.h"
#include "hid.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Default Configure & Validation
//--------------------------------------------------------------------+
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Check if the interface is ready to use
bool tud_hid_ready(void);
// Check if current mode is Boot (true) or Report (false)
bool tud_hid_boot_mode(void);
// Send report to host
bool tud_hid_report(uint8_t report_id, void const* report, uint8_t len);
/*------------- Callbacks (Weak is optional) -------------*/
// Invoked when receiving GET_REPORT control request
// Application must fill buffer report's content and return its length.
// Return zero will cause the stack to STALL request
ATTR_WEAK uint16_t tud_hid_get_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen);
// Invoked when receiving SET_REPORT control request
ATTR_WEAK void tud_hid_set_report_cb(uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize);
// Invoked when host switch mode Boot <-> Report via SET_PROTOCOL request
ATTR_WEAK void tud_hid_mode_changed_cb(uint8_t boot_mode);
//--------------------------------------------------------------------+
// KEYBOARD API
// Convenient helper to send keyboard report if application use standard/boot
// layout report as defined by hid_keyboard_report_t
//--------------------------------------------------------------------+
bool tud_hid_keyboard_report(uint8_t report_id, uint8_t modifier, uint8_t keycode[6]);
static inline bool tud_hid_keyboard_key_release(uint8_t report_id)
{
return tud_hid_keyboard_report(report_id, 0, NULL);
}
//--------------------------------------------------------------------+
// MOUSE API
// Convenient helper to send mouse report if application use standard/boot
// layout report as defined by hid_mouse_report_t
//--------------------------------------------------------------------+
bool tud_hid_mouse_report(uint8_t report_id, uint8_t buttons, int8_t x, int8_t y, int8_t scroll, int8_t pan);
bool tud_hid_mouse_move(uint8_t report_id, int8_t x, int8_t y);
bool tud_hid_mouse_scroll(uint8_t report_id, int8_t scroll, int8_t pan);
static inline bool tud_hid_mouse_button_press(uint8_t report_id, uint8_t buttons)
{
return tud_hid_mouse_report(report_id, buttons, 0, 0, 0, 0);
}
static inline bool tud_hid_mouse_button_release(uint8_t report_id)
{
return tud_hid_mouse_report(report_id, 0, 0, 0, 0, 0);
}
/* --------------------------------------------------------------------+
* 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 ) ,\
/* 8 bits Modifier Keys (Shfit, Control, Alt) */ \
__VA_ARGS__ \
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 ) ,\
/* 6-byte Keycodes */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_KEYBOARD ) ,\
HID_USAGE_MIN ( 0 ) ,\
HID_USAGE_MAX ( 255 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 255 ) ,\
HID_REPORT_COUNT ( 6 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
/* 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 ) ,\
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 ) ,\
__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 ( 3 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
/* Left, Right, Middle, Backward, Forward mouse buttons */ \
HID_REPORT_COUNT ( 3 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
/* 3 bit padding */ \
HID_REPORT_COUNT ( 1 ) ,\
HID_REPORT_SIZE ( 5 ) ,\
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 ) ,\
/* Mouse 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_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 ) ,\
__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
* 0x04 - 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 ) ,\
__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_SLEEP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_SYSTEM_POWER_DOWN ) ,\
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 16 buttons and 2 joysticks with following layout
// | Button Map (2 bytes) | X | Y | Z | Rz
#define TUD_HID_REPORT_DESC_GAMEPAD(...) \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_USAGE ( HID_USAGE_DESKTOP_GAMEPAD ) ,\
HID_COLLECTION ( HID_COLLECTION_APPLICATION ) ,\
__VA_ARGS__ \
/* 16 bit Button Map */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_BUTTON ) ,\
HID_USAGE_MIN ( 1 ) ,\
HID_USAGE_MAX ( 16 ) ,\
HID_LOGICAL_MIN ( 0 ) ,\
HID_LOGICAL_MAX ( 1 ) ,\
HID_REPORT_COUNT ( 16 ) ,\
HID_REPORT_SIZE ( 1 ) ,\
HID_INPUT ( HID_DATA | HID_ARRAY | HID_ABSOLUTE ) ,\
/* X, Y, Z, Rz (min -127, max 127 ) */ \
HID_USAGE_PAGE ( HID_USAGE_PAGE_DESKTOP ) ,\
HID_LOGICAL_MIN ( 0x81 ) ,\
HID_LOGICAL_MAX ( 0x7f ) ,\
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_REPORT_COUNT ( 4 ) ,\
HID_REPORT_SIZE ( 8 ) ,\
HID_INPUT ( HID_DATA | HID_VARIABLE | HID_ABSOLUTE ) ,\
HID_COLLECTION_END \
/*--------------------------------------------------------------------
* ASCII to KEYCODE Conversion
* Expand to array of [128][2] (shift, keycode)
*
* Usage: example to convert input char into keyboard report (modifier + keycode)
*
* uint8_t const conv_table[128][2] = { HID_ASCII_TO_KEYCODE };
*
* uint8_t keycode[6] = { 0 };
* uint8_t modifier = 0;
*
* if ( conv_table[chr][0] ) modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
* keycode[0] = conv_table[chr][1];
* tud_hid_keyboard_report(report_id, modifier, keycode);
*
*--------------------------------------------------------------------*/
#define HID_ASCII_TO_KEYCODE \
{0, 0 }, /* 0x00 Null */ \
{0, 0 }, /* 0x01 */ \
{0, 0 }, /* 0x02 */ \
{0, 0 }, /* 0x03 */ \
{0, 0 }, /* 0x04 */ \
{0, 0 }, /* 0x05 */ \
{0, 0 }, /* 0x06 */ \
{0, 0 }, /* 0x07 */ \
{0, HID_KEY_BACKSPACE }, /* 0x08 Backspace */ \
{0, HID_KEY_TAB }, /* 0x09 Tab */ \
{0, HID_KEY_RETURN }, /* 0x0A Line Feed */ \
{0, 0 }, /* 0x0B */ \
{0, 0 }, /* 0x0C */ \
{0, HID_KEY_RETURN }, /* 0x0D CR */ \
{0, 0 }, /* 0x0E */ \
{0, 0 }, /* 0x0F */ \
{0, 0 }, /* 0x10 */ \
{0, 0 }, /* 0x11 */ \
{0, 0 }, /* 0x12 */ \
{0, 0 }, /* 0x13 */ \
{0, 0 }, /* 0x14 */ \
{0, 0 }, /* 0x15 */ \
{0, 0 }, /* 0x16 */ \
{0, 0 }, /* 0x17 */ \
{0, 0 }, /* 0x18 */ \
{0, 0 }, /* 0x19 */ \
{0, 0 }, /* 0x1A */ \
{0, HID_KEY_ESCAPE }, /* 0x1B Escape */ \
{0, 0 }, /* 0x1C */ \
{0, 0 }, /* 0x1D */ \
{0, 0 }, /* 0x1E */ \
{0, 0 }, /* 0x1F */ \
\
{0, HID_KEY_SPACE }, /* 0x20 */ \
{1, HID_KEY_1 }, /* 0x21 ! */ \
{1, HID_KEY_APOSTROPHE }, /* 0x22 " */ \
{1, HID_KEY_3 }, /* 0x23 # */ \
{1, HID_KEY_4 }, /* 0x24 $ */ \
{1, HID_KEY_5 }, /* 0x25 % */ \
{1, HID_KEY_7 }, /* 0x26 & */ \
{0, HID_KEY_APOSTROPHE }, /* 0x27 ' */ \
{1, HID_KEY_9 }, /* 0x28 ( */ \
{1, HID_KEY_0 }, /* 0x29 ) */ \
{1, HID_KEY_8 }, /* 0x2A * */ \
{1, HID_KEY_EQUAL }, /* 0x2B + */ \
{0, HID_KEY_COMMA }, /* 0x2C , */ \
{0, HID_KEY_MINUS }, /* 0x2D - */ \
{0, HID_KEY_PERIOD }, /* 0x2E . */ \
{0, HID_KEY_SLASH }, /* 0x2F / */ \
{0, HID_KEY_0 }, /* 0x30 0 */ \
{0, HID_KEY_1 }, /* 0x31 1 */ \
{0, HID_KEY_2 }, /* 0x32 2 */ \
{0, HID_KEY_3 }, /* 0x33 3 */ \
{0, HID_KEY_4 }, /* 0x34 4 */ \
{0, HID_KEY_5 }, /* 0x35 5 */ \
{0, HID_KEY_6 }, /* 0x36 6 */ \
{0, HID_KEY_7 }, /* 0x37 7 */ \
{0, HID_KEY_8 }, /* 0x38 8 */ \
{0, HID_KEY_9 }, /* 0x39 9 */ \
{1, HID_KEY_SEMICOLON }, /* 0x3A : */ \
{0, HID_KEY_SEMICOLON }, /* 0x3B ; */ \
{1, HID_KEY_COMMA }, /* 0x3C < */ \
{0, HID_KEY_EQUAL }, /* 0x3D = */ \
{1, HID_KEY_PERIOD }, /* 0x3E > */ \
{1, HID_KEY_SLASH }, /* 0x3F ? */ \
\
{1, HID_KEY_2 }, /* 0x40 @ */ \
{1, HID_KEY_A }, /* 0x41 A */ \
{1, HID_KEY_B }, /* 0x42 B */ \
{1, HID_KEY_C }, /* 0x43 C */ \
{1, HID_KEY_D }, /* 0x44 D */ \
{1, HID_KEY_E }, /* 0x45 E */ \
{1, HID_KEY_F }, /* 0x46 F */ \
{1, HID_KEY_G }, /* 0x47 G */ \
{1, HID_KEY_H }, /* 0x48 H */ \
{1, HID_KEY_I }, /* 0x49 I */ \
{1, HID_KEY_J }, /* 0x4A J */ \
{1, HID_KEY_K }, /* 0x4B K */ \
{1, HID_KEY_L }, /* 0x4C L */ \
{1, HID_KEY_M }, /* 0x4D M */ \
{1, HID_KEY_N }, /* 0x4E N */ \
{1, HID_KEY_O }, /* 0x4F O */ \
{1, HID_KEY_P }, /* 0x50 P */ \
{1, HID_KEY_Q }, /* 0x51 Q */ \
{1, HID_KEY_R }, /* 0x52 R */ \
{1, HID_KEY_S }, /* 0x53 S */ \
{1, HID_KEY_T }, /* 0x55 T */ \
{1, HID_KEY_U }, /* 0x55 U */ \
{1, HID_KEY_V }, /* 0x56 V */ \
{1, HID_KEY_W }, /* 0x57 W */ \
{1, HID_KEY_X }, /* 0x58 X */ \
{1, HID_KEY_Y }, /* 0x59 Y */ \
{1, HID_KEY_Z }, /* 0x5A Z */ \
{0, HID_KEY_BRACKET_LEFT }, /* 0x5B [ */ \
{0, HID_KEY_BACKSLASH }, /* 0x5C '\' */ \
{0, HID_KEY_BRACKET_RIGHT }, /* 0x5D ] */ \
{1, HID_KEY_6 }, /* 0x5E ^ */ \
{1, HID_KEY_MINUS }, /* 0x5F _ */ \
\
{0, HID_KEY_GRAVE }, /* 0x60 ` */ \
{0, HID_KEY_A }, /* 0x61 a */ \
{0, HID_KEY_B }, /* 0x62 b */ \
{0, HID_KEY_C }, /* 0x63 c */ \
{0, HID_KEY_D }, /* 0x66 d */ \
{0, HID_KEY_E }, /* 0x65 e */ \
{0, HID_KEY_F }, /* 0x66 f */ \
{0, HID_KEY_G }, /* 0x67 g */ \
{0, HID_KEY_H }, /* 0x68 h */ \
{0, HID_KEY_I }, /* 0x69 i */ \
{0, HID_KEY_J }, /* 0x6A j */ \
{0, HID_KEY_K }, /* 0x6B k */ \
{0, HID_KEY_L }, /* 0x6C l */ \
{0, HID_KEY_M }, /* 0x6D m */ \
{0, HID_KEY_N }, /* 0x6E n */ \
{0, HID_KEY_O }, /* 0x6F o */ \
{0, HID_KEY_P }, /* 0x70 p */ \
{0, HID_KEY_Q }, /* 0x71 q */ \
{0, HID_KEY_R }, /* 0x72 r */ \
{0, HID_KEY_S }, /* 0x73 s */ \
{0, HID_KEY_T }, /* 0x75 t */ \
{0, HID_KEY_U }, /* 0x75 u */ \
{0, HID_KEY_V }, /* 0x76 v */ \
{0, HID_KEY_W }, /* 0x77 w */ \
{0, HID_KEY_X }, /* 0x78 x */ \
{0, HID_KEY_Y }, /* 0x79 y */ \
{0, HID_KEY_Z }, /* 0x7A z */ \
{1, HID_KEY_BRACKET_LEFT }, /* 0x7B { */ \
{1, HID_KEY_BACKSLASH }, /* 0x7C | */ \
{1, HID_KEY_BRACKET_RIGHT }, /* 0x7D } */ \
{1, HID_KEY_GRAVE }, /* 0x7E ~ */ \
{0, HID_KEY_DELETE } /* 0x7F Delete */ \
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void hidd_init(void);
bool hidd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
bool hidd_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
bool hidd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void hidd_reset(uint8_t rhport);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_HID_DEVICE_H_ */

View file

@ -0,0 +1,72 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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
//--------------------------------------------------------------------+
// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE)
//--------------------------------------------------------------------+
/// Header Functional Descriptor (Communication Interface)
typedef struct 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 MIDI_FUCN_DESC_
uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal
uint16_t wTotalLength ;
}midi_desc_func_header_t;
/// Union Functional Descriptor (Communication Interface)
typedef struct 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;
/** @} */
#ifdef __cplusplus
}
#endif
#endif
/** @} */

View file

@ -0,0 +1,347 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MIDI)
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "midi_device.h"
#include "class/audio/audio.h"
#include "device/usbd_pvt.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct
{
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
// 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
// We need to pack messages into words before queueing their transmission so buffer across write
// calls.
uint8_t message_buffer[4];
uint8_t message_buffer_length;
uint8_t message_target_length;
// Endpoint Transfer buffer
CFG_TUSB_MEM_ALIGN uint8_t epout_buf[CFG_TUD_MIDI_EPSIZE];
CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_MIDI_EPSIZE];
} midid_interface_t;
#define ITF_MEM_RESET_SIZE offsetof(midid_interface_t, rx_ff)
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
CFG_TUSB_ATTR_USBRAM midid_interface_t _midid_itf[CFG_TUD_MIDI];
bool tud_midi_n_connected(uint8_t itf) {
midid_interface_t* midi = &_midid_itf[itf];
return midi->itf_num != 0;
}
//--------------------------------------------------------------------+
// READ API
//--------------------------------------------------------------------+
uint32_t tud_midi_n_available(uint8_t itf, uint8_t jack_id)
{
return tu_fifo_count(&_midid_itf[itf].rx_ff);
}
char tud_midi_n_read_char(uint8_t itf, uint8_t jack_id)
{
char ch;
return tu_fifo_read(&_midid_itf[itf].rx_ff, &ch) ? ch : (-1);
}
uint32_t tud_midi_n_read(uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize)
{
return tu_fifo_read_n(&_midid_itf[itf].rx_ff, buffer, bufsize);
}
void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id)
{
tu_fifo_clear(&_midid_itf[itf].rx_ff);
}
void midi_rx_done_cb(midid_interface_t* midi, uint8_t const* buffer, uint32_t bufsize) {
if (bufsize % 4 != 0) {
return;
}
for(uint32_t i=0; i<bufsize; i += 4) {
uint8_t header = buffer[i];
// uint8_t cable_number = (header & 0xf0) >> 4;
uint8_t code_index = header & 0x0f;
// We always copy over the first byte.
uint8_t count = 1;
// Ignore subsequent bytes based on the code.
if (code_index != 0x5 && code_index != 0xf) {
count = 2;
if (code_index != 0x2 && code_index != 0x6 && code_index != 0xc && code_index != 0xd) {
count = 3;
}
}
tu_fifo_write_n(&midi->rx_ff, &buffer[i + 1], count);
}
}
//--------------------------------------------------------------------+
// WRITE API
//--------------------------------------------------------------------+
static bool maybe_transmit(midid_interface_t* midi, uint8_t itf_index)
{
TU_VERIFY( !dcd_edpt_busy(TUD_OPT_RHPORT, midi->ep_in) ); // skip if previous transfer not complete
uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epin_buf, CFG_TUD_MIDI_EPSIZE);
if (count > 0)
{
TU_VERIFY( tud_midi_n_connected(itf_index) ); // fifo is empty if not connected
TU_ASSERT( dcd_edpt_xfer(TUD_OPT_RHPORT, midi->ep_in, midi->epin_buf, count) );
}
return true;
}
uint32_t tud_midi_n_write(uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize)
{
midid_interface_t* midi = &_midid_itf[itf];
if (midi->itf_num == 0) {
return 0;
}
uint32_t i = 0;
while (i < bufsize) {
uint8_t data = buffer[i];
if (midi->message_buffer_length == 0) {
uint8_t msg = data >> 4;
midi->message_buffer[1] = data;
midi->message_buffer_length = 2;
// Check to see if we're still in a SysEx transmit.
if (midi->message_buffer[0] == 0x4) {
if (data == 0xf7) {
midi->message_buffer[0] = 0x5;
} else {
midi->message_buffer_length = 4;
}
} else if ((msg >= 0x8 && msg <= 0xB) || msg == 0xE) {
midi->message_buffer[0] = jack_id << 4 | msg;
midi->message_target_length = 4;
} else if (msg == 0xf) {
if (data == 0xf0) {
midi->message_buffer[0] = 0x4;
midi->message_target_length = 4;
} else if (data == 0xf1 || data == 0xf3) {
midi->message_buffer[0] = 0x2;
midi->message_target_length = 3;
} else if (data == 0xf2) {
midi->message_buffer[0] = 0x3;
midi->message_target_length = 4;
} else {
midi->message_buffer[0] = 0x5;
midi->message_target_length = 2;
}
} else {
// Pack individual bytes if we don't support packing them into words.
midi->message_buffer[0] = jack_id << 4 | 0xf;
midi->message_buffer[2] = 0;
midi->message_buffer[3] = 0;
midi->message_buffer_length = 2;
midi->message_target_length = 2;
}
} else {
midi->message_buffer[midi->message_buffer_length] = data;
midi->message_buffer_length += 1;
// See if this byte ends a SysEx.
if (midi->message_buffer[0] == 0x4 && data == 0xf7) {
midi->message_buffer[0] = 0x4 + (midi->message_buffer_length - 1);
midi->message_target_length = midi->message_buffer_length;
}
}
if (midi->message_buffer_length == midi->message_target_length) {
uint16_t written = tu_fifo_write_n(&midi->tx_ff, midi->message_buffer, 4);
if (written < 4) {
TU_ASSERT( written == 0 );
break;
}
midi->message_buffer_length = 0;
}
i++;
}
maybe_transmit(midi, itf);
return i;
}
//--------------------------------------------------------------------+
// 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, true);
tu_fifo_config(&midi->tx_ff, midi->tx_ff_buf, CFG_TUD_MIDI_TX_BUFSIZE, 1, true);
#if CFG_FIFO_MUTEX
tu_fifo_config_mutex(&midi->rx_ff, osal_mutex_create(&midi->rx_ff_mutex));
tu_fifo_config_mutex(&midi->tx_ff, osal_mutex_create(&midi->tx_ff_mutex));
#endif
}
}
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);
}
}
bool midid_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length)
{
// For now handle the audio control interface as well.
if ( AUDIO_SUBCLASS_AUDIO_CONTROL == p_interface_desc->bInterfaceSubClass) {
uint8_t const * p_desc = tu_desc_next ( (uint8_t const *) p_interface_desc );
(*p_length) = sizeof(tusb_desc_interface_t);
// Skip over the class specific descriptor.
(*p_length) += p_desc[DESC_OFFSET_LEN];
p_desc = tu_desc_next(p_desc);
return true;
}
if ( AUDIO_SUBCLASS_MIDI_STREAMING != p_interface_desc->bInterfaceSubClass ||
p_interface_desc->bInterfaceProtocol != AUDIO_PROTOCOL_V1 ) {
return false;
}
// Find available interface
midid_interface_t * p_midi = NULL;
for(uint8_t i=0; i<CFG_TUD_MIDI; i++)
{
if ( _midid_itf[i].ep_in == 0 && _midid_itf[i].ep_out == 0 )
{
p_midi = &_midid_itf[i];
break;
}
}
p_midi->itf_num = p_interface_desc->bInterfaceNumber;
uint8_t const * p_desc = tu_desc_next( (uint8_t const *) p_interface_desc );
(*p_length) = sizeof(tusb_desc_interface_t);
uint8_t found_endpoints = 0;
while (found_endpoints < p_interface_desc->bNumEndpoints) {
if ( TUSB_DESC_ENDPOINT == p_desc[DESC_OFFSET_TYPE])
{
TU_ASSERT( dcd_edpt_open(rhport, (tusb_desc_endpoint_t const *) p_desc), false);
uint8_t ep_addr = ((tusb_desc_endpoint_t const *) 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;
}
(*p_length) += p_desc[DESC_OFFSET_LEN];
p_desc = tu_desc_next(p_desc);
found_endpoints += 1;
}
(*p_length) += p_desc[DESC_OFFSET_LEN];
p_desc = tu_desc_next(p_desc);
}
// Prepare for incoming data
TU_ASSERT( dcd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false);
return true;
}
bool midid_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request)
{
return false;
}
bool midid_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
{
//------------- Class Specific Request -------------//
if (p_request->bmRequestType_bit.type != TUSB_REQ_TYPE_CLASS) return false;
return false;
}
bool midid_xfer_cb(uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes)
{
// TODO Support multiple interfaces
uint8_t const itf = 0;
midid_interface_t* p_midi = &_midid_itf[itf];
// receive new data
if ( edpt_addr == p_midi->ep_out )
{
midi_rx_done_cb(p_midi, p_midi->epout_buf, xferred_bytes);
// prepare for next
TU_ASSERT( dcd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false );
} else if ( edpt_addr == p_midi->ep_in ) {
maybe_transmit(p_midi, itf);
}
// nothing to do with in and notif endpoint
return TUSB_ERROR_NONE;
}
#endif

View file

@ -0,0 +1,104 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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 "common/tusb_common.h"
#include "device/usbd.h"
#include "class/audio/audio.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
#ifndef CFG_TUD_MIDI_EPSIZE
#define CFG_TUD_MIDI_EPSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup MIDI_Serial Serial
* @{
* \defgroup MIDI_Serial_Device Device
* @{ */
//--------------------------------------------------------------------+
// APPLICATION API (Multiple Interfaces)
// CFG_TUD_MIDI > 1
//--------------------------------------------------------------------+
bool tud_midi_n_connected (uint8_t itf);
uint32_t tud_midi_n_available (uint8_t itf, uint8_t jack_id);
char tud_midi_n_read_char (uint8_t itf, uint8_t jack_id);
uint32_t tud_midi_n_read (uint8_t itf, uint8_t jack_id, void* buffer, uint32_t bufsize);
void tud_midi_n_read_flush (uint8_t itf, uint8_t jack_id);
char tud_midi_n_peek (uint8_t itf, uint8_t jack_id, int pos);
uint32_t tud_midi_n_write_char (uint8_t itf, char ch);
uint32_t tud_midi_n_write (uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize);
bool tud_midi_n_write_flush (uint8_t itf);
//--------------------------------------------------------------------+
// APPLICATION API (Interface0)
//--------------------------------------------------------------------+
static inline bool tud_midi_connected (void) { return tud_midi_n_connected(0); }
static inline uint32_t tud_midi_available (void) { return tud_midi_n_available(0, 0); }
static inline char tud_midi_read_char (void) { return tud_midi_n_read_char(0, 0); }
static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize) { return tud_midi_n_read(0, 0, buffer, bufsize); }
static inline void tud_midi_read_flush (void) { tud_midi_n_read_flush(0, 0); }
static inline char tud_midi_peek (int pos) { return tud_midi_n_peek(0, 0, pos); }
static inline uint32_t tud_midi_write_char (char ch) { return tud_midi_n_write_char(0, ch); }
static inline uint32_t tud_midi_write (uint8_t jack_id, void const* buffer, uint32_t bufsize) { return tud_midi_n_write(0, jack_id, buffer, bufsize); }
static inline bool tud_midi_write_flush (void) { return tud_midi_n_write_flush(0); }
//--------------------------------------------------------------------+
// APPLICATION CALLBACK API (WEAK is optional)
//--------------------------------------------------------------------+
ATTR_WEAK void tud_midi_rx_cb(uint8_t itf);
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void midid_init (void);
bool midid_open (uint8_t rhport, tusb_desc_interface_t const * p_interface_desc, uint16_t *p_length);
bool midid_control_request (uint8_t rhport, tusb_control_request_t const * p_request);
bool midid_control_request_complete (uint8_t rhport, tusb_control_request_t const * p_request);
bool midid_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes);
void midid_reset (uint8_t rhport);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MIDI_DEVICE_H_ */
/** @} */
/** @} */

View file

@ -0,0 +1,392 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_MSC MassStorage (MSC)
* @{ */
/** \defgroup ClassDriver_MSC_Common Common Definitions
* @{ */
#ifndef _TUSB_MSC_H_
#define _TUSB_MSC_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Mass Storage Class Constant
//--------------------------------------------------------------------+
/// MassStorage Subclass
typedef enum
{
MSC_SUBCLASS_RBC = 1 , ///< Reduced Block Commands (RBC) T10 Project 1240-D
MSC_SUBCLASS_SFF_MMC , ///< SFF-8020i, MMC-2 (ATAPI). Typically used by a CD/DVD device
MSC_SUBCLASS_QIC , ///< QIC-157. Typically used by a tape device
MSC_SUBCLASS_UFI , ///< UFI. Typically used by Floppy Disk Drive (FDD) device
MSC_SUBCLASS_SFF , ///< SFF-8070i. Can be used by Floppy Disk Drive (FDD) device
MSC_SUBCLASS_SCSI ///< SCSI transparent command set
}msc_subclass_type_t;
enum {
MSC_CBW_SIGNATURE = 0x43425355, ///< Constant value of 43425355h (little endian)
MSC_CSW_SIGNATURE = 0x53425355 ///< Constant value of 53425355h (little endian)
};
/// \brief MassStorage Protocol.
/// \details CBI only approved to use with full-speed floopy disk & should not used with highspeed or device other than floopy
typedef enum
{
MSC_PROTOCOL_CBI = 0 , ///< Control/Bulk/Interrupt protocol (with command completion interrupt)
MSC_PROTOCOL_CBI_NO_INTERRUPT = 1 , ///< Control/Bulk/Interrupt protocol (without command completion interrupt)
MSC_PROTOCOL_BOT = 0x50 ///< Bulk-Only Transport
}msc_protocol_type_t;
/// MassStorage Class-Specific Control Request
typedef enum
{
MSC_REQ_GET_MAX_LUN = 254, ///< The Get Max LUN device request is used to determine the number of logical units supported by the device. Logical Unit Numbers on the device shall be numbered contiguously starting from LUN 0 to a maximum LUN of 15
MSC_REQ_RESET = 255 ///< This request is used to reset the mass storage device and its associated interface. This class-specific request shall ready the device for the next CBW from the host.
}msc_request_type_t;
/// \brief Command Block Status Values
/// \details Indicates the success or failure of the command. The device shall set this byte to zero if the command completed
/// successfully. A non-zero value shall indicate a failure during command execution according to the following
typedef enum
{
MSC_CSW_STATUS_PASSED = 0 , ///< MSC_CSW_STATUS_PASSED
MSC_CSW_STATUS_FAILED , ///< MSC_CSW_STATUS_FAILED
MSC_CSW_STATUS_PHASE_ERROR ///< MSC_CSW_STATUS_PHASE_ERROR
}msc_csw_status_t;
/// Command Block Wrapper
typedef struct 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 ATTR_PACKED
{
uint32_t signature ; ///< Signature that helps identify this data packet as a CSW. The signature field shall contain the value 53425355h (little endian), indicating CSW.
uint32_t tag ; ///< The device shall set this field to the value received in the dCBWTag of the associated CBW.
uint32_t data_residue ; ///< For Data-Out the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLength, and the actual amount of data processed by the device. For Data-In the device shall report in the dCSWDataResiduethe difference between the amount of data expected as stated in the dCBWDataTransferLengthand the actual amount of relevant data sent by the device
uint8_t status ; ///< indicates the success or failure of the command. Values from \ref msc_csw_status_t
}msc_csw_t;
TU_VERIFY_STATIC(sizeof(msc_csw_t) == 13, "size is not correct");
//--------------------------------------------------------------------+
// SCSI Constant
//--------------------------------------------------------------------+
/// SCSI Command Operation Code
typedef enum
{
SCSI_CMD_TEST_UNIT_READY = 0x00, ///< The SCSI Test Unit Ready command is used to determine if a device is ready to transfer data (read/write), i.e. if a disk has spun up, if a tape is loaded and ready etc. The device does not perform a self-test operation.
SCSI_CMD_INQUIRY = 0x12, ///< The SCSI Inquiry command is used to obtain basic information from a target device.
SCSI_CMD_MODE_SELECT_6 = 0x15, ///< provides a means for the application client to specify medium, logical unit, or peripheral device parameters to the device server. Device servers that implement the MODE SELECT(6) command shall also implement the MODE SENSE(6) command. Application clients should issue MODE SENSE(6) prior to each MODE SELECT(6) to determine supported mode pages, page lengths, and other parameters.
SCSI_CMD_MODE_SENSE_6 = 0x1A, ///< provides a means for a device server to report parameters to an application client. It is a complementary command to the MODE SELECT(6) command. Device servers that implement the MODE SENSE(6) command shall also implement the MODE SELECT(6) command.
SCSI_CMD_START_STOP_UNIT = 0x1B,
SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL = 0x1E,
SCSI_CMD_READ_CAPACITY_10 = 0x25, ///< The SCSI Read Capacity command is used to obtain data capacity information from a target device.
SCSI_CMD_REQUEST_SENSE = 0x03, ///< The SCSI Request Sense command is part of the SCSI computer protocol standard. This command is used to obtain sense data -- status/error information -- from a target device.
SCSI_CMD_READ_FORMAT_CAPACITY = 0x23, ///< The command allows the Host to request a list of the possible format capacities for an installed writable media. This command also has the capability to report the writable capacity for a media when it is installed
SCSI_CMD_READ_10 = 0x28, ///< The READ (10) command requests that the device server read the specified logical block(s) and transfer them to the data-in buffer.
SCSI_CMD_WRITE_10 = 0x2A, ///< The WRITE (10) command requests thatthe device server transfer the specified logical block(s) from the data-out buffer and write them.
}scsi_cmd_type_t;
/// SCSI Sense Key
typedef enum
{
SCSI_SENSE_NONE = 0x00, ///< no specific Sense Key. This would be the case for a successful command
SCSI_SENSE_RECOVERED_ERROR = 0x01, ///< ndicates the last command completed successfully with some recovery action performed by the disc drive.
SCSI_SENSE_NOT_READY = 0x02, ///< Indicates the logical unit addressed cannot be accessed.
SCSI_SENSE_MEDIUM_ERROR = 0x03, ///< Indicates the command terminated with a non-recovered error condition.
SCSI_SENSE_HARDWARE_ERROR = 0x04, ///< Indicates the disc drive detected a nonrecoverable hardware failure while performing the command or during a self test.
SCSI_SENSE_ILLEGAL_REQUEST = 0x05, ///< Indicates an illegal parameter in the command descriptor block or in the additional parameters
SCSI_SENSE_UNIT_ATTENTION = 0x06, ///< Indicates the disc drive may have been reset.
SCSI_SENSE_DATA_PROTECT = 0x07, ///< Indicates that a command that reads or writes the medium was attempted on a block that is protected from this operation. The read or write operation is not performed.
SCSI_SENSE_FIRMWARE_ERROR = 0x08, ///< Vendor specific sense key.
SCSI_SENSE_ABORTED_COMMAND = 0x0b, ///< Indicates the disc drive aborted the command.
SCSI_SENSE_EQUAL = 0x0c, ///< Indicates a SEARCH DATA command has satisfied an equal comparison.
SCSI_SENSE_VOLUME_OVERFLOW = 0x0d, ///< Indicates a buffered peripheral device has reached the end of medium partition and data remains in the buffer that has not been written to the medium.
SCSI_SENSE_MISCOMPARE = 0x0e ///< ndicates that the source data did not match the data read from the medium.
}scsi_sense_key_type_t;
//--------------------------------------------------------------------+
// SCSI Primary Command (SPC-4)
//--------------------------------------------------------------------+
/// SCSI Test Unit Ready Command
typedef struct 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 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 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 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 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 : 0;
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 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 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 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 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 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 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 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,607 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_MSC)
#include "common/tusb_common.h"
#include "msc_device.h"
#include "device/usbd_pvt.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
enum
{
MSC_STAGE_CMD = 0,
MSC_STAGE_DATA,
MSC_STAGE_STATUS
};
typedef struct {
CFG_TUSB_MEM_ALIGN msc_cbw_t cbw;
//#if defined (__ICCARM__) && (CFG_TUSB_MCU == OPT_MCU_LPC11UXX || CFG_TUSB_MCU == OPT_MCU_LPC13XX)
// uint8_t padding1[64-sizeof(msc_cbw_t)]; // IAR cannot align struct's member
//#endif
CFG_TUSB_MEM_ALIGN 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;
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;
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static mscd_interface_t _mscd_itf = { 0 };
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN static uint8_t _mscd_buf[CFG_TUD_MSC_BUFSIZE];
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
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 inline uint32_t rdwr10_get_lba(uint8_t const command[])
{
// read10 & write10 has the same format
scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command;
// copy first to prevent mis-aligned access
uint32_t lba;
memcpy(&lba, &p_rdwr10->lba, 4);
return __be2n(lba);
}
static inline uint16_t rdwr10_get_blockcount(uint8_t const command[])
{
// read10 & write10 has the same format
scsi_write10_t* p_rdwr10 = (scsi_write10_t*) command;
// copy first to prevent mis-aligned access
uint16_t block_count;
memcpy(&block_count, &p_rdwr10->block_count, 2);
return __be2n_16(block_count);
}
//--------------------------------------------------------------------+
// 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;
}
//--------------------------------------------------------------------+
// USBD-CLASS API
//--------------------------------------------------------------------+
void mscd_init(void)
{
tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
}
void mscd_reset(uint8_t rhport)
{
(void) rhport;
tu_memclr(&_mscd_itf, sizeof(mscd_interface_t));
}
bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_len)
{
// only support SCSI's BOT protocol
TU_ASSERT(MSC_SUBCLASS_SCSI == itf_desc->bInterfaceSubClass &&
MSC_PROTOCOL_BOT == itf_desc->bInterfaceProtocol);
mscd_interface_t * p_msc = &_mscd_itf;
// Open endpoint pair with usbd helper
tusb_desc_endpoint_t const *p_desc_ep = (tusb_desc_endpoint_t const *) tu_desc_next( itf_desc );
TU_ASSERT( usbd_open_edpt_pair(rhport, p_desc_ep, TUSB_XFER_BULK, &p_msc->ep_out, &p_msc->ep_in) );
p_msc->itf_num = itf_desc->bInterfaceNumber;
(*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
// Prepare for Command Block Wrapper
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
return true;
}
// Handle class control request
// return false to stall control endpoint (e.g unsupported request)
bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
{
TU_ASSERT(p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_CLASS);
switch ( p_request->bRequest )
{
case MSC_REQ_RESET:
// TODO: Actually reset interface.
usbd_control_status(rhport, p_request);
break;
case MSC_REQ_GET_MAX_LUN:
{
uint8_t maxlun = 1;
if (tud_msc_maxlun_cb) maxlun = tud_msc_maxlun_cb();
TU_VERIFY(maxlun);
// MAX LUN is minus 1 by specs
maxlun--;
usbd_control_xfer(rhport, p_request, &maxlun, 1);
}
break;
default: return false; // stall unsupported request
}
return true;
}
// Invoked when class request DATA stage is finished.
// return false to stall control endpoint (e.g Host send non-sense DATA)
bool mscd_control_request_complete(uint8_t rhport, tusb_control_request_t const * p_request)
{
(void) rhport;
(void) p_request;
// nothing to do
return true;
}
// return length of response (copied to buffer), -1 if it is not an built-in commands
int32_t proc_builtin_scsi(msc_cbw_t const * p_cbw, uint8_t* buffer, uint32_t bufsize)
{
(void) bufsize; // TODO refractor later
int32_t ret;
switch ( p_cbw->command[0] )
{
case SCSI_CMD_READ_CAPACITY_10:
{
scsi_read_capacity10_resp_t read_capa10;
uint32_t block_count;
uint32_t block_size;
uint16_t block_size_u16;
tud_msc_capacity_cb(p_cbw->lun, &block_count, &block_size_u16);
block_size = (uint32_t) block_size_u16;
read_capa10.last_lba = ENDIAN_BE(block_count-1);
read_capa10.block_size = ENDIAN_BE(block_size);
ret = sizeof(read_capa10);
memcpy(buffer, &read_capa10, ret);
}
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(p_cbw->lun, &block_count, &block_size);
read_fmt_capa.block_num = ENDIAN_BE(block_count);
read_fmt_capa.block_size_u16 = ENDIAN_BE16(block_size);
ret = sizeof(read_fmt_capa);
memcpy(buffer, &read_fmt_capa, ret);
}
break;
case SCSI_CMD_INQUIRY:
{
scsi_inquiry_resp_t inquiry_rsp =
{
.is_removable = 1,
.version = 2,
.response_data_format = 2,
// vendor_id, product_id, product_rev is space padded string
.vendor_id = "",
.product_id = "",
.product_rev = "",
};
memset(inquiry_rsp.vendor_id, ' ', sizeof(inquiry_rsp.vendor_id));
memcpy(inquiry_rsp.vendor_id, CFG_TUD_MSC_VENDOR, tu_min32(strlen(CFG_TUD_MSC_VENDOR), sizeof(inquiry_rsp.vendor_id)));
memset(inquiry_rsp.product_id, ' ', sizeof(inquiry_rsp.product_id));
memcpy(inquiry_rsp.product_id, CFG_TUD_MSC_PRODUCT, tu_min32(strlen(CFG_TUD_MSC_PRODUCT), sizeof(inquiry_rsp.product_id)));
memset(inquiry_rsp.product_rev, ' ', sizeof(inquiry_rsp.product_rev));
memcpy(inquiry_rsp.product_rev, CFG_TUD_MSC_PRODUCT_REV, tu_min32(strlen(CFG_TUD_MSC_PRODUCT_REV), sizeof(inquiry_rsp.product_rev)));
ret = sizeof(inquiry_rsp);
memcpy(buffer, &inquiry_rsp, ret);
}
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(p_cbw->lun);
}
mode_resp.write_protected = !writable;
ret = sizeof(mode_resp);
memcpy(buffer, &mode_resp, ret);
}
break;
case SCSI_CMD_REQUEST_SENSE:
{
scsi_sense_fixed_resp_t sense_rsp =
{
.response_code = 0x70,
.valid = 1
};
sense_rsp.add_sense_len = sizeof(scsi_sense_fixed_resp_t) - 8;
sense_rsp.sense_key = _mscd_itf.sense_key;
sense_rsp.add_sense_code = _mscd_itf.add_sense_code;
sense_rsp.add_sense_qualifier = _mscd_itf.add_sense_qualifier;
ret = sizeof(sense_rsp);
memcpy(buffer, &sense_rsp, ret);
// Clear sense data after copy
tud_msc_set_sense(p_cbw->lun, 0, 0, 0);
}
break;
default: ret = -1; break;
}
return ret;
}
bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes)
{
mscd_interface_t* p_msc = &_mscd_itf;
msc_cbw_t const * 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;
TU_ASSERT( event == XFER_RESULT_SUCCESS &&
xferred_bytes == sizeof(msc_cbw_t) && p_cbw->signature == MSC_CBW_SIGNATURE );
p_csw->signature = MSC_CSW_SIGNATURE;
p_csw->tag = p_cbw->tag;
p_csw->data_residue = 0;
/*------------- Parse command and prepare DATA -------------*/
p_msc->stage = MSC_STAGE_DATA;
p_msc->total_len = p_cbw->total_bytes;
p_msc->xferred_len = 0;
if (SCSI_CMD_READ_10 == p_cbw->command[0])
{
proc_read10_cmd(rhport, p_msc);
}
else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
{
proc_write10_cmd(rhport, p_msc);
}
else
{
// For other SCSI commands
// 1. Zero : Invoke app callback, skip DATA and move to STATUS stage
// 2. OUT : queue transfer (invoke app callback after done)
// 3. IN : invoke app callback to get response
if ( p_cbw->total_bytes == 0)
{
int32_t const cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, NULL, 0);
p_msc->total_len = 0;
p_msc->stage = MSC_STAGE_STATUS;
if ( cb_result < 0 )
{
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
}
else
{
p_csw->status = MSC_CSW_STATUS_PASSED;
}
}
else if ( !TU_BIT_TEST(p_cbw->dir, 7) )
{
// OUT transfer
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, p_msc->total_len) );
}
else
{
// IN Transfer
int32_t cb_result;
// first process if it is a built-in commands
cb_result = proc_builtin_scsi(p_cbw, _mscd_buf, sizeof(_mscd_buf));
// Not an built-in command, invoke user callback
if ( cb_result < 0 )
{
cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len);
}
if ( cb_result > 0 )
{
p_msc->total_len = (uint32_t) cb_result;
p_csw->status = MSC_CSW_STATUS_PASSED;
TU_ASSERT( p_cbw->total_bytes >= p_msc->total_len ); // cannot return more than host expect
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, p_msc->total_len) );
}else
{
p_msc->total_len = 0;
p_csw->status = MSC_CSW_STATUS_FAILED;
p_msc->stage = MSC_STAGE_STATUS;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
usbd_edpt_stall(rhport, p_msc->ep_in);
}
}
}
break;
case MSC_STAGE_DATA:
// OUT transfer, invoke callback if needed
if ( !TU_BIT_TEST(p_cbw->dir, 7) )
{
if ( SCSI_CMD_WRITE_10 != p_cbw->command[0] )
{
int32_t cb_result = tud_msc_scsi_cb(p_cbw->lun, p_cbw->command, _mscd_buf, p_msc->total_len);
if ( cb_result < 0 )
{
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
}else
{
p_csw->status = MSC_CSW_STATUS_PASSED;
}
}
else
{
uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command);
// Adjust lba with transferred bytes
uint32_t const lba = rdwr10_get_lba(p_cbw->command) + (p_msc->xferred_len / block_sz);
// Application can consume smaller bytes
int32_t nbytes = tud_msc_write10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, xferred_bytes);
if ( nbytes < 0 )
{
// negative means error -> skip to status phase, status in CSW set to failed
p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len;
p_csw->status = MSC_CSW_STATUS_FAILED;
p_msc->stage = MSC_STAGE_STATUS;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
break;
}else
{
// Application consume less than what we got (including zero)
if ( nbytes < (int32_t) xferred_bytes )
{
if ( nbytes > 0 )
{
p_msc->xferred_len += nbytes;
memmove(_mscd_buf, _mscd_buf+nbytes, xferred_bytes-nbytes);
}
// simulate an transfer complete with adjusted parameters --> this driver callback will fired again
dcd_event_xfer_complete(rhport, p_msc->ep_out, xferred_bytes-nbytes, XFER_RESULT_SUCCESS, false);
return true; // skip the rest
}
else
{
// Application consume all bytes in our buffer. Nothing to do, process with normal flow
}
}
}
}
// Accumulate data so far
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
{
// READ10 & WRITE10 Can be executed with large bulk of data e.g write 8K bytes (several flash write)
// We break it into multiple smaller command whose data size is up to CFG_TUD_MSC_BUFSIZE
if (SCSI_CMD_READ_10 == p_cbw->command[0])
{
proc_read10_cmd(rhport, p_msc);
}
else if (SCSI_CMD_WRITE_10 == p_cbw->command[0])
{
proc_write10_cmd(rhport, p_msc);
}else
{
// No other command take more than one transfer yet -> unlikely error
TU_BREAKPOINT();
}
}
break;
case MSC_STAGE_STATUS: break; // processed immediately after this switch
default : break;
}
if ( p_msc->stage == MSC_STAGE_STATUS )
{
// Either endpoints is stalled, need to wait until it is cleared by host
if ( usbd_edpt_stalled(rhport, p_msc->ep_in) || usbd_edpt_stalled(rhport, p_msc->ep_out) )
{
// simulate an transfer complete with adjusted parameters --> this driver callback will fired again
dcd_event_xfer_complete(rhport, p_msc->ep_out, 0, XFER_RESULT_SUCCESS, false);
}
else
{
// Move to default CMD stage when sending status
p_msc->stage = MSC_STAGE_CMD;
// Send SCSI Status
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_in , (uint8_t*) &p_msc->csw, sizeof(msc_csw_t)) );
// Invoke complete callback if defined
if ( SCSI_CMD_READ_10 == p_cbw->command[0])
{
if ( tud_msc_read10_complete_cb ) tud_msc_read10_complete_cb(p_cbw->lun);
}
else if ( SCSI_CMD_WRITE_10 == p_cbw->command[0] )
{
if ( tud_msc_write10_complete_cb ) tud_msc_write10_complete_cb(p_cbw->lun);
}
else
{
if ( tud_msc_scsi_complete_cb ) tud_msc_scsi_complete_cb(p_cbw->lun, p_cbw->command);
}
// Queue for the next CBW
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, (uint8_t*) &p_msc->cbw, sizeof(msc_cbw_t)) );
}
}
return true;
}
/*------------------------------------------------------------------*/
/* SCSI Command Process
*------------------------------------------------------------------*/
static void proc_read10_cmd(uint8_t rhport, mscd_interface_t* p_msc)
{
msc_cbw_t const * p_cbw = &p_msc->cbw;
msc_csw_t * p_csw = &p_msc->csw;
uint16_t const block_sz = p_cbw->total_bytes / rdwr10_get_blockcount(p_cbw->command);
// 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(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len);
// Application can consume smaller bytes
nbytes = tud_msc_read10_cb(p_cbw->lun, lba, p_msc->xferred_len % block_sz, _mscd_buf, (uint32_t) nbytes);
if ( nbytes < 0 )
{
// negative means error -> pipe is stalled & status in CSW set to failed
p_csw->data_residue = p_cbw->total_bytes - p_msc->xferred_len;
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); // Sense = Invalid Command Operation
usbd_edpt_stall(rhport, p_msc->ep_in);
}
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( dcd_edpt_xfer(rhport, p_msc->ep_in, _mscd_buf, 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) {
msc_csw_t* p_csw = &p_msc->csw;
p_csw->data_residue = p_cbw->total_bytes;
p_csw->status = MSC_CSW_STATUS_FAILED;
tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_DATA_PROTECT, 0x27, 0x00); // Sense = Write protected
usbd_edpt_stall(rhport, p_msc->ep_out);
return;
}
// remaining bytes capped at class buffer
int32_t nbytes = (int32_t) tu_min32(sizeof(_mscd_buf), p_cbw->total_bytes-p_msc->xferred_len);
// Write10 callback will be called later when usb transfer complete
TU_ASSERT( dcd_edpt_xfer(rhport, p_msc->ep_out, _mscd_buf, nbytes), );
}
#endif

View file

@ -0,0 +1,163 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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 "device/usbd.h"
#include "msc.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Class Driver Configuration
//--------------------------------------------------------------------+
TU_VERIFY_STATIC(CFG_TUD_MSC_BUFSIZE < UINT16_MAX, "Size is not correct");
#ifndef CFG_TUD_MSC_BUFSIZE
#error CFG_TUD_MSC_BUFSIZE must be defined, value of a block size should work well, the more the better
#endif
#ifndef CFG_TUD_MSC_VENDOR
#error CFG_TUD_MSC_VENDOR 8-byte name must be defined
#endif
#ifndef CFG_TUD_MSC_PRODUCT
#error CFG_TUD_MSC_PRODUCT 16-byte name must be defined
#endif
#ifndef CFG_TUD_MSC_PRODUCT_REV
#error CFG_TUD_MSC_PRODUCT_REV 4-byte string must be defined
#endif
/** \addtogroup ClassDriver_MSC
* @{
* \defgroup MSC_Device Device
* @{ */
bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, uint8_t add_sense_qualifier);
//--------------------------------------------------------------------+
// APPLICATION CALLBACK (WEAK is optional)
//--------------------------------------------------------------------+
/**
* Callback invoked when received \ref SCSI_CMD_READ_10 command
* \param[in] lun Logical unit number
* \param[in] lba Logical Block Address to be read
* \param[in] offset Byte offset from LBA
* \param[out] buffer Buffer which application need to update with the response data.
* \param[in] bufsize Requested bytes
*
* \return Number of byte read, if it is less than requested bytes by \a \b bufsize. Tinyusb will transfer
* this amount first and invoked this again for remaining data.
*
* \retval zero Indicate application is not ready yet to response e.g disk I/O is not complete.
* tinyusb will invoke this callback with the same parameters again some time later.
*
* \retval negative Indicate error e.g reading disk I/O. tinyusb will \b STALL the corresponding
* endpoint and return failed status in command status wrapper phase.
*/
ATTR_WEAK int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize);
/**
* Callback invoked when received \ref SCSI_CMD_WRITE_10 command
* \param[in] lun Logical unit number
* \param[in] lba Logical Block Address to be write
* \param[in] offset Byte offset from LBA
* \param[out] buffer Buffer which holds written data.
* \param[in] bufsize Requested bytes
*
* \return Number of byte written, if it is less than requested bytes by \a \b bufsize. Tinyusb will proceed with
* other work and invoked this again with adjusted parameters.
*
* \retval zero Indicate application is not ready yet e.g disk I/O is not complete.
* Tinyusb will invoke this callback with the same parameters again some time later.
*
* \retval negative Indicate error writing disk I/O. Tinyusb will \b STALL the corresponding
* endpoint and return failed status in command status wrapper phase.
*/
ATTR_WEAK int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize);
// Invoked to determine the disk size
ATTR_WEAK void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size);
/**
* Callback invoked when received an SCSI command not in built-in list below.
* \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.
*
* \note Following command is automatically handled by tinyusb stack, callback should not be worried:
* - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, MODE_SENSE6, REQUEST_SENSE
* - READ10 and WRITE10 has their own callbacks
*/
ATTR_WEAK int32_t tud_msc_scsi_cb (uint8_t lun, uint8_t const scsi_cmd[16], void* buffer, uint16_t bufsize);
/*------------- Optional callbacks -------------*/
// Invoked to determine max LUN
ATTR_WEAK uint8_t tud_msc_maxlun_cb(void);
// Invoked when Read10 command is complete
ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun);
// Invoke when Write10 command is complete
ATTR_WEAK void tud_msc_write10_complete_cb(uint8_t lun);
// Invoked when command in tud_msc_scsi_cb is complete
ATTR_WEAK void tud_msc_scsi_complete_cb(uint8_t lun, uint8_t const scsi_cmd[16]);
// Hook to make a mass storage device read-only. TODO remove
ATTR_WEAK bool tud_msc_is_writable_cb(uint8_t lun);
/** @} */
/** @} */
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void mscd_init(void);
bool mscd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
bool mscd_control_request_complete (uint8_t rhport, 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);
void mscd_reset(uint8_t rhport);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_MSC_DEVICE_H_ */

View file

@ -0,0 +1,74 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_Compiler
* \defgroup Group_GCC GNU GCC
* @{ */
#ifndef _TUSB_COMPILER_GCC_H_
#define _TUSB_COMPILER_GCC_H_
#ifdef __cplusplus
extern "C" {
#endif
#define ALIGN_OF(x) __alignof__(x)
// Specifies a minimum alignment for the variable or structure field, measured in bytes
#define ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes)))
// Place variable in a specific section
#define ATTR_SECTION(sec_name) __attribute__ (( section(#sec_name) ))
// Packed struct/variable into smallest possible size
#define ATTR_PACKED __attribute__ ((packed))
#define ATTR_PREPACKED
// The deprecated attribute results in a warning if the function is used.
#define ATTR_DEPRECATED(mess) __attribute__ ((deprecated(mess)))
// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global.
#define ATTR_WEAK __attribute__ ((weak))
// Function/Variable is meant to be possibly unused (thus no warning)
#define ATTR_UNUSED __attribute__ ((unused))
// TODO mcu specific
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define __n2be(x) __builtin_bswap32(x) ///< built-in function to convert 32-bit from native to Big Endian
#define __be2n(x) __n2be(x) ///< built-in function to convert 32-bit from Big Endian to native
#define __n2be_16(u16) __builtin_bswap16(u16)
#define __be2n_16(u16) __n2be_16(u16)
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_COMPILER_GCC_H_ */
/// @}

View file

@ -0,0 +1,58 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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_COMPILER_IAR_H_
#define _TUSB_COMPILER_IAR_H_
#ifdef __cplusplus
extern "C" {
#endif
#define ALIGN_OF(x) __ALIGNOF__(x)
#define ATTR_ALIGNED(bytes) _Pragma(XSTRING_(data_alignment=##bytes))
//#define ATTR_SECTION(section) _Pragma((#section))
#define ATTR_PREPACKED __packed
#define ATTR_PACKED
#define ATTR_DEPRECATED(mess)
#define ATTR_WEAK __weak
#define ATTR_UNUSED
// built-in function to convert 32-bit Big-Endian to Little-Endian
//#if __LITTLE_ENDIAN__
#define __be2n __REV
#define __n2be __be2n
#define __n2be_16(u16) ((uint16_t) __REV16(u16))
#define __be2n_16(u16) __n2be_16(u16)
#error "IAR won't work due to '__packed' placement before struct"
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_COMPILER_IAR_H_ */

View file

@ -0,0 +1,871 @@
/*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
* $FreeBSD$
*/
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
#include <sys/cdefs.h>
/*
* This file defines four types of data structures: singly-linked lists,
* singly-linked tail queues, lists and tail queues.
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A singly-linked tail queue is headed by a pair of pointers, one to the
* head of the list and the other to the tail of the list. The elements are
* singly linked for minimum space and pointer manipulation overhead at the
* expense of O(n) removal for arbitrary elements. New elements can be added
* to the list after an existing element, at the head of the list, or at the
* end of the list. Elements being removed from the head of the tail queue
* should use the explicit macro for this purpose for optimum efficiency.
* A singly-linked tail queue may only be traversed in the forward direction.
* Singly-linked tail queues are ideal for applications with large datasets
* and few or no removals or for implementing a FIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may be traversed in either direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* For details on the use of these macros, see the queue(3) manual page.
*
* Below is a summary of implemented functions where:
* + means the macro is available
* - means the macro is not available
* s means the macro is available but is slow (runs in O(n) time)
*
* SLIST LIST STAILQ TAILQ
* _HEAD + + + +
* _CLASS_HEAD + + + +
* _HEAD_INITIALIZER + + + +
* _ENTRY + + + +
* _CLASS_ENTRY + + + +
* _INIT + + + +
* _EMPTY + + + +
* _FIRST + + + +
* _NEXT + + + +
* _PREV - + - +
* _LAST - - + +
* _LAST_FAST - - - +
* _FOREACH + + + +
* _FOREACH_FROM + + + +
* _FOREACH_SAFE + + + +
* _FOREACH_FROM_SAFE + + + +
* _FOREACH_REVERSE - - - +
* _FOREACH_REVERSE_FROM - - - +
* _FOREACH_REVERSE_SAFE - - - +
* _FOREACH_REVERSE_FROM_SAFE - - - +
* _INSERT_HEAD + + + +
* _INSERT_BEFORE - + - +
* _INSERT_AFTER + + + +
* _INSERT_TAIL - - + +
* _CONCAT s s + +
* _REMOVE_AFTER + - + -
* _REMOVE_HEAD + - + -
* _REMOVE s + s +
* _SWAP + + + +
*
*/
#ifdef QUEUE_MACRO_DEBUG
#warn Use QUEUE_MACRO_DEBUG_TRACE and/or QUEUE_MACRO_DEBUG_TRASH
#define QUEUE_MACRO_DEBUG_TRACE
#define QUEUE_MACRO_DEBUG_TRASH
#endif
#ifdef QUEUE_MACRO_DEBUG_TRACE
/* Store the last 2 places the queue element or head was altered */
struct qm_trace {
unsigned long lastline;
unsigned long prevline;
const char *lastfile;
const char *prevfile;
};
#define TRACEBUF struct qm_trace trace;
#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } ,
#define QMD_TRACE_HEAD(head) do { \
(head)->trace.prevline = (head)->trace.lastline; \
(head)->trace.prevfile = (head)->trace.lastfile; \
(head)->trace.lastline = __LINE__; \
(head)->trace.lastfile = __FILE__; \
} while (0)
#define QMD_TRACE_ELEM(elem) do { \
(elem)->trace.prevline = (elem)->trace.lastline; \
(elem)->trace.prevfile = (elem)->trace.lastfile; \
(elem)->trace.lastline = __LINE__; \
(elem)->trace.lastfile = __FILE__; \
} while (0)
#else /* !QUEUE_MACRO_DEBUG_TRACE */
#define QMD_TRACE_ELEM(elem)
#define QMD_TRACE_HEAD(head)
#define TRACEBUF
#define TRACEBUF_INITIALIZER
#endif /* QUEUE_MACRO_DEBUG_TRACE */
#ifdef QUEUE_MACRO_DEBUG_TRASH
#define TRASHIT(x) do {(x) = (void *)-1;} while (0)
#define QMD_IS_TRASHED(x) ((x) == (void *)(intptr_t)-1)
#else /* !QUEUE_MACRO_DEBUG_TRASH */
#define TRASHIT(x)
#define QMD_IS_TRASHED(x) 0
#endif /* QUEUE_MACRO_DEBUG_TRASH */
#if defined(QUEUE_MACRO_DEBUG_TRACE) || defined(QUEUE_MACRO_DEBUG_TRASH)
#define QMD_SAVELINK(name, link) void **name = (void *)&(link)
#else /* !QUEUE_MACRO_DEBUG_TRACE && !QUEUE_MACRO_DEBUG_TRASH */
#define QMD_SAVELINK(name, link)
#endif /* QUEUE_MACRO_DEBUG_TRACE || QUEUE_MACRO_DEBUG_TRASH */
#ifdef __cplusplus
/*
* In C++ there can be structure lists and class lists:
*/
#define QUEUE_TYPEOF(type) type
#else
#define QUEUE_TYPEOF(type) struct type
#endif
/*
* Singly-linked List declarations.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_CLASS_HEAD(name, type) \
struct name { \
class type *slh_first; /* first element */ \
}
#define SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
#define SLIST_CLASS_ENTRY(type) \
struct { \
class type *sle_next; /* next element */ \
}
/*
* Singly-linked List functions.
*/
#if (defined(_KERNEL) && defined(INVARIANTS))
#define QMD_SLIST_CHECK_PREVPTR(prevp, elm) do { \
if (*(prevp) != (elm)) \
panic("Bad prevptr *(%p) == %p != %p", \
(prevp), *(prevp), (elm)); \
} while (0)
#else
#define QMD_SLIST_CHECK_PREVPTR(prevp, elm)
#endif
#define SLIST_CONCAT(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head1); \
if (curelm == NULL) { \
if ((SLIST_FIRST(head1) = SLIST_FIRST(head2)) != NULL) \
SLIST_INIT(head2); \
} else if (SLIST_FIRST(head2) != NULL) { \
while (SLIST_NEXT(curelm, field) != NULL) \
curelm = SLIST_NEXT(curelm, field); \
SLIST_NEXT(curelm, field) = SLIST_FIRST(head2); \
SLIST_INIT(head2); \
} \
} while (0)
#define SLIST_EMPTY(head) ((head)->slh_first == NULL)
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_FOREACH(var, head, field) \
for ((var) = SLIST_FIRST((head)); \
(var); \
(var) = SLIST_NEXT((var), field))
#define SLIST_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \
(var); \
(var) = SLIST_NEXT((var), field))
#define SLIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = SLIST_FIRST((head)); \
(var) && ((tvar) = SLIST_NEXT((var), field), 1); \
(var) = (tvar))
#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \
(var) && ((tvar) = SLIST_NEXT((var), field), 1); \
(var) = (tvar))
#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \
for ((varp) = &SLIST_FIRST((head)); \
((var) = *(varp)) != NULL; \
(varp) = &SLIST_NEXT((var), field))
#define SLIST_INIT(head) do { \
SLIST_FIRST((head)) = NULL; \
} while (0)
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \
SLIST_NEXT((slistelm), field) = (elm); \
} while (0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \
SLIST_FIRST((head)) = (elm); \
} while (0)
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_REMOVE(head, elm, type, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.sle_next); \
if (SLIST_FIRST((head)) == (elm)) { \
SLIST_REMOVE_HEAD((head), field); \
} \
else { \
QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \
while (SLIST_NEXT(curelm, field) != (elm)) \
curelm = SLIST_NEXT(curelm, field); \
SLIST_REMOVE_AFTER(curelm, field); \
} \
TRASHIT(*oldnext); \
} while (0)
#define SLIST_REMOVE_AFTER(elm, field) do { \
SLIST_NEXT(elm, field) = \
SLIST_NEXT(SLIST_NEXT(elm, field), field); \
} while (0)
#define SLIST_REMOVE_HEAD(head, field) do { \
SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \
} while (0)
#define SLIST_REMOVE_PREVPTR(prevp, elm, field) do { \
QMD_SLIST_CHECK_PREVPTR(prevp, elm); \
*(prevp) = SLIST_NEXT(elm, field); \
TRASHIT((elm)->field.sle_next); \
} while (0)
#define SLIST_SWAP(head1, head2, type) do { \
QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \
SLIST_FIRST(head1) = SLIST_FIRST(head2); \
SLIST_FIRST(head2) = swap_first; \
} while (0)
/*
* Singly-linked Tail queue declarations.
*/
#define STAILQ_HEAD(name, type) \
struct name { \
struct type *stqh_first;/* first element */ \
struct type **stqh_last;/* addr of last next element */ \
}
#define STAILQ_CLASS_HEAD(name, type) \
struct name { \
class type *stqh_first; /* first element */ \
class type **stqh_last; /* addr of last next element */ \
}
#define STAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).stqh_first }
#define STAILQ_ENTRY(type) \
struct { \
struct type *stqe_next; /* next element */ \
}
#define STAILQ_CLASS_ENTRY(type) \
struct { \
class type *stqe_next; /* next element */ \
}
/*
* Singly-linked Tail queue functions.
*/
#define STAILQ_CONCAT(head1, head2) do { \
if (!STAILQ_EMPTY((head2))) { \
*(head1)->stqh_last = (head2)->stqh_first; \
(head1)->stqh_last = (head2)->stqh_last; \
STAILQ_INIT((head2)); \
} \
} while (0)
#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL)
#define STAILQ_FIRST(head) ((head)->stqh_first)
#define STAILQ_FOREACH(var, head, field) \
for((var) = STAILQ_FIRST((head)); \
(var); \
(var) = STAILQ_NEXT((var), field))
#define STAILQ_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \
(var); \
(var) = STAILQ_NEXT((var), field))
#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = STAILQ_FIRST((head)); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define STAILQ_INIT(head) do { \
STAILQ_FIRST((head)) = NULL; \
(head)->stqh_last = &STAILQ_FIRST((head)); \
} while (0)
#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \
if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
STAILQ_NEXT((tqelm), field) = (elm); \
} while (0)
#define STAILQ_INSERT_HEAD(head, elm, field) do { \
if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
STAILQ_FIRST((head)) = (elm); \
} while (0)
#define STAILQ_INSERT_TAIL(head, elm, field) do { \
STAILQ_NEXT((elm), field) = NULL; \
*(head)->stqh_last = (elm); \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
} while (0)
#define STAILQ_LAST(head, type, field) \
(STAILQ_EMPTY((head)) ? NULL : \
__containerof((head)->stqh_last, \
QUEUE_TYPEOF(type), field.stqe_next))
#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
#define STAILQ_REMOVE(head, elm, type, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \
if (STAILQ_FIRST((head)) == (elm)) { \
STAILQ_REMOVE_HEAD((head), field); \
} \
else { \
QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \
while (STAILQ_NEXT(curelm, field) != (elm)) \
curelm = STAILQ_NEXT(curelm, field); \
STAILQ_REMOVE_AFTER(head, curelm, field); \
} \
TRASHIT(*oldnext); \
} while (0)
#define STAILQ_REMOVE_AFTER(head, elm, field) do { \
if ((STAILQ_NEXT(elm, field) = \
STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
} while (0)
#define STAILQ_REMOVE_HEAD(head, field) do { \
if ((STAILQ_FIRST((head)) = \
STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \
(head)->stqh_last = &STAILQ_FIRST((head)); \
} while (0)
#define STAILQ_SWAP(head1, head2, type) do { \
QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \
QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \
STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \
(head1)->stqh_last = (head2)->stqh_last; \
STAILQ_FIRST(head2) = swap_first; \
(head2)->stqh_last = swap_last; \
if (STAILQ_EMPTY(head1)) \
(head1)->stqh_last = &STAILQ_FIRST(head1); \
if (STAILQ_EMPTY(head2)) \
(head2)->stqh_last = &STAILQ_FIRST(head2); \
} while (0)
/*
* List declarations.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_CLASS_HEAD(name, type) \
struct name { \
class type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
#define LIST_CLASS_ENTRY(type) \
struct { \
class type *le_next; /* next element */ \
class type **le_prev; /* address of previous next element */ \
}
/*
* List functions.
*/
#if (defined(_KERNEL) && defined(INVARIANTS))
/*
* QMD_LIST_CHECK_HEAD(LIST_HEAD *head, LIST_ENTRY NAME)
*
* If the list is non-empty, validates that the first element of the list
* points back at 'head.'
*/
#define QMD_LIST_CHECK_HEAD(head, field) do { \
if (LIST_FIRST((head)) != NULL && \
LIST_FIRST((head))->field.le_prev != \
&LIST_FIRST((head))) \
panic("Bad list head %p first->prev != head", (head)); \
} while (0)
/*
* QMD_LIST_CHECK_NEXT(TYPE *elm, LIST_ENTRY NAME)
*
* If an element follows 'elm' in the list, validates that the next element
* points back at 'elm.'
*/
#define QMD_LIST_CHECK_NEXT(elm, field) do { \
if (LIST_NEXT((elm), field) != NULL && \
LIST_NEXT((elm), field)->field.le_prev != \
&((elm)->field.le_next)) \
panic("Bad link elm %p next->prev != elm", (elm)); \
} while (0)
/*
* QMD_LIST_CHECK_PREV(TYPE *elm, LIST_ENTRY NAME)
*
* Validates that the previous element (or head of the list) points to 'elm.'
*/
#define QMD_LIST_CHECK_PREV(elm, field) do { \
if (*(elm)->field.le_prev != (elm)) \
panic("Bad link elm %p prev->next != elm", (elm)); \
} while (0)
#else
#define QMD_LIST_CHECK_HEAD(head, field)
#define QMD_LIST_CHECK_NEXT(elm, field)
#define QMD_LIST_CHECK_PREV(elm, field)
#endif /* (_KERNEL && INVARIANTS) */
#define LIST_CONCAT(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *curelm = LIST_FIRST(head1); \
if (curelm == NULL) { \
if ((LIST_FIRST(head1) = LIST_FIRST(head2)) != NULL) { \
LIST_FIRST(head2)->field.le_prev = \
&LIST_FIRST((head1)); \
LIST_INIT(head2); \
} \
} else if (LIST_FIRST(head2) != NULL) { \
while (LIST_NEXT(curelm, field) != NULL) \
curelm = LIST_NEXT(curelm, field); \
LIST_NEXT(curelm, field) = LIST_FIRST(head2); \
LIST_FIRST(head2)->field.le_prev = &LIST_NEXT(curelm, field); \
LIST_INIT(head2); \
} \
} while (0)
#define LIST_EMPTY(head) ((head)->lh_first == NULL)
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_FOREACH(var, head, field) \
for ((var) = LIST_FIRST((head)); \
(var); \
(var) = LIST_NEXT((var), field))
#define LIST_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : LIST_FIRST((head))); \
(var); \
(var) = LIST_NEXT((var), field))
#define LIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = LIST_FIRST((head)); \
(var) && ((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : LIST_FIRST((head))); \
(var) && ((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_INIT(head) do { \
LIST_FIRST((head)) = NULL; \
} while (0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
QMD_LIST_CHECK_NEXT(listelm, field); \
if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
LIST_NEXT((listelm), field)->field.le_prev = \
&LIST_NEXT((elm), field); \
LIST_NEXT((listelm), field) = (elm); \
(elm)->field.le_prev = &LIST_NEXT((listelm), field); \
} while (0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
QMD_LIST_CHECK_PREV(listelm, field); \
(elm)->field.le_prev = (listelm)->field.le_prev; \
LIST_NEXT((elm), field) = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &LIST_NEXT((elm), field); \
} while (0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
QMD_LIST_CHECK_HEAD((head), field); \
if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \
LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
LIST_FIRST((head)) = (elm); \
(elm)->field.le_prev = &LIST_FIRST((head)); \
} while (0)
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_PREV(elm, head, type, field) \
((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \
__containerof((elm)->field.le_prev, \
QUEUE_TYPEOF(type), field.le_next))
#define LIST_REMOVE(elm, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.le_next); \
QMD_SAVELINK(oldprev, (elm)->field.le_prev); \
QMD_LIST_CHECK_NEXT(elm, field); \
QMD_LIST_CHECK_PREV(elm, field); \
if (LIST_NEXT((elm), field) != NULL) \
LIST_NEXT((elm), field)->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = LIST_NEXT((elm), field); \
TRASHIT(*oldnext); \
TRASHIT(*oldprev); \
} while (0)
#define LIST_SWAP(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \
LIST_FIRST((head1)) = LIST_FIRST((head2)); \
LIST_FIRST((head2)) = swap_tmp; \
if ((swap_tmp = LIST_FIRST((head1))) != NULL) \
swap_tmp->field.le_prev = &LIST_FIRST((head1)); \
if ((swap_tmp = LIST_FIRST((head2))) != NULL) \
swap_tmp->field.le_prev = &LIST_FIRST((head2)); \
} while (0)
/*
* Tail queue declarations.
*/
#define TAILQ_HEAD(name, type) \
struct name { \
struct type *tqh_first; /* first element */ \
struct type **tqh_last; /* addr of last next element */ \
TRACEBUF \
}
#define TAILQ_CLASS_HEAD(name, type) \
struct name { \
class type *tqh_first; /* first element */ \
class type **tqh_last; /* addr of last next element */ \
TRACEBUF \
}
#define TAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
#define TAILQ_ENTRY(type) \
struct { \
struct type *tqe_next; /* next element */ \
struct type **tqe_prev; /* address of previous next element */ \
TRACEBUF \
}
#define TAILQ_CLASS_ENTRY(type) \
struct { \
class type *tqe_next; /* next element */ \
class type **tqe_prev; /* address of previous next element */ \
TRACEBUF \
}
/*
* Tail queue functions.
*/
#if (defined(_KERNEL) && defined(INVARIANTS))
/*
* QMD_TAILQ_CHECK_HEAD(TAILQ_HEAD *head, TAILQ_ENTRY NAME)
*
* If the tailq is non-empty, validates that the first element of the tailq
* points back at 'head.'
*/
#define QMD_TAILQ_CHECK_HEAD(head, field) do { \
if (!TAILQ_EMPTY(head) && \
TAILQ_FIRST((head))->field.tqe_prev != \
&TAILQ_FIRST((head))) \
panic("Bad tailq head %p first->prev != head", (head)); \
} while (0)
/*
* QMD_TAILQ_CHECK_TAIL(TAILQ_HEAD *head, TAILQ_ENTRY NAME)
*
* Validates that the tail of the tailq is a pointer to pointer to NULL.
*/
#define QMD_TAILQ_CHECK_TAIL(head, field) do { \
if (*(head)->tqh_last != NULL) \
panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \
} while (0)
/*
* QMD_TAILQ_CHECK_NEXT(TYPE *elm, TAILQ_ENTRY NAME)
*
* If an element follows 'elm' in the tailq, validates that the next element
* points back at 'elm.'
*/
#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \
if (TAILQ_NEXT((elm), field) != NULL && \
TAILQ_NEXT((elm), field)->field.tqe_prev != \
&((elm)->field.tqe_next)) \
panic("Bad link elm %p next->prev != elm", (elm)); \
} while (0)
/*
* QMD_TAILQ_CHECK_PREV(TYPE *elm, TAILQ_ENTRY NAME)
*
* Validates that the previous element (or head of the tailq) points to 'elm.'
*/
#define QMD_TAILQ_CHECK_PREV(elm, field) do { \
if (*(elm)->field.tqe_prev != (elm)) \
panic("Bad link elm %p prev->next != elm", (elm)); \
} while (0)
#else
#define QMD_TAILQ_CHECK_HEAD(head, field)
#define QMD_TAILQ_CHECK_TAIL(head, headname)
#define QMD_TAILQ_CHECK_NEXT(elm, field)
#define QMD_TAILQ_CHECK_PREV(elm, field)
#endif /* (_KERNEL && INVARIANTS) */
#define TAILQ_CONCAT(head1, head2, field) do { \
if (!TAILQ_EMPTY(head2)) { \
*(head1)->tqh_last = (head2)->tqh_first; \
(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
(head1)->tqh_last = (head2)->tqh_last; \
TAILQ_INIT((head2)); \
QMD_TRACE_HEAD(head1); \
QMD_TRACE_HEAD(head2); \
} \
} while (0)
#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL)
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_FOREACH(var, head, field) \
for ((var) = TAILQ_FIRST((head)); \
(var); \
(var) = TAILQ_NEXT((var), field))
#define TAILQ_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \
(var); \
(var) = TAILQ_NEXT((var), field))
#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = TAILQ_FIRST((head)); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for ((var) = TAILQ_LAST((head), headname); \
(var); \
(var) = TAILQ_PREV((var), headname, field))
#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \
for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \
(var); \
(var) = TAILQ_PREV((var), headname, field))
#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \
for ((var) = TAILQ_LAST((head), headname); \
(var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \
for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \
(var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \
(var) = (tvar))
#define TAILQ_INIT(head) do { \
TAILQ_FIRST((head)) = NULL; \
(head)->tqh_last = &TAILQ_FIRST((head)); \
QMD_TRACE_HEAD(head); \
} while (0)
#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
QMD_TAILQ_CHECK_NEXT(listelm, field); \
if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
TAILQ_NEXT((elm), field)->field.tqe_prev = \
&TAILQ_NEXT((elm), field); \
else { \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
QMD_TRACE_HEAD(head); \
} \
TAILQ_NEXT((listelm), field) = (elm); \
(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \
QMD_TRACE_ELEM(&(elm)->field); \
QMD_TRACE_ELEM(&(listelm)->field); \
} while (0)
#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
QMD_TAILQ_CHECK_PREV(listelm, field); \
(elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
TAILQ_NEXT((elm), field) = (listelm); \
*(listelm)->field.tqe_prev = (elm); \
(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \
QMD_TRACE_ELEM(&(elm)->field); \
QMD_TRACE_ELEM(&(listelm)->field); \
} while (0)
#define TAILQ_INSERT_HEAD(head, elm, field) do { \
QMD_TAILQ_CHECK_HEAD(head, field); \
if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \
TAILQ_FIRST((head))->field.tqe_prev = \
&TAILQ_NEXT((elm), field); \
else \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
TAILQ_FIRST((head)) = (elm); \
(elm)->field.tqe_prev = &TAILQ_FIRST((head)); \
QMD_TRACE_HEAD(head); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
QMD_TAILQ_CHECK_TAIL(head, field); \
TAILQ_NEXT((elm), field) = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
QMD_TRACE_HEAD(head); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
/*
* The FAST function is fast in that it causes no data access other
* then the access to the head. The standard LAST function above
* will cause a data access of both the element you want and
* the previous element. FAST is very useful for instances when
* you may want to prefetch the last data element.
*/
#define TAILQ_LAST_FAST(head, type, field) \
(TAILQ_EMPTY(head) ? NULL : __containerof((head)->tqh_last, QUEUE_TYPEOF(type), field.tqe_next))
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_REMOVE(head, elm, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \
QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \
QMD_TAILQ_CHECK_NEXT(elm, field); \
QMD_TAILQ_CHECK_PREV(elm, field); \
if ((TAILQ_NEXT((elm), field)) != NULL) \
TAILQ_NEXT((elm), field)->field.tqe_prev = \
(elm)->field.tqe_prev; \
else { \
(head)->tqh_last = (elm)->field.tqe_prev; \
QMD_TRACE_HEAD(head); \
} \
*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \
TRASHIT(*oldnext); \
TRASHIT(*oldprev); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_SWAP(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \
QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \
(head1)->tqh_first = (head2)->tqh_first; \
(head1)->tqh_last = (head2)->tqh_last; \
(head2)->tqh_first = swap_first; \
(head2)->tqh_last = swap_last; \
if ((swap_first = (head1)->tqh_first) != NULL) \
swap_first->field.tqe_prev = &(head1)->tqh_first; \
else \
(head1)->tqh_last = &(head1)->tqh_first; \
if ((swap_first = (head2)->tqh_first) != NULL) \
swap_first->field.tqe_prev = &(head2)->tqh_first; \
else \
(head2)->tqh_last = &(head2)->tqh_first; \
} while (0)
#endif /* !_SYS_QUEUE_H_ */

View file

@ -0,0 +1,241 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup Group_Common
* \defgroup Group_CommonH common.h
* @{ */
#ifndef _TUSB_COMMON_H_
#define _TUSB_COMMON_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Macros Helper
//--------------------------------------------------------------------+
#define TU_ARRAY_SZIE(_arr) ( sizeof(_arr) / sizeof(_arr[0]) )
#define TU_MIN(_x, _y) ( (_x) < (_y) ) ? (_x) : (_y) )
#define TU_MAX(_x, _y) ( (_x) > (_y) ) ? (_x) : (_y) )
#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff))
#define U16_LOW_U8(u16) ((uint8_t) ((u16) & 0x00ff))
#define U16_TO_U8S_BE(u16) U16_HIGH_U8(u16), U16_LOW_U8(u16)
#define U16_TO_U8S_LE(u16) U16_LOW_U8(u16), U16_HIGH_U8(u16)
#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB
#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff))
#define U32_B3_U8(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff))
#define U32_B4_U8(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB
#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32)
#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32)
//------------- Bit -------------//
#define TU_BIT(n) (1U << (n)) ///< n-th Bit
#define TU_BIT_SET(x, n) ( (x) | TU_BIT(n) ) ///< set n-th bit of x to 1
#define TU_BIT_CLEAR(x, n) ( (x) & (~TU_BIT(n)) ) ///< clear n-th bit of x
#define TU_BIT_TEST(x, n) ( ((x) & TU_BIT(n)) ? true : false ) ///< check if n-th bit of x is 1
//------------- Endian Conversion -------------//
#define ENDIAN_BE(u32) \
(uint32_t) ( (((u32) & 0xFF) << 24) | (((u32) & 0xFF00) << 8) | (((u32) >> 8) & 0xFF00) | (((u32) >> 24) & 0xFF) )
#define ENDIAN_BE16(le16) ((uint16_t) ((U16_LOW_U8(le16) << 8) | U16_HIGH_U8(le16)) )
//------------- Binary constant -------------//
#if defined(__GNUC__) && !defined(__CC_ARM)
#define TU_BIN8(x) ((uint8_t) (0b##x))
#define TU_BIN16(b1, b2) ((uint16_t) (0b##b1##b2))
#define TU_BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4))
#else
// internal macro of B8, B16, B32
#define _B8__(x) (((x&0x0000000FUL)?1:0) \
+((x&0x000000F0UL)?2:0) \
+((x&0x00000F00UL)?4:0) \
+((x&0x0000F000UL)?8:0) \
+((x&0x000F0000UL)?16:0) \
+((x&0x00F00000UL)?32:0) \
+((x&0x0F000000UL)?64:0) \
+((x&0xF0000000UL)?128:0))
#define TU_BIN8(d) ((uint8_t) _B8__(0x##d##UL))
#define TU_BIN16(dmsb,dlsb) (((uint16_t)TU_BIN8(dmsb)<<8) + TU_BIN8(dlsb))
#define TU_BIN32(dmsb,db2,db3,dlsb) \
(((uint32_t)TU_BIN8(dmsb)<<24) \
+ ((uint32_t)TU_BIN8(db2)<<16) \
+ ((uint32_t)TU_BIN8(db3)<<8) \
+ TU_BIN8(dlsb))
#endif
// for declaration of reserved field, make use of _TU_COUNTER_
#define TU_RESERVED XSTRING_CONCAT_(reserved, _TU_COUNTER_)
//--------------------------------------------------------------------+
// INCLUDES
//--------------------------------------------------------------------+
// Standard Headers
#include <stdbool.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
// Tinyusb Common Headers
#include "tusb_option.h"
#include "tusb_compiler.h"
#include "tusb_verify.h"
#include "tusb_error.h"
#include "tusb_timeout.h"
#include "tusb_types.h"
//--------------------------------------------------------------------+
// INLINE FUNCTION
//--------------------------------------------------------------------+
#ifndef __n2be_16 // TODO clean up
#define __n2be_16(u16) ((uint16_t) ((U16_LOW_U8(u16) << 8) | U16_HIGH_U8(u16)) )
#define __be2n_16(u16) __n2be_16(u16)
#endif
#define tu_memclr(buffer, size) memset((buffer), 0, (size))
#define tu_varclr(_var) tu_memclr(_var, sizeof(*(_var)))
static inline bool tu_mem_test_zero (void const* buffer, uint32_t size)
{
uint8_t const* p_mem = (uint8_t const*) buffer;
for(uint32_t i=0; i<size; i++) if (p_mem[i] != 0) return false;
return true;
}
//------------- Conversion -------------//
static inline uint32_t tu_u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4)
{
return ( ((uint32_t) b1) << 24) + ( ((uint32_t) b2) << 16) + ( ((uint32_t) b3) << 8) + b4;
}
static inline uint8_t tu_u16_high(uint16_t u16)
{
return (uint8_t) ( ((uint16_t) (u16 >> 8)) & 0x00ff);
}
static inline uint8_t tu_u16_low(uint16_t u16)
{
return (uint8_t) (u16 & 0x00ff);
}
static inline uint16_t tu_u16_le2be(uint16_t u16)
{
return ((uint16_t)(tu_u16_low(u16) << 8)) | tu_u16_high(u16);
}
// Min
static inline uint8_t tu_min8 (uint8_t x, uint8_t y ) { return (x < y) ? x : y; }
static inline uint16_t tu_min16 (uint16_t x, uint16_t y) { return (x < y) ? x : y; }
static inline uint32_t tu_min32 (uint32_t x, uint32_t y) { return (x < y) ? x : y; }
// Max
static inline uint8_t tu_max8 (uint8_t x, uint8_t y ) { return (x > y) ? x : y; }
static inline uint16_t tu_max16 (uint16_t x, uint16_t y) { return (x > y) ? x : y; }
static inline uint32_t tu_max32 (uint32_t x, uint32_t y) { return (x > y) ? x : y; }
// Align
static inline uint32_t tu_align32 (uint32_t value) { return (value & 0xFFFFFFE0UL); }
static inline uint32_t tu_align16 (uint32_t value) { return (value & 0xFFFFFFF0UL); }
static inline uint32_t tu_align_n (uint32_t alignment, uint32_t value) { return value & ((uint32_t) ~(alignment-1)); }
static inline uint32_t tu_align4k (uint32_t value) { return (value & 0xFFFFF000UL); }
static inline uint32_t tu_offset4k(uint32_t value) { return (value & 0xFFFUL); }
//------------- Mathematics -------------//
static inline uint32_t tu_abs(int32_t value) { return (value < 0) ? (-value) : value; }
/// inclusive range checking
static inline bool tu_within(uint32_t lower, uint32_t value, uint32_t upper)
{
return (lower <= value) && (value <= upper);
}
// log2 of a value is its MSB's position
// TODO use clz
static inline uint8_t tu_log2(uint32_t value)
{
uint8_t result = 0;
while (value >>= 1)
{
result++;
}
return result;
}
// Bit
static inline uint32_t tu_bit_set(uint32_t value, uint8_t n) { return value | TU_BIT(n); }
static inline uint32_t tu_bit_clear(uint32_t value, uint8_t n) { return value & (~TU_BIT(n)); }
static inline bool tu_bit_test(uint32_t value, uint8_t n) { return (value & TU_BIT(n)) ? true : false; }
/*------------------------------------------------------------------*/
/* Count number of arguments of __VA_ARGS__
* - reference https://groups.google.com/forum/#!topic/comp.std.c/d-6Mj5Lko_s
* - _GET_NTH_ARG() takes args >= N (64) but only expand to Nth one (64th)
* - _RSEQ_N() is reverse sequential to N to add padding to have
* Nth position is the same as the number of arguments
* - ##__VA_ARGS__ is used to deal with 0 paramerter (swallows comma)
*------------------------------------------------------------------*/
#ifndef VA_ARGS_NUM_
#define VA_ARGS_NUM_(...) NARG_(_0, ##__VA_ARGS__,_RSEQ_N())
#define NARG_(...) _GET_NTH_ARG(__VA_ARGS__)
#define _GET_NTH_ARG( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define _RSEQ_N() \
62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_COMMON_H_ */
/** @} */

View file

@ -0,0 +1,71 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup Group_Common
* \defgroup Group_Compiler Compiler
* \brief Group_Compiler brief
* @{ */
#ifndef _TUSB_COMPILER_H_
#define _TUSB_COMPILER_H_
#define STRING_(x) #x ///< stringify without expand
#define XSTRING_(x) STRING_(x) ///< expand then stringify
#define STRING_CONCAT_(a, b) a##b ///< concat without expand
#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) ///< expand then concat
#if defined __COUNTER__ && __COUNTER__ != __COUNTER__
#define _TU_COUNTER_ __COUNTER__
#else
#define _TU_COUNTER_ __LINE__
#endif
//--------------------------------------------------------------------+
// Compile-time Assert (use TU_VERIFY_STATIC to avoid name conflict)
//--------------------------------------------------------------------+
#if __STDC_VERSION__ >= 201112L
#define TU_VERIFY_STATIC _Static_assert
#else
#define TU_VERIFY_STATIC(const_expr, _mess) enum { XSTRING_CONCAT_(_verify_static_, _TU_COUNTER_) = 1/(!!(const_expr)) }
#endif
// allow debugger to watch any module-wide variables anywhere
#if CFG_TUSB_DEBUG
#define STATIC_VAR
#else
#define STATIC_VAR static
#endif
#if defined(__GNUC__)
#include "compiler/tusb_compiler_gcc.h"
#elif defined __ICCARM__
#include "compiler/tusb_compiler_iar.h"
#endif
#endif /* _TUSB_COMPILER_H_ */
/// @}

View file

@ -0,0 +1,74 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup Group_Common
* \defgroup Group_Error Error Codes
* @{ */
#ifndef _TUSB_ERRORS_H_
#define _TUSB_ERRORS_H_
#include "tusb_option.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ERROR_ENUM(x) x,
#define ERROR_STRING(x) #x,
#define ERROR_TABLE(ENTRY) \
ENTRY(TUSB_ERROR_NONE )\
ENTRY(TUSB_ERROR_INVALID_PARA )\
ENTRY(TUSB_ERROR_DEVICE_NOT_READY )\
ENTRY(TUSB_ERROR_INTERFACE_IS_BUSY )\
ENTRY(TUSB_ERROR_HCD_OPEN_PIPE_FAILED )\
ENTRY(TUSB_ERROR_OSAL_TIMEOUT )\
ENTRY(TUSB_ERROR_CDCH_DEVICE_NOT_MOUNTED )\
ENTRY(TUSB_ERROR_MSCH_DEVICE_NOT_MOUNTED )\
ENTRY(TUSB_ERROR_NOT_SUPPORTED )\
ENTRY(TUSB_ERROR_NOT_ENOUGH_MEMORY )\
ENTRY(TUSB_ERROR_FAILED )\
/// \brief Error Code returned
typedef enum
{
ERROR_TABLE(ERROR_ENUM)
TUSB_ERROR_COUNT
}tusb_error_t;
#if CFG_TUSB_DEBUG
/// Enum to String for debugging purposes. Only available if \ref CFG_TUSB_DEBUG > 0
extern char const* const tusb_strerr[TUSB_ERROR_COUNT];
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_ERRORS_H_ */
/** @} */

View file

@ -0,0 +1,266 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (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 <string.h>
#include "osal/osal.h"
#include "tusb_fifo.h"
// implement mutex lock and unlock
#if CFG_FIFO_MUTEX
static void tu_fifo_lock(tu_fifo_t *f)
{
if (f->mutex)
{
osal_mutex_lock(f->mutex, OSAL_TIMEOUT_WAIT_FOREVER);
}
}
static void tu_fifo_unlock(tu_fifo_t *f)
{
if (f->mutex)
{
osal_mutex_unlock(f->mutex);
}
}
#else
#define tu_fifo_lock(_ff)
#define tu_fifo_unlock(_ff)
#endif
bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable)
{
tu_fifo_lock(f);
f->buffer = (uint8_t*) buffer;
f->depth = depth;
f->item_size = item_size;
f->overwritable = overwritable;
f->rd_idx = f->wr_idx = f->count = 0;
tu_fifo_unlock(f);
return true;
}
/******************************************************************************/
/*!
@brief Read one byte out of the RX buffer.
This function will return the byte located at the array index of the
read pointer, and then increment the read pointer index. If the read
pointer exceeds the maximum buffer size, it will roll over to zero.
@param[in] f
Pointer to the FIFO buffer to manipulate
@param[in] p_buffer
Pointer to the place holder for data read from the buffer
@returns TRUE if the queue is not empty
*/
/******************************************************************************/
bool tu_fifo_read(tu_fifo_t* f, void * p_buffer)
{
if( tu_fifo_empty(f) ) return false;
tu_fifo_lock(f);
memcpy(p_buffer,
f->buffer + (f->rd_idx * f->item_size),
f->item_size);
f->rd_idx = (f->rd_idx + 1) % f->depth;
f->count--;
tu_fifo_unlock(f);
return true;
}
/******************************************************************************/
/*!
@brief This function will read n elements into the array index specified by
the write pointer and increment the write index. If the write index
exceeds the max buffer size, then it will roll over to zero.
@param[in] f
Pointer to the FIFO buffer to manipulate
@param[in] p_data
The pointer to data location
@param[in] count
Number of element that buffer can afford
@returns number of items read from the FIFO
*/
/******************************************************************************/
uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count)
{
if( tu_fifo_empty(f) ) return 0;
/* Limit up to fifo's count */
if ( count > f->count ) count = f->count;
/* Could copy up to 2 portions marked as 'x' if queue is wrapped around
* case 1: ....RxxxxW.......
* case 2: xxxxxW....Rxxxxxx
*/
// uint16_t index2upper = tu_min16(count, f->count-f->rd_idx);
uint8_t* p_buf = (uint8_t*) p_buffer;
uint16_t len = 0;
while( (len < count) && tu_fifo_read(f, p_buf) )
{
len++;
p_buf += f->item_size;
}
return len;
}
/******************************************************************************/
/*!
@brief Reads one item without removing it from the FIFO
@param[in] f
Pointer to the FIFO buffer to manipulate
@param[in] pos
Position to read from in the FIFO buffer
@param[in] p_buffer
Pointer to the place holder for data read from the buffer
@returns TRUE if the queue is not empty
*/
/******************************************************************************/
bool tu_fifo_peek_at(tu_fifo_t* f, uint16_t pos, void * p_buffer)
{
if ( pos >= f->count ) return false;
// rd_idx is pos=0
uint16_t index = (f->rd_idx + pos) % f->depth;
memcpy(p_buffer,
f->buffer + (index * f->item_size),
f->item_size);
return true;
}
/******************************************************************************/
/*!
@brief Write one element into the RX buffer.
This function will write one element into the array index specified by
the write pointer and increment the write index. If the write index
exceeds the max buffer size, then it will roll over to zero.
@param[in] f
Pointer to the FIFO buffer to manipulate
@param[in] p_data
The byte to add to the FIFO
@returns TRUE if the data was written to the FIFO (overwrittable
FIFO will always return TRUE)
*/
/******************************************************************************/
bool tu_fifo_write (tu_fifo_t* f, const void * p_data)
{
if ( tu_fifo_full(f) && !f->overwritable ) return false;
tu_fifo_lock(f);
memcpy( f->buffer + (f->wr_idx * f->item_size),
p_data,
f->item_size);
f->wr_idx = (f->wr_idx + 1) % f->depth;
if (tu_fifo_full(f))
{
f->rd_idx = f->wr_idx; // keep the full state (rd == wr && len = size)
}
else
{
f->count++;
}
tu_fifo_unlock(f);
return true;
}
/******************************************************************************/
/*!
@brief This function will write n elements into the array index specified by
the write pointer and increment the write index. If the write index
exceeds the max buffer size, then it will roll over to zero.
@param[in] f
Pointer to the FIFO buffer to manipulate
@param[in] p_data
The pointer to data to add to the FIFO
@param[in] count
Number of element
@return Number of written elements
*/
/******************************************************************************/
uint16_t tu_fifo_write_n (tu_fifo_t* f, const void * p_data, uint16_t count)
{
if ( count == 0 ) return 0;
uint8_t const* p_buf = (uint8_t const*) p_data;
uint16_t len = 0;
while( (len < count) && tu_fifo_write(f, p_buf) )
{
len++;
p_buf += f->item_size;
}
return len;
}
/******************************************************************************/
/*!
@brief Clear the fifo read and write pointers and set length to zero
@param[in] f
Pointer to the FIFO buffer to manipulate
*/
/******************************************************************************/
bool tu_fifo_clear(tu_fifo_t *f)
{
tu_fifo_lock(f);
f->rd_idx = f->wr_idx = f->count = 0;
tu_fifo_unlock(f);
return true;
}

View file

@ -0,0 +1,131 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup Group_Common
* \defgroup group_fifo fifo
* @{ */
#ifndef _TUSB_FIFO_H_
#define _TUSB_FIFO_H_
// mutex is only needed for RTOS
// for OS None, we don't get preempted
#define CFG_FIFO_MUTEX (CFG_TUSB_OS != OPT_OS_NONE)
#include <stdint.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C" {
#endif
#if CFG_FIFO_MUTEX
#define tu_fifo_mutex_t osal_mutex_t
#endif
/** \struct tu_fifo_t
* \brief Simple Circular FIFO
*/
typedef struct
{
uint8_t* buffer ; ///< buffer pointer
uint16_t depth ; ///< max items
uint16_t item_size ; ///< size of each item
bool overwritable ;
volatile uint16_t count ; ///< number of items in queue
volatile uint16_t wr_idx ; ///< write pointer
volatile uint16_t rd_idx ; ///< read pointer
#if CFG_FIFO_MUTEX
tu_fifo_mutex_t mutex;
#endif
} tu_fifo_t;
#define TU_FIFO_DEF(_name, _depth, _type, _overwritable) \
uint8_t _name##_buf[_depth*sizeof(_type)]; \
tu_fifo_t _name = { \
.buffer = _name##_buf, \
.depth = _depth, \
.item_size = sizeof(_type), \
.overwritable = _overwritable, \
}
bool tu_fifo_clear(tu_fifo_t *f);
bool tu_fifo_config(tu_fifo_t *f, void* buffer, uint16_t depth, uint16_t item_size, bool overwritable);
#if CFG_FIFO_MUTEX
static inline void tu_fifo_config_mutex(tu_fifo_t *f, tu_fifo_mutex_t mutex_hdl)
{
f->mutex = mutex_hdl;
}
#endif
bool tu_fifo_write (tu_fifo_t* f, void const * p_data);
uint16_t tu_fifo_write_n (tu_fifo_t* f, void const * p_data, uint16_t count);
bool tu_fifo_read (tu_fifo_t* f, void * p_buffer);
uint16_t tu_fifo_read_n (tu_fifo_t* f, void * p_buffer, uint16_t count);
bool tu_fifo_peek_at (tu_fifo_t* f, uint16_t pos, void * p_buffer);
static inline bool tu_fifo_peek(tu_fifo_t* f, void * p_buffer)
{
return tu_fifo_peek_at(f, 0, p_buffer);
}
static inline bool tu_fifo_empty(tu_fifo_t* f)
{
return (f->count == 0);
}
static inline bool tu_fifo_full(tu_fifo_t* f)
{
return (f->count == f->depth);
}
static inline uint16_t tu_fifo_count(tu_fifo_t* f)
{
return f->count;
}
static inline uint16_t tu_fifo_remaining(tu_fifo_t* f)
{
return f->depth - f->count;
}
static inline uint16_t tu_fifo_depth(tu_fifo_t* f)
{
return f->depth;
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_FIFO_H_ */

View file

@ -0,0 +1,80 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup Group_Common Common Files
* \defgroup Group_TimeoutTimer timeout timer
* @{ */
#ifndef _TUSB_TIMEOUT_H_
#define _TUSB_TIMEOUT_H_
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint32_t start;
uint32_t interval;
}tu_timeout_t;
#if 0
extern uint32_t tusb_hal_millis(void);
static inline void tu_timeout_set(tu_timeout_t* tt, uint32_t msec)
{
tt->interval = msec;
tt->start = tusb_hal_millis();
}
static inline bool tu_timeout_expired(tu_timeout_t* tt)
{
return ( tusb_hal_millis() - tt->start ) >= tt->interval;
}
// For used with periodic event to prevent drift
static inline void tu_timeout_reset(tu_timeout_t* tt)
{
tt->start += tt->interval;
}
static inline void tu_timeout_restart(tu_timeout_t* tt)
{
tt->start = tusb_hal_millis();
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_TIMEOUT_H_ */
/** @} */

View file

@ -0,0 +1,420 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup group_usb_definitions
* \defgroup USBDef_Type USB Types
* @{ */
#ifndef _TUSB_TYPES_H_
#define _TUSB_TYPES_H_
#include <stdbool.h>
#include <stdint.h>
#include "tusb_compiler.h"
#ifdef __cplusplus
extern "C" {
#endif
/*------------------------------------------------------------------*/
/* CONSTANTS
*------------------------------------------------------------------*/
/// defined base on EHCI specs value for Endpoint Speed
typedef enum
{
TUSB_SPEED_FULL = 0,
TUSB_SPEED_LOW ,
TUSB_SPEED_HIGH
}tusb_speed_t;
/// defined base on USB Specs Endpoint's bmAttributes
typedef enum
{
TUSB_XFER_CONTROL = 0 ,
TUSB_XFER_ISOCHRONOUS ,
TUSB_XFER_BULK ,
TUSB_XFER_INTERRUPT
}tusb_xfer_type_t;
typedef enum
{
TUSB_DIR_OUT = 0,
TUSB_DIR_IN = 1,
TUSB_DIR_IN_MASK = 0x80
}tusb_dir_t;
/// USB Descriptor Types (section 9.4 table 9-5)
typedef enum
{
TUSB_DESC_DEVICE = 0x01 ,
TUSB_DESC_CONFIGURATION = 0x02 ,
TUSB_DESC_STRING = 0x03 ,
TUSB_DESC_INTERFACE = 0x04 ,
TUSB_DESC_ENDPOINT = 0x05 ,
TUSB_DESC_DEVICE_QUALIFIER = 0x06 ,
TUSB_DESC_OTHER_SPEED_CONFIG = 0x07 ,
TUSB_DESC_INTERFACE_POWER = 0x08 ,
TUSB_DESC_OTG = 0x09 ,
TUSB_DESC_DEBUG = 0x0A ,
TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B ,
TUSB_DESC_CLASS_SPECIFIC = 0x24
}tusb_desc_type_t;
typedef enum
{
TUSB_REQ_GET_STATUS =0 , ///< 0
TUSB_REQ_CLEAR_FEATURE , ///< 1
TUSB_REQ_RESERVED , ///< 2
TUSB_REQ_SET_FEATURE , ///< 3
TUSB_REQ_RESERVED2 , ///< 4
TUSB_REQ_SET_ADDRESS , ///< 5
TUSB_REQ_GET_DESCRIPTOR , ///< 6
TUSB_REQ_SET_DESCRIPTOR , ///< 7
TUSB_REQ_GET_CONFIGURATION , ///< 8
TUSB_REQ_SET_CONFIGURATION , ///< 9
TUSB_REQ_GET_INTERFACE , ///< 10
TUSB_REQ_SET_INTERFACE , ///< 11
TUSB_REQ_SYNCH_FRAME ///< 12
}tusb_request_code_t;
typedef enum
{
TUSB_REQ_FEATURE_EDPT_HALT = 0,
TUSB_REQ_FEATURE_REMOTE_WAKEUP = 1,
TUSB_REQ_FEATURE_TEST_MODE = 2
}tusb_request_feature_selector_t;
typedef enum
{
TUSB_REQ_TYPE_STANDARD = 0,
TUSB_REQ_TYPE_CLASS,
TUSB_REQ_TYPE_VENDOR
} tusb_request_type_t;
typedef enum
{
TUSB_REQ_RCPT_DEVICE =0,
TUSB_REQ_RCPT_INTERFACE,
TUSB_REQ_RCPT_ENDPOINT,
TUSB_REQ_RCPT_OTHER
} tusb_request_recipient_t;
typedef enum
{
TUSB_CLASS_UNSPECIFIED = 0 ,
TUSB_CLASS_AUDIO = 1 ,
TUSB_CLASS_CDC = 2 ,
TUSB_CLASS_HID = 3 ,
TUSB_CLASS_RESERVED_4 = 4 ,
TUSB_CLASS_PHYSICAL = 5 ,
TUSB_CLASS_IMAGE = 6 ,
TUSB_CLASS_PRINTER = 7 ,
TUSB_CLASS_MSC = 8 ,
TUSB_CLASS_HUB = 9 ,
TUSB_CLASS_CDC_DATA = 10 ,
TUSB_CLASS_SMART_CARD = 11 ,
TUSB_CLASS_RESERVED_12 = 12 ,
TUSB_CLASS_CONTENT_SECURITY = 13 ,
TUSB_CLASS_VIDEO = 14 ,
TUSB_CLASS_PERSONAL_HEALTHCARE = 15 ,
TUSB_CLASS_AUDIO_VIDEO = 16 ,
TUSB_CLASS_DIAGNOSTIC = 0xDC ,
TUSB_CLASS_WIRELESS_CONTROLLER = 0xE0 ,
TUSB_CLASS_MISC = 0xEF ,
TUSB_CLASS_APPLICATION_SPECIFIC = 0xFE ,
TUSB_CLASS_VENDOR_SPECIFIC = 0xFF
}tusb_class_code_t;
typedef enum
{
MISC_SUBCLASS_COMMON = 2
}misc_subclass_type_t;
typedef enum
{
MISC_PROTOCOL_IAD = 1
}misc_protocol_type_t;
enum {
TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = TU_BIT(5),
TUSB_DESC_CONFIG_ATT_SELF_POWERED = TU_BIT(6),
};
#define TUSB_DESC_CONFIG_POWER_MA(x) ((x)/2)
/// Device State
typedef enum
{
TUSB_DEVICE_STATE_UNPLUG = 0 ,
TUSB_DEVICE_STATE_CONFIGURED ,
TUSB_DEVICE_STATE_SUSPENDED ,
}tusb_device_state_t;
typedef enum
{
XFER_RESULT_SUCCESS,
XFER_RESULT_FAILED,
XFER_RESULT_STALLED,
}xfer_result_t;
enum
{
DESC_OFFSET_LEN = 0,
DESC_OFFSET_TYPE = 1
};
enum
{
INTERFACE_INVALID_NUMBER = 0xff
};
//--------------------------------------------------------------------+
// STANDARD DESCRIPTORS
//--------------------------------------------------------------------+
/// USB Standard Device Descriptor (section 9.6.1, table 9-8)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< DEVICE Descriptor Type.
uint16_t bcdUSB ; ///< BUSB Specification Release Number in Binary-Coded Decimal (i.e., 2.10 is 210H). This field identifies the release of the USB Specification with which the device and its descriptors are compliant.
uint8_t bDeviceClass ; ///< Class code (assigned by the USB-IF). \li If this field is reset to zero, each interface within a configuration specifies its own class information and the various interfaces operate independently. \li If this field is set to a value between 1 and FEH, the device supports different class specifications on different interfaces and the interfaces may not operate independently. This value identifies the class definition used for the aggregate interfaces. \li If this field is set to FFH, the device class is vendor-specific.
uint8_t bDeviceSubClass ; ///< Subclass code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass field. \li If the bDeviceClass field is reset to zero, this field must also be reset to zero. \li If the bDeviceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
uint8_t bDeviceProtocol ; ///< Protocol code (assigned by the USB-IF). These codes are qualified by the value of the bDeviceClass and the bDeviceSubClass fields. If a device supports class-specific protocols on a device basis as opposed to an interface basis, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use class-specific protocols on a device basis. However, it may use classspecific protocols on an interface basis. \li If this field is set to FFH, the device uses a vendor-specific protocol on a device basis.
uint8_t bMaxPacketSize0 ; ///< Maximum packet size for endpoint zero (only 8, 16, 32, or 64 are valid). For HS devices is fixed to 64.
uint16_t idVendor ; ///< Vendor ID (assigned by the USB-IF).
uint16_t idProduct ; ///< Product ID (assigned by the manufacturer).
uint16_t bcdDevice ; ///< Device release number in binary-coded decimal.
uint8_t iManufacturer ; ///< Index of string descriptor describing manufacturer.
uint8_t iProduct ; ///< Index of string descriptor describing product.
uint8_t iSerialNumber ; ///< Index of string descriptor describing the device's serial number.
uint8_t bNumConfigurations ; ///< Number of possible configurations.
} tusb_desc_device_t;
/// USB Standard Configuration Descriptor (section 9.6.1 table 9-10) */
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type
uint16_t wTotalLength ; ///< Total length of data returned for this configuration. Includes the combined length of all descriptors (configuration, interface, endpoint, and class- or vendor-specific) returned for this configuration.
uint8_t bNumInterfaces ; ///< Number of interfaces supported by this configuration
uint8_t bConfigurationValue ; ///< Value to use as an argument to the SetConfiguration() request to select this configuration.
uint8_t iConfiguration ; ///< Index of string descriptor describing this configuration
uint8_t bmAttributes ; ///< Configuration characteristics \n D7: Reserved (set to one)\n D6: Self-powered \n D5: Remote Wakeup \n D4...0: Reserved (reset to zero) \n D7 is reserved and must be set to one for historical reasons. \n A device configuration that uses power from the bus and a local source reports a non-zero value in bMaxPower to indicate the amount of bus power required and sets D6. The actual power source at runtime may be determined using the GetStatus(DEVICE) request (see USB 2.0 spec Section 9.4.5). \n If a device configuration supports remote wakeup, D5 is set to one.
uint8_t bMaxPower ; ///< Maximum power consumption of the USB device from the bus in this specific configuration when the device is fully operational. Expressed in 2 mA units (i.e., 50 = 100 mA).
} tusb_desc_configuration_t;
/// USB Standard Interface Descriptor (section 9.6.1 table 9-12)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< INTERFACE Descriptor Type
uint8_t bInterfaceNumber ; ///< Number of this interface. Zero-based value identifying the index in the array of concurrent interfaces supported by this configuration.
uint8_t bAlternateSetting ; ///< Value used to select this alternate setting for the interface identified in the prior field
uint8_t bNumEndpoints ; ///< Number of endpoints used by this interface (excluding endpoint zero). If this value is zero, this interface only uses the Default Control Pipe.
uint8_t bInterfaceClass ; ///< Class code (assigned by the USB-IF). \li A value of zero is reserved for future standardization. \li If this field is set to FFH, the interface class is vendor-specific. \li All other values are reserved for assignment by the USB-IF.
uint8_t bInterfaceSubClass ; ///< Subclass code (assigned by the USB-IF). \n These codes are qualified by the value of the bInterfaceClass field. \li If the bInterfaceClass field is reset to zero, this field must also be reset to zero. \li If the bInterfaceClass field is not set to FFH, all values are reserved for assignment by the USB-IF.
uint8_t bInterfaceProtocol ; ///< Protocol code (assigned by the USB). \n These codes are qualified by the value of the bInterfaceClass and the bInterfaceSubClass fields. If an interface supports class-specific requests, this code identifies the protocols that the device uses as defined by the specification of the device class. \li If this field is reset to zero, the device does not use a class-specific protocol on this interface. \li If this field is set to FFH, the device uses a vendor-specific protocol for this interface.
uint8_t iInterface ; ///< Index of string descriptor describing this interface
} tusb_desc_interface_t;
/// USB Standard Endpoint Descriptor (section 9.6.1 table 9-13)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< ENDPOINT Descriptor Type
uint8_t bEndpointAddress ; ///< The address of the endpoint on the USB device described by this descriptor. The address is encoded as follows: \n Bit 3...0: The endpoint number \n Bit 6...4: Reserved, reset to zero \n Bit 7: Direction, ignored for control endpoints 0 = OUT endpoint 1 = IN endpoint.
struct ATTR_PACKED {
uint8_t xfer : 2;
uint8_t sync : 2;
uint8_t usage : 2;
uint8_t : 2;
} bmAttributes ; ///< This field describes the endpoint's attributes when it is configured using the bConfigurationValue. \n Bits 1..0: Transfer Type \n- 00 = Control \n- 01 = Isochronous \n- 10 = Bulk \n- 11 = Interrupt \n If not an isochronous endpoint, bits 5..2 are reserved and must be set to zero. If isochronous, they are defined as follows: \n Bits 3..2: Synchronization Type \n- 00 = No Synchronization \n- 01 = Asynchronous \n- 10 = Adaptive \n- 11 = Synchronous \n Bits 5..4: Usage Type \n- 00 = Data endpoint \n- 01 = Feedback endpoint \n- 10 = Implicit feedback Data endpoint \n- 11 = Reserved \n Refer to Chapter 5 of USB 2.0 specification for more information. \n All other bits are reserved and must be reset to zero. Reserved bits must be ignored by the host.
struct ATTR_PACKED {
uint16_t size : 11; ///< Maximum packet size this endpoint is capable of sending or receiving when this configuration is selected. \n For isochronous endpoints, this value is used to reserve the bus time in the schedule, required for the per-(micro)frame data payloads. The pipe may, on an ongoing basis, actually use less bandwidth than that reserved. The device reports, if necessary, the actual bandwidth used via its normal, non-USB defined mechanisms. \n For all endpoints, bits 10..0 specify the maximum packet size (in bytes). \n For high-speed isochronous and interrupt endpoints: \n Bits 12..11 specify the number of additional transaction opportunities per microframe: \n- 00 = None (1 transaction per microframe) \n- 01 = 1 additional (2 per microframe) \n- 10 = 2 additional (3 per microframe) \n- 11 = Reserved \n Bits 15..13 are reserved and must be set to zero.
uint16_t hs_period_mult : 2;
uint16_t : 0;
}wMaxPacketSize;
uint8_t bInterval ; ///< Interval for polling endpoint for data transfers. Expressed in frames or microframes depending on the device operating speed (i.e., either 1 millisecond or 125 us units). \n- For full-/high-speed isochronous endpoints, this value must be in the range from 1 to 16. The bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$). \n- For full-/low-speed interrupt endpoints, the value of this field may be from 1 to 255. \n- For high-speed interrupt endpoints, the bInterval value is used as the exponent for a \f$ 2^(bInterval-1) \f$ value; e.g., a bInterval of 4 means a period of 8 (\f$ 2^(4-1) \f$) . This value must be from 1 to 16. \n- For high-speed bulk/control OUT endpoints, the bInterval must specify the maximum NAK rate of the endpoint. A value of 0 indicates the endpoint never NAKs. Other values indicate at most 1 NAK each bInterval number of microframes. This value must be in the range from 0 to 255. \n Refer to Chapter 5 of USB 2.0 specification for more information.
} tusb_desc_endpoint_t;
/// USB Other Speed Configuration Descriptor (section 9.6.1 table 9-11)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
uint16_t wTotalLength ; ///< Total length of data returned
uint8_t bNumInterfaces ; ///< Number of interfaces supported by this speed configuration
uint8_t bConfigurationValue ; ///< Value to use to select configuration
uint8_t IConfiguration ; ///< Index of string descriptor
uint8_t bmAttributes ; ///< Same as Configuration descriptor
uint8_t bMaxPower ; ///< Same as Configuration descriptor
} tusb_desc_other_speed_t;
/// USB Device Qualifier Descriptor (section 9.6.1 table 9-9)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Device Qualifier Type
uint16_t bcdUSB ; ///< USB specification version number (e.g., 0200H for V2.00)
uint8_t bDeviceClass ; ///< Class Code
uint8_t bDeviceSubClass ; ///< SubClass Code
uint8_t bDeviceProtocol ; ///< Protocol Code
uint8_t bMaxPacketSize0 ; ///< Maximum packet size for other speed
uint8_t bNumConfigurations ; ///< Number of Other-speed Configurations
uint8_t bReserved ; ///< Reserved for future use, must be zero
} tusb_desc_device_qualifier_t;
/// USB Interface Association Descriptor (IAD ECN)
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
uint8_t bDescriptorType ; ///< Other_speed_Configuration Type
uint8_t bFirstInterface ; ///< Index of the first associated interface.
uint8_t bInterfaceCount ; ///< Total number of associated interfaces.
uint8_t bFunctionClass ; ///< Interface class ID.
uint8_t bFunctionSubClass ; ///< Interface subclass ID.
uint8_t bFunctionProtocol ; ///< Interface protocol ID.
uint8_t iFunction ; ///< Index of the string descriptor describing the interface association.
} tusb_desc_interface_assoc_t;
/// USB Header Descriptor
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< Descriptor Type
} tusb_desc_header_t;
typedef struct ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< Descriptor Type
uint16_t unicode_string[];
} tusb_desc_string_t;
/*------------------------------------------------------------------*/
/* Types
*------------------------------------------------------------------*/
typedef struct ATTR_PACKED{
union {
struct ATTR_PACKED {
uint8_t recipient : 5; ///< Recipient type tusb_request_recipient_t.
uint8_t type : 2; ///< Request type tusb_request_type_t.
uint8_t direction : 1; ///< Direction type. tusb_dir_t
} bmRequestType_bit;
uint8_t bmRequestType;
};
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} tusb_control_request_t;
TU_VERIFY_STATIC( sizeof(tusb_control_request_t) == 8, "mostly compiler option issue");
// TODO move to somewhere suitable
static inline uint8_t bm_request_type(uint8_t direction, uint8_t type, uint8_t recipient)
{
return ((uint8_t) (direction << 7)) | ((uint8_t) (type << 5)) | (recipient);
}
//--------------------------------------------------------------------+
// Endpoint helper
//--------------------------------------------------------------------+
// Get direction from Endpoint address
static inline tusb_dir_t tu_edpt_dir(uint8_t addr)
{
return (addr & TUSB_DIR_IN_MASK) ? TUSB_DIR_IN : TUSB_DIR_OUT;
}
// Get Endpoint number from address
static inline uint8_t tu_edpt_number(uint8_t addr)
{
return addr & (~TUSB_DIR_IN_MASK);
}
static inline uint8_t tu_edpt_addr(uint8_t num, uint8_t dir)
{
return num | (dir ? TUSB_DIR_IN_MASK : 0);
}
//--------------------------------------------------------------------+
// Descriptor helper
//--------------------------------------------------------------------+
static inline uint8_t const * tu_desc_next(void const* desc)
{
uint8_t const* desc8 = (uint8_t const*) desc;
return desc8 + desc8[DESC_OFFSET_LEN];
}
static inline uint8_t tu_desc_type(void const* desc)
{
return ((uint8_t const*) desc)[DESC_OFFSET_TYPE];
}
static inline uint8_t tu_desc_len(void const* desc)
{
return ((uint8_t const*) desc)[DESC_OFFSET_LEN];
}
// Length of the string descriptors in bytes with slen characters
#define TUD_DESC_STRLEN(_slen) (2*(_slen) + 2)
// Header of string descriptors with len + string type
#define TUD_DESC_STR_HEADER(_slen) ( (uint16_t) ( (TUSB_DESC_STRING << 8 ) | TUD_DESC_STRLEN(_slen)) )
// Convert comma-separated string to descriptor unicode format
#define TUD_DESC_STRCONV( ... ) (const uint16_t[]) { TUD_DESC_STR_HEADER(VA_ARGS_NUM_(__VA_ARGS__)), __VA_ARGS__ }
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_TYPES_H_ */
/** @} */

View file

@ -0,0 +1,174 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef TUSB_VERIFY_H_
#define TUSB_VERIFY_H_
#include <stdbool.h>
#include <stdint.h>
#include "tusb_option.h"
#include "tusb_compiler.h"
/*------------------------------------------------------------------*/
/* This file use an advanced macro technique to mimic the default parameter
* as C++ for the sake of code simplicity. Beware of a headache macro
* manipulation that you are told to stay away.
*
* e.g
*
* - TU_VERIFY( cond ) will return false if cond is false
* - TU_VERIFY( cond, err) will return err instead if cond is false
*------------------------------------------------------------------*/
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TU_VERIFY Helper
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG >= 1
#include <stdio.h>
#define _MESS_ERR(_err) printf("%s: %d: failed, error = %s\n", __func__, __LINE__, tusb_strerr[_err])
#define _MESS_FAILED() printf("%s: %d: failed\n", __func__, __LINE__)
#else
#define _MESS_ERR(_err)
#define _MESS_FAILED()
#endif
// Halt CPU (breakpoint) when hitting error, only apply for Cortex M3, M4, M7
#if defined(__ARM_ARCH_7M__) || defined (__ARM_ARCH_7EM__)
#define TU_BREAKPOINT() \
do {\
volatile uint32_t* ARM_CM_DHCSR = ((volatile uint32_t*) 0xE000EDF0UL); /* Cortex M CoreDebug->DHCSR */ \
if ( (*ARM_CM_DHCSR) & 1UL ) __asm("BKPT #0\n"); /* Only halt mcu if debugger is attached */\
} while(0)
#else
#define TU_BREAKPOINT()
#endif
/*------------------------------------------------------------------*/
/* Macro Generator
*------------------------------------------------------------------*/
// Helper to implement optional parameter for TU_VERIFY Macro family
#define GET_3RD_ARG(arg1, arg2, arg3, ...) arg3
#define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4
/*------------- Generator for TU_VERIFY and TU_VERIFY_HDLR -------------*/
#define TU_VERIFY_DEFINE(_cond, _handler, _ret) do { if ( !(_cond) ) { _handler; return _ret; } } while(0)
/*------------- Generator for TU_VERIFY_ERR and TU_VERIFY_ERR_HDLR -------------*/
#define TU_VERIFY_ERR_DEF2(_error, _handler) \
do { \
uint32_t _err = (uint32_t)(_error); \
if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _err; }\
} while(0)
#define TU_VERIFY_ERR_DEF3(_error, _handler, _ret) \
do { \
uint32_t _err = (uint32_t)(_error); \
if ( 0 != _err ) { _MESS_ERR(_err); _handler; return _ret; }\
} while(0)
/*------------------------------------------------------------------*/
/* TU_VERIFY
* - TU_VERIFY_1ARGS : return false if failed
* - TU_VERIFY_2ARGS : return provided value if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, , false)
#define TU_VERIFY_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, , _ret)
#define TU_VERIFY(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_2ARGS, TU_VERIFY_1ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* TU_VERIFY WITH HANDLER
* - TU_VERIFY_HDLR_2ARGS : execute handler, return false if failed
* - TU_VERIFY_HDLR_3ARGS : execute handler, return provided error if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_HDLR_2ARGS(_cond, _handler) TU_VERIFY_DEFINE(_cond, _handler, false)
#define TU_VERIFY_HDLR_3ARGS(_cond, _handler, _ret) TU_VERIFY_DEFINE(_cond, _handler, _ret)
#define TU_VERIFY_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_HDLR_3ARGS, TU_VERIFY_HDLR_2ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* TU_VERIFY STATUS
* - TU_VERIFY_ERR_1ARGS : return status of condition if failed
* - TU_VERIFY_ERR_2ARGS : return provided status code if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, )
#define TU_VERIFY_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, ,_ret)
#define TU_VERIFY_ERR(...) GET_3RD_ARG(__VA_ARGS__, TU_VERIFY_ERR_2ARGS, TU_VERIFY_ERR_1ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* TU_VERIFY STATUS WITH HANDLER
* - TU_VERIFY_ERR_HDLR_2ARGS : execute handler, return status if failed
* - TU_VERIFY_ERR_HDLR_3ARGS : execute handler, return provided error if failed
*------------------------------------------------------------------*/
#define TU_VERIFY_ERR_HDLR_2ARGS(_error, _handler) TU_VERIFY_ERR_DEF2(_error, _handler)
#define TU_VERIFY_ERR_HDLR_3ARGS(_error, _handler, _ret) TU_VERIFY_ERR_DEF3(_error, _handler, _ret)
#define TU_VERIFY_ERR_HDLR(...) GET_4TH_ARG(__VA_ARGS__, TU_VERIFY_ERR_HDLR_3ARGS, TU_VERIFY_ERR_HDLR_2ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* ASSERT
* basically TU_VERIFY with TU_BREAKPOINT() as handler
* - 1 arg : return false if failed
* - 2 arg : return error if failed
*------------------------------------------------------------------*/
#define ASSERT_1ARGS(_cond) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), false)
#define ASSERT_2ARGS(_cond, _ret) TU_VERIFY_DEFINE(_cond, _MESS_FAILED(); TU_BREAKPOINT(), _ret)
#define TU_ASSERT(...) GET_3RD_ARG(__VA_ARGS__, ASSERT_2ARGS, ASSERT_1ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* ASSERT Error
* basically TU_VERIFY Error with TU_BREAKPOINT() as handler
*------------------------------------------------------------------*/
#define ASERT_ERR_1ARGS(_error) TU_VERIFY_ERR_DEF2(_error, TU_BREAKPOINT())
#define ASERT_ERR_2ARGS(_error, _ret) TU_VERIFY_ERR_DEF3(_error, TU_BREAKPOINT(), _ret)
#define TU_ASSERT_ERR(...) GET_3RD_ARG(__VA_ARGS__, ASERT_ERR_2ARGS, ASERT_ERR_1ARGS)(__VA_ARGS__)
/*------------------------------------------------------------------*/
/* ASSERT HDLR
*------------------------------------------------------------------*/
#ifdef __cplusplus
}
#endif
#endif /* TUSB_VERIFY_H_ */

View file

@ -0,0 +1,140 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup group_usbd
* \defgroup group_dcd Device Controller Driver (DCD)
* @{ */
#ifndef _TUSB_DCD_H_
#define _TUSB_DCD_H_
#include "common/tusb_common.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
DCD_EVENT_BUS_RESET = 1,
DCD_EVENT_UNPLUGGED,
DCD_EVENT_SOF,
DCD_EVENT_SUSPEND,
DCD_EVENT_RESUME,
DCD_EVENT_SETUP_RECEIVED,
DCD_EVENT_XFER_COMPLETE,
// Not an DCD event, just a convenient way to defer ISR function
USBD_EVENT_FUNC_CALL
} dcd_eventid_t;
typedef struct ATTR_ALIGNED(4)
{
uint8_t rhport;
uint8_t event_id;
union {
// USBD_EVT_SETUP_RECEIVED
tusb_control_request_t setup_received;
// USBD_EVT_XFER_COMPLETE
struct {
uint8_t ep_addr;
uint8_t result;
uint32_t len;
}xfer_complete;
// USBD_EVENT_FUNC_CALL
struct {
void (*func) (void*);
void* param;
}func_call;
};
} dcd_event_t;
TU_VERIFY_STATIC(sizeof(dcd_event_t) <= 12, "size is not correct");
/*------------------------------------------------------------------*/
/* Device API
*------------------------------------------------------------------*/
// Initialize controller to device mode
void dcd_init (uint8_t rhport);
// Enable device interrupt
void dcd_int_enable (uint8_t rhport);
// Disable device interrupt
void dcd_int_disable(uint8_t rhport);
// Receive Set Address request, mcu port must also include status IN response
void dcd_set_address(uint8_t rhport, uint8_t dev_addr);
// Receive Set Configure request
void dcd_set_config (uint8_t rhport, uint8_t config_num);
// Wake up host
void dcd_remote_wakeup(uint8_t rhport);
/*------------------------------------------------------------------*/
/* Endpoint API
* - open : Configure endpoint's registers
* - xfer : Submit a transfer. When complete dcd_event_xfer_complete
* must be called to notify the stack
* - busy : Check if endpoint transferring is complete (TODO remove)
* - stall : stall endpoint
* - clear_stall : clear stall
*------------------------------------------------------------------*/
bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc);
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr);
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr);
/*------------------------------------------------------------------*/
/* Event Function
* Called by DCD to notify USBD
*------------------------------------------------------------------*/
void dcd_event_handler(dcd_event_t const * event, bool in_isr);
// helper to send bus signal event
void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr);
// helper to send setup received
void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr);
// helper to send transfer complete event
void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_DCD_H_ */
/// @}

View file

@ -0,0 +1,775 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED
#include "tusb.h"
#include "usbd.h"
#include "device/usbd_pvt.h"
#ifndef CFG_TUD_TASK_QUEUE_SZ
#define CFG_TUD_TASK_QUEUE_SZ 16
#endif
//--------------------------------------------------------------------+
// Device Data
//--------------------------------------------------------------------+
typedef struct {
struct ATTR_PACKED
{
volatile uint8_t connected : 1;
volatile uint8_t configured : 1;
volatile uint8_t suspended : 1;
uint8_t remote_wakeup_en : 1; // enable/disable by host
uint8_t remote_wakeup_support : 1; // configuration descriptor's attribute
uint8_t self_powered : 1; // configuration descriptor's attribute
};
// uint8_t ep_busy_mask[2]; // bit mask for busy endpoint
uint8_t ep_stall_mask[2]; // bit mask for stalled endpoint
uint8_t itf2drv[16]; // map interface number to driver (0xff is invalid)
uint8_t ep2drv[8][2]; // map endpoint to driver ( 0xff is invalid )
}usbd_device_t;
static usbd_device_t _usbd_dev = { 0 };
//--------------------------------------------------------------------+
// Class Driver
//--------------------------------------------------------------------+
typedef struct {
uint8_t class_code;
void (* init ) (void);
bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length);
bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request);
bool (* control_request_complete ) (uint8_t rhport, tusb_control_request_t const * request);
bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t, uint32_t);
void (* sof ) (uint8_t rhport);
void (* reset ) (uint8_t);
} usbd_class_driver_t;
static usbd_class_driver_t const usbd_class_drivers[] =
{
#if CFG_TUD_CDC
{
.class_code = TUSB_CLASS_CDC,
.init = cdcd_init,
.open = cdcd_open,
.control_request = cdcd_control_request,
.control_request_complete = cdcd_control_request_complete,
.xfer_cb = cdcd_xfer_cb,
.sof = NULL,
.reset = cdcd_reset
},
#endif
#if CFG_TUD_MSC
{
.class_code = TUSB_CLASS_MSC,
.init = mscd_init,
.open = mscd_open,
.control_request = mscd_control_request,
.control_request_complete = mscd_control_request_complete,
.xfer_cb = mscd_xfer_cb,
.sof = NULL,
.reset = mscd_reset
},
#endif
#if CFG_TUD_HID
{
.class_code = TUSB_CLASS_HID,
.init = hidd_init,
.open = hidd_open,
.control_request = hidd_control_request,
.control_request_complete = hidd_control_request_complete,
.xfer_cb = hidd_xfer_cb,
.sof = NULL,
.reset = hidd_reset
},
#endif
#if CFG_TUD_MIDI
{
.class_code = TUSB_CLASS_AUDIO,
.init = midid_init,
.open = midid_open,
.control_request = midid_control_request,
.control_request_complete = midid_control_request_complete,
.xfer_cb = midid_xfer_cb,
.sof = NULL,
.reset = midid_reset
},
#endif
#if CFG_TUD_CUSTOM_CLASS
{
.class_code = TUSB_CLASS_VENDOR_SPECIFIC,
.init = cusd_init,
.open = cusd_open,
.control_request = cusd_control_request,
.control_request_complete = cusd_control_request_complete,
.xfer_cb = cusd_xfer_cb,
.sof = NULL,
.reset = cusd_reset
},
#endif
};
enum { USBD_CLASS_DRIVER_COUNT = TU_ARRAY_SZIE(usbd_class_drivers) };
//--------------------------------------------------------------------+
// DCD Event
//--------------------------------------------------------------------+
// Event queue
// OPT_MODE_DEVICE is used by OS NONE for mutex (disable usb isr)
OSAL_QUEUE_DEF(OPT_MODE_DEVICE, _usbd_qdef, CFG_TUD_TASK_QUEUE_SZ, dcd_event_t);
static osal_queue_t _usbd_q;
//--------------------------------------------------------------------+
// Prototypes
//--------------------------------------------------------------------+
static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id);
static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request);
static bool process_set_config(uint8_t rhport);
static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len);
void usbd_control_reset (uint8_t rhport);
bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) );
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
bool tud_mounted(void)
{
return _usbd_dev.configured;
}
bool tud_suspended(void)
{
return _usbd_dev.suspended;
}
bool tud_remote_wakeup(void)
{
// only wake up host if this feature is supported and enabled and we are suspended
TU_VERIFY (_usbd_dev.suspended && _usbd_dev.remote_wakeup_support && _usbd_dev.remote_wakeup_en );
dcd_remote_wakeup(TUD_OPT_RHPORT);
return true;
}
//--------------------------------------------------------------------+
// USBD Task
//--------------------------------------------------------------------+
bool usbd_init (void)
{
tu_varclr(&_usbd_dev);
// Init device queue & task
_usbd_q = osal_queue_create(&_usbd_qdef);
TU_ASSERT(_usbd_q != NULL);
// Init class drivers
for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++) usbd_class_drivers[i].init();
// Init device controller driver
dcd_init(TUD_OPT_RHPORT);
dcd_int_enable(TUD_OPT_RHPORT);
return true;
}
static void usbd_reset(uint8_t rhport)
{
tu_varclr(&_usbd_dev);
memset(_usbd_dev.itf2drv, 0xff, sizeof(_usbd_dev.itf2drv)); // invalid mapping
memset(_usbd_dev.ep2drv , 0xff, sizeof(_usbd_dev.ep2drv )); // invalid mapping
usbd_control_reset(rhport);
for (uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++)
{
if ( usbd_class_drivers[i].reset ) usbd_class_drivers[i].reset( rhport );
}
}
/* USB Device Driver task
* This top level thread manages all device controller event and delegates events to class-specific drivers.
* This should be called periodically within the mainloop or rtos thread.
*
@code
int main(void)
{
application_init();
tusb_init();
while(1) // the mainloop
{
application_code();
tud_task(); // tinyusb device task
}
}
@endcode
*/
void tud_task (void)
{
// Skip if stack is not initialized
if ( !tusb_inited() ) return;
// Loop until there is no more events in the queue
while (1)
{
dcd_event_t event;
if ( !osal_queue_receive(_usbd_q, &event) ) return;
switch ( event.event_id )
{
case DCD_EVENT_BUS_RESET:
usbd_reset(event.rhport);
break;
case DCD_EVENT_UNPLUGGED:
usbd_reset(event.rhport);
// invoke callback
if (tud_umount_cb) tud_umount_cb();
break;
case DCD_EVENT_SETUP_RECEIVED:
// Mark as connected after receiving 1st setup packet.
// But it is easier to set it every time instead of wasting time to check then set
_usbd_dev.connected = 1;
// Process control request
if ( !process_control_request(event.rhport, &event.setup_received) )
{
// Failed -> stall both control endpoint IN and OUT
dcd_edpt_stall(event.rhport, 0);
dcd_edpt_stall(event.rhport, 0 | TUSB_DIR_IN_MASK);
}
break;
case DCD_EVENT_XFER_COMPLETE:
// Only handle xfer callback in ready state
// if (_usbd_dev.connected && !_usbd_dev.suspended)
{
// Invoke the class callback associated with the endpoint address
uint8_t const ep_addr = event.xfer_complete.ep_addr;
if ( 0 == tu_edpt_number(ep_addr) )
{
// control transfer DATA stage callback
usbd_control_xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
}
else
{
uint8_t const drv_id = _usbd_dev.ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)];
TU_ASSERT(drv_id < USBD_CLASS_DRIVER_COUNT,);
usbd_class_drivers[drv_id].xfer_cb(event.rhport, ep_addr, event.xfer_complete.result, event.xfer_complete.len);
}
}
break;
case DCD_EVENT_SUSPEND:
if (tud_suspend_cb) tud_suspend_cb(_usbd_dev.remote_wakeup_en);
break;
case DCD_EVENT_RESUME:
if (tud_resume_cb) tud_resume_cb();
break;
case DCD_EVENT_SOF:
for ( uint8_t i = 0; i < USBD_CLASS_DRIVER_COUNT; i++ )
{
if ( usbd_class_drivers[i].sof )
{
usbd_class_drivers[i].sof(event.rhport);
}
}
break;
case USBD_EVENT_FUNC_CALL:
if ( event.func_call.func ) event.func_call.func(event.func_call.param);
break;
default:
TU_BREAKPOINT();
break;
}
}
}
//--------------------------------------------------------------------+
// Control Request Parser & Handling
//--------------------------------------------------------------------+
// This handles the actual request and its response.
// return false will cause its caller to stall control endpoint
static bool process_control_request(uint8_t rhport, tusb_control_request_t const * p_request)
{
usbd_control_set_complete_callback(NULL);
switch ( p_request->bmRequestType_bit.recipient )
{
//------------- Device Requests e.g in enumeration -------------//
case TUSB_REQ_RCPT_DEVICE:
if ( TUSB_REQ_TYPE_STANDARD != p_request->bmRequestType_bit.type )
{
// Non standard request is not supported
TU_BREAKPOINT();
return false;
}
switch ( p_request->bRequest )
{
case TUSB_REQ_SET_ADDRESS:
// Depending on mcu, status phase could be sent either before or after changing device address
// Therefore DCD must include zero-length status response
dcd_set_address(rhport, (uint8_t) p_request->wValue);
return true; // skip status
break;
case TUSB_REQ_GET_CONFIGURATION:
{
uint8_t cfgnum = _usbd_dev.configured ? 1 : 0;
usbd_control_xfer(rhport, p_request, &cfgnum, 1);
}
break;
case TUSB_REQ_SET_CONFIGURATION:
{
uint8_t const cfg_num = (uint8_t) p_request->wValue;
dcd_set_config(rhport, cfg_num);
_usbd_dev.configured = cfg_num ? 1 : 0;
TU_ASSERT( process_set_config(rhport) );
usbd_control_status(rhport, p_request);
}
break;
case TUSB_REQ_GET_DESCRIPTOR:
{
uint16_t len = 0;
void* buf = (void*) get_descriptor(p_request, &len);
if ( buf == NULL || len == 0 ) return false;
usbd_control_xfer(rhport, p_request, buf, len);
}
break;
case TUSB_REQ_SET_FEATURE:
// Only support remote wakeup for device feature
TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
// Host may enable remote wake up before suspending especially HID device
_usbd_dev.remote_wakeup_en = true;
usbd_control_status(rhport, p_request);
break;
case TUSB_REQ_CLEAR_FEATURE:
// Only support remote wakeup for device feature
TU_VERIFY(TUSB_REQ_FEATURE_REMOTE_WAKEUP == p_request->wValue);
// Host may disable remote wake up after resuming
_usbd_dev.remote_wakeup_en = false;
usbd_control_status(rhport, p_request);
break;
case TUSB_REQ_GET_STATUS:
{
// Device status bit mask
// - Bit 0: Self Powered
// - Bit 1: Remote Wakeup enabled
uint16_t status = (_usbd_dev.self_powered ? 1 : 0) | (_usbd_dev.remote_wakeup_en ? 2 : 0);
usbd_control_xfer(rhport, p_request, &status, 2);
}
break;
// Unknown/Unsupported request
default: TU_BREAKPOINT(); return false;
}
break;
//------------- Class/Interface Specific Request -------------//
case TUSB_REQ_RCPT_INTERFACE:
{
uint8_t const itf = tu_u16_low(p_request->wIndex);
uint8_t const drvid = _usbd_dev.itf2drv[itf];
TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT);
usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_request_complete );
// stall control endpoint if driver return false
return usbd_class_drivers[drvid].control_request(rhport, p_request);
}
break;
//------------- Endpoint Request -------------//
case TUSB_REQ_RCPT_ENDPOINT:
// Non standard request is not supported
TU_VERIFY( TUSB_REQ_TYPE_STANDARD == p_request->bmRequestType_bit.type );
switch ( p_request->bRequest )
{
case TUSB_REQ_GET_STATUS:
{
uint16_t status = usbd_edpt_stalled(rhport, tu_u16_low(p_request->wIndex)) ? 0x0001 : 0x0000;
usbd_control_xfer(rhport, p_request, &status, 2);
}
break;
case TUSB_REQ_CLEAR_FEATURE:
if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue )
{
dcd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex));
}
usbd_control_status(rhport, p_request);
break;
case TUSB_REQ_SET_FEATURE:
if ( TUSB_REQ_FEATURE_EDPT_HALT == p_request->wValue )
{
usbd_edpt_stall(rhport, tu_u16_low(p_request->wIndex));
}
usbd_control_status(rhport, p_request);
break;
// Unknown/Unsupported request
default: TU_BREAKPOINT(); return false;
}
break;
// Unknown recipient
default: TU_BREAKPOINT(); return false;
}
return true;
}
// Process Set Configure Request
// This function parse configuration descriptor & open drivers accordingly
static bool process_set_config(uint8_t rhport)
{
tusb_desc_configuration_t const * desc_cfg = (tusb_desc_configuration_t const *) tud_desc_set.config;
TU_ASSERT(desc_cfg != NULL && desc_cfg->bDescriptorType == TUSB_DESC_CONFIGURATION);
// Parse configuration descriptor
_usbd_dev.remote_wakeup_support = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP) ? 1 : 0;
_usbd_dev.self_powered = (desc_cfg->bmAttributes & TUSB_DESC_CONFIG_ATT_SELF_POWERED) ? 1 : 0;
// Parse interface descriptor
uint8_t const * p_desc = ((uint8_t const*) desc_cfg) + sizeof(tusb_desc_configuration_t);
uint8_t const * desc_end = ((uint8_t const*) desc_cfg) + desc_cfg->wTotalLength;
while( p_desc < desc_end )
{
// Each interface always starts with Interface or Association descriptor
if ( TUSB_DESC_INTERFACE_ASSOCIATION == tu_desc_type(p_desc) )
{
p_desc = tu_desc_next(p_desc); // ignore Interface Association
}else
{
TU_ASSERT( TUSB_DESC_INTERFACE == tu_desc_type(p_desc) );
tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) p_desc;
// Check if class is supported
uint8_t drv_id;
for (drv_id = 0; drv_id < USBD_CLASS_DRIVER_COUNT; drv_id++)
{
if ( usbd_class_drivers[drv_id].class_code == desc_itf->bInterfaceClass ) break;
}
TU_ASSERT( drv_id < USBD_CLASS_DRIVER_COUNT );
// Interface number must not be used already TODO alternate interface
TU_ASSERT( 0xff == _usbd_dev.itf2drv[desc_itf->bInterfaceNumber] );
_usbd_dev.itf2drv[desc_itf->bInterfaceNumber] = drv_id;
uint16_t itf_len=0;
TU_ASSERT( usbd_class_drivers[drv_id].open( rhport, desc_itf, &itf_len ) );
TU_ASSERT( itf_len >= sizeof(tusb_desc_interface_t) );
mark_interface_endpoint(_usbd_dev.ep2drv, p_desc, itf_len, drv_id);
p_desc += itf_len; // next interface
}
}
// invoke callback
if (tud_mount_cb) tud_mount_cb();
return true;
}
// Helper marking endpoint of interface belongs to class driver
static void mark_interface_endpoint(uint8_t ep2drv[8][2], uint8_t const* p_desc, uint16_t desc_len, uint8_t driver_id)
{
uint16_t len = 0;
while( len < desc_len )
{
if ( TUSB_DESC_ENDPOINT == tu_desc_type(p_desc) )
{
uint8_t const ep_addr = ((tusb_desc_endpoint_t const*) p_desc)->bEndpointAddress;
ep2drv[tu_edpt_number(ep_addr)][tu_edpt_dir(ep_addr)] = driver_id;
}
len += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
}
}
// return descriptor's buffer and update desc_len
static void const* get_descriptor(tusb_control_request_t const * p_request, uint16_t* desc_len)
{
tusb_desc_type_t const desc_type = (tusb_desc_type_t) tu_u16_high(p_request->wValue);
uint8_t const desc_index = tu_u16_low( p_request->wValue );
uint8_t const * desc_data = NULL;
uint16_t len = 0;
*desc_len = 0;
switch(desc_type)
{
case TUSB_DESC_DEVICE:
desc_data = (uint8_t const *) tud_desc_set.device;
len = sizeof(tusb_desc_device_t);
break;
case TUSB_DESC_CONFIGURATION:
desc_data = (uint8_t const *) tud_desc_set.config;
len = ((tusb_desc_configuration_t const*) desc_data)->wTotalLength;
break;
case TUSB_DESC_STRING:
// String Descriptor always uses the desc set from user
if ( desc_index < tud_desc_set.string_count )
{
desc_data = tud_desc_set.string_arr[desc_index];
TU_VERIFY( desc_data != NULL, NULL );
len = desc_data[0]; // first byte of descriptor is its size
}else
{
// out of range
// The 0xEE index string is a Microsoft USB extension.
// It can be used to tell Windows what driver it should use for the device !!!
return NULL;
}
break;
case TUSB_DESC_DEVICE_QUALIFIER:
// TODO If not highspeed capable stall this request otherwise
// return the descriptor that could work in highspeed
return NULL;
break;
default: return NULL;
}
*desc_len = len;
return desc_data;
}
//--------------------------------------------------------------------+
// DCD Event Handler
//--------------------------------------------------------------------+
void dcd_event_handler(dcd_event_t const * event, bool in_isr)
{
switch (event->event_id)
{
case DCD_EVENT_BUS_RESET:
osal_queue_send(_usbd_q, event, in_isr);
break;
case DCD_EVENT_UNPLUGGED:
_usbd_dev.connected = 0;
_usbd_dev.configured = 0;
_usbd_dev.suspended = 0;
osal_queue_send(_usbd_q, event, in_isr);
break;
case DCD_EVENT_SOF:
// nothing to do now
break;
case DCD_EVENT_SUSPEND:
// NOTE: When plugging/unplugging device, the D+/D- state are unstable and can accidentally meet the
// SUSPEND condition ( Idle for 3ms ). Some MCUs such as samd don't distinguish suspend vs disconnect as well.
// We will skip handling SUSPEND/RESUME event if not currently connected
if ( _usbd_dev.connected )
{
_usbd_dev.suspended = 1;
osal_queue_send(_usbd_q, event, in_isr);
}
break;
case DCD_EVENT_RESUME:
if ( _usbd_dev.connected )
{
_usbd_dev.suspended = 0;
osal_queue_send(_usbd_q, event, in_isr);
}
break;
case DCD_EVENT_SETUP_RECEIVED:
osal_queue_send(_usbd_q, event, in_isr);
break;
case DCD_EVENT_XFER_COMPLETE:
// skip zero-length control status complete event, should dcd notifies us.
if ( (0 == tu_edpt_number(event->xfer_complete.ep_addr)) && (event->xfer_complete.len == 0) ) break;
osal_queue_send(_usbd_q, event, in_isr);
TU_ASSERT(event->xfer_complete.result == XFER_RESULT_SUCCESS,);
break;
// Not an DCD event, just a convenient way to defer ISR function should we need to
case USBD_EVENT_FUNC_CALL:
osal_queue_send(_usbd_q, event, in_isr);
break;
default: break;
}
}
// helper to send bus signal event
void dcd_event_bus_signal (uint8_t rhport, dcd_eventid_t eid, bool in_isr)
{
dcd_event_t event = { .rhport = rhport, .event_id = eid, };
dcd_event_handler(&event, in_isr);
}
// helper to send setup received
void dcd_event_setup_received(uint8_t rhport, uint8_t const * setup, bool in_isr)
{
dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_SETUP_RECEIVED };
memcpy(&event.setup_received, setup, 8);
dcd_event_handler(&event, in_isr);
}
// helper to send transfer complete event
void dcd_event_xfer_complete (uint8_t rhport, uint8_t ep_addr, uint32_t xferred_bytes, uint8_t result, bool in_isr)
{
dcd_event_t event = { .rhport = rhport, .event_id = DCD_EVENT_XFER_COMPLETE };
event.xfer_complete.ep_addr = ep_addr;
event.xfer_complete.len = xferred_bytes;
event.xfer_complete.result = result;
dcd_event_handler(&event, in_isr);
}
//--------------------------------------------------------------------+
// Helper
//--------------------------------------------------------------------+
// Helper to parse an pair of endpoint descriptors (IN & OUT)
bool usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* ep_desc, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in)
{
for(int i=0; i<2; i++)
{
TU_ASSERT(TUSB_DESC_ENDPOINT == ep_desc->bDescriptorType &&
xfer_type == ep_desc->bmAttributes.xfer );
TU_ASSERT(dcd_edpt_open(rhport, ep_desc));
if ( tu_edpt_dir(ep_desc->bEndpointAddress) == TUSB_DIR_IN )
{
(*ep_in) = ep_desc->bEndpointAddress;
}else
{
(*ep_out) = ep_desc->bEndpointAddress;
}
ep_desc = (tusb_desc_endpoint_t const *) tu_desc_next(ep_desc);
}
return true;
}
// Helper to defer an isr function
void usbd_defer_func(osal_task_func_t func, void* param, bool in_isr)
{
dcd_event_t event =
{
.rhport = 0,
.event_id = USBD_EVENT_FUNC_CALL,
};
event.func_call.func = func;
event.func_call.param = param;
dcd_event_handler(&event, in_isr);
}
//--------------------------------------------------------------------+
// USBD Endpoint API
//--------------------------------------------------------------------+
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_stall(rhport, ep_addr);
_usbd_dev.ep_stall_mask[dir] = tu_bit_set(_usbd_dev.ep_stall_mask[dir], epnum);
}
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr)
{
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
dcd_edpt_clear_stall(rhport, ep_addr);
_usbd_dev.ep_stall_mask[dir] = tu_bit_clear(_usbd_dev.ep_stall_mask[dir], epnum);
}
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
return tu_bit_test(_usbd_dev.ep_stall_mask[dir], epnum);
}
#endif

View file

@ -0,0 +1,167 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
/** \ingroup group_usbd
* @{ */
#ifndef _TUSB_USBD_H_
#define _TUSB_USBD_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "common/tusb_common.h"
#include "device/dcd.h"
/// \brief Descriptor pointer collector to all the needed.
typedef struct {
void const * device; ///< pointer to device descriptor \ref tusb_desc_device_t
void const * config; ///< pointer to the whole configuration descriptor, starting by \ref tusb_desc_configuration_t
uint8_t const** string_arr; ///< a array of pointers to string descriptors
uint16_t string_count;
uint8_t const* hid_report;
}tud_desc_set_t;
// Descriptor collection set, must be defined by application
extern tud_desc_set_t tud_desc_set;
//--------------------------------------------------------------------+
// Application API
//--------------------------------------------------------------------+
// Task function should be called in main/rtos loop
void tud_task (void);
// Check if device is connected and configured
bool tud_mounted(void);
// Check if device is suspended
bool tud_suspended(void);
// Check if device is ready to transfer
static inline bool tud_ready(void)
{
return tud_mounted() && !tud_suspended();
}
// Remote wake up host, only if suspended and enabled by host
bool tud_remote_wakeup(void);
//--------------------------------------------------------------------+
// Application Callbacks (WEAK is optional)
//--------------------------------------------------------------------+
// Invoked when device is mounted (configured)
ATTR_WEAK void tud_mount_cb(void);
// Invoked when device is unmounted
ATTR_WEAK void tud_umount_cb(void);
// Invoked when usb bus is suspended
// Within 7ms, device must draw an average of current less than 2.5 mA from bus
ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en);
// Invoked when usb bus is resumed
ATTR_WEAK void tud_resume_cb(void);
//--------------------------------------------------------------------+
// Interface Descriptor Template
//--------------------------------------------------------------------+
#define TUD_CONFIG_DESC_LEN (9)
// Inteface count, string index, total length, attribute, power in mA
#define TUD_CONFIG_DESCRIPTOR(_itfcount, _stridx, _total_len, _attribute, _power_ma) \
9, TUSB_DESC_CONFIGURATION, U16_TO_U8S_LE(_total_len), _itfcount, 1, _stridx, TU_BIT(7) | _attribute, (_power_ma)/2
//------------- CDC -------------//
// Length of template descriptor: 66 bytes
#define TUD_CDC_DESC_LEN (8+9+5+5+4+5+7+9+7+7)
// CDC Descriptor Template
// interface number, string index, EP notification address and size, EP data address (out,in) and size.
#define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \
/* Interface Associate */\
8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\
/* CDC Control Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, _stridx,\
/* CDC Header */\
5, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\
/* CDC Call */\
5, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (_itfnum) + 1,\
/* CDC ACM: support line request */\
4, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\
/* CDC Union */\
5, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_UNION, _itfnum, (_itfnum) + 1,\
/* Endpoint Notification */\
7, TUSB_DESC_ENDPOINT, _ep_notif, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_ep_notif_size), 16,\
/* CDC Data Interface */\
9, TUSB_DESC_INTERFACE, (_itfnum)+1, 0, 2, TUSB_CLASS_CDC_DATA, 0, 0, 0,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- MSC -------------//
// Length of template descriptor: 23 bytes
#define TUD_MSC_DESC_LEN (9 + 7 + 7)
// Interface number, string index, EP Out & EP In address, EP size
#define TUD_MSC_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
/* Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_MSC, MSC_SUBCLASS_SCSI, MSC_PROTOCOL_BOT, _stridx,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
//------------- HID -------------//
// Length of template descriptor: 25 bytes
#define TUD_HID_DESC_LEN (9 + 9 + 7)
// Interface number, string index, protocol, report descriptor len, EP In address, size & polling interval
#define TUD_HID_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epsize, _ep_interval) \
/* Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 1, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\
/* HID descriptor */\
9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\
/* Endpoint descriptor */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_USBD_H_ */
/** @} */

View file

@ -0,0 +1,156 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED
#include "tusb.h"
#include "device/usbd_pvt.h"
enum
{
EDPT_CTRL_OUT = 0x00,
EDPT_CTRL_IN = 0x80
};
typedef struct
{
tusb_control_request_t request;
void* buffer;
uint16_t total_len;
uint16_t total_transferred;
bool (*complete_cb) (uint8_t, tusb_control_request_t const *);
} usbd_control_xfer_t;
static usbd_control_xfer_t _control_state;
CFG_TUSB_MEM_SECTION CFG_TUSB_MEM_ALIGN uint8_t _usbd_ctrl_buf[CFG_TUD_ENDOINT0_SIZE];
void usbd_control_reset (uint8_t rhport)
{
(void) rhport;
tu_varclr(&_control_state);
}
bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request)
{
// status direction is reversed to one in the setup packet
return dcd_edpt_xfer(rhport, request->bmRequestType_bit.direction ? EDPT_CTRL_OUT : EDPT_CTRL_IN, NULL, 0);
}
// Each transaction is up to endpoint0's max packet size
static bool start_control_data_xact(uint8_t rhport)
{
uint16_t const xact_len = tu_min16(_control_state.total_len - _control_state.total_transferred, CFG_TUD_ENDOINT0_SIZE);
uint8_t ep_addr = EDPT_CTRL_OUT;
if ( _control_state.request.bmRequestType_bit.direction == TUSB_DIR_IN )
{
ep_addr = EDPT_CTRL_IN;
memcpy(_usbd_ctrl_buf, _control_state.buffer, xact_len);
}
return dcd_edpt_xfer(rhport, ep_addr, _usbd_ctrl_buf, xact_len);
}
// TODO may find a better way
void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_request_t const * ) )
{
_control_state.complete_cb = fp;
}
bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len)
{
_control_state.request = (*request);
_control_state.buffer = buffer;
_control_state.total_len = tu_min16(len, request->wLength);
_control_state.total_transferred = 0;
if ( buffer != NULL && len )
{
// Data stage
TU_ASSERT( start_control_data_xact(rhport) );
}else
{
// Status stage
TU_ASSERT( usbd_control_status(rhport, request) );
}
return true;
}
// callback when a transaction complete on DATA stage of control endpoint
bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes)
{
(void) result;
(void) ep_addr;
if ( _control_state.request.bmRequestType_bit.direction == TUSB_DIR_OUT )
{
TU_VERIFY(_control_state.buffer);
memcpy(_control_state.buffer, _usbd_ctrl_buf, xferred_bytes);
}
_control_state.total_transferred += xferred_bytes;
_control_state.buffer += xferred_bytes;
if ( _control_state.total_len == _control_state.total_transferred || xferred_bytes < CFG_TUD_ENDOINT0_SIZE )
{
// DATA stage is complete
bool is_ok = true;
// invoke complete callback if set
// callback can still stall control in status phase e.g out data does not make sense
if ( _control_state.complete_cb )
{
is_ok = _control_state.complete_cb(rhport, &_control_state.request);
}
if ( is_ok )
{
// Send status
TU_ASSERT( usbd_control_status(rhport, &_control_state.request) );
}else
{
// Stall both IN and OUT control endpoint
dcd_edpt_stall(rhport, EDPT_CTRL_OUT);
dcd_edpt_stall(rhport, EDPT_CTRL_IN);
}
}
else
{
// More data to transfer
TU_ASSERT( start_control_data_xact(rhport) );
}
return true;
}
#endif

View file

@ -0,0 +1,66 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef USBD_PVT_H_
#define USBD_PVT_H_
#include "osal/osal.h"
#include "common/tusb_fifo.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// INTERNAL API for stack management
//--------------------------------------------------------------------+
bool usbd_init (void);
// Carry out Data and Status stage of control transfer
// - If len = 0, it is equivalent to sending status only
// - If len > wLength : it will be truncated
bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len);
// Send STATUS (zero length) packet
bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request);
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr);
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr);
bool usbd_edpt_stalled(uint8_t rhport, uint8_t ep_addr);
/*------------------------------------------------------------------*/
/* Helper
*------------------------------------------------------------------*/
// helper to parse an pair of In and Out endpoint descriptors. They must be consecutive
bool usbd_open_edpt_pair(uint8_t rhport, tusb_desc_endpoint_t const* p_desc_ep, uint8_t xfer_type, uint8_t* ep_out, uint8_t* ep_in);
void usbd_defer_func( osal_task_func_t func, void* param, bool in_isr );
#ifdef __cplusplus
}
#endif
#endif /* USBD_PVT_H_ */

View file

@ -0,0 +1,108 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_OSAL_H_
#define _TUSB_OSAL_H_
#ifdef __cplusplus
extern "C" {
#endif
/** \addtogroup group_osal
* @{ */
#include "common/tusb_common.h"
enum
{
OSAL_TIMEOUT_NOTIMEOUT = 0, // return immediately
OSAL_TIMEOUT_NORMAL = 10, // default timeout
OSAL_TIMEOUT_WAIT_FOREVER = 0xFFFFFFFFUL
};
#define OSAL_TIMEOUT_CONTROL_XFER OSAL_TIMEOUT_WAIT_FOREVER
typedef void (*osal_task_func_t)( void * );
//--------------------------------------------------------------------+
// OSAL Porting API
//--------------------------------------------------------------------+
#if 0
void osal_task_delay(uint32_t msec);
//------------- Semaphore -------------//
osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef);
bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr);
bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec);
void osal_semaphore_reset(osal_semaphore_t sem_hdl); // TODO removed
//------------- Mutex -------------//
osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef);
bool osal_mutex_lock (osal_mutex_t sem_hdl, uint32_t msec);
bool osal_mutex_unlock(osal_mutex_t mutex_hdl);
//------------- Queue -------------//
osal_queue_t osal_queue_create(osal_queue_def_t* qdef);
bool osal_queue_receive(osal_queue_t const qhdl, void* data);
bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr);
#endif
#if CFG_TUSB_OS == OPT_OS_NONE
#include "osal_none.h"
#else
#if CFG_TUSB_OS == OPT_OS_FREERTOS
#include "osal_freertos.h"
#elif CFG_TUSB_OS == OPT_OS_MYNEWT
#include "osal_mynewt.h"
#else
#error CFG_TUSB_OS is not defined or OS is not supported yet
#endif
// 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
//------------- Sub Task Assert -------------//
#define STASK_ASSERT_ERR(_err) TU_VERIFY_ERR(_err)
#define STASK_ASSERT_ERR_HDLR(_err, _func) TU_VERIFY_ERR_HDLR(_err, _func)
#define STASK_ASSERT(_cond) TU_VERIFY(_cond, TUSB_ERROR_OSAL_TASK_FAILED)
#define STASK_ASSERT_HDLR(_cond, _func) TU_VERIFY_HDLR(_cond, _func)
#endif
#ifdef __cplusplus
}
#endif
/** @} */
#endif /* _TUSB_OSAL_H_ */

View file

@ -0,0 +1,135 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_OSAL_FREERTOS_H_
#define _TUSB_OSAL_FREERTOS_H_
// FreeRTOS Headers
#include "FreeRTOS.h"
#include "semphr.h"
#include "queue.h"
#include "task.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
vTaskDelay( pdMS_TO_TICKS(msec) );
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef StaticSemaphore_t osal_semaphore_def_t;
typedef SemaphoreHandle_t osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
return xSemaphoreCreateBinaryStatic(semdef);
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
return in_isr ? xSemaphoreGiveFromISR(sem_hdl, NULL) : xSemaphoreGive(sem_hdl);
}
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? portMAX_DELAY : pdMS_TO_TICKS(msec);
return xSemaphoreTake(sem_hdl, ticks);
}
static inline void osal_semaphore_reset(osal_semaphore_t const sem_hdl)
{
xQueueReset(sem_hdl);
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef StaticSemaphore_t osal_mutex_def_t;
typedef SemaphoreHandle_t osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
return xSemaphoreCreateMutexStatic(mdef);
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return osal_semaphore_wait(mutex_hdl, msec);
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return xSemaphoreGive(mutex_hdl);
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \
static _type _name##_##buf[_depth];\
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf };
typedef struct
{
uint16_t depth;
uint16_t item_sz;
void* buf;
StaticQueue_t sq;
}osal_queue_def_t;
typedef QueueHandle_t osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
return xQueueCreateStatic(qdef->depth, qdef->item_sz, (uint8_t*) qdef->buf, &qdef->sq);
}
static inline bool osal_queue_receive(osal_queue_t const queue_hdl, void* data)
{
return xQueueReceive(queue_hdl, data, portMAX_DELAY);
}
static inline bool osal_queue_send(osal_queue_t const queue_hdl, void const * data, bool in_isr)
{
return in_isr ? xQueueSendToBackFromISR(queue_hdl, data, NULL) : xQueueSendToBack(queue_hdl, data, OSAL_TIMEOUT_WAIT_FOREVER);
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_FREERTOS_H_ */

View file

@ -0,0 +1,168 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef OSAL_MYNEWT_H_
#define OSAL_MYNEWT_H_
#include "os/os.h"
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
os_time_delay( os_time_ms_to_ticks32(msec) );
}
//--------------------------------------------------------------------+
// Semaphore API
//--------------------------------------------------------------------+
typedef struct os_sem osal_semaphore_def_t;
typedef struct os_sem* osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
return (os_sem_init(semdef, 0) == OS_OK) ? (osal_semaphore_t) semdef : NULL;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
(void) in_isr;
return os_sem_release(sem_hdl) == OS_OK;
}
static inline bool osal_semaphore_wait(osal_semaphore_t sem_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? OS_TIMEOUT_NEVER : os_time_ms_to_ticks32(msec);
return os_sem_pend(sem_hdl, ticks) == OS_OK;
}
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
{
// TODO implement later
}
//--------------------------------------------------------------------+
// MUTEX API (priority inheritance)
//--------------------------------------------------------------------+
typedef struct os_mutex osal_mutex_def_t;
typedef struct os_mutex* osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
return (os_mutex_init(mdef) == OS_OK) ? (osal_mutex_t) mdef : NULL;
}
static inline bool osal_mutex_lock(osal_mutex_t mutex_hdl, uint32_t msec)
{
uint32_t const ticks = (msec == OSAL_TIMEOUT_WAIT_FOREVER) ? OS_TIMEOUT_NEVER : os_time_ms_to_ticks32(msec);
return os_mutex_pend(mutex_hdl, ticks) == OS_OK;
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return os_mutex_release(mutex_hdl) == OS_OK;
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \
static _type _name##_##buf[_depth];\
static struct os_event* _name##_##evbuf[_depth];\
osal_queue_def_t _name = { .depth = _depth, .item_sz = sizeof(_type), .buf = _name##_##buf, .evbuf = _name##_##evbuf};\
typedef struct
{
uint16_t depth;
uint16_t item_sz;
void* buf;
void* evbuf;
struct os_mempool mpool;
struct os_mempool epool;
struct os_eventq evq;
}osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
if ( OS_OK != os_mempool_init(&qdef->mpool, qdef->depth, qdef->item_sz, qdef->buf, "usbd queue") ) return NULL;
if ( OS_OK != os_mempool_init(&qdef->epool, qdef->depth, sizeof(struct os_event), qdef->evbuf, "usbd evqueue") ) return NULL;
os_eventq_init(&qdef->evq);
return (osal_queue_t) qdef;
}
static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data)
{
struct os_event* ev;
ev = os_eventq_get(&qhdl->evq);
memcpy(data, ev->ev_arg, qhdl->item_sz); // copy message
os_memblock_put(&qhdl->mpool, ev->ev_arg); // put back mem block
os_memblock_put(&qhdl->epool, ev); // put back ev block
return true;
}
static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr)
{
(void) in_isr;
// get a block from mem pool for data
void* ptr = os_memblock_get(&qhdl->mpool);
if (!ptr) return false;
memcpy(ptr, data, qhdl->item_sz);
// get a block from event pool to put into queue
struct os_event* ev = (struct os_event*) os_memblock_get(&qhdl->epool);
if (!ev)
{
os_memblock_put(&qhdl->mpool, ptr);
return false;
}
tu_memclr(ev, sizeof(struct os_event));
ev->ev_arg = ptr;
os_eventq_put(&qhdl->evq, ev);
return true;
}
#ifdef __cplusplus
}
#endif
#endif /* OSAL_MYNEWT_H_ */

View file

@ -0,0 +1,204 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_OSAL_NONE_H_
#define _TUSB_OSAL_NONE_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// TASK API
//--------------------------------------------------------------------+
static inline void osal_task_delay(uint32_t msec)
{
(void) msec;
// TODO only used by Host stack, will implement using SOF
// uint32_t start = tusb_hal_millis();
// while ( ( tusb_hal_millis() - start ) < msec ) {}
}
//--------------------------------------------------------------------+
// Binary Semaphore API
//--------------------------------------------------------------------+
typedef struct
{
volatile uint16_t count;
}osal_semaphore_def_t;
typedef osal_semaphore_def_t* osal_semaphore_t;
static inline osal_semaphore_t osal_semaphore_create(osal_semaphore_def_t* semdef)
{
semdef->count = 0;
return semdef;
}
static inline bool osal_semaphore_post(osal_semaphore_t sem_hdl, bool in_isr)
{
(void) in_isr;
sem_hdl->count++;
return true;
}
// TODO blocking for now
static inline bool osal_semaphore_wait (osal_semaphore_t sem_hdl, uint32_t msec)
{
(void) msec;
while (sem_hdl->count == 0) { }
sem_hdl->count--;
return true;
}
static inline void osal_semaphore_reset(osal_semaphore_t sem_hdl)
{
sem_hdl->count = 0;
}
//--------------------------------------------------------------------+
// MUTEX API
// Within tinyusb, mutex is never used in ISR context
//--------------------------------------------------------------------+
typedef osal_semaphore_def_t osal_mutex_def_t;
typedef osal_semaphore_t osal_mutex_t;
static inline osal_mutex_t osal_mutex_create(osal_mutex_def_t* mdef)
{
mdef->count = 1;
return mdef;
}
static inline bool osal_mutex_lock (osal_mutex_t mutex_hdl, uint32_t msec)
{
return osal_semaphore_wait(mutex_hdl, msec);
}
static inline bool osal_mutex_unlock(osal_mutex_t mutex_hdl)
{
return osal_semaphore_post(mutex_hdl, false);
}
//--------------------------------------------------------------------+
// QUEUE API
//--------------------------------------------------------------------+
#include "common/tusb_fifo.h"
// extern to avoid including dcd.h and hcd.h
#if TUSB_OPT_DEVICE_ENABLED
extern void dcd_int_disable(uint8_t rhport);
extern void dcd_int_enable(uint8_t rhport);
#endif
#if TUSB_OPT_HOST_ENABLED
extern void hcd_int_disable(uint8_t rhport);
extern void hcd_int_enable(uint8_t rhport);
#endif
typedef struct
{
uint8_t role; // device or host
tu_fifo_t ff;
}osal_queue_def_t;
typedef osal_queue_def_t* osal_queue_t;
// role device/host is used by OS NONE for mutex (disable usb isr) only
#define OSAL_QUEUE_DEF(_role, _name, _depth, _type) \
uint8_t _name##_buf[_depth*sizeof(_type)]; \
osal_queue_def_t _name = { \
.role = _role, \
.ff = { \
.buffer = _name##_buf, \
.depth = _depth, \
.item_size = sizeof(_type), \
.overwritable = false, \
}\
}
// lock queue by disable usb isr
static inline void _osal_q_lock(osal_queue_t qhdl)
{
#if TUSB_OPT_DEVICE_ENABLED
if (qhdl->role == OPT_MODE_DEVICE) dcd_int_disable(TUD_OPT_RHPORT);
#endif
#if TUSB_OPT_HOST_ENABLED
if (qhdl->role == OPT_MODE_HOST) hcd_int_disable(TUH_OPT_RHPORT);
#endif
}
// unlock queue
static inline void _osal_q_unlock(osal_queue_t qhdl)
{
#if TUSB_OPT_DEVICE_ENABLED
if (qhdl->role == OPT_MODE_DEVICE) dcd_int_enable(TUD_OPT_RHPORT);
#endif
#if TUSB_OPT_HOST_ENABLED
if (qhdl->role == OPT_MODE_HOST) hcd_int_enable(TUH_OPT_RHPORT);
#endif
}
static inline osal_queue_t osal_queue_create(osal_queue_def_t* qdef)
{
tu_fifo_clear(&qdef->ff);
return (osal_queue_t) qdef;
}
// non blocking
static inline bool osal_queue_receive(osal_queue_t const qhdl, void* data)
{
_osal_q_lock(qhdl);
bool success = tu_fifo_read(&qhdl->ff, data);
_osal_q_unlock(qhdl);
return success;
}
static inline bool osal_queue_send(osal_queue_t const qhdl, void const * data, bool in_isr)
{
if (!in_isr) {
_osal_q_lock(qhdl);
}
bool success = tu_fifo_write(&qhdl->ff, data);
if (!in_isr) {
_osal_q_unlock(qhdl);
}
return success;
}
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_OSAL_NONE_H_ */

View file

@ -0,0 +1,356 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Shawcroft 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.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD21
#include "device/dcd.h"
#include "sam.h"
/*------------------------------------------------------------------*/
/* MACRO TYPEDEF CONSTANT ENUM
*------------------------------------------------------------------*/
static ATTR_ALIGNED(4) UsbDeviceDescBank sram_registers[8][2];
static ATTR_ALIGNED(4) uint8_t _setup_packet[8];
// Setup the control endpoint 0.
static void bus_reset(void)
{
// Max size of packets is 64 bytes.
UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT];
bank_out->PCKSIZE.bit.SIZE = 0x3;
UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN];
bank_in->PCKSIZE.bit.SIZE = 0x3;
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0];
ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1);
ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP;
// Prepare for setup packet
dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet));
}
/*------------------------------------------------------------------*/
/* Controller API
*------------------------------------------------------------------*/
void dcd_init (uint8_t rhport)
{
(void) rhport;
// Reset to get in a clean state.
USB->DEVICE.CTRLA.bit.SWRST = true;
while (USB->DEVICE.SYNCBUSY.bit.SWRST == 0) {}
while (USB->DEVICE.SYNCBUSY.bit.SWRST == 1) {}
USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos;
USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos;
USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos;
USB->DEVICE.QOSCTRL.bit.CQOS = USB_QOSCTRL_CQOS_HIGH_Val;
USB->DEVICE.QOSCTRL.bit.DQOS = USB_QOSCTRL_DQOS_HIGH_Val;
// Configure registers
USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers;
USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS;
USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE | USB_CTRLA_RUNSTDBY;
while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {}
USB->DEVICE.INTFLAG.reg |= USB->DEVICE.INTFLAG.reg; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST;
}
void dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB_IRQn);
}
void dcd_int_disable(uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB_IRQn);
}
void dcd_set_address (uint8_t rhport, uint8_t dev_addr)
{
// Response with status first before changing device address
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
// Wait for EP0 to finish before switching the address.
while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {}
USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN;
// Enable SUSPEND interrupt since the bus signal D+/D- are stable now.
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_SUSPEND; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SUSPEND;
}
void dcd_set_config (uint8_t rhport, uint8_t config_num)
{
(void) rhport;
(void) config_num;
// Nothing to do
}
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
USB->DEVICE.CTRLB.bit.UPRSM = 1;
}
/*------------------------------------------------------------------*/
/* DCD Endpoint port
*------------------------------------------------------------------*/
bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
UsbDeviceDescBank* bank = &sram_registers[epnum][dir];
uint32_t size_value = 0;
while (size_value < 7) {
if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) {
break;
}
size_value++;
}
// unsupported endpoint size
if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false;
bank->PCKSIZE.bit.SIZE = size_value;
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if ( dir == TUSB_DIR_OUT )
{
ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1;
ep->EPINTENSET.bit.TRCPT0 = true;
}else
{
ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1;
ep->EPINTENSET.bit.TRCPT1 = true;
}
return true;
}
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
UsbDeviceDescBank* bank = &sram_registers[epnum][dir];
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
// A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid
// buffer for the control endpoint.
if (epnum == 0 && dir == 0 && buffer == NULL) {
buffer = _setup_packet;
}
bank->ADDR.reg = (uint32_t) buffer;
if ( dir == TUSB_DIR_OUT )
{
bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes;
bank->PCKSIZE.bit.BYTE_COUNT = 0;
ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY;
ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0;
} else
{
bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0;
bank->PCKSIZE.bit.BYTE_COUNT = total_bytes;
// bank->PCKSIZE.bit.AUTO_ZLP = 1;
ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY;
ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1;
}
return true;
}
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1;
} else {
ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0;
}
}
void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1;
} else {
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0;
}
}
bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
// USBD shouldn't check control endpoint state
if ( 0 == ep_addr ) return false;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1;
}
return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1;
}
/*------------------------------------------------------------------*/
static bool maybe_handle_setup_packet(void) {
if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP)
{
USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP;
// This copies the data elsewhere so we can reuse the buffer.
dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true);
return true;
}
return false;
}
void maybe_transfer_complete(void) {
uint32_t epints = USB->DEVICE.EPINTSMRY.reg;
for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) {
if ((epints & (1 << epnum)) == 0) {
continue;
}
if (maybe_handle_setup_packet()) {
continue;
}
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
uint32_t epintflag = ep->EPINTFLAG.reg;
uint16_t total_transfer_size = 0;
// Handle IN completions
if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT1) != 0) {
ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1;
UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_IN];
total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT;
uint8_t ep_addr = epnum | TUSB_DIR_IN_MASK;
dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true);
}
// Handle OUT completions
if ((epintflag & USB_DEVICE_EPINTFLAG_TRCPT0) != 0) {
ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0;
UsbDeviceDescBank* bank = &sram_registers[epnum][TUSB_DIR_OUT];
total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT;
uint8_t ep_addr = epnum;
dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true);
}
// just finished status stage (total size = 0), prepare for next setup packet
if (epnum == 0 && total_transfer_size == 0) {
dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet));
}
}
}
void USB_Handler(void)
{
uint32_t int_status = USB->DEVICE.INTFLAG.reg & USB->DEVICE.INTENSET.reg;
USB->DEVICE.INTFLAG.reg = int_status; // clear interrupt
/*------------- Interrupt Processing -------------*/
if ( int_status & USB_DEVICE_INTFLAG_SOF )
{
dcd_event_bus_signal(0, DCD_EVENT_SOF, true);
}
// SAMD doesn't distinguish between Suspend and Disconnect state.
// Both condition will cause SUSPEND interrupt triggered.
// To prevent being triggered when D+/D- are not stable, SUSPEND interrupt is only
// enabled when we received SET_ADDRESS request and cleared on Bus Reset
if ( int_status & USB_DEVICE_INTFLAG_SUSPEND )
{
// Enable wakeup interrupt
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_WAKEUP; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTFLAG_WAKEUP;
dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true);
}
// Wakeup interrupt is only enabled when we got suspended.
// Wakeup interrupt will disable itself
if ( int_status & USB_DEVICE_INTFLAG_WAKEUP )
{
// disable wakeup interrupt itself
USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP;
dcd_event_bus_signal(0, DCD_EVENT_RESUME, true);
}
if ( int_status & USB_DEVICE_INTFLAG_EORST )
{
// Disable both suspend and wakeup interrupt
USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP | USB_DEVICE_INTFLAG_SUSPEND;
bus_reset();
dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true);
}
// Setup packet received.
maybe_handle_setup_packet();
// Handle complete transfer
maybe_transfer_complete();
}
#endif

View file

@ -0,0 +1,382 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018 Scott Shawcroft 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.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if TUSB_OPT_DEVICE_ENABLED && CFG_TUSB_MCU == OPT_MCU_SAMD51
#include "device/dcd.h"
#include "sam.h"
/*------------------------------------------------------------------*/
/* MACRO TYPEDEF CONSTANT ENUM
*------------------------------------------------------------------*/
static UsbDeviceDescBank sram_registers[8][2];
static ATTR_ALIGNED(4) uint8_t _setup_packet[8];
// Setup the control endpoint 0.
static void bus_reset(void)
{
// Max size of packets is 64 bytes.
UsbDeviceDescBank* bank_out = &sram_registers[0][TUSB_DIR_OUT];
bank_out->PCKSIZE.bit.SIZE = 0x3;
UsbDeviceDescBank* bank_in = &sram_registers[0][TUSB_DIR_IN];
bank_in->PCKSIZE.bit.SIZE = 0x3;
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[0];
ep->EPCFG.reg = USB_DEVICE_EPCFG_EPTYPE0(0x1) | USB_DEVICE_EPCFG_EPTYPE1(0x1);
ep->EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0 | USB_DEVICE_EPINTENSET_TRCPT1 | USB_DEVICE_EPINTENSET_RXSTP;
// Prepare for setup packet
dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet));
}
/*------------------------------------------------------------------*/
/* Controller API
*------------------------------------------------------------------*/
void dcd_init (uint8_t rhport)
{
(void) rhport;
// Reset to get in a clean state.
USB->DEVICE.CTRLA.bit.SWRST = true;
while (USB->DEVICE.SYNCBUSY.bit.SWRST == 0) {}
while (USB->DEVICE.SYNCBUSY.bit.SWRST == 1) {}
USB->DEVICE.PADCAL.bit.TRANSP = (*((uint32_t*) USB_FUSES_TRANSP_ADDR) & USB_FUSES_TRANSP_Msk) >> USB_FUSES_TRANSP_Pos;
USB->DEVICE.PADCAL.bit.TRANSN = (*((uint32_t*) USB_FUSES_TRANSN_ADDR) & USB_FUSES_TRANSN_Msk) >> USB_FUSES_TRANSN_Pos;
USB->DEVICE.PADCAL.bit.TRIM = (*((uint32_t*) USB_FUSES_TRIM_ADDR) & USB_FUSES_TRIM_Msk) >> USB_FUSES_TRIM_Pos;
USB->DEVICE.QOSCTRL.bit.CQOS = 3;
USB->DEVICE.QOSCTRL.bit.DQOS = 3;
// Configure registers
USB->DEVICE.DESCADD.reg = (uint32_t) &sram_registers;
USB->DEVICE.CTRLB.reg = USB_DEVICE_CTRLB_SPDCONF_FS;
USB->DEVICE.CTRLA.reg = USB_CTRLA_MODE_DEVICE | USB_CTRLA_ENABLE | USB_CTRLA_RUNSTDBY;
while (USB->DEVICE.SYNCBUSY.bit.ENABLE == 1) {}
USB->DEVICE.INTFLAG.reg |= USB->DEVICE.INTFLAG.reg; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SOF | USB_DEVICE_INTENSET_EORST;
}
void dcd_int_enable(uint8_t rhport)
{
(void) rhport;
NVIC_EnableIRQ(USB_0_IRQn);
NVIC_EnableIRQ(USB_1_IRQn);
NVIC_EnableIRQ(USB_2_IRQn);
NVIC_EnableIRQ(USB_3_IRQn);
}
void dcd_int_disable(uint8_t rhport)
{
(void) rhport;
NVIC_DisableIRQ(USB_3_IRQn);
NVIC_DisableIRQ(USB_2_IRQn);
NVIC_DisableIRQ(USB_1_IRQn);
NVIC_DisableIRQ(USB_0_IRQn);
}
void dcd_set_address (uint8_t rhport, uint8_t dev_addr)
{
// Response with status first before changing device address
dcd_edpt_xfer(rhport, tu_edpt_addr(0, TUSB_DIR_IN), NULL, 0);
// Wait for EP0 to finish before switching the address.
while (USB->DEVICE.DeviceEndpoint[0].EPSTATUS.bit.BK1RDY == 1) {}
USB->DEVICE.DADD.reg = USB_DEVICE_DADD_DADD(dev_addr) | USB_DEVICE_DADD_ADDEN;
// Enable SUSPEND interrupt since the bus signal D+/D- are stable now.
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTENCLR_SUSPEND; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_SUSPEND;
}
void dcd_set_config (uint8_t rhport, uint8_t config_num)
{
(void) rhport;
(void) config_num;
// Nothing to do
}
void dcd_remote_wakeup(uint8_t rhport)
{
(void) rhport;
USB->DEVICE.CTRLB.bit.UPRSM = 1;
}
/*------------------------------------------------------------------*/
/* DCD Endpoint port
*------------------------------------------------------------------*/
bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * desc_edpt)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(desc_edpt->bEndpointAddress);
uint8_t const dir = tu_edpt_dir(desc_edpt->bEndpointAddress);
UsbDeviceDescBank* bank = &sram_registers[epnum][dir];
uint32_t size_value = 0;
while (size_value < 7) {
if (1 << (size_value + 3) == desc_edpt->wMaxPacketSize.size) {
break;
}
size_value++;
}
// unsupported endpoint size
if ( size_value == 7 && desc_edpt->wMaxPacketSize.size != 1023 ) return false;
bank->PCKSIZE.bit.SIZE = size_value;
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if ( dir == TUSB_DIR_OUT )
{
ep->EPCFG.bit.EPTYPE0 = desc_edpt->bmAttributes.xfer + 1;
ep->EPINTENSET.bit.TRCPT0 = true;
}else
{
ep->EPCFG.bit.EPTYPE1 = desc_edpt->bmAttributes.xfer + 1;
ep->EPINTENSET.bit.TRCPT1 = true;
}
return true;
}
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
UsbDeviceDescBank* bank = &sram_registers[epnum][dir];
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
// A setup token can occur immediately after an OUT STATUS packet so make sure we have a valid
// buffer for the control endpoint.
if (epnum == 0 && dir == 0 && buffer == NULL) {
buffer = _setup_packet;
}
bank->ADDR.reg = (uint32_t) buffer;
if ( dir == TUSB_DIR_OUT )
{
bank->PCKSIZE.bit.MULTI_PACKET_SIZE = total_bytes;
bank->PCKSIZE.bit.BYTE_COUNT = 0;
ep->EPSTATUSCLR.reg |= USB_DEVICE_EPSTATUSCLR_BK0RDY;
ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL0;
} else
{
bank->PCKSIZE.bit.MULTI_PACKET_SIZE = 0;
bank->PCKSIZE.bit.BYTE_COUNT = total_bytes;
ep->EPSTATUSSET.reg |= USB_DEVICE_EPSTATUSSET_BK1RDY;
ep->EPINTFLAG.reg |= USB_DEVICE_EPINTFLAG_TRFAIL1;
}
return true;
}
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ1;
} else {
ep->EPSTATUSSET.reg = USB_DEVICE_EPSTATUSSET_STALLRQ0;
}
}
void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ1;
} else {
ep->EPSTATUSCLR.reg = USB_DEVICE_EPSTATUSCLR_STALLRQ0;
}
}
bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
// USBD shouldn't check control endpoint state
if ( 0 == ep_addr ) return false;
uint8_t const epnum = tu_edpt_number(ep_addr);
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
if (tu_edpt_dir(ep_addr) == TUSB_DIR_IN) {
return ep->EPINTFLAG.bit.TRCPT1 == 0 && ep->EPSTATUS.bit.BK1RDY == 1;
}
return ep->EPINTFLAG.bit.TRCPT0 == 0 && ep->EPSTATUS.bit.BK0RDY == 1;
}
/*------------------------------------------------------------------*/
static bool maybe_handle_setup_packet(void) {
if (USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.bit.RXSTP)
{
USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_RXSTP;
// This copies the data elsewhere so we can reuse the buffer.
dcd_event_setup_received(0, (uint8_t*) sram_registers[0][0].ADDR.reg, true);
return true;
}
return false;
}
/*
*------------------------------------------------------------------*/
/* USB_EORSM_DNRSM, USB_EORST_RST, USB_LPMSUSP_DDISC, USB_LPM_DCONN,
USB_MSOF, USB_RAMACER, USB_RXSTP_TXSTP_0, USB_RXSTP_TXSTP_1,
USB_RXSTP_TXSTP_2, USB_RXSTP_TXSTP_3, USB_RXSTP_TXSTP_4,
USB_RXSTP_TXSTP_5, USB_RXSTP_TXSTP_6, USB_RXSTP_TXSTP_7,
USB_STALL0_STALL_0, USB_STALL0_STALL_1, USB_STALL0_STALL_2,
USB_STALL0_STALL_3, USB_STALL0_STALL_4, USB_STALL0_STALL_5,
USB_STALL0_STALL_6, USB_STALL0_STALL_7, USB_STALL1_0, USB_STALL1_1,
USB_STALL1_2, USB_STALL1_3, USB_STALL1_4, USB_STALL1_5, USB_STALL1_6,
USB_STALL1_7, USB_SUSPEND, USB_TRFAIL0_TRFAIL_0, USB_TRFAIL0_TRFAIL_1,
USB_TRFAIL0_TRFAIL_2, USB_TRFAIL0_TRFAIL_3, USB_TRFAIL0_TRFAIL_4,
USB_TRFAIL0_TRFAIL_5, USB_TRFAIL0_TRFAIL_6, USB_TRFAIL0_TRFAIL_7,
USB_TRFAIL1_PERR_0, USB_TRFAIL1_PERR_1, USB_TRFAIL1_PERR_2,
USB_TRFAIL1_PERR_3, USB_TRFAIL1_PERR_4, USB_TRFAIL1_PERR_5,
USB_TRFAIL1_PERR_6, USB_TRFAIL1_PERR_7, USB_UPRSM, USB_WAKEUP */
void USB_0_Handler(void) {
uint32_t int_status = USB->DEVICE.INTFLAG.reg & USB->DEVICE.INTENSET.reg;
/*------------- Interrupt Processing -------------*/
// SAMD doesn't distinguish between Suspend and Disconnect state.
// Both condition will cause SUSPEND interrupt triggered.
// To prevent being triggered when D+/D- are not stable, SUSPEND interrupt is only
// enabled when we received SET_ADDRESS request and cleared on Bus Reset
if ( int_status & USB_DEVICE_INTFLAG_SUSPEND )
{
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SUSPEND;
// Enable wakeup interrupt
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_WAKEUP; // clear pending
USB->DEVICE.INTENSET.reg = USB_DEVICE_INTFLAG_WAKEUP;
dcd_event_bus_signal(0, DCD_EVENT_SUSPEND, true);
}
// Wakeup interrupt is only enabled when we got suspended.
// Wakeup interrupt will disable itself
if ( int_status & USB_DEVICE_INTFLAG_WAKEUP )
{
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_WAKEUP;
// disable wakeup interrupt itself
USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP;
dcd_event_bus_signal(0, DCD_EVENT_RESUME, true);
}
if ( int_status & USB_DEVICE_INTFLAG_EORST )
{
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_EORST;
// Disable both suspend and wakeup interrupt
USB->DEVICE.INTENCLR.reg = USB_DEVICE_INTFLAG_WAKEUP | USB_DEVICE_INTFLAG_SUSPEND;
bus_reset();
dcd_event_bus_signal(0, DCD_EVENT_BUS_RESET, true);
}
// Setup packet received.
maybe_handle_setup_packet();
}
/* USB_SOF_HSOF */
void USB_1_Handler(void) {
USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_SOF;
dcd_event_bus_signal(0, DCD_EVENT_SOF, true);
}
void transfer_complete(uint8_t direction) {
uint32_t epints = USB->DEVICE.EPINTSMRY.reg;
for (uint8_t epnum = 0; epnum < USB_EPT_NUM; epnum++) {
if ((epints & (1 << epnum)) == 0) {
continue;
}
if (direction == TUSB_DIR_OUT && maybe_handle_setup_packet()) {
continue;
}
UsbDeviceEndpoint* ep = &USB->DEVICE.DeviceEndpoint[epnum];
UsbDeviceDescBank* bank = &sram_registers[epnum][direction];
uint16_t total_transfer_size = bank->PCKSIZE.bit.BYTE_COUNT;
uint8_t ep_addr = epnum;
if (direction == TUSB_DIR_IN) {
ep_addr |= TUSB_DIR_IN_MASK;
}
dcd_event_xfer_complete(0, ep_addr, total_transfer_size, XFER_RESULT_SUCCESS, true);
// just finished status stage (total size = 0), prepare for next setup packet
if (epnum == 0 && total_transfer_size == 0) {
dcd_edpt_xfer(0, 0, _setup_packet, sizeof(_setup_packet));
}
if (direction == TUSB_DIR_IN) {
ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1;
} else {
ep->EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0;
}
}
}
// Bank zero is for OUT and SETUP transactions.
/* USB_TRCPT0_0, USB_TRCPT0_1, USB_TRCPT0_2,
USB_TRCPT0_3, USB_TRCPT0_4, USB_TRCPT0_5,
USB_TRCPT0_6, USB_TRCPT0_7 */
void USB_2_Handler(void) {
transfer_complete(TUSB_DIR_OUT);
}
// Bank one is used for IN transactions.
/* USB_TRCPT1_0, USB_TRCPT1_1, USB_TRCPT1_2,
USB_TRCPT1_3, USB_TRCPT1_4, USB_TRCPT1_5,
USB_TRCPT1_6, USB_TRCPT1_7 */
void USB_3_Handler(void) {
transfer_complete(TUSB_DIR_IN);
}
#endif

View file

@ -0,0 +1,70 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if TUSB_OPT_HOST_ENABLED || TUSB_OPT_DEVICE_ENABLED
#include "tusb.h"
static bool _initialized = false;
// TODO clean up
#if TUSB_OPT_DEVICE_ENABLED
#include "device/usbd_pvt.h"
#endif
bool tusb_init(void)
{
// skip if already initialized
if (_initialized) return true;
#if TUSB_OPT_HOST_ENABLED
TU_VERIFY( usbh_init() ); // init host stack
#endif
#if TUSB_OPT_DEVICE_ENABLED
TU_VERIFY ( usbd_init() ); // init device stack
#endif
_initialized = true;
return TUSB_ERROR_NONE;
}
bool tusb_inited(void)
{
return _initialized;
}
/*------------------------------------------------------------------*/
/* Debug
*------------------------------------------------------------------*/
#if CFG_TUSB_DEBUG
char const* const tusb_strerr[TUSB_ERROR_COUNT] = { ERROR_TABLE(ERROR_STRING) };
#endif
#endif // host or device enabled

View file

@ -0,0 +1,124 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_H_
#define _TUSB_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// INCLUDE
//--------------------------------------------------------------------+
#include "common/tusb_common.h"
#include "osal/osal.h"
#include "common/tusb_fifo.h"
//------------- HOST -------------//
#if TUSB_OPT_HOST_ENABLED
#include "host/usbh.h"
#if HOST_CLASS_HID
#include "class/hid/hid_host.h"
#endif
#if CFG_TUH_MSC
#include "class/msc/msc_host.h"
#endif
#if CFG_TUH_CDC
#include "class/cdc/cdc_host.h"
#endif
#if CFG_TUSB_HOST_CUSTOM_CLASS
#include "class/custom_host.h"
#endif
#endif
//------------- DEVICE -------------//
#if TUSB_OPT_DEVICE_ENABLED
#include "device/usbd.h"
#if CFG_TUD_HID
#include "class/hid/hid_device.h"
#endif
#if CFG_TUD_CDC
#include "class/cdc/cdc_device.h"
#endif
#if CFG_TUD_MSC
#include "class/msc/msc_device.h"
#endif
#if CFG_TUD_MIDI
#include "class/midi/midi_device.h"
#endif
#if CFG_TUD_CUSTOM_CLASS
#include "class/custom/custom_device.h"
#endif
#endif
//--------------------------------------------------------------------+
// APPLICATION API
//--------------------------------------------------------------------+
/** \ingroup group_application_api
* @{ */
// Initialize device/host stack
bool tusb_init(void);
// Check if stack is initialized
bool tusb_inited(void);
// TODO
// bool tusb_teardown(void);
// backward compatible only. TODO remove later
ATTR_DEPRECATED("Please use either tud_task() or tuh_task()")
static inline void tusb_task(void)
{
#if TUSB_OPT_HOST_ENABLED
tuh_task();
#endif
#if TUSB_OPT_DEVICE_ENABLED
tud_task();
#endif
}
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_H_ */

View file

@ -0,0 +1,204 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_OPTION_H_
#define _TUSB_OPTION_H_
#define TUSB_VERSION_YEAR 00
#define TUSB_VERSION_MONTH 00
#define TUSB_VERSION_WEEK 0
#define TUSB_VERSION_NAME "alpha"
#define TUSB_VERSION XSTRING_(TUSB_VERSION_YEAR) "." XSTRING_(TUSB_VERSION_MONTH)
/** \defgroup group_mcu Supported MCU
* \ref CFG_TUSB_MCU must be defined to one of these
* @{ */
#define OPT_MCU_LPC11UXX 1 ///< NXP LPC11Uxx
#define OPT_MCU_LPC13XX 3 ///< NXP LPC13xx
#define OPT_MCU_LPC175X_6X 4 ///< NXP LPC175x, LPC176x
#define OPT_MCU_LPC177X_8X 5 ///< NXP LPC177x, LPC178x
#define OPT_MCU_LPC18XX 6 ///< NXP LPC18xx
#define OPT_MCU_LPC40XX 7 ///< NXP LPC40xx
#define OPT_MCU_LPC43XX 8 ///< NXP LPC43xx
#define OPT_MCU_NRF5X 100 ///< Nordic nRF5x series
#define OPT_MCU_SAMD21 200 ///< MicroChip SAMD21
#define OPT_MCU_SAMD51 201 ///< MicroChip SAMD51
#define OPT_MCU_STM32F4 300 ///< ST STM32F4
#define OPT_MCU_STM32F3 301 ///< ST STM32F3
/** @} */
/** \defgroup group_supported_os Supported RTOS
* \ref CFG_TUSB_OS must be defined to one of these
* @{ */
#define OPT_OS_NONE 1 ///< No RTOS
#define OPT_OS_FREERTOS 2 ///< FreeRTOS
#define OPT_OS_MYNEWT 3 ///< Mynewt OS
/** @} */
// Allow to use command line to change the config name/location
#ifndef CFG_TUSB_CONFIG_FILE
#define CFG_TUSB_CONFIG_FILE "tusb_config.h"
#endif
#include CFG_TUSB_CONFIG_FILE
/** \addtogroup group_configuration
* @{ */
//--------------------------------------------------------------------
// CONTROLLER
// Only 1 roothub port can be configured to be device and/or host.
// tinyusb does not support dual devices or dual host configuration
//--------------------------------------------------------------------
/** \defgroup group_mode Controller Mode Selection
* \brief CFG_TUSB_CONTROLLER_N_MODE must be defined with these
* @{ */
#define OPT_MODE_NONE 0x00 ///< Disabled
#define OPT_MODE_DEVICE 0x01 ///< Device Mode
#define OPT_MODE_HOST 0x02 ///< Host Mode
#define OPT_MODE_HIGH_SPEED 0x10 ///< High speed
/** @} */
#ifndef CFG_TUSB_RHPORT0_MODE
#define CFG_TUSB_RHPORT0_MODE OPT_MODE_NONE
#endif
#ifndef CFG_TUSB_RHPORT1_MODE
#define CFG_TUSB_RHPORT1_MODE OPT_MODE_NONE
#endif
#if ((CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST)) || \
((CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) && (CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE))
#error "tinyusb does not support same modes on more than 1 roothub port"
#endif
// Which roothub port is configured as host
#define TUH_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_HOST) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_HOST) ? 1 : -1) )
#define TUSB_OPT_HOST_ENABLED ( TUH_OPT_RHPORT >= 0 )
// Which roothub port is configured as device
#define TUD_OPT_RHPORT ( (CFG_TUSB_RHPORT0_MODE & OPT_MODE_DEVICE) ? 0 : ((CFG_TUSB_RHPORT1_MODE & OPT_MODE_DEVICE) ? 1 : -1) )
#if TUD_OPT_RHPORT == 0
#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT0_MODE & OPT_MODE_HIGH_SPEED )
#else
#define TUD_OPT_HIGH_SPEED ( CFG_TUSB_RHPORT1_MODE & OPT_MODE_HIGH_SPEED )
#endif
#define TUSB_OPT_DEVICE_ENABLED ( TUD_OPT_RHPORT >= 0 )
//--------------------------------------------------------------------+
// COMMON OPTIONS
//--------------------------------------------------------------------+
/**
determines the debug level for the stack
- Level 3: TBD
- Level 2: TBD
- Level 1: Print out if Assert failed. STATIC_VAR is NULL --> accessible when debugging
- Level 0: no debug information is generated
*/
#ifndef CFG_TUSB_DEBUG
#define CFG_TUSB_DEBUG 0
#warning CFG_TUSB_DEBUG is not defined, default value is 0
#endif
// place data in accessible RAM for usb controller
#ifndef CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_SECTION
#endif
#ifndef CFG_TUSB_MEM_ALIGN
#define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4)
#endif
#ifndef CFG_TUSB_OS
#define CFG_TUSB_OS OPT_OS_NONE
#endif
//--------------------------------------------------------------------
// DEVICE OPTIONS
//--------------------------------------------------------------------
#if TUSB_OPT_DEVICE_ENABLED
#ifndef CFG_TUD_ENDOINT0_SIZE
#define CFG_TUD_ENDOINT0_SIZE 64
#endif
#ifndef CFG_TUD_CTRL_BUFSIZE
#define CFG_TUD_CTRL_BUFSIZE 256
#endif
#ifndef CFG_TUD_CDC
#define CFG_TUD_CDC 0
#endif
#ifndef CFG_TUD_MSC
#define CFG_TUD_MSC 0
#endif
#endif // TUSB_OPT_DEVICE_ENABLED
//--------------------------------------------------------------------
// HOST OPTIONS
//--------------------------------------------------------------------
#if TUSB_OPT_HOST_ENABLED
#ifndef CFG_TUSB_HOST_DEVICE_MAX
#define CFG_TUSB_HOST_DEVICE_MAX 1
#warning CFG_TUSB_HOST_DEVICE_MAX is not defined, default value is 1
#endif
//------------- HUB CLASS -------------//
#if CFG_TUH_HUB && (CFG_TUSB_HOST_DEVICE_MAX == 1)
#error there is no benefit enable hub with max device is 1. Please disable hub or increase CFG_TUSB_HOST_DEVICE_MAX
#endif
//------------- HID CLASS -------------//
#define HOST_CLASS_HID ( CFG_TUH_HID_KEYBOARD + CFG_TUH_HID_MOUSE + CFG_TUSB_HOST_HID_GENERIC )
#ifndef CFG_TUSB_HOST_ENUM_BUFFER_SIZE
#define CFG_TUSB_HOST_ENUM_BUFFER_SIZE 256
#endif
//------------- CLASS -------------//
#endif // TUSB_OPT_HOST_ENABLED
//------------------------------------------------------------------
// Configuration Validation
//------------------------------------------------------------------
#if CFG_TUD_ENDOINT0_SIZE > 64
#error Control Endpoint Max Packet Size cannot be larger than 64
#endif
#endif /* _TUSB_OPTION_H_ */
/** @} */

View file

@ -0,0 +1,94 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2018, hathach for Adafruit
*
* 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_CONFIG_H_
#define _TUSB_CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------
// COMMON CONFIGURATION
//--------------------------------------------------------------------
#ifdef __SAMD51__
#define CFG_TUSB_MCU OPT_MCU_SAMD51
#else
#define CFG_TUSB_MCU OPT_MCU_SAMD21
#endif
#define CFG_TUSB_RHPORT0_MODE OPT_MODE_DEVICE
#define CFG_TUSB_OS OPT_OS_NONE
#define CFG_TUSB_DEBUG 0
#define CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_ALIGN ATTR_ALIGNED(4)
//--------------------------------------------------------------------
// DEVICE CONFIGURATION
//--------------------------------------------------------------------
#define CFG_TUD_ENDOINT0_SIZE 64
//------------- CLASS -------------//
#define CFG_TUD_CDC 1
#define CFG_TUD_MSC 1
#define CFG_TUD_HID 1
#define CFG_TUD_MIDI 0
#define CFG_TUD_CUSTOM_CLASS 0
//--------------------------------------------------------------------
// CDC
//--------------------------------------------------------------------
// FIFO size of CDC TX and RX
#define CFG_TUD_CDC_RX_BUFSIZE 256
#define CFG_TUD_CDC_TX_BUFSIZE 256
//--------------------------------------------------------------------
// MSC
//--------------------------------------------------------------------
// Buffer size of Device Mass storage
#define CFG_TUD_MSC_BUFSIZE 512
// Vendor name included in Inquiry response, max 8 bytes
#define CFG_TUD_MSC_VENDOR "Adafruit"
// Product name included in Inquiry response, max 16 bytes
#define CFG_TUD_MSC_PRODUCT "Bluefruit nRF52"
// Product revision string included in Inquiry response, max 4 bytes
#define CFG_TUD_MSC_PRODUCT_REV "1.0"
//--------------------------------------------------------------------
// HID
//--------------------------------------------------------------------
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_CONFIG_H_ */

View file

@ -124,10 +124,7 @@ void loop( void ) ;
#define digitalPinToInterrupt(P) ( P )
#endif
// USB Device
#include "USB/USBDesc.h"
#include "USB/USBCore.h"
#include "USB/USBAPI.h"
#include "USB/USB_host.h"
// USB
#include "Adafruit_TinyUSB_Core.h"
#endif // Arduino_h

View file

@ -40,8 +40,7 @@ int main( void )
delay(1);
#if defined(USBCON)
USBDevice.init();
USBDevice.attach();
Adafruit_TinyUSB_Core_init();
#endif
setup();
@ -49,8 +48,20 @@ int main( void )
for (;;)
{
loop();
#if defined(USBCON)
tud_task();
#endif
if (serialEventRun) serialEventRun();
}
return 0;
}
void yield(void)
{
#if defined(USBCON)
tud_task();
#endif
}

View file

@ -71,7 +71,7 @@ compiler.arm.cmsis.ldflags="-L{runtime.tools.CMSIS-4.5.0.path}/CMSIS/Lib/GCC/"
# USB Flags
# ---------
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} -DUSBCON '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} -DUSBCON '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' "-I{build.core.path}/Adafruit_TinyUSB_core" "-I{build.core.path}/Adafruit_TinyUSB_core/tinyusb/src"
# Default usb manufacturer will be replaced at compile time using
# numeric vendor ID if available or by board's specific value.