diff --git a/.travis.yml b/.travis.yml index 26238340..a3fc8a0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ install: - 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" + - arduino --install-library "Adafruit NeoPixel","Adafruit NeoMatrix","Adafruit GFX Library","Adafruit SSD1306","MIDI Library","Adafruit ILI9341","Adafruit HX8357 Library" before_script: diff --git a/cores/nRF5/Adafruit_TinyUSB_Core/Adafruit_TinyUSB_Core.cpp b/cores/nRF5/Adafruit_TinyUSB_Core/Adafruit_TinyUSB_Core.cpp index 3d485e62..ade9906a 100644 --- a/cores/nRF5/Adafruit_TinyUSB_Core/Adafruit_TinyUSB_Core.cpp +++ b/cores/nRF5/Adafruit_TinyUSB_Core/Adafruit_TinyUSB_Core.cpp @@ -34,7 +34,7 @@ // MACRO TYPEDEF CONSTANT ENUM DECLARATION //--------------------------------------------------------------------+ -#define USBD_STACK_SZ (150) +#define USBD_STACK_SZ (200) // tinyusb function that handles power event (detected, ready, removed) // We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. diff --git a/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/device/usbd.h b/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/device/usbd.h index 24f290b6..c49bc3ad 100644 --- a/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/device/usbd.h +++ b/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/device/usbd.h @@ -166,8 +166,6 @@ TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_re // CDC Descriptor Template // Interface number, string index, EP notification address and size, EP data address (out, in) and size. -// NOTE: This returns an list of byte (uint_8) values -// NOTE: Unwritten & unverified assumption: _itfnum is in range [0..254] (else overflows below adding 1) #define TUD_CDC_DESCRIPTOR(_itfnum, _stridx, _ep_notif, _ep_notif_size, _epout, _epin, _epsize) \ /* Interface Associate */\ 8, TUSB_DESC_INTERFACE_ASSOCIATION, _itfnum, 2, TUSB_CLASS_CDC, CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, CDC_COMM_PROTOCOL_ATCOMMAND, 0,\ @@ -242,8 +240,6 @@ TU_ATTR_WEAK bool tud_vendor_control_complete_cb(uint8_t rhport, tusb_control_re // MIDI simple descriptor // - 1 Embedded Jack In connected to 1 External Jack Out // - 1 Embedded Jack out connected to 1 External Jack In -// NOTE: This returns an list of byte (uint_8) values -// NOTE: Unwritten & unverified assumption: _itfnum is in range [0..254] (else overflows below adding 1) #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,\ diff --git a/cores/nRF5/common_func.h b/cores/nRF5/common_func.h index 81aa5ad5..fdec3f44 100644 --- a/cores/nRF5/common_func.h +++ b/cores/nRF5/common_func.h @@ -114,12 +114,6 @@ //--------------------------------------------------------------------+ // DEBUG HELPER //--------------------------------------------------------------------+ -#if CFG_DEBUG == 2 - #define malloc_named( name, size ) ({ PRINTF("[malloc] %s : %d\r\n", name, size); malloc(size); }) -#else - #define malloc_named( name, size ) malloc ( size ) -#endif - const char* dbg_err_str(int32_t err_id); // TODO move to other place #if CFG_DEBUG diff --git a/cores/nRF5/linker/nrf52832_s132_v6.ld b/cores/nRF5/linker/nrf52832_s132_v6.ld index 9c8af1f2..2ea949ef 100755 --- a/cores/nRF5/linker/nrf52832_s132_v6.ld +++ b/cores/nRF5/linker/nrf52832_s132_v6.ld @@ -5,7 +5,7 @@ GROUP(-lgcc -lc -lnosys) MEMORY { - FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0x6D000-0x26000 + FLASH (rx) : ORIGIN = 0x26000, LENGTH = 0x6D000 - 0x26000 /* SRAM required by S132 depend on * - Attribute Table Size @@ -14,7 +14,6 @@ MEMORY * - Concurrent connection peripheral + central + secure links * - Event Len, HVN queue, Write CMD queue */ - /* RAM (rwx) : ORIGIN = 0x20003200, LENGTH = 0x20010000 - 0x20003200 */ RAM (rwx) : ORIGIN = 0x20003400, LENGTH = 0x20010000 - 0x20003400 } diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 7d79b9bb..f621e918 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -37,7 +37,8 @@ static TaskHandle_t _loopHandle; void initVariant() __attribute__((weak)); void initVariant() { } -#define LOOP_STACK_SZ (512*3) +#define LOOP_STACK_SZ (256*4) +#define CALLBACK_STACK_SZ (256*3) static void loop_task(void* arg) { @@ -56,7 +57,7 @@ static void loop_task(void* arg) while (1) { loop(); - yield(); // yield run usb background task + yield(); // yield to run other task // Serial events if (serialEvent && serialEventRun) serialEventRun(); @@ -81,7 +82,7 @@ int main( void ) xTaskCreate( loop_task, "loop", LOOP_STACK_SZ, NULL, TASK_PRIO_LOW, &_loopHandle); // Initialize callback task - ada_callback_init(); + ada_callback_init(CALLBACK_STACK_SZ); // Start FreeRTOS scheduler. vTaskStartScheduler(); diff --git a/cores/nRF5/new.cpp b/cores/nRF5/new.cpp index a1cd21f1..c646576a 100644 --- a/cores/nRF5/new.cpp +++ b/cores/nRF5/new.cpp @@ -19,6 +19,10 @@ #include #include "rtos.h" +#include +#include +#include + void *operator new(size_t size) { return rtos_malloc(size); } @@ -42,3 +46,46 @@ void operator delete(void * ptr, unsigned int) { void operator delete[](void * ptr, unsigned int) { rtos_free(ptr); } + + +extern "C" +{ + +// defined in linker script +extern unsigned char __HeapBase[]; +extern unsigned char __HeapLimit[]; + +static unsigned char *sbrk_heap_top = __HeapBase; + +__attribute__((used)) +caddr_t _sbrk( int incr ) +{ + unsigned char *prev_heap; + + if ( sbrk_heap_top + incr > __HeapLimit ) + { + /* Out of dynamic memory heap space */ + errno = ENOMEM; + return (caddr_t) -1; + } + + prev_heap = sbrk_heap_top; + + sbrk_heap_top += incr; + + return (caddr_t) prev_heap; +} + +void __malloc_lock(struct _reent *ptr) +{ + (void) ptr; + vTaskSuspendAll(); +} + +void __malloc_unlock(struct _reent *ptr) +{ + (void) ptr; + xTaskResumeAll(); +} + +} diff --git a/cores/nRF5/rtos.cpp b/cores/nRF5/rtos.cpp index 2006822c..58e4bd86 100644 --- a/cores/nRF5/rtos.cpp +++ b/cores/nRF5/rtos.cpp @@ -93,12 +93,14 @@ void yield(void) void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ) { - LOG_LV1("RTOS", "%s Stack Overflow !!!", pcTaskName); + LOG_LV1("RTOS", "Task %s: stack Overflow !!!", pcTaskName); + while(CFG_DEBUG) yield(); } void vApplicationMallocFailedHook(void) { - LOG_LV1("RTOS", "Failed to Malloc"); + LOG_LV1("RTOS", "Task %s: failed to Malloc", pcTaskGetName(xTaskGetCurrentTaskHandle())); + while(CFG_DEBUG) yield(); } /* configSUPPORT_STATIC_ALLOCATION is set to 1, so the application must provide an diff --git a/cores/nRF5/rtos.h b/cores/nRF5/rtos.h index 3c63def4..49fef4a6 100644 --- a/cores/nRF5/rtos.h +++ b/cores/nRF5/rtos.h @@ -66,12 +66,6 @@ enum #define tick2us(tck) ( ( ((uint64_t)(tck)) * 1000000) / configTICK_RATE_HZ ) #define malloc_type(type) rtos_malloc( sizeof(type) ) - -#if 0 -#define rtos_malloc(_size) ({ printf("[malloc] %s:%d : %d bytes\r\n", __PRETTY_FUNCTION__, __LINE__, _size); pvPortMalloc(_size); }) -#define rtos_free(ptr) ({ printf("[free] %s:%d\r\n" ,__PRETTY_FUNCTION__, __LINE__/*malloc_usable_size(ptr)*/); vPortFree(ptr); }) -#else - #define rtos_malloc_type(_type) (_type*) rtos_malloc(sizeof(_type)) static inline void* rtos_malloc(size_t _size) @@ -84,9 +78,8 @@ static inline void rtos_free( void *pv ) return (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) ? free(pv) : vPortFree(pv); } -#endif - -#ifdef __cplusplus // Visible only with cplusplus +// Visible only with C++ +#ifdef __cplusplus #define SCHEDULER_STACK_SIZE_DFLT (512*2) @@ -106,7 +99,6 @@ public: extern SchedulerRTOS Scheduler; -#endif - +#endif // __cplusplus #endif /* RTOS_H_ */ diff --git a/cores/nRF5/syscall_newlib.c b/cores/nRF5/syscall_newlib.c deleted file mode 100644 index 9b1209dd..00000000 --- a/cores/nRF5/syscall_newlib.c +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************/ -/*! - @file syscall_newlib.c - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -#include -#include -#include - -#include "Arduino.h" - -// TODO linker provide end symbol is enough for nanolib's sbrk() -// Verify this later with upgrade toolchain in the next release - -// defined in linker script -extern unsigned char __HeapBase[]; -extern unsigned char __HeapLimit[]; - -static unsigned char *sbrk_heap_top = __HeapBase; - -//volatile uint32_t first_sbrk = 0; -//volatile uint32_t last_sbrk = 0; - -caddr_t _sbrk( int incr ) -{ - unsigned char *prev_heap; - - if ( sbrk_heap_top + incr > __HeapLimit ) - { - /* Out of dynamic memory heap space */ - errno = ENOMEM; - return (caddr_t) -1; - } - - prev_heap = sbrk_heap_top; - -// if ( !first_sbrk) first_sbrk = sbrk_heap_top; -// last_sbrk = sbrk_heap_top; - - sbrk_heap_top += incr; - - return (caddr_t) prev_heap; -} - -void __malloc_lock(struct _reent *ptr) -{ - (void) ptr; - vTaskSuspendAll(); -} - -void __malloc_unlock(struct _reent *ptr) -{ - (void) ptr; - xTaskResumeAll(); -} - diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index c3a3b948..64e51b70 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -36,7 +36,11 @@ #include "Arduino.h" +#define INITIAL_QUEUE_DEPTH 64 + static QueueHandle_t _cb_queue = NULL; +static uint32_t _cb_qdepth; +static TaskHandle_t _cb_task; void adafruit_callback_task(void* arg) { @@ -47,9 +51,6 @@ void adafruit_callback_task(void* arg) ada_callback_t* cb_data; if ( xQueueReceive(_cb_queue, (void*) &cb_data, portMAX_DELAY) ) { -// PRINT_HEX(cb_data); -// PRINT_HEX(cb_data->malloced_data); - const void* func = cb_data->callback_func; uint32_t* args = cb_data->arguments; @@ -80,18 +81,35 @@ static inline bool is_isr(void) void ada_callback_queue(ada_callback_t* cb_item) { - if ( is_isr() ) + BaseType_t ret = is_isr() ? xQueueSendFromISR(_cb_queue, (void*) &cb_item, NULL) : xQueueSend(_cb_queue, (void*) &cb_item, CFG_CALLBACK_TIMEOUT); + + if ( ret != pdTRUE ) { - xQueueSendFromISR(_cb_queue, (void*) &cb_item, NULL); - }else - { - xQueueSend(_cb_queue, (void*) &cb_item, CFG_CALLBACK_TIMEOUT); + // run out of space, resize queue with double the size + if ( ada_callback_queue_resize(2*_cb_qdepth) ) + { + _cb_qdepth = 2*_cb_qdepth; + + // try again + if ( is_isr() ) + { + xQueueSendFromISR(_cb_queue, (void*) &cb_item, NULL); + }else + { + xQueueSend(_cb_queue, (void*) &cb_item, CFG_CALLBACK_TIMEOUT); + } + }else + { + LOG_LV1("MEMORY", "AdaCallback run out of queue spaces"); + } } } -void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const void* func, uint32_t arguments[], uint8_t argcount) +bool ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const void* func, uint32_t arguments[], uint8_t argcount) { ada_callback_t* cb_data = (ada_callback_t*) rtos_malloc( sizeof(ada_callback_t) + (argcount ? (argcount-1)*4 : 0) ); + VERIFY(cb_data); + cb_data->malloced_data = NULL; cb_data->callback_func = func; cb_data->arg_count = argcount; @@ -99,6 +117,11 @@ void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const voi if ( malloc_data && malloc_len ) { cb_data->malloced_data = rtos_malloc(malloc_len); + if ( !cb_data->malloced_data ) + { + rtos_free(cb_data); + return false; + } memcpy(cb_data->malloced_data, malloc_data, malloc_len); } @@ -117,13 +140,45 @@ void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const voi } ada_callback_queue(cb_data); + + return true; } -void ada_callback_init(void) +void ada_callback_init(uint32_t stack_sz) { // queue to hold "Pointer to callback data" - _cb_queue = xQueueCreate(CFG_CALLBACK_QUEUE_LENGTH, sizeof(ada_callback_t*)); + _cb_qdepth = INITIAL_QUEUE_DEPTH; + _cb_queue = xQueueCreate(_cb_qdepth, sizeof(void*)); - TaskHandle_t callback_task_hdl; - xTaskCreate( adafruit_callback_task, "Callback", CFG_CALLBACK_TASK_STACKSIZE, NULL, TASK_PRIO_NORMAL, &callback_task_hdl); + xTaskCreate( adafruit_callback_task, "Callback", stack_sz, NULL, TASK_PRIO_NORMAL, &_cb_task); +} + +bool ada_callback_queue_resize(uint32_t new_depth) +{ + // create new queue + QueueHandle_t new_queue = xQueueCreate(new_depth, sizeof(void*)); + VERIFY(new_queue); + + LOG_LV1("MEMORY", "AdaCallback increase queue depth to %d", new_depth); + + vTaskSuspend(_cb_task); + taskENTER_CRITICAL(); + + // move item from old queue + ada_callback_t* cb_data; + while ( xQueueReceive(_cb_queue, (void*) &cb_data, 0) ) + { + xQueueSend(new_queue, (void*) &cb_data, CFG_CALLBACK_TIMEOUT); + } + + // delete old queue + vQueueDelete(_cb_queue); + + // Switch to new queue + _cb_queue = new_queue; + + taskEXIT_CRITICAL(); + vTaskResume(_cb_task); + + return true; } diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index b22891f3..887f0bf3 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -38,19 +38,10 @@ #include "common_inc.h" -#ifndef CFG_CALLBACK_TASK_STACKSIZE -#define CFG_CALLBACK_TASK_STACKSIZE (512*2) -#endif - -#ifndef CFG_CALLBACK_QUEUE_LENGTH -#define CFG_CALLBACK_QUEUE_LENGTH 20 -#endif - #ifndef CFG_CALLBACK_TIMEOUT #define CFG_CALLBACK_TIMEOUT 100 #endif - #ifdef __cplusplus extern "C"{ #endif @@ -90,16 +81,6 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); #define _ADA_CB_ARGS(...) _GET_6TH_ARG(_0, ##__VA_ARGS__, _ADA_CB_ARGS_5, _ADA_CB_ARGS_4, _ADA_CB_ARGS_3, _ADA_CB_ARGS_2, _ADA_CB_ARGS_1, _ADA_CB_ARGS_0)(__VA_ARGS__) -/** - * Macro function is called by other module with all intended parameters. - */ -#define _cb_setup(_malloc_data, _malloc_len, _func, ... ) \ - do { \ - uint8_t const _count = VA_ARGS_NUM(__VA_ARGS__); \ - uint32_t arguments[] = { _ADA_CB_ARGS(__VA_ARGS__) }; \ - ada_callback_invoke(_malloc_data, _malloc_len, (void const*) _func, arguments, _count); \ - } while(0) - /** * Schedule an function and parameters to be invoked in Ada Callback Task * Macro can take at least 2 and at max 7 arguments @@ -109,12 +90,17 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); * - 3rd arg : function to be invoked * - 3rd-7th arg : function argument, will be cast to uint32_t */ -#define ada_callback(...) _cb_setup(__VA_ARGS__) +#define ada_callback(_malloc_data, _malloc_len, _func, ... ) \ + ({ \ + uint8_t const _count = VA_ARGS_NUM(__VA_ARGS__); \ + uint32_t arguments[] = { _ADA_CB_ARGS(__VA_ARGS__) }; \ + ada_callback_invoke(_malloc_data, _malloc_len, (void const*) _func, arguments, _count); \ + }) - -void ada_callback_init(void); -void ada_callback_invoke(const void* mdata, uint32_t mlen, const void* func, uint32_t arguments[], uint8_t argcount); +void ada_callback_init(uint32_t stack_sz); +bool ada_callback_invoke(const void* mdata, uint32_t mlen, const void* func, uint32_t arguments[], uint8_t argcount); void ada_callback_queue(ada_callback_t* cb_item); +bool ada_callback_queue_resize(uint32_t new_depth); #ifdef __cplusplus } diff --git a/cores/nRF5/utility/adafruit_fifo.cpp b/cores/nRF5/utility/adafruit_fifo.cpp index 6474167b..fe16740c 100644 --- a/cores/nRF5/utility/adafruit_fifo.cpp +++ b/cores/nRF5/utility/adafruit_fifo.cpp @@ -60,7 +60,7 @@ Adafruit_FIFO::Adafruit_FIFO(uint8_t item_size, uint16_t depth) void Adafruit_FIFO::begin(void) { - _buffer = (uint8_t*) malloc(_item_size*_depth); + _buffer = (uint8_t*) rtos_malloc(_item_size*_depth); _mutex = xSemaphoreCreateMutex(); } diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index c950395a..a7f5ff2a 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -13,42 +13,22 @@ *********************************************************************/ /* This sketch demonstrates the "Image Upload" feature of Bluefruit Mobile App. - * FeatherWing OLED is used to display uploaded image + * Either 2.4" or 3.5" TFT FeatherWing is used to display uploaded image * - https://www.adafruit.com/product/3315 + * - https://www.adafruit.com/product/3651 + * - https://www.adafruit.com/product/4367 */ +#define TFT_35_FEATHERWING 1 +#define TFT_24_FEATHERWING 2 +#define TFT_15_GIZMO 3 + +// one of above supported TFT add-on +#define TFT_IN_USE TFT_35_FEATHERWING + #include #include #include -#include - -// Uart over BLE with large buffer to hold image data -BLEUart bleuart(1024*10); - -/* 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) followed by 'I' helper for image - * - 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: [ '!' ] [ 'I' ] [ uint16 width ] [ uint16 height ] [ r g b ] [ r g b ] [ r g b ] … [ CRC ] - */ - -uint16_t imageWidth = 0; -uint16_t imageHeight = 0; -uint16_t imageX = 0; -uint16_t imageY = 0; - -uint32_t totalPixel = 0; // received pixel - -// color buf must be large enough to consume incoming data fast enough -// otherwise bleuart fifo could be overflow and start dropping data -uint16_t color_buf[2048]; - -// Statistics for speed testing -uint32_t rxStartTime = 0; -uint32_t rxLastTime = 0; #ifdef ARDUINO_NRF52832_FEATHER #define TFT_DC 11 @@ -65,16 +45,63 @@ uint32_t rxLastTime = 0; #define TFT_CS A6 #endif +#if TFT_IN_USE == TFT_35_FEATHERWING + #include "Adafruit_HX8357.h" + Adafruit_HX8357 tft = Adafruit_HX8357(TFT_CS, TFT_DC); +#elif TFT_IN_USE == TFT_24_FEATHERWING + #include + Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); +#elif TFT_IN_USE == TFT_15_GIZMO + #error "Not supported yet" +#else + #error "TFT display is not supported" +#endif -Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); +#define COLOR_WHITE 0xFFFF +#define COLOR_BLACK 0x0000 +#define COLOR_YELLOW 0xFFE0 +#define COLOR_GREEN 0x07E0 +#define COLOR_RED 0xF800 + +// Declaring Uart over BLE with large buffer to hold image data +// Depending on the Image Resolution and Transfer Mode especially without response +// or Interleaved with high ratio. You may need to increase this buffer size +BLEUart bleuart(10*1024); + +/* 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) followed by 'I' helper for image + * - Color depth: 24-bit for RGB 888, 16-bit for RGB 655 + * - 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: [ '!' ] [ 'I' ] [uint8_t color bit] [ uint16 width ] [ uint16 height ] [ r g b ] [ r g b ] [ r g b ] … [ CRC ] + */ + +uint16_t imageWidth = 0; +uint16_t imageHeight = 0; +uint8_t imageColorBit = 0; + +uint32_t totalPixel = 0; // received pixel + +// pixel line buffer, should be large enough to hold an image width +uint16_t pixel_buf[512]; + +// Statistics for speed testing +uint32_t rxStartTime = 0; +uint32_t rxLastTime = 0; + +// for print out message to TFT once +bool bleuart_overflowed = false; void setup() { Serial.begin(115200); tft.begin(); - tft.fillScreen(ILI9341_BLACK); - tft.setTextColor(ILI9341_WHITE); + tft.fillScreen(COLOR_BLACK); + tft.setTextColor(COLOR_WHITE); tft.setTextSize(1); // Config the peripheral connection with maximum bandwidth @@ -91,7 +118,22 @@ void setup() // Configure and Start BLE Uart Service bleuart.begin(); - bleuart.setRxCallback(bleuart_rx_callback); + + // Due to huge amount of image data + // NRF52832 doesn't have enough SRAM to queue up received packets using deferred callbacks. + // Therefore it must process data as soon as it comes, this can be done by + // changing the default "deferred" option to false to invoke callback immediately. + // However, the transfer speed will be affected since immediate callback will block BLE task + // to process data especially when tft.drawRGBBitmap() is calling. +#ifdef NRF52840_XXAA + // 2nd argument is true to deferred callbacks i.e queue it up in seperated callback Task + bleuart.setRxCallback(bleuart_rx_callback, true); +#else + // 2nd argument is false to invoke callbacks immediately (thus blocking other ble events) + bleuart.setRxCallback(bleuart_rx_callback, false); +#endif + + bleuart.setRxOverflowCallback(bleuart_overflow_callback); // Set up and start advertising startAdv(); @@ -130,102 +172,12 @@ void startAdv(void) void loop() { - if ( !Bluefruit.connected() ) return; - if ( !bleuart.notifyEnabled() ) return; - if ( !bleuart.available() ) return; - - // all pixel data is received - if ( totalPixel == imageWidth*imageHeight ) - { - uint8_t crc = bleuart.read(); - // do checksum later - - // print speed summary - print_speed(totalPixel*3 + 7, rxLastTime-rxStartTime); - - // reset and waiting for new image - totalPixel = imageWidth = imageHeight = 0; - } - - // extract pixel data and display on TFT - uint16_t pixelNum = bleuart.available() / 3; - - // Draw multiple lines of image each time i.e pixelNum = n*imageWidth - // pixelNum is capped at color_buf size (512 pixel) - // the rest will be drawn in the next invocation of loop(). - pixelNum = min(pixelNum, sizeof(color_buf)/2); - - // Chop pixel number to multiple of image width - pixelNum = (pixelNum / imageWidth) * imageWidth; - - if ( pixelNum ) - { - for ( uint16_t i=0; i < pixelNum; i++) - { - uint8_t red = bleuart.read(); - uint8_t green = bleuart.read(); - uint8_t blue = bleuart.read(); - - color_buf[i] = ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ( blue >> 3); - } - - tft.drawRGBBitmap(imageX, imageY, color_buf, imageWidth, imageHeight - imageY); - - totalPixel += pixelNum; - - imageX = totalPixel % imageWidth; - imageY = totalPixel / imageWidth; - } -} - -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.setTextColor(ILI9341_GREEN); - tft.println("Ready to receive new image"); - tft.setTextColor(ILI9341_WHITE); -} - -void print_speed(uint32_t count, uint32_t ms) -{ - tft.setCursor(0, imageHeight+5); - tft.print("Received "); - - tft.setTextColor(ILI9341_YELLOW); - tft.print(count); - tft.setTextColor(ILI9341_WHITE); - - tft.print(" bytes in "); - - tft.setTextColor(ILI9341_YELLOW); - tft.print(ms / 1000.0F, 2); - tft.setTextColor(ILI9341_WHITE); - - tft.println(" seconds"); - - tft.print("Speed: "); - tft.setTextColor(ILI9341_YELLOW); - tft.print( (count / 1000.0F) / (ms / 1000.0F), 2); - tft.setTextColor(ILI9341_WHITE); - tft.println(" KB/s"); - - tft.setTextColor(ILI9341_GREEN); - tft.println("Ready to receive new image"); - tft.setTextColor(ILI9341_WHITE); + // nothing to do } +// Invoked when receiving data from bleuart +// Pull data from bleuart fifo & draw image as soon as possible, +// Otherwise bleuart fifo can be overflowed void bleuart_rx_callback(uint16_t conn_hdl) { (void) conn_hdl; @@ -235,6 +187,7 @@ void bleuart_rx_callback(uint16_t conn_hdl) // Received new Image if ( (imageWidth == 0) && (imageHeight == 0) ) { + // take note of time of first packet rxStartTime = millis(); // Skip all data until '!I' is found @@ -242,21 +195,141 @@ void bleuart_rx_callback(uint16_t conn_hdl) if (bleuart.read() != 'I') return; if ( !bleuart.available() ) return; - - imageWidth = bleuart.read16(); + + imageColorBit = bleuart.read8(); + imageWidth = bleuart.read16(); imageHeight = bleuart.read16(); + totalPixel = 0; + + PRINT_INT(imageColorBit); PRINT_INT(imageWidth); PRINT_INT(imageHeight); - tft.fillScreen(ILI9341_BLACK); + tft.fillScreen(COLOR_BLACK); tft.setCursor(0, 0); - imageX = imageY = 0; + } + + // Extract pixel data to buffer and draw image line by line + while ( bleuart.available() >= 3 ) + { + // TFT FeatherWing use 16-bit RGB 655 color, need to convert if input is 24-bit color + if ( imageColorBit == 24 ) + { + uint8_t rgb[3]; + bleuart.read(rgb, 3); + pixel_buf[totalPixel % imageWidth] = ((rgb[0] & 0xF8) << 8) | ((rgb[1] & 0xFC) << 3) | (rgb[2] >> 3); + } + else if ( imageColorBit == 16 ) + { + // native 16-bit 655 color + pixel_buf[totalPixel % imageWidth] = bleuart.read16(); + } + + totalPixel++; + + // enough to draw an image line + if ( (totalPixel % imageWidth) == 0 ) + { + tft.drawRGBBitmap(0, totalPixel/imageWidth, pixel_buf, imageWidth, 1); + } + } + + // all pixel data is received + if ( totalPixel == imageWidth*imageHeight ) + { + uint8_t crc = bleuart.read(); + // do checksum later + + // print speed summary + print_summary(totalPixel*(imageColorBit/8) + 8, rxLastTime-rxStartTime); + + // reset and waiting for new image + imageColorBit = 0; + imageWidth = imageHeight = 0; + totalPixel = 0; } } +void connect_callback(uint16_t conn_handle) +{ + BLEConnection* conn = Bluefruit.Connection(conn_handle); + + tft.println("Connected"); + + // Requesting to Switching to 2MB PHY, larger data length and MTU + // will increase the throughput on supported central. This should be already done + // with latest Bluefruit app, but still put here for user reference + conn->requestPHY(); + tft.println("Switching PHY"); + + conn->requestDataLengthUpdate(); + tft.println("Updating Data Length"); + + conn->requestMtuExchange(247); + tft.println("Exchanging MTU"); + + tft.setTextColor(COLOR_GREEN); + tft.println("Ready to receive new image"); + tft.setTextColor(COLOR_WHITE); +} + +void print_summary(uint32_t count, uint32_t ms) +{ + tft.setCursor(0, imageHeight+5); + tft.print("Received "); + + tft.setTextColor(COLOR_YELLOW); + tft.print(count); + tft.setTextColor(COLOR_WHITE); + + tft.print(" bytes in "); + + tft.setTextColor(COLOR_YELLOW); + tft.print(ms / 1000.0F, 2); + tft.setTextColor(COLOR_WHITE); + + tft.println(" seconds"); + + tft.print("Speed: "); + tft.setTextColor(COLOR_YELLOW); + tft.print( (count / 1000.0F) / (ms / 1000.0F), 2); + tft.setTextColor(COLOR_WHITE); + tft.print(" KB/s for "); + + tft.setTextColor(COLOR_YELLOW); + tft.print(imageWidth); tft.print("x"); tft.print(imageHeight); + + tft.setTextColor(COLOR_WHITE); + tft.println(" Image"); + + tft.setTextColor(COLOR_GREEN); + tft.println("Ready to receive new image"); + tft.setTextColor(COLOR_WHITE); +} + +void bleuart_overflow_callback(uint16_t conn_hdl, uint16_t leftover) +{ + Serial.println("BLEUART rx buffer OVERFLOWED!"); + Serial.println("Please increase buffer size for bleuart"); + + // only print the first time this occur, need disconnect to reset + if (!bleuart_overflowed) + { + tft.setCursor(0, imageHeight+5); + + tft.setTextColor(COLOR_RED); + tft.println("BLEUART rx buffer OVERFLOWED!"); + + tft.setTextColor(COLOR_WHITE); + tft.print("Please increase buffer size for bleuart"); + } + + bleuart_overflowed = true; +} + /** - * Callback invoked when a connection is dropped + * 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 */ @@ -264,9 +337,14 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) { (void) reason; - tft.fillScreen(ILI9341_BLACK); + tft.fillScreen(COLOR_BLACK); tft.setCursor(0, 0); tft.println("Advertising ..."); - totalPixel = imageWidth = imageHeight = 0; + imageColorBit = 0; + imageWidth = imageHeight = 0; + totalPixel = 0; + bleuart_overflowed = false; + + bleuart.flush(); } diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index 98938b3a..a06fefcf 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -361,11 +361,8 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) { ble_gatts_evt_read_t * rd_req = &request->request.read; - if ( _use_ada_cb.read_authorize ) - { - ada_callback(rd_req, sizeof(*rd_req), _rd_authorize_cb, conn_hdl, this, rd_req); - } - else + if ( !(_use_ada_cb.read_authorize && + ada_callback(rd_req, sizeof(*rd_req), _rd_authorize_cb, conn_hdl, this, rd_req)) ) { _rd_authorize_cb(conn_hdl, this, rd_req); } @@ -382,10 +379,8 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) // Write Request with authorization if (_wr_authorize_cb != NULL) { - if ( _use_ada_cb.write_authorize ) - { - ada_callback(wr_req, sizeof(*wr_req), _wr_authorize_cb, conn_hdl, this, wr_req); - }else + if ( !(_use_ada_cb.write_authorize && + ada_callback(wr_req, sizeof(*wr_req), _wr_authorize_cb, conn_hdl, this, wr_req)) ) { _wr_authorize_cb(conn_hdl, this, wr_req); } @@ -435,13 +430,12 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply); - // Long write complete, call write callback if set if (_wr_cb) { - if (_use_ada_cb.write) - { - ada_callback(_long_wr.buffer, _long_wr.count, _wr_cb, conn_hdl, this, _long_wr.buffer, _long_wr.count); - }else + // Long write complete, call write callback if set + // If using ada callback but failed --> invoke callback immediately + if ( !(_use_ada_cb.write && + ada_callback(_long_wr.buffer, _long_wr.count, _wr_cb, conn_hdl, this, _long_wr.buffer, _long_wr.count)) ) { _wr_cb(conn_hdl, this, _long_wr.buffer, _long_wr.count); } @@ -468,19 +462,16 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) { ble_gatts_evt_write_t* request = &event->evt.gatts_evt.params.write; - LOG_LV2_BUFFER(NULL, request->data, request->len); - // Value write if (request->handle == _handles.value_handle) { - LOG_LV2("GATTS", "attr's value, uuid = 0x%04X", request->uuid.uuid); + LOG_LV2("GATTS", "attr's value, uuid = 0x%04X, len = %d", request->uuid.uuid, request->len); + LOG_LV2_BUFFER(NULL, request->data, request->len); if (_wr_cb) { - if (_use_ada_cb.write) - { - ada_callback(request->data, request->len, _wr_cb, conn_hdl, this, request->data, request->len); - }else + if ( !(_use_ada_cb.write && + ada_callback(request->data, request->len, _wr_cb, conn_hdl, this, request->data, request->len)) ) { _wr_cb(conn_hdl, this, request->data, request->len); } @@ -490,18 +481,15 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) // CCCD write if ( request->handle == _handles.cccd_handle ) { - LOG_LV2("GATTS", "attr's cccd"); + uint16_t value; + memcpy(&value, request->data, 2); + + LOG_LV1("GATTS", "attr's cccd = 0x%04X", value); if (_cccd_wr_cb) { - uint16_t value; - memcpy(&value, request->data, 2); - - if ( _use_ada_cb.cccd_write ) - { - ada_callback(NULL, 0, _cccd_wr_cb, conn_hdl, this, value); - } - else + if ( !(_use_ada_cb.cccd_write && + ada_callback(NULL, 0, _cccd_wr_cb, conn_hdl, this, value)) ) { _cccd_wr_cb(conn_hdl, this, value); } diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp index 2135c212..78f8858f 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp @@ -411,10 +411,8 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) if (_notify_cb) { // use AdaCallback or invoke directly - if (_use_ada_cb.notify) - { - ada_callback(hvx->data, hvx->len, _notify_cb, this, hvx->data, hvx->len); - }else + if ( !(_use_ada_cb.notify && + ada_callback(hvx->data, hvx->len, _notify_cb, this, hvx->data, hvx->len)) ) { _notify_cb(this, hvx->data, hvx->len); } @@ -425,10 +423,8 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) if (_indicate_cb) { // use AdaCallback or invoke directly - if (_use_ada_cb.indicate) - { - ada_callback(hvx->data, hvx->len, _indicate_cb, this, hvx->data, hvx->len); - }else + if ( !(_use_ada_cb.indicate && + ada_callback(hvx->data, hvx->len, _indicate_cb, this, hvx->data, hvx->len)) ) { _indicate_cb(this, hvx->data, hvx->len); } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index a5860d06..6d02f4c9 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -38,20 +38,19 @@ #include "utility/bonding.h" #ifndef CFG_BLE_TX_POWER_LEVEL -#define CFG_BLE_TX_POWER_LEVEL 0 +#define CFG_BLE_TX_POWER_LEVEL 0 #endif #ifndef CFG_DEFAULT_NAME -#define CFG_DEFAULT_NAME "Bluefruit52" +#define CFG_DEFAULT_NAME "Bluefruit52" #endif - #ifndef CFG_BLE_TASK_STACKSIZE -#define CFG_BLE_TASK_STACKSIZE (512*3) +#define CFG_BLE_TASK_STACKSIZE (256*5) #endif #ifndef CFG_SOC_TASK_STACKSIZE -#define CFG_SOC_TASK_STACKSIZE (200) +#define CFG_SOC_TASK_STACKSIZE (200) #endif #ifdef USE_TINYUSB @@ -103,7 +102,6 @@ static void bluefruit_blinky_cb( TimerHandle_t xTimer ) digitalToggle(LED_BLUE); } - static void nrf_error_cb(uint32_t id, uint32_t pc, uint32_t info) { #if CFG_DEBUG @@ -210,7 +208,7 @@ void AdafruitBluefruit::configAttrTableSize(uint32_t attr_table_size) _sd_cfg.attr_table_size = align4( maxof(attr_table_size, BLE_GATTS_ATTR_TAB_SIZE_MIN) ); } -void AdafruitBluefruit::configPrphConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize) +void AdafruitBluefruit::configPrphConn(uint16_t mtu_max, uint16_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize) { _sd_cfg.prph.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);; _sd_cfg.prph.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN); @@ -218,7 +216,7 @@ void AdafruitBluefruit::configPrphConn(uint16_t mtu_max, uint8_t event_len, uint _sd_cfg.prph.wrcmd_qsize = wrcmd_qsize; } -void AdafruitBluefruit::configCentralConn(uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize) +void AdafruitBluefruit::configCentralConn(uint16_t mtu_max, uint16_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize) { _sd_cfg.central.mtu_max = maxof(mtu_max, BLE_GATT_ATT_MTU_DEFAULT);; _sd_cfg.central.event_len = maxof(event_len, BLE_GAP_EVENT_LENGTH_MIN); @@ -249,7 +247,7 @@ void AdafruitBluefruit::configPrphBandwidth(uint8_t bw) break; case BANDWIDTH_MAX: - configPrphConn(247, 6, 3, BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT); + configPrphConn(247, 100, 3, BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT); break; default: break; @@ -743,13 +741,14 @@ void adafruit_ble_task(void* arg) { (void) arg; + // malloc buffered is algined by 4 uint8_t * ev_buf = (uint8_t*) rtos_malloc(BLE_EVT_LEN_MAX(BLE_GATT_ATT_MTU_MAX)); while (1) { if ( xSemaphoreTake(Bluefruit._ble_event_sem, portMAX_DELAY) ) { - uint32_t err = ERROR_NONE; + uint32_t err = NRF_SUCCESS; // Until no pending events while( NRF_ERROR_NOT_FOUND != err ) @@ -759,10 +758,13 @@ void adafruit_ble_task(void* arg) // Get BLE Event err = sd_ble_evt_get(ev_buf, &ev_len); - // Handle valid event, ignore error - if( ERROR_NONE == err) + // Handle valid event + if( NRF_SUCCESS == err) { Bluefruit._ble_handler( (ble_evt_t*) ev_buf ); + }else if ( NRF_ERROR_NOT_FOUND != err ) + { + LOG_LV1("BLE", "SD event error %s", dbg_err_str(err)); } } } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 1acf1a4f..ffe5280d 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -1,38 +1,26 @@ -/**************************************************************************/ -/*! - @file bluefruit.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2018, Adafruit Industries (adafruit.com) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ +/* + * The MIT License (MIT) + * + * Copyright (c) 2019, hathach (tinyusb.org) for Adafruit + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ #ifndef BLUEFRUIT_H_ #define BLUEFRUIT_H_ @@ -130,8 +118,8 @@ class AdafruitBluefruit void configAttrTableSize (uint32_t attr_table_size); // Configure Bandwidth for connections - void configPrphConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize); - void configCentralConn (uint16_t mtu_max, uint8_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize); + void configPrphConn (uint16_t mtu_max, uint16_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize); + void configCentralConn (uint16_t mtu_max, uint16_t event_len, uint8_t hvn_qsize, uint8_t wrcmd_qsize); void configPrphBandwidth (uint8_t bw); void configCentralBandwidth(uint8_t bw); @@ -211,10 +199,10 @@ class AdafruitBluefruit // Bandwidth configuration struct { - uint16_t mtu_max; - uint8_t event_len; - uint8_t hvn_qsize; - uint8_t wrcmd_qsize; + uint16_t mtu_max; + uint16_t event_len; + uint8_t hvn_qsize; + uint8_t wrcmd_qsize; }prph, central; }_sd_cfg; diff --git a/libraries/Bluefruit52Lib/src/services/BLEUart.cpp b/libraries/Bluefruit52Lib/src/services/BLEUart.cpp index a178e48a..fca91e37 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEUart.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEUart.cpp @@ -69,6 +69,7 @@ BLEUart::BLEUart(uint16_t fifo_depth) _rx_cb = NULL; _notify_cb = NULL; + _overflow_cb = NULL; _tx_fifo = NULL; _tx_buffered = false; @@ -84,8 +85,15 @@ BLEUart::~BLEUart() void BLEUart::bleuart_rxd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len) { BLEUart& svc = (BLEUart&) chr->parentService(); + uint16_t wrcount = svc._rx_fifo->write(data, len); - svc._rx_fifo->write(data, len); + if ( wrcount < len ) + { + LOG_LV1("MEMORY", "bleuart rxd fifo OVERFLOWED!"); + + // invoke overflow callback + if (svc._overflow_cb) svc._overflow_cb(conn_hdl, len - wrcount); + } #if CFG_DEBUG >= 2 LOG_LV2("BLEUART", "RX: "); @@ -103,9 +111,16 @@ void BLEUart::bleuart_txd_cccd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uin if ( svc._notify_cb ) svc._notify_cb(conn_hdl, value & BLE_GATT_HVX_NOTIFICATION); } -void BLEUart::setRxCallback( rx_callback_t fp) +void BLEUart::setRxCallback(rx_callback_t fp, bool deferred) { _rx_cb = fp; + + _rxd.setWriteCallback(BLEUart::bleuart_rxd_cb, deferred); +} + +void BLEUart::setRxOverflowCallback(rx_overflow_callback_t fp) +{ + _overflow_cb = fp; } void BLEUart::setNotifyCallback(notify_callback_t fp) @@ -157,7 +172,7 @@ err_t BLEUart::begin(void) // Add RXD Characteristic _rxd.setProperties(CHR_PROPS_WRITE | CHR_PROPS_WRITE_WO_RESP); - _rxd.setWriteCallback(BLEUart::bleuart_rxd_cb); + _rxd.setWriteCallback(BLEUart::bleuart_rxd_cb, true); // TODO enable encryption when bonding is enabled _rxd.setPermission(SECMODE_NO_ACCESS, SECMODE_OPEN); diff --git a/libraries/Bluefruit52Lib/src/services/BLEUart.h b/libraries/Bluefruit52Lib/src/services/BLEUart.h index 60e6d764..97545c71 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEUart.h +++ b/libraries/Bluefruit52Lib/src/services/BLEUart.h @@ -53,6 +53,7 @@ class BLEUart : public BLEService, public Stream public: typedef void (*rx_callback_t) (uint16_t conn_hdl); typedef void (*notify_callback_t)(uint16_t conn_hdl, bool enabled); + typedef void (*rx_overflow_callback_t) (uint16_t conn_hdl, uint16_t leftover); BLEUart(uint16_t fifo_depth = BLE_UART_DEFAULT_FIFO_DEPTH); virtual ~BLEUart(); @@ -62,7 +63,8 @@ class BLEUart : public BLEService, public Stream bool notifyEnabled(void); bool notifyEnabled(uint16_t conn_hdl); - void setRxCallback (rx_callback_t fp); + void setRxCallback (rx_callback_t fp, bool deferred = true); + void setRxOverflowCallback(rx_overflow_callback_t fp); void setNotifyCallback(notify_callback_t fp); void bufferTXD(bool enable); @@ -106,8 +108,9 @@ class BLEUart : public BLEService, public Stream bool _tx_buffered; // default is false // Callbacks - rx_callback_t _rx_cb; - notify_callback_t _notify_cb; + rx_callback_t _rx_cb; + notify_callback_t _notify_cb; + rx_overflow_callback_t _overflow_cb; // Static Method for callbacks static void bleuart_rxd_cb(uint16_t conn_hdl, BLECharacteristic* chr, uint8_t* data, uint16_t len); diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 25631f0c..28a1073f 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -131,9 +131,7 @@ static void bond_save_keys_dfr (uint8_t role, uint16_t conn_hdl, bond_keys_t* bk bool bond_save_keys (uint8_t role, uint16_t conn_hdl, bond_keys_t* bkeys) { // queue to execute in Ada Callback thread - ada_callback(bkeys, sizeof(bond_keys_t), bond_save_keys_dfr, role, conn_hdl, bkeys); - - return true; + return ada_callback(bkeys, sizeof(bond_keys_t), bond_save_keys_dfr, role, conn_hdl, bkeys); } bool bond_load_keys(uint8_t role, uint16_t ediv, bond_keys_t* bkeys) @@ -190,9 +188,7 @@ bool bond_save_cccd (uint8_t role, uint16_t conn_hdl, uint16_t ediv) VERIFY(ediv != 0xFFFF); // queue to execute in Ada Callback thread - ada_callback(NULL, 0, bond_save_cccd_dfr, role, conn_hdl, ediv); - - return true; + return ada_callback(NULL, 0, bond_save_cccd_dfr, role, conn_hdl, ediv); } bool bond_load_cccd(uint8_t role, uint16_t conn_hdl, uint16_t ediv)