Java Code Examples for android.bluetooth.BluetoothGattCharacteristic#getDescriptor()

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic#getDescriptor() . 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: 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 2
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 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: BluetoothLeDeviceBase.java    From BlogPracticeDems with Apache License 2.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);

    if (UUID_CHARACTERISTIC.equals(characteristic.getUuid().toString())) {
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
                UUID.fromString(UUID_DESCRIPTOR));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
        Log.d(TAG, " --------- Connect setCharacteristicNotification --------- " + characteristic.getUuid());
    }
}
 
Example 5
Source File: BlePeripheral.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 6 votes vote down vote up
public void readDescriptor(@NonNull BluetoothGattCharacteristic characteristic, UUID descriptorUUID, CompletionHandler completionHandler) {
    final String identifier = kDebugCommands ? getDescriptorIdentifier(characteristic.getService().getUuid(), characteristic.getUuid(), descriptorUUID) : null;
    BleCommand command = new BleCommand(BleCommand.BLECOMMANDTYPE_READDESCRIPTOR, identifier, completionHandler) {
        @Override
        public void execute() {
            // Read Descriptor
            final BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUUID);
            if (descriptor != null) {
                mBluetoothGatt.readDescriptor(descriptor);
            } else {
                Log.w(TAG, "read: descriptor not found: " + descriptorUUID.toString());
                finishExecutingCommand(BluetoothGatt.GATT_READ_NOT_PERMITTED);
            }
        }
    };
    mCommmandQueue.add(command);
}
 
Example 6
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 7
Source File: BTLEDeviceManager.java    From BLEService with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public boolean readDescriptor(String 	address, 
							  UUID 		serviceUUID,
							  UUID 		characteristicUUID, 
							  UUID 		descriptorUUID)throws DeviceManagerException, DeviceNameNotFoundException {
	BTDeviceInfo deviceInfo = getDeviceInfo(address);
	if (deviceInfo == null) {
		throw new DeviceNameNotFoundException(String.format("%s %s",mContext.getString(R.string.device_not_found), address));
	}
	BluetoothGattService service = deviceInfo.getGatt().getService(serviceUUID);
	if (service == null) {
		throw new DeviceManagerException(String.format("%s %s %s",mContext.getString(R.string.service_not_found), address, serviceUUID));
	}
	BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
	if (characteristic == null) {
		throw new DeviceManagerException(String.format("%s %s %s", mContext.getString(R.string.characteristic_not_found),address, characteristicUUID));
	}
	BluetoothGattDescriptor descriptor = characteristic
			.getDescriptor(descriptorUUID);
	if (descriptor == null) {
		throw new DeviceManagerException(String.format("%s %s %s %s", mContext.getString(R.string.descriptor_not_found), address, characteristicUUID, descriptorUUID));
	}
	return readDescriptor(deviceInfo, characteristic, descriptor);
}
 
Example 8
Source File: MultipleBleService.java    From BleLib with Apache License 2.0 6 votes vote down vote up
/**
     * Reads the value for a given descriptor from the associated remote device.
     *
     * @param address            The address of remote device
     * @param serviceUUID        remote device service uuid
     * @param characteristicUUID remote device characteristic uuid
     * @param descriptorUUID     remote device descriptor uuid
     * @return true, if the read operation was initiated successfully
     */
    public boolean readDescriptor(String address, String serviceUUID, String characteristicUUID,
                                  String descriptorUUID) {
        if (mBluetoothGattMap.get(address) == null) {
            Log.w(TAG, "BluetoothGatt is null");
            return false;
        }
//        try {
        BluetoothGattService service =
                mBluetoothGattMap.get(address).getService(UUID.fromString(serviceUUID));
        BluetoothGattCharacteristic characteristic =
                service.getCharacteristic(UUID.fromString(characteristicUUID));
        BluetoothGattDescriptor descriptor =
                characteristic.getDescriptor(UUID.fromString(descriptorUUID));
        return mBluetoothGattMap.get(address).readDescriptor(descriptor);
//        } catch (Exception e) {
//            Log.e(TAG, "read descriptor exception", e);
//            return false;
//        }
    }
 
Example 9
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 10
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 11
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 12
Source File: BleManager.java    From Bluefruit_LE_Connect_Android with MIT License 5 votes vote down vote up
private int getDescriptorPermissions(BluetoothGattService service, String characteristicUUIDString, String descriptorUUIDString) {
    final UUID characteristicUuid = UUID.fromString(characteristicUUIDString);
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    int permissions = 0;
    if (characteristic != null) {
        final UUID descriptorUuid = UUID.fromString(descriptorUUIDString);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
        if (descriptor != null) {
            permissions = descriptor.getPermissions();
        }
    }

    return permissions;
}
 
Example 13
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 14
Source File: AddGattServerServiceCharacteristicTransaction.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * It looks like some phones do not implement these on their own while others implement one or the other
 * or both, so to be sure we want to make sure that any characteristics that we create have these critical
 * descriptors so that we have an opportunity to respond to any read or write requests coming into our
 * gatt server.
 * @param characteristic The characteristic that we are adding to a service
 */

private void addCriticalDescriptorsIfNecessary(BluetoothGattCharacteristic characteristic) {
    CharacteristicNotificationDescriptor notificationDescriptor = new CharacteristicNotificationDescriptor();
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(notificationDescriptor.getUuid());
    if(descriptor == null) {
        characteristic.addDescriptor(notificationDescriptor);
    }
    CharacteristicNamespaceDescriptor namespaceDescriptor = new CharacteristicNamespaceDescriptor();
    BluetoothGattDescriptor characteristicNamespaceDescriptor = characteristic.getDescriptor(namespaceDescriptor.getUuid());
    if(characteristicNamespaceDescriptor == null) {
        characteristic.addDescriptor(namespaceDescriptor);
    }
}
 
Example 15
Source File: BLEService.java    From microbit with Apache License 2.0 5 votes vote down vote up
/**
 * Register to know about the micro:bit requirements. What events does the micro:bit need from us
 * read repeatedly from (3) to find out the events that the micro:bit is interested in receiving.
 * e.g. if a kids app registers to receive events <10,3><15,2> then the first read will
 * give you <10,3> the second <15,2>, the third will give you a zero length value.
 * You can send events to the micro:bit that haven't been asked for, but as no-one will
 * be listening, they will be silently dropped.
 *
 * @param eventService Bluetooth GATT service.
 * @param enable       Enable or disable.
 * @return True, if successful.
 */
private boolean registerMicrobitRequirements(BluetoothGattService eventService, boolean enable) {
    BluetoothGattCharacteristic microbit_requirements = eventService.getCharacteristic(CharacteristicUUIDs
            .ES_MICROBIT_REQUIREMENTS);
    if(microbit_requirements == null) {
        logi("register_eventsFromMicrobit() :: ES_MICROBIT_REQUIREMENTS Not found");
        return false;
    }

    BluetoothGattDescriptor microbit_requirementsDescriptor = microbit_requirements.getDescriptor(UUIDs
            .CLIENT_DESCRIPTOR);
    if(microbit_requirementsDescriptor == null) {
        logi("register_eventsFromMicrobit() :: CLIENT_DESCRIPTOR Not found");
        return false;
    }

    BluetoothGattCharacteristic characteristic = readCharacteristic(microbit_requirements);
    while(characteristic != null && characteristic.getValue() != null && characteristic.getValue().length != 0) {
        String service = BluetoothUtils.parse(characteristic);
        logi("microbit interested in  = " + service);
        if(service.equalsIgnoreCase("4F-04-07-00")) //Incoming Call service
        {
            sendMicroBitNeedsCallNotification();
        }
        if(service.equalsIgnoreCase("4F-04-08-00")) //Incoming SMS service
        {
            sendMicroBitNeedsSmsNotification();
        }
        characteristic = readCharacteristic(microbit_requirements);
    }

    registerForSignalStrength(enable);
    registerForDeviceInfo(enable);

    logi("registerMicrobitRequirements() :: found Constants.ES_MICROBIT_REQUIREMENTS ");
    enableCharacteristicNotification(microbit_requirements, microbit_requirementsDescriptor, enable);
    return true;
}
 
Example 16
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 17
Source File: P_Task_ToggleNotify.java    From AsteroidOSSync with GNU General Public License v3.0 4 votes vote down vote up
@Override protected void executeReadOrWrite()
{
	final BluetoothGattCharacteristic char_native = getFilteredCharacteristic() != null ? getFilteredCharacteristic() : getDevice().getNativeCharacteristic(getServiceUuid(), getCharUuid());

	if( char_native == null )
	{
		this.fail(Status.NO_MATCHING_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, Target.CHARACTERISTIC, getCharUuid(), ReadWriteEvent.NON_APPLICABLE_UUID);
	}
	else if( false == getDevice().layerManager().getGattLayer().setCharacteristicNotification(char_native, m_enable) )
	{
		this.fail(Status.FAILED_TO_TOGGLE_NOTIFICATION, BleStatuses.GATT_STATUS_NOT_APPLICABLE, Target.CHARACTERISTIC, getCharUuid(), ReadWriteEvent.NON_APPLICABLE_UUID);
	}
	else
	{
		final BluetoothGattDescriptor descriptor = char_native.getDescriptor(m_descUuid);

		if( descriptor == null )
		{
			//--- DRK > Previously we were failing the task if the descriptor came up null. It was assumed that writing the descriptor
			//---		was a requirement. It turns out that, at least sometimes, simply calling setCharacteristicNotification(true) is enough.
			succeed();

			// this.fail(Status.NO_MATCHING_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, Target.DESCRIPTOR, m_uuid, m_descUuid);
		}
		else
		{
			m_writeValue = getWriteValue(char_native, m_enable);

			if( false == descriptor.setValue(getWriteValue()) )
			{
				this.fail(Status.FAILED_TO_SET_VALUE_ON_TARGET, BleStatuses.GATT_STATUS_NOT_APPLICABLE, Target.DESCRIPTOR, getCharUuid(), m_descUuid);
			}
			else if( false == getDevice().layerManager().getGattLayer().writeDescriptor(descriptor) )
			{
				this.fail(Status.FAILED_TO_SEND_OUT, BleStatuses.GATT_STATUS_NOT_APPLICABLE, Target.DESCRIPTOR, getCharUuid(), m_descUuid);
			}
			else
			{
				// SUCCESS, so far...
			}
		}
	}
}
 
Example 18
Source File: GattPlugin.java    From bitgatt with Mozilla Public License 2.0 4 votes vote down vote up
private void readGattClientDescriptor(DumperContext dumpContext, Iterator<String> args) throws InterruptedException {
    int index = 0;
    String serviceString = null;
    String characteristicString = null;
    String descriptorString = null;
    String mac = null;
    while (args.hasNext()) {
        if (index == 2) {
            characteristicString = args.next();
        } else if (index == 0) {
            mac = args.next();
        } else if (index == 1) {
            serviceString = args.next();
        } else if (index == 3) {
            descriptorString = args.next();
        }
        index++;
    }
    GattConnection conn = fitbitGatt.getConnectionForBluetoothAddress(context, mac);
    if (conn == null) {
        logError(dumpContext, new IllegalArgumentException("Bluetooth connection for mac " + mac + " not found."));
        return;
    }
    if (mac == null) {
        logError(dumpContext, new IllegalArgumentException("No bluetooth mac provided"));
        return;
    } else if (serviceString == null) {
        logError(dumpContext, new IllegalArgumentException("No service uuid provided"));
        return;
    } else if (characteristicString == null) {
        logError(dumpContext, new IllegalArgumentException("No characteristic uuid provided"));
        return;
    }
    BluetoothGattService service = conn.getGatt().getService(UUID.fromString(serviceString));
    if (service == null) {
        logError(dumpContext, new IllegalArgumentException("Remote gatt service not found"));
        return;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicString));
    if (characteristic == null) {
        logError(dumpContext, new IllegalArgumentException("Remote gatt characteristic not found"));
        return;
    }
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorString));
    if (descriptor == null) {
        logError(dumpContext, new IllegalArgumentException("Remote gatt descriptor not found"));
        return;
    }
    conn.getDevice().addDevicePropertiesChangedListener(this);
    ReadGattDescriptorTransaction readTx = new ReadGattDescriptorTransaction(conn, GattState.READ_DESCRIPTOR_SUCCESS, descriptor);
    CountDownLatch cdl = new CountDownLatch(1);
    conn.runTx(readTx, result -> {
        if (!isJsonFormat) {
            log(dumpContext, result.toString());
            if (result.getResultStatus().equals(TransactionResult.TransactionResultStatus.SUCCESS)) {
                logSuccess(dumpContext, "Successfully read descriptor " + descriptor.getUuid());
                log(dumpContext, Bytes.byteArrayToHexString(result.getData()));
            } else {
                logFailure(dumpContext, "Failed reading descriptor " + descriptor.getUuid());
            }
        } else {
            Map<String, Object> resultMap = new LinkedHashMap<>();
            resultMap.put(RESULT_DESCRIPTOR_VALUE, Bytes.byteArrayToHexString(result.getData()));
            logJsonResult(dumpContext, result, result.toString(), resultMap);
        }
        cdl.countDown();
        conn.getDevice().removeDevicePropertiesChangedListener(this);
    });
    cdl.await();
}
 
Example 19
Source File: BleConnector.java    From FastBle with Apache License 2.0 4 votes vote down vote up
/**
 * indicate setting
 */
private boolean setCharacteristicIndication(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic,
                                            boolean useCharacteristicDescriptor,
                                            boolean enable,
                                            BleIndicateCallback bleIndicateCallback) {
    if (gatt == null || characteristic == null) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("gatt or characteristic equal null"));
        return false;
    }

    boolean success1 = gatt.setCharacteristicNotification(characteristic, enable);
    if (!success1) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("gatt setCharacteristicNotification fail"));
        return false;
    }

    BluetoothGattDescriptor descriptor;
    if (useCharacteristicDescriptor) {
        descriptor = characteristic.getDescriptor(characteristic.getUuid());
    } else {
        descriptor = characteristic.getDescriptor(formUUID(UUID_CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR));
    }
    if (descriptor == null) {
        indicateMsgInit();
        if (bleIndicateCallback != null)
            bleIndicateCallback.onIndicateFailure(new OtherException("descriptor equals null"));
        return false;
    } else {
        descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_INDICATION_VALUE :
                BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        boolean success2 = gatt.writeDescriptor(descriptor);
        if (!success2) {
            indicateMsgInit();
            if (bleIndicateCallback != null)
                bleIndicateCallback.onIndicateFailure(new OtherException("gatt writeDescriptor fail"));
        }
        return success2;
    }
}
 
Example 20
Source File: GattPlugin.java    From bitgatt with Mozilla Public License 2.0 4 votes vote down vote up
private void readLocalGattServerCharacteristicDescriptor(DumperContext dumpContext, Iterator<String> args) throws InterruptedException {
    int index = 0;
    String serviceString = null;
    String characteristicString = null;
    String descriptorString = null;
    while (args.hasNext()) {
        if (index == 0) {
            serviceString = args.next();
        } else if (index == 1) {
            characteristicString = args.next();
        } else if (index == 2) {
            descriptorString = args.next();
        }
        index++;
    }
    if (serviceString == null) {
        logError(dumpContext, new IllegalArgumentException("No service uuid provided"));
        return;
    } else if (characteristicString == null) {
        logError(dumpContext, new IllegalArgumentException("No characteristic uuid provided"));
        return;
    } else if (descriptorString == null) {
        logError(dumpContext, new IllegalArgumentException("No descriptor uuid provided"));
        return;
    }
    GattServerConnection conn = fitbitGatt.getServer();
    if (conn == null) {
        logError(dumpContext, new IllegalArgumentException("No valid gatt server available"));
        return;
    }
    BluetoothGattService localService = conn.getServer().getService(UUID.fromString(serviceString));
    if (localService == null) {
        logError(dumpContext, new IllegalStateException("No service for the uuid " + serviceString + " found"));
        return;
    }
    BluetoothGattCharacteristic localCharacteristic = localService.getCharacteristic(UUID.fromString(characteristicString));
    if (localCharacteristic == null) {
        logError(dumpContext, new IllegalStateException("No characteristic for the uuid " + characteristicString + " found"));
        return;
    }
    BluetoothGattDescriptor localDescriptor = localCharacteristic.getDescriptor(UUID.fromString(descriptorString));
    if (localDescriptor == null) {
        logError(dumpContext, new IllegalStateException("No descriptor for the uuid " + descriptorString + " found"));
        return;
    }
    ReadGattServerCharacteristicDescriptorValueTransaction tx = new ReadGattServerCharacteristicDescriptorValueTransaction(conn, GattState.READ_DESCRIPTOR_SUCCESS, localService, localCharacteristic, localDescriptor);
    CountDownLatch cdl = new CountDownLatch(1);
    conn.runTx(tx, result -> {
        logSuccessOrFailure(result, dumpContext, "Successfully wrote to " + localDescriptor.getUuid().toString() + " on " + localCharacteristic.getUuid().toString() + " on " + localService.getUuid().toString(), "Failed writing to " + localDescriptor.getUuid().toString() + " on " + localCharacteristic.getUuid().toString() + " on " + localService.getUuid().toString());
        cdl.countDown();
    });
    cdl.await();
}