Skip to content

[Bugfix] Incorrect Client connection state tracking and self delete#1123

Merged
h2zero merged 1 commit intomasterfrom
bugfix/client-connection-state
Mar 25, 2026
Merged

[Bugfix] Incorrect Client connection state tracking and self delete#1123
h2zero merged 1 commit intomasterfrom
bugfix/client-connection-state

Conversation

@h2zero
Copy link
Owner

@h2zero h2zero commented Mar 24, 2026

This adds better client state tracking so that functions like NimBLEDevice::getDisconnectedClient get a more accurate state and will not return a connecting client.

This also fixes the client self delete on connection error where function call errors did not delete the client

Summary by CodeRabbit

  • Improvements
    • More reliable and consistent Bluetooth connection status reporting.
    • Improved connection lifecycle handling for connect, disconnect, and failure scenarios.
    • More accurate timeout and MTU behavior during synchronous connection attempts.
    • Better error propagation so failed connections leave the client in a correct state.
  • Bug Fixes
    • Reduced risk of stale or incorrect connection indicators during transient events.
    • More precise detection of disconnected vs connecting states to avoid incorrect deletions or cancels.

@coderabbitai
Copy link

coderabbitai bot commented Mar 24, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Arrr — This PR adds a private ConnStatus enum and m_connStatus to NimBLEClient, rewrites connect/disconnect flows and GAP event handling to maintain that status, centralizes connect error handling, and adjusts when services are deleted and how sync connect/MTU logic observes connection state.

Changes

Cohort / File(s) Summary
Client header
src/NimBLEClient.h
Added private ConnStatus enum (CONNECTED, DISCONNECTED, CONNECTING, DISCONNECTING) and new private member m_connStatus.
Client implementation
src/NimBLEClient.cpp
Introduced m_connStatus state machine; refactored connect(...) to set CONNECTING, centralize error handling (error:) that sets DISCONNECTED and m_lastErr and may self-delete; removed pre-connect conn-find check; deferred deleteServices() until after connect attempts when appropriate; changed synchronous connect/timeout/MTU checks to rely on m_connStatus; adjusted MTU failure propagation; updated disconnect(uint8_t) to set DISCONNECTED vs DISCONNECTING; replaced isConnected() guards with m_connStatus checks; updated GAP event handling to set/clear m_connStatus and to treat in-flight attempts based on CONNECTING.
Device manager
src/NimBLEDevice.cpp
Replaced isConnected() checks with explicit m_connStatus comparisons for client deletion and retrieval logic; treat CONNECTING clients as cancel/delete-on-connect-fail; minor preprocessor indentation adjustments.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

Avast, the client's state now sails so true,
CONNECTING first, then CONNECTED in view,
DISCONNECTING warns of the ebbing tide,
DISCONNECTED rests where lost links hide,
Yarrr — one map for errors, and services pruned aside.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main changes: introducing connection state tracking and fixing client self-deletion behavior on connection errors.
Docstring Coverage ✅ Passed Docstring coverage is 92.86% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bugfix/client-connection-state

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/NimBLEClient.cpp`:
- Around line 297-303: The error path calls NimBLEDevice::deleteClient(this)
while later accessing member fields, causing a use-after-free; change the order
so you update m_connStatus (set to DISCONNECTED) and m_lastErr = rc before
potentially calling NimBLEDevice::deleteClient(this), or alternatively defer
calling deleteClient until after you've stopped accessing any members (e.g.,
capture needed state or set a local flag and call deleteClient after leaving the
method). Ensure this change is applied to the error label and any early return
paths where m_config.deleteOnConnectFail is checked (references:
m_config.deleteOnConnectFail, NimBLEDevice::deleteClient, m_connStatus,
m_lastErr, CONNECTING/DISCONNECTED).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b7834cec-9b49-4daa-a144-46a61da36c29

📥 Commits

Reviewing files that changed from the base of the PR and between 9abb7dd and 2eaabc9.

📒 Files selected for processing (2)
  • src/NimBLEClient.cpp
  • src/NimBLEClient.h

@h2zero h2zero force-pushed the bugfix/client-connection-state branch from 2eaabc9 to 814842e Compare March 24, 2026 23:24
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/NimBLEClient.cpp`:
- Around line 1266-1268: The current change makes NimBLEClient::isConnected()
return true for CONNECTING and DISCONNECTING too; restore the original semantics
by making isConnected() return m_connStatus == CONNECTED only, and add a new
helper (e.g., isConnectingOrConnected() or isConnectedOrInTransition()) that
returns m_connStatus != DISCONNECTED; then update call sites that need the
broader “not disconnected” semantics (search for uses in NimBLEScan,
getConnectedClients, getDisconnectedClient, deleteClient, NimBLEL2CAPChannel,
getRssi, retrieveServices) to call the new helper while leaving callers that
require a stable connected state using isConnected().

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 255181ed-ab76-4138-a632-dae28899f516

📥 Commits

Reviewing files that changed from the base of the PR and between 2eaabc9 and 814842e.

📒 Files selected for processing (2)
  • src/NimBLEClient.cpp
  • src/NimBLEClient.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/NimBLEClient.h

@h2zero h2zero force-pushed the bugfix/client-connection-state branch from 814842e to d049396 Compare March 25, 2026 14:58
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4f1645c1-d23c-451e-ae0f-35a18fe27262

📥 Commits

Reviewing files that changed from the base of the PR and between 814842e and d049396.

📒 Files selected for processing (3)
  • src/NimBLEClient.cpp
  • src/NimBLEClient.h
  • src/NimBLEDevice.cpp

@h2zero h2zero force-pushed the bugfix/client-connection-state branch from d049396 to e3dd9fe Compare March 25, 2026 15:27
@h2zero h2zero requested a review from Copilot March 25, 2026 16:23
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR improves central-role client lifecycle/state tracking in the NimBLE C++ layer so APIs that look for “disconnected” clients don’t accidentally return clients that are mid-connect, and so self-delete on connection failures is handled more consistently.

Changes:

  • Introduces an explicit ConnStatus state machine in NimBLEClient and uses it to gate “connected/disconnected/connecting/disconnecting” behavior.
  • Updates NimBLEDevice client selection/deletion logic to rely on the new connection status rather than isConnected()/task state.
  • Normalizes some preprocessor indentation in NimBLEDevice.cpp.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
src/NimBLEDevice.cpp Uses m_connStatus for delete/disconnected-client selection and minor preprocessor formatting tweaks.
src/NimBLEClient.h Adds ConnStatus enum and m_connStatus field for explicit connection state tracking.
src/NimBLEClient.cpp Implements state transitions across connect/disconnect/GAP events and updates connection-dependent checks accordingly.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@h2zero h2zero force-pushed the bugfix/client-connection-state branch from e3dd9fe to 20eb2cc Compare March 25, 2026 16:54
This adds better client state tracking so that functions like NimBLEDevice::getDisconnectedClient get a more accurate state and will not return a connecting client.

This also fixes the client self delete on connection error where function call errors did not delete the client
@h2zero h2zero force-pushed the bugfix/client-connection-state branch from 20eb2cc to 2149162 Compare March 25, 2026 16:56
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/NimBLEClient.cpp (1)

1356-1356: Avast! There be a stray # floatin' in the code, ye scallywag!

This lone # on line 1356 be a valid "null directive" in C/C++ (does nothin'), but it looks like debris from a previous edit. Should be swabbed off the deck fer cleanliness!

🧹 Proposed fix to clean up the debris
-#
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/NimBLEClient.cpp` at line 1356, Remove the stray null-preprocessor
directive ('#') introduced in NimBLEClient.cpp (a lone '#' token with no
directive) by deleting that line; ensure the dangling '#' is not left in any
function or class scope (e.g., near any NimBLEClient-related functions) and
rebuild to verify there are no remaining stray preprocessor tokens or compile
warnings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/NimBLEClient.cpp`:
- Line 1356: Remove the stray null-preprocessor directive ('#') introduced in
NimBLEClient.cpp (a lone '#' token with no directive) by deleting that line;
ensure the dangling '#' is not left in any function or class scope (e.g., near
any NimBLEClient-related functions) and rebuild to verify there are no remaining
stray preprocessor tokens or compile warnings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 11fb8dce-823e-4144-8671-2f9b8eb629c2

📥 Commits

Reviewing files that changed from the base of the PR and between e3dd9fe and 20eb2cc.

📒 Files selected for processing (3)
  • src/NimBLEClient.cpp
  • src/NimBLEClient.h
  • src/NimBLEDevice.cpp
✅ Files skipped from review due to trivial changes (1)
  • src/NimBLEClient.h
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/NimBLEDevice.cpp

@h2zero h2zero merged commit 4746c60 into master Mar 25, 2026
42 checks passed
@h2zero h2zero deleted the bugfix/client-connection-state branch March 25, 2026 18:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants