Merge branch 'master' into cplay_nrf

This commit is contained in:
Ladyada committed 2019-08-17 13:42:46 -04:00
commit 067059bfea
74 files changed
+13809 -799

No files matched your search

+8 -1
View File
@@ -4,6 +4,9 @@ git:
depth: false
quiet: true
env:
- BSP_PATH="$HOME/.arduino15/packages/adafruit/hardware/nrf52"
addons:
apt:
packages:
@@ -19,8 +22,12 @@ install:
- umake electronics arduino $HOME/arduino_ide
- export PATH=$HOME/arduino_ide:$PATH
- arduino --pref "boardsmanager.additional.urls=https://adafruit.github.io/arduino-board-index/package_adafruit_index.json" --save-prefs
# Install BSP for tools, then remove and create symlink the git code
- arduino --install-boards adafruit:nrf52
- arduino --install-library "Adafruit NeoPixel","Adafruit NeoMatrix","Adafruit GFX Library","Adafruit SSD1306","MIDI Library",
- BSP_VERSION=`eval ls $BSP_PATH`
- rm -r $BSP_PATH/*
- ln -s $TRAVIS_BUILD_DIR $BSP_PATH/$BSP_VERSION
- arduino --install-library "Adafruit NeoPixel","Adafruit NeoMatrix","Adafruit GFX Library","Adafruit SSD1306","MIDI Library","Adafruit ILI9341"
before_script:
+1 -2
View File
@@ -8,7 +8,7 @@ This repository contains the Arduino BSP for Adafruit Bluefruit nRF52 series:
Following boards are also included but are not officially supported:
- [Noric nRF52840DK PCA10056](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK)
- [Nordic nRF52840DK PCA10056](https://www.nordicsemi.com/Software-and-Tools/Development-Kits/nRF52840-DK)
## BSP Installation
@@ -115,4 +115,3 @@ The following libraries are used:
- [tinyusb](https://github.com/hathach/tinyusb) as usb stack
- [nrfx](https://github.com/NordicSemiconductor/nrfx) for peripherals driver
- [littlefs](https://github.com/ARMmbed/littlefs) for internal file system
- [fatfs by elm-chan](http://elm-chan.org/fsw/ff/00index_e.html) for external file system
File diff suppressed because it is too large. Load diff
+22 -5
View File
@@ -1,13 +1,30 @@
# Adafruit nRF52 Arduino Core Changelog
# 0.11.1
## Next Release
## 0.12.0 - 2019.08.05
- Update tinyusb core to support webUSB & vendor class
- Added a couple delete operators to make std=gnu++14/17, PR #312 thanks to @kevinfrei
- Fix Serial.read() return clean 8-bit, PR #308 thanks to @pyro9
- Added availableForWrite(), PR #311 thanks to @pyro9
## 0.11.1 - 2019.07.10
- Update tinyusb core to support USB MIDI
- Refactor Ada Callback, use ISCR to detect isr context. Use function instead of macro
- Implement #240 run travis test with all example sketches
- Fix auto-start of advertising when central is connected, thanks to @ogatatsu PR #268
- Fixed auto-start of advertising when central is connected, thanks to @ogatatsu PR #268
- Added Tone()/noTone() functions
- Travis-ci builds all sketches when commit code
- Fixed setAppearance/getAppearance() typo, thanks to @paulmand3l PR #292
- Fixed rssi_proximity_peripheral sketch, thanks to @dicobrazz PR #295
- Fixed doc typo, thanks to @yvadher PR #296
- Fixed HID usage code location comment in exmaple sketch, thanks to @stefandz PR #297
- Fixed #277 conn LED doesn't stop when scanner is time out
- Added connection handle to Bluefruit.connParied()
# 0.11.0
## 0.11.0
- Rework USB driver to support Adafruit_TinyUSB library (support HID and MSC)
- Added Metro nRF52840 Express
@@ -29,7 +46,7 @@
- enhance Serial.available()/write() to prevent blocking wait without yield/delay
- Clean up compiler warnings
# 0.10.1
## 0.10.1
This release added multiple concurrent peripheral connections support, allow Bluefruit device to multiple central (phones/PC) simultaneously. It introduces new BLE class: BLEPeriph, BLEConnection, remove BLEGap, refactor/rename/move functions and callbacks.
@@ -72,7 +89,7 @@ This release added multiple concurrent peripheral connections support, allow Blu
- Removed keyboardReport() variant with flat keycode parameters
- Added conn_handle parameter to keyboard led callback
# 0.9.3
## 0.9.3
- Correct bootloader version text in IDE to 0.2.6
- Fixed #173 bleuart return incorrect value when failed to send (PR #178 thanks Nenik)
@@ -37,10 +37,11 @@ Adafruit_USBD_CDC::Adafruit_USBD_CDC(void)
}
uint16_t Adafruit_USBD_CDC::getDescriptor(uint8_t* buf, uint16_t bufsize)
uint16_t Adafruit_USBD_CDC::getDescriptor(uint8_t itfnum, 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) };
// usb core will automatically update endpoint number
uint8_t desc[] = { TUD_CDC_DESCRIPTOR(itfnum, 0, EPIN, 8, EPOUT, EPIN, 64) };
uint16_t const len = sizeof(desc);
if ( bufsize < len ) return 0;
@@ -52,9 +53,13 @@ uint16_t Adafruit_USBD_CDC::getDescriptor(uint8_t* buf, uint16_t bufsize)
// Baud and config is ignore in CDC
void Adafruit_USBD_CDC::begin (uint32_t baud)
{
(void) baud;
}
void Adafruit_USBD_CDC::begin (uint32_t baud, uint8_t config)
{
(void) baud;
(void) config;
}
void Adafruit_USBD_CDC::end(void)
@@ -86,7 +91,8 @@ int Adafruit_USBD_CDC::available(void)
int Adafruit_USBD_CDC::peek(void)
{
return tud_cdc_peek(0);
uint8_t ch;
return tud_cdc_peek(0, &ch) ? (int) ch : -1;
}
int Adafruit_USBD_CDC::read(void)
@@ -101,7 +107,7 @@ void Adafruit_USBD_CDC::flush(void)
size_t Adafruit_USBD_CDC::write(uint8_t ch)
{
return tud_cdc_write_char((char) ch);
return write(&ch, 1);
}
size_t Adafruit_USBD_CDC::write(const uint8_t *buffer, size_t size)
@@ -120,6 +126,11 @@ size_t Adafruit_USBD_CDC::write(const uint8_t *buffer, size_t size)
return size - remain;
}
int Adafruit_USBD_CDC::availableForWrite(void)
{
return tud_cdc_write_available();
}
extern "C"
{
@@ -128,6 +139,7 @@ extern "C"
void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts)
{
(void) itf; // interface ID, not used
(void) rts;
// DTR = false is counted as disconnected
if ( !dtr )
@@ -34,22 +34,24 @@ public:
Adafruit_USBD_CDC(void);
// fron Adafruit_USBD_Interface
virtual uint16_t getDescriptor(uint8_t* buf, uint16_t bufsize);
virtual uint16_t getDescriptor(uint8_t itfnum, 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 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);
}
virtual int availableForWrite(void);
operator bool();
};
@@ -40,7 +40,7 @@ Adafruit_USBD_Device USBDevice;
Adafruit_USBD_Device::Adafruit_USBD_Device(void)
{
tusb_desc_device_t desc_dev =
tusb_desc_device_t const desc_dev =
{
.bLength = sizeof(tusb_desc_device_t),
.bDescriptorType = TUSB_DESC_DEVICE,
@@ -57,17 +57,15 @@ Adafruit_USBD_Device::Adafruit_USBD_Device(void)
.idVendor = 0,
.idProduct = 0,
.bcdDevice = 0x0100,
.iManufacturer = 0x01,
.iProduct = 0x02,
.iSerialNumber = 0x03,
.bNumConfigurations = 0x01
};
_desc_device = desc_dev;
tusb_desc_configuration_t dev_cfg =
tusb_desc_configuration_t const dev_cfg =
{
.bLength = sizeof(tusb_desc_configuration_t),
.bDescriptorType = TUSB_DESC_CONFIGURATION,
@@ -75,7 +73,6 @@ Adafruit_USBD_Device::Adafruit_USBD_Device(void)
// 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,
@@ -95,26 +92,17 @@ Adafruit_USBD_Device::Adafruit_USBD_Device(void)
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);
uint16_t const len = itf.getDescriptor(_itf_count, 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++;
tusb_desc_interface_t* desc_itf = (tusb_desc_interface_t*) desc;
if (desc_itf->bAlternateSetting == 0) _itf_count++;
}else if (desc[1] == TUSB_DESC_ENDPOINT)
{
tusb_desc_endpoint_t* desc_ep = (tusb_desc_endpoint_t*) desc;
@@ -127,7 +115,7 @@ bool Adafruit_USBD_Device::addInterface(Adafruit_USBD_Interface& itf)
_desc_cfglen += len;
// Update config descriptor
// Update configuration descriptor
tusb_desc_configuration_t* config = (tusb_desc_configuration_t*)_desc_cfg;
config->wTotalLength = _desc_cfglen;
config->bNumInterfaces = _itf_count;
@@ -141,6 +129,11 @@ void Adafruit_USBD_Device::setID(uint16_t vid, uint16_t pid)
_desc_device.idProduct = pid;
}
void Adafruit_USBD_Device::setVersion(uint16_t bcd)
{
_desc_device.bcdUSB = bcd;
}
bool Adafruit_USBD_Device::begin(void)
{
return true;
@@ -30,7 +30,7 @@
class Adafruit_USBD_Interface
{
public:
virtual uint16_t getDescriptor(uint8_t* buf, uint16_t bufsize) = 0;
virtual uint16_t getDescriptor(uint8_t itfnum, uint8_t* buf, uint16_t bufsize) = 0;
};
class Adafruit_USBD_Device
@@ -52,12 +52,13 @@ class Adafruit_USBD_Device
bool addInterface(Adafruit_USBD_Interface& itf);
void setID(uint16_t vid, uint16_t pid);
void setVersion(uint16_t bcd);
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(); }
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(); }
friend uint8_t const * tud_descriptor_device_cb(void);
friend uint8_t const * tud_descriptor_configuration_cb(uint8_t index);
@@ -29,8 +29,8 @@
* Currently only MIDI subclass is supported
* @{ */
#ifndef _TUSB_CDC_H__
#define _TUSB_CDC_H__
#ifndef _TUSB_AUDIO_H__
#define _TUSB_AUDIO_H__
#include "common/tusb_common.h"
@@ -41,9 +41,9 @@
/// 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_CONTROL = 0x01 , ///< Audio Control
AUDIO_SUBCLASS_STREAMING , ///< Audio Streaming
AUDIO_SUBCLASS_MIDI_STREAMING , ///< MIDI Streaming
} audio_subclass_type_t;
/// Audio Protocol Codes
@@ -54,6 +54,40 @@ typedef enum
AUDIO_PROTOCOL_V3 = 0x30, ///< Version 3.0
} audio_protocol_type_t;
/// Audio Function Category Codes
typedef enum
{
AUDIO_FUNC_DESKTOP_SPEAKER = 0x01,
AUDIO_FUNC_HOME_THEATER = 0x02,
AUDIO_FUNC_MICROPHONE = 0x03,
AUDIO_FUNC_HEADSET = 0x04,
AUDIO_FUNC_TELEPHONE = 0x05,
AUDIO_FUNC_CONVERTER = 0x06,
AUDIO_FUNC_SOUND_RECODER = 0x07,
AUDIO_FUNC_IO_BOX = 0x08,
AUDIO_FUNC_MUSICAL_INSTRUMENT = 0x09,
AUDIO_FUNC_PRO_AUDIO = 0x0A,
AUDIO_FUNC_AUDIO_VIDEO = 0x0B,
AUDIO_FUNC_CONTROL_PANEL = 0x0C
} audio_function_t;
/// Audio Class-Specific AC Interface Descriptor Subtypes
typedef enum
{
AUDIO_CS_INTERFACE_HEADER = 0x01,
AUDIO_CS_INTERFACE_INPUT_TERMINAL = 0x02,
AUDIO_CS_INTERFACE_OUTPUT_TERMINAL = 0x03,
AUDIO_CS_INTERFACE_MIXER_UNIT = 0x04,
AUDIO_CS_INTERFACE_SELECTOR_UNIT = 0x05,
AUDIO_CS_INTERFACE_FEATURE_UNIT = 0x06,
AUDIO_CS_INTERFACE_EFFECT_UNIT = 0x07,
AUDIO_CS_INTERFACE_PROCESSING_UNIT = 0x08,
AUDIO_CS_INTERFACE_EXTENSION_UNIT = 0x09,
AUDIO_CS_INTERFACE_CLOCK_SOURCE = 0x0A,
AUDIO_CS_INTERFACE_CLOCK_SELECTOR = 0x0B,
AUDIO_CS_INTERFACE_CLOCK_MULTIPLIER = 0x0C,
AUDIO_CS_INTERFACE_SAMPLE_RATE_CONVERTER = 0x0D,
} audio_cs_interface_subtype_t;
/** @} */
@@ -41,7 +41,7 @@
/** \defgroup ClassDriver_CDC_Common Common Definitions
* @{ */
// TODO remove
/// CDC Pipe ID, used to indicate which pipe the API is addressing to (Notification, Out, In)
typedef enum
{
@@ -52,8 +52,9 @@ typedef enum
}cdc_pipeid_t;
//--------------------------------------------------------------------+
// CDC COMMUNICATION INTERFACE CLASS
// CDC Communication Interface Class
//--------------------------------------------------------------------+
/// Communication Interface Subclass Codes
typedef enum
{
@@ -117,7 +118,7 @@ typedef enum
}cdc_func_desc_type_t;
//--------------------------------------------------------------------+
// CDC DATA INTERFACE CLASS
// CDC Data Interface Class
//--------------------------------------------------------------------+
// SUBCLASS code of Data Interface is not used and should/must be zero
@@ -138,8 +139,9 @@ typedef enum{
}cdc_data_protocol_type_t;
//--------------------------------------------------------------------+
// MANAGEMENT ELEMENT REQUEST (CONTROL ENDPOINT)
// Management Element Request (Control Endpoint)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Request Codes
typedef enum
{
@@ -189,8 +191,9 @@ typedef enum
}cdc_management_request_t;
//--------------------------------------------------------------------+
// MANAGEMENT ELEMENENT NOTIFICATION (NOTIFICATION ENDPOINT)
// Management Elemenent Notification (Notification Endpoint)
//--------------------------------------------------------------------+
/// Communication Interface Management Element Notification Codes
typedef enum
{
@@ -209,14 +212,15 @@ typedef enum
}cdc_notification_request_t;
//--------------------------------------------------------------------+
// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE)
// Class Specific Functional Descriptor (Communication Interface)
//--------------------------------------------------------------------+
/// Header Functional Descriptor (Communication Interface)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUCN_DESC_
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above CDC_FUNC_DESC_
uint16_t bcdCDC ; ///< CDC release number in Binary-Coded Decimal
}cdc_desc_func_header_t;
@@ -246,7 +250,7 @@ typedef struct TU_ATTR_PACKED
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.
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) \
@@ -73,21 +73,18 @@ typedef struct
//--------------------------------------------------------------------+
CFG_TUSB_MEM_SECTION static cdcd_interface_t _cdcd_itf[CFG_TUD_CDC];
//bool pending_read_from_host; TODO remove
static void _prep_out_transaction (uint8_t itf)
{
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
// skip if previous transfer not complete
if ( usbd_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 )
{
usbd_edpt_xfer(TUD_OPT_RHPORT, p_cdc->ep_out, p_cdc->epout_buf, CFG_TUD_CDC_EPSIZE);
// pending_read_from_host = true;
}
}
@@ -124,12 +121,6 @@ uint32_t tud_cdc_n_available(uint8_t itf)
return tu_fifo_count(&_cdcd_itf[itf].rx_ff);
}
signed char tud_cdc_n_read_char(uint8_t itf)
{
signed 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);
@@ -137,10 +128,9 @@ uint32_t tud_cdc_n_read(uint8_t itf, void* buffer, uint32_t bufsize)
return num_read;
}
signed char tud_cdc_n_peek(uint8_t itf, int pos)
bool tud_cdc_n_peek(uint8_t itf, int pos, uint8_t* chr)
{
signed char ch;
return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, &ch) ? ch : (-1);
return tu_fifo_peek_at(&_cdcd_itf[itf].rx_ff, pos, chr);
}
void tud_cdc_n_read_flush (uint8_t itf)
@@ -152,17 +142,6 @@ void tud_cdc_n_read_flush (uint8_t 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);
@@ -193,6 +172,11 @@ bool tud_cdc_n_write_flush (uint8_t itf)
return true;
}
uint32_t tud_cdc_n_write_available (uint8_t itf)
{
return tu_fifo_remaining(&_cdcd_itf[itf].tx_ff);
}
//--------------------------------------------------------------------+
// USBD Driver API
@@ -265,7 +249,7 @@ bool cdcd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t
(*p_length) = sizeof(tusb_desc_interface_t);
// Communication Functional Descriptors
while ( TUSB_DESC_CLASS_SPECIFIC == tu_desc_type(p_desc) )
while ( TUSB_DESC_CS_INTERFACE == tu_desc_type(p_desc) )
{
(*p_length) += tu_desc_len(p_desc);
p_desc = tu_desc_next(p_desc);
@@ -296,7 +280,6 @@ bool cdcd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t
}
// Prepare for incoming data
// pending_read_from_host = false;
_prep_out_transaction(cdc_id);
return true;
@@ -304,7 +287,7 @@ bool cdcd_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t
// 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)
bool cdcd_control_complete(uint8_t rhport, tusb_control_request_t const * request)
{
(void) rhport;
@@ -338,11 +321,11 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request
switch ( request->bRequest )
{
case CDC_REQUEST_SET_LINE_CODING:
usbd_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
tud_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));
tud_control_xfer(rhport, request, &p_cdc->line_coding, sizeof(cdc_line_coding_t));
break;
case CDC_REQUEST_SET_CONTROL_LINE_STATE:
@@ -353,7 +336,7 @@ bool cdcd_control_request(uint8_t rhport, tusb_control_request_t const * request
// 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);
tud_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));
@@ -374,7 +357,7 @@ bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_
uint8_t const itf = 0;
cdcd_interface_t* p_cdc = &_cdcd_itf[itf];
// receive new data
// Received new data
if ( ep_addr == p_cdc->ep_out )
{
for(uint32_t i=0; i<xferred_bytes; i++)
@@ -392,11 +375,18 @@ bool cdcd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_
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
// Data sent to host, we could continue to fetch data tx fifo to send.
// But it will cause incorrect baudrate set in line coding.
// Though maybe the baudrate is not really important !!!
// if ( ep_addr == p_cdc->ep_in )
// {
//
// }
// nothing to do with notif endpoint for now
return true;
}
@@ -48,46 +48,48 @@
* @{ */
//--------------------------------------------------------------------+
// APPLICATION API (Multiple Interfaces)
// 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);
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);
signed 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);
signed char tud_cdc_n_peek (uint8_t itf, int pos);
uint32_t tud_cdc_n_available (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);
bool tud_cdc_n_peek (uint8_t itf, int pos, uint8_t* u8);
static inline int32_t tud_cdc_n_read_char (uint8_t itf);
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);
uint32_t tud_cdc_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
bool tud_cdc_n_write_flush (uint8_t itf);
uint32_t tud_cdc_n_write_available (uint8_t itf);
static inline uint32_t tud_cdc_n_write_char (uint8_t itf, char ch);
static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str);
//--------------------------------------------------------------------+
// APPLICATION API (Interface0)
// 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 bool tud_cdc_connected (void);
static inline uint8_t tud_cdc_get_line_state (void);
static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding);
static inline void tud_cdc_set_wanted_char (char wanted);
static inline uint32_t tud_cdc_available (void) { return tud_cdc_n_available(0); }
static inline signed 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 signed char tud_cdc_peek (int pos) { return tud_cdc_n_peek(0, pos); }
static inline uint32_t tud_cdc_available (void);
static inline int32_t tud_cdc_read_char (void);
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize);
static inline void tud_cdc_read_flush (void);
static inline bool tud_cdc_peek (int pos, uint8_t* u8);
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); }
static inline uint32_t tud_cdc_write_char (char ch);
static inline uint32_t tud_cdc_write (void const* buffer, uint32_t bufsize);
static inline uint32_t tud_cdc_write_str (char const* str);
static inline bool tud_cdc_write_flush (void);
static inline uint32_t tud_cdc_write_available (void);
//--------------------------------------------------------------------+
// APPLICATION CALLBACK API (WEAK is optional)
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when received new data
@@ -102,18 +104,107 @@ TU_ATTR_WEAK void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts);
// Invoked when line coding is change via SET_LINE_CODING
TU_ATTR_WEAK void tud_cdc_line_coding_cb(uint8_t itf, cdc_line_coding_t const* p_line_coding);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline int32_t tud_cdc_n_read_char (uint8_t itf)
{
uint8_t ch;
return tud_cdc_n_read(itf, &ch, 1) ? (int32_t) ch : -1;
}
static inline uint32_t tud_cdc_n_write_char(uint8_t itf, char ch)
{
return tud_cdc_n_write(itf, &ch, 1);
}
static inline uint32_t tud_cdc_n_write_str (uint8_t itf, char const* str)
{
return tud_cdc_n_write(itf, str, strlen(str));
}
static inline bool tud_cdc_connected (void)
{
return tud_cdc_n_connected(0);
}
static inline uint8_t tud_cdc_get_line_state (void)
{
return tud_cdc_n_get_line_state(0);
}
static inline void tud_cdc_get_line_coding (cdc_line_coding_t* coding)
{
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 int32_t tud_cdc_read_char (void)
{
return tud_cdc_n_read_char(0);
}
static inline uint32_t tud_cdc_read (void* buffer, uint32_t bufsize)
{
return tud_cdc_n_read(0, buffer, bufsize);
}
static inline void tud_cdc_read_flush (void)
{
tud_cdc_n_read_flush(0);
}
static inline bool tud_cdc_peek (int pos, uint8_t* u8)
{
return tud_cdc_n_peek(0, pos, u8);
}
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);
}
static inline uint32_t tud_cdc_write_available(void)
{
return tud_cdc_n_write_available(0);
}
/** @} */
/** @} */
//--------------------------------------------------------------------+
// 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);
void cdcd_init (void);
void cdcd_reset (uint8_t rhport);
bool cdcd_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool cdcd_control_request (uint8_t rhport, tusb_control_request_t const * request);
bool cdcd_control_complete (uint8_t rhport, tusb_control_request_t const * request);
bool cdcd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
@@ -1,93 +0,0 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && 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
@@ -1,58 +0,0 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_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_ */
@@ -205,7 +205,7 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
if (p_request->bRequest == TUSB_REQ_GET_DESCRIPTOR && desc_type == HID_DESC_TYPE_REPORT)
{
uint8_t const * desc_report = tud_hid_descriptor_report_cb();
usbd_control_xfer(rhport, p_request, (void*) desc_report, p_hid->reprot_desc_len);
tud_control_xfer(rhport, p_request, (void*) desc_report, p_hid->reprot_desc_len);
}else
{
return false; // stall unsupported request
@@ -225,12 +225,12 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
uint16_t xferlen = tud_hid_get_report_cb(report_id, (hid_report_type_t) report_type, p_hid->epin_buf, p_request->wLength);
TU_ASSERT( xferlen > 0 );
usbd_control_xfer(rhport, p_request, p_hid->epin_buf, xferlen);
tud_control_xfer(rhport, p_request, p_hid->epin_buf, xferlen);
}
break;
case HID_REQ_CONTROL_SET_REPORT:
usbd_control_xfer(rhport, p_request, p_hid->epout_buf, p_request->wLength);
tud_control_xfer(rhport, p_request, p_hid->epout_buf, p_request->wLength);
break;
case HID_REQ_CONTROL_SET_IDLE:
@@ -241,18 +241,18 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
if ( !tud_hid_set_idle_cb(p_hid->idle_rate) ) return false;
}
usbd_control_status(rhport, p_request);
tud_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);
tud_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);
tud_control_xfer(rhport, p_request, &protocol, 1);
}
break;
@@ -261,7 +261,7 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
if (tud_hid_boot_mode_cb) tud_hid_boot_mode_cb(p_hid->boot_mode);
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
default: return false; // stall unsupported request
@@ -276,7 +276,7 @@ bool hidd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
// 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)
bool hidd_control_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 );
@@ -300,12 +300,12 @@ TU_ATTR_WEAK bool tud_hid_set_idle_cb(uint8_t idle_rate);
//--------------------------------------------------------------------+
// 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);
void hidd_init (void);
void hidd_reset (uint8_t rhport);
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 * request);
bool hidd_control_complete (uint8_t rhport, tusb_control_request_t const * request);
bool hidd_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
@@ -39,27 +39,122 @@
#endif
//--------------------------------------------------------------------+
// FUNCTIONAL DESCRIPTOR (COMMUNICATION INTERFACE)
// Class Specific Descriptor
//--------------------------------------------------------------------+
/// Header Functional Descriptor (Communication Interface)
typedef enum
{
MIDI_CS_INTERFACE_HEADER = 0x01,
MIDI_CS_INTERFACE_IN_JACK = 0x02,
MIDI_CS_INTERFACE_OUT_JACK = 0x03,
MIDI_CS_INTERFACE_ELEMENT = 0x04,
} midi_cs_interface_subtype_t;
typedef enum
{
MIDI_CS_ENDPOINT_GENERAL = 0x01
} midi_cs_endpoint_subtype_t;
typedef enum
{
MIDI_JACK_EMBEDDED = 0x01,
MIDI_JACK_EXTERNAL = 0x02
} midi_jack_type_t;
/// MIDI Interface Header Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType one of above MIDI_FUCN_DESC_
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint16_t bcdMSC ; ///< MidiStreaming SubClass release number in Binary-Coded Decimal
uint16_t wTotalLength ;
}midi_desc_func_header_t;
} midi_desc_header_t;
/// Union Functional Descriptor (Communication Interface)
/// MIDI In Jack Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType 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;
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bJackType ; ///< Embedded or External
uint8_t bJackID ; ///< Unique ID for MIDI IN Jack
uint8_t iJack ; ///< string descriptor
} midi_desc_in_jack_t;
/// MIDI Out Jack Descriptor with single pin
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bJackType ; ///< Embedded or External
uint8_t bJackID ; ///< Unique ID for MIDI IN Jack
uint8_t bNrInputPins;
uint8_t baSourceID;
uint8_t baSourcePin;
uint8_t iJack ; ///< string descriptor
} midi_desc_out_jack_t ;
/// MIDI Out Jack Descriptor with multiple pins
#define midi_desc_out_jack_n_t(input_num) \
struct TU_ATTR_PACKED { \
uint8_t bLength ; \
uint8_t bDescriptorType ; \
uint8_t bDescriptorSubType ; \
uint8_t bJackType ; \
uint8_t bJackID ; \
uint8_t bNrInputPins ; \
struct TU_ATTR_PACKED { \
uint8_t baSourceID; \
uint8_t baSourcePin; \
} pins[input_num]; \
uint8_t iJack ; \
}
/// MIDI Element Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
uint8_t bDescriptorType ; ///< Descriptor Type, must be Class-Specific
uint8_t bDescriptorSubType ; ///< Descriptor SubType
uint8_t bElementID;
uint8_t bNrInputPins;
uint8_t baSourceID;
uint8_t baSourcePin;
uint8_t bNrOutputPins;
uint8_t bInTerminalLink;
uint8_t bOutTerminalLink;
uint8_t bElCapsSize;
uint16_t bmElementCaps;
uint8_t iElement;
} midi_desc_element_t;
/// MIDI Element Descriptor with multiple pins
#define midi_desc_element_n_t(input_num) \
struct TU_ATTR_PACKED { \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint8_t bDescriptorSubType; \
uint8_t bElementID; \
uint8_t bNrInputPins; \
struct TU_ATTR_PACKED { \
uint8_t baSourceID; \
uint8_t baSourcePin; \
} pins[input_num]; \
uint8_t bNrOutputPins; \
uint8_t bInTerminalLink; \
uint8_t bOutTerminalLink; \
uint8_t bElCapsSize; \
uint16_t bmElementCaps; \
uint8_t iElement; \
}
/** @} */
@@ -44,6 +44,7 @@ typedef struct
uint8_t ep_in;
uint8_t ep_out;
/*------------- From this point, data is not cleared by bus reset -------------*/
// FIFO
tu_fifo_t rx_ff;
tu_fifo_t tx_ff;
@@ -72,11 +73,12 @@ typedef struct
//--------------------------------------------------------------------+
// INTERNAL OBJECT & FUNCTION DECLARATION
//--------------------------------------------------------------------+
CFG_TUSB_ATTR_USBRAM midid_interface_t _midid_itf[CFG_TUD_MIDI];
CFG_TUSB_MEM_SECTION midid_interface_t _midid_itf[CFG_TUD_MIDI];
bool tud_midi_n_connected(uint8_t itf) {
bool tud_midi_n_mounted (uint8_t itf)
{
midid_interface_t* midi = &_midid_itf[itf];
return midi->itf_num != 0;
return midi->ep_in && midi->ep_out;
}
//--------------------------------------------------------------------+
@@ -87,12 +89,6 @@ 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);
@@ -103,7 +99,6 @@ 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;
@@ -133,15 +128,15 @@ void midi_rx_done_cb(midid_interface_t* midi, uint8_t const* buffer, uint32_t bu
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
// skip if previous transfer not complete
TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, midi->ep_in) );
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;
uint16_t count = tu_fifo_read_n(&midi->tx_ff, midi->epin_buf, CFG_TUD_MIDI_EPSIZE);
if (count > 0)
{
TU_ASSERT( usbd_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)
@@ -229,6 +224,7 @@ void midid_init(void)
// 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));
@@ -252,20 +248,18 @@ void midid_reset(uint8_t rhport)
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) {
if ( AUDIO_SUBCLASS_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_length) += tu_desc_len(p_desc);
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;
}
TU_VERIFY(AUDIO_SUBCLASS_MIDI_STREAMING == p_interface_desc->bInterfaceSubClass &&
AUDIO_PROTOCOL_V1 == p_interface_desc->bInterfaceProtocol );
// Find available interface
midid_interface_t * p_midi = NULL;
@@ -284,7 +278,8 @@ bool midid_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc,
(*p_length) = sizeof(tusb_desc_interface_t);
uint8_t found_endpoints = 0;
while (found_endpoints < p_interface_desc->bNumEndpoints) {
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);
@@ -304,12 +299,12 @@ bool midid_open(uint8_t rhport, tusb_desc_interface_t const * p_interface_desc,
}
// Prepare for incoming data
TU_ASSERT( dcd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false);
TU_ASSERT( usbd_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)
bool midid_control_complete(uint8_t rhport, tusb_control_request_t const * p_request)
{
return false;
}
@@ -322,20 +317,20 @@ bool midid_control_request(uint8_t rhport, tusb_control_request_t const * p_requ
return false;
}
bool midid_xfer_cb(uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes)
bool midid_xfer_cb(uint8_t rhport, uint8_t ep_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 )
if ( ep_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 ) {
TU_ASSERT( usbd_edpt_xfer(rhport, p_midi->ep_out, p_midi->epout_buf, CFG_TUD_MIDI_EPSIZE), false );
} else if ( ep_addr == p_midi->ep_in ) {
maybe_transmit(p_midi, itf);
}
@@ -29,7 +29,9 @@
#include "common/tusb_common.h"
#include "device/usbd.h"
#include "class/audio/audio.h"
#include "midi.h"
//--------------------------------------------------------------------+
// Class Driver Configuration
@@ -38,7 +40,6 @@
#define CFG_TUD_MIDI_EPSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
@@ -49,50 +50,83 @@
* @{ */
//--------------------------------------------------------------------+
// APPLICATION API (Multiple Interfaces)
// Application API (Multiple Interfaces)
// CFG_TUD_MIDI > 1
//--------------------------------------------------------------------+
bool tud_midi_n_connected (uint8_t itf);
bool tud_midi_n_mounted (uint8_t itf);
uint32_t tud_midi_n_available (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);
uint32_t tud_midi_n_write (uint8_t itf, uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize);
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);
static inline
uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3);
//--------------------------------------------------------------------+
// APPLICATION API (Interface0)
// 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); }
static inline bool tud_midi_mounted (void);
static inline uint32_t tud_midi_available (void);
static inline uint32_t tud_midi_read (void* buffer, uint32_t bufsize);
static inline void tud_midi_read_flush (void);
static inline uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize);
static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3);
//--------------------------------------------------------------------+
// APPLICATION CALLBACK API (WEAK is optional)
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
TU_ATTR_WEAK void tud_midi_rx_cb(uint8_t itf);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline uint32_t tud_midi_n_write24 (uint8_t itf, uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3)
{
uint8_t msg[3] = { b1, b2, b3 };
return tud_midi_n_write(itf, jack_id, msg, 3);
}
static inline bool tud_midi_mounted (void)
{
return tud_midi_n_mounted(0);
}
static inline uint32_t tud_midi_available (void)
{
return tud_midi_n_available(0, 0);
}
static inline uint32_t tud_midi_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 uint32_t tud_midi_write (uint8_t jack_id, uint8_t const* buffer, uint32_t bufsize)
{
return tud_midi_n_write(0, jack_id, buffer, bufsize);
}
static inline uint32_t tudi_midi_write24 (uint8_t jack_id, uint8_t b1, uint8_t b2, uint8_t b3)
{
uint8_t msg[3] = { b1, b2, b3 };
return tud_midi_write(jack_id, msg, 3);
}
//--------------------------------------------------------------------+
// 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);
void midid_init (void);
void midid_reset (uint8_t rhport);
bool midid_open (uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool midid_control_request (uint8_t rhport, tusb_control_request_t const * request);
bool midid_control_complete (uint8_t rhport, tusb_control_request_t const * request);
bool midid_xfer_cb (uint8_t rhport, uint8_t edpt_addr, xfer_result_t result, uint32_t xferred_bytes);
#ifdef __cplusplus
}
@@ -111,7 +111,7 @@ bool tud_msc_set_sense(uint8_t lun, uint8_t sense_key, uint8_t add_sense_code, u
}
//--------------------------------------------------------------------+
// USBD-CLASS API
// USBD Driver API
//--------------------------------------------------------------------+
void mscd_init(void)
{
@@ -154,7 +154,7 @@ bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
{
case MSC_REQ_RESET:
// TODO: Actually reset interface.
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
case MSC_REQ_GET_MAX_LUN:
@@ -166,7 +166,7 @@ bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
// MAX LUN is minus 1 by specs
maxlun--;
usbd_control_xfer(rhport, p_request, &maxlun, 1);
tud_control_xfer(rhport, p_request, &maxlun, 1);
}
break;
@@ -178,10 +178,10 @@ bool mscd_control_request(uint8_t rhport, tusb_control_request_t const * p_reque
// 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)
bool mscd_control_complete(uint8_t rhport, tusb_control_request_t const * request)
{
(void) rhport;
(void) p_request;
(void) request;
// nothing to do
return true;
@@ -200,7 +200,7 @@ int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buff
resplen = 0;
if ( !tud_msc_test_unit_ready_cb(lun) )
{
// not ready response with Failed status and sense key = not ready
// Failed status response
resplen = - 1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
@@ -214,7 +214,14 @@ int32_t proc_builtin_scsi(uint8_t lun, uint8_t const scsi_cmd[16], uint8_t* buff
if (tud_msc_start_stop_cb)
{
scsi_start_stop_unit_t const * start_stop = (scsi_start_stop_unit_t const *) scsi_cmd;
tud_msc_start_stop_cb(lun, start_stop->power_condition, start_stop->start, start_stop->load_eject);
if ( !tud_msc_start_stop_cb(lun, start_stop->power_condition, start_stop->start, start_stop->load_eject) )
{
// Failed status response
resplen = - 1;
// If sense key is not set by callback, default to Logical Unit Not Ready, Cause Not Reportable
if ( _mscd_itf.sense_key == 0 ) tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x04, 0x00);
}
}
break;
@@ -417,7 +424,7 @@ bool mscd_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t
// failed but senskey is not set: default to Illegal Request
if ( p_msc->sense_key == 0 ) tud_msc_set_sense(p_cbw->lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00);
/// Stall bulk In if needed
// Stall bulk In if needed
if (p_cbw->total_bytes) usbd_edpt_stall(rhport, p_msc->ep_in);
}
else
@@ -107,7 +107,7 @@ TU_ATTR_WEAK void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16
/**
* Invoked when received an SCSI command not in built-in list below.
* - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, PREVENT_ALLOW_MEDIUM_REMOVE, MODE_SENSE6, REQUEST_SENSE
* - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE
* - READ10 and WRITE10 has their own callbacks
*
* \param[in] lun Logical unit number
@@ -131,7 +131,7 @@ TU_ATTR_WEAK uint8_t tud_msc_get_maxlun_cb(void);
// Invoked when received Start Stop Unit command
// - Start = 0 : stopped power mode, if load_eject = 1 : unload disk storage
// - Start = 1 : active mode, if load_eject = 1 : load disk storage
TU_ATTR_WEAK void tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject);
TU_ATTR_WEAK bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, bool load_eject);
// Invoked when Read10 command is complete
TU_ATTR_WEAK void tud_msc_read10_complete_cb(uint8_t lun);
@@ -151,12 +151,12 @@ TU_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);
void mscd_init (void);
void mscd_reset (uint8_t rhport);
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_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);
#ifdef __cplusplus
}
@@ -0,0 +1,218 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#include "tusb_option.h"
#if (TUSB_OPT_DEVICE_ENABLED && CFG_TUD_VENDOR)
#include "vendor_device.h"
#include "device/usbd_pvt.h"
//--------------------------------------------------------------------+
// MACRO CONSTANT TYPEDEF
//--------------------------------------------------------------------+
typedef struct
{
uint8_t itf_num;
uint8_t ep_in;
uint8_t ep_out;
/*------------- From this point, data is not cleared by bus reset -------------*/
tu_fifo_t rx_ff;
tu_fifo_t tx_ff;
uint8_t rx_ff_buf[CFG_TUD_VENDOR_RX_BUFSIZE];
uint8_t tx_ff_buf[CFG_TUD_VENDOR_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_VENDOR_EPSIZE];
CFG_TUSB_MEM_ALIGN uint8_t epin_buf[CFG_TUD_VENDOR_EPSIZE];
} vendord_interface_t;
CFG_TUSB_MEM_SECTION static vendord_interface_t _vendord_itf[CFG_TUD_VENDOR];
#define ITF_MEM_RESET_SIZE offsetof(vendord_interface_t, rx_ff)
bool tud_vendor_n_mounted (uint8_t itf)
{
return _vendord_itf[itf].ep_in && _vendord_itf[itf].ep_out;
}
uint32_t tud_vendor_n_available (uint8_t itf)
{
return tu_fifo_count(&_vendord_itf[itf].rx_ff);
}
bool tud_vendor_n_peek(uint8_t itf, int pos, uint8_t* u8)
{
return tu_fifo_peek_at(&_vendord_itf[itf].rx_ff, pos, u8);
}
//--------------------------------------------------------------------+
// Read API
//--------------------------------------------------------------------+
static void _prep_out_transaction (vendord_interface_t* p_itf)
{
// skip if previous transfer not complete
if ( usbd_edpt_busy(TUD_OPT_RHPORT, p_itf->ep_out) ) return;
// Prepare for incoming data but only allow what we can store in the ring buffer.
uint16_t max_read = tu_fifo_remaining(&p_itf->rx_ff);
if ( max_read >= CFG_TUD_VENDOR_EPSIZE )
{
usbd_edpt_xfer(TUD_OPT_RHPORT, p_itf->ep_out, p_itf->epout_buf, CFG_TUD_VENDOR_EPSIZE);
}
}
uint32_t tud_vendor_n_read (uint8_t itf, void* buffer, uint32_t bufsize)
{
vendord_interface_t* p_itf = &_vendord_itf[itf];
uint32_t num_read = tu_fifo_read_n(&p_itf->rx_ff, buffer, bufsize);
_prep_out_transaction(p_itf);
return num_read;
}
//--------------------------------------------------------------------+
// Write API
//--------------------------------------------------------------------+
static bool maybe_transmit(vendord_interface_t* p_itf)
{
// skip if previous transfer not complete
TU_VERIFY( !usbd_edpt_busy(TUD_OPT_RHPORT, p_itf->ep_in) );
uint16_t count = tu_fifo_read_n(&p_itf->tx_ff, p_itf->epin_buf, CFG_TUD_VENDOR_EPSIZE);
if (count > 0)
{
TU_ASSERT( usbd_edpt_xfer(TUD_OPT_RHPORT, p_itf->ep_in, p_itf->epin_buf, count) );
}
return true;
}
uint32_t tud_vendor_n_write (uint8_t itf, void const* buffer, uint32_t bufsize)
{
vendord_interface_t* p_itf = &_vendord_itf[itf];
uint16_t ret = tu_fifo_write_n(&p_itf->tx_ff, buffer, bufsize);
maybe_transmit(p_itf);
return ret;
}
//--------------------------------------------------------------------+
// USBD Driver API
//--------------------------------------------------------------------+
void vendord_init(void)
{
tu_memclr(_vendord_itf, sizeof(_vendord_itf));
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++)
{
vendord_interface_t* p_itf = &_vendord_itf[i];
// config fifo
tu_fifo_config(&p_itf->rx_ff, p_itf->rx_ff_buf, CFG_TUD_VENDOR_RX_BUFSIZE, 1, false);
tu_fifo_config(&p_itf->tx_ff, p_itf->tx_ff_buf, CFG_TUD_VENDOR_TX_BUFSIZE, 1, false);
#if CFG_FIFO_MUTEX
tu_fifo_config_mutex(&p_itf->rx_ff, osal_mutex_create(&p_itf->rx_ff_mutex));
tu_fifo_config_mutex(&p_itf->tx_ff, osal_mutex_create(&p_itf->tx_ff_mutex));
#endif
}
}
void vendord_reset(uint8_t rhport)
{
(void) rhport;
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++)
{
vendord_interface_t* p_itf = &_vendord_itf[i];
tu_memclr(p_itf, ITF_MEM_RESET_SIZE);
tu_fifo_clear(&p_itf->rx_ff);
tu_fifo_clear(&p_itf->tx_ff);
}
}
bool vendord_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_len)
{
// Find available interface
vendord_interface_t* p_vendor = NULL;
for(uint8_t i=0; i<CFG_TUD_VENDOR; i++)
{
if ( _vendord_itf[i].ep_in == 0 && _vendord_itf[i].ep_out == 0 )
{
p_vendor = &_vendord_itf[i];
break;
}
}
TU_VERIFY(p_vendor);
// Open endpoint pair with usbd helper
TU_ASSERT(usbd_open_edpt_pair(rhport, tu_desc_next(itf_desc), 2, TUSB_XFER_BULK, &p_vendor->ep_out, &p_vendor->ep_in));
p_vendor->itf_num = itf_desc->bInterfaceNumber;
(*p_len) = sizeof(tusb_desc_interface_t) + 2*sizeof(tusb_desc_endpoint_t);
// Prepare for incoming data
TU_ASSERT(usbd_edpt_xfer(rhport, p_vendor->ep_out, p_vendor->epout_buf, sizeof(p_vendor->epout_buf)));
return true;
}
bool vendord_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;
vendord_interface_t* p_itf = &_vendord_itf[itf];
if ( ep_addr == p_itf->ep_out )
{
// Receive new data
tu_fifo_write_n(&p_itf->rx_ff, p_itf->epout_buf, xferred_bytes);
// Invoked callback if any
if (tud_vendor_rx_cb) tud_vendor_rx_cb(itf);
_prep_out_transaction(p_itf);
}
else if ( ep_addr == p_itf->ep_in )
{
// Send complete, try to send more if possible
maybe_transmit(p_itf);
}
return true;
}
#endif
@@ -0,0 +1,121 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2019 Ha Thach (tinyusb.org)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* This file is part of the TinyUSB stack.
*/
#ifndef _TUSB_VENDOR_DEVICE_H_
#define _TUSB_VENDOR_DEVICE_H_
#include "common/tusb_common.h"
#include "device/usbd.h"
#ifndef CFG_TUD_VENDOR_EPSIZE
#define CFG_TUD_VENDOR_EPSIZE 64
#endif
#ifdef __cplusplus
extern "C" {
#endif
//--------------------------------------------------------------------+
// Application API (Multiple Interfaces)
//--------------------------------------------------------------------+
bool tud_vendor_n_mounted (uint8_t itf);
uint32_t tud_vendor_n_available (uint8_t itf);
uint32_t tud_vendor_n_read (uint8_t itf, void* buffer, uint32_t bufsize);
bool tud_vendor_n_peek (uint8_t itf, int pos, uint8_t* u8);
uint32_t tud_vendor_n_write (uint8_t itf, void const* buffer, uint32_t bufsize);
static inline
uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str);
//--------------------------------------------------------------------+
// Application API (Single Port)
//--------------------------------------------------------------------+
static inline bool tud_vendor_mounted (void);
static inline uint32_t tud_vendor_available (void);
static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize);
static inline bool tud_vendor_peek (int pos, uint8_t* u8);
static inline uint32_t tud_vendor_write (void const* buffer, uint32_t bufsize);
static inline uint32_t tud_vendor_write_str (char const* str);
//--------------------------------------------------------------------+
// Application Callback API (weak is optional)
//--------------------------------------------------------------------+
// Invoked when received new data
TU_ATTR_WEAK void tud_vendor_rx_cb(uint8_t itf);
//--------------------------------------------------------------------+
// Inline Functions
//--------------------------------------------------------------------+
static inline uint32_t tud_vendor_n_write_str (uint8_t itf, char const* str)
{
return tud_vendor_n_write(itf, str, strlen(str));
}
static inline bool tud_vendor_mounted (void)
{
return tud_vendor_n_mounted(0);
}
static inline uint32_t tud_vendor_available (void)
{
return tud_vendor_n_available(0);
}
static inline uint32_t tud_vendor_read (void* buffer, uint32_t bufsize)
{
return tud_vendor_n_read(0, buffer, bufsize);
}
static inline bool tud_vendor_peek (int pos, uint8_t* u8)
{
return tud_vendor_n_peek(0, pos, u8);
}
static inline uint32_t tud_vendor_write (void const* buffer, uint32_t bufsize)
{
return tud_vendor_n_write(0, buffer, bufsize);
}
static inline uint32_t tud_vendor_write_str (char const* str)
{
return tud_vendor_n_write_str(0, str);
}
//--------------------------------------------------------------------+
// Internal Class Driver API
//--------------------------------------------------------------------+
void vendord_init(void);
void vendord_reset(uint8_t rhport);
bool vendord_open(uint8_t rhport, tusb_desc_interface_t const * itf_desc, uint16_t *p_length);
bool vendord_xfer_cb(uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
#ifdef __cplusplus
}
#endif
#endif /* _TUSB_VENDOR_DEVICE_H_ */
@@ -146,9 +146,10 @@ static inline bool tu_bit_test (uint32_t value, uint8_t n) { return (value &
* 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_
#ifndef TU_ARGS_NUM
#define TU_ARGS_NUM(...) NARG_(_0, ##__VA_ARGS__,_RSEQ_N())
#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, \
@@ -68,46 +68,57 @@ typedef enum
TUSB_DIR_IN_MASK = 0x80
}tusb_dir_t;
/// USB Descriptor Types (section 9.4 table 9-5)
/// USB Descriptor Types
typedef enum
{
TUSB_DESC_DEVICE = 0x01 ,
TUSB_DESC_CONFIGURATION = 0x02 ,
TUSB_DESC_STRING = 0x03 ,
TUSB_DESC_INTERFACE = 0x04 ,
TUSB_DESC_ENDPOINT = 0x05 ,
TUSB_DESC_DEVICE_QUALIFIER = 0x06 ,
TUSB_DESC_OTHER_SPEED_CONFIG = 0x07 ,
TUSB_DESC_INTERFACE_POWER = 0x08 ,
TUSB_DESC_OTG = 0x09 ,
TUSB_DESC_DEBUG = 0x0A ,
TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B ,
TUSB_DESC_CLASS_SPECIFIC = 0x24
TUSB_DESC_DEVICE = 0x01,
TUSB_DESC_CONFIGURATION = 0x02,
TUSB_DESC_STRING = 0x03,
TUSB_DESC_INTERFACE = 0x04,
TUSB_DESC_ENDPOINT = 0x05,
TUSB_DESC_DEVICE_QUALIFIER = 0x06,
TUSB_DESC_OTHER_SPEED_CONFIG = 0x07,
TUSB_DESC_INTERFACE_POWER = 0x08,
TUSB_DESC_OTG = 0x09,
TUSB_DESC_DEBUG = 0x0A,
TUSB_DESC_INTERFACE_ASSOCIATION = 0x0B,
TUSB_DESC_BOS = 0x0F,
TUSB_DESC_DEVICE_CAPABILITY = 0x10,
// Class Specific Descriptor
TUSB_DESC_CS_DEVICE = 0x21,
TUSB_DESC_CS_CONFIGURATION = 0x22,
TUSB_DESC_CS_STRING = 0x23,
TUSB_DESC_CS_INTERFACE = 0x24,
TUSB_DESC_CS_ENDPOINT = 0x25,
TUSB_DESC_SUPERSPEED_ENDPOINT_COMPANION = 0x30,
TUSB_DESC_SUPERSPEED_ISO_ENDPOINT_COMPANION = 0x31
}tusb_desc_type_t;
typedef enum
{
TUSB_REQ_GET_STATUS =0 , ///< 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_REQ_GET_STATUS = 0 ,
TUSB_REQ_CLEAR_FEATURE = 1 ,
TUSB_REQ_RESERVED = 2 ,
TUSB_REQ_SET_FEATURE = 3 ,
TUSB_REQ_RESERVED2 = 4 ,
TUSB_REQ_SET_ADDRESS = 5 ,
TUSB_REQ_GET_DESCRIPTOR = 6 ,
TUSB_REQ_SET_DESCRIPTOR = 7 ,
TUSB_REQ_GET_CONFIGURATION = 8 ,
TUSB_REQ_SET_CONFIGURATION = 9 ,
TUSB_REQ_GET_INTERFACE = 10 ,
TUSB_REQ_SET_INTERFACE = 11 ,
TUSB_REQ_SYNCH_FRAME = 12
}tusb_request_code_t;
typedef enum
{
TUSB_REQ_FEATURE_EDPT_HALT = 0,
TUSB_REQ_FEATURE_EDPT_HALT = 0,
TUSB_REQ_FEATURE_REMOTE_WAKEUP = 1,
TUSB_REQ_FEATURE_TEST_MODE = 2
TUSB_REQ_FEATURE_TEST_MODE = 2
}tusb_request_feature_selector_t;
typedef enum
@@ -162,6 +173,26 @@ typedef enum
MISC_PROTOCOL_IAD = 1
}misc_protocol_type_t;
typedef enum
{
DEVICE_CAPABILITY_WIRELESS_USB = 0x01,
DEVICE_CAPABILITY_USB20_EXTENSION = 0x02,
DEVICE_CAPABILITY_SUPERSPEED_USB = 0x03,
DEVICE_CAPABILITY_CONTAINER_id = 0x04,
DEVICE_CAPABILITY_PLATFORM = 0x05,
DEVICE_CAPABILITY_POWER_DELIVERY = 0x06,
DEVICE_CAPABILITY_BATTERY_INFO = 0x07,
DEVICE_CAPABILITY_PD_CONSUMER_PORT = 0x08,
DEVICE_CAPABILITY_PD_PROVIDER_PORT = 0x09,
DEVICE_CAPABILITY_SUPERSPEED_PLUS = 0x0A,
DEVICE_CAPABILITY_PRECESION_TIME_MEASUREMENT = 0x0B,
DEVICE_CAPABILITY_WIRELESS_USB_EXT = 0x0C,
DEVICE_CAPABILITY_BILLBOARD = 0x0D,
DEVICE_CAPABILITY_AUTHENTICATION = 0x0E,
DEVICE_CAPABILITY_BILLBOARD_EX = 0x0F,
DEVICE_CAPABILITY_CONFIGURATION_SUMMARY = 0x10
}device_capability_type_t;
enum {
TUSB_DESC_CONFIG_ATT_REMOTE_WAKEUP = TU_BIT(5),
TUSB_DESC_CONFIG_ATT_SELF_POWERED = TU_BIT(6),
@@ -195,11 +226,25 @@ enum
INTERFACE_INVALID_NUMBER = 0xff
};
typedef enum
{
MS_OS_20_SET_HEADER_DESCRIPTOR = 0x00,
MS_OS_20_SUBSET_HEADER_CONFIGURATION = 0x01,
MS_OS_20_SUBSET_HEADER_FUNCTION = 0x02,
MS_OS_20_FEATURE_COMPATBLE_ID = 0x03,
MS_OS_20_FEATURE_REG_PROPERTY = 0x04,
MS_OS_20_FEATURE_MIN_RESUME_TIME = 0x05,
MS_OS_20_FEATURE_MODEL_ID = 0x06,
MS_OS_20_FEATURE_CCGP_DEVICE = 0x07,
MS_OS_20_FEATURE_VENDOR_REVISION = 0x08
} microsoft_os_20_type_t;
//--------------------------------------------------------------------+
// STANDARD DESCRIPTORS
// USB Descriptors
//--------------------------------------------------------------------+
/// USB Standard Device Descriptor (section 9.6.1, table 9-8)
/// USB Device Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes.
@@ -221,7 +266,16 @@ typedef struct TU_ATTR_PACKED
uint8_t bNumConfigurations ; ///< Number of possible configurations.
} tusb_desc_device_t;
/// USB Standard Configuration Descriptor (section 9.6.1 table 9-10) */
// USB Binary Device Object Store (BOS) Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< CONFIGURATION Descriptor Type
uint16_t wTotalLength ; ///< Total length of data returned for this descriptor
uint8_t bNumDeviceCaps ; ///< Number of device capability descriptors in the BOS
} tusb_desc_bos_t;
/// USB Configuration Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
@@ -235,7 +289,7 @@ typedef struct TU_ATTR_PACKED
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)
/// USB Interface Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
@@ -250,7 +304,7 @@ typedef struct TU_ATTR_PACKED
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)
/// USB Endpoint Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
@@ -274,7 +328,7 @@ typedef struct TU_ATTR_PACKED
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)
/// USB Other Speed Configuration Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
@@ -288,7 +342,7 @@ typedef struct TU_ATTR_PACKED
uint8_t bMaxPower ; ///< Same as Configuration descriptor
} tusb_desc_other_speed_t;
/// USB Device Qualifier Descriptor (section 9.6.1 table 9-9)
/// USB Device Qualifier Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of descriptor
@@ -319,13 +373,7 @@ typedef struct TU_ATTR_PACKED
uint8_t iFunction ; ///< Index of the string descriptor describing the interface association.
} tusb_desc_interface_assoc_t;
/// USB Header Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
uint8_t bDescriptorType ; ///< Descriptor Type
} tusb_desc_header_t;
// USB String Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength ; ///< Size of this descriptor in bytes
@@ -333,6 +381,25 @@ typedef struct TU_ATTR_PACKED
uint16_t unicode_string[];
} tusb_desc_string_t;
// USB Binary Device Object Store (BOS)
typedef struct TU_ATTR_PACKED
{
uint8_t bLength;
uint8_t bDescriptorType ;
uint8_t bDevCapabilityType;
uint8_t bReserved;
uint8_t PlatformCapabilityUUID[16];
uint8_t CapabilityData[];
} tusb_desc_bos_platform_t;
// USB WebuSB URL Descriptor
typedef struct TU_ATTR_PACKED
{
uint8_t bLength;
uint8_t bDescriptorType;
uint8_t bScheme;
char url[];
} tusb_desc_webusb_url_t;
/*------------------------------------------------------------------*/
/* Types
@@ -409,7 +476,7 @@ static inline uint8_t tu_desc_len(void const* desc)
#define TUD_DESC_STR_HEADER(_chr_count) ( (uint16_t) ( (TUSB_DESC_STRING << 8 ) | TUD_DESC_STRLEN(_chr_count)) )
// 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__ }
#define TUD_DESC_STRCONV( ... ) (const uint16_t[]) { TUD_DESC_STR_HEADER(TU_ARGS_NUM(__VA_ARGS__)), __VA_ARGS__ }
#ifdef __cplusplus
}
@@ -51,8 +51,8 @@
//--------------------------------------------------------------------+
#if CFG_TUSB_DEBUG
#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__)
#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()
@@ -61,11 +61,11 @@
// 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)
#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()
@@ -80,22 +80,23 @@
#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)
#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)
#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)
/*------------------------------------------------------------------*/
@@ -141,7 +142,6 @@
#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
@@ -110,9 +110,6 @@ bool dcd_edpt_open (uint8_t rhport, tusb_desc_endpoint_t const * p_endpoi
// Submit a transfer, When complete dcd_event_xfer_complete() is invoked to notify the stack
bool dcd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
// Check if endpoint transferring is complete (TODO remove)
bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr);
// Stall endpoint
void dcd_edpt_stall (uint8_t rhport, uint8_t ep_addr);
@@ -31,6 +31,7 @@
#include "tusb.h"
#include "usbd.h"
#include "device/usbd_pvt.h"
#include "dcd.h"
#ifndef CFG_TUD_TASK_QUEUE_SZ
#define CFG_TUD_TASK_QUEUE_SZ 16
@@ -42,20 +43,20 @@
typedef struct {
struct TU_ATTR_PACKED
{
volatile uint8_t connected : 1;
volatile uint8_t configured : 1;
volatile uint8_t suspended : 1;
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 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_map[2]; // bit mask for busy endpoint
uint8_t ep_stall_map[2]; // bit map 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 )
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 };
@@ -66,80 +67,80 @@ static usbd_device_t _usbd_dev = { 0 };
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);
void (* init ) (void);
void (* reset ) (uint8_t rhport);
bool (* open ) (uint8_t rhport, tusb_desc_interface_t const * desc_intf, uint16_t* p_length);
bool (* control_request ) (uint8_t rhport, tusb_control_request_t const * request);
bool (* control_complete ) (uint8_t rhport, tusb_control_request_t const * request);
bool (* xfer_cb ) (uint8_t rhport, uint8_t ep_addr, xfer_result_t event, uint32_t xferred_bytes);
void (* sof ) (uint8_t rhport);
} usbd_class_driver_t;
static usbd_class_driver_t const usbd_class_drivers[] =
{
#if CFG_TUD_CDC
{
.class_code = TUSB_CLASS_CDC,
.init = cdcd_init,
.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
},
{
.class_code = TUSB_CLASS_CDC,
.init = cdcd_init,
.reset = cdcd_reset,
.open = cdcd_open,
.control_request = cdcd_control_request,
.control_complete = cdcd_control_complete,
.xfer_cb = cdcd_xfer_cb,
.sof = NULL
},
#endif
#if CFG_TUD_MSC
{
.class_code = TUSB_CLASS_MSC,
.init = mscd_init,
.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
},
{
.class_code = TUSB_CLASS_MSC,
.init = mscd_init,
.reset = mscd_reset,
.open = mscd_open,
.control_request = mscd_control_request,
.control_complete = mscd_control_complete,
.xfer_cb = mscd_xfer_cb,
.sof = NULL
},
#endif
#if CFG_TUD_HID
{
.class_code = TUSB_CLASS_HID,
.init = hidd_init,
.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
},
{
.class_code = TUSB_CLASS_HID,
.init = hidd_init,
.reset = hidd_reset,
.open = hidd_open,
.control_request = hidd_control_request,
.control_complete = hidd_control_complete,
.xfer_cb = hidd_xfer_cb,
.sof = NULL
},
#endif
#if CFG_TUD_MIDI
{
.class_code = TUSB_CLASS_AUDIO,
.init = midid_init,
.open = midid_open,
.control_request = midid_control_request,
.control_request_complete = midid_control_request_complete,
.xfer_cb = midid_xfer_cb,
.sof = NULL,
.reset = midid_reset
},
{
.class_code = TUSB_CLASS_AUDIO,
.init = midid_init,
.open = midid_open,
.reset = midid_reset,
.control_request = midid_control_request,
.control_complete = midid_control_complete,
.xfer_cb = midid_xfer_cb,
.sof = NULL
},
#endif
#if CFG_TUD_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
},
#if CFG_TUD_VENDOR
{
.class_code = TUSB_CLASS_VENDOR_SPECIFIC,
.init = vendord_init,
.reset = vendord_reset,
.open = vendord_open,
.control_request = tud_vendor_control_request_cb,
.control_complete = tud_vendor_control_complete_cb,
.xfer_cb = vendord_xfer_cb,
.sof = NULL
},
#endif
};
@@ -236,7 +237,6 @@ static void usbd_reset(uint8_t rhport)
while(1) // the mainloop
{
application_code();
tud_task(); // tinyusb device task
}
}
@@ -346,6 +346,15 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
{
usbd_control_set_complete_callback(NULL);
// Vendor request
if ( p_request->bmRequestType_bit.type == TUSB_REQ_TYPE_VENDOR )
{
TU_VERIFY(tud_vendor_control_request_cb);
if (tud_vendor_control_complete_cb) usbd_control_set_complete_callback(tud_vendor_control_complete_cb);
return tud_vendor_control_request_cb(rhport, p_request);
}
switch ( p_request->bmRequestType_bit.recipient )
{
//------------- Device Requests e.g in enumeration -------------//
@@ -369,7 +378,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
case TUSB_REQ_GET_CONFIGURATION:
{
uint8_t cfgnum = _usbd_dev.configured ? 1 : 0;
usbd_control_xfer(rhport, p_request, &cfgnum, 1);
tud_control_xfer(rhport, p_request, &cfgnum, 1);
}
break;
@@ -381,7 +390,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
_usbd_dev.configured = cfg_num ? 1 : 0;
if ( cfg_num ) TU_ASSERT( process_set_config(rhport, cfg_num) );
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
}
break;
@@ -395,7 +404,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// Host may enable remote wake up before suspending especially HID device
_usbd_dev.remote_wakeup_en = true;
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
case TUSB_REQ_CLEAR_FEATURE:
@@ -404,7 +413,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// Host may disable remote wake up after resuming
_usbd_dev.remote_wakeup_en = false;
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
case TUSB_REQ_GET_STATUS:
@@ -413,7 +422,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
// - 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);
tud_control_xfer(rhport, p_request, &status, 2);
}
break;
@@ -430,10 +439,34 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
TU_VERIFY(drvid < USBD_CLASS_DRIVER_COUNT);
usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_request_complete );
switch ( p_request->bRequest )
{
case TUSB_REQ_GET_INTERFACE:
{
// TODO not support alternate interface yet
uint8_t alternate = 0;
tud_control_xfer(rhport, p_request, &alternate, 1);
}
break;
// stall control endpoint if driver return false
return usbd_class_drivers[drvid].control_request(rhport, p_request);
case TUSB_REQ_SET_INTERFACE:
{
uint8_t alternate = (uint8_t) p_request->wValue;
// TODO not support alternate interface yet
TU_ASSERT(alternate == 0);
tud_control_status(rhport, p_request);
}
break;
default:
// forward to class driver
// stall control endpoint if driver return false
usbd_control_set_complete_callback(usbd_class_drivers[drvid].control_complete);
TU_ASSERT(usbd_class_drivers[drvid].control_request(rhport, p_request));
break;
}
}
break;
@@ -447,7 +480,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
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);
tud_control_xfer(rhport, p_request, &status, 2);
}
break;
@@ -456,7 +489,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
{
usbd_edpt_clear_stall(rhport, tu_u16_low(p_request->wIndex));
}
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
case TUSB_REQ_SET_FEATURE:
@@ -464,7 +497,7 @@ static bool process_control_request(uint8_t rhport, tusb_control_request_t const
{
usbd_edpt_stall(rhport, tu_u16_low(p_request->wIndex));
}
usbd_control_status(rhport, p_request);
tud_control_status(rhport, p_request);
break;
// Unknown/Unsupported request
@@ -519,7 +552,7 @@ static bool process_set_config(uint8_t rhport, uint8_t cfg_num)
_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( 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);
@@ -562,13 +595,29 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
switch(desc_type)
{
case TUSB_DESC_DEVICE:
return usbd_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), sizeof(tusb_desc_device_t));
return tud_control_xfer(rhport, p_request, (void*) tud_descriptor_device_cb(), sizeof(tusb_desc_device_t));
break;
case TUSB_DESC_BOS:
{
// requested by host if USB > 2.0 ( i.e 2.1 or 3.x )
if (!tud_descriptor_bos_cb) return false;
tusb_desc_bos_t const* desc_bos = (tusb_desc_bos_t const*) tud_descriptor_bos_cb();
uint16_t total_len;
memcpy(&total_len, &desc_bos->wTotalLength, 2); // possibly mis-aligned memory
return tud_control_xfer(rhport, p_request, (void*) desc_bos, total_len);
}
break;
case TUSB_DESC_CONFIGURATION:
{
tusb_desc_configuration_t const* desc_config = (tusb_desc_configuration_t const*) tud_descriptor_configuration_cb(desc_index);
return usbd_control_xfer(rhport, p_request, (void*) desc_config, desc_config->wTotalLength);
uint16_t total_len;
memcpy(&total_len, &desc_config->wTotalLength, 2); // possibly mis-aligned memory
return tud_control_xfer(rhport, p_request, (void*) desc_config, total_len);
}
break;
@@ -576,8 +625,8 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
// String Descriptor always uses the desc set from user
if ( desc_index == 0xEE )
{
// The 0xEE index string is a Microsoft USB extension.
// It can be used to tell Windows what driver it should use for the device !!!
// The 0xEE index string is a Microsoft OS Descriptors.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/microsoft-defined-usb-descriptors
return false;
}else
{
@@ -585,7 +634,7 @@ static bool process_get_descriptor(uint8_t rhport, tusb_control_request_t const
TU_ASSERT(desc_str);
// first byte of descriptor is its size
return usbd_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]);
return tud_control_xfer(rhport, p_request, (void*) desc_str, desc_str[0]);
}
break;
@@ -35,7 +35,7 @@
#endif
#include "common/tusb_common.h"
#include "device/dcd.h"
#include "dcd.h"
//--------------------------------------------------------------------+
// Application API
@@ -59,6 +59,14 @@ static inline bool tud_ready(void)
// Remote wake up host, only if suspended and enabled by host
bool tud_remote_wakeup(void);
// Carry out Data and Status stage of control transfer
// - If len = 0, it is equivalent to sending status only
// - If len > wLength : it will be truncated
bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len);
// Send STATUS (zero length) packet
bool tud_control_status(uint8_t rhport, tusb_control_request_t const * request);
//--------------------------------------------------------------------+
// Application Callbacks (WEAK is optional)
//--------------------------------------------------------------------+
@@ -67,6 +75,10 @@ bool tud_remote_wakeup(void);
// Application return pointer to descriptor
uint8_t const * tud_descriptor_device_cb(void);
// Invoked when received GET BOS DESCRIPTOR request
// Application return pointer to descriptor
TU_ATTR_WEAK uint8_t const * tud_descriptor_bos_cb(void);
// Invoked when received GET CONFIGURATION DESCRIPTOR request
// Application return pointer to descriptor, whose contents must exist long enough for transfer to complete
uint8_t const * tud_descriptor_configuration_cb(uint8_t index);
@@ -88,10 +100,59 @@ TU_ATTR_WEAK void tud_suspend_cb(bool remote_wakeup_en);
// Invoked when usb bus is resumed
TU_ATTR_WEAK void tud_resume_cb(void);
// Invoked when received control request with VENDOR TYPE
TU_ATTR_WEAK bool tud_vendor_control_request_cb(uint8_t rhport, tusb_control_request_t const * request);
TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_request_t const * request);
//--------------------------------------------------------------------+
// Interface Descriptor Template
// Binary Device Object Store (BOS) Descriptor Templates
//--------------------------------------------------------------------+
#define TUD_BOS_DESC_LEN 5
// total length, number of device caps
#define TUD_BOS_DESCRIPTOR(_total_len, _caps_num) \
5, TUSB_DESC_BOS, U16_TO_U8S_LE(_total_len), _caps_num
// Device Capability Platform 128-bit UUID + Data
#define TUD_BOS_PLATFORM_DESCRIPTOR(...) \
4+TU_ARGS_NUM(__VA_ARGS__), TUSB_DESC_DEVICE_CAPABILITY, DEVICE_CAPABILITY_PLATFORM, 0x00, __VA_ARGS__
//------------- WebUSB BOS Platform -------------//
// Descriptor Length
#define TUD_BOS_WEBUSB_DESC_LEN 24
// Vendor Code, iLandingPage
#define TUD_BOS_WEBUSB_DESCRIPTOR(_vendor_code, _ipage) \
TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_WEBUSB_UUID, U16_TO_U8S_LE(0x0100), _vendor_code, _ipage)
#define TUD_BOS_WEBUSB_UUID \
0x38, 0xB6, 0x08, 0x34, 0xA9, 0x09, 0xA0, 0x47, \
0x8B, 0xFD, 0xA0, 0x76, 0x88, 0x15, 0xB6, 0x65
//------------- Microsoft OS 2.0 Platform -------------//
#define TUD_BOS_MICROSOFT_OS_DESC_LEN 28
// Total Length of descriptor set, vendor code
#define TUD_BOS_MS_OS_20_DESCRIPTOR(_desc_set_len, _vendor_code) \
TUD_BOS_PLATFORM_DESCRIPTOR(TUD_BOS_MS_OS_20_UUID, U32_TO_U8S_LE(0x06030000), U16_TO_U8S_LE(_desc_set_len), _vendor_code, 0)
#define TUD_BOS_MS_OS_20_UUID \
0xDF, 0x60, 0xDD, 0xD8, 0x89, 0x45, 0xC7, 0x4C, \
0x9C, 0xD2, 0x65, 0x9D, 0x9E, 0x64, 0x8A, 0x9F
//------------- WebUSB URL -------------//
// used to init tusb_desc_webusb_url_t
#define TUD_WEBUSB_URL_DESCRIPTOR(_scheme, _url) \
{ 3 + sizeof(_url) - 1, 3, _scheme, _url }
//--------------------------------------------------------------------+
// Configuration & Interface Descriptor Templates
//--------------------------------------------------------------------+
//------------- Configuration -------------//
#define TUD_CONFIG_DESC_LEN (9)
// Interface count, string index, total length, attribute, power in mA
@@ -111,13 +172,13 @@ TU_ATTR_WEAK void tud_resume_cb(void);
/* 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),\
5, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_HEADER, U16_TO_U8S_LE(0x0120),\
/* CDC Call */\
5, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_CALL_MANAGEMENT, 0, (_itfnum) + 1,\
5, TUSB_DESC_CS_INTERFACE, 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,\
4, TUSB_DESC_CS_INTERFACE, CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT, 2,\
/* CDC Union */\
5, TUSB_DESC_CLASS_SPECIFIC, CDC_FUNC_DESC_UNION, _itfnum, (_itfnum) + 1,\
5, TUSB_DESC_CS_INTERFACE, 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 */\
@@ -160,16 +221,63 @@ TU_ATTR_WEAK void tud_resume_cb(void);
#define TUD_HID_INOUT_DESC_LEN (9 + 9 + 7 + 7)
// HID Input & Output descriptor
// Interface number, string index, protocol, report descriptor len, EP In & Out address, size & polling interval
#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epin, _epout, _epsize, _ep_interval) \
// Interface number, string index, protocol, report descriptor len, EP OUT & IN address, size & polling interval
#define TUD_HID_INOUT_DESCRIPTOR(_itfnum, _stridx, _boot_protocol, _report_desc_len, _epout, _epin, _epsize, _ep_interval) \
/* Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_HID, (_boot_protocol) ? HID_SUBCLASS_BOOT : 0, _boot_protocol, _stridx,\
/* HID descriptor */\
9, HID_DESC_TYPE_HID, U16_TO_U8S_LE(0x0111), 0, 1, HID_DESC_TYPE_REPORT, U16_TO_U8S_LE(_report_desc_len),\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval, \
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_INTERRUPT, U16_TO_U8S_LE(_epsize), _ep_interval
//------------- MIDI -------------//
// Length of template descriptor (96 bytes)
#define TUD_MIDI_DESC_LEN (9 + 9 + 9 + 7 + 6 + 6 + 9 + 9 + 7 + 5 + 7 + 5)
// MIDI simple descriptor
// - 1 Embedded Jack In connected to 1 External Jack Out
// - 1 Embedded Jack out connected to 1 External Jack In
#define TUD_MIDI_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
/* Audio Control (AC) Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 0, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_CONTROL, AUDIO_PROTOCOL_V1, _stridx,\
/* AC Header */\
9, TUSB_DESC_CS_INTERFACE, AUDIO_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0009), 1, _itfnum+1,\
/* MIDI Streaming (MS) Interface */\
9, TUSB_DESC_INTERFACE, _itfnum+1, 0, 2, TUSB_CLASS_AUDIO, AUDIO_SUBCLASS_MIDI_STREAMING, AUDIO_PROTOCOL_V1, 0,\
/* MS Header */\
7, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_HEADER, U16_TO_U8S_LE(0x0100), U16_TO_U8S_LE(0x0025),\
/* MS In Jack (Embedded) */\
6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EMBEDDED, 1, 0,\
/* MS In Jack (External) */\
6, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_IN_JACK, MIDI_JACK_EXTERNAL, 2, 0,\
/* MS Out Jack (Embedded), connected to In Jack External */\
9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EMBEDDED, 3, 1, 2, 1, 0,\
/* MS Out Jack (External), connected to In Jack Embedded */\
9, TUSB_DESC_CS_INTERFACE, MIDI_CS_INTERFACE_OUT_JACK, MIDI_JACK_EXTERNAL, 4, 1, 1, 1, 0,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* MS Endpoint (connected to embedded jack in) */\
5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 1,\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* MS Endpoint (connected to embedded jack out) */\
5, TUSB_DESC_CS_ENDPOINT, MIDI_CS_ENDPOINT_GENERAL, 1, 3
//------------- Vendor -------------//
#define TUD_VENDOR_DESC_LEN (9+7+7)
// Interface number, string index, EP Out & IN address, EP size
#define TUD_VENDOR_DESCRIPTOR(_itfnum, _stridx, _epout, _epin, _epsize) \
/* Interface */\
9, TUSB_DESC_INTERFACE, _itfnum, 0, 2, TUSB_CLASS_VENDOR_SPECIFIC, 0x00, 0x00, _stridx,\
/* Endpoint Out */\
7, TUSB_DESC_ENDPOINT, _epout, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0,\
/* Endpoint In */\
7, TUSB_DESC_ENDPOINT, _epin, TUSB_XFER_BULK, U16_TO_U8S_LE(_epsize), 0
#ifdef __cplusplus
}
@@ -30,6 +30,7 @@
#include "tusb.h"
#include "device/usbd_pvt.h"
#include "dcd.h"
enum
{
@@ -58,7 +59,7 @@ void usbd_control_reset (uint8_t rhport)
tu_varclr(&_control_state);
}
bool usbd_control_status(uint8_t rhport, tusb_control_request_t const * request)
bool tud_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);
@@ -86,7 +87,7 @@ void usbd_control_set_complete_callback( bool (*fp) (uint8_t, tusb_control_reque
_control_state.complete_cb = fp;
}
bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len)
bool tud_control_xfer(uint8_t rhport, tusb_control_request_t const * request, void* buffer, uint16_t len)
{
_control_state.request = (*request);
_control_state.buffer = buffer;
@@ -102,7 +103,7 @@ bool usbd_control_xfer(uint8_t rhport, tusb_control_request_t const * request, v
}else
{
// Status stage
TU_ASSERT( usbd_control_status(rhport, request) );
TU_ASSERT( tud_control_status(rhport, request) );
}
return true;
@@ -138,7 +139,7 @@ bool usbd_control_xfer_cb (uint8_t rhport, uint8_t ep_addr, xfer_result_t result
if ( is_ok )
{
// Send status
TU_ASSERT( usbd_control_status(rhport, &_control_state.request) );
TU_ASSERT( tud_control_status(rhport, &_control_state.request) );
}else
{
// Stall both IN and OUT control endpoint
@@ -39,19 +39,13 @@ bool usbd_init (void);
// USBD Endpoint API
//--------------------------------------------------------------------+
// 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);
//bool usbd_edpt_open(uint8_t rhport, tusb_desc_endpoint_t const * p_endpoint_desc);
// Submit a usb transfer
bool usbd_edpt_xfer (uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
bool usbd_edpt_xfer(uint8_t rhport, uint8_t ep_addr, uint8_t * buffer, uint16_t total_bytes);
// Check if endpoint transferring is complete
bool usbd_edpt_busy (uint8_t rhport, uint8_t ep_addr);
bool usbd_edpt_busy(uint8_t rhport, uint8_t ep_addr);
void usbd_edpt_stall(uint8_t rhport, uint8_t ep_addr);
void usbd_edpt_clear_stall(uint8_t rhport, uint8_t ep_addr);
@@ -332,21 +332,6 @@ void dcd_edpt_clear_stall (uint8_t rhport, uint8_t ep_addr)
}
}
bool dcd_edpt_busy (uint8_t rhport, uint8_t ep_addr)
{
(void) rhport;
// USBD shouldn't check control endpoint state
if ( 0 == tu_edpt_number(ep_addr) ) return false;
uint8_t const epnum = tu_edpt_number(ep_addr);
uint8_t const dir = tu_edpt_dir(ep_addr);
xfer_td_t* xfer = get_td(epnum, dir);
return xfer->actual_len < xfer->total_len;
}
/*------------------------------------------------------------------*/
/* Interrupt Handler
*------------------------------------------------------------------*/
@@ -54,8 +54,8 @@
#include "class/cdc/cdc_host.h"
#endif
#if CFG_TUSB_HOST_CUSTOM_CLASS
#include "class/custom_host.h"
#if CFG_TUH_VENDOR
#include "class/vendor/vendor_host.h"
#endif
#endif
@@ -80,8 +80,8 @@
#include "class/midi/midi_device.h"
#endif
#if CFG_TUD_CUSTOM_CLASS
#include "class/custom/custom_device.h"
#if CFG_TUD_VENDOR
#include "class/vendor/vendor_device.h"
#endif
#endif
@@ -27,11 +27,10 @@
#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)
#define TUSB_VERSION_MAJOR 0
#define TUSB_VERSION_MINOR 5
#define TUSB_VERSION_REVISION 0
#define TUSB_VERSION_STRING TU_STRING(TUSB_VERSION_MAJOR) "." TU_STRING(TUSB_VERSION_MINOR) "." TU_STRING(TUSB_VERSION_REVISION)
/** \defgroup group_mcu Supported MCU
* \ref CFG_TUSB_MCU must be defined to one of these
@@ -162,8 +161,8 @@
#define CFG_TUD_MIDI 0
#endif
#ifndef CFG_TUD_CUSTOM_CLASS
#define CFG_TUD_CUSTOM_CLASS 0
#ifndef CFG_TUD_VENDOR
#define CFG_TUD_VENDOR 0
#endif
+13 -13
View File
@@ -42,7 +42,7 @@
#define CFG_TUSB_OS OPT_OS_FREERTOS
#define CFG_TUSB_MEM_SECTION
#define CFG_TUSB_MEM_ALIGN TU_ATTR_ALIGNED(4)
#define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4)))
//--------------------------------------------------------------------
// DEVICE CONFIGURATION
@@ -54,26 +54,26 @@
#define CFG_TUD_CDC 1
#define CFG_TUD_MSC 1
#define CFG_TUD_HID 1
#define CFG_TUD_MIDI 1
#define CFG_TUD_VENDOR 1
#define CFG_TUD_MIDI 0
#define CFG_TUD_CUSTOM_CLASS 0
//------------- CDC -------------//
// FIFO size of CDC TX and RX
// CDC FIFO size of TX and RX
#define CFG_TUD_CDC_RX_BUFSIZE 256
#define CFG_TUD_CDC_TX_BUFSIZE 256
//------------- MSC -------------//
// Buffer size of Device Mass storage
// MSC Buffer size of Device Mass storage
#define CFG_TUD_MSC_BUFSIZE 512
//------------- HID -------------//
// Should be sufficient to hold ID (if any) + Data
// HID buffer size Should be sufficient to hold ID (if any) + Data
#define CFG_TUD_HID_BUFSIZE 64
// MIDI FIFO size of TX and RX
#define CFG_TUD_MIDI_RX_BUFSIZE 64
#define CFG_TUD_MIDI_TX_BUFSIZE 64
// Vendor FIFO size of TX and RX
#define CFG_TUD_VENDOR_RX_BUFSIZE 64
#define CFG_TUD_VENDOR_TX_BUFSIZE 64
#ifdef __cplusplus
}
+4
View File
@@ -55,6 +55,10 @@ class Print
return write((const uint8_t *)buffer, size);
}
// default to zero, meaning "a single write may block"
// should be overriden by subclasses with buffering
virtual int availableForWrite() { return 0; }
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
+8
View File
@@ -34,3 +34,11 @@ void operator delete(void * ptr) {
void operator delete[](void * ptr) {
rtos_free(ptr);
}
void operator delete(void * ptr, unsigned int) {
rtos_free(ptr);
}
void operator delete[](void * ptr, unsigned int) {
rtos_free(ptr);
}
@@ -163,7 +163,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
/**
@@ -171,7 +171,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -141,7 +141,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
void loop()
@@ -0,0 +1,159 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
/*
* This sketch demonstrate the central API(). A additional bluefruit
* that has bleuart as peripheral is required for the demo.
*/
#include <bluefruit.h>
BLEClientUart clientUart; // bleuart client
uint32_t rx_count = 0;
void setup()
{
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
Serial.println("Bluefruit52 Central BLEUART Example");
Serial.println("-----------------------------------\n");
// Config the connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configCentralBandwidth(BANDWIDTH_MAX);
// Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
// SRAM usage required by SoftDevice will increase dramatically with number of connections
Bluefruit.begin(0, 1);
Bluefruit.setName("Bluefruit52 Central");
// Init BLE Central Uart Serivce
clientUart.begin();
clientUart.setRxCallback(bleuart_rx_callback);
// Increase Blink rate to different from PrPh advertising mode
Bluefruit.setConnLedInterval(250);
// Callbacks for Central
Bluefruit.Central.setConnectCallback(connect_callback);
Bluefruit.Central.setDisconnectCallback(disconnect_callback);
/* Start Central Scanning
* - Enable auto scan if disconnected
* - Interval = 100 ms, window = 80 ms
* - Don't use active scan
* - Start(timeout) with timeout = 0 will scan forever (until connected)
*/
Bluefruit.Scanner.setRxCallback(scan_callback);
Bluefruit.Scanner.restartOnDisconnect(true);
Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms
Bluefruit.Scanner.useActiveScan(false);
Bluefruit.Scanner.start(0); // // 0 = Don't stop scanning after n seconds
}
/**
* Callback invoked when scanner pick up an advertising data
* @param report Structural advertising data
*/
void scan_callback(ble_gap_evt_adv_report_t* report)
{
// Check if advertising contain BleUart service
if ( Bluefruit.Scanner.checkReportForService(report, clientUart) )
{
Serial.print("BLE UART service detected. Connecting ... ");
// Connect to device with bleuart service in advertising
Bluefruit.Central.connect(report);
}else
{
// For Softdevice v6: after received a report, scanner will be paused
// We need to call Scanner resume() to continue scanning
Bluefruit.Scanner.resume();
}
}
/**
* Callback invoked when an connection is established
* @param conn_handle
*/
void connect_callback(uint16_t conn_handle)
{
Serial.println("Connected");
Serial.print("Discovering BLE Uart Service ... ");
if ( clientUart.discover(conn_handle) )
{
Serial.println("Found it");
Serial.println("Enable TXD's notify");
clientUart.enableTXD();
Serial.println("Ready to receive from peripheral");
}else
{
Serial.println("Found NONE");
// disconnect since we couldn't find bleuart service
Bluefruit.disconnect(conn_handle);
}
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) conn_handle;
(void) reason;
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
/**
* Callback invoked when uart received data
* @param uart_svc Reference object to the service where the data
* arrived. In this example it is clientUart
*/
void bleuart_rx_callback(BLEClientUart& uart_svc)
{
int count = uart_svc.available();
uart_svc.flush();
}
void loop()
{
if ( Bluefruit.Central.connected() )
{
// Not discovered yet
if ( clientUart.discovered() )
{
// Discovered means in working state
// Get Serial input and send to Peripheral
if ( Serial.available() )
{
delay(2); // delay a bit for all characters to arrive
char str[20+1] = { 0 };
Serial.readBytes(str, 20);
clientUart.print( str );
}
}
}
}
@@ -244,7 +244,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
/**
@@ -210,5 +210,5 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -142,5 +142,5 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -159,7 +159,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
connection_count--;
}
@@ -94,8 +94,11 @@ void startAdv(void)
void loop()
{
// If service is not yet discovered
if ( !bleCTime.discovered() && !Bluefruit.connPaired() ) return;
// Skip if service is not yet discovered
if ( !bleCTime.discovered() ) return;
// Skip if service connection is not paired/secured
if ( !Bluefruit.connPaired( bleCTime.connHandle() ) ) return;
// Get Time from iOS once per second
// Note it is not advised to update this quickly
@@ -170,5 +173,5 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -103,8 +103,11 @@ void startAdv(void)
void loop()
{
// If service is not yet discovered
if ( !bleCTime.discovered() && !Bluefruit.connPaired() ) return;
// Skip if service is not yet discovered
if ( !bleCTime.discovered() ) return;
// Skip if service connection is not paired/secured
if ( !Bluefruit.connPaired( bleCTime.connHandle() ) ) return;
// Get Time from iOS once per second
// Note it is not advised to update this quickly
@@ -181,7 +181,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
Serial.println("Advertising!");
}
@@ -171,7 +171,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) conn_handle;
(void) reason;
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
Serial.println("Advertising!");
}
@@ -15,14 +15,16 @@
/*
* This sketch uses the HID Consumer Key API to send the Volume Down
* key when PIN_SHUTTER is grounded. This will cause your mobile device
* to capture a photo when you are in the camera app
* to capture a photo when you are in the camera app.
*
* For Feather nRF52840 PIN_SHUTTER is conveniently user switch.
*/
#include <bluefruit.h>
BLEDis bledis;
BLEHidAdafruit blehid;
#define PIN_SHUTTER A0
#define PIN_SHUTTER 7
void setup()
{
@@ -101,30 +103,34 @@ void startAdv(void)
void loop()
{
// Make sure you are connected and bonded/paired
if ( Bluefruit.connected() && Bluefruit.connPaired() )
// Skip if shutter pin is not Ground
if ( digitalRead(PIN_SHUTTER) == 1 ) return;
// Make sure we are connected and bonded/paired
for (uint16_t conn_hdl=0; conn_hdl < BLE_MAX_CONNECTION; conn_hdl++)
{
// Check if pin GND'ed
if ( digitalRead(PIN_SHUTTER) == 0 )
BLEConnection* connection = Bluefruit.Connection(conn_hdl);
if ( connection && connection->connected() && connection->paired() )
{
// Turn on red LED when we start sending data
digitalWrite(LED_RED, 1);
// Send the 'volume down' key press
// Check BLEHidGeneric.h for a list of valid consumer usage codes
blehid.consumerKeyPress(HID_USAGE_CONSUMER_VOLUME_DECREMENT);
// Send the 'volume down' key press to the peer
// Check tinyusb/src/class/hid/hid.h for a list of valid consumer usage codes
blehid.consumerKeyPress(conn_hdl, HID_USAGE_CONSUMER_VOLUME_DECREMENT);
// Delay a bit between reports
delay(10);
// Send key release
blehid.consumerKeyRelease();
blehid.consumerKeyRelease(conn_hdl);
// Turn off the red LED
digitalWrite(LED_RED, 0);
// Delay to avoid constant capturing
delay(500);
}
}
// Delay to avoid constant capturing
delay(500);
}
@@ -0,0 +1,202 @@
/*********************************************************************
This is an example for our nRF52 based Bluefruit LE modules
Pick one up today in the adafruit shop!
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
MIT license, check LICENSE for more information
All text above, and the splash screen below must be included in
any redistribution
*********************************************************************/
/* This sketch demonstrates the "Image Upload" feature of Bluefruit Mobile App.
* FeatherWing OLED is used to display uploaded image
* - https://www.adafruit.com/product/3315
*/
#include <bluefruit.h>
#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
BLEUart bleuart; // uart over ble
/* The Image Transfer module sends the image of your choice to Bluefruit LE over UART.
* Each image sent begins with
* - A single byte char “!” (0x21)
* - Image width (uint16 little endian, 2 bytes)
* - Image height (uint16 little endian, 2 bytes)
* - Pixel data encoded as RGB 24-bit and suffixed by a single byte CRC.
*
* Format: [ ‘!’ ] [ uint16 width ] [ uint16 height ] [ r g b ] [ r g b ] [ r g b ] … [ CRC ]
*/
uint16_t imageWidth = 0;
uint16_t imageHeight = 0;
// Statistics for speed testing
uint32_t rxCount = 0;
uint32_t rxStartTime = 0;
uint32_t rxLastTime = 0;
#ifdef ARDUINO_NRF52832_FEATHER
#define TFT_DC 11
#define TFT_CS 31
#define STMPE_CS 30
#define SD_CS 27
#endif
#ifdef ARDUINO_NRF52840_FEATHER
#define TFT_DC 10
#define TFT_CS 9
#define STMPE_CS 6
#define SD_CS 5
#endif
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
void setup()
{
Serial.begin(115200);
tft.begin();
tft.fillScreen(ILI9341_BLACK);
tft.setTextColor(ILI9341_WHITE);
tft.setTextSize(1);
// Config the peripheral connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnInterval(6, 12); // 7.5 - 15 ms
// Configure and Start BLE Uart Service
bleuart.begin();
bleuart.setRxCallback(bleuart_rx_callback);
// Set up and start advertising
startAdv();
// splash screen effect
delay(100);
tft.println("Advertising ... ");
}
void startAdv(void)
{
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
Bluefruit.Advertising.addAppearance(BLE_APPEARANCE_GENERIC_CLOCK);
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);
// There is no room for Name in Advertising packet
// Use Scan response for Name
Bluefruit.ScanResponse.addName();
/* Start Advertising
* - Enable auto advertising if disconnected
* - Interval: fast mode = 20 ms, slow mode = 152.5 ms
* - Timeout for fast mode is 30 seconds
* - Start(timeout) with timeout = 0 will advertise forever (until connected)
*
* For recommended advertising interval
* https://developer.apple.com/library/content/qa/qa1931/_index.html
*/
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
void loop()
{
// 3 seconds has passed and there is no data received
// then reset rx count
if ( (rxCount > 0) && (rxLastTime + 1000 < millis()) )
{
print_speed(rxCount, rxLastTime-rxStartTime);
rxCount = 0;
}
}
void connect_callback(uint16_t conn_handle)
{
BLEConnection* conn = Bluefruit.Connection(conn_handle);
tft.println("Connected");
conn->requestPHY();
tft.println("Switching PHY");
conn->requestDataLengthUpdate();
tft.println("Updating Data Length");
conn->requestMtuExchange(247);
tft.println("Exchanging MTU");
tft.println("Ready to receive Image");
}
void print_speed(uint32_t count, uint32_t ms)
{
Serial.print("Received ");
Serial.print(count);
Serial.print(" bytes in ");
Serial.print(ms / 1000.0F, 2);
Serial.println(" seconds.");
Serial.print("Speed : ");
Serial.print( (count / 1000.0F) / (ms / 1000.0F), 2);
Serial.println(" KB/s.\r\n");
}
void bleuart_rx_callback(uint16_t conn_hdl)
{
(void) conn_hdl;
rxLastTime = millis();
// first packet
if ( rxCount == 0 )
{
rxStartTime = millis();
// Incorrect format, possibly corrupted data
if ( bleuart.read() != '!' ) bleuart.flush();
rxCount++;
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
}
rxCount += bleuart.available();
bleuart.flush(); // empty rx fifo
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason)
{
(void) reason;
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(0, 0);
tft.println("Advertising ...");
}
@@ -115,5 +115,5 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -121,5 +121,5 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
@@ -14,16 +14,26 @@
#include <bluefruit.h>
// String to send in the throughput test
#define TEST_STRING "01234567899876543210"
const int TEST_STRLEN = strlen(TEST_STRING);
/* Best result is
* - 8.74 KB/s with 20 ms, MTU = 23
* - 23.62 KB/s with 7.5 ms, MTU = 23
* - 47.85 KB/s with 15 ms, MTU = 247
*/
// Number of total data sent ( 1024 times the test string)
#define TOTAL_BYTES (1024 * strlen(TEST_STRING))
// data to send in the throughput test
char test_data[256] = { 0 };
// Number of packet to sent
// actualy number of bytes depends on the MTU of the connection
#define PACKET_NUM 1000
BLEDis bledis;
BLEUart bleuart;
uint32_t rxCount = 0;
uint32_t rxStartTime = 0;
uint32_t rxLastTime = 0;
/**************************************************************************/
/*!
@brief Sets up the HW an the BLE module (this function is called
@@ -31,7 +41,7 @@ BLEUart bleuart;
*/
/**************************************************************************/
void setup(void)
{
{
Serial.begin(115200);
while ( !Serial ) delay(10); // for nrf52840 with native usb
@@ -43,11 +53,17 @@ void setup(void)
// here in case you want to control this manually via PIN 19
Bluefruit.autoConnLed(true);
// Config the peripheral connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
Bluefruit.setName("Bluefruit52");
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
Bluefruit.Periph.setConnInterval(6, 12); // 7.5 - 15 ms
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
@@ -57,6 +73,9 @@ void setup(void)
// Configure and Start BLE Uart Service
bleuart.begin();
bleuart.setRxCallback(bleuart_rx_callback);
bleuart.setNotifyCallback(bleuart_notify_callback);
// Set up and start advertising
startAdv();
}
@@ -90,8 +109,26 @@ void startAdv(void)
void connect_callback(uint16_t conn_handle)
{
(void) conn_handle;
BLEConnection* conn = Bluefruit.Connection(conn_handle);
Serial.println("Connected");
// request PHY changed to 2MB
Serial.println("Request to change PHY");
conn->requestPHY();
// request to update data length
Serial.println("Request to change Data Length");
conn->requestDataLengthUpdate();
// request mtu exchange
Serial.println("Request to change MTU");
conn->requestMtuExchange(247);
// request connection interval of 7.5 ms
//conn->requestConnectionParameter(6); // in unit of 1.25
// delay a bit for all the request to complete
delay(1000);
}
/**
@@ -105,56 +142,99 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason)
(void) reason;
Serial.println();
Serial.println("Disconnected");
Serial.print("Disconnected, reason = 0x"); Serial.println(reason, HEX);
}
/**************************************************************************/
/*!
@brief Constantly poll for new command or response data
*/
/**************************************************************************/
void loop(void)
void bleuart_rx_callback(uint16_t conn_hdl)
{
uint32_t start, stop, sent;
uint32_t remaining = TOTAL_BYTES;
start = stop = sent = 0;
(void) conn_hdl;
rxLastTime = millis();
// first packet
if ( rxCount == 0 )
{
rxStartTime = millis();
}
uint32_t count = bleuart.available();
rxCount += count;
bleuart.flush(); // empty rx fifo
Serial.printf("RX %d bytes\n", count);
}
void bleuart_notify_callback(uint16_t conn_hdl, bool enabled)
{
if ( enabled )
{
Serial.println("Send a key and press enter to start test");
}
}
void print_speed(const char* text, uint32_t count, uint32_t ms)
{
Serial.print(text);
Serial.print(count);
Serial.print(" bytes in ");
Serial.print(ms / 1000.0F, 2);
Serial.println(" seconds.");
Serial.print("Speed : ");
Serial.print( (count / 1000.0F) / (ms / 1000.0F), 2);
Serial.println(" KB/s.\r\n");
}
void test_throughput(void)
{
uint32_t start, sent;
start = sent = 0;
const uint16_t data_mtu = Bluefruit.Connection(0)->getMtu() - 3;
memset(test_data, '1', data_mtu);
uint32_t remaining = data_mtu*PACKET_NUM;
Serial.print("Sending ");
Serial.print(remaining);
Serial.println(" bytes ...");
Serial.flush();
delay(1);
start = millis();
while ( (remaining > 0) && Bluefruit.connected() && bleuart.notifyEnabled() )
{
if ( !bleuart.write(test_data, data_mtu) ) break;
sent += data_mtu;
remaining -= data_mtu;
}
print_speed("Sent ", sent, millis() - start);
}
void loop(void)
{
if (Bluefruit.connected() && bleuart.notifyEnabled())
{
// Wait for user input before trying again
Serial.println("Connected. Send a key and press enter to start test");
getUserInput();
Serial.print("Sending ");
Serial.print(remaining);
Serial.println(" bytes ...");
start = millis();
while ( (remaining > 0) && Bluefruit.connected() && bleuart.notifyEnabled() )
if ( Serial.available() )
{
if ( !bleuart.print(TEST_STRING) ) break;
sent += TEST_STRLEN;
remaining -= TEST_STRLEN;
// Only print every 100th time
// if ( (sent % (100*TEST_STRLEN) ) == 0 )
// {
// Serial.print("Sent: "); Serial.print(sent);
// Serial.print(" Remaining: "); Serial.println(remaining);
// }
getUserInput();
test_throughput();
}
// 3 seconds has passed and there is no data received
// then reset rx count
if ( (rxCount > 0) && (rxLastTime + 1000 < millis()) )
{
print_speed("Received ", rxCount, rxLastTime-rxStartTime);
rxCount = 0;
}
stop = millis() - start;
Serial.print("Sent ");
Serial.print(sent);
Serial.print(" bytes in ");
Serial.print(stop / 1000.0F, 2);
Serial.println(" seconds.");
Serial.println("Speed ");
Serial.print( (sent / 1000.0F) / (stop / 1000.0F), 2);
Serial.println(" KB/s.\r\n");
// Bluefruit.disconnect(0);
// delay(2000);
}
}
@@ -60,7 +60,7 @@ void setup()
blinkTimer.begin(1000, blink_timer_callback);
blinkTimer.start();
if (Bluefruit.begin())
if (!Bluefruit.begin())
{
Serial.println("Unable to init Bluefruit");
while(1)
+2 -2
View File
@@ -61,8 +61,8 @@ setName KEYWORD2
getName KEYWORD2
setTxPower KEYWORD2
getTxPower KEYWORD2
setApperance KEYWORD2
getApperance KEYWORD2
setAppearance KEYWORD2
getAppearance KEYWORD2
connected KEYWORD2
disconnect KEYWORD2
+1 -1
View File
@@ -1,5 +1,5 @@
name=Adafruit Bluefruit nRF52 Libraries
version=0.11.1
version=0.12.0
author=Adafruit
maintainer=Adafruit <info@adafruit.com>
sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules
+10 -11
View File
@@ -340,19 +340,18 @@ bool BLEAdvertising::_start(uint16_t interval, uint16_t timeout)
// ADV Params
ble_gap_adv_params_t adv_para =
{
.properties = {
.type = _type,
.anonymous = 0
},
.p_peer_addr = NULL , // Undirected advertisement
.interval = interval , // advertising interval (in units of 0.625 ms)
.duration = (uint16_t) (timeout*100), // in 10-ms unit
.properties = { .type = _type, .anonymous = 0 },
.p_peer_addr = NULL , // Undirected advertisement
.interval = interval , // advertising interval (in units of 0.625 ms)
.duration = (uint16_t) (timeout*100) , // in 10-ms unit
.max_adv_evts = 0, // TODO can be used for fast/slow mode
.channel_mask = { 0, 0, 0, 0, 0 } , // 40 channel, set 1 to disable
.filter_policy = BLE_GAP_ADV_FP_ANY ,
.max_adv_evts = 0 , // TODO can be used for fast/slow mode
.channel_mask = { 0, 0, 0, 0, 0 } , // 40 channel, set 1 to disable
.filter_policy = BLE_GAP_ADV_FP_ANY ,
//.primary_phy, .secondary_phy, .set_id, .scan_req_notification
.primary_phy = BLE_GAP_PHY_AUTO , // 1 Mbps will be used
.secondary_phy = BLE_GAP_PHY_AUTO , // 1 Mbps will be used
// , .set_id, .scan_req_notification
};
// gap_adv long-live is required by SD v6
+111 -2
View File
@@ -46,6 +46,8 @@ BLEConnection::BLEConnection(uint16_t conn_hdl, ble_gap_evt_connected_t const* e
_connected = true;
_mtu = BLE_GATT_ATT_MTU_DEFAULT;
_data_length = BLE_GATT_ATT_MTU_DEFAULT + 4; // 27
_phy = BLE_GAP_PHY_1MBPS;
_conn_interval = 0;
_peer_addr = evt_connected->peer_addr;
_role = evt_connected->role;
@@ -94,11 +96,21 @@ uint16_t BLEConnection::getMtu (void)
return _mtu;
}
uint16_t BLEConnection::getConnInterval(void)
uint16_t BLEConnection::getConnectionInterval(void)
{
return _conn_interval;
}
uint16_t BLEConnection::getDataLength(void)
{
return _data_length;
}
uint8_t BLEConnection::getPHY(void)
{
return _phy;
}
ble_gap_addr_t BLEConnection::getPeerAddr (void)
{
return _peer_addr;
@@ -132,6 +144,39 @@ bool BLEConnection::setTxPower(int8_t power)
return true;
}
bool BLEConnection::requestMtuExchange(uint16_t mtu)
{
VERIFY_STATUS(sd_ble_gattc_exchange_mtu_request(_conn_hdl, mtu), false);
return true;
}
bool BLEConnection::requestDataLengthUpdate(ble_gap_data_length_params_t const *p_dl_params, ble_gap_data_length_limitation_t *p_dl_limitation)
{
VERIFY_STATUS(sd_ble_gap_data_length_update(_conn_hdl, p_dl_params, p_dl_limitation), false);
return true;
}
bool BLEConnection::requestConnectionParameter(uint16_t conn_interval, uint16_t slave_latency, uint16_t sup_timeout)
{
ble_gap_conn_params_t const conn_params =
{
.min_conn_interval = conn_interval,
.max_conn_interval = conn_interval,
.slave_latency = slave_latency,
.conn_sup_timeout = sup_timeout
};
VERIFY_STATUS(sd_ble_gap_conn_param_update(_conn_hdl, &conn_params), false);
return true;
}
bool BLEConnection::requestPHY(uint8_t phy)
{
ble_gap_phys_t gap_phy = { .tx_phys = phy, .rx_phys = phy };
VERIFY_STATUS( sd_ble_gap_phy_update(_conn_hdl, &gap_phy), false);
return true;
}
bool BLEConnection::disconnect(void)
{
return ERROR_NONE == sd_ble_gap_disconnect(_conn_hdl, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
@@ -405,10 +450,11 @@ void BLEConnection::_eventHandler(ble_evt_t* evt)
ble_gap_conn_params_t* param = &evt->evt.gap_evt.params.conn_param_update.conn_params;
_conn_interval = param->max_conn_interval;
LOG_LV2("GAP", "Conn Interval= %f", _conn_interval*1.25f);
LOG_LV1("GAP", "Conn Interval= %.2f ms, Latency = %d, Supervisor Timeout = %d ms", _conn_interval*1.25f, param->slave_latency, 10*param->conn_sup_timeout);
}
break;
//------------- MTU -------------//
case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST:
{
uint16_t const max_mtu = Bluefruit.getMaxMtu(_role);
@@ -420,6 +466,69 @@ void BLEConnection::_eventHandler(ble_evt_t* evt)
}
break;
case BLE_GATTC_EVT_EXCHANGE_MTU_RSP:
_mtu = evt->evt.gattc_evt.params.exchange_mtu_rsp.server_rx_mtu;
LOG_LV1("GAP", "ATT MTU is changed to %d", _mtu);
break;
//------------- Data Length -------------//
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
{
ble_gap_data_length_params_t* param = &evt->evt.gap_evt.params.data_length_update_request.peer_params;
(void) param;
LOG_LV1("GAP", "Data Length Request is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us);
// Let Softdevice decide the data length
VERIFY_STATUS( sd_ble_gap_data_length_update(_conn_hdl, NULL, NULL), );
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
{
ble_gap_data_length_params_t* datalen = &evt->evt.gap_evt.params.data_length_update.effective_params;
(void) datalen;
LOG_LV1("GAP", "Data Length is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
datalen->max_tx_octets, datalen->max_rx_octets, datalen->max_tx_time_us, datalen->max_rx_time_us);
_data_length = datalen->max_tx_octets;
}
break;
//------------- PHY -------------//
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
ble_gap_phys_t* req_phy = &evt->evt.gap_evt.params.phy_update_request.peer_preferred_phys;
(void) req_phy;
LOG_LV1("GAP", "PHY request tx = 0x%02X, rx = 0x%02X", req_phy->tx_phys, req_phy->rx_phys);
// Tell SoftDevice to choose PHY automatically
ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO };
(void) sd_ble_gap_phy_update(_conn_hdl, &phy);
}
break;
case BLE_GAP_EVT_PHY_UPDATE:
{
ble_gap_evt_phy_update_t* active_phy = &evt->evt.gap_evt.params.phy_update;
if ( active_phy->status != BLE_HCI_STATUS_CODE_SUCCESS )
{
LOG_LV1("GAP", "Failed HCI status = 0x%02X", active_phy->status);
}else
{
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
(void) phy_str;
LOG_LV1("GAP", "PHY active tx: %s, rx: %s", phy_str[active_phy->tx_phy], phy_str[active_phy->rx_phy]);
_phy = active_phy->tx_phy;
}
}
break;
//--------------------------------------------------------------------+
//
//--------------------------------------------------------------------+
+13 -3
View File
@@ -47,8 +47,11 @@ class BLEConnection
uint16_t _conn_hdl;
uint16_t _mtu;
uint16_t _conn_interval;
uint16_t _ediv;
uint16_t _data_length;
uint8_t _phy;
uint8_t _role;
uint16_t _ediv;
bool _connected;
bool _paired;
@@ -75,7 +78,9 @@ class BLEConnection
uint8_t getRole(void);
uint16_t getMtu (void);
uint16_t getConnInterval(void);
uint16_t getConnectionInterval(void);
uint16_t getDataLength(void);
uint8_t getPHY(void);
ble_gap_addr_t getPeerAddr(void);
uint16_t getPeerName(char* buf, uint16_t bufsize);
@@ -84,6 +89,12 @@ class BLEConnection
bool setTxPower(int8_t power); // set power for this connection
bool requestDataLengthUpdate(ble_gap_data_length_params_t const *p_dl_params = NULL, ble_gap_data_length_limitation_t *p_dl_limitation = NULL);
bool requestMtuExchange(uint16_t mtu);
bool requestPHY(uint8_t phy = BLE_GAP_PHY_AUTO);
bool requestConnectionParameter(uint16_t conn_interval, uint16_t slave_latency = BLE_GAP_CONN_SLAVE_LATENCY, uint16_t sup_timeout = BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS/10);
bool requestPairing(void);
bool monitorRssi(uint8_t threshold = BLE_GAP_RSSI_THRESHOLD_INVALID);
int8_t getRssi(void);
void stopRssi(void);
@@ -92,7 +103,6 @@ class BLEConnection
bool getWriteCmdPacket(void);
bool waitForIndicateConfirm(void);
bool requestPairing(void);
bool storeCccd(void);
bool loadKeys(bond_keys_t* bkeys);
+1 -1
View File
@@ -54,7 +54,7 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe
while( _adamsg.isWaiting() )
{
delay( conn->getConnInterval() );
delay( conn->getConnectionInterval() );
}
_adamsg.begin(true);
+1 -1
View File
@@ -158,7 +158,7 @@ void BLEPeriph::printInfo(void)
Serial.println();
Serial.printf(title_fmt, "Conn Timeout");
Serial.printf("%.2f ms", _ppcp.conn_sup_timeout*10.0f);
Serial.printf("%d ms", _ppcp.conn_sup_timeout*10);
Serial.println();
}
+2 -1
View File
@@ -138,8 +138,8 @@ bool BLEScanner::stop(void)
{
VERIFY_STATUS( sd_ble_gap_scan_stop(), false );
Bluefruit._stopConnLed(); // stop blinking
_runnning = false;
Bluefruit._stopConnLed(); // stop blinking
return true;
}
@@ -406,6 +406,7 @@ void BLEScanner::_eventHandler(ble_evt_t* evt)
if (evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_SCAN)
{
_runnning = false;
Bluefruit._stopConnLed();
if (_stop_cb) ada_callback(NULL, 0, _stop_cb);
}
break;
+11 -70
View File
@@ -580,12 +580,12 @@ void AdafruitBluefruit::setConnLedInterval(uint32_t ms)
if ( !active ) xTimerStop(_led_blink_th, 0);
}
bool AdafruitBluefruit::setApperance(uint16_t appear)
bool AdafruitBluefruit::setAppearance(uint16_t appear)
{
return ERROR_NONE == sd_ble_gap_appearance_set(appear);
}
uint16_t AdafruitBluefruit::getApperance(void)
uint16_t AdafruitBluefruit::getAppearance(void)
{
uint16_t appear = 0;
(void) sd_ble_gap_appearance_get(&appear);
@@ -635,9 +635,9 @@ uint16_t AdafruitBluefruit::connHandle(void)
return _conn_hdl;
}
bool AdafruitBluefruit::connPaired(void)
bool AdafruitBluefruit::connPaired(uint16_t conn_hdl)
{
BLEConnection* conn = Bluefruit.Connection(_conn_hdl);
BLEConnection* conn = Bluefruit.Connection(conn_hdl);
return conn && conn->paired();
}
@@ -779,7 +779,7 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
uint16_t const conn_hdl = evt->evt.common_evt.conn_handle;
BLEConnection* conn = this->Connection(conn_hdl);
LOG_LV1("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl);
LOG_LV2("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl);
// GAP handler
if ( conn ) conn->_eventHandler(evt);
@@ -794,6 +794,9 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
ble_gap_evt_connected_t const * para = &evt->evt.gap_evt.params.connected;
LOG_LV1("GAP", "Conn Interval= %.2f ms, Latency = %d, Supervisor Timeout = %d ms",
para->conn_params.max_conn_interval*1.25f, para->conn_params.slave_latency, 10*para->conn_params.conn_sup_timeout);
if ( _connection[conn_hdl] )
{
LOG_LV1("GAP", "Connection is already in used, something wrong !!");
@@ -826,16 +829,7 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason);
// Turn off Conn LED If not connected at all
bool still_connected = false;
for (uint8_t i=0; i<BLE_MAX_CONNECTION; i++)
{
if ( _connection[i] && _connection[i]->connected() )
{
still_connected = true;
break;
}
}
if ( !still_connected ) _setConnLed(false);
if ( !this->connected() ) _setConnLed(false);
// Invoke disconnect callback
if ( conn->getRole() == BLE_GAP_ROLE_PERIPH )
@@ -848,7 +842,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
delete _connection[conn_hdl];
_connection[conn_hdl] = NULL;
}
break;
@@ -862,60 +855,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt)
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST:
{
ble_gap_data_length_params_t* param = &evt->evt.gap_evt.params.data_length_update_request.peer_params;
(void) param;
LOG_LV2("GAP", "Data Length Req is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us);
// Let Softdevice decide the data length
VERIFY_STATUS( sd_ble_gap_data_length_update(conn_hdl, NULL, NULL), );
}
break;
case BLE_GAP_EVT_DATA_LENGTH_UPDATE:
{
ble_gap_data_length_params_t* datalen = &evt->evt.gap_evt.params.data_length_update.effective_params;
(void) datalen;
LOG_LV2("GAP", "Data Length is (tx, rx) octets = (%d, %d), (tx, rx) time = (%d, %d) us",
datalen->max_tx_octets, datalen->max_rx_octets, datalen->max_tx_time_us, datalen->max_rx_time_us);
}
break;
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
ble_gap_phys_t* req_phy = &evt->evt.gap_evt.params.phy_update_request.peer_preferred_phys;
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
(void) req_phy;
(void) phy_str;
LOG_LV1("GAP", "PHY request tx: %s, rx: %s", phy_str[req_phy->tx_phys], phy_str[req_phy->rx_phys]);
// Tell SoftDevice to choose PHY automatically
ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO };
(void) sd_ble_gap_phy_update(conn_hdl, &phy);
}
break;
case BLE_GAP_EVT_PHY_UPDATE:
{
ble_gap_evt_phy_update_t* active_phy = &evt->evt.gap_evt.params.phy_update;
if ( active_phy->status != BLE_HCI_STATUS_CODE_SUCCESS )
{
LOG_LV1("GAP", "Failed HCI status = 0x%02X", active_phy->status);
}else
{
char const *phy_str[] = { "Auto", "1 Mbps", "2 Mbps", "Coded" };
(void) phy_str;
LOG_LV1("GAP", "PHY active tx: %s, rx: %s", phy_str[active_phy->tx_phy], phy_str[active_phy->rx_phy]);
}
}
break;
case BLE_EVT_USER_MEM_REQUEST:
// We will handle Long Write sequence (RW Authorize PREP_WRITE_REQ)
sd_ble_user_mem_reply(conn_hdl, NULL);
@@ -994,6 +933,8 @@ void AdafruitBluefruit::_startConnLed(void)
void AdafruitBluefruit::_stopConnLed(void)
{
xTimerStop(_led_blink_th, 0);
_setConnLed( this->connected() );
}
void AdafruitBluefruit::_setConnLed (bool on_off)
+3 -3
View File
@@ -153,8 +153,8 @@ class AdafruitBluefruit
bool setTxPower (int8_t power);
int8_t getTxPower (void);
bool setApperance (uint16_t appear);
uint16_t getApperance (void);
bool setAppearance (uint16_t appear);
uint16_t getAppearance (void);
ble_gap_sec_params_t getSecureParam(void)
{
@@ -173,7 +173,7 @@ class AdafruitBluefruit
bool connected (uint16_t conn_hdl);
uint16_t connHandle (void);
bool connPaired (void);
bool connPaired (uint16_t conn_hdl);
// Alias to BLEConnection API()
bool disconnect (uint16_t conn_hdl);
@@ -75,11 +75,11 @@ class BLEMidi: public BLEService, public Stream
void autoMIDIread(void* midi_obj);
// Stream API for MIDI Interface
virtual int read ( void );
virtual size_t write ( uint8_t b );
virtual int available ( void );
virtual int peek ( void );
virtual void flush ( void );
virtual int read ( void );
virtual size_t write ( uint8_t b );
virtual int available ( void );
virtual int peek ( void );
virtual void flush ( void );
using Print::write; // pull in write(str) and write(buf, size) from Print
@@ -192,6 +192,24 @@ int BLEUart::read(uint8_t * buf, size_t size)
return _rx_fifo->read(buf, size);
}
uint8_t BLEUart::read8 (void)
{
uint8_t num;
return read(&num, sizeof(num)) ? num : 0;
}
uint16_t BLEUart::read16(void)
{
uint16_t num;
return read((uint8_t*) &num, sizeof(num)) ? num : 0;
}
uint32_t BLEUart::read32(void)
{
uint32_t num;
return read((uint8_t*) &num, sizeof(num)) ? num : 0;
}
size_t BLEUart::write(uint8_t b)
{
return this->write(Bluefruit.connHandle(), &b, 1);
@@ -70,6 +70,11 @@ class BLEUart : public BLEService, public Stream
bool flushTXD (void);
bool flushTXD (uint16_t conn_hdl);
// Read helper
uint8_t read8 (void);
uint16_t read16(void);
uint32_t read32(void);
// Stream API
virtual int read ( void );
virtual int read ( uint8_t * buf, size_t size );
+1 -1
View File
@@ -17,7 +17,7 @@
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
name=Adafruit nRF52 Boards
version=0.11.1
version=0.12.0
# Compile variables
# -----------------
+56 -30
View File
@@ -3,45 +3,71 @@ import glob
import sys
import subprocess
import time
from pathlib import Path
home = str(Path.home())
exit_status = 0
travis = False
if "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true":
travis = True
exit_status = 0
success_count = 0
fail_count = 0
print("Setting board to Feather nRF52840")
build_format = '| {:20} | {:30} | {:9} '
build_separator = '-' * 77
def build_examples(variant):
global exit_status, success_count, fail_count, build_format, build_separator
for sketch in glob.iglob('libraries/**/*.ino', recursive=True):
start_time = time.monotonic()
if os.path.exists(os.path.dirname(sketch) + '/.skip.' + variant):
success = "skipped"
else:
build_result = subprocess.run("arduino --verify {}".format(sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if build_result.returncode != 0:
exit_status = build_result.returncode
success = "\033[31mfailed\033[0m"
fail_count += 1
else:
success = "\033[32msucceeded\033[0m"
success_count += 1
build_duration = time.monotonic() - start_time
if travis:
print('travis_fold:start:build-{}\\r'.format(sketch))
print((build_format + '| {:.2f}s |').format(sketch.split(os.path.sep)[1], os.path.basename(sketch), success, build_duration))
if build_result.returncode != 0:
print(build_result.stdout.decode("utf-8"))
if travis:
print('travis_fold:end:build-{}\\r'.format(sketch))
build_time = time.monotonic()
print(build_separator)
print('| {:^73} |'.format('Feather nRF52840 Express'))
print(build_separator)
print((build_format + '| {:5} |').format('Library', 'Example', 'Result', 'Time'))
print(build_separator)
subprocess.run("arduino --board adafruit:nrf52:feather52840:softdevice=s140v6,debug=l0 --save-prefs", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
build_examples('feather52840')
for sketch in glob.iglob('libraries/**/*.ino', recursive=True):
start_time = time.monotonic()
build_result = subprocess.run("arduino --verify {}".format(sketch), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
build_duration = time.monotonic() - start_time
print('\r\n')
print(build_separator)
print('| {:^73} |'.format('Feather nRF52832'))
print((build_format + '| {:5} |').format('Library', 'Example', 'Result', 'Time'))
print(build_separator)
subprocess.run("arduino --board adafruit:nrf52:feather52832:softdevice=s132v6,debug=l0 --save-prefs", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
build_examples('feather52832')
if build_result.returncode != 0:
exit_status = build_result.returncode
success = "\033[31mfailed\033[0m"
fail_count += 1
else:
success = "\033[32msucceeded\033[0m"
success_count += 1
print(build_separator)
build_time = time.monotonic() - build_time
print("Build Sumamary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m and took {:.2f}s".format(success_count, fail_count, build_time))
print(build_separator)
if travis:
print('travis_fold:start:build-{}\\r'.format(sketch))
print("Build {} took {:.2f}s and {}".format(sketch, build_duration, success))
if build_result.returncode != 0:
print(build_result.stdout.decode("utf-8"))
if travis:
print('travis_fold:end:build-{}\\r'.format(sketch))
print("Build Sumamary: {} \033[32msucceeded\033[0m, {} \033[31mfailed\033[0m".format(success_count, fail_count))
sys.exit(exit_status)
sys.exit(exit_status)
+125
View File
@@ -0,0 +1,125 @@
/*
Copyright (c) 2014-2015 Arduino LLC. All right reserved.
Copyright (c) 2016 Sandeep Mistry All right reserved.
Copyright (c) 2018, Adafruit Industries (adafruit.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "variant.h"
#include "wiring_constants.h"
#include "wiring_digital.h"
#include "nrf.h"
#include "nrf_pwm.h"
const uint32_t g_ADigitalPinMap[] =
{
// D0 .. D8
26, // P0.26 (SDA)
27, // P0.27 (SCL)
33, // P1.01 (SDA1) (UART1_RTS) (SPI1_SCK) (PWM3)
34, // P1.02 (SCL1) (UART1_CTS) (SPI1_MOSI) (PWM3)
40, // P1.08 (UART2_TX) (SPI1_MISO) (PWM1)
42, // P1.10 (UART2_RX) (PWM1)
43, // P1.11 (UART2_CTS) (PWM1)
44, // P1.12 (PWM0)
35, // P1.03 (UART2_RTS)
// D9 .. D20
6, // P0.06 (UART1_TX)
8, // P0.27 (UART1_RX)
46, // P1.14 (SPI_MISO)
45, // P1.13 (SPI_MOSI)
47, // P1.15 (SPI_SCK)
31, // P0.31 (PWM3) (SPI_SS) (ADC5)
30, // P0.30 (PWM3) (ADC4)
29, // P0.29 (PWM2) (ADC3)
28, // P0.28 (PWM2) (ADC2)
4, // P0.04 (PWM2) (ADC1)
3, // P0.03 (PWM2) (ADC0)
11, // P0.11 (MODE)
18, // P0.18 (RESET)
};
void initVariant()
{
switch_antenna(false);
}
void switch_antenna(bool useExternal) {
if (useExternal) {
digitalWrite(ANTENNA_SWITCH_1, LOW);
digitalWrite(ANTENNA_SWITCH_2, HIGH);
}
else {
digitalWrite(ANTENNA_SWITCH_1, HIGH);
digitalWrite(ANTENNA_SWITCH_2, LOW);
}
}
void led_pwm_init(uint32_t led_index, uint32_t led_pin) {
NRF_PWM_Type* pwm = NRF_PWM0;
pwm->ENABLE = 0;
nrf_gpio_cfg_output(led_pin);
nrf_gpio_pin_write(led_pin, 1 - LED_STATE_ON);
pwm->PSEL.OUT[led_index] = led_pin;
pwm->MODE = PWM_MODE_UPDOWN_Up;
pwm->COUNTERTOP = 0xff;
pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_16;
pwm->DECODER = PWM_DECODER_LOAD_Individual;
pwm->LOOP = 0;
pwm->SEQ[0].PTR = (uint32_t) (led_duty_cycles);
pwm->SEQ[0].CNT = 4; // default mode is Individual --> count must be 4
pwm->SEQ[0].REFRESH = 0;
pwm->SEQ[0].ENDDELAY = 0;
pwm->ENABLE = 1;
pwm->EVENTS_SEQEND[0] = 0;
// pwm->TASKS_SEQSTART[0] = 1;
}
void led_pwm_teardown(void) {
pwm_teardown(NRF_PWM0);
}
void led_pwm_duty_cycle(uint32_t led_index, uint16_t duty_cycle) {
led_duty_cycles[led_index] = duty_cycle;
nrf_pwm_event_clear(NRF_PWM0, NRF_PWM_EVENT_SEQEND0);
nrf_pwm_task_trigger(NRF_PWM0, NRF_PWM_TASK_SEQSTART0);
}
void pwm_teardown(NRF_PWM_Type* pwm) {
pwm->TASKS_SEQSTART[0] = 0;
pwm->ENABLE = 0;
pwm->PSEL.OUT[0] = 0xFFFFFFFF;
pwm->PSEL.OUT[1] = 0xFFFFFFFF;
pwm->PSEL.OUT[2] = 0xFFFFFFFF;
pwm->PSEL.OUT[3] = 0xFFFFFFFF;
pwm->MODE = 0;
pwm->COUNTERTOP = 0x3FF;
pwm->PRESCALER = 0;
pwm->DECODER = 0;
pwm->LOOP = 0;
pwm->SEQ[0].PTR = 0;
pwm->SEQ[0].CNT = 0;
}
+210
View File
@@ -0,0 +1,210 @@
/*
Copyright (c) 2014-2015 Arduino LLC. All right reserved.
Copyright (c) 2016 Sandeep Mistry All right reserved.
Copyright (c) 2018, Adafruit Industries (adafruit.com)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _VARIANT_PARTICLE_XENON_
#define _VARIANT_PARTICLE_XENON_
#define _PINNUM(port, pin) ((port)*32 + (pin))
/** Master clock frequency */
#define VARIANT_MCK (64000000ul)
#define USE_LFXO // Board uses 32khz crystal for LF
// define USE_LFRC // Board uses RC for LF
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
#include "WVariant.h"
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
// Number of pins defined in PinDescription array
#define PINS_COUNT (34)
#define NUM_DIGITAL_PINS (20)
#define NUM_ANALOG_INPUTS (6) // A6 is used for battery, A7 is analog reference
#define NUM_ANALOG_OUTPUTS (6)
/*
* Digital pins
*/
#define PIN_D0 _PINNUM(0, 26)
#define PIN_D1 _PINNUM(0, 27)
#define PIN_D2 _PINNUM(1, 1)
#define PIN_D3 _PINNUM(1, 2)
#define PIN_D4 _PINNUM(1, 8)
#define PIN_D5 _PINNUM(1, 10)
#define PIN_D6 _PINNUM(1, 11)
#define PIN_D7 _PINNUM(1, 12)
#define PIN_D8 _PINNUM(1, 3)
#define PIN_D9 _PINNUM(0, 6)
#define PIN_D10 _PINNUM(0, 8)
#define PIN_D11 _PINNUM(1, 14)
#define PIN_D12 _PINNUM(1, 13)
#define PIN_D13 _PINNUM(1, 15)
#define PIN_D14 _PINNUM(0, 31)
#define PIN_D15 _PINNUM(0, 30)
#define PIN_D16 _PINNUM(0, 29)
#define PIN_D17 _PINNUM(0, 28)
#define PIN_D18 _PINNUM(0, 24)
#define PIN_D19 _PINNUM(0, 3)
#define PIN_D20 _PINNUM(0, 11)
static const uint8_t D0 = PIN_D0;
static const uint8_t D1 = PIN_D1;
static const uint8_t D2 = PIN_D2;
static const uint8_t D3 = PIN_D4;
static const uint8_t D5 = PIN_D5;
static const uint8_t D6 = PIN_D0;
static const uint8_t D7 = PIN_D1;
static const uint8_t D8 = PIN_D2;
static const uint8_t D9 = PIN_D4;
static const uint8_t D10 = PIN_D5;
static const uint8_t D11 = PIN_D0;
static const uint8_t D12 = PIN_D1;
static const uint8_t D13 = PIN_D2;
static const uint8_t D14 = PIN_D4;
static const uint8_t D15 = PIN_D5;
static const uint8_t D16 = PIN_D0;
static const uint8_t D17 = PIN_D1;
static const uint8_t D18 = PIN_D2;
static const uint8_t D19 = PIN_D4;
static const uint8_t D20 = PIN_D5;
// LEDs
#define LEDS_NUMBER 1
#define LED_PRIMARY_PIN _PINNUM(1, 12)
#define LED_STATE_ON 1
#define LED_PRIMARY_IDX 0
#define LED_RGB_RED_IDX 1
#define LED_RGB_GREEN_IDX 2
#define LED_RGB_BLUE_IDX 3
#define LED_RGB_RED_PIN _PINNUM(0, 13)
#define LED_RGB_GREEN_PIN _PINNUM(0, 14)
#define LED_RGB_BLUE_PIN _PINNUM(0, 15)
#define BOARD_RGB_BRIGHTNESS 0x202020
static const uint8_t LED_BUILTIN = LED_PRIMARY_PIN;
static const uint8_t LED_RGB_RED = LED_RGB_RED_PIN;
static const uint8_t LED_RGB_GREEN = LED_RGB_GREEN_PIN;
static const uint8_t LED_RGB_BLUE = LED_RGB_BLUE_PIN;
// Buttons
#define BUTTONS_NUMBER 2
#define BUTTON_DFU _PINNUM(0, 11)
#define BUTTON_FRESET _PINNUM(0, 03) // A0
#define BUTTON_PULL NRF_GPIO_PIN_PULLUP
static const uint8_t BUTTON_MODE = PIN_D20;
// Antenna
#define ANTENNA_SWITCH_1 _PINNUM(0, 24)
#define ANTENNA_SWITCH_2 _PINNUM(0, 25)
// NFC
#define NFC1 _PINNUM(0, 9)
#define NFC2 _PINNUM(0, 10)
/*
* Analog pins
*/
#define PIN_A0 _PINNUM(0, 3)
#define PIN_A1 _PINNUM(0, 4)
#define PIN_A2 _PINNUM(0, 28)
#define PIN_A3 _PINNUM(0, 29)
#define PIN_A4 _PINNUM(0, 30)
#define PIN_A5 _PINNUM(0, 31)
static const uint8_t A0 = PIN_A0 ;
static const uint8_t A1 = PIN_A1 ;
static const uint8_t A2 = PIN_A2 ;
static const uint8_t A3 = PIN_A3 ;
static const uint8_t A4 = PIN_A4 ;
static const uint8_t A5 = PIN_A5 ;
#define ADC_RESOLUTION 14
/*
* Serial interfaces
*/
// Serial
#define PIN_SERIAL_RX PIN_D9
#define PIN_SERIAL_TX PIN_D10
#define PIN_SERIAL2_RX PIN_D5
#define PIN_SERIAL2_TX PIN_D6
//#define HAVE_HWSERIAL2 true // TODO: implement UARTE in Uart.cpp
/*
* SPI Interfaces
*/
#define SPI_INTERFACES_COUNT 2
#define PIN_SPI_SS PIN_A0
#define PIN_SPI_MISO _PINNUM(1, 14)
#define PIN_SPI_MOSI _PINNUM(1, 13)
#define PIN_SPI_SCK _PINNUM(1, 15)
#define PIN_SPI1_MISO _PINNUM(1, 8)
#define PIN_SPI1_MOSI _PINNUM(1, 2)
#define PIN_SPI1_SCK _PINNUM(1, 1)
static const uint8_t SS = PIN_SPI_SS;
static const uint8_t MOSI = PIN_SPI_MOSI;
static const uint8_t MISO = PIN_SPI_MISO;
static const uint8_t SCK = PIN_SPI_SCK;
static const uint8_t MOSI1 = PIN_SPI1_MOSI;
static const uint8_t MISO1 = PIN_SPI1_MISO;
static const uint8_t SCK1 = PIN_SPI1_SCK;
/*
* Wire Interfaces
*/
#define WIRE_INTERFACES_COUNT 2
#define PIN_WIRE_SDA _PINNUM(0, 26)
#define PIN_WIRE_SCL _PINNUM(0, 27)
#define PIN_WIRE1_SDA _PINNUM(1, 1)
#define PIN_WIRE1_SCL _PINNUM(1, 2)
// On-board QSPI Flash
#define EXTERNAL_FLASH_DEVICES GD25Q16C
#define USB_MSC_BLOCK_SIZE 512
#define USB_MSC_BLOCK_COUNT ((2*1024*1024) / USB_MSC_BLOCK_SIZE)
void switch_antenna(bool useExternal);
// led pwm
void led_pwm_init(uint32_t led_index, uint32_t led_pin);
void led_pwm_teardown(void);
void led_pwm_duty_cycle(uint32_t led_index, uint16_t duty_cycle);
void pwm_teardown(NRF_PWM_Type* pwm);
static uint16_t led_duty_cycles[PWM0_CH_NUM] = { 0 };
#ifdef __cplusplus
}
#endif
/*----------------------------------------------------------------------------
* Arduino objects - C++ only
*----------------------------------------------------------------------------*/
#endif