2 Commits

Author SHA1 Message Date
h2zero
4c8a13afe4 Add secondary services as an include on the primary. 2021-09-13 08:39:59 -06:00
h2zero
79f442d24b Add secondary service capability. 2021-09-13 08:38:27 -06:00
28 changed files with 306 additions and 454 deletions

27
.travis.yml Normal file
View File

@@ -0,0 +1,27 @@
sudo: false
before_install:
- cd ${TMPDIR-/tmp}
- wget -q http://doxygen.nl/files/doxygen-1.9.0.src.tar.gz
- tar -xzvf doxygen-1.9.0.src.tar.gz
- mkdir doxygen_build
- cd doxygen_build
- cmake ../doxygen-1.9.0/
- make
- export PATH="${TMPDIR-/tmp}/doxygen_build/bin:$PATH"
- cd ${TRAVIS_BUILD_DIR}
branches:
only:
- master
script:
- doxygen ./docs/Doxyfile
deploy:
provider: pages
skip_cleanup: true
local_dir: docs/html
github_token: $GH_REPO_TOKEN
on:
branch: master

View File

@@ -1,27 +1,6 @@
# Changelog
All notable changes to this project will be documented in this file.
## [1.3.2] - 2022-01-15
### Fixed
- Initialize advertising complete callback in NimBLEAdvertising constructor.
- Clear client disconnect timer in constructor before initializing.
- Fix missing data when reading large values.
- Fix missing data in notifications when using a large MTU size and more than 270 bytes of data are sent.
- Workaround fix added for cases when the task notification value is not cleared, causing various functions that should block not to block.
### Added
- `NimBLEClient::getLastError` : Gets the error code of the last function call that produces a return code from the stack.
- `NimBLECharacteristic::notify` : Overload method to send notifications/indications with custom values.
- Added conditional checks for ESP32 specific functions/values to support use of the library on non-esp32 devices.
- Added an alias to use the callback name from the original library `onMtuChanged`.
- `NimBLEClient::setDataLen` and `NimBLEServer::setDataLen`: Data length extension support (IDF version >= 4.3.2 only)
- Config option to set logging level for esp-nimble-cpp
### Changed
- Critical section calls now use the NimBLE API instead of FreeRTOS directly. This removes the need for a `portMUX_TYPE` variable in the class definitions.
- Removed unnecessary variables in `NimBLEService` and changed the constructor no no longer accept `numHandles` and `inst_id` parameters.
All notable changes to this project will be documented in this file.
## [1.3.1] - 2021-08-04

26
Kconfig
View File

@@ -1,31 +1,5 @@
menu "ESP-NimBLE-CPP configuration"
choice NIMBLE_CPP_LOG_LEVEL
prompt "NimBLE CPP log verbosity"
default NIMBLE_CPP_LOG_LEVEL_NONE
help
Select NimBLE CPP log verbosity level.
config NIMBLE_CPP_LOG_LEVEL_NONE
bool "No logs"
config NIMBLE_CPP_LOG_LEVEL_ERROR
bool "Error logs"
config NIMBLE_CPP_LOG_LEVEL_WARNING
bool "Warning logs"
config NIMBLE_CPP_LOG_LEVEL_INFO
bool "Info logs"
config NIMBLE_CPP_LOG_LEVEL_DEBUG
bool "Debug logs"
endchoice #NIMBLE_CPP_LOG_LEVEL
config NIMBLE_CPP_LOG_LEVEL
int
default 0 if NIMBLE_CPP_LOG_LEVEL_NONE
default 1 if NIMBLE_CPP_LOG_LEVEL_ERROR
default 2 if NIMBLE_CPP_LOG_LEVEL_WARNING
default 3 if NIMBLE_CPP_LOG_LEVEL_INFO
default 4 if NIMBLE_CPP_LOG_LEVEL_DEBUG
config NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT
bool "Show NimBLE return codes as text in debug log."
default "n"

View File

@@ -11,9 +11,11 @@
* Created on: Jul 3, 2017
* Author: kolban
*/
#include "sdkconfig.h"
#if defined(CONFIG_BT_ENABLED)
#include "nimconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
#if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
#include "NimBLEDevice.h"
#include "NimBLEAdvertisedDevice.h"
@@ -781,5 +783,7 @@ size_t NimBLEAdvertisedDevice::getPayloadLength() {
return m_payload.size();
} // getPayloadLength
#endif /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_CENTRAL */
#endif // #if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL)
#endif /* CONFIG_BT_ENABLED */

View File

@@ -29,7 +29,6 @@
#include <map>
#include <vector>
#include <time.h>
class NimBLEScan;

View File

@@ -69,7 +69,6 @@ void NimBLEAdvertising::reset() {
m_advDataSet = false;
// Set this to non-zero to prevent auto start if host reset before started by app.
m_duration = BLE_HS_FOREVER;
m_advCompCB = nullptr;
} // reset
@@ -655,8 +654,12 @@ bool NimBLEAdvertising::start(uint32_t duration, void (*advCompleteCB)(NimBLEAdv
break;
}
if(rc != 0) {
return false;
}
NIMBLE_LOGD(LOG_TAG, "<< Advertising start");
return (rc == 0);
return true;
} // start

View File

@@ -49,6 +49,7 @@ NimBLECharacteristic::NimBLECharacteristic(const NimBLEUUID &uuid, uint16_t prop
m_pCallbacks = &defaultCallback;
m_pService = pService;
m_value = "";
m_valMux = portMUX_INITIALIZER_UNLOCKED;
m_timestamp = 0;
m_removed = 0;
} // NimBLECharacteristic
@@ -234,12 +235,12 @@ NimBLEUUID NimBLECharacteristic::getUUID() {
* @return A std::string containing the current characteristic value.
*/
std::string NimBLECharacteristic::getValue(time_t *timestamp) {
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
std::string retVal = m_value;
if(timestamp != nullptr) {
*timestamp = m_timestamp;
}
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
return retVal;
} // getValue
@@ -250,9 +251,10 @@ std::string NimBLECharacteristic::getValue(time_t *timestamp) {
* @return The length of the current characteristic data.
*/
size_t NimBLECharacteristic::getDataLength() {
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
size_t len = m_value.length();
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
return len;
}
@@ -285,10 +287,11 @@ int NimBLECharacteristic::handleGapEvent(uint16_t conn_handle, uint16_t attr_han
pCharacteristic->m_pCallbacks->onRead(pCharacteristic, &desc);
}
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&pCharacteristic->m_valMux);
rc = os_mbuf_append(ctxt->om, (uint8_t*)pCharacteristic->m_value.data(),
pCharacteristic->m_value.length());
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&pCharacteristic->m_valMux);
return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
}
@@ -394,7 +397,6 @@ void NimBLECharacteristic::indicate() {
NIMBLE_LOGD(LOG_TAG, "<< indicate");
} // indicate
/**
* @brief Send a notification.\n
* A notification is a transmission of up to the first 20 bytes of the characteristic value.\n
@@ -402,18 +404,8 @@ void NimBLECharacteristic::indicate() {
* @param[in] is_notification if true sends a notification, false sends an indication.
*/
void NimBLECharacteristic::notify(bool is_notification) {
notify(getValue(), is_notification);
}
NIMBLE_LOGD(LOG_TAG, ">> notify: length: %d", getDataLength());
/**
* @brief Send a notification.\n
* A notification is a transmission of up to the first 20 bytes of the characteristic value.\n
* A notification will not block; it is a fire and forget.
* @param[in] is_notification if true sends a notification, false sends an indication.
*/
void NimBLECharacteristic::notify(std::string value, bool is_notification) {
size_t length = value.length();
NIMBLE_LOGD(LOG_TAG, ">> notify: length: %d", length);
if(!(m_properties & NIMBLE_PROPERTY::NOTIFY) &&
!(m_properties & NIMBLE_PROPERTY::INDICATE))
@@ -430,13 +422,15 @@ void NimBLECharacteristic::notify(std::string value, bool is_notification) {
m_pCallbacks->onNotify(this);
std::string value = getValue();
size_t length = value.length();
bool reqSec = (m_properties & BLE_GATT_CHR_F_READ_AUTHEN) ||
(m_properties & BLE_GATT_CHR_F_READ_AUTHOR) ||
(m_properties & BLE_GATT_CHR_F_READ_ENC);
int rc = 0;
for (auto &it : m_subscribedVec) {
uint16_t _mtu = getService()->getServer()->getPeerMTU(it.first) - 3;
uint16_t _mtu = getService()->getServer()->getPeerMTU(it.first);
// check if connected and subscribed
if(_mtu == 0 || it.second == 0) {
@@ -452,8 +446,8 @@ void NimBLECharacteristic::notify(std::string value, bool is_notification) {
}
}
if (length > _mtu) {
NIMBLE_LOGW(LOG_TAG, "- Truncating to %d bytes (maximum notify size)", _mtu);
if (length > _mtu - 3) {
NIMBLE_LOGW(LOG_TAG, "- Truncating to %d bytes (maximum notify size)", _mtu - 3);
}
if(is_notification && (!(it.second & NIMBLE_SUB_NOTIFY))) {
@@ -520,7 +514,7 @@ NimBLECharacteristicCallbacks* NimBLECharacteristic::getCallbacks() {
* @param [in] length The length of the data in bytes.
*/
void NimBLECharacteristic::setValue(const uint8_t* data, size_t length) {
#if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 4
#if CONFIG_LOG_DEFAULT_LEVEL > 3 || (ARDUINO_ARCH_ESP32 && CORE_DEBUG_LEVEL >= 4)
char* pHex = NimBLEUtils::buildHexData(nullptr, data, length);
NIMBLE_LOGD(LOG_TAG, ">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str());
free(pHex);
@@ -532,10 +526,10 @@ void NimBLECharacteristic::setValue(const uint8_t* data, size_t length) {
}
time_t t = time(nullptr);
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
m_value = std::string((char*)data, length);
m_timestamp = t;
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
NIMBLE_LOGD(LOG_TAG, "<< setValue");
} // setValue

View File

@@ -84,8 +84,6 @@ public:
void indicate();
void notify(bool is_notification = true);
void notify(std::string value, bool is_notification = true);
size_t getSubscribedCount();
NimBLEDescriptor* createDescriptor(const char* uuid,
@@ -155,6 +153,7 @@ private:
NimBLEService* m_pService;
std::string m_value;
std::vector<NimBLEDescriptor*> m_dscVec;
portMUX_TYPE m_valMux;
time_t m_timestamp;
uint8_t m_removed;

View File

@@ -20,7 +20,6 @@
#include <string>
#include <unordered_set>
#include <climits>
#if defined(CONFIG_NIMBLE_CPP_IDF)
#include "nimble/nimble_port.h"
@@ -64,7 +63,6 @@ NimBLEClient::NimBLEClient(const NimBLEAddress &peerAddress) : m_peerAddress(pee
m_deleteCallbacks = false;
m_pTaskData = nullptr;
m_connEstablished = false;
m_lastErr = 0;
m_pConnParams.scan_itvl = 16; // Scan interval in 0.625ms units (NimBLE Default)
m_pConnParams.scan_window = 16; // Scan window in 0.625ms units (NimBLE Default)
@@ -75,7 +73,6 @@ NimBLEClient::NimBLEClient(const NimBLEAddress &peerAddress) : m_peerAddress(pee
m_pConnParams.min_ce_len = BLE_GAP_INITIAL_CONN_MIN_CE_LEN; // Minimum length of connection event in 0.625ms units
m_pConnParams.max_ce_len = BLE_GAP_INITIAL_CONN_MAX_CE_LEN; // Maximum length of connection event in 0.625ms units
memset(&m_dcTimer, 0, sizeof(m_dcTimer));
ble_npl_callout_init(&m_dcTimer, nimble_port_get_dflt_eventq(),
NimBLEClient::dcTimerCb, this);
} // NimBLEClient
@@ -208,8 +205,7 @@ bool NimBLEClient::connect(const NimBLEAddress &address, bool deleteAttibutes) {
m_peerAddress = address;
}
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
m_pTaskData = &taskData;
int rc = 0;
@@ -255,17 +251,11 @@ bool NimBLEClient::connect(const NimBLEAddress &address, bool deleteAttibutes) {
} while (rc == BLE_HS_EBUSY);
m_lastErr = rc;
if(rc != 0) {
m_pTaskData = nullptr;
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
// Wait for the connect timeout time +1 second for the connection to complete
if(ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(m_connectTimeout + 1000)) == pdFALSE) {
m_pTaskData = nullptr;
@@ -283,7 +273,6 @@ bool NimBLEClient::connect(const NimBLEAddress &address, bool deleteAttibutes) {
return false;
} else if(taskData.rc != 0){
m_lastErr = taskData.rc;
NIMBLE_LOGE(LOG_TAG, "Connection failed; status=%d %s",
taskData.rc,
NimBLEUtils::returnCodeToString(taskData.rc));
@@ -316,8 +305,7 @@ bool NimBLEClient::connect(const NimBLEAddress &address, bool deleteAttibutes) {
* @return True on success.
*/
bool NimBLEClient::secureConnection() {
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
int retryCount = 1;
@@ -326,20 +314,14 @@ bool NimBLEClient::secureConnection() {
int rc = NimBLEDevice::startSecurity(m_conn_id);
if(rc != 0){
m_lastErr = rc;
m_pTaskData = nullptr;
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
} while (taskData.rc == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING) && retryCount--);
if(taskData.rc != 0){
m_lastErr = taskData.rc;
return false;
}
@@ -390,7 +372,6 @@ int NimBLEClient::disconnect(uint8_t reason) {
}
NIMBLE_LOGD(LOG_TAG, "<< disconnect()");
m_lastErr = rc;
return rc;
} // disconnect
@@ -464,17 +445,12 @@ void NimBLEClient::updateConnParams(uint16_t minInterval, uint16_t maxInterval,
* @param [in] tx_octets The preferred number of payload octets to use (Range 0x001B-0x00FB).
*/
void NimBLEClient::setDataLen(uint16_t tx_octets) {
#if defined(CONFIG_NIMBLE_CPP_IDF) && defined(ESP_IDF_VERSION) && \
ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4,3,2)
return;
#else
uint16_t tx_time = (tx_octets + 14) * 8;
int rc = ble_gap_set_data_len(m_conn_id, tx_octets, tx_time);
if(rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Set data length error: %d, %s", rc, NimBLEUtils::returnCodeToString(rc));
}
#endif
} // setDataLen
@@ -554,7 +530,6 @@ int NimBLEClient::getRssi() {
if(rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Failed to read RSSI error code: %d, %s",
rc, NimBLEUtils::returnCodeToString(rc));
m_lastErr = rc;
return 0;
}
@@ -682,8 +657,7 @@ bool NimBLEClient::retrieveServices(const NimBLEUUID *uuid_filter) {
}
int rc = 0;
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
if(uuid_filter == nullptr) {
rc = ble_gattc_disc_all_svcs(m_conn_id, NimBLEClient::serviceDiscoveredCB, &taskData);
@@ -694,18 +668,11 @@ bool NimBLEClient::retrieveServices(const NimBLEUUID *uuid_filter) {
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "ble_gattc_disc_all_svcs: rc=%d %s", rc, NimBLEUtils::returnCodeToString(rc));
m_lastErr = rc;
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
// wait until we have all the services
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
m_lastErr = taskData.rc;
if(taskData.rc == 0){
NIMBLE_LOGD(LOG_TAG, "<< retrieveServices");
@@ -975,18 +942,19 @@ uint16_t NimBLEClient::getMTU() {
NIMBLE_LOGD(LOG_TAG, "Got Notification for characteristic %s",
(*characteristic)->toString().c_str());
uint32_t data_len = OS_MBUF_PKTLEN(event->notify_rx.om);
time_t t = time(nullptr);
ble_npl_hw_enter_critical();
(*characteristic)->m_value = std::string((char *)event->notify_rx.om->om_data, data_len);
portENTER_CRITICAL(&(*characteristic)->m_valMux);
(*characteristic)->m_value = std::string((char *)event->notify_rx.om->om_data,
event->notify_rx.om->om_len);
(*characteristic)->m_timestamp = t;
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&(*characteristic)->m_valMux);
if ((*characteristic)->m_notifyCallback != nullptr) {
NIMBLE_LOGD(LOG_TAG, "Invoking callback for notification on characteristic %s",
(*characteristic)->toString().c_str());
(*characteristic)->m_notifyCallback(*characteristic, event->notify_rx.om->om_data,
data_len, !event->notify_rx.indication);
event->notify_rx.om->om_len,
!event->notify_rx.indication);
}
break;
}
@@ -1186,15 +1154,6 @@ std::string NimBLEClient::toString() {
} // toString
/**
* @brief Get the last error code reported by the NimBLE host
* @return int, the NimBLE error code.
*/
int NimBLEClient::getLastError() {
return m_lastErr;
} // getLastError
void NimBLEClientCallbacks::onConnect(NimBLEClient* pClient) {
NIMBLE_LOGD("NimBLEClientCallbacks", "onConnect: default");
}

View File

@@ -71,7 +71,6 @@ public:
void setDataLen(uint16_t tx_octets);
void discoverAttributes();
NimBLEConnInfo getConnInfo();
int getLastError();
private:
NimBLEClient(const NimBLEAddress &peerAddress);
@@ -89,7 +88,6 @@ private:
bool retrieveServices(const NimBLEUUID *uuid_filter = nullptr);
NimBLEAddress m_peerAddress;
int m_lastErr;
uint16_t m_conn_id;
bool m_connEstablished;
bool m_deleteCallbacks;

View File

@@ -49,6 +49,7 @@ NimBLEDescriptor::NimBLEDescriptor(NimBLEUUID uuid, uint16_t properties, uint16_
m_pCharacteristic = pCharacteristic;
m_pCallbacks = &defaultCallbacks; // No initial callback.
m_value.attr_value = (uint8_t*) calloc(max_len,1); // Allocate storage for the value.
m_valMux = portMUX_INITIALIZER_UNLOCKED;
m_properties = 0;
m_removed = 0;
@@ -142,9 +143,6 @@ NimBLECharacteristic* NimBLEDescriptor::getCharacteristic() {
int NimBLEDescriptor::handleGapEvent(uint16_t conn_handle, uint16_t attr_handle,
struct ble_gatt_access_ctxt *ctxt, void *arg) {
(void)conn_handle;
(void)attr_handle;
const ble_uuid_t *uuid;
int rc;
NimBLEDescriptor* pDescriptor = (NimBLEDescriptor*)arg;
@@ -161,10 +159,9 @@ int NimBLEDescriptor::handleGapEvent(uint16_t conn_handle, uint16_t attr_handle,
if(ctxt->om->om_pkthdr_len > 8) {
pDescriptor->m_pCallbacks->onRead(pDescriptor);
}
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&pDescriptor->m_valMux);
rc = os_mbuf_append(ctxt->om, pDescriptor->getValue(), pDescriptor->getLength());
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&pDescriptor->m_valMux);
return rc == 0 ? 0 : BLE_ATT_ERR_INSUFFICIENT_RES;
}
@@ -235,12 +232,10 @@ void NimBLEDescriptor::setValue(const uint8_t* data, size_t length) {
NIMBLE_LOGE(LOG_TAG, "Size %d too large, must be no bigger than %d", length, m_value.attr_max_len);
return;
}
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
m_value.attr_len = length;
memcpy(m_value.attr_value, data, length);
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
} // setValue
@@ -280,7 +275,6 @@ NimBLEDescriptorCallbacks::~NimBLEDescriptorCallbacks() {}
* @param [in] pDescriptor The descriptor that is the source of the event.
*/
void NimBLEDescriptorCallbacks::onRead(NimBLEDescriptor* pDescriptor) {
(void)pDescriptor;
NIMBLE_LOGD("NimBLEDescriptorCallbacks", "onRead: default");
} // onRead
@@ -290,7 +284,6 @@ void NimBLEDescriptorCallbacks::onRead(NimBLEDescriptor* pDescriptor) {
* @param [in] pDescriptor The descriptor that is the source of the event.
*/
void NimBLEDescriptorCallbacks::onWrite(NimBLEDescriptor* pDescriptor) {
(void)pDescriptor;
NIMBLE_LOGD("NimBLEDescriptorCallbacks", "onWrite: default");
} // onWrite

View File

@@ -90,6 +90,7 @@ private:
NimBLECharacteristic* m_pCharacteristic;
uint8_t m_properties;
attr_value_t m_value;
portMUX_TYPE m_valMux;
uint8_t m_removed;
}; // NimBLEDescriptor

View File

@@ -18,38 +18,32 @@
#include "NimBLEDevice.h"
#include "NimBLEUtils.h"
#ifdef ESP_PLATFORM
# include "esp_err.h"
# include "esp_bt.h"
# include "nvs_flash.h"
# if defined(CONFIG_NIMBLE_CPP_IDF)
# include "esp_nimble_hci.h"
# include "nimble/nimble_port.h"
# include "nimble/nimble_port_freertos.h"
# include "host/ble_hs.h"
# include "host/ble_hs_pvcy.h"
# include "host/util/util.h"
# include "services/gap/ble_svc_gap.h"
# include "services/gatt/ble_svc_gatt.h"
# else
# include "nimble/esp_port/esp-hci/include/esp_nimble_hci.h"
# endif
#include "esp_err.h"
#include "esp_bt.h"
#include "nvs_flash.h"
#if defined(CONFIG_NIMBLE_CPP_IDF)
#include "esp_nimble_hci.h"
#include "nimble/nimble_port.h"
#include "nimble/nimble_port_freertos.h"
#include "host/ble_hs.h"
#include "host/ble_hs_pvcy.h"
#include "host/util/util.h"
#include "services/gap/ble_svc_gap.h"
#include "services/gatt/ble_svc_gatt.h"
#else
# include "nimble/nimble/controller/include/controller/ble_phy.h"
#include "nimble/esp_port/esp-hci/include/esp_nimble_hci.h"
#include "nimble/porting/nimble/include/nimble/nimble_port.h"
#include "nimble/porting/npl/freertos/include/nimble/nimble_port_freertos.h"
#include "nimble/nimble/host/include/host/ble_hs.h"
#include "nimble/nimble/host/include/host/ble_hs_pvcy.h"
#include "nimble/nimble/host/util/include/host/util/util.h"
#include "nimble/nimble/host/services/gap/include/services/gap/ble_svc_gap.h"
#include "nimble/nimble/host/services/gatt/include/services/gatt/ble_svc_gatt.h"
#endif
#ifndef CONFIG_NIMBLE_CPP_IDF
# include "nimble/porting/nimble/include/nimble/nimble_port.h"
# include "nimble/porting/npl/freertos/include/nimble/nimble_port_freertos.h"
# include "nimble/nimble/host/include/host/ble_hs.h"
# include "nimble/nimble/host/include/host/ble_hs_pvcy.h"
# include "nimble/nimble/host/util/include/host/util/util.h"
# include "nimble/nimble/host/services/gap/include/services/gap/ble_svc_gap.h"
# include "nimble/nimble/host/services/gatt/include/services/gatt/ble_svc_gatt.h"
#endif
#if defined(ESP_PLATFORM) && defined(CONFIG_ENABLE_ARDUINO_DEPENDS)
# include "esp32-hal-bt.h"
#ifdef CONFIG_ENABLE_ARDUINO_DEPENDS
#include "esp32-hal-bt.h"
#endif
#include "NimBLELog.h"
@@ -81,10 +75,9 @@ std::list <NimBLEAddress> NimBLEDevice::m_ignoreList;
std::vector<NimBLEAddress> NimBLEDevice::m_whiteList;
NimBLESecurityCallbacks* NimBLEDevice::m_securityCallbacks = nullptr;
uint8_t NimBLEDevice::m_own_addr_type = BLE_OWN_ADDR_PUBLIC;
#ifdef ESP_PLATFORM
uint16_t NimBLEDevice::m_scanDuplicateSize = CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE;
uint8_t NimBLEDevice::m_scanFilterMode = CONFIG_BTDM_SCAN_DUPL_TYPE;
#endif
/**
* @brief Create a new instance of a server.
@@ -149,8 +142,7 @@ void NimBLEDevice::stopAdvertising() {
* try and release/delete it.
*/
#if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER)
/* STATIC */
NimBLEScan* NimBLEDevice::getScan() {
/* STATIC */ NimBLEScan* NimBLEDevice::getScan() {
if (m_pScan == nullptr) {
m_pScan = new NimBLEScan();
}
@@ -167,8 +159,7 @@ NimBLEScan* NimBLEDevice::getScan() {
* @return A reference to the new client object.
*/
#if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
/* STATIC */
NimBLEClient* NimBLEDevice::createClient(NimBLEAddress peerAddress) {
/* STATIC */ NimBLEClient* NimBLEDevice::createClient(NimBLEAddress peerAddress) {
if(m_cList.size() >= NIMBLE_MAX_CONNECTIONS) {
NIMBLE_LOGW(LOG_TAG,"Number of clients exceeds Max connections. Cur=%d Max=%d",
m_cList.size(), NIMBLE_MAX_CONNECTIONS);
@@ -186,8 +177,7 @@ NimBLEClient* NimBLEDevice::createClient(NimBLEAddress peerAddress) {
* Checks if it is connected or trying to connect and disconnects/stops it first.
* @param [in] pClient A pointer to the client object.
*/
/* STATIC */
bool NimBLEDevice::deleteClient(NimBLEClient* pClient) {
/* STATIC */ bool NimBLEDevice::deleteClient(NimBLEClient* pClient) {
if(pClient == nullptr) {
return false;
}
@@ -231,8 +221,7 @@ bool NimBLEDevice::deleteClient(NimBLEClient* pClient) {
* @brief Get the list of created client objects.
* @return A pointer to the list of clients.
*/
/* STATIC */
std::list<NimBLEClient*>* NimBLEDevice::getClientList() {
/* STATIC */std::list<NimBLEClient*>* NimBLEDevice::getClientList() {
return &m_cList;
} // getClientList
@@ -241,8 +230,7 @@ std::list<NimBLEClient*>* NimBLEDevice::getClientList() {
* @brief Get the number of created client objects.
* @return Number of client objects created.
*/
/* STATIC */
size_t NimBLEDevice::getClientListSize() {
/* STATIC */size_t NimBLEDevice::getClientListSize() {
return m_cList.size();
} // getClientList
@@ -252,8 +240,7 @@ size_t NimBLEDevice::getClientListSize() {
* @param [in] conn_id The client connection ID to search for.
* @return A pointer to the client object with the spcified connection ID.
*/
/* STATIC */
NimBLEClient* NimBLEDevice::getClientByID(uint16_t conn_id) {
/* STATIC */NimBLEClient* NimBLEDevice::getClientByID(uint16_t conn_id) {
for(auto it = m_cList.cbegin(); it != m_cList.cend(); ++it) {
if((*it)->getConnId() == conn_id) {
return (*it);
@@ -269,8 +256,7 @@ NimBLEClient* NimBLEDevice::getClientByID(uint16_t conn_id) {
* @param [in] peer_addr The address of the peer to search for.
* @return A pointer to the client object with the peer address.
*/
/* STATIC */
NimBLEClient* NimBLEDevice::getClientByPeerAddress(const NimBLEAddress &peer_addr) {
/* STATIC */NimBLEClient* NimBLEDevice::getClientByPeerAddress(const NimBLEAddress &peer_addr) {
for(auto it = m_cList.cbegin(); it != m_cList.cend(); ++it) {
if((*it)->getPeerAddress().equals(peer_addr)) {
return (*it);
@@ -284,8 +270,7 @@ NimBLEClient* NimBLEDevice::getClientByPeerAddress(const NimBLEAddress &peer_add
* @brief Finds the first disconnected client in the list.
* @return A pointer to the first client object that is not connected to a peer.
*/
/* STATIC */
NimBLEClient* NimBLEDevice::getDisconnectedClient() {
/* STATIC */NimBLEClient* NimBLEDevice::getDisconnectedClient() {
for(auto it = m_cList.cbegin(); it != m_cList.cend(); ++it) {
if(!(*it)->isConnected()) {
return (*it);
@@ -296,7 +281,7 @@ NimBLEClient* NimBLEDevice::getDisconnectedClient() {
#endif // #if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL)
#ifdef ESP_PLATFORM
/**
* @brief Set the transmission power.
* @param [in] powerLevel The power level to set, can be one of:
@@ -322,15 +307,12 @@ NimBLEClient* NimBLEDevice::getDisconnectedClient() {
* * ESP_BLE_PWR_TYPE_SCAN = 10, For scan
* * ESP_BLE_PWR_TYPE_DEFAULT = 11, For default, if not set other, it will use default value
*/
/* STATIC */
void NimBLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) {
/* STATIC */ void NimBLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) {
NIMBLE_LOGD(LOG_TAG, ">> setPower: %d (type: %d)", powerLevel, powerType);
esp_err_t errRc = esp_ble_tx_power_set(powerType, powerLevel);
if (errRc != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_ble_tx_power_set: rc=%d", errRc);
}
NIMBLE_LOGD(LOG_TAG, "<< setPower");
} // setPower
@@ -352,8 +334,9 @@ void NimBLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t p
* * ESP_BLE_PWR_TYPE_DEFAULT = 11, For default, if not set other, it will use default value
* @return the power level currently used by the type specified.
*/
/* STATIC */
int NimBLEDevice::getPower(esp_ble_power_type_t powerType) {
/* STATIC */ int NimBLEDevice::getPower(esp_ble_power_type_t powerType) {
switch(esp_ble_tx_power_get(powerType)) {
case ESP_PWR_LVL_N12:
return -12;
@@ -376,25 +359,13 @@ int NimBLEDevice::getPower(esp_ble_power_type_t powerType) {
}
} // getPower
#else
void NimBLEDevice::setPower(int dbm) {
ble_phy_txpwr_set(dbm);
}
int NimBLEDevice::getPower() {
return ble_phy_txpwr_get();
}
#endif
/**
* @brief Get our device address.
* @return A NimBLEAddress object of our public address if we have one,
* if not then our current random address.
*/
/* STATIC*/
NimBLEAddress NimBLEDevice::getAddress() {
/* STATIC*/ NimBLEAddress NimBLEDevice::getAddress() {
ble_addr_t addr = {BLE_ADDR_PUBLIC, 0};
if(BLE_HS_ENOADDR == ble_hs_id_copy_addr(BLE_ADDR_PUBLIC, addr.val, NULL)) {
@@ -411,8 +382,7 @@ NimBLEAddress NimBLEDevice::getAddress() {
* @brief Return a string representation of the address of this device.
* @return A string representation of this device address.
*/
/* STATIC */
std::string NimBLEDevice::toString() {
/* STATIC */ std::string NimBLEDevice::toString() {
return getAddress().toString();
} // toString
@@ -422,8 +392,7 @@ std::string NimBLEDevice::toString() {
* @param [in] mtu Value to set local mtu:
* * This should be larger than 23 and lower or equal to BLE_ATT_MTU_MAX = 527.
*/
/* STATIC */
int NimBLEDevice::setMTU(uint16_t mtu) {
/* STATIC */int NimBLEDevice::setMTU(uint16_t mtu) {
NIMBLE_LOGD(LOG_TAG, ">> setLocalMTU: %d", mtu);
int rc = ble_att_set_preferred_mtu(mtu);
@@ -441,13 +410,11 @@ int NimBLEDevice::setMTU(uint16_t mtu) {
* @brief Get local MTU value set.
* @return The current preferred MTU setting.
*/
/* STATIC */
uint16_t NimBLEDevice::getMTU() {
/* STATIC */uint16_t NimBLEDevice::getMTU() {
return ble_att_preferred_mtu();
}
#ifdef ESP_PLATFORM
/**
* @brief Set the duplicate filter cache size for filtering scanned devices.
* @param [in] cacheSize The number of advertisements filtered before the cache is reset.\n
@@ -493,7 +460,6 @@ void NimBLEDevice::setScanFilterMode(uint8_t mode) {
m_scanFilterMode = mode;
}
#endif
#if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL) || defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
/**
@@ -516,7 +482,7 @@ int NimBLEDevice::getNumBonds() {
/**
* @brief Deletes all bonding information.
*/
/*STATIC*/
/*STATIC*/
void NimBLEDevice::deleteAllBonds() {
ble_store_clear();
}
@@ -596,7 +562,6 @@ NimBLEAddress NimBLEDevice::getBondedAddress(int index) {
* @param [in] address The address to check for in the whitelist.
* @returns true if the address is in the whitelist.
*/
/*STATIC*/
bool NimBLEDevice::onWhiteList(const NimBLEAddress & address) {
for (auto &it : m_whiteList) {
if (it == address) {
@@ -613,7 +578,6 @@ bool NimBLEDevice::onWhiteList(const NimBLEAddress & address) {
* @param [in] address The address to add to the whitelist.
* @returns true if successful.
*/
/*STATIC*/
bool NimBLEDevice::whiteListAdd(const NimBLEAddress & address) {
if (NimBLEDevice::onWhiteList(address)) {
return true;
@@ -645,7 +609,6 @@ bool NimBLEDevice::whiteListAdd(const NimBLEAddress & address) {
* @param [in] address The address to remove from the whitelist.
* @returns true if successful.
*/
/*STATIC*/
bool NimBLEDevice::whiteListRemove(const NimBLEAddress & address) {
if (!NimBLEDevice::onWhiteList(address)) {
return true;
@@ -685,7 +648,6 @@ bool NimBLEDevice::whiteListRemove(const NimBLEAddress & address) {
* @brief Gets the count of addresses in the whitelist.
* @returns The number of addresses in the whitelist.
*/
/*STATIC*/
size_t NimBLEDevice::getWhiteListCount() {
return m_whiteList.size();
}
@@ -696,7 +658,6 @@ size_t NimBLEDevice::getWhiteListCount() {
* @param [in] index The vector index to retrieve the address from.
* @returns the NimBLEAddress at the whitelist index or nullptr if not found.
*/
/*STATIC*/
NimBLEAddress NimBLEDevice::getWhiteListAddress(size_t index) {
if (index > m_whiteList.size()) {
NIMBLE_LOGE(LOG_TAG, "Invalid index; %u", index);
@@ -710,8 +671,7 @@ NimBLEAddress NimBLEDevice::getWhiteListAddress(size_t index) {
* @brief Host reset, we pass the message so we don't make calls until resynced.
* @param [in] reason The reason code for the reset.
*/
/* STATIC */
void NimBLEDevice::onReset(int reason)
/* STATIC */ void NimBLEDevice::onReset(int reason)
{
if(!m_synced) {
return;
@@ -735,8 +695,7 @@ void NimBLEDevice::onReset(int reason)
/**
* @brief Host resynced with controller, all clear to make calls to the stack.
*/
/* STATIC */
void NimBLEDevice::onSync(void)
/* STATIC */ void NimBLEDevice::onSync(void)
{
NIMBLE_LOGI(LOG_TAG, "NimBle host synced.");
// This check is needed due to potentially being called multiple times in succession
@@ -749,14 +708,6 @@ void NimBLEDevice::onSync(void)
int rc = ble_hs_util_ensure_addr(0);
assert(rc == 0);
#ifndef ESP_PLATFORM
rc = ble_hs_id_infer_auto(m_own_addr_type, &m_own_addr_type);
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "error determining address type; rc=%d", rc);
return;
}
#endif
// Yield for houskeeping before returning to operations.
// Occasionally triggers exception without.
taskYIELD();
@@ -782,11 +733,9 @@ void NimBLEDevice::onSync(void)
/**
* @brief The main host task.
*/
/* STATIC */
void NimBLEDevice::host_task(void *param)
/* STATIC */ void NimBLEDevice::host_task(void *param)
{
NIMBLE_LOGI(LOG_TAG, "BLE Host Task Started");
/* This function will return only when nimble_port_stop() is executed */
nimble_port_run();
@@ -798,11 +747,9 @@ void NimBLEDevice::host_task(void *param)
* @brief Initialize the %BLE environment.
* @param [in] deviceName The device name of the device.
*/
/* STATIC */
void NimBLEDevice::init(const std::string &deviceName) {
/* STATIC */ void NimBLEDevice::init(const std::string &deviceName) {
if(!initialized){
int rc=0;
#ifdef ESP_PLATFORM
esp_err_t errRc = ESP_OK;
#ifdef CONFIG_ENABLE_ARDUINO_DEPENDS
@@ -822,7 +769,7 @@ void NimBLEDevice::init(const std::string &deviceName) {
esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
#if defined (CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32S3)
#ifdef CONFIG_IDF_TARGET_ESP32C3
bt_cfg.bluetooth_mode = ESP_BT_MODE_BLE;
#else
bt_cfg.mode = ESP_BT_MODE_BLE;
@@ -834,7 +781,6 @@ void NimBLEDevice::init(const std::string &deviceName) {
ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg));
ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_BLE));
ESP_ERROR_CHECK(esp_nimble_hci_init());
#endif
nimble_port_init();
// Setup callbacks for host events
@@ -859,10 +805,9 @@ void NimBLEDevice::init(const std::string &deviceName) {
nimble_port_freertos_init(NimBLEDevice::host_task);
}
// Wait for host and controller to sync before returning and accepting new tasks
while(!m_synced){
taskYIELD();
vTaskDelay(1 / portTICK_PERIOD_MS);
}
initialized = true; // Set the initialization flag to ensure we are only initialized once.
@@ -874,17 +819,16 @@ void NimBLEDevice::init(const std::string &deviceName) {
* @param [in] clearAll If true, deletes all server/advertising/scan/client objects after deinitializing.
* @note If clearAll is true when called, any references to the created objects become invalid.
*/
/* STATIC */
void NimBLEDevice::deinit(bool clearAll) {
/* STATIC */ void NimBLEDevice::deinit(bool clearAll) {
int ret = nimble_port_stop();
if (ret == 0) {
nimble_port_deinit();
#ifdef ESP_PLATFORM
ret = esp_nimble_hci_and_controller_deinit();
if (ret != ESP_OK) {
NIMBLE_LOGE(LOG_TAG, "esp_nimble_hci_and_controller_deinit() failed with error: %d", ret);
}
#endif
initialized = false;
m_synced = false;
@@ -931,7 +875,6 @@ void NimBLEDevice::deinit(bool clearAll) {
* @brief Check if the initialization is complete.
* @return true if initialized.
*/
/*STATIC*/
bool NimBLEDevice::getInitialized() {
return initialized;
} // getInitialized
@@ -943,8 +886,7 @@ bool NimBLEDevice::getInitialized() {
* @param mitm If true we are capable of man in the middle protection, false if not.
* @param sc If true we will perform secure connection pairing, false we will use legacy pairing.
*/
/*STATIC*/
void NimBLEDevice::setSecurityAuth(bool bonding, bool mitm, bool sc) {
/*STATIC*/ void NimBLEDevice::setSecurityAuth(bool bonding, bool mitm, bool sc) {
NIMBLE_LOGD(LOG_TAG, "Setting bonding: %d, mitm: %d, sc: %d",bonding,mitm,sc);
ble_hs_cfg.sm_bonding = bonding;
ble_hs_cfg.sm_mitm = mitm;
@@ -961,8 +903,7 @@ void NimBLEDevice::setSecurityAuth(bool bonding, bool mitm, bool sc) {
* * 0x08 BLE_SM_PAIR_AUTHREQ_SC
* * 0x10 BLE_SM_PAIR_AUTHREQ_KEYPRESS - not yet supported.
*/
/*STATIC*/
void NimBLEDevice::setSecurityAuth(uint8_t auth_req) {
/*STATIC*/void NimBLEDevice::setSecurityAuth(uint8_t auth_req) {
NimBLEDevice::setSecurityAuth((auth_req & BLE_SM_PAIR_AUTHREQ_BOND)>0,
(auth_req & BLE_SM_PAIR_AUTHREQ_MITM)>0,
(auth_req & BLE_SM_PAIR_AUTHREQ_SC)>0);
@@ -978,8 +919,7 @@ void NimBLEDevice::setSecurityAuth(uint8_t auth_req) {
* * 0x03 BLE_HS_IO_NO_INPUT_OUTPUT NoInputNoOutput IO capability
* * 0x04 BLE_HS_IO_KEYBOARD_DISPLAY KeyboardDisplay Only IO capability
*/
/*STATIC*/
void NimBLEDevice::setSecurityIOCap(uint8_t iocap) {
/*STATIC*/ void NimBLEDevice::setSecurityIOCap(uint8_t iocap) {
ble_hs_cfg.sm_io_cap = iocap;
} // setSecurityIOCap
@@ -993,8 +933,7 @@ void NimBLEDevice::setSecurityIOCap(uint8_t iocap) {
* * 0x04: BLE_SM_PAIR_KEY_DIST_SIGN
* * 0x08: BLE_SM_PAIR_KEY_DIST_LINK
*/
/*STATIC*/
void NimBLEDevice::setSecurityInitKey(uint8_t init_key) {
/*STATIC*/void NimBLEDevice::setSecurityInitKey(uint8_t init_key) {
ble_hs_cfg.sm_our_key_dist = init_key;
} // setsSecurityInitKey
@@ -1008,8 +947,7 @@ void NimBLEDevice::setSecurityInitKey(uint8_t init_key) {
* * 0x04: BLE_SM_PAIR_KEY_DIST_SIGN
* * 0x08: BLE_SM_PAIR_KEY_DIST_LINK
*/
/*STATIC*/
void NimBLEDevice::setSecurityRespKey(uint8_t resp_key) {
/*STATIC*/void NimBLEDevice::setSecurityRespKey(uint8_t resp_key) {
ble_hs_cfg.sm_their_key_dist = resp_key;
} // setsSecurityRespKey
@@ -1018,8 +956,7 @@ void NimBLEDevice::setSecurityRespKey(uint8_t resp_key) {
* @brief Set the passkey the server will ask for when pairing.
* @param [in] pin The passkey to use.
*/
/*STATIC*/
void NimBLEDevice::setSecurityPasskey(uint32_t pin) {
/*STATIC*/void NimBLEDevice::setSecurityPasskey(uint32_t pin) {
m_passkey = pin;
} // setSecurityPasskey
@@ -1028,8 +965,7 @@ void NimBLEDevice::setSecurityPasskey(uint32_t pin) {
* @brief Get the current passkey used for pairing.
* @return The current passkey.
*/
/*STATIC*/
uint32_t NimBLEDevice::getSecurityPasskey() {
/*STATIC*/uint32_t NimBLEDevice::getSecurityPasskey() {
return m_passkey;
} // getSecurityPasskey
@@ -1039,13 +975,11 @@ uint32_t NimBLEDevice::getSecurityPasskey() {
* @param [in] callbacks Pointer to NimBLESecurityCallbacks class
* @deprecated For backward compatibility, New code should use client/server callback methods.
*/
/*STATIC*/
void NimBLEDevice::setSecurityCallbacks(NimBLESecurityCallbacks* callbacks) {
NimBLEDevice::m_securityCallbacks = callbacks;
} // setSecurityCallbacks
#ifdef ESP_PLATFORM
/**
* @brief Set the own address type.
* @param [in] own_addr_type Own Bluetooth Device address type.\n
@@ -1056,7 +990,6 @@ void NimBLEDevice::setSecurityCallbacks(NimBLESecurityCallbacks* callbacks) {
* * 0x03: BLE_OWN_ADDR_RPA_RANDOM_DEFAULT
* @param [in] useNRPA If true, and address type is random, uses a non-resolvable random address.
*/
/*STATIC*/
void NimBLEDevice::setOwnAddrType(uint8_t own_addr_type, bool useNRPA) {
m_own_addr_type = own_addr_type;
switch (own_addr_type) {
@@ -1080,15 +1013,18 @@ void NimBLEDevice::setOwnAddrType(uint8_t own_addr_type, bool useNRPA) {
break;
}
} // setOwnAddrType
#endif
/**
* @brief Start the connection securing and authorization for this connection.
* @param conn_id The connection id of the peer device.
* @returns NimBLE stack return code, 0 = success.
*/
/* STATIC */
int NimBLEDevice::startSecurity(uint16_t conn_id) {
/* STATIC */int NimBLEDevice::startSecurity(uint16_t conn_id) {
/* if(m_securityCallbacks != nullptr) {
m_securityCallbacks->onSecurityRequest();
}
*/
int rc = ble_gap_security_initiate(conn_id);
if(rc != 0){
NIMBLE_LOGE(LOG_TAG, "ble_gap_security_initiate: rc=%d %s", rc, NimBLEUtils::returnCodeToString(rc));
@@ -1103,8 +1039,7 @@ int NimBLEDevice::startSecurity(uint16_t conn_id) {
* @param [in] address The address to look for.
* @return True if ignoring.
*/
/*STATIC*/
bool NimBLEDevice::isIgnored(const NimBLEAddress &address) {
/*STATIC*/ bool NimBLEDevice::isIgnored(const NimBLEAddress &address) {
for(auto &it : m_ignoreList) {
if(it.equals(address)){
return true;
@@ -1119,8 +1054,7 @@ bool NimBLEDevice::isIgnored(const NimBLEAddress &address) {
* @brief Add a device to the ignore list.
* @param [in] address The address of the device we want to ignore.
*/
/*STATIC*/
void NimBLEDevice::addIgnored(const NimBLEAddress &address) {
/*STATIC*/ void NimBLEDevice::addIgnored(const NimBLEAddress &address) {
m_ignoreList.push_back(address);
}
@@ -1129,8 +1063,7 @@ void NimBLEDevice::addIgnored(const NimBLEAddress &address) {
* @brief Remove a device from the ignore list.
* @param [in] address The address of the device we want to remove from the list.
*/
/*STATIC*/
void NimBLEDevice::removeIgnored(const NimBLEAddress &address) {
/*STATIC*/void NimBLEDevice::removeIgnored(const NimBLEAddress &address) {
for(auto it = m_ignoreList.begin(); it != m_ignoreList.end(); ++it) {
if((*it).equals(address)){
m_ignoreList.erase(it);
@@ -1144,7 +1077,6 @@ void NimBLEDevice::removeIgnored(const NimBLEAddress &address) {
* @brief Set a custom callback for gap events.
* @param [in] handler The function to call when gap events occur.
*/
/*STATIC*/
void NimBLEDevice::setCustomGapHandler(gap_event_handler handler) {
m_customGapHandler = handler;
int rc = ble_gap_event_listener_register(&m_listener, m_customGapHandler, NULL);
@@ -1156,4 +1088,5 @@ void NimBLEDevice::setCustomGapHandler(gap_event_handler handler) {
}
} // setCustomGapHandler
#endif // CONFIG_BT_ENABLED

View File

@@ -38,9 +38,7 @@
#include "NimBLESecurity.h"
#include "NimBLEAddress.h"
#ifdef ESP_PLATFORM
# include "esp_bt.h"
#endif
#include "esp_bt.h"
#include <map>
#include <string>
@@ -111,17 +109,8 @@ public:
static NimBLEServer* getServer();
#endif
#ifdef ESP_PLATFORM
static void setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType=ESP_BLE_PWR_TYPE_DEFAULT);
static int getPower(esp_ble_power_type_t powerType=ESP_BLE_PWR_TYPE_DEFAULT);
static void setOwnAddrType(uint8_t own_addr_type, bool useNRPA=false);
static void setScanDuplicateCacheSize(uint16_t cacheSize);
static void setScanFilterMode(uint8_t type);
#else
static void setPower(int dbm);
static int getPower();
#endif
static void setCustomGapHandler(gap_event_handler handler);
static void setSecurityAuth(bool bonding, bool mitm, bool sc);
static void setSecurityAuth(uint8_t auth_req);
@@ -131,12 +120,15 @@ public:
static void setSecurityPasskey(uint32_t pin);
static uint32_t getSecurityPasskey();
static void setSecurityCallbacks(NimBLESecurityCallbacks* pCallbacks);
static void setOwnAddrType(uint8_t own_addr_type, bool useNRPA=false);
static int startSecurity(uint16_t conn_id);
static int setMTU(uint16_t mtu);
static uint16_t getMTU();
static bool isIgnored(const NimBLEAddress &address);
static void addIgnored(const NimBLEAddress &address);
static void removeIgnored(const NimBLEAddress &address);
static void setScanDuplicateCacheSize(uint16_t cacheSize);
static void setScanFilterMode(uint8_t type);
#if defined(CONFIG_BT_NIMBLE_ROLE_BROADCASTER)
static NimBLEAdvertising* getAdvertising();
@@ -206,10 +198,8 @@ private:
static ble_gap_event_listener m_listener;
static gap_event_handler m_customGapHandler;
static uint8_t m_own_addr_type;
#ifdef ESP_PLATFORM
static uint16_t m_scanDuplicateSize;
static uint8_t m_scanFilterMode;
#endif
static std::vector<NimBLEAddress> m_whiteList;
};

View File

@@ -126,30 +126,30 @@ std::string NimBLEEddystoneTLM::toString() {
out += " C\n";
out += "Adv. Count ";
snprintf(val, sizeof(val), "%" PRIu32, ENDIAN_CHANGE_U32(m_eddystoneData.advCount));
snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U32(m_eddystoneData.advCount));
out += val;
out += "\n";
out += "Time in seconds ";
snprintf(val, sizeof(val), "%" PRIu32, rawsec/10);
snprintf(val, sizeof(val), "%d", rawsec/10);
out += val;
out += "\n";
out += "Time ";
snprintf(val, sizeof(val), "%04" PRIu32, rawsec / 864000);
snprintf(val, sizeof(val), "%04d", rawsec / 864000);
out += val;
out += ".";
snprintf(val, sizeof(val), "%02" PRIu32, (rawsec / 36000) % 24);
snprintf(val, sizeof(val), "%02d", (rawsec / 36000) % 24);
out += val;
out += ":";
snprintf(val, sizeof(val), "%02" PRIu32, (rawsec / 600) % 60);
snprintf(val, sizeof(val), "%02d", (rawsec / 600) % 60);
out += val;
out += ":";
snprintf(val, sizeof(val), "%02" PRIu32, (rawsec / 10) % 60);
snprintf(val, sizeof(val), "%02d", (rawsec / 10) % 60);
out += val;
out += "\n";

View File

@@ -27,7 +27,7 @@ NimBLEHIDDevice::NimBLEHIDDevice(NimBLEServer* server) {
* Here we create mandatory services described in bluetooth specification
*/
m_deviceInfoService = server->createService(NimBLEUUID((uint16_t) 0x180a));
m_hidService = server->createService(NimBLEUUID((uint16_t) 0x1812));
m_hidService = server->createService(NimBLEUUID((uint16_t) 0x1812), 40);
m_batteryService = server->createService(NimBLEUUID((uint16_t) 0x180f));
/*

View File

@@ -13,67 +13,59 @@
#if defined(CONFIG_BT_ENABLED)
#if defined(CONFIG_NIMBLE_CPP_IDF) // using esp-idf
# include "esp_log.h"
# ifndef CONFIG_NIMBLE_CPP_LOG_LEVEL
# define CONFIG_NIMBLE_CPP_LOG_LEVEL 0
# endif
# define NIMBLE_CPP_LOG_PRINT(level, tag, format, ...) do { \
if (CONFIG_NIMBLE_CPP_LOG_LEVEL >= level) \
ESP_LOG_LEVEL_LOCAL(level, tag, format, ##__VA_ARGS__); \
} while(0)
#include "esp_log.h"
# define NIMBLE_LOGD(tag, format, ...) \
NIMBLE_CPP_LOG_PRINT(ESP_LOG_DEBUG, tag, format, ##__VA_ARGS__)
# define NIMBLE_LOGI(tag, format, ...) \
NIMBLE_CPP_LOG_PRINT(ESP_LOG_INFO, tag, format, ##__VA_ARGS__)
# define NIMBLE_LOGW(tag, format, ...) \
NIMBLE_CPP_LOG_PRINT(ESP_LOG_WARN, tag, format, ##__VA_ARGS__)
# define NIMBLE_LOGE(tag, format, ...) \
NIMBLE_CPP_LOG_PRINT(ESP_LOG_ERROR, tag, format, ##__VA_ARGS__)
# define NIMBLE_LOGC(tag, format, ...) \
NIMBLE_CPP_LOG_PRINT(ESP_LOG_ERROR, tag, format, ##__VA_ARGS__)
#define NIMBLE_LOGE(tag, format, ...) ESP_LOGE(tag, format, ##__VA_ARGS__)
#define NIMBLE_LOGW(tag, format, ...) ESP_LOGW(tag, format, ##__VA_ARGS__)
#define NIMBLE_LOGI(tag, format, ...) ESP_LOGI(tag, format, ##__VA_ARGS__)
#define NIMBLE_LOGD(tag, format, ...) ESP_LOGD(tag, format, ##__VA_ARGS__)
#define NIMBLE_LOGC(tag, format, ...) ESP_LOGE(tag, format, ##__VA_ARGS__)
#else // using Arduino
# include "nimble/porting/nimble/include/syscfg/syscfg.h"
# include "nimble/console/console.h"
# ifndef CONFIG_NIMBLE_CPP_LOG_LEVEL
# if defined(ARDUINO_ARCH_ESP32) && defined(CORE_DEBUG_LEVEL)
# define CONFIG_NIMBLE_CPP_LOG_LEVEL CORE_DEBUG_LEVEL
# else
# define CONFIG_NIMBLE_CPP_LOG_LEVEL 0
# endif
# endif
# if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 4
# define NIMBLE_LOGD( tag, format, ... ) console_printf("D %s: "#format"\n",tag,##__VA_ARGS__)
# else
# define NIMBLE_LOGD( tag, format, ... ) (void)tag
# endif
#include "nimble/porting/nimble/include/syscfg/syscfg.h"
#include "nimble/console/console.h"
# if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 3
# define NIMBLE_LOGI( tag, format, ... ) console_printf("I %s: "#format"\n",tag,##__VA_ARGS__)
# else
# define NIMBLE_LOGI( tag, format, ... ) (void)tag
# endif
// If Arduino is being used, strip out the colors and ignore log printing below ui setting.
// Note: because CONFIG_LOG_DEFAULT_LEVEL is set at ERROR in Arduino we must use MODLOG_DFLT(ERROR
// otherwise no messages will be printed above that level.
#ifndef NIMBLE_CPP_DEBUG_LEVEL
#if defined(ARDUINO_ARCH_ESP32) && defined(CORE_DEBUG_LEVEL)
#define NIMBLE_CPP_DEBUG_LEVEL CORE_DEBUG_LEVEL
#else
#define NIMBLE_CPP_DEBUG_LEVEL 0
#endif
#endif
#if NIMBLE_CPP_DEBUG_LEVEL >= 4
#define NIMBLE_LOGD( tag, format, ... ) console_printf("D %s: "#format"\n",tag,##__VA_ARGS__)
#else
#define NIMBLE_LOGD( tag, format, ... ) (void)tag
#endif
#if NIMBLE_CPP_DEBUG_LEVEL >= 3
#define NIMBLE_LOGI( tag, format, ... ) console_printf("I %s: "#format"\n",tag,##__VA_ARGS__)
#else
#define NIMBLE_LOGI( tag, format, ... ) (void)tag
#endif
#if NIMBLE_CPP_DEBUG_LEVEL >= 2
#define NIMBLE_LOGW( tag, format, ... ) console_printf("W %s: "#format"\n",tag,##__VA_ARGS__)
#else
#define NIMBLE_LOGW( tag, format, ... ) (void)tag
#endif
#if NIMBLE_CPP_DEBUG_LEVEL >= 1
#define NIMBLE_LOGE( tag, format, ... ) console_printf("E %s: "#format"\n",tag,##__VA_ARGS__)
#define NIMBLE_LOGC( tag, format, ... ) console_printf("CRIT %s: "#format"\n",tag,##__VA_ARGS__)
#else
#define NIMBLE_LOGE( tag, format, ... ) (void)tag
#define NIMBLE_LOGC( tag, format, ... ) (void)tag
#endif
# if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 2
# define NIMBLE_LOGW( tag, format, ... ) console_printf("W %s: "#format"\n",tag,##__VA_ARGS__)
# else
# define NIMBLE_LOGW( tag, format, ... ) (void)tag
# endif
# if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 1
# define NIMBLE_LOGE( tag, format, ... ) console_printf("E %s: "#format"\n",tag,##__VA_ARGS__)
# define NIMBLE_LOGC( tag, format, ... ) console_printf("CRIT %s: "#format"\n",tag,##__VA_ARGS__)
# else
# define NIMBLE_LOGE( tag, format, ... ) (void)tag
# define NIMBLE_LOGC( tag, format, ... ) (void)tag
# endif
#endif /* CONFIG_NIMBLE_CPP_IDF */
#endif /* CONFIG_BT_ENABLED */

View File

@@ -19,8 +19,6 @@
#include "NimBLEUtils.h"
#include "NimBLELog.h"
#include <climits>
static const char* LOG_TAG = "NimBLERemoteCharacteristic";
/**
@@ -59,6 +57,7 @@ static const char* LOG_TAG = "NimBLERemoteCharacteristic";
m_pRemoteService = pRemoteService;
m_notifyCallback = nullptr;
m_timestamp = 0;
m_valMux = portMUX_INITIALIZER_UNLOCKED;
NIMBLE_LOGD(LOG_TAG, "<< NimBLERemoteCharacteristic(): %s", m_uuid.toString().c_str());
} // NimBLERemoteCharacteristic
@@ -239,8 +238,7 @@ bool NimBLERemoteCharacteristic::retrieveDescriptors(const NimBLEUUID *uuid_filt
}
int rc = 0;
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
// If we don't know the end handle of this characteristic retrieve the next one in the service
// The end handle is the next characteristic definition handle -1.
@@ -255,10 +253,6 @@ bool NimBLERemoteCharacteristic::retrieveDescriptors(const NimBLEUUID *uuid_filt
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
if (taskData.rc != 0) {
@@ -280,10 +274,6 @@ bool NimBLERemoteCharacteristic::retrieveDescriptors(const NimBLEUUID *uuid_filt
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
if (taskData.rc != 0) {
@@ -415,12 +405,12 @@ NimBLEUUID NimBLERemoteCharacteristic::getUUID() {
* @return The value of the remote characteristic.
*/
std::string NimBLERemoteCharacteristic::getValue(time_t *timestamp) {
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
std::string value = m_value;
if(timestamp != nullptr) {
*timestamp = m_timestamp;
}
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
return value;
}
@@ -484,8 +474,7 @@ std::string NimBLERemoteCharacteristic::readValue(time_t *timestamp) {
int rc = 0;
int retryCount = 1;
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, &value};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(),0, &value};
do {
rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0,
@@ -497,10 +486,6 @@ std::string NimBLERemoteCharacteristic::readValue(time_t *timestamp) {
return value;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;
@@ -527,13 +512,13 @@ std::string NimBLERemoteCharacteristic::readValue(time_t *timestamp) {
} while(rc != 0 && retryCount--);
time_t t = time(nullptr);
ble_npl_hw_enter_critical();
portENTER_CRITICAL(&m_valMux);
m_value = value;
m_timestamp = t;
if(timestamp != nullptr) {
*timestamp = m_timestamp;
}
ble_npl_hw_exit_critical(0);
portEXIT_CRITICAL(&m_valMux);
NIMBLE_LOGD(LOG_TAG, "<< readValue length: %d rc=%d", value.length(), rc);
return value;
@@ -563,12 +548,11 @@ int NimBLERemoteCharacteristic::onReadCB(uint16_t conn_handle,
if(rc == 0) {
if(attr) {
uint32_t data_len = OS_MBUF_PKTLEN(attr->om);
if(((*strBuf).length() + data_len) > BLE_ATT_ATTR_MAX_LEN) {
if(((*strBuf).length() + attr->om->om_len) > BLE_ATT_ATTR_MAX_LEN) {
rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
} else {
NIMBLE_LOGD(LOG_TAG, "Got %d bytes", data_len);
(*strBuf) += std::string((char*) attr->om->om_data, data_len);
NIMBLE_LOGD(LOG_TAG, "Got %d bytes", attr->om->om_len);
(*strBuf) += std::string((char*) attr->om->om_data, attr->om->om_len);
return 0;
}
}
@@ -758,8 +742,7 @@ bool NimBLERemoteCharacteristic::writeValue(const uint8_t* data, size_t length,
return (rc==0);
}
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
do {
if(length > mtu) {
@@ -779,10 +762,6 @@ bool NimBLERemoteCharacteristic::writeValue(const uint8_t* data, size_t length,
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;

View File

@@ -159,6 +159,7 @@ private:
std::string m_value;
notify_callback m_notifyCallback;
time_t m_timestamp;
portMUX_TYPE m_valMux;
// We maintain a vector of descriptors owned by this characteristic.
std::vector<NimBLERemoteDescriptor*> m_descriptorVector;

View File

@@ -19,8 +19,6 @@
#include "NimBLEUtils.h"
#include "NimBLELog.h"
#include <climits>
static const char* LOG_TAG = "NimBLERemoteDescriptor";
/**
@@ -139,8 +137,7 @@ std::string NimBLERemoteDescriptor::readValue() {
int rc = 0;
int retryCount = 1;
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, &value};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(),0, &value};
do {
rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0,
@@ -152,10 +149,6 @@ std::string NimBLERemoteDescriptor::readValue() {
return value;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;
@@ -193,7 +186,6 @@ int NimBLERemoteDescriptor::onReadCB(uint16_t conn_handle,
const struct ble_gatt_error *error,
struct ble_gatt_attr *attr, void *arg)
{
(void)attr;
ble_task_data_t *pTaskData = (ble_task_data_t*)arg;
NimBLERemoteDescriptor* desc = (NimBLERemoteDescriptor*)pTaskData->pATT;
uint16_t conn_id = desc->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId();
@@ -209,12 +201,11 @@ int NimBLERemoteDescriptor::onReadCB(uint16_t conn_handle,
if(rc == 0) {
if(attr) {
uint32_t data_len = OS_MBUF_PKTLEN(attr->om);
if(((*strBuf).length() + data_len) > BLE_ATT_ATTR_MAX_LEN) {
if(((*strBuf).length() + attr->om->om_len) > BLE_ATT_ATTR_MAX_LEN) {
rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
} else {
NIMBLE_LOGD(LOG_TAG, "Got %d bytes", data_len);
(*strBuf) += std::string((char*) attr->om->om_data, data_len);
NIMBLE_LOGD(LOG_TAG, "Got %d bytes", attr->om->om_len);
(*strBuf) += std::string((char*) attr->om->om_data, attr->om->om_len);
return 0;
}
}
@@ -296,8 +287,7 @@ bool NimBLERemoteDescriptor::writeValue(const uint8_t* data, size_t length, bool
return (rc == 0);
}
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
do {
if(length > mtu) {
@@ -318,10 +308,6 @@ bool NimBLERemoteDescriptor::writeValue(const uint8_t* data, size_t length, bool
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
rc = taskData.rc;

View File

@@ -20,8 +20,6 @@
#include "NimBLEDevice.h"
#include "NimBLELog.h"
#include <climits>
static const char* LOG_TAG = "NimBLERemoteService";
/**
@@ -198,8 +196,7 @@ bool NimBLERemoteService::retrieveCharacteristics(const NimBLEUUID *uuid_filter)
NIMBLE_LOGD(LOG_TAG, ">> retrieveCharacteristics() for service: %s", getUUID().toString().c_str());
int rc = 0;
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {this, cur_task, 0, nullptr};
ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr};
if(uuid_filter == nullptr) {
rc = ble_gattc_disc_all_chrs(m_pClient->getConnId(),
@@ -221,10 +218,6 @@ bool NimBLERemoteService::retrieveCharacteristics(const NimBLEUUID *uuid_filter)
return false;
}
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
if(taskData.rc == 0){

View File

@@ -20,7 +20,6 @@
#include "NimBLELog.h"
#include <string>
#include <climits>
static const char* LOG_TAG = "NimBLEScan";
@@ -357,15 +356,10 @@ NimBLEScanResults NimBLEScan::start(uint32_t duration, bool is_continue) {
NIMBLE_LOGW(LOG_TAG, "Blocking scan called with duration = forever");
}
TaskHandle_t cur_task = xTaskGetCurrentTaskHandle();
ble_task_data_t taskData = {nullptr, cur_task, 0, nullptr};
ble_task_data_t taskData = {nullptr, xTaskGetCurrentTaskHandle(),0, nullptr};
m_pTaskData = &taskData;
if(start(duration, nullptr, is_continue)) {
#ifdef ulTaskNotifyValueClear
// Clear the task notification value to ensure we block
ulTaskNotifyValueClear(cur_task, ULONG_MAX);
#endif
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
}

View File

@@ -80,17 +80,18 @@ NimBLEService* NimBLEServer::createService(const char* uuid) {
* to provide inst_id value different for each service.
* @return A reference to the new service object.
*/
NimBLEService* NimBLEServer::createService(const NimBLEUUID &uuid) {
NimBLEService* NimBLEServer::createService(const NimBLEUUID &uuid, uint32_t numHandles, uint8_t inst_id) {
NIMBLE_LOGD(LOG_TAG, ">> createService - %s", uuid.toString().c_str());
// TODO: add functionality to use inst_id for multiple services with same uuid
(void)inst_id;
// Check that a service with the supplied UUID does not already exist.
if(getServiceByUUID(uuid) != nullptr) {
NIMBLE_LOGW(LOG_TAG, "Warning creating a duplicate service UUID: %s",
std::string(uuid).c_str());
}
NimBLEService* pService = new NimBLEService(uuid);
m_svcVec.push_back(pService);
NimBLEService* pService = new NimBLEService(uuid, numHandles, this);
m_svcVec.push_back(pService); // Save a reference to this service being on this server.
serviceChanged();
NIMBLE_LOGD(LOG_TAG, "<< createService");
@@ -181,7 +182,7 @@ void NimBLEServer::start() {
abort();
}
#if CONFIG_NIMBLE_CPP_LOG_LEVEL >= 4
#if CONFIG_LOG_DEFAULT_LEVEL > 3 || (ARDUINO_ARCH_ESP32 && CORE_DEBUG_LEVEL >= 4)
ble_gatts_show_local();
#endif
/*** Future use ***
@@ -785,17 +786,12 @@ void NimBLEServer::updateConnParams(uint16_t conn_handle,
* @param [in] tx_octets The preferred number of payload octets to use (Range 0x001B-0x00FB).
*/
void NimBLEServer::setDataLen(uint16_t conn_handle, uint16_t tx_octets) {
#if defined(CONFIG_NIMBLE_CPP_IDF) && defined(ESP_IDF_VERSION) && \
ESP_IDF_VERSION <= ESP_IDF_VERSION_VAL(4,3,2)
return;
#else
uint16_t tx_time = (tx_octets + 14) * 8;
int rc = ble_gap_set_data_len(conn_handle, tx_octets, tx_time);
if(rc != 0) {
NIMBLE_LOGE(LOG_TAG, "Set data length error: %d, %s", rc, NimBLEUtils::returnCodeToString(rc));
}
#endif
} // setDataLen

View File

@@ -21,8 +21,6 @@
#define NIMBLE_ATT_REMOVE_HIDE 1
#define NIMBLE_ATT_REMOVE_DELETE 2
#define onMtuChanged onMTUChange
#include "NimBLEUtils.h"
#include "NimBLEAddress.h"
#include "NimBLEAdvertising.h"
@@ -43,7 +41,8 @@ class NimBLEServer {
public:
size_t getConnectedCount();
NimBLEService* createService(const char* uuid);
NimBLEService* createService(const NimBLEUUID &uuid);
NimBLEService* createService(const NimBLEUUID &uuid, uint32_t numHandles=15,
uint8_t inst_id=0);
void removeService(NimBLEService* service, bool deleteSvc = false);
void addService(NimBLEService* service);
NimBLEAdvertising* getAdvertising();

View File

@@ -17,7 +17,6 @@
#include "nimconfig.h"
#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL)
#include "NimBLEDevice.h"
#include "NimBLEService.h"
#include "NimBLEUtils.h"
#include "NimBLELog.h"
@@ -32,21 +31,29 @@ static const char* LOG_TAG = "NimBLEService"; // Tag for logging.
/**
* @brief Construct an instance of the NimBLEService
* @param [in] uuid The UUID of the service.
* @param [in] numHandles The maximum number of handles associated with the service.
* @param [in] pServer A pointer to the server instance that this service belongs to.
*/
NimBLEService::NimBLEService(const char* uuid)
: NimBLEService(NimBLEUUID(uuid)) {
NimBLEService::NimBLEService(const char* uuid, uint16_t numHandles, NimBLEServer* pServer)
: NimBLEService(NimBLEUUID(uuid), numHandles, pServer) {
}
/**
* @brief Construct an instance of the BLEService
* @param [in] uuid The UUID of the service.
* @param [in] numHandles The maximum number of handles associated with the service.
* @param [in] pServer A pointer to the server instance that this service belongs to.
*/
NimBLEService::NimBLEService(const NimBLEUUID &uuid) {
NimBLEService::NimBLEService(const NimBLEUUID &uuid, uint16_t numHandles, NimBLEServer* pServer) {
m_uuid = uuid;
m_handle = NULL_HANDLE;
m_pServer = pServer;
m_numHandles = numHandles;
m_pSvcDef = nullptr;
m_removed = 0;
m_secondary = false;
m_pSecSvcDef = nullptr;
} // NimBLEService
@@ -65,6 +72,13 @@ NimBLEService::~NimBLEService() {
delete(m_pSvcDef);
}
if(m_pSecSvcDef != nullptr) {
for(auto &it : m_secSvcVec) {
delete it;
}
delete m_pSecSvcDef;
}
for(auto &it : m_chrVec) {
delete it;
}
@@ -125,7 +139,7 @@ bool NimBLEService::start() {
ble_gatt_chr_def* pChr_a = nullptr;
ble_gatt_dsc_def* pDsc_a = nullptr;
svc[0].type = BLE_GATT_SVC_TYPE_PRIMARY;
svc[0].type = m_secondary ? BLE_GATT_SVC_TYPE_SECONDARY : BLE_GATT_SVC_TYPE_PRIMARY;
svc[0].uuid = &m_uuid.getNative()->u;
svc[0].includes = NULL;
@@ -217,6 +231,19 @@ bool NimBLEService::start() {
// end of services must indicate to api with type = 0
svc[1].type = 0;
m_pSvcDef = svc;
if(m_secSvcVec.size() > 0){
size_t numSecSvcs = m_secSvcVec.size();
ble_gatt_svc_def** m_pSecSvcDef = new ble_gatt_svc_def*[numSecSvcs + 1];
int i = 0;
for(auto& it : m_secSvcVec) {
it->start();
m_pSecSvcDef[i] = it->m_pSvcDef;
++i;
}
m_pSecSvcDef[numSecSvcs] = nullptr;
m_pSvcDef->includes = (const ble_gatt_svc_def**)m_pSecSvcDef;
}
}
int rc = ble_gatts_count_cfg((const ble_gatt_svc_def*)m_pSvcDef);
@@ -229,7 +256,6 @@ bool NimBLEService::start() {
if (rc != 0) {
NIMBLE_LOGE(LOG_TAG, "ble_gatts_add_svcs, rc= %d, %s", rc, NimBLEUtils::returnCodeToString(rc));
return false;
}
NIMBLE_LOGD(LOG_TAG, "<< start()");
@@ -246,6 +272,44 @@ uint16_t NimBLEService::getHandle() {
} // getHandle
/**
* @brief Creates a BLE service as a secondary service to the service this was called from.
* @param [in] uuid The UUID of the secondary service.
* @return A reference to the new secondary service object.
*/
NimBLEService* NimBLEService::createService(const NimBLEUUID &uuid) {
NIMBLE_LOGD(LOG_TAG, ">> createService - %s", uuid.toString().c_str());
NimBLEServer* pServer = getServer();
NimBLEService* pService = new NimBLEService(uuid, 0, pServer);
m_secSvcVec.push_back(pService);
pService->m_secondary = true;
pServer->serviceChanged();
NIMBLE_LOGD(LOG_TAG, "<< createService");
return pService;
}
/**
* @brief Adds a secondary service to this service which was either already created but removed from availability,\n
* or created and later added.
* @param [in] service The secondary service object to add.
*/
void NimBLEService::addService(NimBLEService* service) {
// If adding a service that was not removed add it and return.
// Else reset GATT and send service changed notification.
if(service->m_removed == 0) {
m_secSvcVec.push_back(service);
return;
}
service->m_secondary = true;
service->m_removed = 0;
getServer()->serviceChanged();
}
/**
* @brief Create a new BLE Characteristic associated with this service.
* @param [in] uuid - The UUID of the characteristic.
@@ -421,7 +485,7 @@ std::string NimBLEService::toString() {
* @return The BLEServer associated with this service.
*/
NimBLEServer* NimBLEService::getServer() {
return NimBLEDevice::getServer();
return m_pServer;
}// getServer
#endif /* CONFIG_BT_ENABLED && CONFIG_BT_NIMBLE_ROLE_PERIPHERAL */

View File

@@ -34,8 +34,8 @@ class NimBLECharacteristic;
class NimBLEService {
public:
NimBLEService(const char* uuid);
NimBLEService(const NimBLEUUID &uuid);
NimBLEService(const char* uuid, uint16_t numHandles, NimBLEServer* pServer);
NimBLEService(const NimBLEUUID &uuid, uint16_t numHandles, NimBLEServer* pServer);
~NimBLEService();
NimBLEServer* getServer();
@@ -67,6 +67,9 @@ public:
std::vector<NimBLECharacteristic*> getCharacteristics(const char* uuid);
std::vector<NimBLECharacteristic*> getCharacteristics(const NimBLEUUID &uuid);
void addService(NimBLEService* service);
NimBLEService* createService(const NimBLEUUID &uuid);
private:
@@ -74,10 +77,15 @@ private:
friend class NimBLEDevice;
uint16_t m_handle;
NimBLEServer* m_pServer;
NimBLEUUID m_uuid;
uint16_t m_numHandles;
ble_gatt_svc_def* m_pSvcDef;
uint8_t m_removed;
bool m_secondary;
ble_gatt_svc_def** m_pSecSvcDef;
std::vector<NimBLECharacteristic*> m_chrVec;
std::vector<NimBLEService*> m_secSvcVec;
}; // NimBLEService

View File

@@ -11,8 +11,7 @@
#include "NimBLEUtils.h"
#include "NimBLELog.h"
#include <stdlib.h>
#include "nimconfig.h"
static const char* LOG_TAG = "NimBLEUtils";
@@ -343,7 +342,6 @@ const char* NimBLEUtils::returnCodeToString(int rc) {
return "Unknown";
}
#else // #if defined(CONFIG_NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT)
(void)rc;
return "";
#endif // #if defined(CONFIG_NIMBLE_CPP_ENABLE_RETURN_CODE_TEXT)
}
@@ -371,7 +369,6 @@ const char* NimBLEUtils::advTypeToString(uint8_t advType) {
return "Unknown flag";
}
#else // #if defined(CONFIG_NIMBLE_CPP_ENABLE_ADVERTISMENT_TYPE_TEXT)
(void)advType;
return "";
#endif // #if defined(CONFIG_NIMBLE_CPP_ENABLE_ADVERTISMENT_TYPE_TEXT)
} // adFlagsToString
@@ -419,11 +416,8 @@ char* NimBLEUtils::buildHexData(uint8_t* target, const uint8_t* source, uint8_t
* @param [in] arg Unused.
*/
void NimBLEUtils::dumpGapEvent(ble_gap_event *event, void *arg){
(void)arg;
#if defined(CONFIG_NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT)
NIMBLE_LOGD(LOG_TAG, "Received a GAP event: %s", gapEventToString(event->type));
#else
(void)event;
#endif
}
@@ -510,7 +504,6 @@ const char* NimBLEUtils::gapEventToString(uint8_t eventType) {
return "Unknown event type";
}
#else // #if defined(CONFIG_NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT)
(void)eventType;
return "";
#endif // #if defined(CONFIG_NIMBLE_CPP_ENABLE_GAP_EVENT_CODE_TEXT)
} // gapEventToString

View File

@@ -44,12 +44,6 @@
*/
#define CONFIG_BT_NIMBLE_LOG_LEVEL 5
/** @brief Un-comment to set the debug log messages level from the NimBLE CPP Wrapper.\n
* Values: 0 = NONE, 1 = ERROR, 2 = WARNING, 3 = INFO, 4+ = DEBUG\n
* Uses approx. 32kB of flash memory.
*/
#define CONFIG_NIMBLE_CPP_LOG_LEVEL 0
/** @brief Un-comment to see NimBLE host return codes as text debug log messages.
* Uses approx. 7kB of flash memory.
*/