diff --git a/src/NimBLEClient.cpp b/src/NimBLEClient.cpp index 7b6411226..decdb456f 100644 --- a/src/NimBLEClient.cpp +++ b/src/NimBLEClient.cpp @@ -63,10 +63,7 @@ NimBLEClient::NimBLEClient(const NimBLEAddress& peerAddress) m_pClientCallbacks{&defaultCallbacks}, m_connHandle{BLE_HS_CONN_HANDLE_NONE}, m_terminateFailCount{0}, - m_deleteCallbacks{false}, - m_connEstablished{false}, - m_asyncConnect{false}, - m_exchangeMTU{true}, + m_config{}, # if CONFIG_BT_NIMBLE_EXT_ADV m_phyMask{BLE_GAP_LE_PHY_1M_MASK | BLE_GAP_LE_PHY_2M_MASK | BLE_GAP_LE_PHY_CODED_MASK}, # endif @@ -89,7 +86,7 @@ NimBLEClient::~NimBLEClient() { // Before we are finished with the client, we must release resources. deleteServices(); - if (m_deleteCallbacks) { + if (m_config.deleteCallbacks) { delete m_pClientCallbacks; } } // ~NimBLEClient @@ -122,7 +119,7 @@ size_t NimBLEClient::deleteService(const NimBLEUUID& uuid) { } return m_svcVec.size(); -} // deleteServices +} // deleteService /** * @brief Connect to the BLE Server using the address of the last connected device, or the address\n @@ -174,16 +171,11 @@ bool NimBLEClient::connect(const NimBLEAddress& address, bool deleteAttributes, return false; } - if (isConnected() || m_connEstablished) { + if (isConnected()) { NIMBLE_LOGE(LOG_TAG, "Client already connected"); return false; } - if (NimBLEDevice::isConnectionInProgress()) { - NIMBLE_LOGE(LOG_TAG, "Connection already in progress"); - return false; - } - const ble_addr_t* peerAddr = address.getBase(); if (ble_gap_conn_find_by_addr(peerAddr, NULL) == 0) { NIMBLE_LOGE(LOG_TAG, "A connection to %s already exists", address.toString().c_str()); @@ -201,12 +193,9 @@ bool NimBLEClient::connect(const NimBLEAddress& address, bool deleteAttributes, deleteServices(); } - int rc = 0; - m_asyncConnect = asyncConnect; - m_exchangeMTU = exchangeMTU; - - // Set the connection in progress flag to prevent a scan from starting while connecting. - NimBLEDevice::setConnectionInProgress(true); + int rc = 0; + m_config.asyncConnect = asyncConnect; + m_config.exchangeMTU = exchangeMTU; do { # if CONFIG_BT_NIMBLE_EXT_ADV @@ -261,11 +250,10 @@ bool NimBLEClient::connect(const NimBLEAddress& address, bool deleteAttributes, if (rc != 0) { m_lastErr = rc; - NimBLEDevice::setConnectionInProgress(false); return false; } - if (m_asyncConnect) { + if (m_config.asyncConnect) { return true; } @@ -289,19 +277,14 @@ bool NimBLEClient::connect(const NimBLEAddress& address, bool deleteAttributes, rc = taskData.m_flags; if (rc != 0) { NIMBLE_LOGE(LOG_TAG, "Connection failed; status=%d %s", rc, NimBLEUtils::returnCodeToString(rc)); - // If the failure was not a result of a disconnection, make sure we disconnect now to avoid dangling connections - if (isConnected()) { - disconnect(); - } m_lastErr = rc; + if (m_config.deleteOnConnectFail) { + NimBLEDevice::deleteClient(this); + } return false; - } else { - NIMBLE_LOGI(LOG_TAG, "Connection established"); } - m_connEstablished = true; m_pClientCallbacks->onConnect(this); - NIMBLE_LOGD(LOG_TAG, "<< connect()"); // Check if still connected before returning return isConnected(); @@ -357,7 +340,7 @@ bool NimBLEClient::disconnect(uint8_t reason) { * @brief Cancel an ongoing connection attempt. * @return True if the command was successfully sent. */ -bool NimBLEClient::cancelConnect() { +bool NimBLEClient::cancelConnect() const { int rc = ble_gap_conn_cancel(); if (rc != 0 && rc != BLE_HS_EALREADY) { NIMBLE_LOGE(LOG_TAG, "ble_gap_conn_cancel failed: rc=%d %s", rc, NimBLEUtils::returnCodeToString(rc)); @@ -368,6 +351,32 @@ bool NimBLEClient::cancelConnect() { return true; } // cancelConnect +/** + * @brief Set or unset a flag to delete this client when disconnected or connection failed. + * @param [in] deleteOnDisconnect Set the client to self delete when disconnected. + * @param [in] deleteOnConnectFail Set the client to self delete when a connection attempt fails. + */ +void NimBLEClient::setSelfDelete(bool deleteOnDisconnect, bool deleteOnConnectFail) { + m_config.deleteOnDisconnect = deleteOnDisconnect; + m_config.deleteOnConnectFail = deleteOnConnectFail; +} // setSelfDelete + +/** + * @brief Get a copy of the clients configuration. + * @return A copy of the clients configuration. + */ +NimBLEClient::Config NimBLEClient::getConfig() const { + return m_config; +} // getConfig + +/** + * @brief Set the client configuration options. + * @param [in] config The config options instance to set the client configuration to. + */ +void NimBLEClient::setConfig(NimBLEClient::Config config) { + m_config = config; +} // setConfig + # if CONFIG_BT_NIMBLE_EXT_ADV /** * @brief Set the PHY types to use when connecting to a server. @@ -492,9 +501,8 @@ uint16_t NimBLEClient::getConnHandle() const { * To disconnect from a peer, use disconnect(). */ void NimBLEClient::clearConnection() { - m_connHandle = BLE_HS_CONN_HANDLE_NONE; - m_connEstablished = false; - m_peerAddress = NimBLEAddress{}; + m_connHandle = BLE_HS_CONN_HANDLE_NONE; + m_peerAddress = NimBLEAddress{}; } // clearConnection /** @@ -509,15 +517,13 @@ void NimBLEClient::clearConnection() { * This enables the GATT Server to read the attributes of the client connected to it. */ bool NimBLEClient::setConnection(const NimBLEConnInfo& connInfo) { - if (isConnected() || m_connEstablished) { + if (isConnected()) { NIMBLE_LOGE(LOG_TAG, "Already connected"); return false; } - m_peerAddress = connInfo.getAddress(); - m_connHandle = connInfo.getConnHandle(); - m_connEstablished = true; - + m_peerAddress = connInfo.getAddress(); + m_connHandle = connInfo.getConnHandle(); return true; } // setConnection @@ -763,6 +769,12 @@ int NimBLEClient::serviceDiscoveredCB(uint16_t connHandle, NimBLETaskData* pTaskData = (NimBLETaskData*)arg; NimBLEClient* pClient = (NimBLEClient*)pTaskData->m_pInstance; + if (error->status == BLE_HS_ENOTCONN) { + NIMBLE_LOGE(LOG_TAG, "<< Service Discovered; Not connected"); + NimBLEUtils::taskRelease(*pTaskData, error->status); + return error->status; + } + // Make sure the service discovery is for this device if (pClient->getConnHandle() != connHandle) { return 0; @@ -902,8 +914,9 @@ bool NimBLEClient::exchangeMTU() { * @param [in] arg A pointer to the client instance that registered for this callback. */ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { - NimBLEClient* pClient = (NimBLEClient*)arg; - int rc = 0; + NimBLEClient* pClient = (NimBLEClient*)arg; + int rc = 0; + NimBLETaskData* pTaskData = pClient->m_pTaskData; // save a copy in case client is deleted NIMBLE_LOGD(LOG_TAG, "Got Client event %s", NimBLEUtils::gapEventToString(event->type)); @@ -917,7 +930,7 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { rc = event->disconnect.reason; // If Host reset tell the device now before returning to prevent - // any errors caused by calling host functions before resyncing. + // any errors caused by calling host functions before re-syncing. switch (rc) { case BLE_HS_ECONTROLLER: case BLE_HS_ETIMEOUT_HCI: @@ -930,41 +943,45 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { break; } + NIMBLE_LOGD(LOG_TAG, "disconnect; reason=%d, %s", rc, NimBLEUtils::returnCodeToString(rc)); + pClient->m_terminateFailCount = 0; NimBLEDevice::removeIgnored(pClient->m_peerAddress); - pClient->m_connHandle = BLE_HS_CONN_HANDLE_NONE; - // If we received a connected event but did not get established - // then a disconnect event will be sent but we should not send it to the - // app for processing. Instead we will ensure the task is released - // and report the error. - if (!pClient->m_connEstablished) { - break; + // Don't call the disconnect callback if we are waiting for a connection to complete and it fails + if (rc != (BLE_HS_ERR_HCI_BASE + BLE_ERR_CONN_ESTABLISHMENT) || pClient->m_config.asyncConnect) { + pClient->m_pClientCallbacks->onDisconnect(pClient, rc); } - NIMBLE_LOGI(LOG_TAG, "disconnect; reason=%d, %s", rc, NimBLEUtils::returnCodeToString(rc)); + pClient->m_connHandle = BLE_HS_CONN_HANDLE_NONE; + + if (pClient->m_config.deleteOnDisconnect) { + // If we are set to self delete on disconnect but we have a task waiting on the connection + // completion we will set the flag to delete on connect fail instead of deleting here + // to prevent segmentation faults or double deleting + if (pTaskData != nullptr && rc == (BLE_HS_ERR_HCI_BASE + BLE_ERR_CONN_ESTABLISHMENT)) { + pClient->m_config.deleteOnConnectFail = true; + break; + } + NimBLEDevice::deleteClient(pClient); + } - pClient->m_connEstablished = false; - pClient->m_pClientCallbacks->onDisconnect(pClient, rc); break; } // BLE_GAP_EVENT_DISCONNECT case BLE_GAP_EVENT_CONNECT: { // If we aren't waiting for this connection response we should drop the connection immediately. - if (pClient->isConnected() || (!pClient->m_asyncConnect && pClient->m_pTaskData == nullptr)) { + if (pClient->isConnected() || (!pClient->m_config.asyncConnect && pClient->m_pTaskData == nullptr)) { ble_gap_terminate(event->connect.conn_handle, BLE_ERR_REM_USER_CONN_TERM); return 0; } - NimBLEDevice::setConnectionInProgress(false); rc = event->connect.status; if (rc == 0) { - NIMBLE_LOGI(LOG_TAG, "Connected event"); - pClient->m_connHandle = event->connect.conn_handle; - if (pClient->m_exchangeMTU) { - if (!pClient->exchangeMTU() && !pClient->m_asyncConnect) { - rc = pClient->m_lastErr; + if (pClient->m_config.exchangeMTU) { + if (!pClient->exchangeMTU() && !pClient->m_config.asyncConnect) { + rc = pClient->m_lastErr; // sets the error in the task data break; } } @@ -974,15 +991,19 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { NimBLEDevice::addIgnored(pClient->m_peerAddress); } else { pClient->m_connHandle = BLE_HS_CONN_HANDLE_NONE; - if (!pClient->m_asyncConnect) { + if (!pClient->m_config.asyncConnect) { break; } + + if (pClient->m_config.deleteOnConnectFail) { // async connect + delete pClient; + return 0; + } } - if (pClient->m_asyncConnect) { - pClient->m_connEstablished = rc == 0; + if (pClient->m_config.asyncConnect) { pClient->m_pClientCallbacks->onConnect(pClient); - } else if (!pClient->m_exchangeMTU) { + } else if (!pClient->m_config.exchangeMTU) { break; // not waiting for MTU exchange so release the task now. } @@ -1005,13 +1026,6 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { case BLE_GAP_EVENT_NOTIFY_RX: { if (pClient->m_connHandle != event->notify_rx.conn_handle) return 0; - - // If a notification comes before this flag is set we might - // access a vector while it is being cleared in connect() - if (!pClient->m_connEstablished) { - return 0; - } - NIMBLE_LOGD(LOG_TAG, "Notify Received for handle: %d", event->notify_rx.attr_handle); for (const auto& svc : pClient->m_svcVec) { @@ -1170,8 +1184,8 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) { } } // Switch - if (pClient->m_pTaskData != nullptr) { - NimBLEUtils::taskRelease(*pClient->m_pTaskData, rc); + if (pTaskData != nullptr) { + NimBLEUtils::taskRelease(*pTaskData, rc); } return 0; @@ -1192,11 +1206,11 @@ bool NimBLEClient::isConnected() const { */ void NimBLEClient::setClientCallbacks(NimBLEClientCallbacks* pClientCallbacks, bool deleteCallbacks) { if (pClientCallbacks != nullptr) { - m_pClientCallbacks = pClientCallbacks; - m_deleteCallbacks = deleteCallbacks; + m_pClientCallbacks = pClientCallbacks; + m_config.deleteCallbacks = deleteCallbacks; } else { - m_pClientCallbacks = &defaultCallbacks; - m_deleteCallbacks = false; + m_pClientCallbacks = &defaultCallbacks; + m_config.deleteCallbacks = false; } } // setClientCallbacks diff --git a/src/NimBLEClient.h b/src/NimBLEClient.h index 99b4dde03..d5c326502 100644 --- a/src/NimBLEClient.h +++ b/src/NimBLEClient.h @@ -51,7 +51,8 @@ class NimBLEClient { bool connect(const NimBLEAddress& address, bool deleteAttributes = true, bool asyncConnect = false, bool exchangeMTU = true); bool connect(bool deleteAttributes = true, bool asyncConnect = false, bool exchangeMTU = true); bool disconnect(uint8_t reason = BLE_ERR_REM_USER_CONN_TERM); - bool cancelConnect(); + bool cancelConnect() const; + void setSelfDelete(bool deleteOnDisconnect, bool deleteOnConnectFail); NimBLEAddress getPeerAddress() const; bool setPeerAddress(const NimBLEAddress& address); int getRssi() const; @@ -95,6 +96,17 @@ class NimBLEClient { void setConnectPhy(uint8_t mask); # endif + struct Config { + uint8_t deleteCallbacks : 1; // Delete the callback object when the client is deleted. + uint8_t deleteOnDisconnect : 1; // Delete the client when disconnected. + uint8_t deleteOnConnectFail : 1; // Delete the client when a connection attempt fails. + uint8_t asyncConnect : 1; // Connect asynchronously. + uint8_t exchangeMTU : 1; // Exchange MTU after connection. + }; + + Config getConfig() const; + void setConfig(Config config); + private: NimBLEClient(const NimBLEAddress& peerAddress); ~NimBLEClient(); @@ -117,10 +129,8 @@ class NimBLEClient { NimBLEClientCallbacks* m_pClientCallbacks; uint16_t m_connHandle; uint8_t m_terminateFailCount; - bool m_deleteCallbacks; - bool m_connEstablished; - bool m_asyncConnect; - bool m_exchangeMTU; + Config m_config; + # if CONFIG_BT_NIMBLE_EXT_ADV uint8_t m_phyMask; # endif diff --git a/src/NimBLEDevice.cpp b/src/NimBLEDevice.cpp index 1f1370958..a85815168 100644 --- a/src/NimBLEDevice.cpp +++ b/src/NimBLEDevice.cpp @@ -101,10 +101,6 @@ std::vector NimBLEDevice::m_ignoreList{}; std::vector NimBLEDevice::m_whiteList{}; uint8_t NimBLEDevice::m_ownAddrType{BLE_OWN_ADDR_PUBLIC}; -# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL) || defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL) -bool NimBLEDevice::m_connectionInProgress{false}; -# endif - # ifdef ESP_PLATFORM # ifdef CONFIG_BTDM_BLE_SCAN_DUPL uint16_t NimBLEDevice::m_scanDuplicateSize{CONFIG_BTDM_SCAN_DUPL_CACHE_SIZE}; @@ -322,41 +318,28 @@ bool NimBLEDevice::deleteClient(NimBLEClient* pClient) { return false; } - // Set the connection established flag to false to stop notifications - // from accessing the attribute vectors while they are being deleted. - pClient->m_connEstablished = false; - int rc = 0; - - if (pClient->isConnected()) { - if (!pClient->disconnect()) { - return false; - } - - while (pClient->isConnected()) { - ble_npl_time_delay(1); - } - // Since we set the flag to false the app will not get a callback - // in the disconnect event so we call it here for good measure. - pClient->m_pClientCallbacks->onDisconnect(pClient, BLE_ERR_CONN_TERM_LOCAL); - } else if (pClient->m_pTaskData != nullptr) { - rc = ble_gap_conn_cancel(); - if (rc != 0 && rc != BLE_HS_EALREADY) { - return false; - } - - while (pClient->m_pTaskData != nullptr) { - ble_npl_time_delay(1); - } - } - for (auto& clt : m_pClients) { if (clt == pClient) { - delete pClient; - clt = nullptr; + if (clt->isConnected()) { + clt->m_config.deleteOnDisconnect = true; + if (!clt->disconnect()) { + break; + } + } else if (pClient->m_pTaskData != nullptr) { + clt->m_config.deleteOnConnectFail = true; + if (!clt->cancelConnect()) { + break; + } + } else { + delete clt; + clt = nullptr; + } + + return true; } } - return true; + return false; } // deleteClient /** @@ -1251,23 +1234,6 @@ bool NimBLEDevice::setCustomGapHandler(gap_event_handler handler) { return rc == 0; } // setCustomGapHandler -/** - * @brief Set the connection in progress flag. - * @param [in] inProgress The connection in progress flag. - * @details This is used to prevent a scan from starting while a connection is in progress. - */ -void NimBLEDevice::setConnectionInProgress(bool inProgress) { - m_connectionInProgress = inProgress; -} // setConnectionInProgress - -/** - * @brief Check if a connection is in progress. - * @return True if a connection is in progress. - */ -bool NimBLEDevice::isConnectionInProgress() { - return m_connectionInProgress; -} // isConnectionInProgress - /** * @brief Return a string representation of the address of this device. * @return A string representation of this device address. diff --git a/src/NimBLEDevice.h b/src/NimBLEDevice.h index 9a722b714..1530377aa 100644 --- a/src/NimBLEDevice.h +++ b/src/NimBLEDevice.h @@ -184,8 +184,6 @@ class NimBLEDevice { static bool isBonded(const NimBLEAddress& address); static bool deleteAllBonds(); static NimBLEAddress getBondedAddress(int index); - static void setConnectionInProgress(bool inProgress); - static bool isConnectionInProgress(); # endif private: @@ -197,10 +195,6 @@ class NimBLEDevice { static uint8_t m_ownAddrType; static std::vector m_whiteList; -# if defined(CONFIG_BT_NIMBLE_ROLE_CENTRAL) || defined(CONFIG_BT_NIMBLE_ROLE_PERIPHERAL) - static bool m_connectionInProgress; -# endif - # if defined(CONFIG_BT_NIMBLE_ROLE_OBSERVER) static NimBLEScan* m_pScan; # endif diff --git a/src/NimBLERemoteCharacteristic.cpp b/src/NimBLERemoteCharacteristic.cpp index 3d812ac7b..d2dbf1d8b 100644 --- a/src/NimBLERemoteCharacteristic.cpp +++ b/src/NimBLERemoteCharacteristic.cpp @@ -69,6 +69,12 @@ int NimBLERemoteCharacteristic::descriptorDiscCB( const auto pChr = (NimBLERemoteCharacteristic*)pTaskData->m_pInstance; const NimBLEUUID* uuidFilter = filter->uuid; + if (error->status == BLE_HS_ENOTCONN) { + NIMBLE_LOGE(LOG_TAG, "<< Descriptor Discovery; Not connected"); + NimBLEUtils::taskRelease(*pTaskData, error->status); + return error->status; + } + if (pChr->getHandle() != chr_val_handle) { rc = BLE_HS_EDONE; // descriptor not for this characteristic } diff --git a/src/NimBLERemoteService.cpp b/src/NimBLERemoteService.cpp index 4517da844..8e70adec6 100644 --- a/src/NimBLERemoteService.cpp +++ b/src/NimBLERemoteService.cpp @@ -148,6 +148,13 @@ int NimBLERemoteService::characteristicDiscCB(uint16_t conn_handle, auto pTaskData = (NimBLETaskData*)arg; const auto pSvc = (NimBLERemoteService*)pTaskData->m_pInstance; + + if (error->status == BLE_HS_ENOTCONN) { + NIMBLE_LOGE(LOG_TAG, "<< Characteristic Discovery; Not connected"); + NimBLEUtils::taskRelease(*pTaskData, error->status); + return error->status; + } + // Make sure the discovery is for this device if (pSvc->getClient()->getConnHandle() != conn_handle) { return 0; diff --git a/src/NimBLERemoteValueAttribute.cpp b/src/NimBLERemoteValueAttribute.cpp index 7d4089f54..56d3fa13e 100644 --- a/src/NimBLERemoteValueAttribute.cpp +++ b/src/NimBLERemoteValueAttribute.cpp @@ -91,6 +91,12 @@ int NimBLERemoteValueAttribute::onWriteCB(uint16_t conn_handle, const ble_gatt_e auto pTaskData = static_cast(arg); const auto pAtt = static_cast(pTaskData->m_pInstance); + if (error->status == BLE_HS_ENOTCONN) { + NIMBLE_LOGE(LOG_TAG, "<< Write complete; Not connected"); + NimBLEUtils::taskRelease(*pTaskData, error->status); + return error->status; + } + if (pAtt->getClient()->getConnHandle() != conn_handle) { return 0; } @@ -170,6 +176,12 @@ int NimBLERemoteValueAttribute::onReadCB(uint16_t conn_handle, const ble_gatt_er auto pTaskData = static_cast(arg); const auto pAtt = static_cast(pTaskData->m_pInstance); + if (error->status == BLE_HS_ENOTCONN) { + NIMBLE_LOGE(LOG_TAG, "<< Read complete; Not connected"); + NimBLEUtils::taskRelease(*pTaskData, error->status); + return error->status; + } + if (pAtt->getClient()->getConnHandle() != conn_handle) { return 0; } diff --git a/src/NimBLEScan.cpp b/src/NimBLEScan.cpp index d3fc1c666..58b4988ac 100644 --- a/src/NimBLEScan.cpp +++ b/src/NimBLEScan.cpp @@ -291,7 +291,7 @@ bool NimBLEScan::isScanning() { bool NimBLEScan::start(uint32_t duration, bool is_continue) { NIMBLE_LOGD(LOG_TAG, ">> start: duration=%" PRIu32, duration); - if (NimBLEDevice::isConnectionInProgress()) { + if (ble_gap_conn_active()) { NIMBLE_LOGE(LOG_TAG, "Connection in progress, cannot start scan"); return false; } diff --git a/src/NimBLEUtils.cpp b/src/NimBLEUtils.cpp index 4ec9f7aee..b8e09c212 100644 --- a/src/NimBLEUtils.cpp +++ b/src/NimBLEUtils.cpp @@ -143,7 +143,7 @@ const char* NimBLEUtils::returnCodeToString(int rc) { case BLE_HS_ENOTSUP: return "Operation disabled at compile time"; case BLE_HS_EAPP: - return "Application error"; + return "Operation canceled by app"; case BLE_HS_EBADDATA: return "Invalid command from peer"; case BLE_HS_EOS: