Better handling of connection state and calls to gatt.close().

This commit is contained in:
Greg 2019-12-06 16:22:13 -05:00
parent a4a7dea4ba
commit ca70d55f7e
3 changed files with 31 additions and 0 deletions

BIN
Ble.jar

Binary file not shown.

View File

@ -126,6 +126,13 @@ public class BleConnect extends Fragment {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
BluetoothDevice device = gatt.getDevice();
String addr = device.getAddress();
if (status != BluetoothGatt.GATT_SUCCESS) {
Log.d("gio", "onConnectionStateChange: error code " + status);
onDisconnect(gatt, addr);
Log.d("gio", "gatt.close()");
gatt.close();
return;
}
switch (newState) {
case BluetoothProfile.STATE_CONNECTED: {
Log.d("gio", "Connected");
@ -133,14 +140,21 @@ public class BleConnect extends Fragment {
onConnect(gatt, addr);
break;
}
case BluetoothProfile.STATE_CONNECTING:
case BluetoothProfile.STATE_DISCONNECTING: {
break;
}
case BluetoothProfile.STATE_DISCONNECTED: {
Log.d("gio", "Disconnected");
onDisconnect(gatt, addr);
Log.d("gio", "gatt.close()");
gatt.close();
break;
}
default: {
Log.d("gio", "onConnectionStateChange: unknown state");
onDisconnect(gatt, addr);
Log.d("gio", "gatt.close()");
gatt.close();
break;
}
@ -177,7 +191,15 @@ public class BleConnect extends Fragment {
Log.d("gio","BleConnect: disconnect");
handler.post(new Runnable() {
public void run() {
boolean callClose = false;
BluetoothDevice device = gatt.getDevice();
if (device != null) {
callClose = (manager.getConnectionState(device, BluetoothProfile.GATT) != BluetoothGatt.STATE_CONNECTED);
}
gatt.disconnect();
if (callClose) {
gatt.close();
}
}
});
}

View File

@ -178,6 +178,9 @@ func (b *BLE) knownPeripheral(p Peripheral) (Peripheral, bool) {
//DiscoverServices asks a Peripheral for its Services
func (p Peripheral) DiscoverServices() {
if p.gatt == 0 {
return
}
connect()
log.Printf("discovering services")
runInJVM(func(env *C.JNIEnv) {
@ -188,6 +191,9 @@ func (p Peripheral) DiscoverServices() {
//DiscoverCharacteristics asks a Peripheral for the Characteristics related
//to a Service
func (p Peripheral) DiscoverCharacteristics(serv Service) {
if p.gatt == 0 {
return
}
//launch a goroutine because this function calls back directly
//from the same thread.
go func() {
@ -202,6 +208,9 @@ func (p Peripheral) DiscoverCharacteristics(serv Service) {
//SetNotifyValue subscribes to a characteristic
func (p Peripheral) SetNotifyValue(c Characteristic) {
if p.gatt == 0 {
return
}
runInJVM(func(env *C.JNIEnv) {
log.Printf("setCharacteristicNotification: %s", c.UUID)
C.setCharacteristicNotification(env, gBLE.handle.BleConnect, p.gatt, c.characteristic)