This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

How to return BLE peripheral's connection status

I'm writing an Android application that connects to various BLE peripherals including the NRF51 and NRF52. I don't know if this question is appropriate for this site, but here it goes.

I noticed that the method onConnectionStateChange() from Android ble API is not invariably invoked (or just not invoked on time) when a peripheral is non-manually disconnected like for example when the peripheral is powered off. Is there a way to get the connection state of a connected BLE peripheral manually versus just waiting for the onConnectionStateChange() to fire? I tried using BluetoothManager#getConnectionState but this method seems to be accessing the connection state updated by whatever thread is calling onConnectionStateChange(), and does not actually ask the device if it's connected. In other words, BluetoothManager#getConnectionState just returns false if onConnectionStateChange() hasn't been called yet.

Here is my isConnected method in an Android application I'm writing

public boolean isConnected(){
    
    // If the device has never connected, it's gatt service is null.
    if(mGatt != null){
    
        BluetoothManager btm =
                (BluetoothManager)
                        MainActivity.mMainActivity.getSystemService(Context.BLUETOOTH_SERVICE);
                        
        int state = btm.getConnectionState(mGatt.getDevice(), BluetoothProfile.GATT);

        return state == 2;
    }

    // The gat service is null, the device is not connected, return false.
    return false;
}
Parents
  • Hi Michael,

    I would assume that you want to have onConnectionStateChange() involked right away when you power off the device ?

    Note that there is one parameter in a connection parameters which is connection supervision timeout. The central will continue to send connection events packet even it doesn't receive anything from the peripheral until the supervision timeout occurs.

    This is because if there is an interference occurs for a short period of time the connection still can be restored.

    You can reduce the time the central waiting by requesting shorter supervision timeout from the peripheral side.

  • The beacon can request the connection timeout to be updated. But it's the phone who decide which number the timeout should be. You can refer to CONN_SUP_TIMEOUT in the nRF51 firmware. Usually we set it to 4 seconds.

Reply Children
No Data
Related