From c157680575c0ad990b195c6c0aef1d28928aa6a7 Mon Sep 17 00:00:00 2001 From: h2zero Date: Wed, 13 Jan 2021 22:00:39 -0700 Subject: [PATCH] Limit delay in NimBLEClient::connect to connection timeout. In the case the controller become unresponsive, or does not comply with the timeout period, this will ensure the application continues instead of potentially blocking forever. --- src/NimBLEClient.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/src/NimBLEClient.cpp b/src/NimBLEClient.cpp index 2b4f59f..b0e2795 100644 --- a/src/NimBLEClient.cpp +++ b/src/NimBLEClient.cpp @@ -246,9 +246,23 @@ bool NimBLEClient::connect(const NimBLEAddress &address, bool deleteAttibutes) { } while (rc == BLE_HS_EBUSY); - // Wait for the connection to complete. - ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - if(taskData.rc != 0){ + // 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; + // If a connection was made but no response from MTU exchange; disconnect + if(isConnected()) { + NIMBLE_LOGE(LOG_TAG, "Connect timeout - no response"); + disconnect(); + } else { + // workaround; if the controller doesn't cancel the connection + // at the timeout cancel it here. + NIMBLE_LOGE(LOG_TAG, "Connect timeout - cancelling"); + ble_gap_conn_cancel(); + } + + return false; + + } else if(taskData.rc != 0){ NIMBLE_LOGE(LOG_TAG, "Connection failed; status=%d %s", taskData.rc, NimBLEUtils::returnCodeToString(taskData.rc));