Skip to content

Commit 2fe5031

Browse files
authored
Merge pull request #7 from doudar/copilot/refactor-nimbleclient-code
Refactor NimBLEClient service lookup path to reduce duplicate work and branch repetition
2 parents 78a42af + 3c81e21 commit 2fe5031

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

src/NimBLEClient.cpp

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -636,19 +636,21 @@ NimBLERemoteService* NimBLEClient::getService(const char* uuid) {
636636
* @return A pointer to the service or nullptr if not found.
637637
*/
638638
NimBLERemoteService* NimBLEClient::getService(const NimBLEUUID& uuid) {
639-
NIMBLE_LOGD(LOG_TAG, ">> getService: uuid: %s", uuid.toString().c_str());
639+
const std::string uuidStr = uuid.toString();
640+
NIMBLE_LOGD(LOG_TAG, ">> getService: uuid: %s", uuidStr.c_str());
640641

641642
for (auto& it : m_svcVec) {
642643
if (it->getUUID() == uuid) {
643-
NIMBLE_LOGD(LOG_TAG, "<< getService: found the service with uuid: %s", uuid.toString().c_str());
644+
NIMBLE_LOGD(LOG_TAG, "<< getService: found the service with uuid: %s", uuidStr.c_str());
644645
return it;
645646
}
646647
}
647648

648649
size_t prevSize = m_svcVec.size();
650+
auto getLastIfAdded = [this, prevSize]() -> NimBLERemoteService* { return m_svcVec.size() > prevSize ? m_svcVec.back() : nullptr; };
649651
if (retrieveServices(&uuid)) {
650-
if (m_svcVec.size() > prevSize) {
651-
return m_svcVec.back();
652+
if (NimBLERemoteService* svc = getLastIfAdded()) {
653+
return svc;
652654
}
653655

654656
// If the request was successful but 16/32 bit uuid not found
@@ -657,8 +659,8 @@ NimBLERemoteService* NimBLEClient::getService(const NimBLEUUID& uuid) {
657659
NimBLEUUID uuid128(uuid);
658660
uuid128.to128();
659661
if (retrieveServices(&uuid128)) {
660-
if (m_svcVec.size() > prevSize) {
661-
return m_svcVec.back();
662+
if (NimBLERemoteService* svc = getLastIfAdded()) {
663+
return svc;
662664
}
663665
}
664666
} else {
@@ -669,8 +671,8 @@ NimBLERemoteService* NimBLEClient::getService(const NimBLEUUID& uuid) {
669671
// if the uuid was 128 bit but not of the BLE base type this check will fail
670672
if (uuid16.bitSize() == BLE_UUID_TYPE_16) {
671673
if (retrieveServices(&uuid16)) {
672-
if (m_svcVec.size() > prevSize) {
673-
return m_svcVec.back();
674+
if (NimBLERemoteService* svc = getLastIfAdded()) {
675+
return svc;
674676
}
675677
}
676678
}

0 commit comments

Comments
 (0)