From fdb0692a4aba05b2329593a5f24f85b8bcef616e Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 13:59:37 +0800 Subject: [PATCH 1/7] DEV-1247 BLE connect: don't block the main thread on the MTU; fail on notify/connect errors onConnectSuccess runs on FastBle's main-thread handler and waited 3 s for an MTU result that FastBle delivers on that same thread, so the wait always timed out and every connect froze the UI for ~3.1 s. Setup now continues from the MTU callback (success or failure) and initialize() waits for the RX notification to be enabled: MTU, then notify, then initialize. A failed connect, a failed notify subscription or a missing RX characteristic now logs the reason, disconnects, sets CONNECTION_FAILED and lets connect() return, instead of leaving the driver timing out on commands with nothing in the log. HIL (-Transport ble, Shimmer3R): connect ~3 s faster, no PerfMonitor longMsg from BleBluetooth$MainHandler. Co-Authored-By: Claude Opus 5.5 --- .../Shimmer3BLEAndroid.java | 117 ++++++++++++------ 1 file changed, 76 insertions(+), 41 deletions(-) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index ee3646a9..52d25918 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -126,59 +126,33 @@ public void onStartConnect() { @Override public void onConnectFail(BleDevice bleDevice, BleException exception) { - + connectionFailed("Connect Failure: " + exception); } @Override - public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) { + public void onConnectSuccess(final BleDevice bleDevice, final BluetoothGatt gatt, int status) { mBuffer = new ThreadSafeByteFifoBuffer(1000000); + mBleDevice = bleDevice; mTaskMTU = new TaskCompletionSource<>(); + // 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 (mTaskMTU.trySetResult("MTU Failure")) { + onMtuSet(bleDevice, gatt); + } } @Override public void onMtuChanged(int mtu) { System.out.println("MTU Changed: " + mtu); - mTaskMTU.setResult("MTU Changed: " + mtu); + if (mTaskMTU.trySetResult("MTU Changed: " + mtu)) { + onMtuSet(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); - } - - 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"); - //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, - //new ObjectCluster("", bleDevice.getMac(), BT_STATE.CONNECTED)).sendToTarget(); - sendCallBackMsg(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, new ObjectCluster("", bleDevice.getMac(), BT_STATE.CONNECTED)); - Bundle bundle = new Bundle(); - bundle.putString(TOAST, "Device connection established"); - sendMsgToHandlerList(MESSAGE_TOAST, bundle); - - mIOThread = new IOThread(); - mIOThread.start(); - if (mUseProcessingThread){ - mPThread = new ProcessingThread(); - mPThread.start(); - } - - initialize(); } @Override @@ -206,9 +180,65 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl } } + /** + * Continues connect once the MTU request has finished, whether or not it succeeded. + * The rest of setup waits for the RX notification, see {@link #onNotifyEnabled(BleDevice)} + */ + private void onMtuSet(BleDevice bleDevice, BluetoothGatt gatt) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { + gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); + } + + startServiceS(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(BleDevice bleDevice) { + if (!mTaskConnect.trySetResult("Connected")) { + return; + } + System.out.println(bleDevice.getMac() + " Connected"); + //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, + //new ObjectCluster("", bleDevice.getMac(), BT_STATE.CONNECTED)).sendToTarget(); + sendCallBackMsg(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, new ObjectCluster("", bleDevice.getMac(), BT_STATE.CONNECTED)); + Bundle bundle = new Bundle(); + bundle.putString(TOAST, "Device connection established"); + sendMsgToHandlerList(MESSAGE_TOAST, bundle); + + mIOThread = new IOThread(); + mIOThread.start(); + if (mUseProcessingThread){ + mPThread = new ProcessingThread(); + mPThread.start(); + } + + initialize(); + } + + /** + * Indicate that the connection attempt failed and notify the UI Activity + */ + private void connectionFailed(String reason) { + System.out.println(mMyBluetoothAddress + " " + reason); + if (!mTaskConnect.trySetResult(reason)) { + return; + } + BleManager.getInstance().disconnect(mBleDevice); + setBluetoothRadioState(BT_STATE.CONNECTION_FAILED); + Bundle bundle = new Bundle(); + bundle.putString(TOAST, "Unable to connect device"); + sendMsgToHandlerList(MESSAGE_TOAST, bundle); + } + public void startServiceS(BleDevice bleDevice) { List services = BleManager.getInstance().getBluetoothGattServices(bleDevice); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { + boolean isRxFound = false; + if (services != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { for (BluetoothGattService service : services) { @@ -219,6 +249,7 @@ public void startServiceS(BleDevice bleDevice) { //newConnectedBLEDevice(bleDevice,characteristic); CharSequence text = "TXID!"; } else if (characteristic.getUuid().compareTo(rxid) == 0) { + isRxFound = true; newConnectedBLEDevice(bleDevice, characteristic); CharSequence text = "RxID!"; } @@ -228,6 +259,9 @@ public void startServiceS(BleDevice bleDevice) { } + if (!isRxFound) { + connectionFailed("RX characteristic not found"); + } } /** @@ -248,12 +282,13 @@ public void newConnectedBLEDevice(final BleDevice bleDevice, final BluetoothGatt @Override public void onNotifySuccess() { - + System.out.println("Notify Success"); + onNotifyEnabled(bleDevice); } @Override public void onNotifyFailure(BleException exception) { - + connectionFailed("Notify Failure: " + exception); } @Override From f7a2398dd200a4d06e1ac64e118015e3a4b70dfa Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 15:20:11 +0800 Subject: [PATCH 2/7] DEV-1247 Review fixes: disconnect the callback's device; per-attempt MTU task; no "lost" report for a failed connect - connectionFailed() disconnects the BleDevice the failing callback was given, not mBleDevice, which is unset or stale on the onConnectFail path. - The MTU callback completes a task local to its attempt, so a late MTU result after a timeout can't complete a later attempt's task. - onDisConnected only reports DISCONNECTED and "connection was lost" for a connection that reached Connected. A failed setup is already reported as CONNECTION_FAILED, and the toasts contradicted each other. Shimmer3R BLE HIL: streamRest and reconnectLoop (5/5) pass, no main-thread longMsg. Co-Authored-By: Claude Opus 5.5 --- .../Shimmer3BLEAndroid.java | 23 ++++++++++++------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index 52d25918..30c6e5bf 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -126,21 +126,23 @@ public void onStartConnect() { @Override public void onConnectFail(BleDevice bleDevice, BleException exception) { - connectionFailed("Connect Failure: " + exception); + connectionFailed(bleDevice, "Connect Failure: " + exception); } @Override public void onConnectSuccess(final BleDevice bleDevice, final BluetoothGatt gatt, int status) { mBuffer = new ThreadSafeByteFifoBuffer(1000000); mBleDevice = bleDevice; - mTaskMTU = new TaskCompletionSource<>(); + // This attempt's own task, so a late MTU result can't complete a later attempt's + 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: " + exception); - if (mTaskMTU.trySetResult("MTU Failure")) { + if (taskMTU.trySetResult("MTU Failure")) { onMtuSet(bleDevice, gatt); } } @@ -148,7 +150,7 @@ public void onSetMTUFailure(BleException exception) { @Override public void onMtuChanged(int mtu) { System.out.println("MTU Changed: " + mtu); - if (mTaskMTU.trySetResult("MTU Changed: " + mtu)) { + if (taskMTU.trySetResult("MTU Changed: " + mtu)) { onMtuSet(bleDevice, gatt); } } @@ -157,6 +159,11 @@ public void onMtuChanged(int mtu) { @Override public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) { + if (!"Connected".equals(mTaskConnect.getTask().getResult())) { + // Setup never finished: connectionFailed() reports it as CONNECTION_FAILED, not as a lost connection + System.out.println(bleDevice.getMac() + " Disconnected during connect"); + return; + } //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, //new ObjectCluster("", bleDevice.getMac(), BT_STATE.DISCONNECTED)).sendToTarget(); sendCallBackMsg(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, new ObjectCluster("", bleDevice.getMac(), BT_STATE.DISCONNECTED)); @@ -223,12 +230,12 @@ private void onNotifyEnabled(BleDevice bleDevice) { /** * Indicate that the connection attempt failed and notify the UI Activity */ - private void connectionFailed(String reason) { + private void connectionFailed(BleDevice bleDevice, String reason) { System.out.println(mMyBluetoothAddress + " " + reason); if (!mTaskConnect.trySetResult(reason)) { return; } - BleManager.getInstance().disconnect(mBleDevice); + BleManager.getInstance().disconnect(bleDevice); setBluetoothRadioState(BT_STATE.CONNECTION_FAILED); Bundle bundle = new Bundle(); bundle.putString(TOAST, "Unable to connect device"); @@ -260,7 +267,7 @@ public void startServiceS(BleDevice bleDevice) { } if (!isRxFound) { - connectionFailed("RX characteristic not found"); + connectionFailed(bleDevice, "RX characteristic not found"); } } @@ -288,7 +295,7 @@ public void onNotifySuccess() { @Override public void onNotifyFailure(BleException exception) { - connectionFailed("Notify Failure: " + exception); + connectionFailed(bleDevice, "Notify Failure: " + exception); } @Override From d67ff5d122485f322d90321dd9de812cdfce09d4 Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 15:30:05 +0800 Subject: [PATCH 3/7] DEV-1247 Review fixes: fail a setup-time disconnect at once; ignore a late success after a failure - onDisConnected before setup finished now calls connectionFailed(), so connect() returns and CONNECTION_FAILED is set straight away instead of after an MTU/notify timeout or connect()'s 10 s wait. - connect() keeps this attempt's own task. onDisConnected, onConnectSuccess and the wait use it, so a late callback from an earlier attempt can't complete or fail a newer one. - A late onConnectSuccess for an attempt that has already failed is disconnected instead of set up. - A missing services list is reported as such, not as a missing RX characteristic. - Comments on the per-attempt tasks spelled out. Shimmer3R BLE HIL: streamRest and reconnectLoop (5/5) pass, no main-thread longMsg. Co-Authored-By: Claude Opus 5.5 --- .../Shimmer3BLEAndroid.java | 28 ++++++++++++++----- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index 30c6e5bf..33ac19e6 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -117,7 +117,9 @@ public void sendCallBackMsg(int msgid,Object obj){ */ @Override public void connect(String s, String s1) { - 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(mMyBluetoothAddress, new BleGattCallback() { @Override public void onStartConnect() { @@ -131,9 +133,14 @@ public void onConnectFail(BleDevice bleDevice, BleException exception) { @Override public void onConnectSuccess(final BleDevice bleDevice, final BluetoothGatt gatt, int status) { + if (taskConnect.getTask().isCompleted()) { + // This attempt has already failed, so drop a late success instead of setting it up + BleManager.getInstance().disconnect(bleDevice); + return; + } mBuffer = new ThreadSafeByteFifoBuffer(1000000); mBleDevice = bleDevice; - // This attempt's own task, so a late MTU result can't complete a later attempt's + // 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 @@ -159,9 +166,12 @@ public void onMtuChanged(int mtu) { @Override public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) { - if (!"Connected".equals(mTaskConnect.getTask().getResult())) { - // Setup never finished: connectionFailed() reports it as CONNECTION_FAILED, not as a lost connection - System.out.println(bleDevice.getMac() + " Disconnected during connect"); + if (!"Connected".equals(taskConnect.getTask().getResult())) { + // Setup never finished, so this is a failed connect (CONNECTION_FAILED), not a lost connection. + // Fail it now rather than wait for the MTU or notify timeout. + if (!taskConnect.getTask().isCompleted() && taskConnect == mTaskConnect) { + connectionFailed(bleDevice, "Disconnected during connect"); + } return; } //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, @@ -177,7 +187,7 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl try { - boolean result = mTaskConnect.getTask().waitForCompletion(10, TimeUnit.SECONDS); + boolean result = taskConnect.getTask().waitForCompletion(10, TimeUnit.SECONDS); Thread.sleep(200); if (!result) { System.out.println("Connect fail"); @@ -244,8 +254,12 @@ private void connectionFailed(BleDevice bleDevice, String reason) { public void startServiceS(BleDevice bleDevice) { List services = BleManager.getInstance().getBluetoothGattServices(bleDevice); + if (services == null) { + connectionFailed(bleDevice, "GATT services not available"); + return; + } boolean isRxFound = false; - if (services != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { for (BluetoothGattService service : services) { From 57f064b7d55a6f091254ff175e3fd13cbd359dea Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 15:44:26 +0800 Subject: [PATCH 4/7] DEV-1247 Review fix: carry the connect attempt's task through every setup step onMtuSet, startServiceS, newConnectedBLEDevice and their callbacks now carry the task of the connect attempt they belong to. onNotifyEnabled and connectionFailed ignore an attempt that is no longer current, so a late notify or service result from an earlier attempt can't mark a newer one Connected, fail it, or disconnect it. The public startServiceS and newConnectedBLEDevice keep their signatures and use the current attempt. Shimmer3R BLE HIL: streamRest and reconnectLoop (5/5) pass, no main-thread longMsg. Co-Authored-By: Claude Opus 5.5 --- .../Shimmer3BLEAndroid.java | 43 +++++++++++-------- 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index 33ac19e6..6aaa5429 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -128,7 +128,7 @@ public void onStartConnect() { @Override public void onConnectFail(BleDevice bleDevice, BleException exception) { - connectionFailed(bleDevice, "Connect Failure: " + exception); + connectionFailed(taskConnect, bleDevice, "Connect Failure: " + exception); } @Override @@ -150,7 +150,7 @@ public void onConnectSuccess(final BleDevice bleDevice, final BluetoothGatt gatt public void onSetMTUFailure(BleException exception) { System.out.println("MTU Failure: " + exception); if (taskMTU.trySetResult("MTU Failure")) { - onMtuSet(bleDevice, gatt); + onMtuSet(taskConnect, bleDevice, gatt); } } @@ -158,7 +158,7 @@ public void onSetMTUFailure(BleException exception) { public void onMtuChanged(int mtu) { System.out.println("MTU Changed: " + mtu); if (taskMTU.trySetResult("MTU Changed: " + mtu)) { - onMtuSet(bleDevice, gatt); + onMtuSet(taskConnect, bleDevice, gatt); } } }); @@ -169,9 +169,7 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl if (!"Connected".equals(taskConnect.getTask().getResult())) { // Setup never finished, so this is a failed connect (CONNECTION_FAILED), not a lost connection. // Fail it now rather than wait for the MTU or notify timeout. - if (!taskConnect.getTask().isCompleted() && taskConnect == mTaskConnect) { - connectionFailed(bleDevice, "Disconnected during connect"); - } + connectionFailed(taskConnect, bleDevice, "Disconnected during connect"); return; } //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, @@ -199,14 +197,15 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl /** * Continues connect once the MTU request has finished, whether or not it succeeded. - * The rest of setup waits for the RX notification, see {@link #onNotifyEnabled(BleDevice)} + * The rest of setup waits for the RX notification, 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(BleDevice bleDevice, BluetoothGatt gatt) { + private void onMtuSet(TaskCompletionSource taskConnect, BleDevice bleDevice, BluetoothGatt gatt) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH); } - startServiceS(bleDevice); + 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); } @@ -215,8 +214,8 @@ private void onMtuSet(BleDevice bleDevice, BluetoothGatt gatt) { /** * Finishes connect once the RX notification is enabled, as no reply from the device can arrive before then */ - private void onNotifyEnabled(BleDevice bleDevice) { - if (!mTaskConnect.trySetResult("Connected")) { + private void onNotifyEnabled(TaskCompletionSource taskConnect, BleDevice bleDevice) { + if (taskConnect != mTaskConnect || !taskConnect.trySetResult("Connected")) { return; } System.out.println(bleDevice.getMac() + " Connected"); @@ -240,9 +239,9 @@ private void onNotifyEnabled(BleDevice bleDevice) { /** * Indicate that the connection attempt failed and notify the UI Activity */ - private void connectionFailed(BleDevice bleDevice, String reason) { + private void connectionFailed(TaskCompletionSource taskConnect, BleDevice bleDevice, String reason) { System.out.println(mMyBluetoothAddress + " " + reason); - if (!mTaskConnect.trySetResult(reason)) { + if (taskConnect != mTaskConnect || !taskConnect.trySetResult(reason)) { return; } BleManager.getInstance().disconnect(bleDevice); @@ -253,9 +252,13 @@ private void connectionFailed(BleDevice bleDevice, String reason) { } 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(bleDevice, "GATT services not available"); + connectionFailed(taskConnect, bleDevice, "GATT services not available"); return; } boolean isRxFound = false; @@ -271,7 +274,7 @@ public void startServiceS(BleDevice bleDevice) { CharSequence text = "TXID!"; } else if (characteristic.getUuid().compareTo(rxid) == 0) { isRxFound = true; - newConnectedBLEDevice(bleDevice, characteristic); + newConnectedBLEDevice(taskConnect, bleDevice, characteristic); CharSequence text = "RxID!"; } } @@ -281,7 +284,7 @@ public void startServiceS(BleDevice bleDevice) { } if (!isRxFound) { - connectionFailed(bleDevice, "RX characteristic not found"); + connectionFailed(taskConnect, bleDevice, "RX characteristic not found"); } } @@ -292,6 +295,10 @@ public void startServiceS(BleDevice bleDevice) { * @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; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { BleManager.getInstance().notify( @@ -304,12 +311,12 @@ public void newConnectedBLEDevice(final BleDevice bleDevice, final BluetoothGatt @Override public void onNotifySuccess() { System.out.println("Notify Success"); - onNotifyEnabled(bleDevice); + onNotifyEnabled(taskConnect, bleDevice); } @Override public void onNotifyFailure(BleException exception) { - connectionFailed(bleDevice, "Notify Failure: " + exception); + connectionFailed(taskConnect, bleDevice, "Notify Failure: " + exception); } @Override From ef7f7d2af5e5554d9a1ce4f08bc6ad6386d2ea10 Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 15:45:53 +0800 Subject: [PATCH 5/7] DEV-1247 Review fix: ignore a connect success from a superseded attempt onConnectSuccess returns at once if a newer connect() has replaced this attempt's task, so it can't overwrite the newer attempt's device, buffer or MTU task. It doesn't disconnect: the newer attempt owns the same device. Co-Authored-By: Claude Opus 5.5 --- .../androidradiodriver/Shimmer3BLEAndroid.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index 6aaa5429..ddd28b59 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -133,6 +133,10 @@ public void onConnectFail(BleDevice bleDevice, BleException exception) { @Override 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); From a0d676f368175cd11fec3bb217ee1b7b2b067905 Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 15:53:46 +0800 Subject: [PATCH 6/7] DEV-1247 Review fixes: a caller's disconnect during setup isn't a failure; skip a late MTU result - onDisConnected before setup finished: an active disconnect (the caller's own disconnect()) ends the attempt quietly instead of setting CONNECTION_FAILED over the DISCONNECTED it already set. Only a dropped link is reported as a failed connect. - onMtuSet returns at once if its attempt has failed or been replaced while the MTU was pending, so it doesn't request priority or notifications on a dead or stale link. Shimmer3R BLE HIL reconnectLoop 5/5, no main-thread longMsg. Co-Authored-By: Claude Opus 5.5 --- .../androidradiodriver/Shimmer3BLEAndroid.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index ddd28b59..3c83ab67 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -171,9 +171,14 @@ public void onMtuChanged(int mtu) { @Override public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) { if (!"Connected".equals(taskConnect.getTask().getResult())) { - // Setup never finished, so this is a failed connect (CONNECTION_FAILED), not a lost connection. - // Fail it now rather than wait for the MTU or notify timeout. - connectionFailed(taskConnect, bleDevice, "Disconnected during connect"); + // Setup never finished, so this is not a lost connection + if (isActiveDisConnected) { + // disconnect() was called during setup: end this attempt without reporting a failure + taskConnect.trySetResult("Disconnected"); + } else { + // The link dropped: fail the connect now rather than wait for the MTU or notify timeout + connectionFailed(taskConnect, bleDevice, "Disconnected during connect"); + } return; } //mHandler.obtainMessage(ShimmerBluetooth.MSG_IDENTIFIER_STATE_CHANGE, -1, -1, @@ -205,6 +210,10 @@ public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, Bl * 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); } From 5c8ecc14921e32bde516658152b2fd990f0371b1 Mon Sep 17 00:00:00 2001 From: JongChern Date: Tue, 20 Oct 2026 16:00:47 +0800 Subject: [PATCH 7/7] DEV-1247 Review fix: ignore a superseded attempt's disconnect onDisConnected returns at once if a newer connect() has replaced this attempt, so an old link going down after disconnect() and a quick reconnect can't report DISCONNECTED or "connection was lost" over the new attempt. Shimmer3R BLE HIL reconnectLoop: cycles 1-4 connect and report their disconnects as before. Cycle 5 hit the separate GATT 133 at link setup that is open on the PR. Co-Authored-By: Claude Opus 5.5 --- .../androidradiodriver/Shimmer3BLEAndroid.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java index 3c83ab67..0b6f2e14 100644 --- a/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java +++ b/ShimmerAndroidInstrumentDriver/ShimmerAndroidInstrumentDriver/src/main/java/com/shimmerresearch/androidradiodriver/Shimmer3BLEAndroid.java @@ -170,6 +170,10 @@ public void onMtuChanged(int mtu) { @Override public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) { + if (taskConnect != mTaskConnect) { + // An earlier connection's link went down after a newer connect() started: not this one's state + return; + } if (!"Connected".equals(taskConnect.getTask().getResult())) { // Setup never finished, so this is not a lost connection if (isActiveDisConnected) {