android.bluetooth.BluetoothGattCallback Java Examples

The following examples show how to use android.bluetooth.BluetoothGattCallback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java    From easyble-x with Apache License 2.0 6 votes vote down vote up
@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        device = getIntent().getParcelableExtra("device");
        setContentView(R.layout.activity_main);
        assignViews();
        initViews();
        //连接配置,举个例随意配置两项
        ConnectionConfiguration config = new ConnectionConfiguration();
        config.setConnectTimeoutMillis(10000);
        config.setRequestTimeoutMillis(1000);
        config.setAutoReconnect(false);
//        connection = EasyBLE.getInstance().connect(device, config, observer);//回调监听连接状态,设置此回调不影响观察者接收连接状态消息
        connection = EasyBLE.getInstance().connect(device, config);//观察者监听连接状态  
        connection.setBluetoothGattCallback(new BluetoothGattCallback() {
            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                Log.d("EasyBLE", "原始写入数据:" + StringUtils.toHex(characteristic.getValue()));
            }
        });
    }
 
Example #2
Source File: Device.java    From neatle with MIT License 6 votes vote down vote up
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void execute(BluetoothGattCallback callback) {
    NeatleLogger.d("Execute " + callback);
    boolean wasIdle;
    synchronized (lock) {
        wasIdle = currentCallback == DO_NOTHING_CALLBACK;
        if (currentCallback == callback || queue.contains(callback)) {
            NeatleLogger.d("Restarting " + callback);
        } else {
            NeatleLogger.d("Queueing up " + callback);
            queue.add(callback);
        }
    }
    if (wasIdle && areServicesDiscovered()) {
        resume();
    } else {
        connect();
    }
}
 
Example #3
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
    public void onServicesDiscoveredCharacteristicIndicateTest() throws Exception {
        BluetoothGattCallback callback = connectAndGetCallback();

        BluetoothGattService service = mock(BluetoothGattService.class);
        when(service.getUuid()).thenReturn(SERVICE_UUID);
        when(gatt.getServices()).thenReturn(Arrays.asList(service));

        BluetoothGattCharacteristic characteristic = mock(BluetoothGattCharacteristic.class);
        when(characteristic.getProperties()).thenReturn(PROPERTY_INDICATE);
        when(service.getCharacteristics()).thenReturn(Arrays.asList(characteristic));

        callback.onServicesDiscovered(gatt, 0);

        List<UUID> expected = Arrays.asList(SERVICE_UUID);

//        assertThat(peripheral.getServices(), is(expected));
    }
 
Example #4
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
   public void onServicesDiscoveredCharacteristicNotifyTest() throws Exception {
       BluetoothGattCallback callback = connectAndGetCallback();

       BluetoothGattService service = mock(BluetoothGattService.class);
       when(service.getUuid()).thenReturn(SERVICE_UUID);
       when(gatt.getServices()).thenReturn(Arrays.asList(service));

       BluetoothGattCharacteristic characteristic = mock(BluetoothGattCharacteristic.class);
       when(characteristic.getProperties()).thenReturn(PROPERTY_NOTIFY);
       when(service.getCharacteristics()).thenReturn(Arrays.asList(characteristic));

       callback.onServicesDiscovered(gatt, 0);

       List<UUID> expected = Arrays.asList(SERVICE_UUID);

//       assertThat(peripheral.getServices(), is(expected));
   }
 
Example #5
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setNotifyIndicationTest() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_INDICATE,0);
    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"),0);
    service.addCharacteristic(characteristic);
    characteristic.addDescriptor(descriptor);

    when(gatt.getServices()).thenReturn(Arrays.asList(service));
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    peripheral.setNotify(characteristic, true);
    verify(gatt).setCharacteristicNotification(characteristic, true);
    assertEquals(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE[0], descriptor.getValue()[0]);
    assertEquals(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE[1], descriptor.getValue()[1]);
    verify(gatt).writeDescriptor(descriptor);

    callback.onDescriptorWrite(gatt, descriptor, 0);
    verify(peripheralCallback).onNotificationStateUpdate(peripheral, characteristic, 0);
}
 
Example #6
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setNotifyNotificationTest() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_NOTIFY,0);
    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"),0);
    service.addCharacteristic(characteristic);
    characteristic.addDescriptor(descriptor);

    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.setNotify(characteristic, true);
    verify(gatt).setCharacteristicNotification(characteristic, true);
    assertEquals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE[0], descriptor.getValue()[0]);
    assertEquals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE[1], descriptor.getValue()[1]);
    verify(gatt).writeDescriptor(descriptor);

    callback.onDescriptorWrite(gatt, descriptor, 0);
    verify(peripheralCallback).onNotificationStateUpdate(peripheral, characteristic, 0);
}
 
Example #7
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setNotifyDisableTest() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_NOTIFY,0);
    BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"),0);
    service.addCharacteristic(characteristic);
    characteristic.addDescriptor(descriptor);

    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.setNotify(characteristic, false);
    verify(gatt).setCharacteristicNotification(characteristic, false);
    assertEquals(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE[0], descriptor.getValue()[0]);
    assertEquals(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE[1], descriptor.getValue()[1]);
    verify(gatt).writeDescriptor(descriptor);

    callback.onDescriptorWrite(gatt, descriptor, 0);

    verify(peripheralCallback).onNotificationStateUpdate(peripheral, characteristic, 0);
}
 
Example #8
Source File: Device.java    From neatle with MIT License 6 votes vote down vote up
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public void executeFinished(BluetoothGattCallback callback) {
    synchronized (lock) {
        if (callback == currentCallback) {
            this.currentCallback = DO_NOTHING_CALLBACK;
            NeatleLogger.d("Finished " + callback);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    resume();
                }
            });
        } else {
            this.queue.remove(callback);
            NeatleLogger.d("Removed from queue " + callback);
        }
    }
}
 
Example #9
Source File: UnitTestGatt.java    From SweetBlue with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BluetoothGatt connect(P_NativeDeviceLayer device, Context context, boolean useAutoConnect, BluetoothGattCallback callback) {
    m_gattIsNull = false;
    m_explicitDisconnect = false;
    m_device.getManager().getPostManager().postToUpdateThreadDelayed(new Runnable()
    {
        @Override public void run()
        {
            if (!m_explicitDisconnect)
            {
                setToConnecting();
            }
        }
    }, 100);
    m_device.getManager().getPostManager().postToUpdateThreadDelayed(new Runnable()
    {
        @Override public void run()
        {
            if (!m_explicitDisconnect)
            {
                setToConnected();
            }
        }
    }, 250);
    return device.connect(context, useAutoConnect, callback);
}
 
Example #10
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void queueTestRetryCommand() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    BluetoothGattCharacteristic characteristic2 = new BluetoothGattCharacteristic(UUID.fromString("00002A1E-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    service.addCharacteristic(characteristic);
    service.addCharacteristic(characteristic2);
    when(gatt.readCharacteristic(characteristic)).thenReturn(true);
    when(gatt.getServices()).thenReturn(Arrays.asList(service));

    peripheral.readCharacteristic(characteristic);

    verify(gatt).readCharacteristic(characteristic);

    // Trigger bonding to start
    callback.onCharacteristicRead(gatt, characteristic, 5);

    Field field = BluetoothPeripheral.class.getDeclaredField("bondStateReceiver");
    field.setAccessible(true);
    BroadcastReceiver broadcastReceiver = (BroadcastReceiver) field.get(peripheral);

    Intent intent = mock(Intent.class);
    when(intent.getAction()).thenReturn(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    when(intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)).thenReturn(BOND_BONDED);
    when(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)).thenReturn(device);

    broadcastReceiver.onReceive(context, intent);

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    verify(gatt, times(2)).readCharacteristic(characteristic);
}
 
Example #11
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void queueTestConsecutiveReadsNoResponse() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();
    callback.onConnectionStateChange(gatt, GATT_SUCCESS, STATE_CONNECTED);

    BluetoothGattService service = new BluetoothGattService(SERVICE_UUID, 0);
    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    BluetoothGattCharacteristic characteristic2 = new BluetoothGattCharacteristic(UUID.fromString("00002A1E-0000-1000-8000-00805f9b34fb"),PROPERTY_READ,0);
    service.addCharacteristic(characteristic);
    service.addCharacteristic(characteristic2);
    byte[] byteArray = new byte[] {0x01, 0x02, 0x03};
    characteristic.setValue(byteArray);
    characteristic2.setValue(byteArray);

    when(gatt.readCharacteristic(characteristic)).thenReturn(true);

    peripheral.readCharacteristic(characteristic);
    peripheral.readCharacteristic(characteristic2);

    verify(gatt).readCharacteristic(characteristic);
    verify(peripheralCallback, never()).onCharacteristicUpdate(peripheral, byteArray, characteristic, 0);
    verify(gatt, never()).readCharacteristic(characteristic2);
}
 
Example #12
Source File: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void notifyTest() {
    BluetoothGattCallback callback = connectAndGetCallback();

    BluetoothGattCharacteristic characteristic = new BluetoothGattCharacteristic(UUID.fromString("00002A1C-0000-1000-8000-00805f9b34fb"), PROPERTY_INDICATE,0);
    peripheral.setNotify(characteristic, true);

    byte[] originalByteArray = new byte[]{0x01};
    characteristic.setValue(originalByteArray);
    callback.onCharacteristicChanged(gatt, characteristic);

    ArgumentCaptor<BluetoothPeripheral> captorPeripheral = ArgumentCaptor.forClass(BluetoothPeripheral.class);
    ArgumentCaptor<byte[]> captorValue = ArgumentCaptor.forClass(byte[].class);
    ArgumentCaptor<BluetoothGattCharacteristic> captorCharacteristic = ArgumentCaptor.forClass(BluetoothGattCharacteristic.class);
    ArgumentCaptor<Integer> captorStatus = ArgumentCaptor.forClass(Integer.class);
    verify(peripheralCallback).onCharacteristicUpdate(captorPeripheral.capture(), captorValue.capture(), captorCharacteristic.capture(), captorStatus.capture());

    byte[] value = captorValue.getValue();
    assertEquals(0x01, value[0]);  // Check if original value is returned and not the one in the characteristic
    assertNotEquals(value, originalByteArray);   // Check if the byte array has been copied
    assertEquals(peripheral, captorPeripheral.getValue());
    assertEquals(characteristic, captorCharacteristic.getValue());
    assertEquals(GATT_SUCCESS, (int) captorStatus.getValue() );
}
 
Example #13
Source File: CharacteristicSubscriptionTest.java    From neatle with MIT License 6 votes vote down vote up
@Test
public void testStopWhileStillStarting() {
    final BluetoothGatt bluetoothGatt = Mockito.mock(BluetoothGatt.class, Answers.RETURNS_DEEP_STUBS);

    when(device.isConnected()).thenReturn(true);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            BluetoothGattCallback callback = invocationOnMock.getArgument(0);
            callback.onServicesDiscovered(bluetoothGatt, BluetoothGatt.GATT_SUCCESS);

            return null;
        }
    }).when(device).execute(Mockito.<BluetoothGattCallback>any());

    subscription.start();

    Robolectric.getForegroundThreadScheduler().pause();

    subscription.stop();
    subscription.start();

    Robolectric.getForegroundThreadScheduler().unPause();

    assertTrue(subscription.isStarted());
}
 
Example #14
Source File: NodeTest.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void connectEmptyNode(){

    BluetoothDevice device = spy(Shadow.newInstanceOf(BluetoothDevice.class));
    Node node = createNode(device);

    Assert.assertEquals(Node.State.Idle, node.getState());
    node.connect(RuntimeEnvironment.application);

    TestUtil.execAllAsyncTask();

    verify(device).connectGatt(eq(RuntimeEnvironment.application), eq(false),
            any(BluetoothGattCallback.class));
    Assert.assertEquals(Node.State.Dead, node.getState());
}
 
Example #15
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    NeatleLogger.d("createCharacteristicRead");
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onCharacteristicRead(gatt, characteristic, status);
}
 
Example #16
Source File: BluetoothDeviceShadow.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * open a connection with the device the returning connection is a shadow object that can be
 * queue with the mockito framework
 * @param c
 * @param b
 * @param callback
 * @return
 */
@Implementation
public BluetoothGatt connectGatt(Context c,boolean b,BluetoothGattCallback callback){
    mGattConnection = spy(Shadow.newInstanceOf(BluetoothGatt.class));
    BluetoothGattShadow shadowGatt = Shadow.extract(mGattConnection);
    shadowGatt.setGattCallBack(callback);
    shadowGatt.setServices(mServices);
    mGattConnection.connect();
    return mGattConnection;
}
 
Example #17
Source File: BleConnectWorker.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
@Override
public boolean openGatt() {
    checkRuntime();

    BluetoothLog.v(String.format("openGatt for %s", getAddress()));

    if (mBluetoothGatt != null) {
        BluetoothLog.e(String.format("Previous gatt not closed"));
        return true;
    }

    Context context = BluetoothUtils.getContext();
    BluetoothGattCallback callback = new BluetoothGattResponse(mBluetoothGattResponse);

    if (Version.isMarshmallow()) {
        mBluetoothGatt = mBluetoothDevice.connectGatt(context, false, callback, BluetoothDevice.TRANSPORT_LE);
    } else {
        mBluetoothGatt = mBluetoothDevice.connectGatt(context, false, callback);
    }

    if (mBluetoothGatt == null) {
        BluetoothLog.e(String.format("openGatt failed: connectGatt return null!"));
        return false;
    }

    return true;
}
 
Example #18
Source File: BtReconnect.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private static BluetoothGatt connectGattApi21(final BluetoothDevice bluetoothDevice) {
    try {
        final Method method = bluetoothDevice.getClass().getMethod("connectGatt", Context.class, Boolean.TYPE, BluetoothGattCallback.class, Integer.TYPE);
        UserError.Log.d(TAG, "Trying connect with api21");
        return (BluetoothGatt) method.invoke(bluetoothDevice, null, mAutoConnect, getInstance(), TRANSPORT_LE);
    } catch (Exception e) {
        UserError.Log.d(TAG, "Connection failed: " + e);
        return bluetoothDevice.connectGatt(xdrip.getAppContext(), mAutoConnect, getInstance());
    }
}
 
Example #19
Source File: BtReconnect.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.O)
private static BluetoothGatt connectGattApi26(final BluetoothDevice bluetoothDevice, final int type) {
    try {
        final Method method = bluetoothDevice.getClass().getMethod("connectGatt", Context.class, Boolean.TYPE, BluetoothGattCallback.class, Integer.TYPE, Boolean.TYPE, Integer.TYPE, Handler.class);
        UserError.Log.d(TAG, "Trying reconnect");
        return (BluetoothGatt) method.invoke(bluetoothDevice, null, mAutoConnect, getInstance(), TRANSPORT_LE, Boolean.TRUE, type, null);
    } catch (Exception e) {
        UserError.Log.d(TAG, "Received exception: " + e + " falling back");
        return bluetoothDevice.connectGatt(xdrip.getAppContext(), mAutoConnect, getInstance(), TRANSPORT_LE, type);
    }
}
 
Example #20
Source File: BleConnectionCompat.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
private static boolean connectUsingReflection(BluetoothGatt bluetoothGatt, BluetoothGattCallback bluetoothGattCallback,
                                              boolean autoConnect)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
    RxBleLog.v("Connecting using reflection");
    setAutoConnectValue(bluetoothGatt, autoConnect);
    Method connectMethod = bluetoothGatt.getClass().getDeclaredMethod("connect", Boolean.class, BluetoothGattCallback.class);
    connectMethod.setAccessible(true);
    return (Boolean) (connectMethod.invoke(bluetoothGatt, true, bluetoothGattCallback));
}
 
Example #21
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onReadRemoteRssi(gatt, rssi, status);
}
 
Example #22
Source File: BleConnectionCompat.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
private BluetoothGatt connectGattCompat(BluetoothGattCallback bluetoothGattCallback, BluetoothDevice device, boolean autoConnect) {
    RxBleLog.v("Connecting without reflection");

    if (Build.VERSION.SDK_INT >= 23 /* Build.VERSION_CODES.M */) {
        return device.connectGatt(context, autoConnect, bluetoothGattCallback, TRANSPORT_LE);
    } else {
        return device.connectGatt(context, autoConnect, bluetoothGattCallback);
    }
}
 
Example #23
Source File: NodeTest.java    From BlueSTSDK_Android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void connectNodeWithDebug(){

    BluetoothDevice device = spy(Shadow.newInstanceOf(BluetoothDevice.class));
    BluetoothDeviceShadow shadowDevice = Shadow.extract(device);

    BluetoothGattService debugService = new BluetoothGattService(BLENodeDefines.Services
            .Debug.DEBUG_SERVICE_UUID,BluetoothGattService.SERVICE_TYPE_PRIMARY);
    debugService.addCharacteristic(
            new BluetoothGattCharacteristic(BLENodeDefines.Services.Debug.DEBUG_STDERR_UUID,
                    BluetoothGattCharacteristic.PERMISSION_READ |
                            BluetoothGattCharacteristic.PERMISSION_WRITE,
                    BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic
                            .PROPERTY_NOTIFY));
    debugService.addCharacteristic(
            new BluetoothGattCharacteristic(BLENodeDefines.Services.Debug.DEBUG_TERM_UUID,
                    BluetoothGattCharacteristic.PERMISSION_READ |
                            BluetoothGattCharacteristic.PERMISSION_WRITE,
                    BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic
                            .PROPERTY_NOTIFY)
    );

    shadowDevice.addService(debugService);

    Node node = createNode(device);
    Assert.assertEquals(Node.State.Idle, node.getState());
    node.connect(RuntimeEnvironment.application);

    TestUtil.execAllAsyncTask();

    verify(device).connectGatt(eq(RuntimeEnvironment.application), eq(false),
            any(BluetoothGattCallback.class));
    Assert.assertEquals(Node.State.Connected, node.getState());
    Assert.assertTrue(node.getDebug()!=null);
}
 
Example #24
Source File: BtReconnect.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private static BluetoothGatt connectGattApi21(final BluetoothDevice bluetoothDevice) {
    try {
        final Method method = bluetoothDevice.getClass().getMethod("connectGatt", Context.class, Boolean.TYPE, BluetoothGattCallback.class, Integer.TYPE);
        UserError.Log.d(TAG, "Trying connect with api21");
        return (BluetoothGatt) method.invoke(bluetoothDevice, null, mAutoConnect, getInstance(), TRANSPORT_LE);
    } catch (Exception e) {
        UserError.Log.d(TAG, "Connection failed: " + e);
        return bluetoothDevice.connectGatt(xdrip.getAppContext(), mAutoConnect, getInstance());
    }
}
 
Example #25
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onDescriptorRead(gatt, descriptor, status);
}
 
Example #26
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onCharacteristicChanged(gatt, characteristic);

    notifyCharacteristicChange(CommandResult.createCharacteristicChanged(characteristic));
}
 
Example #27
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
    NeatleLogger.d("onReliableWriteCompleted");
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onReliableWriteCompleted(gatt, status);
}
 
Example #28
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    NeatleLogger.d("onCharacteristicWrite " + status);
    BluetoothGattCallback target;
    synchronized (lock) {
        target = currentCallback;
    }
    target.onCharacteristicWrite(gatt, characteristic, status);
}
 
Example #29
Source File: Device.java    From neatle with MIT License 5 votes vote down vote up
private void resume() {
    BluetoothGattCallback target;
    BluetoothGatt targetGatt;
    boolean doResume;

    synchronized (lock) {
        if (currentCallback == DO_NOTHING_CALLBACK) {
            BluetoothGattCallback newCallback = queue.poll();
            if (newCallback == null) {
                if (changeListeners.isEmpty()) {
                    disconnectOnIdle();
                }
                return;
            }
            currentCallback = newCallback;
        }
        target = currentCallback;
        doResume = areServicesDiscovered();
        targetGatt = this.gatt;
    }

    if (doResume) {
        NeatleLogger.i("Resuming with " + target);
        currentCallback.onServicesDiscovered(targetGatt, BluetoothGatt.GATT_SUCCESS);
    } else {
        NeatleLogger.i("Will resume after services are discovered with " + target);
        connect();
    }
}
 
Example #30
Source File: CorePeripheralTest.java    From RxCentralBle with Apache License 2.0 5 votes vote down vote up
private void prepareConnect(boolean discoverServiceSuccess) {
  when(bluetoothDevice.connectGatt(any(), anyBoolean(), any())).thenReturn(bluetoothGatt);
  when(bluetoothGatt.discoverServices()).thenReturn(discoverServiceSuccess);

  connectTestObserver = corePeripheral.connect().test();

  ArgumentCaptor<BluetoothGattCallback> gattCaptor =
      ArgumentCaptor.forClass(BluetoothGattCallback.class);
  verify(bluetoothDevice).connectGatt(any(), anyBoolean(), gattCaptor.capture());

  bluetoothGattCallback = gattCaptor.getValue();
}