@@ -66,7 +66,7 @@ NimBLEClient::NimBLEClient(const NimBLEAddress& peerAddress)
6666 m_deleteCallbacks{false },
6767 m_connEstablished{false },
6868 m_asyncConnect{false },
69- m_asyncSecure{ false },
69+ m_asyncSecureAttempt{ 0 },
7070 m_exchangeMTU{true },
7171# if CONFIG_BT_NIMBLE_EXT_ADV
7272 m_phyMask{BLE_GAP_LE_PHY_1M_MASK | BLE_GAP_LE_PHY_2M_MASK | BLE_GAP_LE_PHY_CODED_MASK},
@@ -327,29 +327,30 @@ bool NimBLEClient::secureConnection(bool async) {
327327 return false ;
328328 }
329329
330- m_asyncSecure = async;
331-
332330 // Set the secure in progress flag to prevent a scan from starting while securing.
333331 NimBLEDevice::setSecureInProgress (true );
334332
335333 int rc = 0 ;
336- if (!NimBLEDevice::startSecurity (m_connHandle, &rc)) {
334+ if (async && !NimBLEDevice::startSecurity (m_connHandle, &rc)) {
337335 m_lastErr = rc;
338- m_asyncSecure = false ;
336+ m_asyncSecureAttempt = 0 ;
339337 NimBLEDevice::setSecureInProgress (false );
340338 NIMBLE_LOGE (LOG_TAG, " secureConnection: failed to start rc=%d" , rc);
341339 return false ;
342340 }
343341
344- if (m_asyncSecure) {
342+ if (async) {
343+ m_asyncSecureAttempt++;
345344 return true ;
346345 }
347346
348347 NimBLETaskData taskData (const_cast <NimBLEClient*>(this ), BLE_HS_ENOTCONN);
349348 m_pTaskData = &taskData;
350349 int retryCount = 1 ;
351350 do {
352- NimBLEUtils::taskWait (taskData, BLE_NPL_TIME_FOREVER);
351+ if (NimBLEDevice::startSecurity (m_connHandle)) {
352+ NimBLEUtils::taskWait (taskData, BLE_NPL_TIME_FOREVER);
353+ }
353354 } while (taskData.m_flags == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING) && retryCount--);
354355
355356 m_pTaskData = nullptr ;
@@ -970,6 +971,7 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) {
970971
971972 NIMBLE_LOGI (LOG_TAG, " disconnect; reason=%d, %s" , rc, NimBLEUtils::returnCodeToString (rc));
972973
974+ pClient->m_asyncSecureAttempt = 0 ;
973975 pClient->m_connEstablished = false ;
974976 pClient->m_pClientCallbacks ->onDisconnect (pClient, rc);
975977 break ;
@@ -1127,8 +1129,13 @@ int NimBLEClient::handleGapEvent(struct ble_gap_event* event, void* arg) {
11271129 if (event->enc_change .status == (BLE_HS_ERR_HCI_BASE + BLE_ERR_PINKEY_MISSING)) {
11281130 // Key is missing, try deleting.
11291131 ble_store_util_delete_peer (&peerInfo.m_desc .peer_id_addr );
1132+ // Attempt a retry if async secure failed.
1133+ if (pClient->m_asyncSecureAttempt == 1 ) {
1134+ pClient->secureConnection (true );
1135+ }
11301136 } else {
11311137 pClient->m_pClientCallbacks ->onAuthenticationComplete (peerInfo);
1138+ pClient->m_asyncSecureAttempt = 0 ;
11321139 }
11331140 }
11341141
0 commit comments