Skip to content

Commit

Permalink
Wait a bit between stopping LE scan and connecting
Browse files Browse the repository at this point in the history
To see if it helps @ReidarHH in #335
  • Loading branch information
erijo committed Oct 8, 2018
1 parent 2f1b766 commit 960c7e8
Showing 1 changed file with 21 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ public void connect(String hwAddress) {
}
else {
Timber.d("No coarse location permission, connecting without LE scan");
connectGatt(hwAddress);
connectGatt(btAdapter.getRemoteDevice(hwAddress));
}
}

Expand Down Expand Up @@ -460,8 +460,16 @@ private void connectGatt(BluetoothDevice device) {
}
}

private void connectGatt(String hwAddress) {
connectGatt(btAdapter.getRemoteDevice(hwAddress));
private void stopLeScanAndConnectGatt(final BluetoothDevice device) {
stopLeScan();

// Delay the call to connectGatt to let things settle a bit
handler.postDelayed(new Runnable() {
@Override
public void run() {
connectGatt(device);
}
}, 500);
}

private void startLeScanForDevice(final String hwAddress) {
Expand All @@ -476,27 +484,28 @@ public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
handler.post(new Runnable() {
@Override
public void run() {
// Check that callback != null in case the same device is found multiple times
// and thus multiple calls to connect to it are queued. Only the first will
// have callback != null.
if (leScanCallback != null) {
stopLeScan();
connectGatt(device);
stopLeScanAndConnectGatt(device);
}
}
});
}
};

Timber.d("Starting LE scan for device [%s]", hwAddress);
btAdapter.startLeScan(leScanCallback);

// Stop scan and try to connect to the device directly if the device isn't found in time
handler.postAtTime(new Runnable() {
@Override
public void run() {
Timber.d("Device not found in LE scan, connecting directly");
stopLeScan();
connectGatt(hwAddress);
stopLeScanAndConnectGatt(btAdapter.getRemoteDevice(hwAddress));
}
}, leScanCallback, SystemClock.uptimeMillis() + LE_SCAN_TIMEOUT_MS);

Timber.d("Starting LE scan for device [%s]", hwAddress);
btAdapter.startLeScan(leScanCallback);
}

private void stopLeScan() {
Expand All @@ -515,6 +524,8 @@ public void disconnect(boolean doCleanup) {
stopLeScan();

if (bluetoothGatt == null) {
// Could be a pending connectGatt waiting
handler.removeCallbacksAndMessages(null);
return;
}

Expand Down

0 comments on commit 960c7e8

Please sign in to comment.