diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/VerisenseBleAndroidRadioByteCommunication.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/VerisenseBleAndroidRadioByteCommunication.java index 33a89603..22cf44fc 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/VerisenseBleAndroidRadioByteCommunication.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/VerisenseBleAndroidRadioByteCommunication.java @@ -63,7 +63,9 @@ public VerisenseBleAndroidRadioByteCommunication(String mac) { */ @Override public void connect() { - mTaskConnect = new TaskCompletionSource<>(); + // Task for this attempt only, so a late callback from an earlier attempt can't complete or fail this one + final TaskCompletionSource taskConnect = new TaskCompletionSource<>(); + mTaskConnect = taskConnect; BleManager.getInstance().connect(mMac, new BleGattCallback() { @Override public void onStartConnect() { @@ -72,58 +74,58 @@ public void onStartConnect() { @Override public void onConnectFail(BleDevice bleDevice, BleException exception) { - if (mByteCommunicationListener != null) { - mByteCommunicationListener.eventDisconnected(); - } + connectionFailed(taskConnect, bleDevice, "Connect Failure: " + exception); } @Override - public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { - mTaskMTU= new TaskCompletionSource<>(); + public void onConnectSuccess(final BleDevice bleDevice, final BluetoothGatt gatt, int status) { + if (taskConnect != mTaskConnect) { + // A newer connect() owns this device now, so leave its link alone + return; + } + if (taskConnect.getTask().isCompleted()) { + // This attempt has already failed, so drop a late success instead of setting it up + BleManager.getInstance().disconnect(bleDevice); + return; + } + mBleDevice = bleDevice; + // MTU task for this attempt only, so a late MTU result can't complete the MTU task of a later attempt + final TaskCompletionSource taskMTU = new TaskCompletionSource<>(); + mTaskMTU = taskMTU; + // FastBle runs this and the MTU callback on the main thread, so waiting here for the + // MTU would block the UI and always time out. Setup continues from the callback instead. BleManager.getInstance().setMtu(bleDevice, 251, new BleMtuChangedCallback() { @Override public void onSetMTUFailure(BleException exception) { - System.out.println("MTU Failure"); - + System.out.println("MTU Failure: " + exception); + if (taskMTU.trySetResult("MTU Failure")) { + onMtuSet(taskConnect, bleDevice, gatt); + } } @Override public void onMtuChanged(int mtu) { System.out.println("MTU Changed: " + mtu); - mTaskMTU.setResult("MTU Changed: " + mtu); + if (taskMTU.trySetResult("MTU Changed: " + mtu)) { + onMtuSet(taskConnect, bleDevice, gatt); + } } }); - - try { - boolean result = mTaskMTU.getTask().waitForCompletion(3, TimeUnit.SECONDS); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); - } - - if (mByteCommunicationListener != null) { - mByteCommunicationListener.eventConnected(); - } - mBleDevice = bleDevice; - startServiceS(bleDevice); - System.out.println(bleDevice.getMac() + " Connected"); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - gatt.setPreferredPhy(BluetoothDevice.PHY_LE_2M_MASK, BluetoothDevice.PHY_LE_2M_MASK, BluetoothDevice.PHY_OPTION_NO_PREFERRED); - } - mTaskConnect.setResult("Connected"); } @Override public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) { + // Dropped before setup finished: fail the connect now rather than wait for the MTU or notify timeout + if (!taskConnect.getTask().isCompleted()) { + connectionFailed(taskConnect, bleDevice, "Disconnected during connect"); + } System.out.println(); } }); try { - boolean result = mTaskConnect.getTask().waitForCompletion(5, TimeUnit.SECONDS); + boolean result = taskConnect.getTask().waitForCompletion(5, TimeUnit.SECONDS); Thread.sleep(200); if (!result) { System.out.println("Connect fail"); @@ -133,12 +135,68 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl } } + /** + * Continues connect once the MTU request has finished, whether or not it succeeded. + * Connected is reported once the RX notification is enabled, see {@link #onNotifyEnabled(TaskCompletionSource, BleDevice)}. + * Each step carries its connect attempt's task, so results from an attempt that is no longer current are ignored. + */ + private void onMtuSet(TaskCompletionSource taskConnect, BleDevice bleDevice, BluetoothGatt gatt) { + if (taskConnect != mTaskConnect || taskConnect.getTask().isCompleted()) { + // The attempt failed or a newer one replaced it while the MTU was pending + return; + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); + } + + startServiceS(taskConnect, bleDevice); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + gatt.setPreferredPhy(BluetoothDevice.PHY_LE_2M_MASK, BluetoothDevice.PHY_LE_2M_MASK, BluetoothDevice.PHY_OPTION_NO_PREFERRED); + } + } + + /** + * Finishes connect once the RX notification is enabled, as no reply from the device can arrive before then + */ + private void onNotifyEnabled(TaskCompletionSource taskConnect, BleDevice bleDevice) { + if (taskConnect != mTaskConnect || !taskConnect.trySetResult("Connected")) { + return; + } + System.out.println(bleDevice.getMac() + " Connected"); + if (mByteCommunicationListener != null) { + mByteCommunicationListener.eventConnected(); + } + } + + /** + * The connection attempt failed: drop the link and tell the listener + */ + private void connectionFailed(TaskCompletionSource taskConnect, BleDevice bleDevice, String reason) { + System.out.println(mMac + " " + reason); + if (taskConnect != mTaskConnect || !taskConnect.trySetResult(reason)) { + return; + } + BleManager.getInstance().disconnect(bleDevice); + if (mByteCommunicationListener != null) { + mByteCommunicationListener.eventDisconnected(); + } + } + /** * Get services and start notify for characteristics changed * @param bleDevice BLE device */ public void startServiceS(BleDevice bleDevice){ + startServiceS(mTaskConnect, bleDevice); + } + + private void startServiceS(TaskCompletionSource taskConnect, BleDevice bleDevice){ List services = BleManager.getInstance().getBluetoothGattServices(bleDevice); + if (services == null) { + connectionFailed(taskConnect, bleDevice, "GATT services not available"); + return; + } + boolean isRxFound = false; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { @@ -151,7 +209,8 @@ public void startServiceS(BleDevice bleDevice){ CharSequence text = "TXID!"; } else if (characteristic.getUuid().compareTo(rxid)==0){ - newConnectedBLEDevice(bleDevice,characteristic); + isRxFound = true; + newConnectedBLEDevice(taskConnect, bleDevice,characteristic); CharSequence text = "RxID!"; } } @@ -160,6 +219,9 @@ else if (characteristic.getUuid().compareTo(rxid)==0){ } + if (!isRxFound) { + connectionFailed(taskConnect, bleDevice, "RX characteristic not found"); + } } /** @@ -168,6 +230,10 @@ else if (characteristic.getUuid().compareTo(rxid)==0){ * @param characteristic */ public void newConnectedBLEDevice(final BleDevice bleDevice, final BluetoothGattCharacteristic characteristic) { + newConnectedBLEDevice(mTaskConnect, bleDevice, characteristic); + } + + private void newConnectedBLEDevice(final TaskCompletionSource taskConnect, final BleDevice bleDevice, final BluetoothGattCharacteristic characteristic) { int count = 1; @@ -181,12 +247,13 @@ public void newConnectedBLEDevice(final BleDevice bleDevice, final BluetoothGatt @Override public void onNotifySuccess() { - + System.out.println("Notify Success"); + onNotifyEnabled(taskConnect, bleDevice); } @Override public void onNotifyFailure(BleException exception) { - + connectionFailed(taskConnect, bleDevice, "Notify Failure: " + exception); } @Override