From 2d04696be1af7069b709a1253f88b904f1b44137 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 17 Jan 2018 12:48:46 +0700 Subject: [PATCH 01/39] fix burn issue with osx --- changelog.md | 5 +++++ libraries/Bluefruit52Lib/library.properties | 2 +- platform.txt | 6 +++--- programmers.txt | 6 ++++-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/changelog.md b/changelog.md index 866618c8..66561853 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,10 @@ # Adafruit nRF52 Arduino Core Changelog +## 0.8.2 + +- Fixed burning bootloader issue with MacOS +- + ## 0.8.1 - Prevent sketch compiled with S132 v2 upload to device running S132 v5 and vice versa. diff --git a/libraries/Bluefruit52Lib/library.properties b/libraries/Bluefruit52Lib/library.properties index cb6f953d..dcf231b4 100644 --- a/libraries/Bluefruit52Lib/library.properties +++ b/libraries/Bluefruit52Lib/library.properties @@ -1,5 +1,5 @@ name=Adafruit BLE Libraries for Bluefruit52 -version=0.8.1 +version=0.8.2 author=Adafruit maintainer=Adafruit sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules diff --git a/platform.txt b/platform.txt index 9cf6bc7a..45ad466e 100644 --- a/platform.txt +++ b/platform.txt @@ -17,7 +17,7 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA name=Adafruit nRF52 Boards -version=0.8.1 +version=0.8.2 # Compile variables # ----------------- @@ -81,7 +81,7 @@ compiler.elf2hex.extra_flags= # ---------------- ## Compile c files -recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {compiler.nrf.flags} {includes} "{source_file}" -o "{object_file}" +recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BSP_VERSION="{version}" {compiler.c.extra_flags} {build.extra_flags} {compiler.nrf.flags} {includes} "{source_file}" -o "{object_file}" ## Compile c++ files recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} -DARDUINO_BSP_VERSION="{version}" {compiler.cpp.extra_flags} {build.extra_flags} {compiler.nrf.flags} {includes} "{source_file}" -o "{object_file}" @@ -123,11 +123,11 @@ recipe.output.save_file={build.project_name}.{build.variant}.hex #********************************************** # nrfutil for uploading +# Note : For MacOS, make a symlink to /usr/local/bin/nrfutil if installed to other location #********************************************** tools.nrfutil.cmd=nrfutil tools.nrfutil.cmd.windows={runtime.platform.path}/tools/nrfutil-0.5.2/binaries/win32/nrfutil.exe -# MacOS nrfutil location, make a symlink if installed to other location tools.nrfutil.cmd.macosx=/usr/local/bin/nrfutil tools.nrfutil.upload.params.verbose=--verbose diff --git a/programmers.txt b/programmers.txt index 8978e1b5..5eb074ed 100644 --- a/programmers.txt +++ b/programmers.txt @@ -7,15 +7,17 @@ nrfjprog.program.tool=bootburn nrfjprog.program.path= nrfjprog.program.cmd=nrfjprog nrfjprog.program.cmd.windows=nrfjprog.exe -#nrfjprog.program.pattern="{program.path}{program.cmd}" --program "{runtime.platform.path}/bin/bootloader/{build.variant}/{build.sd_version}/{build.bootfile}.hex" -f nrf52 --chiperase --reset + nrfjprog.program.pattern="{program.path}{program.cmd}" --program "{runtime.platform.path}/bin/bootloader/{build.variant}/{build.bootfile}.hex" -f nrf52 --chiperase --reset #********************************************** # nrfutil to upgrade bootloader +# # Note : For MacOS, make a symlink to /usr/local/bin/nrfutil if installed to other location #********************************************** nrfutil_boot.name=Bootloader DFU for Bluefruit nRF52 nrfutil_boot.program.tool=bootburn nrfutil_boot.program.cmd=nrfutil nrfutil_boot.program.cmd.windows={runtime.platform.path}/tools/nrfutil-0.5.2/binaries/win32/nrfutil.exe -#nrfutil_boot.program.pattern={program.cmd} --verbose dfu serial -pkg "{runtime.platform.path}/bin/bootloader/{build.variant}/{build.sd_version}/{build.bootfile}.zip" -p {serial.port} -b 115200 +nrfutil_boot.program.cmd.macosx=/usr/local/bin/nrfutil + nrfutil_boot.program.pattern={program.cmd} --verbose dfu serial -pkg "{runtime.platform.path}/bin/bootloader/{build.variant}/{build.bootfile}.zip" -p {serial.port} -b 115200 From a70d157656e362348a06b1c6e82a2fcb324c3fb6 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 17 Jan 2018 21:41:29 +0700 Subject: [PATCH 02/39] add isWaiting for AdaMsg --- libraries/Bluefruit52Lib/src/utility/AdaMsg.cpp | 16 +++++++++++++++- libraries/Bluefruit52Lib/src/utility/AdaMsg.h | 4 ++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/libraries/Bluefruit52Lib/src/utility/AdaMsg.cpp b/libraries/Bluefruit52Lib/src/utility/AdaMsg.cpp index a40e3386..3888af21 100644 --- a/libraries/Bluefruit52Lib/src/utility/AdaMsg.cpp +++ b/libraries/Bluefruit52Lib/src/utility/AdaMsg.cpp @@ -36,15 +36,21 @@ #include "AdaMsg.h" -AdaMsg::AdaMsg(void) +void AdaMsg::_init(void) { _dynamic = true; + _waiting = false; _sem = NULL; buffer = NULL; remaining = xferlen = 0; } +AdaMsg::AdaMsg(void) +{ + _init(); +} + // dynamic mean semaphore is malloced and freed only when in action void AdaMsg::begin(bool dynamic) { @@ -58,6 +64,7 @@ void AdaMsg::begin(bool dynamic) void AdaMsg::stop(void) { if (!_dynamic) vSemaphoreDelete(_sem); + _init(); } void AdaMsg::prepare(void* buf, uint16_t bufsize) @@ -82,10 +89,12 @@ int32_t AdaMsg::waitUntilComplete(uint32_t ms) int result = -1; + _waiting = true; if ( xSemaphoreTake(_sem, ms2tick(ms) ) ) { result = xferlen; } + _waiting = false; if (_dynamic) { @@ -96,6 +105,11 @@ int32_t AdaMsg::waitUntilComplete(uint32_t ms) return result; } +bool AdaMsg::isWaiting(void) +{ + return _waiting; +} + uint16_t AdaMsg::feed(void* data, uint16_t len) { len = min16(len, remaining); diff --git a/libraries/Bluefruit52Lib/src/utility/AdaMsg.h b/libraries/Bluefruit52Lib/src/utility/AdaMsg.h index de2e015c..39463148 100644 --- a/libraries/Bluefruit52Lib/src/utility/AdaMsg.h +++ b/libraries/Bluefruit52Lib/src/utility/AdaMsg.h @@ -42,8 +42,11 @@ class AdaMsg { private: bool _dynamic; + volatile bool _waiting; SemaphoreHandle_t _sem; + void _init(void); + public: uint8_t* buffer; uint16_t remaining; @@ -57,6 +60,7 @@ class AdaMsg void prepare(void* buf, uint16_t bufsize); int32_t waitUntilComplete(uint32_t ms); + bool isWaiting(void); uint16_t feed(void* data, uint16_t len); void complete(void); From 20a2db556c01235292a5df987e7fed7b43bb1ed7 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 17 Jan 2018 21:43:57 +0700 Subject: [PATCH 03/39] add indicate API, add getCccd to BLECharacteristic --- .../Bluefruit52Lib/src/BLECharacteristic.cpp | 105 ++++++++++++++++-- .../Bluefruit52Lib/src/BLECharacteristic.h | 13 +++ libraries/Bluefruit52Lib/src/BLEGatt.cpp | 25 +++++ libraries/Bluefruit52Lib/src/BLEGatt.h | 1 + 4 files changed, 137 insertions(+), 7 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index cc998fa0..3fa476b2 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -496,12 +496,10 @@ uint32_t BLECharacteristic::read32(void) return read(&num, sizeof(num)) ? num : 0; } -/*------------------------------------------------------------------*/ -/* NOTIFY - *------------------------------------------------------------------*/ -bool BLECharacteristic::notifyEnabled(void) + +uint16_t BLECharacteristic::getCccd(void) { - VERIFY( _properties.notify && Bluefruit.connected() ); + VERIFY( Bluefruit.connected() && (_handles.cccd_handle != BLE_GATT_HANDLE_INVALID), 0 ); uint16_t cccd; ble_gatts_value_t value = @@ -522,7 +520,16 @@ bool BLECharacteristic::notifyEnabled(void) VERIFY_STATUS(err); } - return (cccd & BLE_GATT_HVX_NOTIFICATION); + return cccd; +} + +/*------------------------------------------------------------------*/ +/* NOTIFY + *------------------------------------------------------------------*/ +bool BLECharacteristic::notifyEnabled(void) +{ + VERIFY( _properties.notify ); + return (getCccd() & BLE_GATT_HVX_NOTIFICATION); } bool BLECharacteristic::notify(const void* data, uint16_t len) @@ -557,7 +564,7 @@ bool BLECharacteristic::notify(const void* data, uint16_t len) VERIFY_STATUS( sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params), false ); remaining -= packet_len; - u8data += packet_len; + u8data += packet_len; } } else @@ -593,3 +600,87 @@ bool BLECharacteristic::notify32(int num) { return notify32( (uint32_t) num); } + +/*------------------------------------------------------------------*/ +/* NOTIFY + *------------------------------------------------------------------*/ +bool BLECharacteristic::indicateEnabled(void) +{ + VERIFY( _properties.indicate ); + return (getCccd() & BLE_GATT_HVX_INDICATION); +} + +bool BLECharacteristic::indicate(const void* data, uint16_t len) +{ + VERIFY( _properties.indicate ); + + // could not exceed max len + uint16_t remaining = min16(len, _max_len); + + if ( indicateEnabled() ) + { + uint16_t const max_payload = Bluefruit.Gap.getMTU( Bluefruit.connHandle() ) - 3; + const uint8_t* u8data = (const uint8_t*) data; + + while ( remaining ) + { + uint16_t packet_len = min16(max_payload, remaining); + + ble_gatts_hvx_params_t hvx_params = + { + .handle = _handles.value_handle, + .type = BLE_GATT_HVX_INDICATION, + .offset = 0, + .p_len = &packet_len, + .p_data = (uint8_t*) u8data, + }; + + LOG_LV2("CHR", "Indicate %d bytes", packet_len); + err_t err; + + // If previous indicate is still in progress, wait for a while and try again + while ( NRF_ERROR_BUSY == (err = sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params)) ) + { + // TODO should wait for BLE_GATTS_EVT_HVC event + delay( Bluefruit.connInterval() ); + } + + VERIFY_STATUS( err, false ); + + remaining -= packet_len; + u8data += packet_len; + } + } + else + { + write(data, remaining); + return false; + } + + return true; +} + +bool BLECharacteristic::indicate(const char * str) +{ + return indicate( (const uint8_t*) str, strlen(str) ); +} + +bool BLECharacteristic::indicate8(uint8_t num) +{ + return indicate( (uint8_t*) &num, sizeof(num)); +} + +bool BLECharacteristic::indicate16(uint16_t num) +{ + return indicate( (uint8_t*) &num, sizeof(num)); +} + +bool BLECharacteristic::indicate32(uint32_t num) +{ + return indicate( (uint8_t*) &num, sizeof(num)); +} + +bool BLECharacteristic::indicate32(int num) +{ + return indicate32( (uint32_t) num); +} diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.h b/libraries/Bluefruit52Lib/src/BLECharacteristic.h index 9e0dac2d..ece72bee 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.h +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.h @@ -135,6 +135,8 @@ class BLECharacteristic uint32_t read32(void); /*------------- Notify -------------*/ + uint16_t getCccd(void); + bool notifyEnabled(void); bool notify(const void* data, uint16_t len); @@ -145,6 +147,17 @@ class BLECharacteristic bool notify32 (uint32_t num); bool notify32 (int num); + /*------------- Indicate -------------*/ + bool indicateEnabled(void); + + bool indicate(const void* data, uint16_t len); + bool indicate(const char* str); + + bool indicate8 (uint8_t num); + bool indicate16 (uint16_t num); + bool indicate32 (uint32_t num); + bool indicate32 (int num); + /*------------- Internal Functions -------------*/ virtual void _eventHandler(ble_evt_t* event); diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index f7765295..b14ed533 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -49,6 +49,12 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe int32_t count = 0; ble_gattc_handle_range_t hdl_range = { .start_handle = start_hdl, .end_handle = end_hdl }; + while( _adamsg.isWaiting() ) + { + // TODO multiple peripherals + delay( Bluefruit.connInterval() ); + } + _adamsg.begin(true); _adamsg.prepare(buffer, bufsize); @@ -68,6 +74,25 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe return (count < 0) ? 0 : count; } +//bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl) +//{ +// while( _adamsg.isWaiting() ) +// { +// // TODO multiple peripherals +// delay( Bluefruit.connInterval() ); +// } +// +// _adamsg.begin(true); +// _adamsg.prepare(NULL, 0); +// +// // Wait for HVC event +// int32_t result = _adamsg.waitUntilComplete(BLE_GENERIC_TIMEOUT); +// +// _adamsg.stop(); +// +// return (result == 0); +//} + void BLEGatt::_eventHandler(ble_evt_t* evt) { // conn handle has fixed offset regardless of event type diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.h b/libraries/Bluefruit52Lib/src/BLEGatt.h index ce19093e..a930b2a2 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.h +++ b/libraries/Bluefruit52Lib/src/BLEGatt.h @@ -59,6 +59,7 @@ class BLEGatt BLEGatt(void); uint16_t readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffer, uint16_t bufsize, uint16_t start_hdl = 1, uint16_t end_hdl = 0xffff); +// bool waitForIndicateConfirm(uint16_t conn_hdl); /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY From f86c0940a11d0497a6d26afa21306bba2a6900f8 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 18 Jan 2018 12:54:52 +0700 Subject: [PATCH 04/39] add software serial gpstest example --- .gitignore | 1 + .../gpstest_swuart/gpstest_swuart.ino | 55 +++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 libraries/Bluefruit52Lib/examples/Hardware/gpstest_swuart/gpstest_swuart.ino diff --git a/.gitignore b/.gitignore index 55728e49..2705565e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ .DS_Store *.swp +/Output diff --git a/libraries/Bluefruit52Lib/examples/Hardware/gpstest_swuart/gpstest_swuart.ino b/libraries/Bluefruit52Lib/examples/Hardware/gpstest_swuart/gpstest_swuart.ino new file mode 100644 index 00000000..9cbe300f --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Hardware/gpstest_swuart/gpstest_swuart.ino @@ -0,0 +1,55 @@ +/********************************************************************* + This is an example for our nRF52 based Bluefruit LE modules + + Pick one up today in the adafruit shop! + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + MIT license, check LICENSE for more information + All text above, and the splash screen below must be included in + any redistribution +*********************************************************************/ + +/* This example show how to use Software Serial on Bluefruit nRF52 + * to interact with GPS FeatherWing https://www.adafruit.com/product/3133 + * + * Hardware Set up + * - Connect 3V and GND to GPS wing + * - + */ + +#include + +#define SW_RXD A0 +#define SW_TXD A1 + +// Declare an Software Serial instance +SoftwareSerial mySerial(SW_RXD, SW_TXD); + +void setup() { + + // Init hardware UART <-> Serial Monitor + Serial.begin(115200); + Serial.println("GPS echo test"); + + // Init Software Uart <-> GPS FeatherWing + mySerial.begin(9600); // default NMEA GPS baud +} + + +void loop() { + + // Pass data from Serial (HW uart) to GPS Wing (SW Uart) + if (Serial.available()) { + char c = Serial.read(); + mySerial.write(c); + } + + // Pass data from GPS Wing (SW Uart) to Serial (HW uart) + if (mySerial.available()) { + char c = mySerial.read(); + Serial.write(c); + } +} From 4747a9b7ae264f39de88297211c0f5e5ee760c2b Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 18 Jan 2018 14:00:04 +0700 Subject: [PATCH 05/39] add useAdaCallback option to setNotifyCallback(), setIndicateCallback() for client char --- changelog.md | 4 +- libraries/Bluefruit52Lib/keywords.txt | 1 - .../src/BLEClientCharacteristic.cpp | 67 +++++++++++++------ .../src/BLEClientCharacteristic.h | 21 ++++-- .../Bluefruit52Lib/src/clients/BLEAncs.cpp | 5 +- 5 files changed, 64 insertions(+), 34 deletions(-) diff --git a/changelog.md b/changelog.md index 66561853..3e338803 100644 --- a/changelog.md +++ b/changelog.md @@ -3,7 +3,9 @@ ## 0.8.2 - Fixed burning bootloader issue with MacOS -- +- Added gpstest_swuart example sketch +- Added indicate API for BLECharacteristic +- Added useAdaCallback option to setNotifyCallback(), setIndicateCallback() for BLEClientCharacteristic ## 0.8.1 diff --git a/libraries/Bluefruit52Lib/keywords.txt b/libraries/Bluefruit52Lib/keywords.txt index 5bd1ddc7..fa82d3bb 100644 --- a/libraries/Bluefruit52Lib/keywords.txt +++ b/libraries/Bluefruit52Lib/keywords.txt @@ -201,7 +201,6 @@ enableIndicate KEYWORD2 disableIndicate KEYWORD2 setNotifyCallback KEYWORD2 -useAdaCallback KEYWORD2 ####################################### # BLEScanner Methods (KEYWORD2) diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp index 12d89162..4f3112df 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp @@ -43,7 +43,9 @@ void BLEClientCharacteristic::_init(void) _cccd_handle = BLE_GATT_HANDLE_INVALID; _notify_cb = NULL; - _use_AdaCallback = true; + _indicate_cb = NULL; + + varclr(&_use_ada_cb); } BLEClientCharacteristic::BLEClientCharacteristic(void) @@ -112,11 +114,6 @@ bool BLEClientCharacteristic::discovered(void) return _chr.handle_value != BLE_GATT_HANDLE_INVALID; } -void BLEClientCharacteristic::useAdaCallback(bool enabled) -{ - _use_AdaCallback = enabled; -} - uint16_t BLEClientCharacteristic::connHandle(void) { return _service->connHandle(); @@ -331,9 +328,16 @@ uint16_t BLEClientCharacteristic::write32(int value) } -void BLEClientCharacteristic::setNotifyCallback(notify_cb_t fp) +void BLEClientCharacteristic::setNotifyCallback(notify_cb_t fp, bool useAdaCallback) { _notify_cb = fp; + _use_ada_cb.notify = useAdaCallback; +} + +void BLEClientCharacteristic::setIndicateCallback(indicate_cb_t fp, bool useAdaCallback) +{ + _indicate_cb = fp; + _use_ada_cb.indicate = useAdaCallback; } bool BLEClientCharacteristic::writeCCCD(uint16_t value) @@ -392,26 +396,45 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) { ble_gattc_evt_hvx_t* hvx = &evt->evt.gattc_evt.params.hvx; - if ( hvx->type == BLE_GATT_HVX_NOTIFICATION ) + switch ( hvx->type ) { - if (_notify_cb) - { - // use AdaCallback or invoke directly - if (_use_AdaCallback) + case BLE_GATT_HVX_NOTIFICATION: + if (_notify_cb) { - uint8_t* data = (uint8_t*) rtos_malloc(hvx->len); - if (!data) return; - memcpy(data, hvx->data, hvx->len); + // use AdaCallback or invoke directly + if (_use_ada_cb.notify) + { + uint8_t* data = (uint8_t*) rtos_malloc(hvx->len); + if (!data) return; + memcpy(data, hvx->data, hvx->len); - ada_callback(data, _notify_cb, this, data, hvx->len); - }else - { - _notify_cb(*this, hvx->data, hvx->len); + ada_callback(data, _notify_cb, this, data, hvx->len); + }else + { + _notify_cb(*this, hvx->data, hvx->len); + } } - } - }else - { + break; + case BLE_GATT_HVX_INDICATION: + if (_indicate_cb) + { + // use AdaCallback or invoke directly + if (_use_ada_cb.indicate) + { + uint8_t* data = (uint8_t*) rtos_malloc(hvx->len); + if (!data) return; + memcpy(data, hvx->data, hvx->len); + + ada_callback(data, _notify_cb, this, data, hvx->len); + }else + { + _notify_cb(*this, hvx->data, hvx->len); + } + } + break; + + default : break; } } break; diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h index 2fccdc87..6a52562d 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h @@ -100,23 +100,30 @@ class BLEClientCharacteristic bool disableIndicate (void); /*------------- Callbacks -------------*/ - void setNotifyCallback(notify_cb_t fp); - void useAdaCallback(bool enabled); + void setNotifyCallback(notify_cb_t fp, bool useAdaCallback = true); + void setIndicateCallback(indicate_cb_t fp, bool useAdaCallback = true); /*------------- Internal usage -------------*/ void _assign(ble_gattc_char_t* gattc_chr); bool _discoverDescriptor(uint16_t conn_handle, ble_gattc_handle_range_t hdl_range); private: - ble_gattc_char_t _chr; - uint16_t _cccd_handle; + ble_gattc_char_t _chr; + uint16_t _cccd_handle; BLEClientService* _service; - notify_cb_t _notify_cb; - bool _use_AdaCallback; // whether callback is invoked in separated task with AdaCallback - AdaMsg _adamsg; + /*------------- Callbacks -------------*/ + notify_cb_t _notify_cb; + indicate_cb_t _indicate_cb; + + struct ATTR_PACKED { + uint8_t notify : 1; + uint8_t indicate : 1; + } _use_ada_cb; + + void _init (void); void _eventHandler (ble_evt_t* event); diff --git a/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp b/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp index 96c241af..c57ccd12 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp @@ -94,10 +94,9 @@ bool BLEAncs::begin(void) _notification.setNotifyCallback(bleancs_notification_cb); - // Data Attribute is likely requested in notification callback + // Data Attribute is most likely requested in notification callback // let's call data's callback in the ble task - _data.useAdaCallback(false); - _data.setNotifyCallback(bleancs_data_cb); + _data.setNotifyCallback(bleancs_data_cb, false); return true; } From d0655b369d18794fbd54c791e2854cfedabb9222 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 18 Jan 2018 15:07:39 +0700 Subject: [PATCH 06/39] change BLECLientCharacteristic notify callback signature from notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) to notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) Added --- changelog.md | 6 +++++- .../central_custom_hrm/central_custom_hrm.ino | 4 ++-- .../Bluefruit52Lib/src/BLEClientCharacteristic.cpp | 8 +++++--- .../Bluefruit52Lib/src/BLEClientCharacteristic.h | 4 ++-- libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp | 12 ++++++------ libraries/Bluefruit52Lib/src/clients/BLEAncs.h | 4 ++-- .../Bluefruit52Lib/src/clients/BLEClientCts.cpp | 6 +++--- .../Bluefruit52Lib/src/clients/BLEClientUart.cpp | 6 +++--- libraries/Bluefruit52Lib/src/clients/BLEClientUart.h | 2 +- 9 files changed, 29 insertions(+), 23 deletions(-) diff --git a/changelog.md b/changelog.md index 3e338803..aaf31ec8 100644 --- a/changelog.md +++ b/changelog.md @@ -5,7 +5,11 @@ - Fixed burning bootloader issue with MacOS - Added gpstest_swuart example sketch - Added indicate API for BLECharacteristic -- Added useAdaCallback option to setNotifyCallback(), setIndicateCallback() for BLEClientCharacteristic +- BLEClientCharacteristic + - Added setIndicateCallback(), issue #113 + - Added useAdaCallback option to setNotifyCallback(), setIndicateCallback() + - Change notify callback signature from +notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) to notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) ## 0.8.1 diff --git a/libraries/Bluefruit52Lib/examples/Central/central_custom_hrm/central_custom_hrm.ino b/libraries/Bluefruit52Lib/examples/Central/central_custom_hrm/central_custom_hrm.ino index 1d8a3c3f..37ea5a69 100644 --- a/libraries/Bluefruit52Lib/examples/Central/central_custom_hrm/central_custom_hrm.ino +++ b/libraries/Bluefruit52Lib/examples/Central/central_custom_hrm/central_custom_hrm.ino @@ -175,12 +175,12 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) /** * Hooked callback that triggered when a measurement value is sent from peripheral - * @param chr Reference to client characteristic that even occurred, + * @param chr Pointer client characteristic that even occurred, * in this example it should be hrmc * @param data Pointer to received data * @param len Length of received data */ -void hrm_notify_callback(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) +void hrm_notify_callback(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) { // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml // Measurement contains of control byte0 and measurement (8 or 16 bit) + optional field diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp index 4f3112df..0d1a5497 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp @@ -408,10 +408,11 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) if (!data) return; memcpy(data, hvx->data, hvx->len); + // data is free by callback ada_callback(data, _notify_cb, this, data, hvx->len); }else { - _notify_cb(*this, hvx->data, hvx->len); + _notify_cb(this, hvx->data, hvx->len); } } break; @@ -426,10 +427,11 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) if (!data) return; memcpy(data, hvx->data, hvx->len); - ada_callback(data, _notify_cb, this, data, hvx->len); + // data is free by callback + ada_callback(data, _indicate_cb, this, data, hvx->len); }else { - _notify_cb(*this, hvx->data, hvx->len); + _indicate_cb(this, hvx->data, hvx->len); } } break; diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h index 6a52562d..1b5c048e 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.h @@ -47,8 +47,8 @@ class BLEClientCharacteristic { public: /*--------- Callback Signatures ----------*/ - typedef void (*notify_cb_t ) (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); - typedef void (*indicate_cb_t) (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); + typedef void (*notify_cb_t ) (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); + typedef void (*indicate_cb_t) (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); BLEUuid uuid; diff --git a/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp b/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp index c57ccd12..53b6ffb9 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEAncs.cpp @@ -40,8 +40,8 @@ #define DEBUG_ANCS 0 -void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); -void bleancs_data_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); +void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); +void bleancs_data_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); /* ANCS Service : 7905F431-B5CE-4E99-A40F-4B1E122D00D0 * Control Point : 69D1D8F3-45E1-49A8-9821-9BBDFDAAD9D9 @@ -383,14 +383,14 @@ bool BLEAncs::actNegative(uint32_t uid) /*------------------------------------------------------------------*/ /* Callback *------------------------------------------------------------------*/ -void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) +void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) { - BLEAncs& svc = (BLEAncs&) chr.parentService(); + BLEAncs& svc = (BLEAncs&) chr->parentService(); svc._handleNotification(data, len); } -void bleancs_data_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) +void bleancs_data_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) { - BLEAncs& svc = (BLEAncs&) chr.parentService(); + BLEAncs& svc = (BLEAncs&) chr->parentService(); svc._handleData(data, len); } diff --git a/libraries/Bluefruit52Lib/src/clients/BLEAncs.h b/libraries/Bluefruit52Lib/src/clients/BLEAncs.h index 016c4be8..315b209a 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEAncs.h +++ b/libraries/Bluefruit52Lib/src/clients/BLEAncs.h @@ -177,8 +177,8 @@ class BLEAncs : public BLEClientService void _handleNotification(uint8_t* data, uint16_t len); void _handleData(uint8_t* data, uint16_t len); - friend void bleancs_notification_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); - friend void bleancs_data_cb (BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); + friend void bleancs_notification_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); + friend void bleancs_data_cb (BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); }; diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientCts.cpp b/libraries/Bluefruit52Lib/src/clients/BLEClientCts.cpp index 3b006c59..978cdda8 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientCts.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientCts.cpp @@ -36,7 +36,7 @@ #include "bluefruit.h" -void blects_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); +void blects_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); BLEClientCts::BLEClientCts(void) : BLEClientService(UUID16_SVC_CURRENT_TIME), _cur_time(UUID16_CHR_CURRENT_TIME), _local_info(UUID16_CHR_LOCAL_TIME_INFORMATION) @@ -107,7 +107,7 @@ void BLEClientCts::_cur_time_notify_cb(uint8_t* data, uint16_t len) if ( _adjust_cb ) _adjust_cb( Time.adjust_reason ); } -void blects_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) +void blects_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) { - ((BLEClientCts&) chr.parentService())._cur_time_notify_cb(data, len); + ((BLEClientCts&) chr->parentService())._cur_time_notify_cb(data, len); } diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientUart.cpp b/libraries/Bluefruit52Lib/src/clients/BLEClientUart.cpp index e3eef5a7..d021f912 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientUart.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientUart.cpp @@ -36,7 +36,7 @@ #include "bluefruit.h" -void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); +void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); BLEClientUart::BLEClientUart(uint16_t fifo_depth) : BLEClientService(BLEUART_UUID_SERVICE), _txd(BLEUART_UUID_CHR_TXD), _rxd(BLEUART_UUID_CHR_RXD), @@ -96,9 +96,9 @@ void BLEClientUart::disconnect(void) flush(); } -void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len) +void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) { - BLEClientUart& uart_svc = (BLEClientUart&) chr.parentService(); + BLEClientUart& uart_svc = (BLEClientUart&) chr->parentService(); uart_svc._rx_fifo.write(data, len); // invoke callback diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientUart.h b/libraries/Bluefruit52Lib/src/clients/BLEClientUart.h index 0e5d7a6c..9227bbb6 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientUart.h +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientUart.h @@ -83,7 +83,7 @@ class BLEClientUart : public BLEClientService, public Stream Adafruit_FIFO _rx_fifo; rx_callback_t _rx_cb; - friend void bleuart_central_notify_cb(BLEClientCharacteristic& chr, uint8_t* data, uint16_t len); + friend void bleuart_central_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); }; #endif /* BLECLIENTUART_H_ */ From 96c7689e05da184aa1b08327fec8124f4fbc4b1f Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 18 Jan 2018 15:09:52 +0700 Subject: [PATCH 07/39] add send confirm to indicate --- libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp index 0d1a5497..f77ff223 100644 --- a/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLEClientCharacteristic.cpp @@ -388,6 +388,7 @@ bool BLEClientCharacteristic::disableIndicate (void) void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) { + const uint16_t evt_conn_hdl = evt->evt.common_evt.conn_handle; uint16_t gatt_status = evt->evt.gattc_evt.gatt_status; switch(evt->header.evt_id) @@ -433,6 +434,9 @@ void BLEClientCharacteristic::_eventHandler(ble_evt_t* evt) { _indicate_cb(this, hvx->data, hvx->len); } + + // Send confirmation to server + VERIFY_STATUS( sd_ble_gattc_hv_confirm(evt_conn_hdl, hvx->handle), ); } break; From cffa6456e489765bf36a715f13f1f26a6f494b00 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 23 Jan 2018 13:19:10 +0700 Subject: [PATCH 08/39] fix typo --- libraries/Bluefruit52Lib/src/BLECharacteristic.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index 3fa476b2..f00d0061 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -602,7 +602,7 @@ bool BLECharacteristic::notify32(int num) } /*------------------------------------------------------------------*/ -/* NOTIFY +/* INDICATE *------------------------------------------------------------------*/ bool BLECharacteristic::indicateEnabled(void) { From b735d6a46c1196216d309f41504af55f483e6bde Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 29 Jan 2018 16:24:50 +0700 Subject: [PATCH 09/39] added custom_htm as example for indicate API --- .../Peripheral/custom_htm/IEEE11073float.cpp | 106 +++++++++ .../Peripheral/custom_htm/IEEE11073float.h | 89 +++++++ .../Peripheral/custom_htm/custom_htm.ino | 220 ++++++++++++++++++ libraries/Bluefruit52Lib/keywords.txt | 8 +- 4 files changed, 422 insertions(+), 1 deletion(-) create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.cpp create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.h create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.cpp b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.cpp new file mode 100644 index 00000000..6b372bd1 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.cpp @@ -0,0 +1,106 @@ +/**************************************************************************/ +/*! + @file IEEE11073float.h +*/ +/**************************************************************************/ + +/** + * \file bytelib.c + * \brief Byte manipulation module implementation. + * Copyright (C) 2010 Signove Tecnologia Corporation. + * All rights reserved. + * Contact: Signove Tecnologia Corporation (contact@signove.com) + * + * $LICENSE_TEXT:BEGIN$ + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation and appearing + * in the file LICENSE included in the packaging of this file; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $LICENSE_TEXT:END$ + * + * \author Walter Guerra, Mateus Lima + * \date Jun 14, 2010 + */ + +#include +#include "IEEE11073float.h" + +uint32_t float2IEEE11073(double data, uint8_t output[4]) +{ + uint32_t result = MDER_NaN; + + + if (isnan(data)) { + goto finally; + }/* else if (data > MDER_FLOAT_MAX) { + result = MDER_POSITIVE_INFINITY; + goto finally; + } else if (data < MDER_FLOAT_MIN) { + result = MDER_NEGATIVE_INFINITY; + goto finally; + } else if (data >= -MDER_FLOAT_EPSILON && + data <= MDER_FLOAT_EPSILON) { + result = 0; + goto finally; + }*/ + + double sgn; sgn = data > 0 ? +1 : -1; + double mantissa; mantissa = fabs(data); + int32_t exponent; exponent = 0; // Note: 10**x exponent, not 2**x + + // scale up if number is too big + while (mantissa > MDER_FLOAT_MANTISSA_MAX) { + mantissa /= 10.0; + ++exponent; + if (exponent > MDER_FLOAT_EXPONENT_MAX) { + // argh, should not happen + if (sgn > 0) { + result = MDER_POSITIVE_INFINITY; + } else { + result = MDER_NEGATIVE_INFINITY; + } + goto finally; + } + } + + // scale down if number is too small + while (mantissa < 1) { + mantissa *= 10; + --exponent; + if (exponent < MDER_FLOAT_EXPONENT_MIN) { + // argh, should not happen + result = 0; + goto finally; + } + } + + // scale down if number needs more precision + double smantissa; smantissa = round(mantissa * MDER_FLOAT_PRECISION); + double rmantissa; rmantissa = round(mantissa) * MDER_FLOAT_PRECISION; + double mdiff; mdiff = abs(smantissa - rmantissa); + while (mdiff > 0.5 && exponent > MDER_FLOAT_EXPONENT_MIN && + (mantissa * 10) <= MDER_FLOAT_MANTISSA_MAX) { + mantissa *= 10; + --exponent; + smantissa = round(mantissa * MDER_FLOAT_PRECISION); + rmantissa = round(mantissa) * MDER_FLOAT_PRECISION; + mdiff = abs(smantissa - rmantissa); + } + + uint32_t int_mantissa; int_mantissa = (int) round(sgn * mantissa); + result = (exponent << 24) | (int_mantissa & 0xFFFFFF); + +finally: + if ( output ) memcpy(output, &result, 4); + return result; +} diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.h b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.h new file mode 100644 index 00000000..b5dec8fb --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/IEEE11073float.h @@ -0,0 +1,89 @@ +/**************************************************************************/ +/*! + @file IEEE11073float.h +*/ +/**************************************************************************/ + +/** + * \file bytelib.c + * \brief Byte manipulation module implementation. + * Copyright (C) 2010 Signove Tecnologia Corporation. + * All rights reserved. + * Contact: Signove Tecnologia Corporation (contact@signove.com) + * + * $LICENSE_TEXT:BEGIN$ + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation and appearing + * in the file LICENSE included in the packaging of this file; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $LICENSE_TEXT:END$ + * + * \author Walter Guerra, Mateus Lima + * \date Jun 14, 2010 + */ + +#ifndef _IEEE11073FLOAT_H_ +#define _IEEE11073FLOAT_H_ + +#include + +typedef enum { + MDER_POSITIVE_INFINITY = 0x007FFFFE, + MDER_NaN = 0x007FFFFF, + MDER_NRes = 0x00800000, + MDER_RESERVED_VALUE = 0x00800001, + MDER_NEGATIVE_INFINITY = 0x00800002 +} ReservedFloatValues; +static const int32_t FIRST_RESERVED_VALUE = MDER_POSITIVE_INFINITY; + +// (2 ** 23 - 3) +#define MDER_FLOAT_MANTISSA_MAX 0x007FFFFD +// 2 ** 7 - 1 +#define MDER_FLOAT_EXPONENT_MAX 127 +#define MDER_FLOAT_EXPONENT_MIN -128 +// (2 ** 23 - 3) * 10 ** 127 +#define MDER_FLOAT_MAX 8.388604999999999e+133 +// -(2 ** 23 - 3) * 10 ** 127 +#define MDER_FLOAT_MIN (-MDER_FLOAT_MAX) +// 10 ** -128 +#define MDER_FLOAT_EPSILON 1e-128 +// 10 ** upper(23 * log(2) / log(10)) +// precision for a number 1.0000xxx +#define MDER_FLOAT_PRECISION 10000000 + +typedef enum { + MDER_S_POSITIVE_INFINITY = 0x07FE, + MDER_S_NaN = 0x07FF, + MDER_S_NRes = 0x0800, + MDER_S_RESERVED_VALUE = 0x0801, + MDER_S_NEGATIVE_INFINITY = 0x0802 +} ReservedSFloatValues; +static const uint32_t FIRST_S_RESERVED_VALUE = MDER_S_POSITIVE_INFINITY; + +// (2 ** 11 - 3) +#define MDER_SFLOAT_MANTISSA_MAX 0x07FD +// 2 ** 3 - 1 +#define MDER_SFLOAT_EXPONENT_MAX 7 +#define MDER_SFLOAT_EXPONENT_MIN -8 +// (2 ** 11 - 3) * 10 ** 7 +#define MDER_SFLOAT_MAX 20450000000.0 +// -(2 ** 11 - 3) * 10 ** 7 +#define MDER_SFLOAT_MIN (-MDER_SFLOAT_MAX) +// 10 ** -8 +#define MDER_SFLOAT_EPSILON 1e-8 +// 10 ** upper(11 * log(2) / log(10)) +#define MDER_SFLOAT_PRECISION 10000 + +uint32_t float2IEEE11073(double data, uint8_t output[4]); + +#endif /* _IEEE11073FLOAT_H_ */ diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino new file mode 100644 index 00000000..6668fd41 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino @@ -0,0 +1,220 @@ +/********************************************************************* + 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 +#include "IEEE11073float.h" + +/* Health Thermometer Service Definitions + * Health Thermometer Service: 0x1809 + * Temperature Measurement Char: 0x2A1C + * Temperature Type Char: 0x2A1D + */ +BLEService htms = BLEService(UUID16_SVC_HEALTH_THERMOMETER); +BLECharacteristic htmc = BLECharacteristic(UUID16_CHR_TEMPERATURE_MEASUREMENT); +BLECharacteristic ttype = BLECharacteristic(UUID16_CHR_TEMPERATURE_TYPE); + +BLEDis bledis; // DIS (Device Information Service) helper class instance + +double tempvalue = 0; + +// Advanced function prototypes +void startAdv(void); +void setupHTM(void); +void connect_callback(uint16_t conn_handle); +void disconnect_callback(uint16_t conn_handle, uint8_t reason); + +void setup() +{ + Serial.begin(115200); + Serial.println("Bluefruit52 Heath Thermometer Example"); + Serial.println("-------------------------------------\n"); + + // Initialise the Bluefruit module + Serial.println("Initialise the Bluefruit nRF52 module"); + Bluefruit.begin(); + Bluefruit.setName("Bluefruit52"); + + // Set the connect/disconnect callback handlers + Bluefruit.setConnectCallback(connect_callback); + Bluefruit.setDisconnectCallback(disconnect_callback); + + // Configure and Start the Device Information Service + Serial.println("Configuring the Device Information Service"); + bledis.setManufacturer("Adafruit Industries"); + bledis.setModel("Bluefruit Feather52"); + bledis.begin();; + + // Setup the Heath Thermometer service using + // BLEService and BLECharacteristic classes + Serial.println("Configuring the Heath Thermometer Service"); + setupHTM(); + + // Setup the advertising packet(s) + Serial.println("Setting up the advertising payload(s)"); + startAdv(); + + Serial.println("Ready Player One!!!"); + Serial.println("\nAdvertising"); +} + +void startAdv(void) +{ + // Advertising packet + Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE); + Bluefruit.Advertising.addTxPower(); + + // Include HTM Service UUID + Bluefruit.Advertising.addService(htms); + + // Include Name + Bluefruit.Advertising.addName(); + + /* Start Advertising + * - Enable auto advertising if disconnected + * - Interval: fast mode = 20 ms, slow mode = 152.5 ms + * - Timeout for fast mode is 30 seconds + * - Start(timeout) with timeout = 0 will advertise forever (until connected) + * + * For recommended advertising interval + * https://developer.apple.com/library/content/qa/qa1931/_index.html + */ + Bluefruit.Advertising.restartOnDisconnect(true); + Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms + Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode + Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds +} + +void setupHTM(void) +{ + // Configure the Health Thermometer service + // See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.service.health_thermometer.xml + // Supported Characteristics: + // Name UUID Requirement Properties + // ---------------------------- ------ ----------- ---------- + // Temperature Measurement 0x2A1C Mandatory Indicate + // Temperature Type 0x2A1D Optional Read + // + // Intermediate Temperature 0x2A1E Optional Read, Notify <-- Not used here + // Measurement Interval 0x2A21 Optional Read, Write, Indicate <-- Not used here + htms.begin(); + + // Note: You must call .begin() on the BLEService before calling .begin() on + // any characteristic(s) within that service definition.. Calling .begin() on + // a BLECharacteristic will cause it to be added to the last BLEService that + // was 'begin()'ed! + + // Configure the Temperature Measurement characteristic + // See:https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_measurement.xml + // Properties = Indicte + // Min Len = 5 + // Max Len = 5 + // B0 = UINT8 - Flag (MANDATORY) + // b3:7 = Reserved + // b2 = Temperature Type Flag (0 = Not present, 1 = Present) + // b1 = Timestamp Flag (0 = Not present, 1 = Present) + // b0 = Unit Flag (0 = Celsius, 1 = Fahrenheit) + // B4:1 = FLOAT - IEEE-11073 32-bit FLOAT measurement value + htmc.setProperties(CHR_PROPS_INDICATE); + htmc.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); + htmc.setFixedLen(5); + htmc.setCccdWriteCallback(cccd_callback); // Optionally capture CCCD updates + htmc.begin(); + uint8_t htmdata[5] = { 0b00000001, 0 }; // Set the characteristic to use Fahrenheit, without type, timestamp field + htmc.write(htmdata, 5); // Use .write for init data + + // Configure the Temperature Type characteristic + // See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_type.xml + // Properties = Read + // Min Len = 1 + // Max Len = 1 + // B0 = UINT8 - Temperature Type + // 0 = Reserved + // 1 = Armpit + // 2 = Body (general) + // 3 = Ear (usually ear lobe) + // 4 = Finger + // 5 = Gastro-intestinal Tract + // 6 = Mouth + // 7 = Rectum + // 8 = Toe + // 9 = Tympanum (ear drum) + // 10:255 = Reserved + ttype.setProperties(CHR_PROPS_READ); + ttype.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); + ttype.setFixedLen(1); + ttype.begin(); + ttype.write8(2); // Set the characteristic to 'Body' (2) +} + +void connect_callback(uint16_t conn_handle) +{ + char central_name[32] = { 0 }; + Bluefruit.Gap.getPeerName(conn_handle, central_name, sizeof(central_name)); + + Serial.print("Connected to "); + Serial.println(central_name); +} + +void disconnect_callback(uint16_t conn_handle, uint8_t reason) +{ + (void) conn_handle; + (void) reason; + + Serial.println("Disconnected"); + Serial.println("Advertising!"); +} + +void cccd_callback(BLECharacteristic& chr, uint16_t cccd_value) +{ + // Display the raw request packet + Serial.print("CCCD Updated: "); + //Serial.printBuffer(request->data, request->len); + Serial.print(cccd_value); + Serial.println(""); + + // Check the characteristic this CCCD update is associated with in case + // this handler is used for multiple CCCD records. + if (chr.uuid == htmc.uuid) { + if (chr.indicateEnabled()) { + Serial.println("Temperature Measurement 'Indicate' enabled"); + } else { + Serial.println("Temperature Measurement 'Indicate' disabled"); + } + } +} + +void loop() +{ + digitalToggle(LED_RED); + + if ( Bluefruit.connected() ) { + uint8_t htmdata[5] = { 0b00000001 }; // Fahrenheit unit + + float2IEEE11073(tempvalue, &htmdata[1]); + + // Note: We use .indicate instead of .write! + // If it is connected but CCCD is not enabled + // The characteristic's value is still updated although notification is not sent + if ( htmc.indicate(htmdata, sizeof(htmdata)) ){ + Serial.print("Temperature Measurement updated to: "); Serial.println(tempvalue); + }else{ + Serial.println("ERROR: Indicate not set in the CCCD or not connected!"); + } + + tempvalue += 0.5F; + } + + // Only send update once per second + delay(1000); +} + diff --git a/libraries/Bluefruit52Lib/keywords.txt b/libraries/Bluefruit52Lib/keywords.txt index fa82d3bb..41a56755 100644 --- a/libraries/Bluefruit52Lib/keywords.txt +++ b/libraries/Bluefruit52Lib/keywords.txt @@ -154,12 +154,17 @@ handles KEYWORD2 write KEYWORD2 notifyEnabled KEYWORD2 - notify KEYWORD2 notify8 KEYWORD2 notify16 KEYWORD2 notify32 KEYWORD2 +indicateEnabled KEYWORD2 +indicate KEYWORD2 +indicate8 KEYWORD2 +indicate16 KEYWORD2 +indicate32 KEYWORD2 + ####################################### # BLEClientService Methods (KEYWORD2) @@ -201,6 +206,7 @@ enableIndicate KEYWORD2 disableIndicate KEYWORD2 setNotifyCallback KEYWORD2 +setIndicateCallback KEYWORD2 ####################################### # BLEScanner Methods (KEYWORD2) From 357ffb9029c4b84773bafda84a87c3dc58b6938f Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 29 Jan 2018 16:25:14 +0700 Subject: [PATCH 10/39] clean up --- .../examples/Peripheral/custom_hrm/custom_hrm.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/custom_hrm/custom_hrm.ino b/libraries/Bluefruit52Lib/examples/Peripheral/custom_hrm/custom_hrm.ino index 69d00ea9..2d7178d3 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/custom_hrm/custom_hrm.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/custom_hrm/custom_hrm.ino @@ -121,7 +121,7 @@ void setupHRM(void) // Configure the Heart Rate Measurement characteristic // See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.heart_rate_measurement.xml - // Permission = Notify + // Properties = Notify // Min Len = 1 // Max Len = 8 // B0 = UINT8 - Flag (MANDATORY) @@ -144,7 +144,7 @@ void setupHRM(void) // Configure the Body Sensor Location characteristic // See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.body_sensor_location.xml - // Permission = Read + // Properties = Read // Min Len = 1 // Max Len = 1 // B0 = UINT8 - Body Sensor Location From 84a42000f514a124abad4ed79c09a21a0352245e Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 29 Jan 2018 16:26:02 +0700 Subject: [PATCH 11/39] update changelog --- changelog.md | 1 + 1 file changed, 1 insertion(+) diff --git a/changelog.md b/changelog.md index aaf31ec8..f1765d3a 100644 --- a/changelog.md +++ b/changelog.md @@ -5,6 +5,7 @@ - Fixed burning bootloader issue with MacOS - Added gpstest_swuart example sketch - Added indicate API for BLECharacteristic +- Added custom_htm as usage example for indicate API. - BLEClientCharacteristic - Added setIndicateCallback(), issue #113 - Added useAdaCallback option to setNotifyCallback(), setIndicateCallback() From fc2e3603c85dbad8e6556ad495cfeab1276b722d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 29 Jan 2018 16:45:58 +0700 Subject: [PATCH 12/39] update htm example --- .../Peripheral/custom_htm/custom_htm.ino | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino index 6668fd41..a95244eb 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/custom_htm/custom_htm.ino @@ -17,11 +17,9 @@ /* Health Thermometer Service Definitions * Health Thermometer Service: 0x1809 * Temperature Measurement Char: 0x2A1C - * Temperature Type Char: 0x2A1D */ BLEService htms = BLEService(UUID16_SVC_HEALTH_THERMOMETER); BLECharacteristic htmc = BLECharacteristic(UUID16_CHR_TEMPERATURE_MEASUREMENT); -BLECharacteristic ttype = BLECharacteristic(UUID16_CHR_TEMPERATURE_TYPE); BLEDis bledis; // DIS (Device Information Service) helper class instance @@ -102,8 +100,8 @@ void setupHTM(void) // Name UUID Requirement Properties // ---------------------------- ------ ----------- ---------- // Temperature Measurement 0x2A1C Mandatory Indicate - // Temperature Type 0x2A1D Optional Read - // + // + // Temperature Type 0x2A1D Optional Read <-- Not used here // Intermediate Temperature 0x2A1E Optional Read, Notify <-- Not used here // Measurement Interval 0x2A21 Optional Read, Write, Indicate <-- Not used here htms.begin(); @@ -116,27 +114,25 @@ void setupHTM(void) // Configure the Temperature Measurement characteristic // See:https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_measurement.xml // Properties = Indicte - // Min Len = 5 - // Max Len = 5 + // Min Len = 6 + // Max Len = 6 // B0 = UINT8 - Flag (MANDATORY) // b3:7 = Reserved // b2 = Temperature Type Flag (0 = Not present, 1 = Present) // b1 = Timestamp Flag (0 = Not present, 1 = Present) // b0 = Unit Flag (0 = Celsius, 1 = Fahrenheit) // B4:1 = FLOAT - IEEE-11073 32-bit FLOAT measurement value + // B5 = Temperature Type htmc.setProperties(CHR_PROPS_INDICATE); htmc.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); - htmc.setFixedLen(5); + htmc.setFixedLen(6); htmc.setCccdWriteCallback(cccd_callback); // Optionally capture CCCD updates htmc.begin(); - uint8_t htmdata[5] = { 0b00000001, 0 }; // Set the characteristic to use Fahrenheit, without type, timestamp field - htmc.write(htmdata, 5); // Use .write for init data + uint8_t htmdata[6] = { 0b00000101, 0, 0 ,0 ,0, 2 }; // Set the characteristic to use Fahrenheit, with type (body) but no timestamp field + htmc.write(htmdata, sizeof(htmdata)); // Use .write for init data - // Configure the Temperature Type characteristic + // Temperature Type Value // See: https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.temperature_type.xml - // Properties = Read - // Min Len = 1 - // Max Len = 1 // B0 = UINT8 - Temperature Type // 0 = Reserved // 1 = Armpit @@ -149,11 +145,6 @@ void setupHTM(void) // 8 = Toe // 9 = Tympanum (ear drum) // 10:255 = Reserved - ttype.setProperties(CHR_PROPS_READ); - ttype.setPermission(SECMODE_OPEN, SECMODE_NO_ACCESS); - ttype.setFixedLen(1); - ttype.begin(); - ttype.write8(2); // Set the characteristic to 'Body' (2) } void connect_callback(uint16_t conn_handle) @@ -198,7 +189,7 @@ void loop() digitalToggle(LED_RED); if ( Bluefruit.connected() ) { - uint8_t htmdata[5] = { 0b00000001 }; // Fahrenheit unit + uint8_t htmdata[6] = { 0b00000101, 0,0,0,0, 2 }; // Fahrenheit unit, temperature type = body (2) float2IEEE11073(tempvalue, &htmdata[1]); From 9e0a6ff7750611a89e4b15f14708f8c7eb3e9bf7 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 30 Jan 2018 14:27:38 +0700 Subject: [PATCH 13/39] enhance indicat API() to wait for confirm or timeout from peer. --- .../Bluefruit52Lib/src/BLECharacteristic.cpp | 16 ++-- libraries/Bluefruit52Lib/src/BLEGap.h | 6 ++ libraries/Bluefruit52Lib/src/BLEGatt.cpp | 86 ++++++++++++------- libraries/Bluefruit52Lib/src/BLEGatt.h | 3 +- 4 files changed, 68 insertions(+), 43 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index f00d0061..0be98396 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -619,7 +619,9 @@ bool BLECharacteristic::indicate(const void* data, uint16_t len) if ( indicateEnabled() ) { - uint16_t const max_payload = Bluefruit.Gap.getMTU( Bluefruit.connHandle() ) - 3; + uint16_t conn_hdl = Bluefruit.connHandle(); + + uint16_t const max_payload = Bluefruit.Gap.getMTU( conn_hdl ) - 3; const uint8_t* u8data = (const uint8_t*) data; while ( remaining ) @@ -636,16 +638,10 @@ bool BLECharacteristic::indicate(const void* data, uint16_t len) }; LOG_LV2("CHR", "Indicate %d bytes", packet_len); - err_t err; - // If previous indicate is still in progress, wait for a while and try again - while ( NRF_ERROR_BUSY == (err = sd_ble_gatts_hvx(Bluefruit.connHandle(), &hvx_params)) ) - { - // TODO should wait for BLE_GATTS_EVT_HVC event - delay( Bluefruit.connInterval() ); - } - - VERIFY_STATUS( err, false ); + // Blocking wait until receiving confirmation from peer + VERIFY_STATUS( sd_ble_gatts_hvx( conn_hdl, &hvx_params), false ); + VERIFY ( Bluefruit.Gatt.waitForIndicateConfirm(conn_hdl) ); remaining -= packet_len; u8data += packet_len; diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index 07e4066c..ec51df8f 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -105,11 +105,17 @@ class BLEGap SemaphoreHandle_t hvn_tx_sem; SemaphoreHandle_t wrcmd_tx_sem; + + SemaphoreHandle_t indicate_confirm_sem; + bool hvc_received; } gap_peer_t; gap_peer_t _peers[BLE_MAX_CONN]; + gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; } + friend class AdafruitBluefruit; + friend class BLEGatt; }; #endif /* BLEGAP_H_ */ diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index b14ed533..16f94ff3 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -74,24 +74,20 @@ uint16_t BLEGatt::readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffe return (count < 0) ? 0 : count; } -//bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl) -//{ -// while( _adamsg.isWaiting() ) -// { -// // TODO multiple peripherals -// delay( Bluefruit.connInterval() ); -// } -// -// _adamsg.begin(true); -// _adamsg.prepare(NULL, 0); -// -// // Wait for HVC event -// int32_t result = _adamsg.waitUntilComplete(BLE_GENERIC_TIMEOUT); -// -// _adamsg.stop(); -// -// return (result == 0); -//} +bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl) +{ + BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(conn_hdl); + + // hvi confirm semaphore is created on the fly + peer->indicate_confirm_sem = xSemaphoreCreateBinary(); + + xSemaphoreTake(peer->indicate_confirm_sem, portMAX_DELAY); + + vSemaphoreDelete(peer->indicate_confirm_sem); + peer->indicate_confirm_sem = NULL; + + return peer->hvc_received; +} void BLEGatt::_eventHandler(ble_evt_t* evt) { @@ -204,25 +200,51 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) } // GATTC Read Characteristic by UUID procedure - if ( evt_id == BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP ) + switch ( evt_id ) { - ble_gattc_evt_char_val_by_uuid_read_rsp_t* rd_rsp = &evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp; - - if (rd_rsp->count) + case BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP: { - #if SD_VER < 500 - _adamsg.feed(rd_rsp->handle_value[0].p_value, rd_rsp->value_len); - #else - ble_gattc_handle_value_t hdl_value; + ble_gattc_evt_char_val_by_uuid_read_rsp_t* rd_rsp = &evt->evt.gattc_evt.params.char_val_by_uuid_read_rsp; - if ( ERROR_NONE == sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(&evt->evt.gattc_evt, &hdl_value) ) - { - _adamsg.feed(hdl_value.p_value, rd_rsp->value_len); - } - #endif + if (rd_rsp->count) + { + #if SD_VER < 500 + _adamsg.feed(rd_rsp->handle_value[0].p_value, rd_rsp->value_len); + #else + ble_gattc_handle_value_t hdl_value; - _adamsg.complete(); + if ( ERROR_NONE == sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(&evt->evt.gattc_evt, &hdl_value) ) + { + _adamsg.feed(hdl_value.p_value, rd_rsp->value_len); + } + #endif + + _adamsg.complete(); + } } + + case BLE_GATTS_EVT_HVC: + { + LOG_LV2("GATTS", "Confirm received handle = 0x%04X", evt->evt.gatts_evt.params.hvc.handle); + BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl); + + if ( peer->indicate_confirm_sem ) xSemaphoreGive(peer->indicate_confirm_sem); + peer->hvc_received = true; + } + break; + + case BLE_GATTS_EVT_TIMEOUT: + { + LOG_LV2("GATTS", "Timeout Source = %d", evt->evt.gatts_evt.params.timeout.src); + + BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl); + + if ( peer->indicate_confirm_sem ) xSemaphoreGive(peer->indicate_confirm_sem); + peer->hvc_received = false; + } + break; + + default: break; } } diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.h b/libraries/Bluefruit52Lib/src/BLEGatt.h index a930b2a2..4443fc7d 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.h +++ b/libraries/Bluefruit52Lib/src/BLEGatt.h @@ -59,7 +59,8 @@ class BLEGatt BLEGatt(void); uint16_t readCharByUuid(uint16_t conn_hdl, BLEUuid bleuuid, void* buffer, uint16_t bufsize, uint16_t start_hdl = 1, uint16_t end_hdl = 0xffff); -// bool waitForIndicateConfirm(uint16_t conn_hdl); + + bool waitForIndicateConfirm(uint16_t conn_hdl); /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY From b58d2c1f2053b8c200df2bfee49fbe7237cd3fa0 Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 30 Jan 2018 14:29:16 +0700 Subject: [PATCH 14/39] increase version to 0.8.3 --- libraries/Bluefruit52Lib/library.properties | 2 +- platform.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/Bluefruit52Lib/library.properties b/libraries/Bluefruit52Lib/library.properties index dcf231b4..6532283e 100644 --- a/libraries/Bluefruit52Lib/library.properties +++ b/libraries/Bluefruit52Lib/library.properties @@ -1,5 +1,5 @@ name=Adafruit BLE Libraries for Bluefruit52 -version=0.8.2 +version=0.8.3 author=Adafruit maintainer=Adafruit sentence=Arduino library for nRF52-based Adafruit Bluefruit LE modules diff --git a/platform.txt b/platform.txt index 45ad466e..20050b1c 100644 --- a/platform.txt +++ b/platform.txt @@ -17,7 +17,7 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA name=Adafruit nRF52 Boards -version=0.8.2 +version=0.8.3 # Compile variables # ----------------- From 98e69635eeb7156d57752db878b14c3622369646 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 12 Feb 2018 15:17:23 +0700 Subject: [PATCH 15/39] adding hid central --- changelog.md | 5 + .../Central/central_hid/central_hid.ino | 135 ++++++++++++++++++ libraries/Bluefruit52Lib/src/BLEDiscovery.h | 6 + libraries/Bluefruit52Lib/src/BLEScanner.cpp | 10 ++ libraries/Bluefruit52Lib/src/BLEScanner.h | 3 + libraries/Bluefruit52Lib/src/bluefruit.h | 1 + .../src/clients/BLEClientHidAdafruit.cpp | 119 +++++++++++++++ .../src/clients/BLEClientHidAdafruit.h | 79 ++++++++++ 8 files changed, 358 insertions(+) create mode 100644 libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino create mode 100644 libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp create mode 100644 libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h diff --git a/changelog.md b/changelog.md index f1765d3a..8d81b1d5 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,10 @@ # Adafruit nRF52 Arduino Core Changelog +## 0.8.3 + +- Enhance indicat API() to wait for confirm or timeout from peer. +- Add BLEScanner filterService() for BLEService and BLEClientService + ## 0.8.2 - Fixed burning bootloader issue with MacOS diff --git a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino new file mode 100644 index 00000000..906f369d --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino @@ -0,0 +1,135 @@ +/********************************************************************* + This is an example for our nRF52 based Bluefruit LE modules + + Pick one up today in the adafruit shop! + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + MIT license, check LICENSE for more information + All text above, and the splash screen below must be included in + any redistribution +*********************************************************************/ + +/* + * This sketch demonstrate the central API(). A additional bluefruit + * that has bleuart as peripheral is required for the demo. + */ +#include + +BLEClientHidAdafruit hid; + +void setup() +{ + Serial.begin(115200); + + Serial.println("Bluefruit52 Central HID (Keyboard + Mouse) Example"); + Serial.println("--------------------------------------------------\n"); + + // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1 + // SRAM usage required by SoftDevice will increase dramatically with number of connections + Bluefruit.begin(0, 1); + + Bluefruit.setName("Bluefruit52 Central"); + + // Init BLE Central Uart Serivce + hid.begin(); + //clientUart.setRxCallback(bleuart_rx_callback); + + // Increase Blink rate to different from PrPh advertising mode + Bluefruit.setConnLedInterval(250); + + // Callbacks for Central + Bluefruit.Central.setConnectCallback(connect_callback); + Bluefruit.Central.setDisconnectCallback(disconnect_callback); + + /* Start Central Scanning + * - Enable auto scan if disconnected + * - Interval = 100 ms, window = 80 ms + * - Don't use active scan + * - Start(timeout) with timeout = 0 will scan forever (until connected) + */ + Bluefruit.Scanner.setRxCallback(scan_callback); + Bluefruit.Scanner.restartOnDisconnect(true); + Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms + Bluefruit.Scanner.useActiveScan(false); + Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after n seconds + + Bluefruit.Scanner.filterService(hid); // only report HID service +} + +/** + * Callback invoked when scanner pick up an advertising data + * @param report Structural advertising data + */ +void scan_callback(ble_gap_evt_adv_report_t* report) +{ + // Connect to device + Bluefruit.Central.connect(report); +} + +/** + * Callback invoked when an connection is established + * @param conn_handle + */ +void connect_callback(uint16_t conn_handle) +{ + Serial.println("Connected"); + + Serial.print("Discovering HID Service ... "); + + if ( hid.discover(conn_handle) ) + { + Serial.println("Found it"); + +// Serial.println("Enable TXD's notify"); +// clientUart.enableTXD(); + + Serial.println("Ready to receive from peripheral"); + }else + { + Serial.println("Found NONE"); + + // disconect since we couldn't find bleuart service + Bluefruit.Central.disconnect(conn_handle); + } +} + +/** + * Callback invoked when a connection is dropped + * @param conn_handle + * @param reason + */ +void disconnect_callback(uint16_t conn_handle, uint8_t reason) +{ + (void) conn_handle; + (void) reason; + + Serial.println("Disconnected"); +} + +/** + * Callback invoked when uart received data + * @param uart_svc Reference object to the service where the data + * arrived. In this example it is clientUart + */ +//void bleuart_rx_callback(BLEClientUart& uart_svc) +//{ +// Serial.print("[RX]: "); +// +// while ( uart_svc.available() ) +// { +// Serial.print( (char) uart_svc.read() ); +// } +// +// Serial.println(); +//} + +void loop() +{ + // nothing to do + if ( !hid.discovered() ) return; + +} + diff --git a/libraries/Bluefruit52Lib/src/BLEDiscovery.h b/libraries/Bluefruit52Lib/src/BLEDiscovery.h index 3268a61a..913f9495 100644 --- a/libraries/Bluefruit52Lib/src/BLEDiscovery.h +++ b/libraries/Bluefruit52Lib/src/BLEDiscovery.h @@ -95,6 +95,12 @@ class BLEDiscovery return discoverCharacteristic(conn_handle, chr_arr, arrcount(chr_arr)); } + uint8_t discoverCharacteristic(uint16_t conn_handle, BLEClientCharacteristic& chr1, BLEClientCharacteristic& chr2, BLEClientCharacteristic& chr3, BLEClientCharacteristic& chr4, BLEClientCharacteristic& chr5, BLEClientCharacteristic& chr6) + { + BLEClientCharacteristic* chr_arr[] = {&chr1, &chr2, &chr3, &chr4, &chr5, &chr6}; + return discoverCharacteristic(conn_handle, chr_arr, arrcount(chr_arr)); + } + /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY * Although declare as public, it is meant to be invoked by internal diff --git a/libraries/Bluefruit52Lib/src/BLEScanner.cpp b/libraries/Bluefruit52Lib/src/BLEScanner.cpp index 024fe20a..905a8ce3 100644 --- a/libraries/Bluefruit52Lib/src/BLEScanner.cpp +++ b/libraries/Bluefruit52Lib/src/BLEScanner.cpp @@ -277,6 +277,16 @@ void BLEScanner::filterUuid(BLEUuid ble_uuid[], uint8_t count) for(uint8_t i=0; i Date: Mon, 12 Feb 2018 16:08:25 +0700 Subject: [PATCH 16/39] more central hid code --- .../Central/central_hid/central_hid.ino | 9 +++++ libraries/Bluefruit52Lib/src/BLEGap.h | 5 +++ .../src/clients/BLEClientHidAdafruit.cpp | 34 +++++++++++-------- .../src/clients/BLEClientHidAdafruit.h | 16 ++++++++- 4 files changed, 49 insertions(+), 15 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino index 906f369d..23fe9427 100644 --- a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino +++ b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino @@ -83,6 +83,15 @@ void connect_callback(uint16_t conn_handle) { Serial.println("Found it"); + // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.hid_information.xml + uint8_t hidInfo[4]; + hid.getHidInfo(hidInfo); + + Serial.printf("HID version: %d.%d\n", hidInfo[0], hidInfo[1]); + Serial.print("Country code: "); Serial.println(hidInfo[2]); + Serial.printf("HID Flags : 0x%02X\n", hidInfo[3]); + + // Serial.println("Enable TXD's notify"); // clientUart.enableTXD(); diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index ec51df8f..d8e28d28 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -79,6 +79,8 @@ class BLEGap 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); +// bool requestPairing (uint16_t conn_handle); + /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY * Although declare as public, it is meant to be invoked by internal @@ -108,6 +110,9 @@ class BLEGap SemaphoreHandle_t indicate_confirm_sem; bool hvc_received; + + // not really peer data +// ble_gap_sec_params_t sec_param; } gap_peer_t; gap_peer_t _peers[BLE_MAX_CONN]; diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp index 06d812d1..cd28bf90 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp @@ -36,16 +36,6 @@ #include "bluefruit.h" -void kbd_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) -{ - -} - -void mouse_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) -{ - -} - BLEClientHidAdafruit::BLEClientHidAdafruit(void) : BLEClientService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _protcol_mode(UUID16_CHR_PROTOCOL_MODE), @@ -53,7 +43,6 @@ BLEClientHidAdafruit::BLEClientHidAdafruit(void) _mouse_boot_input(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT), _hid_info(UUID16_CHR_HID_INFORMATION), _hid_control(UUID16_CHR_HID_CONTROL_POINT) { - _country = 0; } bool BLEClientHidAdafruit::begin(void) @@ -61,15 +50,19 @@ bool BLEClientHidAdafruit::begin(void) // Invoke base class begin() BLEClientService::begin(); + _protcol_mode.begin(this); + _hid_info.begin(this); + _hid_control.begin(this); + _kbd_boot_input.begin(this); _kbd_boot_output.begin(this); _mouse_boot_input.begin(this); - // set notify callback - _kbd_boot_input.setNotifyCallback(kbd_client_notify_cb); - _mouse_boot_input.setNotifyCallback(mouse_client_notify_cb); + // set notify callback +// _kbd_boot_input.setNotifyCallback(kbd_client_notify_cb); +// _mouse_boot_input.setNotifyCallback(mouse_client_notify_cb); } bool BLEClientHidAdafruit::discover(uint16_t conn_handle) @@ -88,6 +81,19 @@ bool BLEClientHidAdafruit::discover(uint16_t conn_handle) return true; } +bool BLEClientHidAdafruit::getHidInfo(uint8_t info[4]) +{ + return 4 == _hid_info.read(info, 4); +} + +uint8_t BLEClientHidAdafruit::getCountryCode(void) +{ + uint8_t info[4] = { 0 }; + getHidInfo(info); + + return info[2]; +} + bool BLEClientHidAdafruit::keyboardPresent(void) { return _kbd_boot_input.discovered() && _kbd_boot_output.discovered(); diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h index 889728ac..c18b0474 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h @@ -46,22 +46,36 @@ class BLEClientHidAdafruit : public BLEClientService { public: + // Callback Signatures + typedef void (*kbd_callback_t ) (uint8_t modifier, uint8_t keycode[6]); + typedef void (*mouse_callback_t ) (uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan); + BLEClientHidAdafruit(void); virtual bool begin(void); virtual bool discover(uint16_t conn_handle); + bool getHidInfo(uint8_t info[4]); + uint8_t getCountryCode(void); + + // Check if peripheral support keyboard/mouse bool keyboardPresent(void); bool mousePresent(void); + // Enable/Disable report notification for keyboard/mouse bool enableKeyboard(void); bool disableKeyboard(void); bool enableMouse(void); bool disableMouse(void); + // Report callback + void setKeyboardReportCallback(kbd_callback_t fp); + void setMouseReportCallback(mouse_callback_t fp); + private: - uint8_t _country; + kbd_callback_t _kbd_cb; + mouse_callback_t _mouse_cb; // Only support Boot protocol for keyboard and Mouse BLEClientCharacteristic _protcol_mode; From 4fab39f26a068a6b9aef4b413a4be4b65a550886 Mon Sep 17 00:00:00 2001 From: hathach Date: Wed, 14 Feb 2018 00:22:40 +0700 Subject: [PATCH 17/39] improving bonding management --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 4 + libraries/Bluefruit52Lib/src/BLEGap.h | 3 - libraries/Bluefruit52Lib/src/bluefruit.cpp | 88 ++++++------- libraries/Bluefruit52Lib/src/bluefruit.h | 11 +- .../Bluefruit52Lib/src/bluefruit_common.h | 2 + .../Bluefruit52Lib/src/utility/bonding.cpp | 120 ++++++++++++++++++ .../Bluefruit52Lib/src/utility/bonding.h | 67 ++++++++++ 7 files changed, 242 insertions(+), 53 deletions(-) create mode 100644 libraries/Bluefruit52Lib/src/utility/bonding.cpp create mode 100644 libraries/Bluefruit52Lib/src/utility/bonding.h diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 75507a14..4f544777 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -240,6 +240,10 @@ void BLEGap::_eventHandler(ble_evt_t* evt) } break; + case BLE_GAP_EVT_SEC_PARAMS_REQUEST: + // Pairing in progress, Peer asking for our info + break; + #if SD_VER < 500 case BLE_EVT_TX_COMPLETE: if ( peer->hvn_tx_sem ) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index d8e28d28..723ccdc4 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -110,9 +110,6 @@ class BLEGap SemaphoreHandle_t indicate_confirm_sem; bool hvc_received; - - // not really peer data -// ble_gap_sec_params_t sec_param; } gap_peer_t; gap_peer_t _peers[BLE_MAX_CONN]; diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 123a80c7..6737d99f 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -36,6 +36,7 @@ #include "bluefruit.h" #include +#include "utility/bonding.h" #define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) @@ -1057,7 +1058,8 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) { _bonded = true; - ada_callback(NULL, _adafruit_save_bond_key_dfr, _conn_hdl); +// ada_callback(NULL, _adafruit_save_bond_key_dfr, _conn_hdl); + bond_save_keys(evt_conn_hdl, &_bond_data); }else { PRINT_HEX(status->auth_status); @@ -1149,11 +1151,11 @@ void AdafruitBluefruit::clearBonds(void) * - Name 32 bytes * - CCCD variable *------------------------------------------------------------------*/ -void _adafruit_save_bond_key_dfr(uint32_t conn_handle) -{ - (void) conn_handle; - Bluefruit._saveBondKeys(); -} +//void _adafruit_save_bond_key_dfr(uint32_t conn_handle) +//{ +// (void) conn_handle; +// Bluefruit._saveBondKeys(); +//} void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) { @@ -1161,43 +1163,43 @@ void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) Bluefruit._saveBondCCCD(); } -void AdafruitBluefruit::_saveBondKeys(void) -{ - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); - - char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; - Gap.getPeerName(_conn_hdl, devname, CFG_MAX_DEVNAME_LEN); - - NffsFile file(filename, FS_ACCESS_WRITE); - - VERIFY( file.exists(), ); - - bool result = true; - - // write keys - if ( !file.write((uint8_t*)&_bond_data, sizeof(_bond_data)) ) - { - result = false; - } - - // write device name - if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) ) - { - result = false; - } - - file.close(); - - if (result) - { - LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); - }else - { - LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname); - } - printBondDir(); -} +//void AdafruitBluefruit::_saveBondKeys(void) +//{ +// char filename[BOND_FILENAME_LEN]; +// sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); +// +// char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; +// Gap.getPeerName(_conn_hdl, devname, CFG_MAX_DEVNAME_LEN); +// +// NffsFile file(filename, FS_ACCESS_WRITE); +// +// VERIFY( file.exists(), ); +// +// bool result = true; +// +// // write keys +// if ( !file.write((uint8_t*)&_bond_data, sizeof(_bond_data)) ) +// { +// result = false; +// } +// +// // write device name +// if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) ) +// { +// result = false; +// } +// +// file.close(); +// +// if (result) +// { +// LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); +// }else +// { +// LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname); +// } +// printBondDir(); +//} bool AdafruitBluefruit::_loadBondKeys(uint16_t ediv) { diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 02159a8d..d1281e3f 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -40,7 +40,6 @@ #include "bluefruit_common.h" #define CFG_ADV_BLINKY_INTERVAL 500 -#define CFG_MAX_DEVNAME_LEN 32 /* Note changing these parameters will affect APP_RAM_BASE * --> need to update RAM region in linker file @@ -91,6 +90,9 @@ #include "utility/AdaCallback.h" + +#include "utility/bonding.h" + enum { BANDWIDTH_AUTO = 0, @@ -234,12 +236,7 @@ class AdafruitBluefruit ble_gap_sec_params_t _sec_param; // Shared keys with bonded device, size = 80 bytes - struct - { - ble_gap_enc_key_t own_enc; - ble_gap_enc_key_t peer_enc; - ble_gap_id_key_t peer_id; - } _bond_data; + bond_data_t _bond_data; enum { diff --git a/libraries/Bluefruit52Lib/src/bluefruit_common.h b/libraries/Bluefruit52Lib/src/bluefruit_common.h index c6250fb7..f6f98c93 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit_common.h +++ b/libraries/Bluefruit52Lib/src/bluefruit_common.h @@ -43,6 +43,8 @@ #include "utility/AdaMsg.h" +#define CFG_MAX_DEVNAME_LEN 32 + #define BLE_GENERIC_TIMEOUT 100 #define BLE_GAP_CONN_SUPERVISION_TIMEOUT_MS 2000 diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp new file mode 100644 index 00000000..7c53d80e --- /dev/null +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -0,0 +1,120 @@ +/**************************************************************************/ +/*! + @file bonding.cpp + @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 "bonding.h" +#include "bluefruit.h" + +#if CFG_DEBUG >= 2 +//#define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) +#define printBondDir() +#else +#define printBondDir() +#endif + + + +/*------------------------------------------------------------------*/ +/* Saving Bond Data to Nffs in following layout + * - _bond_data 80 bytes + * - Name 32 bytes + * - CCCD variable + *------------------------------------------------------------------*/ +static void bond_save_keys_dfr(uint16_t conn_hdl, bond_data_t* bdata) +{ + char filename[BOND_FILENAME_LEN]; + sprintf(filename, BOND_FILENAME, bdata->own_enc.master_id.ediv); + + char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; + Bluefruit.Gap.getPeerName(conn_hdl, devname, CFG_MAX_DEVNAME_LEN); + + NffsFile file(filename, FS_ACCESS_WRITE); + + VERIFY( file.exists(), ); + + bool result = true; + + // write keys + if ( !file.write((uint8_t*)bdata, sizeof(bond_data_t)) ) + { + result = false; + } + + // write device name + if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) ) + { + result = false; + } + + file.close(); + + if (result) + { + LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); + }else + { + LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname); + } + + printBondDir(); +} + +void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata) +{ + uint8_t* buf = (uint8_t*) rtos_malloc( sizeof(bond_data_t) ); + VERIFY(buf, ); + + memcpy(buf, bdata, sizeof(bond_data_t)); + + // queue to execute in Ada Callback thread + ada_callback(buf, bond_save_keys_dfr, conn_hdl, buf); +} + +void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv) +{ + +} + +bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) +{ + +} + +bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) +{ + +} diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h new file mode 100644 index 00000000..aad06ec3 --- /dev/null +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -0,0 +1,67 @@ +/**************************************************************************/ +/*! + @file bonding.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. +*/ +/**************************************************************************/ +#ifndef BONDING_H_ +#define BONDING_H_ + +#include "bluefruit_common.h" + +#define CFG_BOND_NFFS_DIR "/adafruit/bond" +#define BOND_FILENAME CFG_BOND_NFFS_DIR "/%04x" +#define BOND_FILENAME_LEN (sizeof(CFG_BOND_NFFS_DIR) + 10) + +// Shared keys with bonded device, size = 80 bytes +typedef struct +{ + ble_gap_enc_key_t own_enc; + ble_gap_enc_key_t peer_enc; + ble_gap_id_key_t peer_id; +} bond_data_t; + +enum +{ + BOND_FILE_DEVNAME_OFFSET = sizeof(bond_data_t), + BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN +}; + + +void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata); +void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv); + +bool bond_load_keys(uint16_t ediv, bond_data_t* bdata); +bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv); + + +#endif /* BONDING_H_ */ From 45b4e58a6a0f8883bb2e7539894e20ab7921ddcc Mon Sep 17 00:00:00 2001 From: Robert Hodaszi Date: Wed, 21 Feb 2018 16:48:56 +0100 Subject: [PATCH 18/39] BLEHidGeneric: fix missing writeN() function update Otherwise getting the following error: uint16_t BLECharacteristic::write(const void*, uint16_t): 431: verify failed, error = NRF_ERROR_INVALID_ADDR Signed-off-by: Robert Hodaszi --- libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp index 337c49b7..e3301249 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp @@ -232,7 +232,7 @@ err_t BLEHidGeneric::begin(void) _chr_control.setPermission(SECMODE_NO_ACCESS, SECMODE_ENC_NO_MITM); _chr_control.setFixedLen(1); VERIFY_STATUS( _chr_control.begin() ); - _chr_control.write( (uint8_t) 0 ); + _chr_control.write8(0); return ERROR_NONE; } From dcbecb8b5fcb120565c3a33bf56e4a5ec736cc93 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Feb 2018 14:51:10 +0700 Subject: [PATCH 19/39] complete move all bond function to bonding.cpp --- .../BLEHomekit/src/HAPCharacteristic.cpp | 8 - .../Bluefruit52Lib/src/BLECharacteristic.cpp | 8 - libraries/Bluefruit52Lib/src/BLEGatt.cpp | 18 +- libraries/Bluefruit52Lib/src/bluefruit.cpp | 215 +++++++++--------- libraries/Bluefruit52Lib/src/bluefruit.h | 25 +- .../Bluefruit52Lib/src/utility/bonding.cpp | 89 ++++++++ 6 files changed, 219 insertions(+), 144 deletions(-) diff --git a/libraries/BLEHomekit/src/HAPCharacteristic.cpp b/libraries/BLEHomekit/src/HAPCharacteristic.cpp index da99bc70..054c8663 100644 --- a/libraries/BLEHomekit/src/HAPCharacteristic.cpp +++ b/libraries/BLEHomekit/src/HAPCharacteristic.cpp @@ -406,14 +406,6 @@ void HAPCharacteristic::_eventHandler(ble_evt_t* event) memcpy(&value, request->data, 2); _cccd_wr_cb(*this, value); } - - // TODO could move later - // Save CCCD if bonded to file whenever changed - extern void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle); - if ( Bluefruit.connPaired() ) - { - ada_callback(NULL, _adafruit_save_bond_cccd_dfr, conn_hdl); - } } } diff --git a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp index 0be98396..2ed9fa69 100644 --- a/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp +++ b/libraries/Bluefruit52Lib/src/BLECharacteristic.cpp @@ -394,14 +394,6 @@ void BLECharacteristic::_eventHandler(ble_evt_t* event) memcpy(&value, request->data, 2); _cccd_wr_cb(*this, value); } - - // TODO could move later - // Save CCCD if bonded to file whenever changed - extern void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle); - if ( Bluefruit.connPaired() ) - { - ada_callback(NULL, _adafruit_save_bond_cccd_dfr, event->evt.common_evt.conn_handle); - } } } break; diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index 16f94ff3..61695f19 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -35,6 +35,7 @@ /**************************************************************************/ #include "bluefruit.h" +#include "utility/bonding.h" BLEGatt::BLEGatt(void) @@ -95,7 +96,8 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) const uint16_t evt_conn_hdl = evt->evt.common_evt.conn_handle; const uint16_t evt_id = evt->header.evt_id; - // Server Service TODO multiple peripherals + /*------------- Server service -------------*/ + // TODO multiple peripherals // if ( evt_conn_hdl == Bluefruit.connHandle() ) { if ( evt_id == BLE_GAP_EVT_DISCONNECTED || evt_id == BLE_GAP_EVT_CONNECTED ) @@ -113,7 +115,7 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) } } - // Server Characteristics + /*------------- Server Characteristics -------------*/ // TODO multiple prph connection if ( evt_conn_hdl == Bluefruit.connHandle() ) { @@ -127,11 +129,11 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) 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; - break; + break; case BLE_GATTS_EVT_WRITE: req_handle = evt->evt.gatts_evt.params.write.handle; - break; + break; default: break; } @@ -140,11 +142,17 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) if ((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 ( Bluefruit.connPaired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) ) + { + bond_save_cccd(evt_conn_hdl, Bluefruit._bond_data.own_enc.master_id.ediv); + } } } } - // Client Characteristics + /*------------- Client Characteristics -------------*/ for(int i=0; i<_client.chr_count; i++) { if ( evt_conn_hdl == _client.chr_list[i]->connHandle() ) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 6737d99f..e9fe1f50 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -64,8 +64,6 @@ extern "C" void adafruit_ble_task(void* arg); void adafruit_soc_task(void* arg); -void _adafruit_save_bond_key_dfr(uint32_t conn_handle); - #if CFG_DEBUG >= 2 #define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) #else @@ -954,9 +952,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) break; case BLE_GAP_EVT_DISCONNECTED: - // Save all configured cccd - if (_bonded) _saveBondCCCD(); - if (_disconnect_cb) ada_callback(NULL, _disconnect_cb, _conn_hdl, evt->evt.gap_evt.params.disconnected.reason); LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason); @@ -1012,7 +1007,7 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) // return security information. Otherwise NULL ble_gap_evt_sec_info_request_t* sec_request = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request; - if ( _loadBondKeys(sec_request->master_id.ediv) ) + if ( bond_load_keys(sec_request->master_id.ediv, &_bond_data) ) { sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_bond_data.own_enc.enc_info, &_bond_data.peer_id.id_info, NULL); } else @@ -1039,10 +1034,10 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) // Connection is secured aka Paired COMMENT_OUT( ble_gap_conn_sec_t* conn_sec = (ble_gap_conn_sec_t*) &evt->evt.gap_evt.params.conn_sec_update.conn_sec; ) - // Previously bonded --> secure by re-connection process - // --> Load & Set Sys Attr (Apply Service Context) - // Else Init Sys Attr - _loadBondCCCD(_bond_data.own_enc.master_id.ediv); + // Previously bonded --> secure by re-connection process + // --> Load & Set Sys Attr (Apply Service Context) + // Else Init Sys Attr + bond_load_cccd(evt_conn_hdl, _bond_data.own_enc.master_id.ediv); // Consider Paired as Bonded _bonded = true; @@ -1157,11 +1152,11 @@ void AdafruitBluefruit::clearBonds(void) // Bluefruit._saveBondKeys(); //} -void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) -{ - (void) conn_handle; - Bluefruit._saveBondCCCD(); -} +//void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) +//{ +// (void) conn_handle; +// Bluefruit._saveBondCCCD(); +//} //void AdafruitBluefruit::_saveBondKeys(void) //{ @@ -1201,103 +1196,103 @@ void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) // printBondDir(); //} -bool AdafruitBluefruit::_loadBondKeys(uint16_t ediv) -{ - VERIFY_STATIC(sizeof(_bond_data) == 80 ); +//bool AdafruitBluefruit::_loadBondKeys(uint16_t ediv) +//{ +// VERIFY_STATIC(sizeof(_bond_data) == 80 ); +// +// char filename[BOND_FILENAME_LEN]; +// sprintf(filename, BOND_FILENAME, ediv); +// +// bool result = (Nffs.readFile(filename, &_bond_data, sizeof(_bond_data)) > 0); +// +// if ( result ) +// { +// LOG_LV2("BOND", "Load Keys from file %s", filename); +// }else +// { +// LOG_LV1("BOND", "Keys not found"); +// } +// +// return result; +//} - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); +//void AdafruitBluefruit::_saveBondCCCD(void) +//{ +// VERIFY( _bond_data.own_enc.master_id.ediv != 0xFFFF, ); +// +// uint16_t len=0; +// sd_ble_gatts_sys_attr_get(_conn_hdl, NULL, &len, SVC_CONTEXT_FLAG); +// +// uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); +// VERIFY( sys_attr, ); +// +// if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(_conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) ) +// { +// // save to file +// char filename[BOND_FILENAME_LEN]; +// sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); +// +// if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) +// { +// LOG_LV2("BOND", "CCCD setting is saved to file %s", filename); +// }else +// { +// LOG_LV1("BOND", "Failed to save CCCD setting"); +// } +// +// } +// +// printBondDir(); +// +// rtos_free(sys_attr); +//} - bool result = (Nffs.readFile(filename, &_bond_data, sizeof(_bond_data)) > 0); - - if ( result ) - { - LOG_LV2("BOND", "Load Keys from file %s", filename); - }else - { - LOG_LV1("BOND", "Keys not found"); - } - - return result; -} - -void AdafruitBluefruit::_saveBondCCCD(void) -{ - VERIFY( _bond_data.own_enc.master_id.ediv != 0xFFFF, ); - - uint16_t len=0; - sd_ble_gatts_sys_attr_get(_conn_hdl, NULL, &len, SVC_CONTEXT_FLAG); - - uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); - VERIFY( sys_attr, ); - - if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(_conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) ) - { - // save to file - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); - - if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) - { - LOG_LV2("BOND", "CCCD setting is saved to file %s", filename); - }else - { - LOG_LV1("BOND", "Failed to save CCCD setting"); - } - - } - - printBondDir(); - - rtos_free(sys_attr); -} - -void AdafruitBluefruit::_loadBondCCCD(uint16_t ediv) -{ - bool loaded = false; - - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); - - NffsFile file(filename, FS_ACCESS_READ); - - if ( file.exists() ) - { - int32_t len = file.size() - BOND_FILE_CCCD_OFFSET; - - if ( len ) - { - uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); - - if (sys_attr) - { - file.seek(BOND_FILE_CCCD_OFFSET); - - if ( file.read(sys_attr, len ) ) - { - if (ERROR_NONE == sd_ble_gatts_sys_attr_set(_conn_hdl, sys_attr, len, SVC_CONTEXT_FLAG) ) - { - loaded = true; - - LOG_LV2("BOND", "Load CCCD from file %s", filename); - }else - { - LOG_LV1("BOND", "CCCD setting not found"); - } - } - - rtos_free(sys_attr); - } - } - } - - file.close(); - - if ( !loaded ) - { - sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); - } -} +//void AdafruitBluefruit::_loadBondCCCD(uint16_t ediv) +//{ +// bool loaded = false; +// +// char filename[BOND_FILENAME_LEN]; +// sprintf(filename, BOND_FILENAME, ediv); +// +// NffsFile file(filename, FS_ACCESS_READ); +// +// if ( file.exists() ) +// { +// int32_t len = file.size() - BOND_FILE_CCCD_OFFSET; +// +// if ( len ) +// { +// uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); +// +// if (sys_attr) +// { +// file.seek(BOND_FILE_CCCD_OFFSET); +// +// if ( file.read(sys_attr, len ) ) +// { +// if (ERROR_NONE == sd_ble_gatts_sys_attr_set(_conn_hdl, sys_attr, len, SVC_CONTEXT_FLAG) ) +// { +// loaded = true; +// +// LOG_LV2("BOND", "Load CCCD from file %s", filename); +// }else +// { +// LOG_LV1("BOND", "CCCD setting not found"); +// } +// } +// +// rtos_free(sys_attr); +// } +// } +// } +// +// file.close(); +// +// if ( !loaded ) +// { +// sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); +// } +//} void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key) { diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index d1281e3f..91a80a59 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -196,8 +196,16 @@ class AdafruitBluefruit void _setConnLed (bool on_off); void _bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key); - void _saveBondKeys(void); - void _saveBondCCCD(void); +// void _saveBondKeys(void); +// void _saveBondCCCD(void); + + // Shared keys with bonded device, size = 80 bytes + bond_data_t _bond_data; + enum + { + BOND_FILE_DEVNAME_OFFSET = sizeof(_bond_data), + BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN + }; private: /*------------- SoftDevice Configuration -------------*/ @@ -235,15 +243,6 @@ class AdafruitBluefruit ble_gap_sec_params_t _sec_param; - // Shared keys with bonded device, size = 80 bytes - bond_data_t _bond_data; - - enum - { - BOND_FILE_DEVNAME_OFFSET = sizeof(_bond_data), - BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN - }; - COMMENT_OUT( uint8_t _auth_type; char _pin[BLE_GAP_PASSKEY_LEN]; @@ -252,8 +251,8 @@ COMMENT_OUT( /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY *------------------------------------------------------------------*/ - bool _loadBondKeys(uint16_t ediv); - void _loadBondCCCD(uint16_t ediv); +// bool _loadBondKeys(uint16_t ediv); +// void _loadBondCCCD(uint16_t ediv); void _ble_handler(ble_evt_t* evt); friend void SD_EVT_IRQHandler(void); diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 7c53d80e..87e714a8 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -46,6 +46,7 @@ #define printBondDir() #endif +#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) /*------------------------------------------------------------------*/ @@ -104,17 +105,105 @@ void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata) ada_callback(buf, bond_save_keys_dfr, conn_hdl, buf); } +static void bond_save_cccd_dfr (uint16_t conn_hdl, uint16_t ediv) +{ + uint16_t len=0; + sd_ble_gatts_sys_attr_get(conn_hdl, NULL, &len, SVC_CONTEXT_FLAG); + + uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); + VERIFY( sys_attr, ); + + if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) ) + { + // save to file + char filename[BOND_FILENAME_LEN]; + sprintf(filename, BOND_FILENAME, ediv); + + if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) + { + LOG_LV2("BOND", "CCCD setting is saved to file %s", filename); + }else + { + LOG_LV1("BOND", "Failed to save CCCD setting"); + } + + } + + rtos_free(sys_attr); + printBondDir(); +} + void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv) { + VERIFY( ediv != 0xFFFF, ); + // queue to execute in Ada Callback thread + ada_callback(NULL, bond_save_cccd_dfr, cond_hdl, ediv); } bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) { + char filename[BOND_FILENAME_LEN]; + sprintf(filename, BOND_FILENAME, ediv); + bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0); + + if ( result ) + { + LOG_LV2("BOND", "Load Keys from file %s", filename); + }else + { + LOG_LV1("BOND", "Keys not found"); + } + + return result; } bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) { + bool loaded = false; + char filename[BOND_FILENAME_LEN]; + sprintf(filename, BOND_FILENAME, ediv); + + NffsFile file(filename, FS_ACCESS_READ); + + if ( file.exists() ) + { + int32_t len = file.size() - BOND_FILE_CCCD_OFFSET; + + if ( len ) + { + uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); + + if (sys_attr) + { + file.seek(BOND_FILE_CCCD_OFFSET); + + if ( file.read(sys_attr, len ) ) + { + if (ERROR_NONE == sd_ble_gatts_sys_attr_set(cond_hdl, sys_attr, len, SVC_CONTEXT_FLAG) ) + { + loaded = true; + + LOG_LV2("BOND", "Load CCCD from file %s", filename); + }else + { + LOG_LV1("BOND", "CCCD setting not found"); + } + } + + rtos_free(sys_attr); + } + } + } + + file.close(); + + if ( !loaded ) + { + sd_ble_gatts_sys_attr_set(cond_hdl, NULL, 0, 0); + } + + return loaded; } From acd4abec1d2e2b46d416fe007a3823c18c5e4371 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Feb 2018 14:56:36 +0700 Subject: [PATCH 20/39] clean up --- libraries/Bluefruit52Lib/src/bluefruit.cpp | 157 --------------------- libraries/Bluefruit52Lib/src/bluefruit.h | 5 - 2 files changed, 162 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index e9fe1f50..d0f9f1af 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -38,8 +38,6 @@ #include #include "utility/bonding.h" -#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) - #define CFG_BLE_TX_POWER_LEVEL 0 #define CFG_DEFAULT_NAME "Bluefruit52" @@ -1053,7 +1051,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) { _bonded = true; -// ada_callback(NULL, _adafruit_save_bond_key_dfr, _conn_hdl); bond_save_keys(evt_conn_hdl, &_bond_data); }else { @@ -1140,160 +1137,6 @@ void AdafruitBluefruit::clearBonds(void) printBondDir(); } -/*------------------------------------------------------------------*/ -/* Saving Bond Data to Nffs in following layout - * - _bond_data 80 bytes - * - Name 32 bytes - * - CCCD variable - *------------------------------------------------------------------*/ -//void _adafruit_save_bond_key_dfr(uint32_t conn_handle) -//{ -// (void) conn_handle; -// Bluefruit._saveBondKeys(); -//} - -//void _adafruit_save_bond_cccd_dfr(uint32_t conn_handle) -//{ -// (void) conn_handle; -// Bluefruit._saveBondCCCD(); -//} - -//void AdafruitBluefruit::_saveBondKeys(void) -//{ -// char filename[BOND_FILENAME_LEN]; -// sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); -// -// char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; -// Gap.getPeerName(_conn_hdl, devname, CFG_MAX_DEVNAME_LEN); -// -// NffsFile file(filename, FS_ACCESS_WRITE); -// -// VERIFY( file.exists(), ); -// -// bool result = true; -// -// // write keys -// if ( !file.write((uint8_t*)&_bond_data, sizeof(_bond_data)) ) -// { -// result = false; -// } -// -// // write device name -// if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) ) -// { -// result = false; -// } -// -// file.close(); -// -// if (result) -// { -// LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); -// }else -// { -// LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname); -// } -// printBondDir(); -//} - -//bool AdafruitBluefruit::_loadBondKeys(uint16_t ediv) -//{ -// VERIFY_STATIC(sizeof(_bond_data) == 80 ); -// -// char filename[BOND_FILENAME_LEN]; -// sprintf(filename, BOND_FILENAME, ediv); -// -// bool result = (Nffs.readFile(filename, &_bond_data, sizeof(_bond_data)) > 0); -// -// if ( result ) -// { -// LOG_LV2("BOND", "Load Keys from file %s", filename); -// }else -// { -// LOG_LV1("BOND", "Keys not found"); -// } -// -// return result; -//} - -//void AdafruitBluefruit::_saveBondCCCD(void) -//{ -// VERIFY( _bond_data.own_enc.master_id.ediv != 0xFFFF, ); -// -// uint16_t len=0; -// sd_ble_gatts_sys_attr_get(_conn_hdl, NULL, &len, SVC_CONTEXT_FLAG); -// -// uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); -// VERIFY( sys_attr, ); -// -// if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(_conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) ) -// { -// // save to file -// char filename[BOND_FILENAME_LEN]; -// sprintf(filename, BOND_FILENAME, _bond_data.own_enc.master_id.ediv); -// -// if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) -// { -// LOG_LV2("BOND", "CCCD setting is saved to file %s", filename); -// }else -// { -// LOG_LV1("BOND", "Failed to save CCCD setting"); -// } -// -// } -// -// printBondDir(); -// -// rtos_free(sys_attr); -//} - -//void AdafruitBluefruit::_loadBondCCCD(uint16_t ediv) -//{ -// bool loaded = false; -// -// char filename[BOND_FILENAME_LEN]; -// sprintf(filename, BOND_FILENAME, ediv); -// -// NffsFile file(filename, FS_ACCESS_READ); -// -// if ( file.exists() ) -// { -// int32_t len = file.size() - BOND_FILE_CCCD_OFFSET; -// -// if ( len ) -// { -// uint8_t* sys_attr = (uint8_t*) rtos_malloc( len ); -// -// if (sys_attr) -// { -// file.seek(BOND_FILE_CCCD_OFFSET); -// -// if ( file.read(sys_attr, len ) ) -// { -// if (ERROR_NONE == sd_ble_gatts_sys_attr_set(_conn_hdl, sys_attr, len, SVC_CONTEXT_FLAG) ) -// { -// loaded = true; -// -// LOG_LV2("BOND", "Load CCCD from file %s", filename); -// }else -// { -// LOG_LV1("BOND", "CCCD setting not found"); -// } -// } -// -// rtos_free(sys_attr); -// } -// } -// } -// -// file.close(); -// -// if ( !loaded ) -// { -// sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); -// } -//} - void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key) { if (!_bonded) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 91a80a59..d8a9ddc2 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -196,9 +196,6 @@ class AdafruitBluefruit void _setConnLed (bool on_off); void _bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key); -// void _saveBondKeys(void); -// void _saveBondCCCD(void); - // Shared keys with bonded device, size = 80 bytes bond_data_t _bond_data; enum @@ -251,8 +248,6 @@ COMMENT_OUT( /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY *------------------------------------------------------------------*/ -// bool _loadBondKeys(uint16_t ediv); -// void _loadBondCCCD(uint16_t ediv); void _ble_handler(ble_evt_t* evt); friend void SD_EVT_IRQHandler(void); From 86ea7e7ae5731c742f82ad51e2f3b1d4a4ae3928 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Feb 2018 15:04:44 +0700 Subject: [PATCH 21/39] more clean up --- libraries/Bluefruit52Lib/src/bluefruit.cpp | 19 +----- libraries/Bluefruit52Lib/src/bluefruit.h | 5 -- .../Bluefruit52Lib/src/utility/bonding.cpp | 65 ++++++++++++------- .../Bluefruit52Lib/src/utility/bonding.h | 6 +- 4 files changed, 48 insertions(+), 47 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index d0f9f1af..b0f08c3d 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -41,14 +41,9 @@ #define CFG_BLE_TX_POWER_LEVEL 0 #define CFG_DEFAULT_NAME "Bluefruit52" - #define CFG_BLE_TASK_STACKSIZE (512*3) #define CFG_SOC_TASK_STACKSIZE (200) -#define CFG_BOND_NFFS_DIR "/adafruit/bond" -#define BOND_FILENAME CFG_BOND_NFFS_DIR "/%04x" -#define BOND_FILENAME_LEN (sizeof(CFG_BOND_NFFS_DIR) + 10) - AdafruitBluefruit Bluefruit; /*------------------------------------------------------------------*/ @@ -62,12 +57,6 @@ extern "C" void adafruit_ble_task(void* arg); void adafruit_soc_task(void* arg); -#if CFG_DEBUG >= 2 -#define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) -#else -#define printBondDir() -#endif - /*------------------------------------------------------------------*/ /* INTERNAL FUNCTION *------------------------------------------------------------------*/ @@ -1128,13 +1117,7 @@ bool AdafruitBluefruit::requestPairing(void) void AdafruitBluefruit::clearBonds(void) { - // Detele bonds dir - Nffs.remove(CFG_BOND_NFFS_DIR); - - // Create an empty one - Nffs.mkdir_p(CFG_BOND_NFFS_DIR); - - printBondDir(); + bond_clear(); } void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key) diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index d8a9ddc2..89cc757d 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -198,11 +198,6 @@ class AdafruitBluefruit // Shared keys with bonded device, size = 80 bytes bond_data_t _bond_data; - enum - { - BOND_FILE_DEVNAME_OFFSET = sizeof(_bond_data), - BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN - }; private: /*------------- SoftDevice Configuration -------------*/ diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 87e714a8..96f83af3 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -39,22 +39,24 @@ #include "bonding.h" #include "bluefruit.h" +#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) + #if CFG_DEBUG >= 2 -//#define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) -#define printBondDir() +#define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) #else #define printBondDir() #endif -#define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) - - /*------------------------------------------------------------------*/ /* Saving Bond Data to Nffs in following layout * - _bond_data 80 bytes * - Name 32 bytes * - CCCD variable *------------------------------------------------------------------*/ + +/*------------------------------------------------------------------*/ +/* Keys + *------------------------------------------------------------------*/ static void bond_save_keys_dfr(uint16_t conn_hdl, bond_data_t* bdata) { char filename[BOND_FILENAME_LEN]; @@ -105,6 +107,28 @@ void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata) ada_callback(buf, bond_save_keys_dfr, conn_hdl, buf); } +bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) +{ + char filename[BOND_FILENAME_LEN]; + sprintf(filename, BOND_FILENAME, ediv); + + bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0); + + if ( result ) + { + LOG_LV2("BOND", "Load Keys from file %s", filename); + }else + { + LOG_LV1("BOND", "Keys not found"); + } + + return result; +} + + +/*------------------------------------------------------------------*/ +/* CCCD + *------------------------------------------------------------------*/ static void bond_save_cccd_dfr (uint16_t conn_hdl, uint16_t ediv) { uint16_t len=0; @@ -141,23 +165,6 @@ void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv) ada_callback(NULL, bond_save_cccd_dfr, cond_hdl, ediv); } -bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) -{ - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); - - bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0); - - if ( result ) - { - LOG_LV2("BOND", "Load Keys from file %s", filename); - }else - { - LOG_LV1("BOND", "Keys not found"); - } - - return result; -} bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) { @@ -207,3 +214,17 @@ bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) return loaded; } + +/*------------------------------------------------------------------*/ +/* DELETE + *------------------------------------------------------------------*/ +void bond_clear(void) +{ + // Detele bonds dir + Nffs.remove(CFG_BOND_NFFS_DIR); + + // Create an empty one + Nffs.mkdir_p(CFG_BOND_NFFS_DIR); + + printBondDir(); +} diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h index aad06ec3..67731d8b 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.h +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -58,10 +58,12 @@ enum void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata); -void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv); - bool bond_load_keys(uint16_t ediv, bond_data_t* bdata); + +void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv); bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv); +void bond_clear(void); + #endif /* BONDING_H_ */ From c4e25295e2f062d925d505a413ce2c359b79b738 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Feb 2018 23:38:41 +0700 Subject: [PATCH 22/39] move pairing event handle code to BLEGap - add bond_init() - move thing around --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 220 +++++++++++++--- libraries/Bluefruit52Lib/src/BLEGap.h | 71 +++--- libraries/Bluefruit52Lib/src/bluefruit.cpp | 239 ++++++++---------- libraries/Bluefruit52Lib/src/bluefruit.h | 5 - .../Bluefruit52Lib/src/services/BLEDfu.cpp | 24 +- .../Bluefruit52Lib/src/utility/bonding.cpp | 7 + .../Bluefruit52Lib/src/utility/bonding.h | 3 +- 7 files changed, 349 insertions(+), 220 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 4f544777..4a4e03f3 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -53,7 +53,19 @@ BLEGap::BLEGap(void) _cfg_central.wr_cmd_qsize = BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT; #endif - + _sec_param = (ble_gap_sec_params_t) + { + .bond = 1, + .mitm = 0, + .lesc = 0, + .keypress = 0, + .io_caps = BLE_GAP_IO_CAPS_NONE, + .oob = 0, + .min_key_size = 7, + .max_key_size = 16, + .kdist_own = { .enc = 1, .id = 1}, + .kdist_peer = { .enc = 1, .id = 1}, + }; } @@ -83,19 +95,19 @@ uint16_t BLEGap::getMaxMtuByConnCfg(uint8_t conn_cfg) return (conn_cfg == CONN_CFG_PERIPHERAL) ? _cfg_prph.mtu_max : _cfg_central.mtu_max; } -uint16_t BLEGap::getMaxMtu (uint8_t conn_handle) +uint16_t BLEGap::getMaxMtu (uint8_t conn_hdl) { - return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.mtu_max : _cfg_central.mtu_max; + return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.mtu_max : _cfg_central.mtu_max; } -uint8_t BLEGap::getHvnQueueSize (uint8_t conn_handle) +uint8_t BLEGap::getHvnQueueSize (uint8_t conn_hdl) { - return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.hvn_tx_qsize : _cfg_central.hvn_tx_qsize; + return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.hvn_tx_qsize : _cfg_central.hvn_tx_qsize; } -uint8_t BLEGap::getWriteCmdQueueSize (uint8_t conn_handle) +uint8_t BLEGap::getWriteCmdQueueSize (uint8_t conn_hdl) { - return (getRole(conn_handle) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.wr_cmd_qsize : _cfg_central.wr_cmd_qsize; + return (getRole(conn_hdl) == BLE_GAP_ROLE_PERIPH) ? _cfg_prph.wr_cmd_qsize : _cfg_central.wr_cmd_qsize; } @@ -142,52 +154,76 @@ bool BLEGap::setAddr(uint8_t mac[6], uint8_t type) return true; } -bool BLEGap::connected(uint16_t conn_handle) +bool BLEGap::connected(uint16_t conn_hdl) { - return _peers[conn_handle].connected; + return _peers[conn_hdl].connected; } -uint8_t BLEGap::getRole(uint16_t conn_handle) +bool BLEGap::bonded(uint16_t conn_hdl) { - return _peers[conn_handle].role; + return _peers[conn_hdl].bonded; } -uint8_t BLEGap::getPeerAddr(uint16_t conn_handle, uint8_t addr[6]) +bool BLEGap::requestPairing(uint16_t conn_hdl) { - memcpy(addr, _peers[conn_handle].addr.addr, BLE_GAP_ADDR_LEN); - return _peers[conn_handle].addr.addr_type; + gap_peer_t* peer = &_peers[conn_hdl]; + + // skip if already bonded + if ( peer->bonded ) return true; + + VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); + uint32_t start = millis(); + + // timeout in 30 seconds + while ( ! ((volatile bool) peer->bonded) && (start + 30000 > millis()) ) + { + yield(); + } + + return peer->bonded; } -ble_gap_addr_t BLEGap::getPeerAddr(uint16_t conn_handle) +uint8_t BLEGap::getRole(uint16_t conn_hdl) { - return _peers[conn_handle].addr; + return _peers[conn_hdl].role; } -bool BLEGap::getHvnPacket(uint16_t conn_handle) +uint8_t BLEGap::getPeerAddr(uint16_t conn_hdl, uint8_t addr[6]) { - VERIFY( (conn_handle < BLE_MAX_CONN) && (_peers[conn_handle].hvn_tx_sem != NULL) ); - - return xSemaphoreTake(_peers[conn_handle].hvn_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT)); + memcpy(addr, _peers[conn_hdl].addr.addr, BLE_GAP_ADDR_LEN); + return _peers[conn_hdl].addr.addr_type; } -bool BLEGap::getWriteCmdPacket(uint16_t conn_handle) +ble_gap_addr_t BLEGap::getPeerAddr(uint16_t conn_hdl) +{ + return _peers[conn_hdl].addr; +} + +bool BLEGap::getHvnPacket(uint16_t conn_hdl) +{ + VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].hvn_tx_sem != NULL) ); + + return xSemaphoreTake(_peers[conn_hdl].hvn_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT)); +} + +bool BLEGap::getWriteCmdPacket(uint16_t conn_hdl) { #if SD_VER < 500 - return getHvnPacket(conn_handle); + return getHvnPacket(conn_hdl); #else - VERIFY( (conn_handle < BLE_MAX_CONN) && (_peers[conn_handle].wrcmd_tx_sem != NULL) ); - return xSemaphoreTake(_peers[conn_handle].wrcmd_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT)); + VERIFY( (conn_hdl < BLE_MAX_CONN) && (_peers[conn_hdl].wrcmd_tx_sem != NULL) ); + return xSemaphoreTake(_peers[conn_hdl].wrcmd_tx_sem, ms2tick(BLE_GENERIC_TIMEOUT)); #endif } -uint16_t BLEGap::getMTU (uint16_t conn_handle) +uint16_t BLEGap::getMTU (uint16_t conn_hdl) { - return _peers[conn_handle].att_mtu; + return _peers[conn_hdl].att_mtu; } -uint16_t BLEGap::getPeerName(uint16_t conn_handle, char* buf, uint16_t bufsize) +uint16_t BLEGap::getPeerName(uint16_t conn_hdl, char* buf, uint16_t bufsize) { - return Bluefruit.Gatt.readCharByUuid(conn_handle, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize); + return Bluefruit.Gatt.readCharByUuid(conn_hdl, BLEUuid(BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME), buf, bufsize); } /** @@ -197,9 +233,9 @@ uint16_t BLEGap::getPeerName(uint16_t conn_handle, char* buf, uint16_t bufsize) void BLEGap::_eventHandler(ble_evt_t* evt) { // conn handle has fixed offset regardless of event type - const uint16_t conn_handle = evt->evt.common_evt.conn_handle; + const uint16_t conn_hdl = evt->evt.common_evt.conn_handle; - gap_peer_t* peer = &_peers[conn_handle]; + gap_peer_t* peer = (conn_hdl == BLE_CONN_HANDLE_INVALID) ? NULL : &_peers[conn_hdl]; switch(evt->header.evt_id) { @@ -215,13 +251,13 @@ void BLEGap::_eventHandler(ble_evt_t* evt) // Init transmission buffer for notification #if SD_VER < 500 uint8_t txbuf_max; - (void) sd_ble_tx_packet_count_get(conn_handle, &txbuf_max); + (void) sd_ble_tx_packet_count_get(conn_hdl, &txbuf_max); peer->hvn_tx_sem = xSemaphoreCreateCounting(txbuf_max, txbuf_max); #else - peer->hvn_tx_sem = xSemaphoreCreateCounting(getHvnQueueSize(conn_handle), getHvnQueueSize(conn_handle)); + peer->hvn_tx_sem = xSemaphoreCreateCounting(getHvnQueueSize(conn_hdl), getHvnQueueSize(conn_hdl)); #endif - peer->wrcmd_tx_sem = xSemaphoreCreateCounting(getWriteCmdQueueSize(conn_handle), getWriteCmdQueueSize(conn_handle)); + peer->wrcmd_tx_sem = xSemaphoreCreateCounting(getWriteCmdQueueSize(conn_hdl), getWriteCmdQueueSize(conn_hdl)); } break; @@ -230,7 +266,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) ble_gap_evt_disconnected_t const* para = &evt->evt.gap_evt.params.disconnected; // mark as disconnected, but keep the role for sub sequence event handler - peer->connected = false; + peer->connected = peer->bonded = false; vSemaphoreDelete( peer->hvn_tx_sem ); peer->hvn_tx_sem = NULL; @@ -241,7 +277,115 @@ void BLEGap::_eventHandler(ble_evt_t* evt) break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: + { // Pairing in progress, Peer asking for our info + peer->bond_data = (bond_data_t*) rtos_malloc( sizeof(bond_data_t)); + VERIFY(peer->bond_data, ); + + bond_data_t* bdata = peer->bond_data; + memclr(bdata, sizeof(bond_data_t)); + + peer->ediv = 0xFFFF; // invalid value for ediv + + /* Step 1: Pairing/Bonding + * - Central supplies its parameters + * - We replies with our security parameters + */ + // ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params; + COMMENT_OUT( + // Change security parameter according to authentication type + if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY) + { + sec_para.mitm = 1; + sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY; + } + ) + + ble_gap_sec_keyset_t keyset = + { + .keys_own = { + .p_enc_key = &bdata->own_enc, + .p_id_key = NULL, + .p_sign_key = NULL, + .p_pk = NULL + }, + + .keys_peer = { + .p_enc_key = &bdata->peer_enc, + .p_id_key = &bdata->peer_id, + .p_sign_key = NULL, + .p_pk = NULL + } + }; + + VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID); + } + break; + + case BLE_GAP_EVT_AUTH_STATUS: + { + // Bonding process completed + ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status; + + // Pairing/Bonding succeeded --> save encryption keys + if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) + { + peer->bonded = true; + peer->ediv = peer->bond_data->own_enc.master_id.ediv; + + bond_save_keys(conn_hdl, peer->bond_data); + }else + { + PRINT_HEX(status->auth_status); + } + + rtos_free(peer->bond_data); + peer->bond_data = NULL; + } + break; + + case BLE_GAP_EVT_SEC_INFO_REQUEST: + { + // Reconnection. If bonded previously, Central will ask for stored keys. + // return security information. Otherwise NULL + ble_gap_evt_sec_info_request_t* sec_req = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request; + + bond_data_t bdata; + varclr(&bdata); + + if ( bond_load_keys(sec_req->master_id.ediv, &bdata) ) + { + sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &bdata.own_enc.enc_info, &bdata.peer_id.id_info, NULL); + + peer->ediv = bdata.own_enc.master_id.ediv; + } else + { + sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL); + } + } + break; + + case BLE_GAP_EVT_CONN_SEC_UPDATE: + // Connection is secured aka Paired + + // Previously bonded --> secure by re-connection process + // --> Load & Set Sys Attr (Apply Service Context) + // Else Init Sys Attr + bond_load_cccd(conn_hdl, peer->ediv); + + // Paired is Bonded (as we always save keys) + peer->bonded = true; + break; + + case BLE_GAP_EVT_PASSKEY_DISPLAY: + { + // ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display; + // + // PRINT_INT(passkey_display->match_request); + // PRINT_BUFFER(passkey_display->passkey, 6); + + // sd_ble_gap_auth_key_reply + } break; #if SD_VER < 500 @@ -283,7 +427,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) param->max_tx_octets, param->max_rx_octets, param->max_tx_time_us, param->max_rx_time_us); // Let Softdevice decide the data length - VERIFY_STATUS( sd_ble_gap_data_length_update(conn_handle, NULL, NULL), ); + VERIFY_STATUS( sd_ble_gap_data_length_update(conn_hdl, NULL, NULL), ); } break; @@ -306,7 +450,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) // Tell SoftDevice to choose PHY automatically ble_gap_phys_t phy = { BLE_GAP_PHY_AUTO, BLE_GAP_PHY_AUTO }; - (void) sd_ble_gap_phy_update(conn_handle, &phy); + (void) sd_ble_gap_phy_update(conn_hdl, &phy); } break; @@ -329,8 +473,8 @@ void BLEGap::_eventHandler(ble_evt_t* evt) case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST: { - peer->att_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, getMaxMtu(conn_handle)); - VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(conn_handle, peer->att_mtu), ); + peer->att_mtu = minof(evt->evt.gatts_evt.params.exchange_mtu_request.client_rx_mtu, getMaxMtu(conn_hdl)); + VERIFY_STATUS( sd_ble_gatts_exchange_mtu_reply(conn_hdl, peer->att_mtu), ); LOG_LV1("GAP", "ATT MTU is changed to %d", peer->att_mtu); } diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index 723ccdc4..456c1c6f 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -39,6 +39,7 @@ #include #include "bluefruit_common.h" #include "BLEUuid.h" +#include "utility/bonding.h" enum { @@ -49,8 +50,8 @@ enum class BLEGap { public: - typedef void (*connect_callback_t ) (uint16_t conn_handle); - typedef void (*disconnect_callback_t ) (uint16_t conn_handle, uint8_t reason); + typedef void (*connect_callback_t ) (uint16_t conn_hdl); + typedef void (*disconnect_callback_t ) (uint16_t conn_hdl, uint8_t reason); BLEGap(void); @@ -58,29 +59,29 @@ class BLEGap bool setAddr (uint8_t mac[6], uint8_t type); // bool setPrivacy (); sd_ble_gap_privacy_set() - bool connected (uint16_t conn_handle); + bool connected (uint16_t conn_hdl); + bool bonded (uint16_t conn_hdl); + bool requestPairing (uint16_t conn_hdl); - uint8_t getRole (uint16_t conn_handle); + uint8_t getRole (uint16_t conn_hdl); - uint8_t getPeerAddr (uint16_t conn_handle, uint8_t addr[6]); - ble_gap_addr_t getPeerAddr (uint16_t conn_handle); - uint16_t getPeerName (uint16_t conn_handle, char* buf, uint16_t bufsize); + uint8_t getPeerAddr (uint16_t conn_hdl, uint8_t addr[6]); + ble_gap_addr_t getPeerAddr (uint16_t conn_hdl); + uint16_t getPeerName (uint16_t conn_hdl, char* buf, uint16_t bufsize); - uint16_t getMTU (uint16_t conn_handle); + uint16_t getMTU (uint16_t conn_hdl); uint16_t getMaxMtuByConnCfg (uint8_t conn_cfg); - uint16_t getMaxMtu (uint8_t conn_handle); + uint16_t getMaxMtu (uint8_t conn_hdl); - uint8_t getHvnQueueSize (uint8_t conn_handle); - uint8_t getWriteCmdQueueSize (uint8_t conn_handle); + uint8_t getHvnQueueSize (uint8_t conn_hdl); + uint8_t getWriteCmdQueueSize (uint8_t conn_hdl); - bool getHvnPacket (uint16_t conn_handle); - bool getWriteCmdPacket (uint16_t conn_handle); + bool getHvnPacket (uint16_t conn_hdl); + bool getWriteCmdPacket (uint16_t conn_hdl); 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); -// bool requestPairing (uint16_t conn_handle); - /*------------------------------------------------------------------*/ /* INTERNAL USAGE ONLY * Although declare as public, it is meant to be invoked by internal @@ -88,6 +89,28 @@ class BLEGap *------------------------------------------------------------------*/ void _eventHandler(ble_evt_t* evt); + // Array of TX Packet semaphore, indexed by connection handle + // Peer info where conn_hdl serves as index + typedef struct { + bool connected; + bool bonded; + uint8_t role; + uint16_t att_mtu; + + ble_gap_addr_t addr; + + uint16_t ediv; + bond_data_t* bond_data; + + SemaphoreHandle_t hvn_tx_sem; + SemaphoreHandle_t wrcmd_tx_sem; + + SemaphoreHandle_t indicate_confirm_sem; + bool hvc_received; + } gap_peer_t; + + gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; } + private: struct { uint16_t mtu_max; @@ -96,25 +119,9 @@ class BLEGap uint8_t wr_cmd_qsize; } _cfg_prph, _cfg_central; - // Array of TX Packet semaphore, indexed by connection handle - // Peer info where conn_handle serves as index - typedef struct { - bool connected; - uint8_t role; - uint16_t att_mtu; - - ble_gap_addr_t addr; - - SemaphoreHandle_t hvn_tx_sem; - SemaphoreHandle_t wrcmd_tx_sem; - - SemaphoreHandle_t indicate_confirm_sem; - bool hvc_received; - } gap_peer_t; - gap_peer_t _peers[BLE_MAX_CONN]; - gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; } + ble_gap_sec_params_t _sec_param; friend class AdafruitBluefruit; friend class BLEGatt; diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index b0f08c3d..7956b05e 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -109,7 +109,6 @@ AdafruitBluefruit::AdafruitBluefruit(void) _tx_power = 0; _conn_hdl = BLE_CONN_HANDLE_INVALID; - _bonded = false; _ppcp_min_conn = BLE_GAP_CONN_MIN_INTERVAL_DFLT; _ppcp_max_conn = BLE_GAP_CONN_MAX_INTERVAL_DFLT; @@ -125,20 +124,6 @@ COMMENT_OUT( varclr(&_bond_data); _bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv - - _sec_param = (ble_gap_sec_params_t) - { - .bond = 1, - .mitm = 0, - .lesc = 0, - .keypress = 0, - .io_caps = BLE_GAP_IO_CAPS_NONE, - .oob = 0, - .min_key_size = 7, - .max_key_size = 16, - .kdist_own = { .enc = 1, .id = 1}, - .kdist_peer = { .enc = 1, .id = 1}, - }; } void AdafruitBluefruit::configServiceChanged(bool changed) @@ -464,9 +449,8 @@ err_t AdafruitBluefruit::begin(uint8_t prph_count, uint8_t central_count) // Create Timer for led advertising blinky _led_blink_th = xTimerCreate(NULL, ms2tick(CFG_ADV_BLINKY_INTERVAL/2), true, NULL, bluefruit_blinky_cb); - // Initialize nffs for bonding (it is safe to call nffs_pkg_init() multiple time) - Nffs.begin(); - (void) Nffs.mkdir_p(CFG_BOND_NFFS_DIR); + // Initialize bonding + bond_init(); return ERROR_NONE; } @@ -597,7 +581,7 @@ uint16_t AdafruitBluefruit::connHandle(void) bool AdafruitBluefruit::connPaired(void) { - return _bonded; + return Gap.bonded(_conn_hdl); } uint16_t AdafruitBluefruit::connInterval(void) @@ -944,109 +928,94 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) LOG_LV2("GAP", "Disconnect Reason 0x%02X", evt->evt.gap_evt.params.disconnected.reason); _conn_hdl = BLE_CONN_HANDLE_INVALID; - _bonded = false; break; - case BLE_GAP_EVT_SEC_PARAMS_REQUEST: - { - // Pairing in progress - varclr(&_bond_data); - _bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv +// case BLE_GAP_EVT_SEC_PARAMS_REQUEST: +// // Pairing in progress +// varclr(&_bond_data); +// _bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv +// +// /* Step 1: Pairing/Bonding +// * - Central supplies its parameters +// * - We replies with our security parameters +// */ +// // ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params; +// COMMENT_OUT( +// // Change security parameter according to authentication type +// if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY) +// { +// sec_para.mitm = 1; +// sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY; +// } +// ) +// +// ble_gap_sec_keyset_t keyset = +// { +// .keys_own = { +// .p_enc_key = &_bond_data.own_enc, +// .p_id_key = NULL, +// .p_sign_key = NULL, +// .p_pk = NULL +// }, +// +// .keys_peer = { +// .p_enc_key = &_bond_data.peer_enc, +// .p_id_key = &_bond_data.peer_id, +// .p_sign_key = NULL, +// .p_pk = NULL +// } +// }; +// +// VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID); +// break; - /* Step 1: Pairing/Bonding - * - Central supplies its parameters - * - We replies with our security parameters - */ - // ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params; - COMMENT_OUT( - // Change security parameter according to authentication type - if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY) - { - sec_para.mitm = 1; - sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY; - } - ) +// case BLE_GAP_EVT_SEC_INFO_REQUEST: +// { +// // Reconnection. If bonded previously, Central will ask for stored keys. +// // return security information. Otherwise NULL +// ble_gap_evt_sec_info_request_t* sec_request = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request; +// +// if ( bond_load_keys(sec_request->master_id.ediv, &_bond_data) ) +// { +// sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_bond_data.own_enc.enc_info, &_bond_data.peer_id.id_info, NULL); +// } else +// { +// sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL); +// } +// } +// break; - ble_gap_sec_keyset_t keyset = - { - .keys_own = { - .p_enc_key = &_bond_data.own_enc, - .p_id_key = NULL, - .p_sign_key = NULL, - .p_pk = NULL - }, - - .keys_peer = { - .p_enc_key = &_bond_data.peer_enc, - .p_id_key = &_bond_data.peer_id, - .p_sign_key = NULL, - .p_pk = NULL - } - }; - - VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID); - } - break; - - case BLE_GAP_EVT_SEC_INFO_REQUEST: - { - // Reconnection. If bonded previously, Central will ask for stored keys. - // return security information. Otherwise NULL - ble_gap_evt_sec_info_request_t* sec_request = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request; - - if ( bond_load_keys(sec_request->master_id.ediv, &_bond_data) ) - { - sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_bond_data.own_enc.enc_info, &_bond_data.peer_id.id_info, NULL); - } else - { - sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL); - } - } - break; - - - case BLE_GAP_EVT_PASSKEY_DISPLAY: - { - // ble_gap_evt_passkey_display_t const* passkey_display = &evt->evt.gap_evt.params.passkey_display; - // - // PRINT_INT(passkey_display->match_request); - // PRINT_BUFFER(passkey_display->passkey, 6); - - // sd_ble_gap_auth_key_reply - } - break; - - case BLE_GAP_EVT_CONN_SEC_UPDATE: - { - // Connection is secured aka Paired - COMMENT_OUT( ble_gap_conn_sec_t* conn_sec = (ble_gap_conn_sec_t*) &evt->evt.gap_evt.params.conn_sec_update.conn_sec; ) - - // Previously bonded --> secure by re-connection process - // --> Load & Set Sys Attr (Apply Service Context) - // Else Init Sys Attr - bond_load_cccd(evt_conn_hdl, _bond_data.own_enc.master_id.ediv); - - // Consider Paired as Bonded - _bonded = true; - } - break; - - case BLE_GAP_EVT_AUTH_STATUS: - { - // Bonding process completed - ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status; - - // Pairing/Bonding succeeded --> save encryption keys - if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) - { - _bonded = true; - bond_save_keys(evt_conn_hdl, &_bond_data); - }else - { - PRINT_HEX(status->auth_status); - } - } - break; +// case BLE_GAP_EVT_CONN_SEC_UPDATE: +// { +// // Connection is secured aka Paired +// COMMENT_OUT( ble_gap_conn_sec_t* conn_sec = (ble_gap_conn_sec_t*) &evt->evt.gap_evt.params.conn_sec_update.conn_sec; ) +// +// // Previously bonded --> secure by re-connection process +// // --> Load & Set Sys Attr (Apply Service Context) +// // Else Init Sys Attr +// bond_load_cccd(evt_conn_hdl, _bond_data.own_enc.master_id.ediv); +// +// // Consider Paired as Bonded +// _bonded = true; +// } +// break; +// +// case BLE_GAP_EVT_AUTH_STATUS: +// { +// // Bonding process completed +// ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status; +// +// // Pairing/Bonding succeeded --> save encryption keys +// if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) +// { +// _bonded = true; +// bond_save_keys(evt_conn_hdl, &_bond_data); +// }else +// { +// PRINT_HEX(status->auth_status); +// } +// } +// break; case BLE_GATTS_EVT_SYS_ATTR_MISSING: sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); @@ -1100,19 +1069,7 @@ void AdafruitBluefruit::_setConnLed (bool on_off) *------------------------------------------------------------------*/ bool AdafruitBluefruit::requestPairing(void) { - // skip if already bonded - if (_bonded) return true; - - VERIFY_STATUS( sd_ble_gap_authenticate(_conn_hdl, &_sec_param ), false); - uint32_t start = millis(); - - // timeout in 30 seconds - while ( !_bonded && (start + 30000 > millis()) ) - { - yield(); - } - - return _bonded; + return Gap.requestPairing(_conn_hdl); } void AdafruitBluefruit::clearBonds(void) @@ -1122,14 +1079,18 @@ void AdafruitBluefruit::clearBonds(void) void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key) { - if (!_bonded) - { - (*addr) = getPeerAddr(); - }else - { - (*addr) = _bond_data.peer_id.id_addr_info; - (*irk) = _bond_data.peer_id.id_info; + (*addr) = getPeerAddr(); - (*enc_key) = _bond_data.own_enc; + if ( connPaired() ) + { + bond_data_t bdata; + + if ( bond_load_keys( Gap._get_peer(_conn_hdl)->ediv, &bdata ) ) + { + (*addr) = _bond_data.peer_id.id_addr_info; + (*irk) = _bond_data.peer_id.id_info; + + (*enc_key) = _bond_data.own_enc; + } } } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 89cc757d..2414bc49 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -89,8 +89,6 @@ #include "clients/BLEClientHidAdafruit.h" #include "utility/AdaCallback.h" - - #include "utility/bonding.h" enum @@ -228,13 +226,10 @@ class AdafruitBluefruit BLEDfu _dfu_svc; uint16_t _conn_hdl; - bool _bonded; BLEGap::connect_callback_t _connect_cb; BLEGap::disconnect_callback_t _disconnect_cb; - ble_gap_sec_params_t _sec_param; - COMMENT_OUT( uint8_t _auth_type; char _pin[BLE_GAP_PASSKEY_LEN]; diff --git a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp index 92ae8ecd..4849b036 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp @@ -92,17 +92,19 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt (request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_NOW) && (request->op != BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL)) { + uint16_t conn_hdl = Bluefruit.connHandle(); + ble_gatts_rw_authorize_reply_params_t reply = { .type = BLE_GATTS_AUTHORIZE_TYPE_WRITE }; if ( !chr.notifyEnabled() ) { reply.params.write.gatt_status = BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR; - sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply); + sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply); return; } reply.params.write.gatt_status = BLE_GATT_STATUS_SUCCESS; - sd_ble_gatts_rw_authorize_reply(Bluefruit.connHandle(), &reply); + sd_ble_gatts_rw_authorize_reply(conn_hdl, &reply); enum { START_DFU = 1 }; if ( request->data[0] == START_DFU ) @@ -128,10 +130,22 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt // Get CCCD uint16_t sysattr_len = sizeof(peer_data->sys_attr); - sd_ble_gatts_sys_attr_get(Bluefruit.connHandle(), peer_data->sys_attr, &sysattr_len, BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS); + sd_ble_gatts_sys_attr_get(conn_hdl, peer_data->sys_attr, &sysattr_len, BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS); - // Get Bond Data - Bluefruit._bledfu_get_bond_data(&peer_data->addr, &peer_data->irk, &peer_data->enc_key); + // Get Bond Data or using Address if not bonded + peer_data->addr = Bluefruit.Gap.getPeerAddr(conn_hdl); + + if ( Bluefruit.Gap.bonded(conn_hdl) ) + { + bond_data_t bdata; + + if ( bond_load_keys( Bluefruit.Gap._get_peer(conn_hdl)->ediv, &bdata ) ) + { + peer_data->addr = bdata.peer_id.id_addr_info; + peer_data->irk = bdata.peer_id.id_info; + peer_data->enc_key = bdata.own_enc; + } + } // Calculate crc peer_data->crc16 = crc16((uint8_t*) peer_data, offsetof(peer_data_t, crc16)); diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 96f83af3..5f5c02b7 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -54,6 +54,13 @@ * - CCCD variable *------------------------------------------------------------------*/ +void bond_init(void) +{ + // Initialize nffs for bonding (it is safe to call nffs_pkg_init() multiple time) + Nffs.begin(); + (void) Nffs.mkdir_p(CFG_BOND_NFFS_DIR); +} + /*------------------------------------------------------------------*/ /* Keys *------------------------------------------------------------------*/ diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h index 67731d8b..4d9b3dd7 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.h +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -56,6 +56,8 @@ enum BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN }; +void bond_init(void); +void bond_clear(void); void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata); bool bond_load_keys(uint16_t ediv, bond_data_t* bdata); @@ -63,7 +65,6 @@ bool bond_load_keys(uint16_t ediv, bond_data_t* bdata); void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv); bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv); -void bond_clear(void); #endif /* BONDING_H_ */ From 0e74a76c0a961c19d76702dd4b757b29138eca63 Mon Sep 17 00:00:00 2001 From: hathach Date: Thu, 22 Feb 2018 23:47:41 +0700 Subject: [PATCH 23/39] more clean up --- libraries/Bluefruit52Lib/src/BLEGap.h | 2 +- libraries/Bluefruit52Lib/src/BLEGatt.cpp | 2 +- libraries/Bluefruit52Lib/src/bluefruit.cpp | 107 --------------------- libraries/Bluefruit52Lib/src/bluefruit.h | 4 - 4 files changed, 2 insertions(+), 113 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index 456c1c6f..37f7d82b 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -100,7 +100,7 @@ class BLEGap ble_gap_addr_t addr; uint16_t ediv; - bond_data_t* bond_data; + bond_data_t* bond_data; // Shared keys with bonded device, size ~ 80 bytes SemaphoreHandle_t hvn_tx_sem; SemaphoreHandle_t wrcmd_tx_sem; diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index 61695f19..69dcfef6 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -146,7 +146,7 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) // Save CCCD if paired if ( Bluefruit.connPaired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) ) { - bond_save_cccd(evt_conn_hdl, Bluefruit._bond_data.own_enc.master_id.ediv); + bond_save_cccd(evt_conn_hdl, Bluefruit.Gap._get_peer(evt_conn_hdl)->ediv); } } } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 7956b05e..0f67e1d5 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -121,9 +121,6 @@ COMMENT_OUT( _auth_type = BLE_GAP_AUTH_KEY_TYPE_NONE; varclr(_pin); ) - - varclr(&_bond_data); - _bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv } void AdafruitBluefruit::configServiceChanged(bool changed) @@ -930,93 +927,6 @@ void AdafruitBluefruit::_ble_handler(ble_evt_t* evt) _conn_hdl = BLE_CONN_HANDLE_INVALID; break; -// case BLE_GAP_EVT_SEC_PARAMS_REQUEST: -// // Pairing in progress -// varclr(&_bond_data); -// _bond_data.own_enc.master_id.ediv = 0xFFFF; // invalid value for ediv -// -// /* Step 1: Pairing/Bonding -// * - Central supplies its parameters -// * - We replies with our security parameters -// */ -// // ble_gap_sec_params_t* peer = &evt->evt.gap_evt.params.sec_params_request.peer_params; -// COMMENT_OUT( -// // Change security parameter according to authentication type -// if ( _auth_type == BLE_GAP_AUTH_KEY_TYPE_PASSKEY) -// { -// sec_para.mitm = 1; -// sec_para.io_caps = BLE_GAP_IO_CAPS_DISPLAY_ONLY; -// } -// ) -// -// ble_gap_sec_keyset_t keyset = -// { -// .keys_own = { -// .p_enc_key = &_bond_data.own_enc, -// .p_id_key = NULL, -// .p_sign_key = NULL, -// .p_pk = NULL -// }, -// -// .keys_peer = { -// .p_enc_key = &_bond_data.peer_enc, -// .p_id_key = &_bond_data.peer_id, -// .p_sign_key = NULL, -// .p_pk = NULL -// } -// }; -// -// VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID); -// break; - -// case BLE_GAP_EVT_SEC_INFO_REQUEST: -// { -// // Reconnection. If bonded previously, Central will ask for stored keys. -// // return security information. Otherwise NULL -// ble_gap_evt_sec_info_request_t* sec_request = (ble_gap_evt_sec_info_request_t*) &evt->evt.gap_evt.params.sec_info_request; -// -// if ( bond_load_keys(sec_request->master_id.ediv, &_bond_data) ) -// { -// sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &_bond_data.own_enc.enc_info, &_bond_data.peer_id.id_info, NULL); -// } else -// { -// sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, NULL, NULL, NULL); -// } -// } -// break; - -// case BLE_GAP_EVT_CONN_SEC_UPDATE: -// { -// // Connection is secured aka Paired -// COMMENT_OUT( ble_gap_conn_sec_t* conn_sec = (ble_gap_conn_sec_t*) &evt->evt.gap_evt.params.conn_sec_update.conn_sec; ) -// -// // Previously bonded --> secure by re-connection process -// // --> Load & Set Sys Attr (Apply Service Context) -// // Else Init Sys Attr -// bond_load_cccd(evt_conn_hdl, _bond_data.own_enc.master_id.ediv); -// -// // Consider Paired as Bonded -// _bonded = true; -// } -// break; -// -// case BLE_GAP_EVT_AUTH_STATUS: -// { -// // Bonding process completed -// ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status; -// -// // Pairing/Bonding succeeded --> save encryption keys -// if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) -// { -// _bonded = true; -// bond_save_keys(evt_conn_hdl, &_bond_data); -// }else -// { -// PRINT_HEX(status->auth_status); -// } -// } -// break; - case BLE_GATTS_EVT_SYS_ATTR_MISSING: sd_ble_gatts_sys_attr_set(_conn_hdl, NULL, 0, 0); break; @@ -1077,20 +987,3 @@ void AdafruitBluefruit::clearBonds(void) bond_clear(); } -void AdafruitBluefruit::_bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key) -{ - (*addr) = getPeerAddr(); - - if ( connPaired() ) - { - bond_data_t bdata; - - if ( bond_load_keys( Gap._get_peer(_conn_hdl)->ediv, &bdata ) ) - { - (*addr) = _bond_data.peer_id.id_addr_info; - (*irk) = _bond_data.peer_id.id_info; - - (*enc_key) = _bond_data.own_enc; - } - } -} diff --git a/libraries/Bluefruit52Lib/src/bluefruit.h b/libraries/Bluefruit52Lib/src/bluefruit.h index 2414bc49..3a697792 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.h +++ b/libraries/Bluefruit52Lib/src/bluefruit.h @@ -192,10 +192,6 @@ class AdafruitBluefruit void _startConnLed (void); void _stopConnLed (void); void _setConnLed (bool on_off); - void _bledfu_get_bond_data(ble_gap_addr_t* addr, ble_gap_irk_t* irk, ble_gap_enc_key_t* enc_key); - - // Shared keys with bonded device, size = 80 bytes - bond_data_t _bond_data; private: /*------------- SoftDevice Configuration -------------*/ From e1c78409c26bb8a16784349ec4db47ec34b37c22 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 14:45:10 +0700 Subject: [PATCH 24/39] correct parameter for pairing in central role --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 4a4e03f3..24d3d87a 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -318,7 +318,11 @@ void BLEGap::_eventHandler(ble_evt_t* evt) } }; - VERIFY_STATUS(sd_ble_gap_sec_params_reply(evt->evt.gap_evt.conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, &_sec_param, &keyset), RETURN_VOID); + VERIFY_STATUS(sd_ble_gap_sec_params_reply(conn_hdl, + BLE_GAP_SEC_STATUS_SUCCESS, + peer->role == BLE_GAP_ROLE_PERIPH ? &_sec_param : NULL, + &keyset), + ); } break; From 7cead7272652874f5fe34eb2d74d1b135b60a772 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 15:01:30 +0700 Subject: [PATCH 25/39] enhance hid service --- .../src/services/BLEHidAdafruit.cpp | 3 ++- .../src/services/BLEHidGeneric.cpp | 19 ++++++++++++------- .../src/services/BLEHidGeneric.h | 8 +++++--- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp index fe38635f..c6268349 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp @@ -205,7 +205,8 @@ err_t BLEHidAdafruit::begin(void) uint16_t output_len[] = { 1 }; setReportLen(input_len, output_len, NULL); - enableBootProtocol(true, true); + enableKeyboard(true); + enableMouse(true); setReportMap(hid_report_descriptor, sizeof(hid_report_descriptor)); VERIFY_STATUS( BLEHidGeneric::begin() ); diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp index e3301249..267956a8 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp @@ -45,7 +45,7 @@ enum { BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_feature) : BLEService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _chr_control(UUID16_CHR_HID_CONTROL_POINT) { - _boot_keyboard = _boot_mouse = false; + _has_keyboard = _has_mouse = false; _report_map = NULL; _report_map_len = 0; @@ -88,12 +88,17 @@ BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_ } } -void BLEHidGeneric::enableBootProtocol(bool bootKeyboard, bool bootMouse) +void BLEHidGeneric::enableKeyboard(bool enable) { - _boot_keyboard = bootKeyboard; - _boot_mouse = bootMouse; + _has_keyboard = enable; } +void BLEHidGeneric::enableMouse(bool enable) +{ + _has_mouse = enable; +} + + void BLEHidGeneric::setHidInfo(uint16_t bcd, uint8_t country, uint8_t flags) { memcpy(_hid_info, &bcd, 2); @@ -137,7 +142,7 @@ err_t BLEHidGeneric::begin(void) VERIFY_STATUS( BLEService::begin() ); // Protocol Mode - if ( _boot_keyboard || _boot_mouse ) + if ( _has_keyboard || _has_mouse ) { _chr_protocol = new BLECharacteristic(UUID16_CHR_PROTOCOL_MODE); VERIFY(_chr_protocol, NRF_ERROR_NO_MEM); @@ -192,7 +197,7 @@ err_t BLEHidGeneric::begin(void) report_map.write(_report_map, _report_map_len); // Boot Keyboard Input & Output Report - if ( _boot_keyboard ) + if ( _has_keyboard ) { _chr_boot_keyboard_input = new BLECharacteristic(UUID16_CHR_BOOT_KEYBOARD_INPUT_REPORT); _chr_boot_keyboard_input->setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY); @@ -209,7 +214,7 @@ err_t BLEHidGeneric::begin(void) } // Boot Mouse Input Report - if ( _boot_mouse ) + if ( _has_mouse ) { _chr_boot_mouse_input = new BLECharacteristic(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT); _chr_boot_mouse_input->setProperties(CHR_PROPS_READ | CHR_PROPS_NOTIFY); diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h index 8a4fdd11..66773e17 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h @@ -91,7 +91,9 @@ class BLEHidGeneric : public BLEService BLEHidGeneric(uint8_t num_input, uint8_t num_output = 0, uint8_t num_feature = 0); - void enableBootProtocol(bool bootKeyboard, bool bootMouse); + void enableKeyboard(bool enable); + void enableMouse(bool enable); + void setHidInfo(uint16_t bcd, uint8_t country, uint8_t flags); void setReportLen(uint16_t input_len[], uint16_t output_len[] = NULL, uint16_t feature_len[] = NULL); @@ -108,8 +110,8 @@ class BLEHidGeneric : public BLEService uint8_t _num_output; uint8_t _num_feature; - bool _boot_keyboard; - bool _boot_mouse; + bool _has_keyboard; + bool _has_mouse; uint8_t _hid_info[4]; const uint8_t* _report_map; From 049a0afc5c27094684f5ec49f21fa5890df2833f Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 15:48:03 +0700 Subject: [PATCH 26/39] enhance blehid generic to support protocol boot mode --- .../src/services/BLEHidAdafruit.cpp | 16 +++++++- .../src/services/BLEHidGeneric.cpp | 37 ++++++++++++++++++- .../src/services/BLEHidGeneric.h | 12 +++++- 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp index c6268349..99a76a85 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidAdafruit.cpp @@ -222,7 +222,13 @@ err_t BLEHidAdafruit::begin(void) *------------------------------------------------------------------*/ bool BLEHidAdafruit::keyboardReport(hid_keyboard_report_t* report) { - return inputReport( REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t)); + if ( isBootMode() ) + { + return bootKeyboardReport(report, sizeof(hid_keyboard_report_t)); + }else + { + return inputReport( REPORT_ID_KEYBOARD, report, sizeof(hid_keyboard_report_t)); + } } bool BLEHidAdafruit::keyboardReport(uint8_t modifier, uint8_t keycode[6]) @@ -314,7 +320,13 @@ bool BLEHidAdafruit::consumerKeyRelease(void) *------------------------------------------------------------------*/ bool BLEHidAdafruit::mouseReport(hid_mouse_report_t* report) { - return inputReport( REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t)); + if ( isBootMode() ) + { + return bootMouseReport(report, sizeof(hid_mouse_report_t)); + }else + { + return inputReport( REPORT_ID_MOUSE, report, sizeof(hid_mouse_report_t)); + } } bool BLEHidAdafruit::mouseReport(uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan) diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp index 267956a8..bff7cf8d 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp @@ -46,6 +46,8 @@ BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_ : BLEService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _chr_control(UUID16_CHR_HID_CONTROL_POINT) { _has_keyboard = _has_mouse = false; + _protocol_mode = 1; // report mode + _report_map = NULL; _report_map_len = 0; @@ -88,6 +90,9 @@ BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_ } } +/*------------------------------------------------------------------*/ +/* CONFIG + *------------------------------------------------------------------*/ void BLEHidGeneric::enableKeyboard(bool enable) { _has_keyboard = enable; @@ -98,7 +103,6 @@ void BLEHidGeneric::enableMouse(bool enable) _has_mouse = enable; } - void BLEHidGeneric::setHidInfo(uint16_t bcd, uint8_t country, uint8_t flags) { memcpy(_hid_info, &bcd, 2); @@ -124,6 +128,10 @@ void BLEHidGeneric::setOutputReportCallback(uint8_t reportID, output_report_cb_t _output_cbs[reportID] = fp; } +/*------------------------------------------------------------------*/ +/* Callbacks + *------------------------------------------------------------------*/ +// TODO output report COMMENT_OUT ( void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request) { @@ -134,6 +142,17 @@ void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* requ } ) +void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset) +{ + BLEHidGeneric& svc = (BLEHidGeneric&) chr.parentService(); + svc._protocol_mode = *data; + + LOG_LV2("HID", "Protocol Mode : %d (0 Boot, 1 Report)", *data); +} + +/*------------------------------------------------------------------*/ +/* Begin + *------------------------------------------------------------------*/ err_t BLEHidGeneric::begin(void) { VERIFY ( (_report_map != NULL) && _report_map_len, NRF_ERROR_INVALID_PARAM); @@ -149,8 +168,9 @@ err_t BLEHidGeneric::begin(void) _chr_protocol->setProperties(CHR_PROPS_READ | CHR_PROPS_WRITE_WO_RESP); _chr_protocol->setFixedLen(1); + _chr_protocol->setWriteCallback(blehid_generic_protocol_mode_cb); VERIFY_STATUS( _chr_protocol->begin() ); - _chr_protocol->write8(1); + _chr_protocol->write8(_protocol_mode); } // Input reports @@ -242,6 +262,9 @@ err_t BLEHidGeneric::begin(void) return ERROR_NONE; } +/*------------------------------------------------------------------*/ +/* Input Report + *------------------------------------------------------------------*/ bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len) { // 0 will treated as report ID = 1 @@ -250,6 +273,16 @@ bool BLEHidGeneric::inputReport(uint8_t reportID, void const* data, int len) return _chr_inputs[reportID-1].notify( (uint8_t const*) data, len); } +bool BLEHidGeneric::bootKeyboardReport(void const* data, int len) +{ + return _chr_boot_keyboard_input->notify(data, len); +} + +bool BLEHidGeneric::bootMouseReport(void const* data, int len) +{ + return _chr_boot_mouse_input->notify(data, len); +} + /*------------------------------------------------------------------*/ /* *------------------------------------------------------------------*/ diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h index 66773e17..0c899c0b 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h @@ -103,15 +103,21 @@ class BLEHidGeneric : public BLEService virtual err_t begin(void); + bool isBootMode(void) { return _protocol_mode == 0; } + + // Report bool inputReport(uint8_t reportID, void const* data, int len); + bool bootKeyboardReport(void const* data, int len); + bool bootMouseReport(void const* data, int len); protected: uint8_t _num_input; uint8_t _num_output; uint8_t _num_feature; - bool _has_keyboard; - bool _has_mouse; + bool _has_keyboard; + bool _has_mouse; + bool _protocol_mode; // 0 boot, 1 report (default) uint8_t _hid_info[4]; const uint8_t* _report_map; @@ -135,6 +141,8 @@ class BLEHidGeneric : public BLEService BLECharacteristic _chr_control; + friend void blehid_generic_protocol_mode_cb(BLECharacteristic& chr, uint8_t* data, uint16_t len, uint16_t offset); + COMMENT_OUT ( friend void blehidgeneric_output_cb(BLECharacteristic& chr, ble_gatts_evt_write_t* request); ) From 1fd9cbedc5855e80edc6ee27dc49cf279ecfd265 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 18:53:18 +0700 Subject: [PATCH 27/39] add HID_KEYCODE_TO_ASCII decode --- .../src/services/BLEHidGeneric.cpp | 113 +++++++++++++++++- .../src/services/BLEHidGeneric.h | 16 ++- 2 files changed, 125 insertions(+), 4 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp index bff7cf8d..90e8631c 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.cpp @@ -46,7 +46,7 @@ BLEHidGeneric::BLEHidGeneric(uint8_t num_input, uint8_t num_output, uint8_t num_ : BLEService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _chr_control(UUID16_CHR_HID_CONTROL_POINT) { _has_keyboard = _has_mouse = false; - _protocol_mode = 1; // report mode + _protocol_mode = HID_PROTOCOL_MODE_REPORT; _report_map = NULL; _report_map_len = 0; @@ -284,7 +284,7 @@ bool BLEHidGeneric::bootMouseReport(void const* data, int len) } /*------------------------------------------------------------------*/ -/* +/* Ascii to Keycode *------------------------------------------------------------------*/ const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] = { @@ -421,3 +421,112 @@ const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128] = {0, HID_KEY_DELETE } // 0x7F Delete }; +/*------------------------------------------------------------------*/ +/* Keycode to Ascii + *------------------------------------------------------------------*/ +const hid_keycode_to_ascii_t HID_KEYCODE_TO_ASCII[128] = +{ + {0 , 0 }, // 0x00 + {0 , 0 }, // 0x01 + {0 , 0 }, // 0x02 + {0 , 0 }, // 0x03 + {'a' , 'A' }, // 0x04 + {'b' , 'B' }, // 0x05 + {'c' , 'C' }, // 0x06 + {'d' , 'D' }, // 0x07 + {'e' , 'E' }, // 0x08 + {'f' , 'F' }, // 0x09 + {'g' , 'G' }, // 0x0a + {'h' , 'H' }, // 0x0b + {'i' , 'I' }, // 0x0c + {'j' , 'J' }, // 0x0d + {'k' , 'K' }, // 0x0e + {'l' , 'L' }, // 0x0f + {'m' , 'M' }, // 0x10 + {'n' , 'N' }, // 0x11 + {'o' , 'O' }, // 0x12 + {'p' , 'P' }, // 0x13 + {'q' , 'Q' }, // 0x14 + {'r' , 'R' }, // 0x15 + {'s' , 'S' }, // 0x16 + {'t' , 'T' }, // 0x17 + {'u' , 'U' }, // 0x18 + {'v' , 'V' }, // 0x19 + {'w' , 'W' }, // 0x1a + {'x' , 'X' }, // 0x1b + {'y' , 'Y' }, // 0x1c + {'z' , 'Z' }, // 0x1d + {'1' , '!' }, // 0x1e + {'2' , '@' }, // 0x1f + {'3' , '#' }, // 0x20 + {'4' , '$' }, // 0x21 + {'5' , '%' }, // 0x22 + {'6' , '^' }, // 0x23 + {'7' , '&' }, // 0x24 + {'8' , '*' }, // 0x25 + {'9' , '(' }, // 0x26 + {'0' , ')' }, // 0x27 + {'\r' , '\r' }, // 0x28 + {'\x1b', '\x1b' }, // 0x29 + {'\b' , '\b' }, // 0x2a + {'\t' , '\t' }, // 0x2b + {' ' , ' ' }, // 0x2c + {'-' , '_' }, // 0x2d + {'=' , '+' }, // 0x2e + {'[' , '{' }, // 0x2f + {']' , '}' }, // 0x30 + {'\\' , '|' }, // 0x31 + {'#' , '~' }, // 0x32 + {';' , ':' }, // 0x33 + {'\'' , '\"' }, // 0x34 + {0 , 0 }, // 0x35 + {',' , '<' }, // 0x36 + {'.' , '>' }, // 0x37 + {'/' , '?' }, // 0x38 + + {0 , 0 }, // 0x39 + {0 , 0 }, // 0x3a + {0 , 0 }, // 0x3b + {0 , 0 }, // 0x3c + {0 , 0 }, // 0x3d + {0 , 0 }, // 0x3e + {0 , 0 }, // 0x3f + {0 , 0 }, // 0x40 + {0 , 0 }, // 0x41 + {0 , 0 }, // 0x42 + {0 , 0 }, // 0x43 + {0 , 0 }, // 0x44 + {0 , 0 }, // 0x45 + {0 , 0 }, // 0x46 + {0 , 0 }, // 0x47 + {0 , 0 }, // 0x48 + {0 , 0 }, // 0x49 + {0 , 0 }, // 0x4a + {0 , 0 }, // 0x4b + {0 , 0 }, // 0x4c + {0 , 0 }, // 0x4d + {0 , 0 }, // 0x4e + {0 , 0 }, // 0x4f + {0 , 0 }, // 0x50 + {0 , 0 }, // 0x51 + {0 , 0 }, // 0x52 + {0 , 0 }, // 0x53 + + {'/' , '/' }, // 0x54 + {'*' , '*' }, // 0x55 + {'-' , '-' }, // 0x56 + {'+' , '+' }, // 0x57 + {'\r' , '\r' }, // 0x58 + {'1' , 0 }, // 0x59 /* numpad1 & end */ \ + {'2' , 0 }, // 0x5a + {'3' , 0 }, // 0x5b + {'4' , 0 }, // 0x5c + {'5' , '5' }, // 0x5d + {'6' , 0 }, // 0x5e + {'7' , 0 }, // 0x5f + {'8' , 0 }, // 0x60 + {'9' , 0 }, // 0x61 + {'0' , 0 }, // 0x62 + {'0' , 0 }, // 0x63 + {'=' , '=' }, // 0x67 +}; diff --git a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h index 0c899c0b..22e15390 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h +++ b/libraries/Bluefruit52Lib/src/services/BLEHidGeneric.h @@ -41,12 +41,24 @@ #include "BLECharacteristic.h" #include "BLEService.h" +enum +{ + HID_PROTOCOL_MODE_BOOT = 0, + HID_PROTOCOL_MODE_REPORT = 1 +}; + typedef struct{ uint8_t shift; uint8_t keycode; }hid_ascii_to_keycode_entry_t; extern const hid_ascii_to_keycode_entry_t HID_ASCII_TO_KEYCODE[128]; +typedef struct{ + uint8_t ascii; + uint8_t shifted; +}hid_keycode_to_ascii_t; +extern hid_keycode_to_ascii_t const HID_KEYCODE_TO_ASCII[128]; + /// Standard HID Boot Protocol Mouse Report. typedef ATTR_PACKED_STRUCT(struct) { @@ -103,7 +115,7 @@ class BLEHidGeneric : public BLEService virtual err_t begin(void); - bool isBootMode(void) { return _protocol_mode == 0; } + bool isBootMode(void) { return _protocol_mode == HID_PROTOCOL_MODE_BOOT; } // Report bool inputReport(uint8_t reportID, void const* data, int len); @@ -117,7 +129,7 @@ class BLEHidGeneric : public BLEService bool _has_keyboard; bool _has_mouse; - bool _protocol_mode; // 0 boot, 1 report (default) + bool _protocol_mode; uint8_t _hid_info[4]; const uint8_t* _report_map; From f16576b70c1fd190c5885cdbbc44c8684856e928 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 18:53:57 +0700 Subject: [PATCH 28/39] central keyboard work with polling method - central bonding still needs some more work for reconnection. --- .../Central/central_hid/central_hid.ino | 111 ++++++++++++++---- libraries/Bluefruit52Lib/keywords.txt | 29 +++++ .../src/clients/BLEClientHidAdafruit.cpp | 101 +++++++++++++--- .../src/clients/BLEClientHidAdafruit.h | 36 ++++-- 4 files changed, 228 insertions(+), 49 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino index 23fe9427..787bb787 100644 --- a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino +++ b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino @@ -18,14 +18,23 @@ */ #include +// Polling or callback implementation +#define POLLING 1 + BLEClientHidAdafruit hid; +// Last checked report, to detect if we receive a new one with polling method +hid_keyboard_report_t last_kbd_report = { 0 }; +hid_mouse_report_t last_mse_report = { 0 }; + void setup() { Serial.begin(115200); Serial.println("Bluefruit52 Central HID (Keyboard + Mouse) Example"); Serial.println("--------------------------------------------------\n"); + + Bluefruit.configCentralConn(23, 3, 1, 3); // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1 // SRAM usage required by SoftDevice will increase dramatically with number of connections @@ -83,6 +92,13 @@ void connect_callback(uint16_t conn_handle) { Serial.println("Found it"); + // HID device mostly require pairing/bonding + if ( !Bluefruit.Gap.requestPairing(conn_handle) ) + { + Serial.print("Failed to paired"); + return; + } + // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.hid_information.xml uint8_t hidInfo[4]; hid.getHidInfo(hidInfo); @@ -90,11 +106,17 @@ void connect_callback(uint16_t conn_handle) Serial.printf("HID version: %d.%d\n", hidInfo[0], hidInfo[1]); Serial.print("Country code: "); Serial.println(hidInfo[2]); Serial.printf("HID Flags : 0x%02X\n", hidInfo[3]); + + // BLEClientHidAdafruit currently only suports Boot Protocol Mode + // for Keyboard and Mouse. Let's set the protocol mode on prph to Boot Mode + hid.setProtocolMode(HID_PROTOCOL_MODE_BOOT); + + // Enable Keyboard report notification if present on prph + if ( hid.keyboardPresent() ) hid.enableKeyboard(); + + // Enable Mouse report notification if present on prph + if ( hid.mousePresent() ) hid.enableMouse(); - -// Serial.println("Enable TXD's notify"); -// clientUart.enableTXD(); - Serial.println("Ready to receive from peripheral"); }else { @@ -118,27 +140,72 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) Serial.println("Disconnected"); } -/** - * Callback invoked when uart received data - * @param uart_svc Reference object to the service where the data - * arrived. In this example it is clientUart - */ -//void bleuart_rx_callback(BLEClientUart& uart_svc) -//{ -// Serial.print("[RX]: "); -// -// while ( uart_svc.available() ) -// { -// Serial.print( (char) uart_svc.read() ); -// } -// -// Serial.println(); -//} - void loop() { - // nothing to do + +#if POLLING + // nothing to do if hid not discovered if ( !hid.discovered() ) return; + + /*------------- Polling Keyboard -------------*/ + hid_keyboard_report_t kbd_report; + // Get latest report + hid.getKeyboardReport(&kbd_report); + + // Check with last report to see if there is new arrival report + if ( memcmp(&last_kbd_report, &kbd_report, sizeof(kbd_report)) ) + { + bool shifted = false; + + if ( kbd_report.modifier ) + { + if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTCTRL | KEYBOARD_MODIFIER_RIGHTCTRL) ) + { + Serial.print("Ctrl "); + } + + if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT) ) + { + Serial.print("Shift "); + + shifted = true; + } + + if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTALT | KEYBOARD_MODIFIER_RIGHTALT) ) + { + Serial.print("Alt "); + } + } + + for(uint8_t i=0; i<6; i++) + { + uint8_t kc = kbd_report.keycode[i]; + char ch = 0; + + if ( kc < 128 ) + { + ch = shifted ? HID_KEYCODE_TO_ASCII[kc].shifted : HID_KEYCODE_TO_ASCII[kc].ascii; + }else + { + // non-US keyboard !!?? + } + + // Printable + if (ch) + { + Serial.print(ch); + } + } + } + + // update last report + memcpy(&last_kbd_report, &kbd_report, sizeof(kbd_report)); + + + // polling interval is 5 ms + delay(5); +#endif + } diff --git a/libraries/Bluefruit52Lib/keywords.txt b/libraries/Bluefruit52Lib/keywords.txt index 41a56755..ad1cd907 100644 --- a/libraries/Bluefruit52Lib/keywords.txt +++ b/libraries/Bluefruit52Lib/keywords.txt @@ -470,6 +470,35 @@ SECMODE_ENC_WITH_MITM LITERAL1 SECMODE_SIGNED_NO_MITM LITERAL1 SECMODE_SIGNED_WITH_MITM LITERAL1 +####################################### +# HID Constants +####################################### + +HID_PROTOCOL_MODE_BOOT LITERAL1 +HID_PROTOCOL_MODE_REPORT LITERAL1 + +MOUSE_BUTTON_LEFT LITERAL1 +MOUSE_BUTTON_RIGHT LITERAL1 +MOUSE_BUTTON_MIDDLE LITERAL1 +MOUSE_BUTTON_BACKWARD LITERAL1 +MOUSE_BUTTON_FORWARD LITERAL1 + +KEYBOARD_MODIFIER_LEFTCTRL LITERAL1 +KEYBOARD_MODIFIER_LEFTSHIFT LITERAL1 +KEYBOARD_MODIFIER_LEFTALT LITERAL1 +KEYBOARD_MODIFIER_LEFTGUI LITERAL1 +KEYBOARD_MODIFIER_RIGHTCTRL LITERAL1 +KEYBOARD_MODIFIER_RIGHTSHIFT LITERAL1 +KEYBOARD_MODIFIER_RIGHTALT LITERAL1 +KEYBOARD_MODIFIER_RIGHTGUI LITERAL1 + +KEYBOARD_LED_NUMLOCK LITERAL1 +KEYBOARD_LED_CAPSLOCK LITERAL1 +KEYBOARD_LED_SCROLLLOCK LITERAL1 +KEYBOARD_LED_COMPOSE LITERAL1 +KEYBOARD_LED_KANA LITERAL1 + + ####################################### # ANCS Constants ####################################### diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp index cd28bf90..f9293ee8 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.cpp @@ -40,11 +40,29 @@ BLEClientHidAdafruit::BLEClientHidAdafruit(void) : BLEClientService(UUID16_SVC_HUMAN_INTERFACE_DEVICE), _protcol_mode(UUID16_CHR_PROTOCOL_MODE), _kbd_boot_input(UUID16_CHR_BOOT_KEYBOARD_INPUT_REPORT), _kbd_boot_output(UUID16_CHR_BOOT_KEYBOARD_OUTPUT_REPORT), - _mouse_boot_input(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT), + _mse_boot_input(UUID16_CHR_BOOT_MOUSE_INPUT_REPORT), _hid_info(UUID16_CHR_HID_INFORMATION), _hid_control(UUID16_CHR_HID_CONTROL_POINT) { + _kbd_cb = NULL; + _mse_cb = NULL; + varclr(&_last_kbd_report); + varclr(&_last_mse_report); } + +void kbd_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) +{ + BLEClientHidAdafruit& svc = (BLEClientHidAdafruit&) chr->parentService(); + svc._handle_kbd_input(data, len); +} + +void mse_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len) +{ + BLEClientHidAdafruit& svc = (BLEClientHidAdafruit&) chr->parentService(); + svc._handle_mse_input(data, len); +} + + bool BLEClientHidAdafruit::begin(void) { // Invoke base class begin() @@ -57,12 +75,22 @@ bool BLEClientHidAdafruit::begin(void) _kbd_boot_input.begin(this); _kbd_boot_output.begin(this); - _mouse_boot_input.begin(this); + _mse_boot_input.begin(this); // set notify callback -// _kbd_boot_input.setNotifyCallback(kbd_client_notify_cb); -// _mouse_boot_input.setNotifyCallback(mouse_client_notify_cb); + _kbd_boot_input.setNotifyCallback(kbd_client_notify_cb); + _mse_boot_input.setNotifyCallback(mse_client_notify_cb); +} + +void BLEClientHidAdafruit::setKeyboardReportCallback(kbd_callback_t fp) +{ + _kbd_cb = fp; +} + +void BLEClientHidAdafruit::setMouseReportCallback(mse_callback_t fp) +{ + _mse_cb = fp; } bool BLEClientHidAdafruit::discover(uint16_t conn_handle) @@ -72,7 +100,7 @@ bool BLEClientHidAdafruit::discover(uint16_t conn_handle) _conn_hdl = BLE_CONN_HANDLE_INVALID; // make as invalid until we found all chars // Discover all characteristics - Bluefruit.Discovery.discoverCharacteristic(conn_handle, _protcol_mode, _kbd_boot_input, _kbd_boot_output, _mouse_boot_input, _hid_info, _hid_control); + Bluefruit.Discovery.discoverCharacteristic(conn_handle, _protcol_mode, _kbd_boot_input, _kbd_boot_output, _mse_boot_input, _hid_info, _hid_control); VERIFY( _protcol_mode.discovered() && _hid_info.discovered() && _hid_control.discovered() ); VERIFY ( keyboardPresent() || mousePresent() ); @@ -81,6 +109,9 @@ bool BLEClientHidAdafruit::discover(uint16_t conn_handle) return true; } +/*------------------------------------------------------------------*/ +/* Info + *------------------------------------------------------------------*/ bool BLEClientHidAdafruit::getHidInfo(uint8_t info[4]) { return 4 == _hid_info.read(info, 4); @@ -94,32 +125,70 @@ uint8_t BLEClientHidAdafruit::getCountryCode(void) return info[2]; } +bool BLEClientHidAdafruit::setProtocolMode(uint8_t mode) +{ + return _protcol_mode.write8(mode); +} + +/*------------------------------------------------------------------*/ +/* Keyboard + *------------------------------------------------------------------*/ bool BLEClientHidAdafruit::keyboardPresent(void) { return _kbd_boot_input.discovered() && _kbd_boot_output.discovered(); } -bool BLEClientHidAdafruit::mousePresent(void) -{ - return _mouse_boot_input.discovered(); -} - bool BLEClientHidAdafruit::enableKeyboard(void) { _kbd_boot_input.enableNotify(); } -bool BLEClientHidAdafruit::enableMouse(void) -{ - _mouse_boot_input.enableNotify(); -} - bool BLEClientHidAdafruit::disableKeyboard(void) { _kbd_boot_input.disableNotify(); } +void BLEClientHidAdafruit::_handle_kbd_input(uint8_t* data, uint16_t len) +{ + varclr(&_last_kbd_report); + memcpy(&_last_kbd_report, data, len); + + if ( _kbd_cb ) _kbd_cb(&_last_kbd_report); +} + +void BLEClientHidAdafruit::getKeyboardReport(hid_keyboard_report_t* report) +{ + memcpy(report, &_last_kbd_report, sizeof(hid_keyboard_report_t)); +} + +/*------------------------------------------------------------------*/ +/* Mouse + *------------------------------------------------------------------*/ +bool BLEClientHidAdafruit::mousePresent(void) +{ + return _mse_boot_input.discovered(); +} + +bool BLEClientHidAdafruit::enableMouse(void) +{ + _mse_boot_input.enableNotify(); +} + bool BLEClientHidAdafruit::disableMouse(void) { - _mouse_boot_input.disableNotify(); + _mse_boot_input.disableNotify(); } + +void BLEClientHidAdafruit::_handle_mse_input(uint8_t* data, uint16_t len) +{ + varclr(&_last_mse_report); + memcpy(&_last_mse_report, data, len); + + if ( _mse_cb ) _mse_cb(&_last_mse_report); +} + +void BLEClientHidAdafruit::getMouseReport(hid_mouse_report_t* report) +{ + memcpy(report, &_last_mse_report, sizeof(hid_mouse_report_t)); +} + diff --git a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h index c18b0474..526f1c2b 100644 --- a/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h +++ b/libraries/Bluefruit52Lib/src/clients/BLEClientHidAdafruit.h @@ -47,8 +47,8 @@ class BLEClientHidAdafruit : public BLEClientService { public: // Callback Signatures - typedef void (*kbd_callback_t ) (uint8_t modifier, uint8_t keycode[6]); - typedef void (*mouse_callback_t ) (uint8_t buttons, int8_t x, int8_t y, int8_t wheel, int8_t pan); + typedef void (*kbd_callback_t ) (hid_keyboard_report_t* report); + typedef void (*mse_callback_t ) (hid_mouse_report_t* report); BLEClientHidAdafruit(void); @@ -58,24 +58,32 @@ class BLEClientHidAdafruit : public BLEClientService bool getHidInfo(uint8_t info[4]); uint8_t getCountryCode(void); - // Check if peripheral support keyboard/mouse - bool keyboardPresent(void); - bool mousePresent(void); + bool setProtocolMode(uint8_t mode); - // Enable/Disable report notification for keyboard/mouse + // Keyboard API + bool keyboardPresent(void); bool enableKeyboard(void); bool disableKeyboard(void); + void getKeyboardReport(hid_keyboard_report_t* report); + + // Mouse API + bool mousePresent(void); bool enableMouse(void); bool disableMouse(void); + void getMouseReport(hid_mouse_report_t* report); + // Report callback void setKeyboardReportCallback(kbd_callback_t fp); - void setMouseReportCallback(mouse_callback_t fp); + void setMouseReportCallback(mse_callback_t fp); - private: - kbd_callback_t _kbd_cb; - mouse_callback_t _mouse_cb; + protected: + kbd_callback_t _kbd_cb; + mse_callback_t _mse_cb; + + hid_keyboard_report_t _last_kbd_report; + hid_mouse_report_t _last_mse_report; // Only support Boot protocol for keyboard and Mouse BLEClientCharacteristic _protcol_mode; @@ -85,7 +93,13 @@ class BLEClientHidAdafruit : public BLEClientService BLEClientCharacteristic _kbd_boot_input; BLEClientCharacteristic _kbd_boot_output; - BLEClientCharacteristic _mouse_boot_input; + BLEClientCharacteristic _mse_boot_input; + + void _handle_kbd_input(uint8_t* data, uint16_t len); + void _handle_mse_input(uint8_t* data, uint16_t len); + + friend void kbd_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); + friend void mse_client_notify_cb(BLEClientCharacteristic* chr, uint8_t* data, uint16_t len); }; From 203d9bd3f33f87e29da07593063e78b3dedeb163 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 23 Feb 2018 23:24:18 +0700 Subject: [PATCH 29/39] update configCentralConn value --- .../examples/Central/central_hid/central_hid.ino | 2 -- libraries/Bluefruit52Lib/src/BLEGap.cpp | 8 ++++++-- libraries/Bluefruit52Lib/src/bluefruit.cpp | 6 +++--- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino index 787bb787..c0cac08f 100644 --- a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino +++ b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino @@ -33,8 +33,6 @@ void setup() Serial.println("Bluefruit52 Central HID (Keyboard + Mouse) Example"); Serial.println("--------------------------------------------------\n"); - - Bluefruit.configCentralConn(23, 3, 1, 3); // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1 // SRAM usage required by SoftDevice will increase dramatically with number of connections diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 24d3d87a..557a5fa4 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -331,13 +331,17 @@ void BLEGap::_eventHandler(ble_evt_t* evt) // Bonding process completed ble_gap_evt_auth_status_t* status = &evt->evt.gap_evt.params.auth_status; - // Pairing/Bonding succeeded --> save encryption keys + // Pairing succeeded --> save encryption keys ( Bonding ) if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) { peer->bonded = true; peer->ediv = peer->bond_data->own_enc.master_id.ediv; - bond_save_keys(conn_hdl, peer->bond_data); + // TODO Skip bonding for central, implement re-establishment connection later. + if ( peer->role == BLE_GAP_ROLE_PERIPH ) + { + bond_save_keys(conn_hdl, peer->bond_data); + } }else { PRINT_HEX(status->auth_status); diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 0f67e1d5..6e199b7b 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -194,15 +194,15 @@ void AdafruitBluefruit::configCentralBandwidth(uint8_t bw) // TODO Bandwidth auto case BANDWIDTH_AUTO: case BANDWIDTH_NORMAL: - configCentralConn(BLE_GATT_ATT_MTU_DEFAULT, BLE_GAP_EVENT_LENGTH_DEFAULT, BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT, BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT); + configCentralConn(BLE_GATT_ATT_MTU_DEFAULT, BLE_GAP_EVENT_LENGTH_DEFAULT, BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT, 3); break; case BANDWIDTH_HIGH: - configCentralConn(128, 6, 2, BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT); + configCentralConn(128, 6, 1, 3); break; case BANDWIDTH_MAX: - configCentralConn(247, 6, 3, BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT); + configCentralConn(247, 6, 1, 3); break; default: break; From 49b0924a2a115653a1a69873e2fd4ae7c2a4b134 Mon Sep 17 00:00:00 2001 From: hracetech <36821575+hracetech@users.noreply.github.com> Date: Sun, 25 Feb 2018 18:48:37 +0100 Subject: [PATCH 30/39] Update BLEUuid.h UUID for Cycling Power Service added... --- libraries/Bluefruit52Lib/src/BLEUuid.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/Bluefruit52Lib/src/BLEUuid.h b/libraries/Bluefruit52Lib/src/BLEUuid.h index 1b8329c3..351e57f4 100644 --- a/libraries/Bluefruit52Lib/src/BLEUuid.h +++ b/libraries/Bluefruit52Lib/src/BLEUuid.h @@ -81,6 +81,7 @@ class BLEUuid #define UUID16_SVC_BLOOD_PRESSURE 0x1810 #define UUID16_SVC_CURRENT_TIME 0x1805 #define UUID16_SVC_CYCLING_SPEED_AND_CADENCE 0x1816 +#define UUID16_SVC_CYCLING_POWER 0x1818 #define UUID16_SVC_LOCATION_AND_NAVIGATION 0x1819 #define UUID16_SVC_DEVICE_INFORMATION 0x180A #define UUID16_SVC_GLUCOSE 0x1808 @@ -121,6 +122,8 @@ class BLEUuid #define UUID16_CHR_BOOT_KEYBOARD_OUTPUT_REPORT 0x2A32 #define UUID16_CHR_BOOT_MOUSE_INPUT_REPORT 0x2A33 #define UUID16_CHR_CURRENT_TIME 0x2A2B +#define UUID16_CHR_CYCLING_POWER_MEASUREMENT 0x2A63 +#define UUID16_CHR_CYCLING_POWER_FEATURE 0x2A65 #define UUID16_CHR_DATE_TIME 0x2A08 #define UUID16_CHR_DAY_DATE_TIME 0x2A0A #define UUID16_CHR_DAY_OF_WEEK 0x2A09 From a05d4676868aca4b25b725a5d3b7c80960a5110d Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 15:11:13 +0700 Subject: [PATCH 31/39] enhance bonding management - seperate bond folder for prph and central - use mac address if couldn't get peer name when saving bond data --- libraries/Bluefruit52Lib/src/BLECentral.cpp | 6 + libraries/Bluefruit52Lib/src/BLECentral.h | 2 + libraries/Bluefruit52Lib/src/BLEGap.cpp | 10 +- libraries/Bluefruit52Lib/src/BLEGap.h | 2 +- libraries/Bluefruit52Lib/src/BLEGatt.cpp | 3 +- libraries/Bluefruit52Lib/src/bluefruit.cpp | 32 +--- .../Bluefruit52Lib/src/services/BLEDfu.cpp | 2 +- .../Bluefruit52Lib/src/utility/bonding.cpp | 139 ++++++++++++++---- .../Bluefruit52Lib/src/utility/bonding.h | 25 +++- 9 files changed, 147 insertions(+), 74 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLECentral.cpp b/libraries/Bluefruit52Lib/src/BLECentral.cpp index 2a4ebfcd..3c0c6407 100644 --- a/libraries/Bluefruit52Lib/src/BLECentral.cpp +++ b/libraries/Bluefruit52Lib/src/BLECentral.cpp @@ -35,6 +35,7 @@ /**************************************************************************/ #include "bluefruit.h" +#include "utility/bonding.h" /** * Constructor @@ -137,6 +138,11 @@ void BLECentral::setDisconnectCallback( BLEGap::disconnect_callback_t fp) _disconnect_cb = fp; } +void BLECentral::clearBonds(void) +{ + bond_clear_cntr(); +} + /** * Event is forwarded from Bluefruit Poll() method * @param event diff --git a/libraries/Bluefruit52Lib/src/BLECentral.h b/libraries/Bluefruit52Lib/src/BLECentral.h index 072d994f..a1e5ed2e 100644 --- a/libraries/Bluefruit52Lib/src/BLECentral.h +++ b/libraries/Bluefruit52Lib/src/BLECentral.h @@ -71,6 +71,8 @@ class BLECentral bool connected (uint16_t conn_handle); // If connected to a specific peripheral bool connected (void); // If connected to any peripherals + void clearBonds (void); + /*------------- Callbacks -------------*/ void setConnectCallback ( BLEGap::connect_callback_t fp); void setDisconnectCallback( BLEGap::disconnect_callback_t fp); diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 557a5fa4..38ffa4fc 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -337,11 +337,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) peer->bonded = true; peer->ediv = peer->bond_data->own_enc.master_id.ediv; - // TODO Skip bonding for central, implement re-establishment connection later. - if ( peer->role == BLE_GAP_ROLE_PERIPH ) - { - bond_save_keys(conn_hdl, peer->bond_data); - } + bond_save_keys(peer->role, conn_hdl, peer->bond_data); }else { PRINT_HEX(status->auth_status); @@ -361,7 +357,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) bond_data_t bdata; varclr(&bdata); - if ( bond_load_keys(sec_req->master_id.ediv, &bdata) ) + if ( bond_load_keys(peer->role, sec_req->master_id.ediv, &bdata) ) { sd_ble_gap_sec_info_reply(evt->evt.gap_evt.conn_handle, &bdata.own_enc.enc_info, &bdata.peer_id.id_info, NULL); @@ -379,7 +375,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) // Previously bonded --> secure by re-connection process // --> Load & Set Sys Attr (Apply Service Context) // Else Init Sys Attr - bond_load_cccd(conn_hdl, peer->ediv); + bond_load_cccd(peer->role, conn_hdl, peer->ediv); // Paired is Bonded (as we always save keys) peer->bonded = true; diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index 37f7d82b..c4dca518 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -124,7 +124,7 @@ class BLEGap ble_gap_sec_params_t _sec_param; friend class AdafruitBluefruit; - friend class BLEGatt; +// friend class BLEGatt; }; #endif /* BLEGAP_H_ */ diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index 69dcfef6..fb25e85f 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -146,7 +146,8 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) // Save CCCD if paired if ( Bluefruit.connPaired() && (evt_id == BLE_GATTS_EVT_WRITE) && (req_handle == chr->handles().cccd_handle) ) { - bond_save_cccd(evt_conn_hdl, Bluefruit.Gap._get_peer(evt_conn_hdl)->ediv); + BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl); + bond_save_cccd( peer->role, evt_conn_hdl, peer->ediv); } } } diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 6e199b7b..01ecc233 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -731,34 +731,12 @@ void AdafruitBluefruit::printInfo(void) Serial.println(); /*------------- List the paried device -------------*/ - Serial.printf(title_fmt, "Paired Devices"); + Serial.printf(title_fmt, "Peripheral Paired Devices\n"); + bond_print_list(BLE_GAP_ROLE_PERIPH); Serial.println(); - NffsDir dir(CFG_BOND_NFFS_DIR); - NffsDirEntry dirEntry; - while( dir.read(&dirEntry) ) - { - if ( !dirEntry.isDirectory() ) - { - char name[64]; - dirEntry.getName(name, sizeof(name)); - - Serial.printf(" %s : ", name); - - // open file to read device name - NffsFile file(CFG_BOND_NFFS_DIR, dirEntry, FS_ACCESS_READ); - - varclr(name); - - file.seek(BOND_FILE_DEVNAME_OFFSET); - if ( file.read(name, CFG_MAX_DEVNAME_LEN) ) - { - Serial.println(name); - } - - file.close(); - } - } + Serial.printf(title_fmt, "Central Paired Devices\n"); + bond_print_list(BLE_GAP_ROLE_CENTRAL); Serial.println(); Serial.println(); @@ -984,6 +962,6 @@ bool AdafruitBluefruit::requestPairing(void) void AdafruitBluefruit::clearBonds(void) { - bond_clear(); + bond_clear_prph(); } diff --git a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp index 4849b036..5e07de09 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp @@ -139,7 +139,7 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt { bond_data_t bdata; - if ( bond_load_keys( Bluefruit.Gap._get_peer(conn_hdl)->ediv, &bdata ) ) + if ( bond_load_keys( BLE_GAP_ROLE_PERIPH, Bluefruit.Gap._get_peer(conn_hdl)->ediv, &bdata ) ) { peer_data->addr = bdata.peer_id.id_addr_info; peer_data->irk = bdata.peer_id.id_info; diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 5f5c02b7..f012e448 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -42,9 +42,9 @@ #define SVC_CONTEXT_FLAG (BLE_GATTS_SYS_ATTR_FLAG_SYS_SRVCS | BLE_GATTS_SYS_ATTR_FLAG_USR_SRVCS) #if CFG_DEBUG >= 2 -#define printBondDir() dbgPrintDir(CFG_BOND_NFFS_DIR) +#define printBondDir(role) dbgPrintDir( role == BLE_GAP_ROLE_PERIPH ? BOND_DIR_PRPH : BOND_DIR_CNTR ) #else -#define printBondDir() +#define printBondDir(role) #endif /*------------------------------------------------------------------*/ @@ -58,16 +58,24 @@ void bond_init(void) { // Initialize nffs for bonding (it is safe to call nffs_pkg_init() multiple time) Nffs.begin(); - (void) Nffs.mkdir_p(CFG_BOND_NFFS_DIR); + + (void) Nffs.mkdir_p(BOND_DIR_PRPH); + (void) Nffs.mkdir_p(BOND_DIR_CNTR); } /*------------------------------------------------------------------*/ /* Keys *------------------------------------------------------------------*/ -static void bond_save_keys_dfr(uint16_t conn_hdl, bond_data_t* bdata) +static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata) { - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, bdata->own_enc.master_id.ediv); + char filename[BOND_FNAME_LEN]; + if ( role == BLE_GAP_ROLE_PERIPH ) + { + sprintf(filename, BOND_FNAME_PRPH, bdata->own_enc.master_id.ediv); + }else + { + sprintf(filename, BOND_FNAME_CNTR, bdata->own_enc.master_id.ediv); + } char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; Bluefruit.Gap.getPeerName(conn_hdl, devname, CFG_MAX_DEVNAME_LEN); @@ -84,12 +92,15 @@ static void bond_save_keys_dfr(uint16_t conn_hdl, bond_data_t* bdata) result = false; } - // write device name - if ( strlen(devname) && !file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN) ) + // If couldn't get devname use peer mac address + if ( !strlen(devname) ) { - result = false; + uint8_t* mac = bdata->peer_id.id_addr_info.addr; + sprintf(devname, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]); } + file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN); + file.close(); if (result) @@ -100,10 +111,10 @@ static void bond_save_keys_dfr(uint16_t conn_hdl, bond_data_t* bdata) LOG_LV1("BOND", "Failed to save keys for \"%s\"", devname); } - printBondDir(); + printBondDir(role); } -void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata) +void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata) { uint8_t* buf = (uint8_t*) rtos_malloc( sizeof(bond_data_t) ); VERIFY(buf, ); @@ -111,13 +122,19 @@ void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata) memcpy(buf, bdata, sizeof(bond_data_t)); // queue to execute in Ada Callback thread - ada_callback(buf, bond_save_keys_dfr, conn_hdl, buf); + ada_callback(buf, bond_save_keys_dfr, role, conn_hdl, buf); } -bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) +bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata) { - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); + char filename[BOND_FNAME_LEN]; + if ( role == BLE_GAP_ROLE_PERIPH ) + { + sprintf(filename, BOND_FNAME_PRPH, ediv); + }else + { + sprintf(filename, BOND_FNAME_CNTR, ediv); + } bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0); @@ -136,7 +153,7 @@ bool bond_load_keys(uint16_t ediv, bond_data_t* bdata) /*------------------------------------------------------------------*/ /* CCCD *------------------------------------------------------------------*/ -static void bond_save_cccd_dfr (uint16_t conn_hdl, uint16_t ediv) +static void bond_save_cccd_dfr (uint8_t role, uint16_t conn_hdl, uint16_t ediv) { uint16_t len=0; sd_ble_gatts_sys_attr_get(conn_hdl, NULL, &len, SVC_CONTEXT_FLAG); @@ -147,8 +164,14 @@ static void bond_save_cccd_dfr (uint16_t conn_hdl, uint16_t ediv) if ( ERROR_NONE == sd_ble_gatts_sys_attr_get(conn_hdl, sys_attr, &len, SVC_CONTEXT_FLAG) ) { // save to file - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); + char filename[BOND_FNAME_LEN]; + if ( role == BLE_GAP_ROLE_PERIPH ) + { + sprintf(filename, BOND_FNAME_PRPH, ediv); + }else + { + sprintf(filename, BOND_FNAME_CNTR, ediv); + } if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) { @@ -161,24 +184,30 @@ static void bond_save_cccd_dfr (uint16_t conn_hdl, uint16_t ediv) } rtos_free(sys_attr); - printBondDir(); + printBondDir(role); } -void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv) +void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv) { VERIFY( ediv != 0xFFFF, ); // queue to execute in Ada Callback thread - ada_callback(NULL, bond_save_cccd_dfr, cond_hdl, ediv); + ada_callback(NULL, bond_save_cccd_dfr, role, cond_hdl, ediv); } -bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) +bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv) { bool loaded = false; - char filename[BOND_FILENAME_LEN]; - sprintf(filename, BOND_FILENAME, ediv); + char filename[BOND_FNAME_LEN]; + if ( role == BLE_GAP_ROLE_PERIPH ) + { + sprintf(filename, BOND_FNAME_PRPH, ediv); + }else + { + sprintf(filename, BOND_FNAME_CNTR, ediv); + } NffsFile file(filename, FS_ACCESS_READ); @@ -222,16 +251,68 @@ bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv) return loaded; } +void bond_print_list(uint8_t role) +{ + const char* dpath = (role == BLE_GAP_ROLE_PERIPH ? BOND_DIR_PRPH : BOND_DIR_CNTR); + + NffsDir dir(dpath); + NffsDirEntry dirEntry; + + while( dir.read(&dirEntry) ) + { + if ( !dirEntry.isDirectory() ) + { + char name[64]; + dirEntry.getName(name, sizeof(name)); + + cprintf(" %s : ", name); + + // open file to read device name + NffsFile file(dpath, dirEntry, FS_ACCESS_READ); + + varclr(name); + + file.seek(BOND_FILE_DEVNAME_OFFSET); + if ( file.read(name, CFG_MAX_DEVNAME_LEN) ) + { + cprintf(name); + } + + cprintf("\n"); + file.close(); + } + } + cprintf("\n"); +} + /*------------------------------------------------------------------*/ /* DELETE *------------------------------------------------------------------*/ -void bond_clear(void) +void bond_clear_prph(void) { // Detele bonds dir - Nffs.remove(CFG_BOND_NFFS_DIR); + Nffs.remove(BOND_DIR_PRPH); // Create an empty one - Nffs.mkdir_p(CFG_BOND_NFFS_DIR); - - printBondDir(); + (void) Nffs.mkdir_p(BOND_DIR_PRPH); +} + +void bond_clear_cntr(void) +{ + // Detele bonds dir + Nffs.remove(BOND_DIR_CNTR); + + // Create an empty one + (void) Nffs.mkdir_p(BOND_DIR_CNTR); +} + + +void bond_clear_all(void) +{ + // Detele bonds dir + Nffs.remove(BOND_DIR_ROOT); + + // Create an empty one for prph and central + (void) Nffs.mkdir_p(BOND_DIR_PRPH); + (void) Nffs.mkdir_p(BOND_DIR_CNTR); } diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h index 4d9b3dd7..2c76e393 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.h +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -38,9 +38,14 @@ #include "bluefruit_common.h" -#define CFG_BOND_NFFS_DIR "/adafruit/bond" -#define BOND_FILENAME CFG_BOND_NFFS_DIR "/%04x" -#define BOND_FILENAME_LEN (sizeof(CFG_BOND_NFFS_DIR) + 10) +#define BOND_DIR_ROOT "/adafruit/bond" +#define BOND_DIR_PRPH BOND_DIR_ROOT "/prph" +#define BOND_DIR_CNTR BOND_DIR_ROOT "/cntr" + +#define BOND_FNAME_PRPH BOND_DIR_PRPH "/%04x" +#define BOND_FNAME_CNTR BOND_DIR_CNTR "/%04x" + +#define BOND_FNAME_LEN max(sizeof(BOND_FNAME_PRPH), sizeof(BOND_FNAME_CNTR)) // Shared keys with bonded device, size = 80 bytes typedef struct @@ -57,13 +62,17 @@ enum }; void bond_init(void); -void bond_clear(void); +void bond_clear_prph(void); +void bond_clear_cntr(void); +void bond_clear_all(void); -void bond_save_keys(uint16_t conn_hdl, bond_data_t* bdata); -bool bond_load_keys(uint16_t ediv, bond_data_t* bdata); +void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata); +bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata); -void bond_save_cccd(uint16_t cond_hdl, uint16_t ediv); -bool bond_load_cccd(uint16_t cond_hdl, uint16_t ediv); +void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); +bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); + +void bond_print_list(uint8_t role); From 393ee6cf1def11e11d52a346adc22c73f9b189ed Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 15:17:17 +0700 Subject: [PATCH 32/39] renamed bonded to paired --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 18 ++++++++++-------- libraries/Bluefruit52Lib/src/BLEGap.h | 4 ++-- libraries/Bluefruit52Lib/src/bluefruit.cpp | 2 +- .../Bluefruit52Lib/src/services/BLEDfu.cpp | 2 +- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 38ffa4fc..3995f32c 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -159,9 +159,9 @@ bool BLEGap::connected(uint16_t conn_hdl) return _peers[conn_hdl].connected; } -bool BLEGap::bonded(uint16_t conn_hdl) +bool BLEGap::paired(uint16_t conn_hdl) { - return _peers[conn_hdl].bonded; + return _peers[conn_hdl].paired; } bool BLEGap::requestPairing(uint16_t conn_hdl) @@ -169,18 +169,20 @@ bool BLEGap::requestPairing(uint16_t conn_hdl) gap_peer_t* peer = &_peers[conn_hdl]; // skip if already bonded - if ( peer->bonded ) return true; + if ( peer->paired ) return true; + + VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); uint32_t start = millis(); // timeout in 30 seconds - while ( ! ((volatile bool) peer->bonded) && (start + 30000 > millis()) ) + while ( ! ((volatile bool) peer->paired) && (start + 30000 > millis()) ) { yield(); } - return peer->bonded; + return peer->paired; } uint8_t BLEGap::getRole(uint16_t conn_hdl) @@ -266,7 +268,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) ble_gap_evt_disconnected_t const* para = &evt->evt.gap_evt.params.disconnected; // mark as disconnected, but keep the role for sub sequence event handler - peer->connected = peer->bonded = false; + peer->connected = peer->paired = false; vSemaphoreDelete( peer->hvn_tx_sem ); peer->hvn_tx_sem = NULL; @@ -334,7 +336,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) // Pairing succeeded --> save encryption keys ( Bonding ) if (BLE_GAP_SEC_STATUS_SUCCESS == status->auth_status) { - peer->bonded = true; + peer->paired = true; peer->ediv = peer->bond_data->own_enc.master_id.ediv; bond_save_keys(peer->role, conn_hdl, peer->bond_data); @@ -378,7 +380,7 @@ void BLEGap::_eventHandler(ble_evt_t* evt) bond_load_cccd(peer->role, conn_hdl, peer->ediv); // Paired is Bonded (as we always save keys) - peer->bonded = true; + peer->paired = true; break; case BLE_GAP_EVT_PASSKEY_DISPLAY: diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index c4dca518..9fa06e7b 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -60,7 +60,7 @@ class BLEGap // bool setPrivacy (); sd_ble_gap_privacy_set() bool connected (uint16_t conn_hdl); - bool bonded (uint16_t conn_hdl); + bool paired (uint16_t conn_hdl); bool requestPairing (uint16_t conn_hdl); uint8_t getRole (uint16_t conn_hdl); @@ -93,7 +93,7 @@ class BLEGap // Peer info where conn_hdl serves as index typedef struct { bool connected; - bool bonded; + bool paired; uint8_t role; uint16_t att_mtu; diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 01ecc233..438b7d92 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -578,7 +578,7 @@ uint16_t AdafruitBluefruit::connHandle(void) bool AdafruitBluefruit::connPaired(void) { - return Gap.bonded(_conn_hdl); + return Gap.paired(_conn_hdl); } uint16_t AdafruitBluefruit::connInterval(void) diff --git a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp index 5e07de09..6208a5f8 100644 --- a/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp +++ b/libraries/Bluefruit52Lib/src/services/BLEDfu.cpp @@ -135,7 +135,7 @@ static void bledfu_control_wr_authorize_cb(BLECharacteristic& chr, ble_gatts_evt // Get Bond Data or using Address if not bonded peer_data->addr = Bluefruit.Gap.getPeerAddr(conn_hdl); - if ( Bluefruit.Gap.bonded(conn_hdl) ) + if ( Bluefruit.Gap.paired(conn_hdl) ) { bond_data_t bdata; From e81f60cd2eeddf0213937e3191c3e6a890e5398c Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 16:07:34 +0700 Subject: [PATCH 33/39] update clear bonds examples --- .../Peripheral/clearbonds/clearbonds.ino | 60 +++---------------- 1 file changed, 7 insertions(+), 53 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/clearbonds/clearbonds.ino b/libraries/Bluefruit52Lib/examples/Peripheral/clearbonds/clearbonds.ino index e1181313..b98129aa 100644 --- a/libraries/Bluefruit52Lib/examples/Peripheral/clearbonds/clearbonds.ino +++ b/libraries/Bluefruit52Lib/examples/Peripheral/clearbonds/clearbonds.ino @@ -18,6 +18,7 @@ #include #include +#include void setup() { @@ -29,13 +30,17 @@ void setup() Serial.println(); Serial.println("----- Before -----\n"); - printDir("/adafruit/bond"); + bond_print_list(BLE_GAP_ROLE_PERIPH); + bond_print_list(BLE_GAP_ROLE_CENTRAL); Bluefruit.clearBonds(); + Bluefruit.Central.clearBonds(); Serial.println(); Serial.println("----- After -----\n"); - printDir("/adafruit/bond"); + + bond_print_list(BLE_GAP_ROLE_PERIPH); + bond_print_list(BLE_GAP_ROLE_CENTRAL); } void loop() @@ -46,54 +51,3 @@ void loop() delay(1000); } -void printDir(const char* cwd) -{ - // Open the input folder - NffsDir dir(cwd); - - Serial.println(cwd); - - // File Entry Information which hold file attribute and name - NffsDirEntry dirEntry; - - // Loop through the directory - while( dir.read(&dirEntry) ) - { - // Indentation - Serial.print("|_ "); - - char eName[64]; - dirEntry.getName(eName, sizeof(eName)); - - char fullpath[256]; - strcpy(fullpath, cwd); - strcat(fullpath, "/"); - strcat(fullpath, eName); - - Serial.print( eName ); - - if ( dirEntry.isDirectory() ) - { - Serial.println("/"); - }else - { - // Print file size starting from position 50 - int pos = 3 + strlen(eName); - - // Print padding - for (int i=pos; i<50; i++) Serial.print(' '); - - // Print at least one extra space in case current position > 50 - Serial.print(' '); - - NffsFile file(fullpath); - - Serial.print( file.size() ); - Serial.println( " Bytes"); - - file.close(); - } - } - - dir.close(); -} From f3136abcdaa1439b75813ff018672b801531c2ca Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 17:30:14 +0700 Subject: [PATCH 34/39] improve bonding with on-the-fly semaphore enhance central bond --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 54 +++++++++++++------ libraries/Bluefruit52Lib/src/BLEGap.h | 5 +- libraries/Bluefruit52Lib/src/BLEGatt.cpp | 12 ++--- libraries/Bluefruit52Lib/src/bluefruit.cpp | 8 +-- .../Bluefruit52Lib/src/utility/bonding.cpp | 39 +++++++++++++- .../Bluefruit52Lib/src/utility/bonding.h | 20 +++---- 6 files changed, 101 insertions(+), 37 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index 3995f32c..ca2b900b 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -168,20 +168,35 @@ bool BLEGap::requestPairing(uint16_t conn_hdl) { gap_peer_t* peer = &_peers[conn_hdl]; - // skip if already bonded + // skip if already paired if ( peer->paired ) return true; - - - VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); - uint32_t start = millis(); - - // timeout in 30 seconds - while ( ! ((volatile bool) peer->paired) && (start + 30000 > millis()) ) + // Check to see if we did bonded with current prph + if ( peer->role == BLE_GAP_ROLE_CENTRAL ) { - yield(); + bond_data_t bdata; + + if ( bond_find_cntr(&peer->addr, &bdata) ) + { + LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, bdata.peer_enc.master_id.ediv); + VERIFY_STATUS( sd_ble_gap_encrypt(conn_hdl, &bdata.peer_enc.master_id, &bdata.peer_enc.enc_info), false); + }else + { + VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); + } + }else + { + VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); } + // Wait for pairing process using on-the-fly semaphore + peer->pair_sem = xSemaphoreCreateBinary(); + + xSemaphoreTake(peer->pair_sem, portMAX_DELAY); + + vSemaphoreDelete(peer->pair_sem); + peer->pair_sem = NULL; + return peer->paired; } @@ -372,15 +387,22 @@ void BLEGap::_eventHandler(ble_evt_t* evt) break; case BLE_GAP_EVT_CONN_SEC_UPDATE: - // Connection is secured aka Paired + { + const ble_gap_conn_sec_t* conn_sec = &evt->evt.gap_evt.params.conn_sec_update.conn_sec; - // Previously bonded --> secure by re-connection process - // --> Load & Set Sys Attr (Apply Service Context) - // Else Init Sys Attr - bond_load_cccd(peer->role, conn_hdl, peer->ediv); + // Connection is secured (paired) + if ( !( conn_sec->sec_mode.sm == 1 && conn_sec->sec_mode.lv == 1) ) + { + // Previously bonded --> secure by re-connection process + // --> Load & Set Sys Attr (Apply Service Context) + // Else Init Sys Attr + bond_load_cccd(peer->role, conn_hdl, peer->ediv); - // Paired is Bonded (as we always save keys) - peer->paired = true; + peer->paired = true; + } + + if (peer->pair_sem) xSemaphoreGive(peer->pair_sem); + } break; case BLE_GAP_EVT_PASSKEY_DISPLAY: diff --git a/libraries/Bluefruit52Lib/src/BLEGap.h b/libraries/Bluefruit52Lib/src/BLEGap.h index 9fa06e7b..fefdcf95 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.h +++ b/libraries/Bluefruit52Lib/src/BLEGap.h @@ -105,8 +105,11 @@ class BLEGap SemaphoreHandle_t hvn_tx_sem; SemaphoreHandle_t wrcmd_tx_sem; - SemaphoreHandle_t indicate_confirm_sem; bool hvc_received; + + // On-demand semaphore that are created on the fly + SemaphoreHandle_t hvc_sem; + SemaphoreHandle_t pair_sem; } gap_peer_t; gap_peer_t* _get_peer(uint16_t conn_hdl) { return &_peers[conn_hdl]; } diff --git a/libraries/Bluefruit52Lib/src/BLEGatt.cpp b/libraries/Bluefruit52Lib/src/BLEGatt.cpp index fb25e85f..75401e4d 100644 --- a/libraries/Bluefruit52Lib/src/BLEGatt.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGatt.cpp @@ -80,12 +80,12 @@ bool BLEGatt::waitForIndicateConfirm(uint16_t conn_hdl) BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(conn_hdl); // hvi confirm semaphore is created on the fly - peer->indicate_confirm_sem = xSemaphoreCreateBinary(); + peer->hvc_sem = xSemaphoreCreateBinary(); - xSemaphoreTake(peer->indicate_confirm_sem, portMAX_DELAY); + xSemaphoreTake(peer->hvc_sem, portMAX_DELAY); - vSemaphoreDelete(peer->indicate_confirm_sem); - peer->indicate_confirm_sem = NULL; + vSemaphoreDelete(peer->hvc_sem); + peer->hvc_sem = NULL; return peer->hvc_received; } @@ -237,7 +237,7 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) LOG_LV2("GATTS", "Confirm received handle = 0x%04X", evt->evt.gatts_evt.params.hvc.handle); BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl); - if ( peer->indicate_confirm_sem ) xSemaphoreGive(peer->indicate_confirm_sem); + if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem); peer->hvc_received = true; } break; @@ -248,7 +248,7 @@ void BLEGatt::_eventHandler(ble_evt_t* evt) BLEGap::gap_peer_t* peer = Bluefruit.Gap._get_peer(evt_conn_hdl); - if ( peer->indicate_confirm_sem ) xSemaphoreGive(peer->indicate_confirm_sem); + if ( peer->hvc_sem ) xSemaphoreGive(peer->hvc_sem); peer->hvc_received = false; } break; diff --git a/libraries/Bluefruit52Lib/src/bluefruit.cpp b/libraries/Bluefruit52Lib/src/bluefruit.cpp index 438b7d92..f354bda7 100644 --- a/libraries/Bluefruit52Lib/src/bluefruit.cpp +++ b/libraries/Bluefruit52Lib/src/bluefruit.cpp @@ -731,13 +731,13 @@ void AdafruitBluefruit::printInfo(void) Serial.println(); /*------------- List the paried device -------------*/ - Serial.printf(title_fmt, "Peripheral Paired Devices\n"); + Serial.printf(title_fmt, "Peripheral Paired Devices"); + Serial.println(); bond_print_list(BLE_GAP_ROLE_PERIPH); - Serial.println(); - Serial.printf(title_fmt, "Central Paired Devices\n"); - bond_print_list(BLE_GAP_ROLE_CENTRAL); + Serial.printf(title_fmt, "Central Paired Devices"); Serial.println(); + bond_print_list(BLE_GAP_ROLE_CENTRAL); Serial.println(); } diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index f012e448..6d3bf5dd 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -74,7 +74,7 @@ static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bda sprintf(filename, BOND_FNAME_PRPH, bdata->own_enc.master_id.ediv); }else { - sprintf(filename, BOND_FNAME_CNTR, bdata->own_enc.master_id.ediv); + sprintf(filename, BOND_FNAME_CNTR, bdata->peer_enc.master_id.ediv); } char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; @@ -103,6 +103,10 @@ static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bda file.close(); + PRINT_HEX(bdata->own_enc.master_id.ediv); + PRINT_HEX(bdata->peer_enc.master_id.ediv); + + if (result) { LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); @@ -285,6 +289,39 @@ void bond_print_list(uint8_t role) cprintf("\n"); } + +bool bond_find_cntr(ble_gap_addr_t* addr, bond_data_t* bdata) +{ + bool found = false; + + NffsDir dir(BOND_DIR_CNTR); + NffsDirEntry dirEntry; + + while( dir.read(&dirEntry) && !found ) + { + // Read bond data of each stored file + if ( !dirEntry.isDirectory() ) + { + NffsFile file(BOND_DIR_CNTR, dirEntry, FS_ACCESS_READ); + if ( file.read( (uint8_t*)bdata, sizeof(bond_data_t)) ) + { + if ( !memcmp(addr->addr, bdata->peer_id.id_addr_info.addr, 6) ) + { + // Compare static address + found = true; + }else if ( addr->addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE ) + { + // Resolving private address + } + } + + file.close(); + } + } + + return found; +} + /*------------------------------------------------------------------*/ /* DELETE *------------------------------------------------------------------*/ diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h index 2c76e393..1e2fae71 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.h +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -61,18 +61,20 @@ enum BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN }; -void bond_init(void); -void bond_clear_prph(void); -void bond_clear_cntr(void); -void bond_clear_all(void); +void bond_init(void); +void bond_clear_prph(void); +void bond_clear_cntr(void); +void bond_clear_all(void); -void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata); -bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata); +void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata); +bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata); -void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); -bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); +void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); +bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); -void bond_print_list(uint8_t role); +void bond_print_list(uint8_t role); + +bool bond_find_cntr(ble_gap_addr_t* addr, bond_data_t* bdata); From 231f862338a204b75bd899788d85e0840a16d90b Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 17:49:12 +0700 Subject: [PATCH 35/39] enhance bonding process - auto remove obsolete key on central and re-try with a fresh session. --- libraries/Bluefruit52Lib/src/BLEGap.cpp | 20 +++++++- .../Bluefruit52Lib/src/utility/bonding.cpp | 50 +++++++------------ .../Bluefruit52Lib/src/utility/bonding.h | 20 ++++---- 3 files changed, 46 insertions(+), 44 deletions(-) diff --git a/libraries/Bluefruit52Lib/src/BLEGap.cpp b/libraries/Bluefruit52Lib/src/BLEGap.cpp index ca2b900b..f88449be 100644 --- a/libraries/Bluefruit52Lib/src/BLEGap.cpp +++ b/libraries/Bluefruit52Lib/src/BLEGap.cpp @@ -171,15 +171,19 @@ bool BLEGap::requestPairing(uint16_t conn_hdl) // skip if already paired if ( peer->paired ) return true; - // Check to see if we did bonded with current prph + uint16_t cntr_ediv = 0xFFFF; + if ( peer->role == BLE_GAP_ROLE_CENTRAL ) { + // Check to see if we did bonded with current prph previously bond_data_t bdata; if ( bond_find_cntr(&peer->addr, &bdata) ) { - LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, bdata.peer_enc.master_id.ediv); + cntr_ediv = bdata.peer_enc.master_id.ediv; + LOG_LV2("BOND", "Load Keys from file " BOND_FNAME_CNTR, cntr_ediv); VERIFY_STATUS( sd_ble_gap_encrypt(conn_hdl, &bdata.peer_enc.master_id, &bdata.peer_enc.enc_info), false); + }else { VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); @@ -194,6 +198,18 @@ bool BLEGap::requestPairing(uint16_t conn_hdl) xSemaphoreTake(peer->pair_sem, portMAX_DELAY); + // Failed to pair using centra stored keys, this happens when + // Prph delete bonds while we did not --> let's remove the obsolete keyfile and move on + if ( !peer->paired && (cntr_ediv != 0xffff) ) + { + bond_remove_key(BLE_GAP_ROLE_CENTRAL, cntr_ediv); + + // Re-try with a fresh session + VERIFY_STATUS( sd_ble_gap_authenticate(conn_hdl, &_sec_param ), false); + + xSemaphoreTake(peer->pair_sem, portMAX_DELAY); + } + vSemaphoreDelete(peer->pair_sem); peer->pair_sem = NULL; diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.cpp b/libraries/Bluefruit52Lib/src/utility/bonding.cpp index 6d3bf5dd..81bcf143 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.cpp +++ b/libraries/Bluefruit52Lib/src/utility/bonding.cpp @@ -47,6 +47,11 @@ #define printBondDir(role) #endif +static void get_fname(char* fname, uint8_t role, uint16_t ediv) +{ + sprintf(fname, ( role == BLE_GAP_ROLE_PERIPH ) ? BOND_FNAME_PRPH : BOND_FNAME_CNTR, ediv); +} + /*------------------------------------------------------------------*/ /* Saving Bond Data to Nffs in following layout * - _bond_data 80 bytes @@ -69,13 +74,7 @@ void bond_init(void) static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata) { char filename[BOND_FNAME_LEN]; - if ( role == BLE_GAP_ROLE_PERIPH ) - { - sprintf(filename, BOND_FNAME_PRPH, bdata->own_enc.master_id.ediv); - }else - { - sprintf(filename, BOND_FNAME_CNTR, bdata->peer_enc.master_id.ediv); - } + get_fname(filename, role, role == BLE_GAP_ROLE_PERIPH ? bdata->own_enc.master_id.ediv : bdata->peer_enc.master_id.ediv); char devname[CFG_MAX_DEVNAME_LEN] = { 0 }; Bluefruit.Gap.getPeerName(conn_hdl, devname, CFG_MAX_DEVNAME_LEN); @@ -100,13 +99,8 @@ static void bond_save_keys_dfr(uint8_t role, uint16_t conn_hdl, bond_data_t* bda } file.write((uint8_t*) devname, CFG_MAX_DEVNAME_LEN); - file.close(); - PRINT_HEX(bdata->own_enc.master_id.ediv); - PRINT_HEX(bdata->peer_enc.master_id.ediv); - - if (result) { LOG_LV2("BOND", "Keys for \"%s\" is saved to file %s", devname, filename); @@ -132,13 +126,7 @@ void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata) bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata) { char filename[BOND_FNAME_LEN]; - if ( role == BLE_GAP_ROLE_PERIPH ) - { - sprintf(filename, BOND_FNAME_PRPH, ediv); - }else - { - sprintf(filename, BOND_FNAME_CNTR, ediv); - } + get_fname(filename, role, ediv); bool result = (Nffs.readFile(filename, bdata, sizeof(bond_data_t)) > 0); @@ -169,13 +157,7 @@ static void bond_save_cccd_dfr (uint8_t role, uint16_t conn_hdl, uint16_t ediv) { // save to file char filename[BOND_FNAME_LEN]; - if ( role == BLE_GAP_ROLE_PERIPH ) - { - sprintf(filename, BOND_FNAME_PRPH, ediv); - }else - { - sprintf(filename, BOND_FNAME_CNTR, ediv); - } + get_fname(filename, role, ediv); if ( Nffs.writeFile(filename, sys_attr, len, BOND_FILE_CCCD_OFFSET) ) { @@ -205,13 +187,7 @@ bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv) bool loaded = false; char filename[BOND_FNAME_LEN]; - if ( role == BLE_GAP_ROLE_PERIPH ) - { - sprintf(filename, BOND_FNAME_PRPH, ediv); - }else - { - sprintf(filename, BOND_FNAME_CNTR, ediv); - } + get_fname(filename, role, ediv); NffsFile file(filename, FS_ACCESS_READ); @@ -353,3 +329,11 @@ void bond_clear_all(void) (void) Nffs.mkdir_p(BOND_DIR_PRPH); (void) Nffs.mkdir_p(BOND_DIR_CNTR); } + +void bond_remove_key(uint8_t role, uint16_t ediv) +{ + char filename[BOND_FNAME_LEN]; + get_fname(filename, role, ediv); + + Nffs.remove(filename); +} diff --git a/libraries/Bluefruit52Lib/src/utility/bonding.h b/libraries/Bluefruit52Lib/src/utility/bonding.h index 1e2fae71..f6740312 100644 --- a/libraries/Bluefruit52Lib/src/utility/bonding.h +++ b/libraries/Bluefruit52Lib/src/utility/bonding.h @@ -61,18 +61,20 @@ enum BOND_FILE_CCCD_OFFSET = BOND_FILE_DEVNAME_OFFSET + CFG_MAX_DEVNAME_LEN }; -void bond_init(void); -void bond_clear_prph(void); -void bond_clear_cntr(void); -void bond_clear_all(void); +void bond_init(void); +void bond_clear_prph(void); +void bond_clear_cntr(void); +void bond_clear_all(void); -void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata); -bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata); +void bond_remove_key(uint8_t role, uint16_t ediv); -void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); -bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); +void bond_save_keys(uint8_t role, uint16_t conn_hdl, bond_data_t* bdata); +bool bond_load_keys(uint8_t role, uint16_t ediv, bond_data_t* bdata); -void bond_print_list(uint8_t role); +void bond_save_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); +bool bond_load_cccd(uint8_t role, uint16_t cond_hdl, uint16_t ediv); + +void bond_print_list(uint8_t role); bool bond_find_cntr(ble_gap_addr_t* addr, bond_data_t* bdata); From 028b420ccfc7a6cd7ce695654aa1d3902fef6197 Mon Sep 17 00:00:00 2001 From: hathach Date: Mon, 26 Feb 2018 17:54:07 +0700 Subject: [PATCH 36/39] add central hid callback implementation --- .../Central/central_hid/central_hid.ino | 48 ++++++++++++------- 1 file changed, 31 insertions(+), 17 deletions(-) diff --git a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino index c0cac08f..597521b9 100644 --- a/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino +++ b/libraries/Bluefruit52Lib/examples/Central/central_hid/central_hid.ino @@ -23,7 +23,7 @@ BLEClientHidAdafruit hid; -// Last checked report, to detect if we receive a new one with polling method +// Last checked report, to detect if there is changes between reports hid_keyboard_report_t last_kbd_report = { 0 }; hid_mouse_report_t last_mse_report = { 0 }; @@ -42,7 +42,10 @@ void setup() // Init BLE Central Uart Serivce hid.begin(); - //clientUart.setRxCallback(bleuart_rx_callback); + + #if POLLING == 0 + hid.setKeyboardReportCallback(keyboard_report_callback); + #endif // Increase Blink rate to different from PrPh advertising mode Bluefruit.setConnLedInterval(250); @@ -141,7 +144,7 @@ void disconnect_callback(uint16_t conn_handle, uint8_t reason) void loop() { -#if POLLING +#if POLLING == 1 // nothing to do if hid not discovered if ( !hid.discovered() ) return; @@ -151,26 +154,43 @@ void loop() // Get latest report hid.getKeyboardReport(&kbd_report); - // Check with last report to see if there is new arrival report - if ( memcmp(&last_kbd_report, &kbd_report, sizeof(kbd_report)) ) + processKeyboardReport(&kbd_report); + + + // polling interval is 5 ms + delay(5); +#endif + +} + + +void keyboard_report_callback(hid_keyboard_report_t* report) +{ + processKeyboardReport(report); +} + +void processKeyboardReport(hid_keyboard_report_t* report) +{ + // Check with last report to see if there is any changes + if ( memcmp(&last_kbd_report, report, sizeof(hid_keyboard_report_t)) ) { bool shifted = false; - if ( kbd_report.modifier ) + if ( report->modifier ) { - if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTCTRL | KEYBOARD_MODIFIER_RIGHTCTRL) ) + if ( report->modifier & (KEYBOARD_MODIFIER_LEFTCTRL | KEYBOARD_MODIFIER_RIGHTCTRL) ) { Serial.print("Ctrl "); } - if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT) ) + if ( report->modifier & (KEYBOARD_MODIFIER_LEFTSHIFT | KEYBOARD_MODIFIER_RIGHTSHIFT) ) { Serial.print("Shift "); shifted = true; } - if ( kbd_report.modifier & (KEYBOARD_MODIFIER_LEFTALT | KEYBOARD_MODIFIER_RIGHTALT) ) + if ( report->modifier & (KEYBOARD_MODIFIER_LEFTALT | KEYBOARD_MODIFIER_RIGHTALT) ) { Serial.print("Alt "); } @@ -178,7 +198,7 @@ void loop() for(uint8_t i=0; i<6; i++) { - uint8_t kc = kbd_report.keycode[i]; + uint8_t kc = report->keycode[i]; char ch = 0; if ( kc < 128 ) @@ -198,12 +218,6 @@ void loop() } // update last report - memcpy(&last_kbd_report, &kbd_report, sizeof(kbd_report)); - - - // polling interval is 5 ms - delay(5); -#endif - + memcpy(&last_kbd_report, report, sizeof(hid_keyboard_report_t)); } From 38047231b1a577f3b7821374ded98efc3463268c Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 27 Feb 2018 20:04:54 +0700 Subject: [PATCH 37/39] Fix I2C lock-up when endTransmission() is called with empty txBuffer close #121 --- libraries/Wire/Wire_nRF52.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libraries/Wire/Wire_nRF52.cpp b/libraries/Wire/Wire_nRF52.cpp index e6ef2824..36de1f5d 100755 --- a/libraries/Wire/Wire_nRF52.cpp +++ b/libraries/Wire/Wire_nRF52.cpp @@ -214,7 +214,9 @@ uint8_t TwoWire::endTransmission(bool stopBit) while(!_p_twim->EVENTS_TXSTARTED && !_p_twim->EVENTS_ERROR); _p_twim->EVENTS_TXSTARTED = 0x0UL; - while(!_p_twim->EVENTS_LASTTX && !_p_twim->EVENTS_ERROR); + if (txBuffer.available()) { + while(!_p_twim->EVENTS_LASTTX && !_p_twim->EVENTS_ERROR); + } _p_twim->EVENTS_LASTTX = 0x0UL; if (stopBit || _p_twim->EVENTS_ERROR) From 5afca5157376b04731f8134585f306c3a10b519c Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 27 Feb 2018 20:20:05 +0700 Subject: [PATCH 38/39] update changelog --- changelog.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 8d81b1d5..c62dc1ab 100644 --- a/changelog.md +++ b/changelog.md @@ -2,8 +2,13 @@ ## 0.8.3 -- Enhance indicat API() to wait for confirm or timeout from peer. -- Add BLEScanner filterService() for BLEService and BLEClientService +- Enhanced indicat API() to wait for confirm or timeout from peer. +- Added BLEScanner filterService() for BLEService and BLEClientService +- Enhanced bonding management to support central bond and re-connection +- Added BLEClientHidAdafruit implementation for client HID + - Added Central HID example +- Enhanced BLEHidGeneric/BLEHidAdafruit to support boot protocol mode. +- Fixed I2C lock-up when endTransmission() is called with empty txBuffer. ## 0.8.2 From 5a850a00cb9644e871560ae4aa39ede7f2a2aa7c Mon Sep 17 00:00:00 2001 From: hathach Date: Tue, 3 Apr 2018 14:56:20 +0700 Subject: [PATCH 39/39] fix changelog typo --- changelog.md | 2 +- cores/nRF5/wiring.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index c62dc1ab..2ddd7114 100644 --- a/changelog.md +++ b/changelog.md @@ -2,7 +2,7 @@ ## 0.8.3 -- Enhanced indicat API() to wait for confirm or timeout from peer. +- Enhanced indicate API() to wait for confirm or timeout from peer. - Added BLEScanner filterService() for BLEService and BLEClientService - Enhanced bonding management to support central bond and re-connection - Added BLEClientHidAdafruit implementation for client HID diff --git a/cores/nRF5/wiring.c b/cores/nRF5/wiring.c index 5d2509df..e7d881f8 100644 --- a/cores/nRF5/wiring.c +++ b/cores/nRF5/wiring.c @@ -36,6 +36,7 @@ void init( void ) // Retrieve bootloader version bootloaderVersion = BOOTLOADER_VERSION_REGISTER; + // Select Clock Source : XTAL or RC #if defined( USE_LFXO ) // 32Khz XTAL NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk);