Example usage for android.bluetooth BluetoothGattCallback BluetoothGattCallback

List of usage examples for android.bluetooth BluetoothGattCallback BluetoothGattCallback

Introduction

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

Prototype

BluetoothGattCallback

Source Link

Usage

From source file:fr.bmartel.android.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection//from  w  w  w.ja  va 2  s . co  m
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            String intentAction;

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                intentAction = ActionFilterGatt.ACTION_GATT_CONNECTED;
                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                intentAction = ActionFilterGatt.ACTION_GATT_DISCONNECTED;
                Log.i(TAG, "Disconnected from GATT server.");
                manager.broadcastUpdate(ActionFilterGatt.ACTION_GATT_DISCONNECTED);

                if (BluetoothDeviceConn.this.gatt != null) {
                    BluetoothDeviceConn.this.gatt.close();
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new DottiDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {

                                    String name = "";

                                    JSONObject object = new JSONObject();
                                    object.put("address", getAddress());
                                    object.put("deviceName", getDeviceName());

                                    ArrayList<String> values = new ArrayList<String>();
                                    values.add(object.toString());

                                    connected = true;

                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(
                                            ActionFilterGatt.ACTION_GATT_SERVICES_DISCOVERED, values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            System.out.println("characteristic write received ");
            manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            System.out.println("descriptor write received ");
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            System.out.println("descriptor change received ");

            if (device != null) {
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

From source file:fr.bmartel.android.notti.service.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection//from w w  w.ja  va  2  s  .  co m
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                Log.i(TAG, "Disconnected from GATT server.");

                try {
                    JSONObject object = new JSONObject();
                    object.put(BluetoothConst.DEVICE_ADDRESS, getAddress());
                    object.put(BluetoothConst.DEVICE_NAME, getDeviceName());

                    ArrayList<String> values = new ArrayList<String>();
                    values.add(object.toString());

                    //when device is fully intitialized broadcast service discovery
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED, values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (BluetoothDeviceConn.this.gatt != null) {
                    BluetoothDeviceConn.this.gatt.close();
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new NottiDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {
                                    JSONObject object = new JSONObject();
                                    object.put(BluetoothConst.DEVICE_ADDRESS, getAddress());
                                    object.put(BluetoothConst.DEVICE_NAME, getDeviceName());

                                    ArrayList<String> values = new ArrayList<String>();
                                    values.add(object.toString());

                                    connected = true;
                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_CONNECTED,
                                            values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            if (device != null) {
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

From source file:com.github.akinaru.bleanalyzer.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection/*w w  w  .j ava2  s.  co m*/
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Log.i(TAG, "Connected to GATT server.");
                Log.i(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                Log.i(TAG, "Disconnected from GATT server.");

                try {
                    JSONObject object = new JSONObject();
                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

                    ArrayList<String> values = new ArrayList<String>();
                    values.add(object.toString());

                    //when device is fully intitialized broadcast service discovery
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED, values);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (manager.getWaitingMap().containsKey(deviceAddr)) {
                    manager.getWaitingMap().get(deviceAddr).cancel(true);
                    manager.getWaitingMap().remove(deviceAddr);
                }

                if (BluetoothDeviceConn.this.gatt != null) {
                    Log.i(TAG, "connection close clean");
                    BluetoothDeviceConn.this.gatt.close();
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new RfduinoDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {
                                    JSONObject object = new JSONObject();
                                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

                                    ArrayList<String> values = new ArrayList<String>();
                                    values.add(object.toString());

                                    connected = true;
                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_CONNECTED,
                                            values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            //manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicRead");
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            manager.getEventManager().set();
            if (device != null) {
                Log.i(TAG, "onCharacteristicChanged");
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

From source file:com.github.akinaru.roboticbuttonpusher.bluetooth.connection.BluetoothDeviceConn.java

/**
 * Build Bluetooth device connection//from w w w  . j a  va  2 s. c  o  m
 *
 * @param address
 */
@SuppressLint("NewApi")
public BluetoothDeviceConn(String address, String deviceName, final IBluetoothCustomManager manager) {
    this.deviceAddr = address;
    this.deviceName = deviceName;
    this.manager = manager;

    gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {

            if (newState == BluetoothProfile.STATE_CONNECTED) {

                Log.v(TAG, "Connected to GATT server.");
                Log.v(TAG, "Attempting to start service discovery:" + gatt.discoverServices());

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {

                connected = false;
                Log.v(TAG, "Disconnected from GATT server.");

                if (status != 133) {
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_DISCONNECTED,
                            new ArrayList<String>());
                } else {
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_RETRY,
                            new ArrayList<String>());
                }

                if (manager.getWaitingMap().containsKey(deviceAddr)) {
                    manager.getWaitingMap().get(deviceAddr).cancel(true);
                    manager.getWaitingMap().remove(deviceAddr);
                }

                if (BluetoothDeviceConn.this.gatt != null) {
                    Log.v(TAG, "connection close clean");
                    BluetoothDeviceConn.this.gatt.close();
                }
                if (remove) {
                    manager.getConnectionList().remove(deviceAddr);
                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_REMOVED,
                            new ArrayList<String>());
                }
            }
        }

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

            if (status == BluetoothGatt.GATT_SUCCESS) {

                Runnable test = new Runnable() {
                    @Override
                    public void run() {

                        //you can improve this by using reflection
                        device = new RfduinoDevice(BluetoothDeviceConn.this);

                        device.addInitListener(new IDeviceInitListener() {
                            @Override
                            public void onInit() {
                                try {
                                    JSONObject object = new JSONObject();
                                    object.put(JsonConstants.BT_ADDRESS, getAddress());
                                    object.put(JsonConstants.BT_DEVICE_NAME, getDeviceName());

                                    ArrayList<String> values = new ArrayList<String>();
                                    values.add(object.toString());

                                    connected = true;
                                    //when device is fully intitialized broadcast service discovery
                                    manager.broadcastUpdateStringList(BluetoothEvents.BT_EVENT_DEVICE_CONNECTED,
                                            values);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        device.init();
                    }
                };
                Thread testThread = new Thread(test);
                testThread.start();

            } else {
                Log.w(TAG, "onServicesDiscovered received: " + status);
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                device.notifyCharacteristicWriteReceived(characteristic);
            }
        }

        @Override
        // Result of a characteristic read operation
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                int status) {
            manager.getEventManager().set();
            if (device != null) {
                Log.v(TAG, "onCharacteristicRead");
                device.notifyCharacteristicReadReceived(characteristic);
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            manager.getEventManager().set();
        }

        @Override
        // Characteristic notification
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            manager.getEventManager().set();
            if (device != null) {
                Log.v(TAG, "onCharacteristicChanged");
                device.notifyCharacteristicChangeReceived(characteristic);
            }
        }
    };
}

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

private void createGATT(final BluetoothDevice device) {
    bluetoothGatt = device.connectGatt(this, true, new BluetoothGattCallback() {
        @Override/*  w  w  w .  ja  v a2  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:net.emilymaier.movebot.HeartFragment.java

@Override
@SuppressWarnings("deprecation")
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
    Log.d("HeartFragment", "Bluetooth LE device found");
    BluetoothGatt bluetoothGatt = device.connectGatt(act, false, new BluetoothGattCallback() {
        @Override/*from   w w  w.j  a  va2 s.  co m*/
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.d("HeartFragment", "Connected to LE device");
                gatt.discoverServices();
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                BluetoothGattCharacteristic characteristic = null;
                for (BluetoothGattService service : gatt.getServices()) {
                    characteristic = service
                            .getCharacteristic(UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"));
                    if (characteristic != null) {
                        break;
                    }
                }
                if (characteristic != null) {
                    Log.d("HeartFragment", "Found device with HRM characteristic");
                    HeartDevice device = new HeartDevice();
                    device.bluetoothGatt = gatt;
                    device.characteristic = characteristic;
                    for (HeartDevice testDevice : heartDevices) {
                        if (testDevice.bluetoothGatt.getDevice().getAddress()
                                .equals(device.bluetoothGatt.getDevice().getAddress())) {
                            heartDevices.remove(testDevice);
                        }
                    }
                    heartDevices.add(device);
                } else {
                    Log.d("HeartFragment", "Device does not have HRM characteristic");
                    gatt.disconnect();
                    gatt.close();
                }
            } else {
                Log.w("HeartFragment", "Failed to discover device services");
                gatt.disconnect();
                gatt.close();
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            int flag = characteristic.getProperties();
            int format = -1;
            if ((flag & 0x01) != 0) {
                format = BluetoothGattCharacteristic.FORMAT_UINT16;
            } else {
                format = BluetoothGattCharacteristic.FORMAT_UINT8;
            }
            final int heartRate = characteristic.getIntValue(format, 1);
            act.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    act.updateHeart(heartRate);
                }
            });
        }
    });
}