From f4846e812fdbbc31f004929bf27bd2275ef7f9f4 Mon Sep 17 00:00:00 2001 From: hjlee Date: Sun, 30 Nov 2025 19:41:14 +0900 Subject: [PATCH] Fix descriptor search range in retrieveDescriptors() The previous implementation incorrectly used the service's end handle when searching for descriptors, which caused it to retrieve descriptors from subsequent characteristics as well. This fix calculates the correct end handle by finding the next characteristic's handle and using (next_handle - 1) as the search limit. This ensures only descriptors belonging to the current characteristic are retrieved. Fixes incorrect descriptor retrieval when multiple characteristics exist in the same service. --- src/NimBLERemoteCharacteristic.cpp | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/NimBLERemoteCharacteristic.cpp b/src/NimBLERemoteCharacteristic.cpp index 2c23ccbf..64a1f308 100644 --- a/src/NimBLERemoteCharacteristic.cpp +++ b/src/NimBLERemoteCharacteristic.cpp @@ -94,8 +94,24 @@ int NimBLERemoteCharacteristic::descriptorDiscCB( bool NimBLERemoteCharacteristic::retrieveDescriptors(NimBLEDescriptorFilter* pFilter) const { NIMBLE_LOGD(LOG_TAG, ">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); + const auto pSvc = getRemoteService(); + uint16_t endHandle = pSvc->getEndHandle(); + + // Find the handle of the next characteristic to limit the descriptor search range. + const auto& chars = pSvc->getCharacteristics(false); + for (auto it = chars.begin(); it != chars.end(); ++it) { + if ((*it)->getHandle() == this->getHandle()) { + auto next_it = std::next(it); + if (next_it != chars.end()) { + endHandle = (*next_it)->getHandle() - 1; + NIMBLE_LOGD(LOG_TAG, "Search range limited to handle 0x%04X", endHandle); + } + break; + } + } + // If this is the last handle then there are no descriptors - if (getHandle() == getRemoteService()->getEndHandle()) { + if (getHandle() == endHandle) { NIMBLE_LOGD(LOG_TAG, "<< retrieveDescriptors(): found 0 descriptors."); return true; } @@ -108,7 +124,7 @@ bool NimBLERemoteCharacteristic::retrieveDescriptors(NimBLEDescriptorFilter* pFi int rc = ble_gattc_disc_all_dscs(getClient()->getConnHandle(), getHandle(), - getRemoteService()->getEndHandle(), + endHandle, NimBLERemoteCharacteristic::descriptorDiscCB, pFilter); if (rc != 0) {