Example usage for android.bluetooth BluetoothGattCharacteristic getUuid

List of usage examples for android.bluetooth BluetoothGattCharacteristic getUuid

Introduction

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

Prototype

public UUID getUuid() 

Source Link

Document

Returns the UUID of this characteristic

Usage

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  av a 2 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.example.ecgfile.DeviceControlActivity.java

@SuppressLint("SimpleDateFormat")
private void getGattServices(List<BluetoothGattService> gattServices) {
    System.out.println("getGattServices");
    if (gattServices == null) {
        System.out.println("getGattServices null ");
        return;// w  ww.j  av  a2s. c o  m
    }
    String uuid = null;

    // Loops through available GATT Services.
    for (BluetoothGattService gattService : gattServices) {
        uuid = gattService.getUuid().toString();
        if (uuid.equals("0000ffe0-0000-1000-8000-00805f9b34fb")
                || uuid.equals("0000ffe5-0000-1000-8000-00805f9b34fb")) { // 2uuid service

            List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
            ArrayList<BluetoothGattCharacteristic> charas = new ArrayList<BluetoothGattCharacteristic>();

            // Loops through available Characteristics.
            for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                charas.add(gattCharacteristic);
                uuid = gattCharacteristic.getUuid().toString();
                if (uuid.equals("0000ffe4-0000-1000-8000-00805f9b34fb")) {
                    mNotifyCharacteristic = gattCharacteristic;
                    Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
                }
                if (uuid.equals("0000ffe9-0000-1000-8000-00805f9b34fb")) {
                    mNCharW = gattCharacteristic;
                }
            }
        }
    }
}

From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.hplus.HPlusSupport.java

@Override
public boolean onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    if (super.onCharacteristicChanged(gatt, characteristic)) {
        return true;
    }//w w w  . j av  a2  s.c  o m

    UUID characteristicUUID = characteristic.getUuid();
    byte[] data = characteristic.getValue();
    if (data.length == 0)
        return true;

    switch (data[0]) {
    case HPlusConstants.DATA_VERSION:
        return syncHelper.processVersion(data);

    case HPlusConstants.DATA_STATS:
        return syncHelper.processRealtimeStats(data);

    case HPlusConstants.DATA_SLEEP:
        return syncHelper.processIncomingSleepData(data);

    case HPlusConstants.DATA_STEPS:
        return syncHelper.processDaySummary(data);

    case HPlusConstants.DATA_DAY_SUMMARY:
    case HPlusConstants.DATA_DAY_SUMMARY_ALT:
        return syncHelper.processIncomingDaySlotData(data);

    default:
        LOG.debug("Unhandled characteristic changed: " + characteristicUUID);
        return true;
    }
}

From source file:com.example.android.bluetoothlegatt.BluetoothLeService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {/*www.  ja  v a  2 s .  c o m*/
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            //// print data received.
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            //Log.i(TAG, "windsome1:"+ stringBuilder.toString());
            //Log.i(TAG, "windsome2:"+ new String(data));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());

            //// write to file.
            long currTime = System.currentTimeMillis();
            /*if ((currTime - cacheTime) > 500) {
            Log.i(TAG, "write cache to file! currTime="+currTime+", cacheTime="+cacheTime+", interval="+(currTime - cacheTime));
            boolean isSame = writeCacheToFile2 ();
            cacheData2.clear();
            intent.putExtra(EXTRA_DATA_SAME, isSame);
            }*/
            cacheData2.add(data);
            cacheTime = currTime;
            mToastHandler.removeCallbacks(mRunnable);
            mToastHandler.postDelayed(mRunnable, 300);

        }
    }
    sendBroadcast(intent);
}

From source file:com.example.android.bluetoothlegatt.BluetoothLeService.java

/**
 * Enables or disables notification on a give characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled If true, enable notification.  False otherwise.
 *///from w w  w  .jav  a 2s  .  c o  m
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }

    if (!mBluetoothGatt.setCharacteristicNotification(characteristic, enabled)) {
        Log.e(TAG, "setCharacteristicNotification fail! enabled=" + enabled);
    }

    if ((UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb")).equals(characteristic.getUuid())) {
        //mBluetoothGatt.writeCharacteristic(characteristic);
        List<BluetoothGattDescriptor> descs = characteristic.getDescriptors();
        for (int i = 0; i < descs.size(); i++) {
            BluetoothGattDescriptor desc = descs.get(i);
            desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            Log.d(TAG, "writeDescriptor notify, uuid=" + desc.getUuid().toString());
            mBluetoothGatt.writeDescriptor(desc);
        }
        //BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
        //descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        //mBluetoothGatt.writeDescriptor(descriptor);
    }

    // This is specific to Heart Rate Measurement.
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        BluetoothGattDescriptor descriptor = characteristic
                .getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}

From source file:net.kenevans.android.blecardiacmonitor.BCMBleService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    Date now = new Date();
    long date = now.getTime();
    // // DEBUG//  ww w .  j a  v  a2s.c  om
    // Set this to "" to not get the date in the return value
    // String dateStr = " @ " + millisecTimeFormater.format(now);
    String dateStr = "";
    final Intent intent = new Intent(action);
    intent.putExtra(EXTRA_UUID, characteristic.getUuid().toString());
    intent.putExtra(EXTRA_DATE, date);

    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        HeartRateValues values = new HeartRateValues(characteristic, date);
        mLastHr = values.getHr();
        mLastRr = values.getRr();
        mLastHrDate = date;
        // // DEBUG
        // Log.d(TAG, String.format("Received heart rate measurement: %d",
        // mLastHr));
        if (mDbAdapter != null) {
            mDbAdapter.createData(mLastHrDate, mSessionStartTime, mLastHr, mLastRr);
        }
        intent.putExtra(EXTRA_HR, String.valueOf(values.getHr() + dateStr));
        intent.putExtra(EXTRA_RR, values.getRr() + dateStr);
        intent.putExtra(EXTRA_DATA, values.getInfo());
    } else if (UUID_BATTERY_LEVEL.equals(characteristic.getUuid())) {
        mLastBat = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        Log.d(TAG, String.format("Received battery level: %d", mLastBat));
        intent.putExtra(EXTRA_BAT, String.valueOf(mLastBat) + dateStr);
        intent.putExtra(EXTRA_DATA, String.valueOf("Battery Level: " + mLastBat));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data) {
                stringBuilder.append(String.format("%02X ", byteChar));
            }
            intent.putExtra(EXTRA_DATA,
                    BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) + "\n"
                            + new String(data) + "\n" + stringBuilder.toString());
        } else {
            intent.putExtra(EXTRA_DATA,
                    BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) + "\n"
                            + ((data == null) ? "null" : "No data"));
        }
    }
    sendBroadcast(intent);
}

From source file:com.megster.cordova.ble.central.Peripheral.java

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    super.onCharacteristicRead(gatt, characteristic, status);
    LOG.d(TAG, "onCharacteristicRead " + characteristic);

    if (readCallback != null) {

        if (status == BluetoothGatt.GATT_SUCCESS) {
            readCallback.success(characteristic.getValue());
        } else {//from  ww  w  .  j  av  a2  s . co  m
            readCallback.error("Error reading " + characteristic.getUuid() + " status=" + status);
        }

        readCallback = null;

    }

    commandCompleted();
}

From source file:com.qi.airstat.BluetoothLeService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    final Intent intent = new Intent(action);

    int signal = 0;

    // This is special handling for the Heart Rate Measurement profile.  Data parsing is
    // carried out as per profile specifications:
    // http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        int flag = characteristic.getProperties();
        int format = -1;
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {//from   w ww .j a v a 2 s.  c o m
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }

        final int heartRate = characteristic.getIntValue(format, 1);
        signal = heartRate;
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data)
                stringBuilder.append(String.format("%02X ", byteChar));
            intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());

            signal = Integer.parseInt(new String(data));
        }
    }

    DatabaseManager databaseManager = new DatabaseManager(BluetoothLeService.this);
    SQLiteDatabase database = databaseManager.getWritableDatabase();

    ContentValues values = new ContentValues();
    String date = new SimpleDateFormat("yyMMddHHmmss").format(new java.util.Date());

    values.put(Constants.DATABASE_COMMON_COLUMN_TIME_STAMP, date);
    values.put(Constants.DATABASE_HEART_RATE_COLUMN_HEART_RATE, signal);
    database.insert(Constants.DATABASE_HEART_RATE_TABLE, null, values);

    database.close();

    try {
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    } catch (SecurityException exception) {
        exception.printStackTrace();
    }

    JSONObject reformedObject = new JSONObject();
    JSONArray reformedArray = new JSONArray();

    try {
        JSONObject item = new JSONObject();
        item.put("timeStamp", date);
        item.put("connectionID", Constants.CID_BLE);
        item.put("heartrate", signal);
        item.put("latitude", latitude);
        item.put("longitude", longitude);

        reformedArray.put(item);
        reformedObject.put("HR", reformedArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    HttpService httpService = new HttpService();
    String responseCode = httpService.executeConn(null, "POST",
            "http://teamc-iot.calit2.net/IOT/public/rcv_json_data", reformedObject);

    sendBroadcast(intent);
}

From source file:net.kenevans.android.blecardiacmonitor.BCMBleService.java

/**
 * Enables or disables notification on a given characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled        If true, enable notification. False otherwise.
 *///from w  w w  .  j av a  2 s.co  m
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    boolean res = mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
    if (!res) {
        Log.d(TAG, "setCharacteristicNotification failed for "
                + BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()));
    }
}

From source file:net.kenevans.android.hxmmonitor.HxMBleService.java

private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
    Date now = new Date();
    long date = now.getTime();
    // // DEBUG//from w ww . jav  a 2s .com
    // Set this to "" to not get the date in the return value
    // String dateStr = " @ " + millisecTimeFormater.format(now);
    String dateStr = "";
    final Intent intent = new Intent(action);
    intent.putExtra(EXTRA_UUID, characteristic.getUuid().toString());
    intent.putExtra(EXTRA_DATE, date);

    if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
        HeartRateValues values = new HeartRateValues(characteristic, date);
        mLastHr = values.getHr();
        mLastRr = values.getRr();
        mLastHrDate = date;
        // // DEBUG
        // Log.d(TAG, String.format("Received heart rate measurement: %d",
        // mLastHr));
        if (mDbAdapter != null && (mCharCustom == null || !mDoCustom)) {
            mDbAdapter.createData(mLastHrDate, mSessionStartTime, mLastHr, mLastRr, INVALID_INT, INVALID_INT);
        }
        intent.putExtra(EXTRA_HR, String.valueOf(values.getHr() + dateStr));
        intent.putExtra(EXTRA_RR, values.getRr() + dateStr);
        intent.putExtra(EXTRA_DATA, values.getInfo());
    } else if (UUID_CUSTOM_MEASUREMENT.equals(characteristic.getUuid())) {
        HxMCustomValues values = new HxMCustomValues(characteristic, date);
        mLastAct = values.getActivity();
        mLastPa = values.getPa();
        // // DEBUG
        // Log.d(TAG, String.format("Received custom measurement: %d %d",
        // mLastAct, mLastPa));
        if (mDbAdapter != null) {
            if (mCharHr == null || !mDoHr) {
                mDbAdapter.createData(date, mSessionStartTime, INVALID_INT, INVALID_STRING, mLastAct, mLastPa);
            } else {
                mDbAdapter.createData(mLastHrDate, mSessionStartTime, mLastHr, mLastRr, mLastAct, mLastPa);
            }
        }
        intent.putExtra(EXTRA_ACT, String.valueOf(values.getActivity() + dateStr));
        intent.putExtra(EXTRA_PA, String.valueOf(values.getPa() + dateStr));
        intent.putExtra(EXTRA_DATA, dateStr + values.getInfo());
    } else if (UUID_BATTERY_LEVEL.equals(characteristic.getUuid())) {
        mLastBat = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        Log.d(TAG, String.format("Received battery level: %d", mLastBat));
        intent.putExtra(EXTRA_BAT, String.valueOf(mLastBat) + dateStr);
        intent.putExtra(EXTRA_DATA, String.valueOf("Battery Level: " + mLastBat));
    } else {
        // For all other profiles, writes the data formatted in HEX.
        final byte[] data = characteristic.getValue();
        if (data != null && data.length > 0) {
            final StringBuilder stringBuilder = new StringBuilder(data.length);
            for (byte byteChar : data) {
                stringBuilder.append(String.format("%02X ", byteChar));
            }
            intent.putExtra(EXTRA_DATA,
                    BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) + "\n"
                            + new String(data) + "\n" + stringBuilder.toString());
        } else {
            intent.putExtra(EXTRA_DATA,
                    BleNamesResolver.resolveCharacteristicName(characteristic.getUuid().toString()) + "\n"
                            + ((data == null) ? "null" : "No data"));
        }
    }
    sendBroadcast(intent);
}