android.bluetooth.BluetoothGattDescriptor Java Examples

The following examples show how to use android.bluetooth.BluetoothGattDescriptor. 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: BluetoothPeripheralTest.java    From blessed-android with MIT License 6 votes vote down vote up
@Test
public void setNotifyIndicationTest() throws Exception {
    BluetoothGattCallback callback = connectAndGetCallback();

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

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

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

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

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

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

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

    callback.onDescriptorWrite(gatt, descriptor, 0);

    verify(peripheralCallback).onNotificationStateUpdate(peripheral, characteristic, 0);
}
 
Example #3
Source File: BleService.java    From bleTester with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
private void getChartacteristicValue(
		BluetoothGattCharacteristic characteristic) {
	// TODO Auto-generated method stub
	List<BluetoothGattDescriptor> des = characteristic.getDescriptors();
	Intent mIntent = new Intent(ACTION_CHAR_READED);
	if (des.size() != 0) {
		mIntent.putExtra("desriptor1", des.get(0).getUuid().toString());
		mIntent.putExtra("desriptor2", des.get(1).getUuid().toString());
	}
	mIntent.putExtra("StringValue", characteristic.getStringValue(0));
	String hexValue = Utils.bytesToHex(characteristic.getValue());
	mIntent.putExtra("HexValue", hexValue.toString());
	mIntent.putExtra("time", DateUtil.getCurrentDatatime());
	sendBroadcast(mIntent);
}
 
Example #4
Source File: RxBleConnectionMock.java    From RxAndroidBle with Apache License 2.0 6 votes vote down vote up
@NonNull
private Completable setupCharacteristicNotification(
        final UUID bluetoothGattCharacteristicUUID,
        final NotificationSetupMode setupMode,
        final boolean enabled,
        final boolean isIndication
) {
    if (setupMode == NotificationSetupMode.DEFAULT) {
        final byte[] enableValue = isIndication ? ENABLE_INDICATION_VALUE : ENABLE_NOTIFICATION_VALUE;
        return getClientConfigurationDescriptor(bluetoothGattCharacteristicUUID)
                .flatMapCompletable(new Function<BluetoothGattDescriptor, Completable>() {
                    @Override
                    public Completable apply(BluetoothGattDescriptor bluetoothGattDescriptor) {
                        return writeDescriptor(bluetoothGattDescriptor, enabled ? enableValue : DISABLE_NOTIFICATION_VALUE);
                    }
                });
    } else {
        return Completable.complete();
    }

}
 
Example #5
Source File: BleWrapper.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void setNotificationForCharacteristic(BluetoothGattCharacteristic ch, boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) return;
    
    boolean success = mBluetoothGatt.setCharacteristicNotification(ch, enabled);
    if(!success) {
    	Log.e("------", "Seting proper notification status for characteristic failed!");
    }
    
    // This is also sometimes required (e.g. for heart rate monitors) to enable notifications/indications
    // see: https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml
    BluetoothGattDescriptor descriptor = ch.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
    if(descriptor != null) {
    	byte[] val = enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
     descriptor.setValue(val);
     mBluetoothGatt.writeDescriptor(descriptor);
    }
}
 
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: BTLEDeviceManager.java    From BLEService with BSD 3-Clause "New" or "Revised" License 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.
   * @param immediate setNotification immediately, don't enqueue
   */
  public void setCharacteristicNotification(BTDeviceInfo 					deviceInfo, 
  										  BluetoothGattCharacteristic 	characteristic,
                                            boolean 						enabled) throws DeviceManagerException {
  	Log.d(TAG, "setCharacteristicNotification " + deviceInfo.getDeviceAddress() + " name = " + deviceInfo.getDevice().getName());
      if (mBluetoothAdapter == null) { 
         	throw new DeviceManagerException(mContext.getString(R.string.adapter_uninitialized));
      }
      if (deviceInfo.getGatt() == null) {
          throw new DeviceManagerException(String.format("%s %s", mContext.getString(R.string.no_gatt_info), deviceInfo.getDeviceAddress()));
      }
      
      // if there are no notification requests outstanding, we can issue one right away.
      deviceInfo.enqueueCommand(new BTLECommandSetCharacteristicNotification(deviceInfo, characteristic, true));
      // this is some serious "guess the magic word".  You have to write this characteristic to receive notififcations.
      // setCharacteristicNotification() isn't enough.
      // from http://stackoverflow.com/questions/17910322/android-ble-api-gatt-notification-not-received
      BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BTUUID.CHARACTERISTIC_UPDATE_NOTIFICATION_DESCRIPTOR_UUID));
      descriptor.setValue(enabled ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[] { 0x00, 0x00 });
deviceInfo.enqueueCommand(new BTLECommandWriteDescriptor(deviceInfo, descriptor));
  }
 
Example #8
Source File: GattUtilsTest.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testCopyDescriptor(){
    byte[] data = new byte[]{0x01, 0x02, 0x03};
    BluetoothGattDescriptor descriptor = mock(BluetoothGattDescriptor.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(descriptor.getValue()).thenReturn(data);
    when(descriptor.getUuid()).thenReturn(UUID.fromString("E69169D1-11A7-4545-B7FC-02A3ADFC3EAC"));
    when(descriptor.getPermissions()).thenReturn(BluetoothGattDescriptor.PERMISSION_READ);
    BluetoothGattDescriptorCopy result = new GattUtils().copyDescriptor(descriptor);
    if(result == null) {
        fail(String.format(Locale.ENGLISH, "The result was null for descriptor: %s, with data: %s", descriptor.getUuid(), Arrays.toString(descriptor.getValue())));
        return;
    }
    data[2] = 0x04;
    Assert.assertNotEquals(Arrays.hashCode(data), Arrays.hashCode(result.getValue()));
}
 
Example #9
Source File: GattUtilsTest.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testCopyDescriptorWithNullValue(){
    byte[] data = null;
    BluetoothGattDescriptor descriptor = mock(BluetoothGattDescriptor.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(descriptor.getValue()).thenReturn(data);
    when(descriptor.getUuid()).thenReturn(UUID.fromString("E69169D1-11A7-4545-B7FC-02A3ADFC3EAC"));
    when(descriptor.getPermissions()).thenReturn(BluetoothGattDescriptor.PERMISSION_READ);
    BluetoothGattDescriptorCopy result = new GattUtils().copyDescriptor(descriptor);
    if(result == null) {
        fail(String.format(Locale.ENGLISH, "The result was null for descriptor: %s, with data: %s", descriptor.getUuid(), Arrays.toString(descriptor.getValue())));
        return;
    }
    Assert.assertNull(result.getValue());
}
 
Example #10
Source File: GattUtilsTest.java    From bitgatt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testCopyCharacteristicWithDescriptorChild(){
    byte[] data = null;
    BluetoothGattCharacteristic characteristic = mock(BluetoothGattCharacteristic.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(characteristic.getValue()).thenReturn(data);
    when(characteristic.getUuid()).thenReturn(UUID.fromString("E69169D1-11A7-4545-B7FC-02A3ADFC3EAC"));
    when(characteristic.getPermissions()).thenReturn(BluetoothGattCharacteristic.PERMISSION_READ);
    when(characteristic.getProperties()).thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY);
    BluetoothGattDescriptor descriptor = mock(BluetoothGattDescriptor.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(descriptor.getValue()).thenReturn(data);
    when(descriptor.getUuid()).thenReturn(UUID.fromString("E69169D1-11A7-4545-B7FC-02A3ADFC3EAC"));
    when(descriptor.getPermissions()).thenReturn(BluetoothGattDescriptor.PERMISSION_READ);
    characteristic.addDescriptor(descriptor);
    BluetoothGattCharacteristicCopy result = new GattUtils().copyCharacteristic(characteristic);
    if(result == null) {
        fail(String.format(Locale.ENGLISH, "The result was null for characteristic: %s, with data: %s", characteristic.getUuid(), Arrays.toString(characteristic.getValue())));
        return;
    }
    Assert.assertNotEquals(descriptor, characteristic.getDescriptor(descriptor.getUuid()));
}
 
Example #11
Source File: MusicControlActivity.java    From android_wear_for_ios with MIT License 6 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    Log.d(TAG_LOG, " onDescriptorWrite:: " + status);
    // Notification source
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG_LOG, "status: write success ");
        //find music controll service
        Log.d(TAG_LOG, "*+*+*+*+*+*+*+*+*+*+ find music control");
        BluetoothGattService service = bluetooth_gatt.getService(UUID.fromString(service_ams));
        if(service != null) {
            BluetoothGattCharacteristic chara = service.getCharacteristic(UUID.fromString(characteristics_entity_update));
            if(chara != null) {
                chara.setValue(new byte[]{(byte) 0x02, (byte) 0x00, (byte) 0x02});
                bluetooth_gatt.writeCharacteristic(chara);
            }
        }
    }
}
 
Example #12
Source File: DescriptorWriteOperation.java    From tap-android-sdk with Apache License 2.0 6 votes vote down vote up
@Override
public void onExecute(@NonNull BluetoothGatt gatt) {
    BluetoothGattDescriptor d = extractDescriptor(gatt);
    if (d == null) {
        postOnError(ErrorStrings.NO_DESCRIPTOR);
        return;
    }

    if (!d.setValue(data)) {
        postOnError(ErrorStrings.VALUE_STORE_FAIL);
        return;
    }

    if (!gatt.writeDescriptor(d)) {
        postOnError(ErrorStrings.WRITE_OP_INIT_FAIL);
    }
}
 
Example #13
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.
 * @param characteristic Characteristic to act on.
 * @param enabled        If true, enable notification.  False otherwise.
 */
public void setCharacteristicNotification(String address,
                                          BluetoothGattCharacteristic characteristic,
                                          boolean enabled) {
    if (mBluetoothAdapter == null || mBluetoothGattMap.get(address) == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    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 #14
Source File: BlePeripheral.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
public void characteristicDisableNotify(@NonNull final BluetoothGattCharacteristic characteristic, CompletionHandler completionHandler) {
    final String identifier = getCharacteristicIdentifier(characteristic);
    BleCommand command = new BleCommand(BleCommand.BLECOMMANDTYPE_SETNOTIFY, kDebugCommands ? identifier : null, completionHandler) {

        @Override
        public void execute() {

            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(kClientCharacteristicConfigUUID);
            if (mBluetoothGatt != null && descriptor != null && (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                mNotifyHandlers.remove(identifier);
                descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                mBluetoothGatt.writeDescriptor(descriptor);
            } else {
                Log.w(TAG, "disable notify: client config descriptor not found for characteristic: " + characteristic.getUuid().toString());
                finishExecutingCommand(BluetoothGatt.GATT_FAILURE);
            }
        }
    };
    mCommmandQueue.add(command);
}
 
Example #15
Source File: BleManager.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean internalEnableNotifications(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_NOTIFY) == 0)
		return false;

	gatt.setCharacteristicNotification(characteristic, true);
	final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
	if (descriptor != null) {
		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
Example #16
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean internalEnableNotifications(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

	final BluetoothGattDescriptor descriptor = getCccd(characteristic, BluetoothGattCharacteristic.PROPERTY_NOTIFY);
	if (descriptor != null) {
		log(Log.DEBUG, "gatt.setCharacteristicNotification(" + characteristic.getUuid() + ", true)");
		gatt.setCharacteristicNotification(characteristic, true);

		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		log(Log.VERBOSE, "Enabling notifications for " + characteristic.getUuid());
		log(Log.DEBUG, "gatt.writeDescriptor(" +
				BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
Example #17
Source File: BleGattExecutor.java    From Bluefruit_LE_Connect_Android with MIT License 5 votes vote down vote up
private BleGattExecutor.ServiceAction serviceIndicateAction(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 remotely
                config.setValue(enable ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE : BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                bluetoothGatt.writeDescriptor(config);

                return false;
            } else {
                Log.w(TAG, "Characteristic UUID is null");
                return true;
            }
        }
    };
}
 
Example #18
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the Client Characteristic Config Descriptor if the characteristic has the
 * required property. It may return null if the CCCD is not there.
 *
 * @param characteristic   the characteristic to look the CCCD in.
 * @param requiredProperty the required property: {@link BluetoothGattCharacteristic#PROPERTY_NOTIFY}
 *                         or {@link BluetoothGattCharacteristic#PROPERTY_INDICATE}.
 * @return The CCC descriptor or null if characteristic is null, if it doesn't have the
 * required property, or if the CCCD is missing.
 */
private static BluetoothGattDescriptor getCccd(@Nullable final BluetoothGattCharacteristic characteristic,
											   final int requiredProperty) {
	if (characteristic == null)
		return null;

	// Check characteristic property
	final int properties = characteristic.getProperties();
	if ((properties & requiredProperty) == 0)
		return null;

	return characteristic.getDescriptor(BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
}
 
Example #19
Source File: P_BleServer_Listeners.java    From AsteroidOSSync with GNU General Public License v3.0 5 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)
{
	m_server.getManager().getPostManager().runOrPostToUpdateThread(new Runnable()
	{
		@Override public void run()
		{
			onWriteRequest_updateThread(device, value, requestId, offset, preparedWrite, responseNeeded, descriptor.getCharacteristic().getService().getUuid(), descriptor.getCharacteristic().getUuid(), descriptor.getUuid());
		}
	});
   }
 
Example #20
Source File: DexShareCollectionService.java    From xDrip 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 #21
Source File: P_BleServer_Listeners.java    From SweetBlue with GNU General Public License v3.0 5 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)
{
	m_server.getManager().getPostManager().runOrPostToUpdateThread(new Runnable()
	{
		@Override public void run()
		{
			onWriteRequest_updateThread(device, value, requestId, offset, preparedWrite, responseNeeded, descriptor.getCharacteristic().getService().getUuid(), descriptor.getCharacteristic().getUuid(), descriptor.getUuid());
		}
	});
   }
 
Example #22
Source File: ShareTest.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    Log.i(TAG, "Wrote a discriptor, status: " + status);
    if(step == 2 && currentGattTask == GATT_SETUP) {
        setListeners(2);
    } else if(step == 3) {
        setListeners(3);
    } else if(step == 4) {
        setListeners(4);
    } else if(step == 5) {
        Log.i(TAG, "Done setting Listeners");
    }
}
 
Example #23
Source File: BLETransport.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {

    Log.d(TAG, "DescriptorRead, : Status " + status + " Data : " + new String(descriptor.getValue(), StandardCharsets.UTF_8));

    if (status != BluetoothGatt.GATT_SUCCESS) {
        Log.e(TAG, "Failed to read descriptor");
        EventBus.getDefault().post(new DeviceConnectionEvent(ESPConstants.EVENT_DEVICE_CONNECTION_FAILED));
        return;
    }

    byte[] data = descriptor.getValue();

    String value = new String(data, StandardCharsets.UTF_8);
    uuidMap.put(value, descriptor.getCharacteristic().getUuid().toString());
    Log.d(TAG, "Value : " + value + " for UUID : " + descriptor.getCharacteristic().getUuid().toString());

    if (isReadingDescriptors) {

        readNextDescriptor();

    } else {

        BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(uuidMap.get(ESPConstants.HANDLER_PROTO_VER)));

        if (characteristic != null) {
            // Write anything. It doesn't matter. We need to read characteristic and for that we need to write something.
            characteristic.setValue("ESP");
            bluetoothGatt.writeCharacteristic(characteristic);
        }
    }
}
 
Example #24
Source File: MainActivity.java    From BTLETest with MIT License 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        writeLine("Service discovery completed!");
    }
    else {
        writeLine("Service discovery failed with status: " + status);
    }
    // Save reference to each characteristic.
    tx = gatt.getService(UART_UUID).getCharacteristic(TX_UUID);
    rx = gatt.getService(UART_UUID).getCharacteristic(RX_UUID);
    // Setup notifications on RX characteristic changes (i.e. data received).
    // First call setCharacteristicNotification to enable notification.
    if (!gatt.setCharacteristicNotification(rx, true)) {
        writeLine("Couldn't set notifications for RX characteristic!");
    }
    // Next update the RX characteristic's client descriptor to enable notifications.
    if (rx.getDescriptor(CLIENT_UUID) != null) {
        BluetoothGattDescriptor desc = rx.getDescriptor(CLIENT_UUID);
        desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        if (!gatt.writeDescriptor(desc)) {
            writeLine("Couldn't write RX client descriptor value!");
        }
    }
    else {
        writeLine("Couldn't get RX client descriptor!");
    }
}
 
Example #25
Source File: P_AndroidGatt.java    From AsteroidOSSync with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final boolean writeDescriptor(BluetoothGattDescriptor descriptor)
{
    if (m_gatt != null && descriptor != null)
    {
        return m_gatt.writeDescriptor(descriptor);
    }
    return false;
}
 
Example #26
Source File: BLEServicePeripheral.java    From unity-bluetooth with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public BLEServicePeripheral(final Activity activity) {
    super(activity);

    mBtAdvertiser = mBtAdapter.getBluetoothLeAdvertiser();
    mBtGattCharacteristic = new BluetoothGattCharacteristic(
            UUID.fromString(CHARACTERISTIC_UUID),
            BluetoothGattCharacteristic.PROPERTY_NOTIFY | BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_WRITE
            , BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);
    BluetoothGattDescriptor dataDescriptor = new BluetoothGattDescriptor(
            UUID.fromString(CHARACTERISTIC_CONFIG_UUID),
            BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);
    mBtGattCharacteristic.addDescriptor(dataDescriptor);
}
 
Example #27
Source File: FragmentCharacteristicDetail.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
protected void writeNextDescriptor() {
    if (iterDescriptor.hasNext()) {
        lastDescriptor = iterDescriptor.next();

        if (lastDescriptor.getCharacteristic() == mBluetoothCharact) {
            lastDescriptor.setValue(Common.isSetProperty(Common.PropertyType.NOTIFY, mBluetoothCharact
                    .getProperties()) ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                    : BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
            //mBluetoothLeService.writeDescriptor(mDevice, lastDescriptor);
            mDevice.writeDescriptor(lastDescriptor);
        }
    }
}
 
Example #28
Source File: WriteGattServerCharacteristicDescriptorValueTransaction.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
public WriteGattServerCharacteristicDescriptorValueTransaction(@Nullable GattServerConnection connection, GattState successEndState, BluetoothGattService service, BluetoothGattCharacteristic characteristic, BluetoothGattDescriptor descriptor, byte[] data) {
    super(connection, successEndState);
    this.descriptor = descriptor;
    this.characteristic = characteristic;
    this.service = service;
    this.data = data;
}
 
Example #29
Source File: WriteGattServerCharacteristicDescriptorValueTransaction.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
public WriteGattServerCharacteristicDescriptorValueTransaction(@Nullable GattServerConnection connection, GattState successEndState, BluetoothGattService service, BluetoothGattCharacteristic characteristic, BluetoothGattDescriptor descriptor, byte[] data, long timeoutMillis) {
    super(connection, successEndState, timeoutMillis);
    this.descriptor = descriptor;
    this.characteristic = characteristic;
    this.service = service;
    this.data = data;
}
 
Example #30
Source File: AndroidBle.java    From GizwitsBLE with Apache License 2.0 5 votes vote down vote up
public void onDescriptorWrite(BluetoothGatt gatt,
		BluetoothGattDescriptor descriptor, int status) {
	String address = gatt.getDevice().getAddress();
	Log.d(TAG, "onDescriptorWrite " + address + " status " + status);
	BleRequest request = mService.getCurrentRequest();
	if (request.type == RequestType.CHARACTERISTIC_NOTIFICATION
			|| request.type == RequestType.CHARACTERISTIC_INDICATION
			|| request.type == RequestType.CHARACTERISTIC_STOP_NOTIFICATION) {
		if (status != BluetoothGatt.GATT_SUCCESS) {
			mService.requestProcessed(address,
					RequestType.CHARACTERISTIC_NOTIFICATION, false);
			return;
		}
		if (request.type == RequestType.CHARACTERISTIC_NOTIFICATION) {
			mService.bleCharacteristicNotification(address, descriptor
					.getCharacteristic().getUuid().toString(), true,
					status);
		} else if (request.type == RequestType.CHARACTERISTIC_INDICATION) {
			mService.bleCharacteristicIndication(address, descriptor
					.getCharacteristic().getUuid().toString(), status);
		} else {
			mService.bleCharacteristicNotification(address, descriptor
					.getCharacteristic().getUuid().toString(), false,
					status);
		}
		return;
	}
}