From b208773d0746f5fd4871b7c19cdf23fb698c0fdd Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 5 Apr 2019 16:03:29 +0700 Subject: [PATCH] added multiple peripheral example sketch bleuart_multi.ino --- changelog.md | 1 + .../StandardFirmataBLE/StandardFirmataBLE.ino | 9 +- .../examples/Peripheral/bleuart/bleuart.ino | 3 - .../bleuart_multi/bleuart_multi.ino | 166 ++++++++++++++++++ .../Peripheral/hid_keyboard/hid_keyboard.ino | 3 - libraries/Bluefruit52Lib/src/BLEGatt.cpp | 88 +++++----- libraries/Bluefruit52Lib/src/bluefruit.cpp | 6 +- 7 files changed, 211 insertions(+), 65 deletions(-) create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/bleuart_multi/bleuart_multi.ino diff --git a/changelog.md b/changelog.md index a61b5166..f5726ce2 100644 --- a/changelog.md +++ b/changelog.md @@ -10,6 +10,7 @@ - Added ARDUINO_NRF52832_FEATHER for feather 832, ARDUINO_NRF52840_FEATHER for feather 840, ARDUINO_NRF52_FEATHER for both - Fixed an memory leak with LFS, also extend to allow it to be used with SPI flash on other boards. Thanks @jeremypoulter - Seperate OTA DFU service from Bluefruit.begin(), sketch must explicit add it if needed. +- Added multiple peripheral-role connections support, example sketch is at `examples/Peripherals/bleuart_multi` - Introduce BLEPeriph class (Bluefruit.Periph) to mange peripheral role's connection - setConnInterval(), setConnIntervalMS(), setConnSupervisionTimeout(), setConnSupervisionTimeoutMS() - setConnectCallback(), setDisconnectCallback() diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/StandardFirmataBLE/StandardFirmataBLE.ino b/libraries/Bluefruit52Lib/examples/Peripheral/StandardFirmataBLE/StandardFirmataBLE.ino index 92fd90c6..f334d04f 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/StandardFirmataBLE/StandardFirmataBLE.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/StandardFirmataBLE/StandardFirmataBLE.ino @@ -869,13 +869,8 @@ void startAdv(void) *============================================================================*/ void loop() { - // Skip if not connected and bleuart notification is enabled - if ( !(Bluefruit.connected() && bleuart.notifyEnabled()) ) - { - // go to low power mode since there is nothing to do - waitForEvent(); - return; - } + // Skip if not connected and bleuart notification is not enabled + if ( !(Bluefruit.connected() && bleuart.notifyEnabled()) ) return; byte pin, analogPin; diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/bleuart/bleuart.ino b/libraries/Bluefruit52Lib/examples/Peripheral/bleuart/bleuart.ino index b38a12e0..e0681161 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/bleuart/bleuart.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/bleuart/bleuart.ino @@ -115,9 +115,6 @@ void loop() ch = (uint8_t) bleuart.read(); Serial.write(ch); } - - // Request CPU to enter low-power mode until an event/interrupt occurs - waitForEvent(); } // callback invoked when central connects diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/bleuart_multi/bleuart_multi.ino b/libraries/Bluefruit52Lib/examples/Peripheral/bleuart_multi/bleuart_multi.ino new file mode 100644 index 00000000..5f9c605e --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/bleuart_multi/bleuart_multi.ino @@ -0,0 +1,166 @@ +/********************************************************************* + This is an example for our nRF52 based Bluefruit LE modules + + Pick one up today in the adafruit shop! + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + MIT license, check LICENSE for more information + All text above, and the splash screen below must be included in + any redistribution +*********************************************************************/ +#include + +#define MAX_PRPH_CONNECTION 2 +uint8_t connection_count = 0; + +// BLE Service +BLEDfu bledfu; // OTA DFU service +BLEDis bledis; // device information +BLEUart bleuart; // uart over ble + +void setup() +{ + Serial.begin(115200); + while ( !Serial ) delay(10); // for nrf52840 with native usb + + Serial.println("Bluefruit52 BLEUART Example"); + Serial.println("---------------------------\n"); + + // Setup the BLE LED to be enabled on CONNECT + // Note: This is actually the default behaviour, but provided + // here in case you want to control this LED manually via PIN 19 + Bluefruit.autoConnLed(true); + + // Initialize Bluefruit with max concurrent connections as Peripheral = 2, Central = 0 + Bluefruit.begin(MAX_PRPH_CONNECTION, 0); + // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4 + Bluefruit.setTxPower(4); + Bluefruit.setName("Bluefruit52"); + Bluefruit.Periph.setConnectCallback(connect_callback); + Bluefruit.Periph.setDisconnectCallback(disconnect_callback); + + // To be consistent OTA DFU should be added first if it exists + bledfu.begin(); + + // Configure and Start Device Information Service + bledis.setManufacturer("Adafruit Industries"); + bledis.setModel("Bluefruit Feather52"); + bledis.begin(); + + // Configure and Start BLE Uart Service + bleuart.begin(); + + // Set up and start advertising + startAdv(); + + Serial.println("Please use Adafruit's Bluefruit LE app to connect in UART mode"); + Serial.println("Once connected, enter character(s) that you wish to send"); +} + +void startAdv(void) +{ + // Advertising packet + Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.Advertising.addTxPower(); + + // Include bleuart 128-bit uuid + Bluefruit.Advertising.addService(bleuart); + + // Secondary Scan Response packet (optional) + // Since there is no room for 'Name' in Advertising packet + Bluefruit.ScanResponse.addName(); + + /* Start Advertising + * - Enable auto advertising if disconnected + * - Interval: fast mode = 20 ms, slow mode = 152.5 ms + * - Timeout for fast mode is 30 seconds + * - Start(timeout) with timeout = 0 will advertise forever (until connected) + * + * For recommended advertising interval + * https://developer.apple.com/library/content/qa/qa1931/_index.html + */ + Bluefruit.Advertising.restartOnDisconnect(true); + Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms + Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode + Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds +} + + +// print a string to Serial Uart and all connected BLE Uart +void printAll(uint8_t* buf, int count) +{ + Serial.write(buf, count); + + // Send to all connected centrals + for (uint8_t conn_hdl=0; conn_hdl < MAX_PRPH_CONNECTION; conn_hdl++) + { + bleuart.write(conn_hdl, buf, count); + } +} + +void loop() +{ + uint8_t buf[64]; + int count; + + // Forward data from HW Serial to BLEUART + while (Serial.available()) + { + // Delay to wait for enough input + delay(2); + count = Serial.readBytes(buf, sizeof(buf)); + + printAll(buf, count); + } + + // Forward from BLEUART to HW Serial + while ( bleuart.available() ) + { + count = bleuart.read(buf, sizeof(buf)); + + printAll(buf, count); + } +} + +// callback invoked when central connects +void connect_callback(uint16_t conn_handle) +{ + // Get the reference to current connection + BLEConnection* connection = Bluefruit.Connection(conn_handle); + + char central_name[32] = { 0 }; + connection->getPeerName(central_name, sizeof(central_name)); + + Serial.print("Connected to "); + Serial.println(central_name); + + connection_count++; + Serial.print("Connection count: "); + Serial.println(connection_count); + + // Keep advertising if not reaching max + if (connection_count < MAX_PRPH_CONNECTION) + { + Serial.println("Keep advertising"); + Bluefruit.Advertising.start(0); + } +} + +/** + * Callback invoked when a connection is dropped + * @param conn_handle connection where this event happens + * @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h + */ +void disconnect_callback(uint16_t conn_handle, uint8_t reason) +{ + (void) conn_handle; + (void) reason; + + Serial.println(); + Serial.println("Disconnected"); + + connection_count--; +} diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard/hid_keyboard.ino b/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard/hid_keyboard.ino index 4d907534..acb9f03d 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard/hid_keyboard.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/hid_keyboard/hid_keyboard.ino @@ -120,9 +120,6 @@ void loop() // Delay a bit after a report delay(5); } - - // Request CPU to enter low-power mode until an event/interrupt occurs - waitForEvent(); } /** diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index 2edd4127..e0f24d8f 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -85,72 +85,64 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) BLEConnection* conn = Bluefruit.Connection(evt_conn_hdl); /*------------- Server service -------------*/ - // TODO multiple peripherals -// if ( evt_conn_hdl == Bluefruit.connHandle() ) + if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED ) { - if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED ) + for(uint8_t i=0; i<_server.svc_count; i++) { - for(uint8_t i=0; i<_server.svc_count; i++) + if ( evt_id == BLE_GAP_EVT_DISCONNECTED ) { - if ( evt_id == BLE_GAP_EVT_DISCONNECTED ) - { - _server.svc_list[i]->svc_disconnect_hdl(evt_conn_hdl); - }else - { - _server.svc_list[i]->svc_connect_hdl(evt_conn_hdl); - } + _server.svc_list[i]->svc_disconnect_hdl(evt_conn_hdl); + }else + { + _server.svc_list[i]->svc_connect_hdl(evt_conn_hdl); } } } /*------------- Server Characteristics -------------*/ - // TODO multiple prph connection - if ( evt_conn_hdl == Bluefruit.connHandle() ) + for(uint8_t i=0; i<_server.chr_count; i++) { - for(uint8_t i=0; i<_server.chr_count; i++) + BLECharacteristic* chr = _server.chr_list[i]; + uint16_t req_handle = BLE_GATT_HANDLE_INVALID; + + // BLE_GATTS_OP_EXEC_WRITE_REQ_NOW has no handle, uuid only command op + bool exec_write_now = false; + + switch (evt_id) { - BLECharacteristic* chr = _server.chr_list[i]; - uint16_t req_handle = BLE_GATT_HANDLE_INVALID; - - // BLE_GATTS_OP_EXEC_WRITE_REQ_NOW has no handle, uuid only command op - bool exec_write_now = false; - - switch (evt_id) + case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: { - case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: - { - // Handle has the same offset for read & write request - req_handle = evt->evt.gatts_evt.params.authorize_request.request.read.handle; + // Handle has the same offset for read & write request + req_handle = evt->evt.gatts_evt.params.authorize_request.request.read.handle; - if ( evt->evt.gatts_evt.params.authorize_request.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE ) + if ( evt->evt.gatts_evt.params.authorize_request.type == BLE_GATTS_AUTHORIZE_TYPE_WRITE ) + { + ble_gatts_evt_write_t * wr_req = &evt->evt.gatts_evt.params.authorize_request.request.write; + if ( wr_req->op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW ) { - ble_gatts_evt_write_t * wr_req = &evt->evt.gatts_evt.params.authorize_request.request.write; - if ( wr_req->op == BLE_GATTS_OP_EXEC_WRITE_REQ_NOW ) - { - exec_write_now = true; - } + exec_write_now = true; } } - break; - - case BLE_GATTS_EVT_WRITE: - req_handle = evt->evt.gatts_evt.params.write.handle; - break; - - default: break; } + break; - // invoke characteristic handler if matched - if ( exec_write_now || - ((req_handle != BLE_GATT_HANDLE_INVALID) && (req_handle == chr->handles().value_handle || req_handle == chr->handles().cccd_handle)) ) + case BLE_GATTS_EVT_WRITE: + req_handle = evt->evt.gatts_evt.params.write.handle; + break; + + default: break; + } + + // invoke characteristic handler if matched + if ( exec_write_now || + ((req_handle != BLE_GATT_HANDLE_INVALID) && (req_handle == chr->handles().value_handle || req_handle == chr->handles().cccd_handle)) ) + { + chr->_eventHandler(evt); + + // Save CCCD if paired + if ( conn->paired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) ) { - chr->_eventHandler(evt); - - // Save CCCD if paired - if ( conn->paired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) ) - { - conn->storeCccd(); - } + conn->storeCccd(); } } } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 49a3ad2f..1b24ef26 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -463,9 +463,7 @@ bool AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) TaskHandle_t soc_task_hdl; xTaskCreate( adafruit_soc_task, "SOC", CFG_SOC_TASK_STACKSIZE, NULL, TASK_PRIO_HIGH, &soc_task_hdl); - // Interrupt priority has already been set by the stack. -// NVIC_SetPriority(SD_EVT_IRQn, 6); - NVIC_EnableIRQ(SD_EVT_IRQn); + NVIC_EnableIRQ(SD_EVT_IRQn); // enable SD interrupt // Create Timer for led advertising blinky _led_blink_th = xTimerCreate(NULL, ms2tick(CFG_ADV_BLINKY_INTERVAL/2), true, NULL, bluefruit_blinky_cb); @@ -509,7 +507,7 @@ bool AdafruitBluefruit::setAddr (ble_gap_addr_t* gap_addr) void AdafruitBluefruit::setName (char const * str) { ble_gap_conn_sec_mode_t sec_mode = BLE_SECMODE_OPEN; -sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) str, strlen(str)); + sd_ble_gap_device_name_set(&sec_mode, (uint8_t const *) str, strlen(str)); } uint8_t AdafruitBluefruit::getName(char* name, uint16_t bufsize)