diff --git a/Ble.jar b/Ble.jar index f52d79b..fb85bb4 100644 Binary files a/Ble.jar and b/Ble.jar differ diff --git a/BleConnect.java b/BleConnect.java index 604c404..b4e4d69 100644 --- a/BleConnect.java +++ b/BleConnect.java @@ -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(); + } } }); } diff --git a/ble_android.go b/ble_android.go index 8baf4c0..c1d4074 100644 --- a/ble_android.go +++ b/ble_android.go @@ -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)