h2zero / NimBLE-Arduino

A fork of the NimBLE library structured for compilation with Arduino, for use with ESP32, nRF5x.
https://h2zero.github.io/NimBLE-Arduino/
Apache License 2.0
698 stars 144 forks source link

BLE Server keeps notify subscriber after client disconnection #718

Open chall3ng3r opened 1 week ago

chall3ng3r commented 1 week ago

I am working with a Flutter based Android app which connects to ESP32 via NimBLE-Arduino.

I've noticed that if the mobile app disconnects from ESP32, the notify subscription is kept by the ESP32. When same mobile app client connects back, the subscriber count is shown as one, which is incorrect as the mobile client have not yet sent the request to notify from the new connection.

On ESP32, I have a check if subscriber count is one, then update the value and call notify. Which starts immediately, but the mobile app never receives these until I subscribe > unsubscribe > subscribe from the mobile app. After this, I start getting the notifications.

I have the callback set for disconnect event on ESP32, but I am not able to find a way in NimBLE lib to unsubscribe disconnected client from all notify subscriptions.

Let me know if there's a way to manually unsubscribe clients when they disconnect from server on ESP32.

Thanks.

void notifyUpdate()
{
    // check if there is a connection
    if (pServer && pServer->getConnectedCount() == 0)
    {
        return;
    }

    // check if there is a subscribed client << this is automatically one when client reconnects
    if (pCharacteristic1->getSubscribedCount() > 0)
    {
        // update data
        pCharacteristic1->setValue(123);

        // notify client
        pCharacteristic1->notify(true); << client never get these if it reconnects
    }
}
h2zero commented 6 days ago

Is your phone bonded to the esp32?

chall3ng3r commented 4 days ago

Yes, phone is bonded to ESP32.