Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Close gatt when disconnecting #49

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.annotation.SuppressLint;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
Expand All @@ -16,6 +17,7 @@
import com.uber.rxcentralble.ConnectionManager;
import com.uber.rxcentralble.PeripheralManager;
import com.uber.rxcentralble.Irrelevant;
import com.uber.rxcentralble.Peripheral;
import com.uber.rxcentralble.RxCentralLogger;
import com.uber.rxcentralble.ScanMatcher;
import com.uber.rxcentralble.Scanner;
Expand Down Expand Up @@ -55,6 +57,9 @@ public class MainActivity extends AppCompatActivity {
@BindView(R.id.toggleButtonDirectConnect)
ToggleButton directConnectToggle;

@BindView(R.id.toggleButtonMacAddress)
ToggleButton nameOrMacToggle;

Disposable bluetoothDetection;
Disposable connection;

Expand Down Expand Up @@ -195,17 +200,43 @@ public void bleDetect(CompoundButton button, boolean checked) {
}
}

@OnCheckedChanged(R.id.toggleButtonDirectConnect)
public void directConnect(CompoundButton button, boolean checked) {
nameOrMacToggle.setChecked(false);
nameOrMacToggle.setEnabled(!checked);
}

@OnCheckedChanged(R.id.toggleButtonMacAddress)
public void nameOrMac(CompoundButton button, boolean checked) {
nameEditText.setText("");
if (checked) {
nameEditText.setHint(R.string.hint_mac);
} else {
nameEditText.setHint(R.string.hint_name);
}
}

private void connect() {
if (connection == null) {
String name = nameEditText.getEditableText().toString();
if (!TextUtils.isEmpty(name)) {
Timber.i("Connect to: " + name);
String nameOrMac = nameEditText.getEditableText().toString();
if (!TextUtils.isEmpty(nameOrMac)) {
Timber.i("Connect to: " + nameOrMac);
connectButton.setText("Cancel");

connection = connectionManager
.connect(new NameScanMatcher(name),
DEFAULT_SCAN_TIMEOUT * 20,
DEFAULT_CONNECTION_TIMEOUT)
nameOrMacToggle.setEnabled(false);
directConnectToggle.setEnabled(false);

Observable<Peripheral> pendingConnection;
if (nameOrMacToggle.isChecked()) {
pendingConnection = connectionManager
.connect(BluetoothAdapter.getDefaultAdapter().getRemoteDevice(nameOrMac),
DEFAULT_CONNECTION_TIMEOUT);
} else {
pendingConnection = connectionManager
.connect(new NameScanMatcher(nameOrMac),
DEFAULT_SCAN_TIMEOUT * 20,
DEFAULT_CONNECTION_TIMEOUT);
}
connection = pendingConnection
.retryWhen(errors ->
errors.flatMap(
error -> {
Expand All @@ -220,14 +251,18 @@ private void connect() {
peripheralManager.setPeripheral(peripheral);

AndroidSchedulers.mainThread().scheduleDirect(() -> connectButton.setText("Disconnect"));
Timber.i("Connected to: " + name);
Timber.i("Connected to: " + nameOrMac);
Timber.i("Max Write Length (MTU): " + peripheral.getMaxWriteLength());
},
error -> {
connection.dispose();
connection = null;

AndroidSchedulers.mainThread().scheduleDirect(() -> connectButton.setText("Connect"));
AndroidSchedulers.mainThread().scheduleDirect(() -> {
connectButton.setText("Connect");
enableByNameOrMacAfterConnection();
directConnectToggle.setEnabled(true);
});
Timber.i("Connection error: " + error.getMessage());
}
);
Expand All @@ -238,6 +273,8 @@ private void connect() {
connection = null;

connectButton.setText("Connect");
enableByNameOrMacAfterConnection();
directConnectToggle.setEnabled(true);
Timber.i("Disconnected");
}
}
Expand All @@ -248,6 +285,8 @@ private void directConnect() {
if (!TextUtils.isEmpty(name)) {
Timber.i("Connect to: " + name);
connectButton.setText("Cancel");
nameOrMacToggle.setEnabled(false);
directConnectToggle.setEnabled(false);

ScanMatcher scanMatcher = new NameScanMatcher(name);
connection = scanner
Expand Down Expand Up @@ -279,7 +318,11 @@ private void directConnect() {
connection.dispose();
connection = null;

AndroidSchedulers.mainThread().scheduleDirect(() -> connectButton.setText("Connect"));
AndroidSchedulers.mainThread().scheduleDirect(() -> {
connectButton.setText("Connect");
enableByNameOrMacAfterConnection();
directConnectToggle.setEnabled(true);
});
Timber.i("Connection error: " + error.getMessage());
}
);
Expand All @@ -290,7 +333,13 @@ private void directConnect() {
connection = null;

connectButton.setText("Connect");
enableByNameOrMacAfterConnection();
directConnectToggle.setEnabled(true);
Timber.i("Disconnected");
}
}

private void enableByNameOrMacAfterConnection() {
nameOrMacToggle.setEnabled(!directConnectToggle.isChecked());
}
}
19 changes: 18 additions & 1 deletion rx-central-ble-sample/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,36 @@
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="name"
android:hint="@string/hint_name"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="@id/toggleButtonMacAddress"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ToggleButton
android:id="@+id/toggleButtonMacAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="ToggleButton"
android:textOff="By Name"
android:textOn="By Mac"
android:visibility="visible"
app:layout_constraintEnd_toStartOf="@id/buttonConnect"
app:layout_constraintStart_toEndOf="@+id/nameEditText"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonConnect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="17dp"
android:text="Connect"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/toggleButtonMacAddress"
app:layout_constraintTop_toTopOf="parent" />

<TextView
Expand Down
2 changes: 2 additions & 0 deletions rx-central-ble-sample/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<resources>
<string name="app_name">RxCentralBle Sample</string>
<string name="hint_name">name</string>
<string name="hint_mac">mac</string>
</resources>
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ public class CorePeripheral implements Peripheral {
@Nullable private SingleSubject<Integer> readRssiSubject;

private int mtu = DEFAULT_MTU;
private Boolean isConnected = false;

public CorePeripheral(BluetoothDevice device, Context context) {
this.context = context;
Expand Down Expand Up @@ -201,6 +202,9 @@ public void disconnect() {
synchronized (syncRoot) {
if (bluetoothGatt != null) {
bluetoothGatt.disconnect();
if (!isConnected) {
bluetoothGatt.close();
}
bluetoothGatt = null;
}

Expand Down Expand Up @@ -517,6 +521,7 @@ public void onConnectionStateChange(
if (connectionStateSubject != null) {
if (newState == BluetoothGatt.STATE_CONNECTED) {
if (status == 0) {
isConnected = true;
if (!gatt.discoverServices()) {
connectionStateSubject.onError(
new ConnectionError(
Expand All @@ -541,6 +546,7 @@ public void onConnectionStateChange(
}

gatt.close();
isConnected = false;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
Expand Down Expand Up @@ -147,6 +148,7 @@ public void connect_gattCallback_nonZeroStatus() {
});

verify(bluetoothGatt).disconnect();
verify(bluetoothGatt).close();
}

@Test
Expand All @@ -171,6 +173,7 @@ public void connect_serviceDiscoveryGattFailed() {
});

verify(bluetoothGatt).disconnect();
verify(bluetoothGatt, never()).close();
}

@Test
Expand Down Expand Up @@ -199,6 +202,7 @@ public void connect_serviceDiscovery_gattCallback_nonZeroStatus() {
});

verify(bluetoothGatt).disconnect();
verify(bluetoothGatt, never()).close();
}

@Test
Expand Down Expand Up @@ -872,6 +876,16 @@ public void disconnect() {
ConnectionError error = (ConnectionError) throwable;
return error != null && error.getCode() == DISCONNECTION;
});
verify(bluetoothGatt, never()).close();
}

@Test
public void disconnect_notConnected() {
prepareConnect(false);

corePeripheral.disconnect();

verify(bluetoothGatt).close();
}

private void prepareConnect(boolean discoverServiceSuccess) {
Expand Down