Java Code Examples for android.bluetooth.BluetoothGattDescriptor#setValue()

The following examples show how to use android.bluetooth.BluetoothGattDescriptor#setValue() . 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: GattClient.java    From blefun-androidthings with Apache License 2.0 8 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        boolean connected = false;

        BluetoothGattService service = gatt.getService(SERVICE_UUID);
        if (service != null) {
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(CHARACTERISTIC_COUNTER_UUID);
            if (characteristic != null) {
                gatt.setCharacteristicNotification(characteristic, true);

                BluetoothGattDescriptor descriptor = characteristic.getDescriptor(DESCRIPTOR_CONFIG);
                if (descriptor != null) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    connected = gatt.writeDescriptor(descriptor);
                }
            }
        }
        mListener.onConnected(connected);
    } else {
        Log.w(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example 2
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
private boolean internalEnableIndications(final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null)
		return false;

	// Check characteristic property
	final int properties = characteristic.getProperties();
	if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE) == 0)
		return false;

	gatt.setCharacteristicNotification(characteristic, true);
	final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
Example 3
Source File: BaseMyo.java    From myolib with Apache License 2.0 7 votes vote down vote up
private void internalSend(MyoMsg msg) {
    BluetoothGattService gattService = mBluetoothGatt.getService(msg.getServiceUUID());
    if (gattService == null) {
        Logy.w(TAG, "BluetoothGattService unavailable!: " + msg.toString());
        return;
    }
    BluetoothGattCharacteristic gattChar = gattService.getCharacteristic(msg.getCharacteristicUUID());
    if (gattChar == null) {
        Logy.w(TAG, "BluetoothGattCharacteristic unavailable!: " + msg.toString());
        return;
    }

    mDispatchTime = System.currentTimeMillis();
    if (msg.getDescriptorUUID() != null) {
        BluetoothGattDescriptor gattDesc = gattChar.getDescriptor(msg.getDescriptorUUID());
        if (gattDesc == null) {
            Logy.w(TAG, "BluetoothGattDescriptor unavailable!: " + msg.toString());
            return;
        }
        mMsgCallbackMap.put(msg.getIdentifier(), msg);
        if (msg instanceof WriteMsg) {
            gattDesc.setValue(((WriteMsg) msg).getData());
            mBluetoothGatt.writeDescriptor(gattDesc);
        } else {
            mBluetoothGatt.readDescriptor(gattDesc);
        }
    } else {
        mMsgCallbackMap.put(msg.getIdentifier(), msg);
        if (msg instanceof WriteMsg) {
            gattChar.setValue(((WriteMsg) msg).getData());
            mBluetoothGatt.writeCharacteristic(gattChar);
        } else {
            mBluetoothGatt.readCharacteristic(gattChar);
        }
    }
    Logy.v(TAG, "Processed: " + msg.getIdentifier());
}
 
Example 4
Source File: MultipleBleService.java    From BleLib with Apache License 2.0 6 votes vote down vote up
/**
 * Enables or disables notification on a give characteristic.
 *
 * @param address            The address to read from.
 * @param serviceUUID        remote device service uuid
 * @param characteristicUUID remote device characteristic uuid
 * @param enabled            if notify is true
 */
public void setCharacteristicNotification(String address, String serviceUUID,
                                          String characteristicUUID, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGattMap.get(address) == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    BluetoothGattService service =
            mBluetoothGattMap.get(address).getService(UUID.fromString(serviceUUID));
    BluetoothGattCharacteristic characteristic =
            service.getCharacteristic(UUID.fromString(characteristicUUID));

    mBluetoothGattMap.get(address).setCharacteristicNotification(characteristic, enabled);

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
            UUID.fromString(GattAttributes.DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION));
    descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
            BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    mBluetoothGattMap.get(address).writeDescriptor(descriptor);

}
 
Example 5
Source File: HRDemoActivity.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void enableNotificationForHr() {
	log("Enabling notification for Heart Rate");
       boolean success = mBTGatt.setCharacteristicNotification(mBTValueCharacteristic, true);
       if(!success) {
       	log("Enabling notification failed!");
       	return;
       }

       BluetoothGattDescriptor descriptor = mBTValueCharacteristic.getDescriptor(BleDefinedUUIDs.Descriptor.CHAR_CLIENT_CONFIG);
       if(descriptor != null) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBTGatt.writeDescriptor(descriptor);
        log("Notification enabled");
       }		
       else {
       	log("Could not get descriptor for characteristic! Notification are not enabled.");
       }
}
 
Example 6
Source File: BluetoothLeService.java    From IoT-Firstep with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Enables or disables notification on a give characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    // 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);
    }
}
 
Example 7
Source File: BluetoothLeService.java    From IoT-Firstep with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Enables or disables notification on a give characteristic.
 *
 * @param characteristic Characteristic to act on.
 * @param enabled If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

    // 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);
    }
}
 
Example 8
Source File: AbstractHOGPServer.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
@Override
public void onDescriptorWriteRequest(final BluetoothDevice device, final int requestId,
                                     final BluetoothGattDescriptor descriptor, final boolean preparedWrite,
                                     final boolean responseNeeded, final int offset, final byte[] value) {
    if (DEBUG) {
        Log.d(TAG, "onDescriptorWriteRequest descriptor: " + descriptor.getUuid() + ", value: " + Arrays.toString(value) + ", responseNeeded: " + responseNeeded + ", preparedWrite: " + preparedWrite);
    }

    if (mGattServer == null) {
        return;
    }

    descriptor.setValue(value);

    if (responseNeeded) {
        if (BleUuidUtils.matches(DESCRIPTOR_CLIENT_CHARACTERISTIC_CONFIGURATION, descriptor.getUuid())) {
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, EMPTY_BYTES);
        } else {
            mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_FAILURE, 0, EMPTY_BYTES);
        }
    }
}
 
Example 9
Source File: AmazonFreeRTOSDevice.java    From amazon-freertos-ble-android-sdk with Apache License 2.0 6 votes vote down vote up
private boolean writeDescriptor(final String serviceUuid, final String characteristicUuid) {
    BluetoothGattCharacteristic characteristic = getCharacteristic(serviceUuid, characteristicUuid);
    if (characteristic != null) {
        mBluetoothGatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                convertFromInteger(0x2902));
        if (descriptor != null) {
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            mBluetoothGatt.writeDescriptor(descriptor);
            return true;
        } else {
            Log.w(TAG, "There's no such descriptor on characteristic: " + characteristicUuid);
        }
    }
    return false;
}
 
Example 10
Source File: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
public void setCharacteristicIndication(BluetoothGattCharacteristic characteristic, boolean enabled) {
    Log.i(TAG, "Characteristic setting indication");
    if (mBluetoothGatt != null) {
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(HM10Attributes.CLIENT_CHARACTERISTIC_CONFIG));
        Log.i(TAG, "Descriptor found: " + descriptor.getUuid());
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}
 
Example 11
Source File: BleGattExecutor.java    From Bluefruit_LE_Connect_Android with MIT License 5 votes vote down vote up
private BleGattExecutor.ServiceAction serviceNotifyAction(final BluetoothGattService gattService, final String characteristicUuidString, final boolean enable) {
    return new BleGattExecutor.ServiceAction() {
        @Override
        public boolean execute(BluetoothGatt bluetoothGatt) {
            if (characteristicUuidString != null) {
                final UUID characteristicUuid = UUID.fromString(characteristicUuidString);
                final BluetoothGattCharacteristic dataCharacteristic = gattService.getCharacteristic(characteristicUuid);

                if (dataCharacteristic == null) {
                    Log.w(TAG, "Characteristic with UUID " + characteristicUuidString + " not found");
                    return true;
                }

                final UUID clientCharacteristicConfiguration = UUID.fromString(CHARACTERISTIC_CONFIG);
                final BluetoothGattDescriptor config = dataCharacteristic.getDescriptor(clientCharacteristicConfiguration);
                if (config == null)
                    return true;

                // enableNotification/disable locally
                bluetoothGatt.setCharacteristicNotification(dataCharacteristic, enable);
                // enableNotification/disable remotely
                config.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                bluetoothGatt.writeDescriptor(config);

                return false;
            } else {
                Log.w(TAG, "Characteristic UUID is null");
                return true;
            }
        }
    };
}
 
Example 12
Source File: BLEService.java    From android_wear_for_ios with MIT License 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    Log.d(TAG_LOG, "onServicesDiscovered received: " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(UUID.fromString(service_ancs));
        if (service == null) {
            Log.d(TAG_LOG, "cant find service");
        } else {
            Log.d(TAG_LOG, "find service");
            Log.d(TAG_LOG, String.valueOf(bluetooth_gatt.getServices()));

            // subscribe data source characteristic
            BluetoothGattCharacteristic data_characteristic = service.getCharacteristic(UUID.fromString(characteristics_data_source));

            if (data_characteristic == null) {
                Log.d(TAG_LOG, "cant find data source chara");
            } else {
                Log.d(TAG_LOG, "find data source chara :: " + data_characteristic.getUuid());
                Log.d(TAG_LOG, "set notify:: " + data_characteristic.getUuid());
                bluetooth_gatt.setCharacteristicNotification(data_characteristic, true);
                BluetoothGattDescriptor descriptor = data_characteristic.getDescriptor(
                        UUID.fromString(descriptor_config));
                if(descriptor == null){
                    Log.d(TAG_LOG, " ** cant find desc :: " + descriptor.getUuid());
                }else{
                    Log.d(TAG_LOG, " ** find desc :: " + descriptor.getUuid());
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    bluetooth_gatt.writeDescriptor(descriptor);
                    if(api_level >= 21) {
                        stop_le_scanner();
                    }else {
                        bluetooth_adapter.stopLeScan(le_scan_callback);
                    }
                }
            }
        }
    }
}
 
Example 13
Source File: MyBleService.java    From science-journal with Apache License 2.0 5 votes vote down vote up
public void writeValue(String address, BluetoothGattDescriptor descriptor, byte[] value) {
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  if (bluetoothGatt == null) {
    Log.w(TAG, "No connection found for: " + address);
    sendGattBroadcast(address, BleEvents.WRITE_DESC_FAIL, null);
    return;
  }

  if (!descriptor.setValue(value) || !bluetoothGatt.writeDescriptor(descriptor)) {
    sendGattBroadcast(address, BleEvents.WRITE_DESC_FAIL, descriptor.getCharacteristic());
  }
}
 
Example 14
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 5 votes vote down vote up
public boolean writeDescriptor(String address, byte[] data, UUID serviceUUID, UUID characteristicUUID, UUID descriptorUUID){
    if (verifyParams(address)) return false;
    BluetoothGatt bluetoothGatt = gattHashMap.get(address);
    BluetoothGattCharacteristic gattCharacteristic = gattCharacteristic(bluetoothGatt, serviceUUID, characteristicUUID);
    BluetoothGattDescriptor descriptor = gattCharacteristic.getDescriptor(descriptorUUID);
    if (descriptor != null){
        descriptor.setValue(data);
        return bluetoothGatt.writeDescriptor(descriptor);
    }
    return false;
}
 
Example 15
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
    Log.i(TAG, "Characteristic setting notification");
    if (mBluetoothGatt != null) {
        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(HM10Attributes.CLIENT_CHARACTERISTIC_CONFIG));
        Log.i(TAG, "Descriptor found: " + descriptor.getUuid());
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}
 
Example 16
Source File: P_AndroidGatt.java    From SweetBlue with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final boolean setDescValue(BluetoothGattDescriptor descriptor, byte[] data)
{
    if (descriptor != null)
    {
        return descriptor.setValue(data);
    }
    return false;
}
 
Example 17
Source File: UartService.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Disable Notification on TX characteristic
 *
 * @return
 */
public void disableTXNotification()
{

    if (mBluetoothGatt == null) {
        showMessage("mBluetoothGatt null: " + mBluetoothGatt);
        broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
        return;
    }
    BluetoothGattService RxService = mBluetoothGatt.getService(RX_SERVICE_UUID);
    if (RxService == null) {
        showMessage("Rx service not found!");
        broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
        return;
    }
    BluetoothGattCharacteristic TxChar = RxService.getCharacteristic(TX_CHAR_UUID);
    if (TxChar == null) {
        showMessage("Tx charateristic not found!");
        broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
        return;
    }
    mBluetoothGatt.setCharacteristicNotification(TxChar,false);

    BluetoothGattDescriptor descriptor = TxChar.getDescriptor(CCCD);
    descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    mBluetoothGatt.writeDescriptor(descriptor);

}
 
Example 18
Source File: MainActivity.java    From mi-band-2 with MIT License 5 votes vote down vote up
void listenHeartRate() {
    BluetoothGattCharacteristic bchar = bluetoothGatt.getService(CustomBluetoothProfile.HeartRate.service)
            .getCharacteristic(CustomBluetoothProfile.HeartRate.measurementCharacteristic);
    bluetoothGatt.setCharacteristicNotification(bchar, true);
    BluetoothGattDescriptor descriptor = bchar.getDescriptor(CustomBluetoothProfile.HeartRate.descriptor);
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    bluetoothGatt.writeDescriptor(descriptor);
    isListeningHeartRate = true;
}
 
Example 19
Source File: BleConnectWorker.java    From Android-BluetoothKit with Apache License 2.0 4 votes vote down vote up
@Override
    public boolean setCharacteristicNotification(UUID service, UUID character, boolean enable) {
        checkRuntime();

        BluetoothLog.v(String.format("setCharacteristicNotification for %s, service = %s, character = %s, enable = %b",
                getAddress(), service, character, enable));

        BluetoothGattCharacteristic characteristic = getCharacter(service, character);

        if (characteristic == null) {
            BluetoothLog.e(String.format("characteristic not exist!"));
            return false;
        }

//        if (!isCharacteristicNotifyable(characteristic)) {
//            BluetoothLog.e(String.format("characteristic not notifyable!"));
//            return false;
//        }

        if (mBluetoothGatt == null) {
            BluetoothLog.e(String.format("ble gatt null"));
            return false;
        }

        if (!mBluetoothGatt.setCharacteristicNotification(characteristic, enable)) {
            BluetoothLog.e(String.format("setCharacteristicNotification failed"));
            return false;
        }

        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(Constants.CLIENT_CHARACTERISTIC_CONFIG);

        if (descriptor == null) {
            BluetoothLog.e(String.format("getDescriptor for notify null!"));
            return false;
        }

        byte[] value = (enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);

        if (!descriptor.setValue(value)) {
            BluetoothLog.e(String.format("setValue for notify descriptor failed!"));
            return false;
        }

        if (!mBluetoothGatt.writeDescriptor(descriptor)) {
            BluetoothLog.e(String.format("writeDescriptor for notify failed"));
            return false;
        }

        return true;
    }
 
Example 20
Source File: DfuBaseService.java    From microbit with Apache License 2.0 4 votes vote down vote up
/**
 * Enables or disables the notifications for given characteristic. This method is SYNCHRONOUS and wait until the
 * {@link android.bluetooth.BluetoothGattCallback#onDescriptorWrite(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattDescriptor, int)} will be called or the connection state will change from {@link #STATE_CONNECTED_AND_READY}. If
 * connection state will change, or an error will occur, an exception will be thrown.
 *
 * @param gatt           the GATT device
 * @param characteristic the characteristic to enable or disable notifications for
 * @param type           {@link #NOTIFICATIONS} or {@link #INDICATIONS}
 * @throws DfuException
 * @throws UploadAbortedException
 */
private void enableCCCD(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int type) throws DeviceDisconnectedException, DfuException, UploadAbortedException {
    final String debugString = type == NOTIFICATIONS ? "notifications" : "indications";
    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState);

    mReceivedData = null;
    mError = 0;
    if ((type == NOTIFICATIONS && mNotificationsEnabled) || (type == INDICATIONS && mServiceChangedIndicationsEnabled))
        return;

    logi("Enabling " + debugString + "...");
    sendLogBroadcast(LOG_LEVEL_VERBOSE, "Enabling " + debugString + " for " + characteristic.getUuid());

    // enable notifications locally
    gatt.setCharacteristicNotification(characteristic, true);

    // enable notifications on the device
    final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG);
    descriptor.setValue(type == NOTIFICATIONS ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    sendLogBroadcast(LOG_LEVEL_DEBUG, "gatt.writeDescriptor(" + descriptor.getUuid() + (type == NOTIFICATIONS ? ", value=0x01-00)" : ", value=0x02-00)"));
    gatt.writeDescriptor(descriptor);

    // We have to wait until device receives a response or an error occur
    try {
        synchronized (mLock) {
            while ((((type == NOTIFICATIONS && !mNotificationsEnabled) || (type == INDICATIONS && !mServiceChangedIndicationsEnabled))
                    && mConnectionState == STATE_CONNECTED_AND_READY && mError == 0 && !mAborted) || mPaused)
                mLock.wait();
        }
    } catch (final InterruptedException e) {
        loge("Sleeping interrupted", e);
    }

    if (mAborted)
        throw new UploadAbortedException();

    if (mError != 0)
        throw new DfuException("Unable to set " + debugString + " state", mError);

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState);
}