Example usage for android.bluetooth BluetoothGatt connect

List of usage examples for android.bluetooth BluetoothGatt connect

Introduction

In this page you can find the example usage for android.bluetooth BluetoothGatt connect.

Prototype

public boolean connect() 

Source Link

Document

Connect back to remote device.

Usage

From source file:com.google.android.apps.forscience.ble.MyBleService.java

boolean connect(String address) {
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    if (device == null) {
        return false;
    }/*from   w w  w .j av  a2  s .c  o  m*/
    BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
    int connectionState = bluetoothManager.getConnectionState(device, BluetoothProfile.GATT);
    if (bluetoothGatt != null && connectionState != BluetoothProfile.STATE_CONNECTED) {
        return bluetoothGatt.connect();
    }
    if (bluetoothGatt != null && connectionState == BluetoothProfile.STATE_CONNECTED) {
        sendGattBroadcast(address, BleEvents.GATT_CONNECT, null);
        return true;
    }

    if (bluetoothGatt != null) {
        bluetoothGatt.close();
    }
    bluetoothGatt = device.connectGatt(this, false, // autoConnect = false
            gattCallbacks);
    addressToGattClient.put(address, bluetoothGatt);
    return true;
}

From source file:com.wolkabout.hexiwear.service.BluetoothService.java

private void createGATT(final BluetoothDevice device) {
    bluetoothGatt = device.connectGatt(this, true, new BluetoothGattCallback() {
        @Override/*from w  w  w .j  ava2 s  . c  o  m*/
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            isConnected = BluetoothProfile.STATE_CONNECTED == newState;
            if (isConnected) {
                Log.i(TAG, "GATT connected.");
                startForeground(442, getNotification(device));
                gatt.discoverServices();
            } else {
                Log.i(TAG, "GATT disconnected.");
                NotificationService_.intent(BluetoothService.this).stop();
                notificationManager.notify(442, getNotification(device));
                gatt.connect();
            }

            final Intent connectionStateChanged = new Intent(CONNECTION_STATE_CHANGED);
            connectionStateChanged.putExtra(CONNECTION_STATE, isConnected);
            sendBroadcast(connectionStateChanged);
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            Log.i(TAG, "Services discovered.");
            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            discoverCharacteristics(gatt);
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            Log.i(TAG, "Characteristic written: " + status);

            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            final byte command = characteristic.getValue()[0];
            switch (command) {
            case WRITE_TIME:
                Log.i(TAG, "Time written.");
                final BluetoothGattCharacteristic batteryCharacteristic = readableCharacteristics
                        .get(Characteristic.BATTERY.getUuid());
                gatt.setCharacteristicNotification(batteryCharacteristic, true);
                for (BluetoothGattDescriptor descriptor : batteryCharacteristic.getDescriptors()) {
                    if (descriptor.getUuid().toString().startsWith("00002904")) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
                        gatt.writeDescriptor(descriptor);
                    }
                }
                break;
            case WRITE_NOTIFICATION:
                Log.i(TAG, "Notification sent.");
                if (notificationsQueue.isEmpty()) {
                    Log.i(TAG, "Reading characteristics...");
                    readNextCharacteristics(gatt);
                } else {
                    Log.i(TAG, "writing next notification...");
                    alertIn.setValue(notificationsQueue.poll());
                    gatt.writeCharacteristic(alertIn);
                }
                break;
            default:
                Log.w(TAG, "No such ALERT IN command: " + command);
                break;
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            readCharacteristic(gatt, Characteristic.MANUFACTURER);
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                final BluetoothGattCharacteristic gattCharacteristic, int status) {
            if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
                handleAuthenticationError(gatt);
                return;
            }

            final String characteristicUuid = gattCharacteristic.getUuid().toString();
            final Characteristic characteristic = Characteristic.byUuid(characteristicUuid);
            switch (characteristic) {
            case MANUFACTURER:
                manufacturerInfo.manufacturer = gattCharacteristic.getStringValue(0);
                readCharacteristic(gatt, Characteristic.FW_REVISION);
                break;
            case FW_REVISION:
                manufacturerInfo.firmwareRevision = gattCharacteristic.getStringValue(0);
                readCharacteristic(gatt, Characteristic.MODE);
                break;
            default:
                Log.v(TAG, "Characteristic read: " + characteristic.name());
                if (characteristic == Characteristic.MODE) {
                    final Mode newMode = Mode.bySymbol(gattCharacteristic.getValue()[0]);
                    if (mode != newMode) {
                        onModeChanged(newMode);
                    }
                } else {
                    onBluetoothDataReceived(characteristic, gattCharacteristic.getValue());
                }

                if (notificationsQueue.isEmpty()) {
                    readNextCharacteristics(gatt);
                } else {
                    alertIn.setValue(notificationsQueue.poll());
                    gatt.writeCharacteristic(alertIn);
                }

                break;
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic gattCharacteristic) {
            final String characteristicUuid = gattCharacteristic.getUuid().toString();
            final Characteristic characteristic = Characteristic.byUuid(characteristicUuid);
            Log.d(TAG, "Characteristic changed: " + characteristic);

            if (characteristic == Characteristic.BATTERY) {
                onBluetoothDataReceived(Characteristic.BATTERY, gattCharacteristic.getValue());
            }
        }
    });
}

From source file:com.nbplus.iotapp.bluetooth.BluetoothLeService.java

/**
 * Connects to the GATT server hosted on the Bluetooth LE device.
 *
 * @param address The device address of the destination device.
 *
 * @return Return true if the connection is initiated successfully. The connection result
 *         is reported asynchronously through the
 *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
 *         callback.//from w  w w . j a v a  2 s  .c o m
 */
public boolean connect(final String address) {
    if (mBluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    //        if (mScanedList.get(address) == null) {
    //            Iterator<String> iter = mScanedList.keySet().iterator();
    //            while (iter.hasNext()) {
    //                Log.d(TAG, "scanned address = " + iter.next());
    //            }
    //            Log.w(TAG, "Received address = " + address);
    //            Log.w(TAG, "This device is not activated...... check device status");
    //            return false;
    //        }
    BluetoothGatt bluetoothGatt = mConnectedBluetoothGattMap.get(address);

    // Previously connected device.  Try to reconnect.
    if (bluetoothGatt != null) {
        close(address);
        Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection address = " + address);
        if (bluetoothGatt.connect()) {
            mConnectionState = STATE_CONNECTING;
            return true;
        } else {
            return false;
        }
    }

    final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    if (device == null) {
        Log.w(TAG, "Device not found.  Unable to connect.");
        return false;
    }
    // We want to directly connect to the device, so we are setting the autoConnect
    // parameter to false.
    bluetoothGatt = device.connectGatt(this, false, mGattCallback);
    if (bluetoothGatt == null) {
        Log.w(TAG, "device.connectGatt failed");
        return false;
    }
    mConnectedBluetoothGattMap.put(address, bluetoothGatt);

    Log.d(TAG, "Trying to create a new connection.");
    mConnectionState = STATE_CONNECTING;
    return true;
}

From source file:is.hello.buruberi.bluetooth.stacks.android.NativeGattPeripheral.java

@NonNull
@Override/*w ww  .  j  a  v a  2s  . co  m*/
@RequiresPermission(Manifest.permission.BLUETOOTH)
public Observable<GattPeripheral> connect(@ConnectFlags final int flags,
        @NonNull final OperationTimeout timeout) {
    return createObservable(new Observable.OnSubscribe<GattPeripheral>() {
        @Override
        public void call(final Subscriber<? super GattPeripheral> subscriber) {
            if (getConnectionStatus() == STATUS_CONNECTED) {
                logger.warn(LOG_TAG, "Redundant call to connect(), ignoring.");

                subscriber.onNext(NativeGattPeripheral.this);
                subscriber.onCompleted();
                return;
            } else if (getConnectionStatus() == STATUS_CONNECTING
                    || getConnectionStatus() == STATUS_DISCONNECTING) {
                subscriber.onError(new ConnectionStateException("Peripheral is changing connection status."));
                return;
            }

            final boolean autoConnect = ((flags & CONNECT_FLAG_WAIT_AVAILABLE) == CONNECT_FLAG_WAIT_AVAILABLE);
            final int transport = getTransportFromConnectFlags(flags);

            final GattDispatcher.ConnectionListener listener = new GattDispatcher.ConnectionListener() {
                boolean hasRetried = false;

                @Override
                boolean onConnected(@NonNull final BluetoothGatt gatt, int status) {
                    timeout.unschedule();

                    logger.info(LOG_TAG, "Connected " + NativeGattPeripheral.this.toString());

                    startObservingBluetoothState();

                    disconnectForwarder.setEnabled(true);
                    subscriber.onNext(NativeGattPeripheral.this);
                    subscriber.onCompleted();

                    final Intent connectedIntent = new Intent(ACTION_CONNECTED).putExtra(EXTRA_NAME, getName())
                            .putExtra(EXTRA_ADDRESS, getAddress());
                    LocalBroadcastManager.getInstance(stack.applicationContext).sendBroadcast(connectedIntent);

                    return false;
                }

                @Override
                boolean onError(@NonNull BluetoothGatt gatt, int status, int state) {
                    // The first connection attempt made after a user has power cycled their radio,
                    // or the connection to a device is unexpectedly lost, will seemingly fail 100%
                    // of the time. The error code varies by manufacturer. Retrying silently resolves
                    // the issue.
                    if (GattException.isRecoverableConnectError(status) && !hasRetried) {
                        logger.warn(LOG_TAG, "First connection attempt failed due to stack error, retrying.");

                        this.hasRetried = true;
                        gatt.close();
                        NativeGattPeripheral.this.gatt = BluetoothDeviceCompat.connectGatt(bluetoothDevice,
                                stack.applicationContext, autoConnect, gattDispatcher, transport);
                        if (NativeGattPeripheral.this.gatt != null) {
                            timeout.reschedule();
                        } else {
                            timeout.unschedule();

                            disconnectForwarder.setEnabled(true);
                            subscriber.onError(
                                    new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                        }

                        return true;
                    } else {
                        timeout.unschedule();

                        logger.error(LOG_TAG, "Could not connect. " + GattException.statusToString(status),
                                null);
                        disconnectForwarder.setEnabled(true);
                        subscriber.onError(new GattException(status, Operation.CONNECT));

                        return false;
                    }
                }
            };
            gattDispatcher.addConnectionListener(listener);

            timeout.setTimeoutAction(new Action0() {
                @Override
                public void call() {
                    timeout.unschedule();

                    gattDispatcher.removeConnectionListener(listener);
                    stopObservingBluetoothState();

                    disconnectForwarder.setEnabled(true);
                    subscriber.onError(new OperationTimeoutException(Operation.CONNECT));
                }
            }, stack.getScheduler());

            logger.info(LOG_TAG, "Connecting " + NativeGattPeripheral.this.toString());

            if (gatt != null) {
                if (gatt.connect()) {
                    disconnectForwarder.setEnabled(false);
                    timeout.schedule();
                } else {
                    gattDispatcher.removeConnectionListener(listener);

                    subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                }
            } else {
                NativeGattPeripheral.this.gatt = BluetoothDeviceCompat.connectGatt(bluetoothDevice,
                        stack.applicationContext, autoConnect, gattDispatcher, transport);
                if (gatt != null) {
                    disconnectForwarder.setEnabled(false);
                    timeout.schedule();
                } else {
                    gattDispatcher.removeConnectionListener(listener);

                    subscriber.onError(new GattException(GattException.GATT_INTERNAL_ERROR, Operation.CONNECT));
                }
            }
        }
    });
}