From dee231e9bd685f32c0f24211430759ef002de021 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Aug 2019 13:25:50 +0700 Subject: [PATCH 01/19] get image_upload work with 3.5" TFT featherwing --- .../tinyusb/src/device/usbd.h | 4 - .../Peripheral/image_upload/image_upload.ino | 84 +++++++++++-------- 2 files changed, 50 insertions(+), 38 deletions(-) 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/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index c950395a..a7db5719 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -13,14 +13,45 @@ *********************************************************************/ /* 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 */ +// if USE_35_TFT_FEATHERWING = 0 then the 2.4" TFT will be used instead +#define USE_35_TFT_FEATHERWING 1 + #include #include #include -#include + +#ifdef ARDUINO_NRF52832_FEATHER + #define TFT_DC 11 + #define TFT_CS 31 +#endif + +#ifdef ARDUINO_NRF52840_FEATHER + #define TFT_DC 10 + #define TFT_CS 9 +#endif + +#ifdef ARDUINO_NRF52840_CIRCUITPLAY + #define TFT_DC A7 + #define TFT_CS A6 +#endif + +#if USE_35_TFT_FEATHERWING + #include "Adafruit_HX8357.h" + Adafruit_HX8357 tft = Adafruit_HX8357(TFT_CS, TFT_DC); +#else + #include + Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC); +#endif + +#define COLOR_WHITE 0xFFFF +#define COLOR_BLACK 0x0000 +#define COLOR_YELLOW 0xFFE0 +#define COLOR_GREEN 0x07E0 // Uart over BLE with large buffer to hold image data BLEUart bleuart(1024*10); @@ -50,31 +81,14 @@ uint16_t color_buf[2048]; uint32_t rxStartTime = 0; uint32_t rxLastTime = 0; -#ifdef ARDUINO_NRF52832_FEATHER - #define TFT_DC 11 - #define TFT_CS 31 -#endif - -#ifdef ARDUINO_NRF52840_FEATHER - #define TFT_DC 10 - #define TFT_CS 9 -#endif - -#ifdef ARDUINO_NRF52840_CIRCUITPLAY - #define TFT_DC A7 - #define TFT_CS A6 -#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.fillScreen(COLOR_BLACK); + tft.setTextColor(COLOR_WHITE); tft.setTextSize(1); // Config the peripheral connection with maximum bandwidth @@ -135,7 +149,7 @@ void loop() if ( !bleuart.available() ) return; // all pixel data is received - if ( totalPixel == imageWidth*imageHeight ) + if ( (totalPixel != 0) && (totalPixel == imageWidth*imageHeight) ) { uint8_t crc = bleuart.read(); // do checksum later @@ -193,9 +207,9 @@ void connect_callback(uint16_t conn_handle) conn->requestMtuExchange(247); tft.println("Exchanging MTU"); - tft.setTextColor(ILI9341_GREEN); + tft.setTextColor(COLOR_GREEN); tft.println("Ready to receive new image"); - tft.setTextColor(ILI9341_WHITE); + tft.setTextColor(COLOR_WHITE); } void print_speed(uint32_t count, uint32_t ms) @@ -203,27 +217,27 @@ void print_speed(uint32_t count, uint32_t ms) tft.setCursor(0, imageHeight+5); tft.print("Received "); - tft.setTextColor(ILI9341_YELLOW); + tft.setTextColor(COLOR_YELLOW); tft.print(count); - tft.setTextColor(ILI9341_WHITE); + tft.setTextColor(COLOR_WHITE); tft.print(" bytes in "); - tft.setTextColor(ILI9341_YELLOW); + tft.setTextColor(COLOR_YELLOW); tft.print(ms / 1000.0F, 2); - tft.setTextColor(ILI9341_WHITE); + tft.setTextColor(COLOR_WHITE); tft.println(" seconds"); tft.print("Speed: "); - tft.setTextColor(ILI9341_YELLOW); + tft.setTextColor(COLOR_YELLOW); tft.print( (count / 1000.0F) / (ms / 1000.0F), 2); - tft.setTextColor(ILI9341_WHITE); + tft.setTextColor(COLOR_WHITE); tft.println(" KB/s"); - tft.setTextColor(ILI9341_GREEN); + tft.setTextColor(COLOR_GREEN); tft.println("Ready to receive new image"); - tft.setTextColor(ILI9341_WHITE); + tft.setTextColor(COLOR_WHITE); } void bleuart_rx_callback(uint16_t conn_hdl) @@ -249,7 +263,7 @@ void bleuart_rx_callback(uint16_t conn_hdl) PRINT_INT(imageWidth); PRINT_INT(imageHeight); - tft.fillScreen(ILI9341_BLACK); + tft.fillScreen(COLOR_BLACK); tft.setCursor(0, 0); imageX = imageY = 0; } @@ -264,9 +278,11 @@ 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; + + bleuart.flush(); } From d81599d61974b93fe439fdab03144366cc6d1b68 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Aug 2019 23:55:58 +0700 Subject: [PATCH 02/19] increase ada callback queue size from 20 to 40 - fox adacallback queue overflow with large image - fix issue with tft draw bitmap --- cores/nRF5/utility/AdaCallback.c | 8 +++---- cores/nRF5/utility/AdaCallback.h | 2 +- .../Peripheral/image_upload/image_upload.ino | 22 ++++++++++++------- .../Bluefruit52Lib/src/BLECharacteristic.cpp | 13 +++++------ 4 files changed, 25 insertions(+), 20 deletions(-) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index c3a3b948..ac3f1acc 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -47,9 +47,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; @@ -85,7 +82,10 @@ void ada_callback_queue(ada_callback_t* cb_item) xQueueSendFromISR(_cb_queue, (void*) &cb_item, NULL); }else { - xQueueSend(_cb_queue, (void*) &cb_item, CFG_CALLBACK_TIMEOUT); + if ( !xQueueSend(_cb_queue, (void*) &cb_item, CFG_CALLBACK_TIMEOUT) ) + { + LOG_LV1("MEMORY", "AdaCallback run out of queue item, increase CFG_CALLBACK_QUEUE_LENGTH"); + } } } diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index b22891f3..e68cca79 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -43,7 +43,7 @@ #endif #ifndef CFG_CALLBACK_QUEUE_LENGTH -#define CFG_CALLBACK_QUEUE_LENGTH 20 +#define CFG_CALLBACK_QUEUE_LENGTH 40 #endif #ifndef CFG_CALLBACK_TIMEOUT diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index a7db5719..dca26b66 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -68,8 +68,6 @@ BLEUart bleuart(1024*10); uint16_t imageWidth = 0; uint16_t imageHeight = 0; -uint16_t imageX = 0; -uint16_t imageY = 0; uint32_t totalPixel = 0; // received pixel @@ -172,6 +170,19 @@ void loop() // Chop pixel number to multiple of image width pixelNum = (pixelNum / imageWidth) * imageWidth; +#if 0 + static uint32_t last_available = 0; + if ( last_available != bleuart.available() ) + { + last_available = bleuart.available(); + + PRINT_INT(totalPixel); + PRINT_INT(last_available); + PRINT_INT(pixelNum); + Serial.println(); + } +#endif + if ( pixelNum ) { for ( uint16_t i=0; i < pixelNum; i++) @@ -183,12 +194,8 @@ void loop() color_buf[i] = ((red & 0xF8) << 8) | ((green & 0xFC) << 3) | ( blue >> 3); } - tft.drawRGBBitmap(imageX, imageY, color_buf, imageWidth, imageHeight - imageY); - + tft.drawRGBBitmap(0, totalPixel/imageWidth, color_buf, imageWidth, pixelNum/imageWidth); totalPixel += pixelNum; - - imageX = totalPixel % imageWidth; - imageY = totalPixel / imageWidth; } } @@ -265,7 +272,6 @@ void bleuart_rx_callback(uint16_t conn_hdl) tft.fillScreen(COLOR_BLACK); tft.setCursor(0, 0); - imageX = imageY = 0; } } diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index 98938b3a..f1277c35 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -468,12 +468,11 @@ 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) { @@ -490,13 +489,13 @@ 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); From 11892496407a922a86b0cd41d6ecbf59c32938e3 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 27 Aug 2019 00:15:08 +0700 Subject: [PATCH 03/19] use queue static API for adacallback, increase CFG_CALLBACK_QUEUE_LENGTH to 80 --- cores/nRF5/utility/AdaCallback.c | 4 +++- cores/nRF5/utility/AdaCallback.h | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index ac3f1acc..fd44bdf7 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -37,6 +37,8 @@ #include "Arduino.h" static QueueHandle_t _cb_queue = NULL; +static uint8_t _cb_qbuf[CFG_CALLBACK_QUEUE_LENGTH*sizeof(void*)]; +static StaticQueue_t _cb_static_q; void adafruit_callback_task(void* arg) { @@ -122,7 +124,7 @@ void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const voi void ada_callback_init(void) { // queue to hold "Pointer to callback data" - _cb_queue = xQueueCreate(CFG_CALLBACK_QUEUE_LENGTH, sizeof(ada_callback_t*)); + _cb_queue = xQueueCreateStatic(CFG_CALLBACK_QUEUE_LENGTH, sizeof(void*), _cb_qbuf, &_cb_static_q); TaskHandle_t callback_task_hdl; xTaskCreate( adafruit_callback_task, "Callback", CFG_CALLBACK_TASK_STACKSIZE, NULL, TASK_PRIO_NORMAL, &callback_task_hdl); diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index e68cca79..923e1779 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -43,7 +43,7 @@ #endif #ifndef CFG_CALLBACK_QUEUE_LENGTH -#define CFG_CALLBACK_QUEUE_LENGTH 40 +#define CFG_CALLBACK_QUEUE_LENGTH 60 #endif #ifndef CFG_CALLBACK_TIMEOUT From 57bf2d09640b6527517fe19cdaef4ba28a3bd304 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 27 Aug 2019 09:43:17 +0700 Subject: [PATCH 04/19] increase event length to 100 for max bandwidth --- libraries/Bluefruit52Lib/src/bluefruit.cpp | 8 ++++---- libraries/Bluefruit52Lib/src/bluefruit.h | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index a5860d06..53772ca2 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -210,7 +210,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 +218,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 +249,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; @@ -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_LV2("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl); + LOG_LV1("BLE", "%s : Conn Handle = %d", dbg_ble_event_str(evt->header.evt_id), conn_hdl); // GAP handler if ( conn ) conn->_eventHandler(evt); diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 1acf1a4f..ae2695ec 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -130,8 +130,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 +211,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; From d900149a615d92881170b94be8885716d4af7695 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 27 Aug 2019 11:10:05 +0700 Subject: [PATCH 05/19] fix travis build --- .travis.yml | 2 +- libraries/Bluefruit52Lib/src/bluefruit.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 53772ca2..bf7ff541 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -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); From d2fb5785ddb01362fa45706285515e864d9fa1cb Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 11:57:49 +0700 Subject: [PATCH 06/19] clean up --- cores/nRF5/main.cpp | 2 +- cores/nRF5/rtos.h | 14 +++----------- 2 files changed, 4 insertions(+), 12 deletions(-) diff --git a/cores/nRF5/main.cpp b/cores/nRF5/main.cpp index 7d79b9bb..b40e44e1 100644 --- a/cores/nRF5/main.cpp +++ b/cores/nRF5/main.cpp @@ -56,7 +56,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(); 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_ */ From 5a4b00fa98c88a0a6f40d21cd6cdd61f7b98176a Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 12:00:02 +0700 Subject: [PATCH 07/19] add BLEUart overflowed callback --- libraries/Bluefruit52Lib/src/services/BLEUart.cpp | 15 ++++++++++++++- libraries/Bluefruit52Lib/src/services/BLEUart.h | 7 +++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEUart.cpp b/libraries/Bluefruit52Lib/src/services/BLEUart.cpp index a178e48a..4642ed31 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: "); @@ -108,6 +116,11 @@ void BLEUart::setRxCallback( rx_callback_t fp) _rx_cb = fp; } +void BLEUart::setRxOverflowCallback(rx_overflow_callback_t fp) +{ + _overflow_cb = fp; +} + void BLEUart::setNotifyCallback(notify_callback_t fp) { _notify_cb = fp; diff --git a/libraries/Bluefruit52Lib/src/services/BLEUart.h b/libraries/Bluefruit52Lib/src/services/BLEUart.h index 60e6d764..f584bec8 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(); @@ -63,6 +64,7 @@ class BLEUart : public BLEService, public Stream bool notifyEnabled(uint16_t conn_hdl); void setRxCallback (rx_callback_t fp); + 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); From c54d4ed2e8848d503d866442b7ed7028646a4fef Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 12:00:30 +0700 Subject: [PATCH 08/19] change license from BSD to MIT for bluefruit.h --- libraries/Bluefruit52Lib/src/bluefruit.h | 58 ++++++++++-------------- 1 file changed, 23 insertions(+), 35 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index ae2695ec..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_ From d7caa6405a338367594b4212d8fc63c31165787f Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 12:02:36 +0700 Subject: [PATCH 09/19] improve ada callback, automatically resize queue depth when needed --- cores/nRF5/utility/AdaCallback.c | 60 +++++++++++++++++++++++++++----- cores/nRF5/utility/AdaCallback.h | 6 +--- 2 files changed, 52 insertions(+), 14 deletions(-) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index fd44bdf7..9858b1e4 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -36,9 +36,10 @@ #include "Arduino.h" +#define INITIAL_QUEUE_DEPTH 64 + static QueueHandle_t _cb_queue = NULL; -static uint8_t _cb_qbuf[CFG_CALLBACK_QUEUE_LENGTH*sizeof(void*)]; -static StaticQueue_t _cb_static_q; +static uint32_t _cb_qdepth; void adafruit_callback_task(void* arg) { @@ -79,14 +80,26 @@ 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 - { - if ( !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) ) { - LOG_LV1("MEMORY", "AdaCallback run out of queue item, increase CFG_CALLBACK_QUEUE_LENGTH"); + _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"); } } } @@ -124,8 +137,37 @@ void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const voi void ada_callback_init(void) { // queue to hold "Pointer to callback data" - _cb_queue = xQueueCreateStatic(CFG_CALLBACK_QUEUE_LENGTH, sizeof(void*), _cb_qbuf, &_cb_static_q); + _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); } + +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); + + 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(); + + return true; +} diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index 923e1779..c206ae81 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -42,15 +42,10 @@ #define CFG_CALLBACK_TASK_STACKSIZE (512*2) #endif -#ifndef CFG_CALLBACK_QUEUE_LENGTH -#define CFG_CALLBACK_QUEUE_LENGTH 60 -#endif - #ifndef CFG_CALLBACK_TIMEOUT #define CFG_CALLBACK_TIMEOUT 100 #endif - #ifdef __cplusplus extern "C"{ #endif @@ -115,6 +110,7 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); 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_queue(ada_callback_t* cb_item); +bool ada_callback_queue_resize(uint32_t new_depth); #ifdef __cplusplus } From 144bbb531a1a7f247b2ab895c2f60239c2810cb1 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 12:03:39 +0700 Subject: [PATCH 10/19] upgrade image_upload, able to handle write without response --- .../Peripheral/image_upload/image_upload.ino | 146 +++++++++--------- 1 file changed, 77 insertions(+), 69 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index dca26b66..e4cfc3c9 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -52,9 +52,12 @@ #define COLOR_BLACK 0x0000 #define COLOR_YELLOW 0xFFE0 #define COLOR_GREEN 0x07E0 +#define COLOR_RED 0xF800 -// Uart over BLE with large buffer to hold image data -BLEUart bleuart(1024*10); +// 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 @@ -71,14 +74,15 @@ uint16_t imageHeight = 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]; +// 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() { @@ -104,6 +108,7 @@ void setup() // Configure and Start BLE Uart Service bleuart.begin(); bleuart.setRxCallback(bleuart_rx_callback); + bleuart.setRxOverflowCallback(bleuart_overflow_callback); // Set up and start advertising startAdv(); @@ -142,12 +147,61 @@ void startAdv(void) void loop() { - if ( !Bluefruit.connected() ) return; - if ( !bleuart.notifyEnabled() ) return; - if ( !bleuart.available() ) return; + // 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; + + rxLastTime = millis(); + + // Received new Image + if ( (imageWidth == 0) && (imageHeight == 0) ) + { + // take note of time of first packet + rxStartTime = millis(); + + // Skip all data until '!I' is found + while( bleuart.available() && bleuart.read() != '!' ) { } + if (bleuart.read() != 'I') return; + + if ( !bleuart.available() ) return; + + imageWidth = bleuart.read16(); + imageHeight = bleuart.read16(); + + totalPixel = 0; + + PRINT_INT(imageWidth); + PRINT_INT(imageHeight); + + tft.fillScreen(COLOR_BLACK); + tft.setCursor(0, 0); + } + + // Extract pixel data to buffer and draw image line by line + while ( bleuart.available() >= 3 ) + { + uint8_t rgb[3]; + bleuart.read(rgb, 3); + + pixel_buf[totalPixel % imageWidth] = ((rgb[0] & 0xF8) << 8) | ((rgb[1] & 0xFC) << 3) | (rgb[2] >> 3); + + 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 != 0) && (totalPixel == imageWidth*imageHeight) ) + if ( totalPixel == imageWidth*imageHeight ) { uint8_t crc = bleuart.read(); // do checksum later @@ -158,45 +212,6 @@ void loop() // 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 0 - static uint32_t last_available = 0; - if ( last_available != bleuart.available() ) - { - last_available = bleuart.available(); - - PRINT_INT(totalPixel); - PRINT_INT(last_available); - PRINT_INT(pixelNum); - Serial.println(); - } -#endif - - 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(0, totalPixel/imageWidth, color_buf, imageWidth, pixelNum/imageWidth); - totalPixel += pixelNum; - } } void connect_callback(uint16_t conn_handle) @@ -247,36 +262,28 @@ void print_speed(uint32_t count, uint32_t ms) tft.setTextColor(COLOR_WHITE); } -void bleuart_rx_callback(uint16_t conn_hdl) +void bleuart_overflow_callback(uint16_t conn_hdl, uint16_t leftover) { - (void) conn_hdl; + Serial.println("BLEUART rx buffer OVERFLOWED!"); + Serial.println("Please increase buffer size for bleuart"); - rxLastTime = millis(); - - // Received new Image - if ( (imageWidth == 0) && (imageHeight == 0) ) + // only print the first time this occur, need disconnect to reset + if (!bleuart_overflowed) { - rxStartTime = millis(); + tft.setCursor(0, imageHeight+5); - // Skip all data until '!I' is found - while( bleuart.available() && bleuart.read() != '!' ) { } - if (bleuart.read() != 'I') return; + tft.setTextColor(COLOR_RED); + tft.println("BLEUART rx buffer OVERFLOWED!"); - if ( !bleuart.available() ) return; - - imageWidth = bleuart.read16(); - imageHeight = bleuart.read16(); - - PRINT_INT(imageWidth); - PRINT_INT(imageHeight); - - tft.fillScreen(COLOR_BLACK); - tft.setCursor(0, 0); + 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 */ @@ -289,6 +296,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) tft.println("Advertising ..."); totalPixel = imageWidth = imageHeight = 0; + bleuart_overflowed = false; bleuart.flush(); } From 8395b5e8e459c1146913eac50a94c3302a040626 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 18 Sep 2019 16:01:30 +0700 Subject: [PATCH 11/19] clean up --- .../Peripheral/image_upload/image_upload.ino | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index e4cfc3c9..aeab4afd 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -207,7 +207,7 @@ void bleuart_rx_callback(uint16_t conn_hdl) // do checksum later // print speed summary - print_speed(totalPixel*3 + 7, rxLastTime-rxStartTime); + print_summary(totalPixel*3 + 7, rxLastTime-rxStartTime); // reset and waiting for new image totalPixel = imageWidth = imageHeight = 0; @@ -234,7 +234,7 @@ void connect_callback(uint16_t conn_handle) tft.setTextColor(COLOR_WHITE); } -void print_speed(uint32_t count, uint32_t ms) +void print_summary(uint32_t count, uint32_t ms) { tft.setCursor(0, imageHeight+5); tft.print("Received "); @@ -251,11 +251,17 @@ void print_speed(uint32_t count, uint32_t ms) tft.println(" seconds"); - tft.print("Speed: "); + tft.print("Speed "); tft.setTextColor(COLOR_YELLOW); tft.print( (count / 1000.0F) / (ms / 1000.0F), 2); tft.setTextColor(COLOR_WHITE); - tft.println(" KB/s"); + tft.print(" KB/s with "); + + 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"); From 2a4185573bf567115284481085145dfe49a58c6f Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 19 Sep 2019 16:42:36 +0700 Subject: [PATCH 12/19] reduce task stack size - ble task from 512*3 -> 256*5 - loop task from 512*3 -> 256*4 - callback task from 512*2 -> 256*3 - usbd task from 150 -> 200 --- .../Adafruit_TinyUSB_Core.cpp | 2 +- cores/nRF5/linker/nrf52832_s132_v6.ld | 1 - cores/nRF5/main.cpp | 5 +++-- cores/nRF5/rtos.cpp | 1 + cores/nRF5/utility/AdaCallback.c | 4 ++-- cores/nRF5/utility/AdaCallback.h | 6 +----- libraries/Bluefruit52Lib/src/bluefruit.cpp | 20 ++++++++++--------- 7 files changed, 19 insertions(+), 20 deletions(-) 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/linker/nrf52832_s132_v6.ld b/cores/nRF5/linker/nrf52832_s132_v6.ld index 9c8af1f2..a70efd8d 100755 --- a/cores/nRF5/linker/nrf52832_s132_v6.ld +++ b/cores/nRF5/linker/nrf52832_s132_v6.ld @@ -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 b40e44e1..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) { @@ -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/rtos.cpp b/cores/nRF5/rtos.cpp index 2006822c..dd57eea7 100644 --- a/cores/nRF5/rtos.cpp +++ b/cores/nRF5/rtos.cpp @@ -94,6 +94,7 @@ void yield(void) void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ) { LOG_LV1("RTOS", "%s Stack Overflow !!!", pcTaskName); + while(1) yield(); } void vApplicationMallocFailedHook(void) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index 9858b1e4..5064829e 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -134,14 +134,14 @@ void ada_callback_invoke(const void* malloc_data, uint32_t malloc_len, const voi ada_callback_queue(cb_data); } -void ada_callback_init(void) +void ada_callback_init(uint32_t stack_sz) { // queue to hold "Pointer to callback data" _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, &callback_task_hdl); } bool ada_callback_queue_resize(uint32_t new_depth) diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index c206ae81..b6587606 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -38,10 +38,6 @@ #include "common_inc.h" -#ifndef CFG_CALLBACK_TASK_STACKSIZE -#define CFG_CALLBACK_TASK_STACKSIZE (512*2) -#endif - #ifndef CFG_CALLBACK_TIMEOUT #define CFG_CALLBACK_TIMEOUT 100 #endif @@ -107,7 +103,7 @@ typedef void (*adacb_5arg_t) (uint32_t, uint32_t, uint32_t, uint32_t, uint32_t); #define ada_callback(...) _cb_setup(__VA_ARGS__) -void ada_callback_init(void); +void ada_callback_init(uint32_t stack_sz); void 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); diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index bf7ff541..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 @@ -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)); } } } From e400dc895de44e5a2957019b688e74178248a463 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 11:33:32 +0700 Subject: [PATCH 13/19] fix newlib nano _sbrk() is not linked for checking heap --- cores/nRF5/common_func.h | 6 -- cores/nRF5/linker/nrf52832_s132_v6.ld | 2 +- cores/nRF5/new.cpp | 47 +++++++++++++++ cores/nRF5/rtos.cpp | 7 ++- cores/nRF5/syscall_newlib.c | 87 --------------------------- cores/nRF5/utility/adafruit_fifo.cpp | 2 +- 6 files changed, 53 insertions(+), 98 deletions(-) delete mode 100644 cores/nRF5/syscall_newlib.c 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 a70efd8d..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 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 dd57eea7..58e4bd86 100644 --- a/cores/nRF5/rtos.cpp +++ b/cores/nRF5/rtos.cpp @@ -93,13 +93,14 @@ void yield(void) void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ) { - LOG_LV1("RTOS", "%s Stack Overflow !!!", pcTaskName); - while(1) yield(); + 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/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/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(); } From e57a039d6356edfc3a872417163b7b5d5b6a9e3c Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 11:37:36 +0700 Subject: [PATCH 14/19] suspend callback task when reszing, still there is chance to run into issue. --- cores/nRF5/utility/AdaCallback.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index 5064829e..96dccd8a 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -40,6 +40,7 @@ static QueueHandle_t _cb_queue = NULL; static uint32_t _cb_qdepth; +static TaskHandle_t _cb_task; void adafruit_callback_task(void* arg) { @@ -140,8 +141,7 @@ void ada_callback_init(uint32_t stack_sz) _cb_qdepth = INITIAL_QUEUE_DEPTH; _cb_queue = xQueueCreate(_cb_qdepth, sizeof(void*)); - TaskHandle_t callback_task_hdl; - xTaskCreate( adafruit_callback_task, "Callback", stack_sz, 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) @@ -152,6 +152,7 @@ bool ada_callback_queue_resize(uint32_t new_depth) LOG_LV1("MEMORY", "AdaCallback increase queue depth to %d", new_depth); + vTaskSuspend(_cb_task); taskENTER_CRITICAL(); // move item from old queue @@ -168,6 +169,7 @@ bool ada_callback_queue_resize(uint32_t new_depth) _cb_queue = new_queue; taskEXIT_CRITICAL(); + vTaskResume(_cb_task); return true; } From 31ed8a4fbb4324c2e67faf823020437b82a948b3 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 15:28:13 +0700 Subject: [PATCH 15/19] improve ada callback, return false if there is not enough memory. --- cores/nRF5/utility/AdaCallback.c | 11 ++++++++++- cores/nRF5/utility/AdaCallback.h | 20 +++++++------------- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/cores/nRF5/utility/AdaCallback.c b/cores/nRF5/utility/AdaCallback.c index 96dccd8a..64e51b70 100644 --- a/cores/nRF5/utility/AdaCallback.c +++ b/cores/nRF5/utility/AdaCallback.c @@ -105,9 +105,11 @@ void ada_callback_queue(ada_callback_t* cb_item) } } -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; @@ -115,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); } @@ -133,6 +140,8 @@ 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(uint32_t stack_sz) diff --git a/cores/nRF5/utility/AdaCallback.h b/cores/nRF5/utility/AdaCallback.h index b6587606..887f0bf3 100644 --- a/cores/nRF5/utility/AdaCallback.h +++ b/cores/nRF5/utility/AdaCallback.h @@ -81,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 @@ -100,11 +90,15 @@ 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(uint32_t stack_sz); -void ada_callback_invoke(const void* mdata, uint32_t mlen, const void* func, uint32_t arguments[], uint8_t argcount); +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); From 940e902edd1ab02103e684dbcf54284a01ca53cf Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 15:32:36 +0700 Subject: [PATCH 16/19] BLECharacteristic falls back to immed call if ada callback failed --- .../Bluefruit52Lib/src/BLECharacteristic.cpp | 35 +++++++------------ .../src/BLEClientCharacteristic.cpp | 12 +++---- .../Bluefruit52Lib/src/utility/bonding.cpp | 8 ++--- 3 files changed, 18 insertions(+), 37 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index f1277c35..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); } @@ -476,10 +470,8 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) 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); } @@ -496,11 +488,8 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) if (_cccd_wr_cb) { - 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/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) From 460222ba21cc3ac27273364daa8becc83bf52f3a Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 15:33:05 +0700 Subject: [PATCH 17/19] add deferred option to BLEUart setRxCallback() --- libraries/Bluefruit52Lib/src/services/BLEUart.cpp | 6 ++++-- libraries/Bluefruit52Lib/src/services/BLEUart.h | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEUart.cpp b/libraries/Bluefruit52Lib/src/services/BLEUart.cpp index 4642ed31..fca91e37 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEUart.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEUart.cpp @@ -111,9 +111,11 @@ 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) @@ -170,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 f584bec8..97545c71 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEUart.h +++ b/libraries/Bluefruit52Lib/src/services/BLEUart.h @@ -63,7 +63,7 @@ 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); From c31deb3a5bfb334ea0bbe979b5322d18598dd20b Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 23 Sep 2019 16:34:24 +0700 Subject: [PATCH 18/19] update image upload to support color depth 16 or 24 bit. --- .../Peripheral/image_upload/image_upload.ino | 73 +++++++++++++++---- 1 file changed, 57 insertions(+), 16 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index aeab4afd..ae150fba 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -16,10 +16,15 @@ * 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 */ -// if USE_35_TFT_FEATHERWING = 0 then the 2.4" TFT will be used instead -#define USE_35_TFT_FEATHERWING 1 +#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 @@ -40,12 +45,16 @@ #define TFT_CS A6 #endif -#if USE_35_TFT_FEATHERWING +#if TFT_IN_USE == TFT_35_FEATHERWING #include "Adafruit_HX8357.h" Adafruit_HX8357 tft = Adafruit_HX8357(TFT_CS, TFT_DC); -#else +#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 #define COLOR_WHITE 0xFFFF @@ -62,15 +71,17 @@ 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' ] [ uint16 width ] [ uint16 height ] [ r g b ] [ r g b ] [ r g b ] … [ 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 @@ -107,7 +118,21 @@ 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 @@ -171,11 +196,13 @@ void bleuart_rx_callback(uint16_t conn_hdl) if ( !bleuart.available() ) return; + imageColorBit = bleuart.read8(); imageWidth = bleuart.read16(); imageHeight = bleuart.read16(); totalPixel = 0; + PRINT_INT(imageColorBit); PRINT_INT(imageWidth); PRINT_INT(imageHeight); @@ -186,10 +213,18 @@ void bleuart_rx_callback(uint16_t conn_hdl) // Extract pixel data to buffer and draw image line by line while ( bleuart.available() >= 3 ) { - uint8_t rgb[3]; - bleuart.read(rgb, 3); - - pixel_buf[totalPixel % imageWidth] = ((rgb[0] & 0xF8) << 8) | ((rgb[1] & 0xFC) << 3) | (rgb[2] >> 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++; @@ -207,10 +242,12 @@ void bleuart_rx_callback(uint16_t conn_hdl) // do checksum later // print speed summary - print_summary(totalPixel*3 + 7, rxLastTime-rxStartTime); + print_summary(totalPixel*(imageColorBit/8) + 8, rxLastTime-rxStartTime); // reset and waiting for new image - totalPixel = imageWidth = imageHeight = 0; + imageColorBit = 0; + imageWidth = imageHeight = 0; + totalPixel = 0; } } @@ -220,6 +257,7 @@ void connect_callback(uint16_t conn_handle) tft.println("Connected"); +#if 1 conn->requestPHY(); tft.println("Switching PHY"); @@ -228,6 +266,7 @@ void connect_callback(uint16_t conn_handle) conn->requestMtuExchange(247); tft.println("Exchanging MTU"); +#endif tft.setTextColor(COLOR_GREEN); tft.println("Ready to receive new image"); @@ -251,14 +290,14 @@ void print_summary(uint32_t count, uint32_t ms) tft.println(" seconds"); - tft.print("Speed "); + tft.print("Speed: "); tft.setTextColor(COLOR_YELLOW); tft.print( (count / 1000.0F) / (ms / 1000.0F), 2); tft.setTextColor(COLOR_WHITE); - tft.print(" KB/s with "); + tft.print(" KB/s for "); tft.setTextColor(COLOR_YELLOW); - tft.print(imageWidth); tft.print(" x "); tft.print(imageHeight); + tft.print(imageWidth); tft.print("x"); tft.print(imageHeight); tft.setTextColor(COLOR_WHITE); tft.println(" Image"); @@ -301,7 +340,9 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) tft.setCursor(0, 0); tft.println("Advertising ..."); - totalPixel = imageWidth = imageHeight = 0; + imageColorBit = 0; + imageWidth = imageHeight = 0; + totalPixel = 0; bleuart_overflowed = false; bleuart.flush(); From 75f8a054f8f165999bfd660782e68c9dbe45156e Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 24 Sep 2019 12:28:10 +0700 Subject: [PATCH 19/19] everything works well:) --- .../examples/Peripheral/image_upload/image_upload.ino | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino index ae150fba..a7f5ff2a 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/image_upload/image_upload.ino @@ -257,7 +257,9 @@ void connect_callback(uint16_t conn_handle) tft.println("Connected"); -#if 1 + // 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"); @@ -266,7 +268,6 @@ void connect_callback(uint16_t conn_handle) conn->requestMtuExchange(247); tft.println("Exchanging MTU"); -#endif tft.setTextColor(COLOR_GREEN); tft.println("Ready to receive new image");