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

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic#getDescriptors() . 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: H7ConnectThread.java    From PolarHeartRateApplication with MIT License 6 votes vote down vote up
@Override
  public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
  	BluetoothGattService service = gatt.getService(UUID.fromString(HRUUID)); // Return the HR service
//BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString("00002A37-0000-1000-8000-00805F9B34FB"));
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); //Get the hart rate value
for (BluetoothGattCharacteristic cc : characteristics)
	{
		for (BluetoothGattDescriptor descriptor : cc.getDescriptors()) {
		    //find descriptor UUID that matches Client Characteristic Configuration (0x2902)
		    // and then call setValue on that descriptor
			
			//Those two line set the value for the disconnection
			H7ConnectThread.descriptor=descriptor;
			H7ConnectThread.cc=cc;
									
			gatt.setCharacteristicNotification(cc,true);//Register to updates
			descriptor.setValue( BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		    gatt.writeDescriptor(descriptor);
			Log.d("H7ConnectThread", "Connected and regisering to info");
		}
	}
  }
 
Example 2
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 3
Source File: HeartRateConnector.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * Register notification of HeartRateMeasurement Characteristic.
 *
 * @param gatt GATT Service
 * @return true if successful in notification of registration
 */
private boolean callRegisterHeartRateMeasurement(final BluetoothGatt gatt) {
    boolean registered = false;
    BluetoothGattService service = gatt.getService(UUID.fromString(
            BleUtils.SERVICE_HEART_RATE_SERVICE));
    if (service != null) {
        BluetoothGattCharacteristic c = service.getCharacteristic(
                UUID.fromString(BleUtils.CHAR_HEART_RATE_MEASUREMENT));
        if (c != null) {
            registered = gatt.setCharacteristicNotification(c, true);
            if (registered) {
                for (BluetoothGattDescriptor descriptor : c.getDescriptors()) {
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    gatt.writeDescriptor(descriptor);
                }
                mHRDevices.put(gatt, DeviceState.REGISTER_NOTIFY);
            }
        }
    }
    return registered;
}
 
Example 4
Source File: BleRequestImpl.java    From Android-BLE with Apache License 2.0 6 votes vote down vote up
private void setCharacteristicNotificationInternal(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, boolean enabled){
    gatt.setCharacteristicNotification(characteristic, enabled);
    //If the number of descriptors in the eigenvalue of the notification is greater than zero
    if (characteristic.getDescriptors().size() > 0) {
        //Filter descriptors based on the uuid of the descriptor
        List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
        for(BluetoothGattDescriptor descriptor : descriptors){
            if (descriptor != null) {
                //Write the description value
                if((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0){
                    descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                }else if((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0){
                    //两个都是通知的意思,notify和indication的区别在于,notify只是将你要发的数据发送给手机,没有确认机制,
                    //不会保证数据发送是否到达。而indication的方式在手机收到数据时会主动回一个ack回来。即有确认机制,只有收
                    //到这个ack你才能继续发送下一个数据。这保证了数据的正确到达,也起到了流控的作用。所以在打开通知的时候,需要设置一下。
                    descriptor.setValue(enabled?BluetoothGattDescriptor.ENABLE_INDICATION_VALUE:BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
                }
                gatt.writeDescriptor(descriptor);
                BleLog.d(TAG, "setCharacteristicNotificationInternal is "+enabled);
            }
        }
    }
}
 
Example 5
Source File: GattUtils.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Will return the copy of the service
 *
 * @param service The gatt service
 * @return a shallow-ish copy of the service
 */

public @Nullable
BluetoothGattServiceCopy copyService(@Nullable BluetoothGattService service) {
    if (null == service || null == service.getUuid()) {
        return null;
    }
    BluetoothGattServiceCopy newService = new BluetoothGattServiceCopy(service.getUuid(), service.getType());
    if (!service.getIncludedServices().isEmpty()) {
        for (BluetoothGattService includedService : service.getIncludedServices()) {
            BluetoothGattServiceCopy newGattService = new BluetoothGattServiceCopy(includedService.getUuid(), includedService.getType());
            newService.addService(newGattService);
        }
    }
    if (!service.getCharacteristics().isEmpty()) {
        // why not use the copy characteristic method, it will implicitly link itself to the null service
        for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
            BluetoothGattCharacteristicCopy newCharacteristic = new BluetoothGattCharacteristicCopy(characteristic.getUuid(), characteristic.getProperties(), characteristic.getPermissions());
            if (characteristic.getValue() != null) {
                newCharacteristic.setValue(Arrays.copyOf(characteristic.getValue(), characteristic.getValue().length));
            }
            // why not use the copy descriptor method?  It will implicitly link itself to the null characteristic
            for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                BluetoothGattDescriptorCopy newDescriptor = new BluetoothGattDescriptorCopy(descriptor.getUuid(), descriptor.getPermissions());
                if (descriptor.getValue() != null) {
                    newDescriptor.setValue(Arrays.copyOf(descriptor.getValue(), descriptor.getValue().length));
                }
                newCharacteristic.addDescriptor(newDescriptor);
            }
            newService.addCharacteristic(newCharacteristic);
        }
    }
    return newService;
}
 
Example 6
Source File: BluetoothLeService.java    From jessica with MIT License 5 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);

    for( BluetoothGattDescriptor descriptor : characteristic.getDescriptors() ) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mBluetoothGatt.writeDescriptor(descriptor);
    }
}
 
Example 7
Source File: BluetoothDebug.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
private int readServiceCharacteristics(BluetoothGattService service, int offset) {
    for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
        if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) != 0
                && !isBlacklisted(service, characteristic)) {

            if (offset == 0) {
                readBytes(service.getUuid(), characteristic.getUuid());
                return -1;
            }

            offset -= 1;
        }

        for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
            if (offset == 0) {
                readBytes(service.getUuid(), characteristic.getUuid());
                return -1;
            }

            offset -= 1;
        }
    }

    for (BluetoothGattService included : service.getIncludedServices()) {
        offset = readServiceCharacteristics(included, offset);
        if (offset == -1) {
            return offset;
        }
    }

    return offset;
}
 
Example 8
Source File: BluetoothDebug.java    From openScale with GNU General Public License v3.0 5 votes vote down vote up
private void logService(BluetoothGattService service, boolean included) {
    Timber.d("Service %s%s", BluetoothGattUuid.prettyPrint(service.getUuid()),
            included ? " (included)" : "");

    for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
        Timber.d("|- characteristic %s (#%d): %s%s",
                BluetoothGattUuid.prettyPrint(characteristic.getUuid()),
                characteristic.getInstanceId(),
                propertiesToString(characteristic.getProperties(), characteristic.getWriteType()),
                permissionsToString(characteristic.getPermissions()));
        byte[] value = characteristic.getValue();
        if (value != null && value.length > 0) {
            Timber.d("|--> value: %s (%s)", byteInHex(value), byteToString(value));
        }

        for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
            Timber.d("|--- descriptor %s%s",
                    BluetoothGattUuid.prettyPrint(descriptor.getUuid()),
                    permissionsToString(descriptor.getPermissions()));

            value = descriptor.getValue();
            if (value != null && value.length > 0) {
                Timber.d("|-----> value: %s (%s)", byteInHex(value), byteToString(value));
            }
        }
    }

    for (BluetoothGattService includedService : service.getIncludedServices()) {
        logService(includedService, true);
    }
}
 
Example 9
Source File: BleGattCharacter.java    From Android-BluetoothKit with Apache License 2.0 5 votes vote down vote up
public BleGattCharacter(BluetoothGattCharacteristic characteristic) {
    this.uuid = new ParcelUuid(characteristic.getUuid());
    this.property = characteristic.getProperties();
    this.permissions = characteristic.getPermissions();

    for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
        getDescriptors().add(new BleGattDescriptor(descriptor));
    }
}
 
Example 10
Source File: CharacteristicDetailActivity.java    From AndroidBleManager with Apache License 2.0 5 votes vote down vote up
public void setCharacteristicNotification(final BluetoothGattCharacteristic characteristic, final boolean enabled) {
    if (gatt == null) {
        Logger.w("CharacteristicDetailActivity", "BluetoothAdapter not initialized");
        return;
    }
    gatt.setCharacteristicNotification(characteristic, enabled);
    if (enabled){
        for (BluetoothGattDescriptor descriptor:characteristic.getDescriptors()){
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }
    }

}
 
Example 11
Source File: LoggerUtilBluetoothServices.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
private static void appendDescriptors(StringBuilder descriptionBuilder, BluetoothGattCharacteristic characteristic) {
    if (!characteristic.getDescriptors().isEmpty()) {
        appendDescriptorsHeader(descriptionBuilder);
        for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
            appendDescriptorNameHeader(descriptionBuilder, descriptor);
        }
    }
}
 
Example 12
Source File: BikeService.java    From android with MIT License 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);

    print("发现服务:" + status);

    if (BluetoothGatt.GATT_SUCCESS == status) {
        List<BluetoothGattService> gattServices = gatt.getServices();
        if (null == gattServices || gattServices.size() == 0) {
            return;
        }
        for (BluetoothGattService gattService : gattServices) {
            String serviceUUID = gattService.getUuid().toString();
            print("UUID GATT:" + serviceUUID);
            List<BluetoothGattCharacteristic> characteristics = gattService.getCharacteristics();
            for (BluetoothGattCharacteristic characteristic : characteristics) {
                String uuid = characteristic.getUuid().toString();
                print("UUID     Charac:" + uuid);
                print("UUID     Status:" + getProperties(characteristic));
                print("UUID     Status:" + characteristic.getInstanceId());
                List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    print("UUID          Desc:" + descriptor.getUuid().toString());
                    print("UUID          Perm:" + String.valueOf(descriptor.getPermissions()));
                }
                if (UUID_RECEIVE.toString().equalsIgnoreCase(uuid)) {
                    mBluetoothGatt.setCharacteristicNotification(characteristic, true);
                    print("开始监听:" + uuid);
                }
            }
        }
    }
}
 
Example 13
Source File: PBluetoothLEClientBak.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
public void listenToCharacteristic(String UUIDService, String UUIDCharacteristic) {
    MLog.d(TAG, "LISTENING...");

    BluetoothGattService service = mGatt.getService(UUID.fromString(UUIDService));
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(UUIDCharacteristic));

    for (BluetoothGattDescriptor bluetoothGattDescriptor : characteristic.getDescriptors()) {
        bluetoothGattDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
        mGatt.writeDescriptor(bluetoothGattDescriptor);
    }
    mGatt.setCharacteristicNotification(characteristic, true);
}
 
Example 14
Source File: GattUtils.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * To prevent the characteristic from changing out from under us we need to copy it
 * <p>
 * This may happen under high throughput/concurrency
 *
 * @param characteristic The characteristic to be copied
 * @return The shallow-ish copy of the characteristic
 */
public @Nullable
BluetoothGattCharacteristicCopy copyCharacteristic(@Nullable BluetoothGattCharacteristic characteristic) {
    if (null == characteristic || null == characteristic.getUuid()) {
        return null;
    }
    BluetoothGattCharacteristicCopy newCharacteristic =
            new BluetoothGattCharacteristicCopy(characteristic.getUuid(),
                    characteristic.getProperties(), characteristic.getPermissions());
    if (characteristic.getValue() != null) {
        newCharacteristic.setValue(Arrays.copyOf(characteristic.getValue(), characteristic.getValue().length));
    }
    if (!characteristic.getDescriptors().isEmpty()) {
        for (BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
            BluetoothGattDescriptorCopy newDescriptor = new BluetoothGattDescriptorCopy(descriptor.getUuid(), descriptor.getPermissions());
            if (descriptor.getValue() != null) {
                newDescriptor.setValue(Arrays.copyOf(descriptor.getValue(), descriptor.getValue().length));
            }
            newCharacteristic.addDescriptor(newDescriptor);
        }
    }
    if (characteristic.getService() != null) {
        BluetoothGattServiceCopy newService = new BluetoothGattServiceCopy(characteristic.getService().getUuid(), characteristic.getService().getType());
        newService.addCharacteristic(newCharacteristic);
    }
    return newCharacteristic;
}
 
Example 15
Source File: DeviceControlActivity.java    From AndroidBleManager with Apache License 2.0 4 votes vote down vote up
private void displayGattServices(final List<BluetoothGattService> gattServices) {
    if (gattServices == null) return;
    generateExportString(gattServices);

    String uuid = null;
    final String unknownServiceString = getResources().getString(R.string.unknown_service);
    final String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
    final List<Map<String, String>> gattServiceData = new ArrayList<>();
    final List<List<Map<String, String>>> gattCharacteristicData = new ArrayList<>();
    mGattCharacteristics = new ArrayList<>();

    // Loops through available GATT Services.
    for (final BluetoothGattService gattService : gattServices) {
        final Map<String, String> currentServiceData = new HashMap<>();
        uuid = gattService.getUuid().toString();
        currentServiceData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownServiceString));
        currentServiceData.put(LIST_UUID, uuid.substring(4,8));
        System.out.println("---service name:"+currentServiceData.get(LIST_NAME));
        System.out.println("---service uuid:" + uuid);
        gattServiceData.add(currentServiceData);

        final List<Map<String, String>> gattCharacteristicGroupData = new ArrayList<>();
        final List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
        final List<BluetoothGattCharacteristic> charas = new ArrayList<>();

        // Loops through available Characteristics.
        for (final BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
            charas.add(gattCharacteristic);
            final Map<String, String> currentCharaData = new HashMap<>();
            uuid = gattCharacteristic.getUuid().toString();
            String property = getPropertyString(gattCharacteristic.getProperties());
            currentCharaData.put(LIST_NAME, GattAttributeResolver.getAttributeName(uuid, unknownCharaString));
            currentCharaData.put(LIST_UUID, uuid.substring(4,8)+" "+property);
            System.out.println("-----char name:" + currentCharaData.get(LIST_NAME));
            System.out.println("-----chat uuid:"+ uuid);
            gattCharacteristicGroupData.add(currentCharaData);
            for (BluetoothGattDescriptor gattDescriptor:gattCharacteristic.getDescriptors()){
                System.out.println("--------des name:" + gattDescriptor.getUuid());
                System.out.println("--------des uuid:" + gattDescriptor.getValue()+" "+gattDescriptor.getPermissions());
            }
        }

        mGattCharacteristics.add(charas);
        gattCharacteristicData.add(gattCharacteristicGroupData);
    }

    final SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
            this,
            gattServiceData,
            android.R.layout.simple_expandable_list_item_2,
            new String[]{LIST_NAME, LIST_UUID},
            new int[]{android.R.id.text1, android.R.id.text2},
            gattCharacteristicData,
            android.R.layout.simple_expandable_list_item_2,
            new String[]{LIST_NAME, LIST_UUID},
            new int[]{android.R.id.text1, android.R.id.text2}
    );

    mGattServicesList.setAdapter(gattServiceAdapter);
    invalidateOptionsMenu();
}
 
Example 16
Source File: InfoActivity.java    From Bluefruit_LE_Connect_Android with MIT License 4 votes vote down vote up
@Override
    public void onServicesDiscovered() {

        // Remove old data
        mServicesList.clear();
        mCharacteristicsMap.clear();
        mDescriptorsMap.clear();
        mValuesMap.clear();

        // Services
        List<BluetoothGattService> services = mBleManager.getSupportedGattServices();
        for (BluetoothGattService service : services) {
            String serviceUuid = service.getUuid().toString();
            int instanceId = service.getInstanceId();
            String serviceName = KnownUUIDs.getServiceName(serviceUuid);
            String finalServiceName = serviceName != null ? serviceName : serviceUuid;
            ElementPath serviceElementPath = new ElementPath(serviceUuid, instanceId, null, null, finalServiceName, serviceUuid);
            mServicesList.add(serviceElementPath);

            // Characteristics
            List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
            List<ElementPath> characteristicNamesList = new ArrayList<>(characteristics.size());
            for (BluetoothGattCharacteristic characteristic : characteristics) {
                String characteristicUuid = characteristic.getUuid().toString();
                String characteristicName = KnownUUIDs.getCharacteristicName(characteristicUuid);
                String finalCharacteristicName = characteristicName != null ? characteristicName : characteristicUuid;
                ElementPath characteristicElementPath = new ElementPath(serviceUuid, instanceId, characteristicUuid, null, finalCharacteristicName, characteristicUuid);
                characteristicNamesList.add(characteristicElementPath);

                // Read characteristic
                if (mBleManager.isCharacteristicReadable(service, characteristicUuid)) {
                    mBleManager.readCharacteristic(service, characteristicUuid);
                }

                // Descriptors
                List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                List<ElementPath> descriptorNamesList = new ArrayList<>(descriptors.size());
                for (BluetoothGattDescriptor descriptor : descriptors) {
                    String descriptorUuid = descriptor.getUuid().toString();
                    String descriptorName = KnownUUIDs.getDescriptorName(descriptorUuid);
                    String finalDescriptorName = descriptorName != null ? descriptorName : descriptorUuid;
                    descriptorNamesList.add(new ElementPath(serviceUuid, instanceId, characteristicUuid, descriptorUuid, finalDescriptorName, descriptorUuid));

                    // Read descriptor
//                    if (mBleManager.isDescriptorReadable(service, characteristicUuid, descriptorUuid)) {
                    mBleManager.readDescriptor(service, characteristicUuid, descriptorUuid);
//                    }
                }

                mDescriptorsMap.put(characteristicElementPath.getKey(), descriptorNamesList);
            }
            mCharacteristicsMap.put(serviceElementPath.getKey(), characteristicNamesList);
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUI();

            }
        });
    }
 
Example 17
Source File: RileyLinkBLE.java    From AndroidAPS with GNU Affero General Public License v3.0 4 votes vote down vote up
public BLECommOperationResult setNotification_blocking(UUID serviceUUID, UUID charaUUID) {
    BLECommOperationResult rval = new BLECommOperationResult();
    if (bluetoothConnectionGatt != null) {

        try {
            gattOperationSema.acquire();
            SystemClock.sleep(1); // attempting to yield thread, to make sequence of events easier to follow
        } catch (InterruptedException e) {
            LOG.error("setNotification_blocking: interrupted waiting for gattOperationSema");
            return rval;
        }
        if (mCurrentOperation != null) {
            rval.resultCode = BLECommOperationResult.RESULT_BUSY;
        } else {
            if (bluetoothConnectionGatt.getService(serviceUUID) == null) {
                // Catch if the service is not supported by the BLE device
                rval.resultCode = BLECommOperationResult.RESULT_NONE;
                LOG.error("BT Device not supported");
                // TODO: 11/07/2016 UI update for user
            } else {
                BluetoothGattCharacteristic chara = bluetoothConnectionGatt.getService(serviceUUID)
                        .getCharacteristic(charaUUID);
                // Tell Android that we want the notifications
                bluetoothConnectionGatt.setCharacteristicNotification(chara, true);
                List<BluetoothGattDescriptor> list = chara.getDescriptors();
                if (gattDebugEnabled) {
                    for (int i = 0; i < list.size(); i++) {
                        if (isLogEnabled())
                            LOG.debug("Found descriptor: " + list.get(i).toString());
                    }
                }
                BluetoothGattDescriptor descr = list.get(0);
                // Tell the remote device to send the notifications
                mCurrentOperation = new DescriptorWriteOperation(bluetoothConnectionGatt, descr,
                        BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                mCurrentOperation.execute(this);
                if (mCurrentOperation.timedOut) {
                    rval.resultCode = BLECommOperationResult.RESULT_TIMEOUT;
                } else if (mCurrentOperation.interrupted) {
                    rval.resultCode = BLECommOperationResult.RESULT_INTERRUPTED;
                } else {
                    rval.resultCode = BLECommOperationResult.RESULT_SUCCESS;
                }
            }
            mCurrentOperation = null;
            gattOperationSema.release();
        }
    } else {
        LOG.error("setNotification_blocking: not configured!");
        rval.resultCode = BLECommOperationResult.RESULT_NOT_CONFIGURED;
    }
    return rval;
}
 
Example 18
Source File: DeviceServicesActivity.java    From EFRConnect-android with Apache License 2.0 4 votes vote down vote up
/**
 * READ ALL THE SERVICES, PRINT IT ON LOG AND RECOGNIZES HOMEKIT ACCESSORIES
 *****************/
public void getServicesInfo(BluetoothGatt gatt) {

    List<BluetoothGattService> gattServices = gatt.getServices();
    Log.i("onServicesDiscovered", "Services count: " + gattServices.size());

    for (BluetoothGattService gattService : gattServices) {
        String serviceUUID = gattService.getUuid().toString();
        Log.i("onServicesDiscovered", "Service UUID " + serviceUUID + " - Char count: " + gattService.getCharacteristics().size());
        List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();

        for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {

            String CharacteristicUUID = gattCharacteristic.getUuid().toString();
            Log.i("onServicesDiscovered", "Characteristic UUID " + CharacteristicUUID + " - Properties: " + gattCharacteristic.getProperties());

            if (gattCharacteristic.getUuid().toString().equals(ota_control.toString())) {
                if (gattCharacteristics.contains(bluetoothGatt.getService(ota_service).getCharacteristic(ota_data))) {
                    if (!gattServices.contains(bluetoothGatt.getService(homekit_service))) {
                        Log.i("onServicesDiscovered", "Device in DFU Mode");
                    } else {
                        Log.i("onServicesDiscovered", "OTA_Control found");
                        List<BluetoothGattDescriptor> gattDescriptors = gattCharacteristic.getDescriptors();

                        for (BluetoothGattDescriptor gattDescriptor : gattDescriptors) {
                            String descriptor = gattDescriptor.getUuid().toString();

                            if (gattDescriptor.getUuid().toString().equals(homekit_descriptor.toString())) {
                                kit_descriptor = gattDescriptor;
                                Log.i("descriptor", "UUID: " + descriptor);
                                //bluetoothGatt.readDescriptor(gattDescriptor);
                                byte[] stable = {(byte) 0x00, (byte) 0x00};
                                homeKitOTAControl(stable);
                                homekit = true;

                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 19
Source File: DeviceServicesActivity.java    From EFRConnect-android with Apache License 2.0 4 votes vote down vote up
private void loadCharacteristicDescriptors(BluetoothGattCharacteristic bluetoothGattCharacteristic, TextView descriptorsLabelTextView, LinearLayout descriptorLinearLayout) {
    if (bluetoothGattCharacteristic.getDescriptors().size() <= 0) {
        descriptorsLabelTextView.setVisibility(View.GONE);
    } else {
        for (BluetoothGattDescriptor d : bluetoothGattCharacteristic.getDescriptors()) {
            Descriptor descriptor = Engine.getInstance().getDescriptorByUUID(d.getUuid());

            TextView descriptorNameTV = new TextView(this);
            descriptorNameTV.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            if (descriptor == null) {
                descriptorNameTV.setText(getResources().getString(R.string.unknown));
            } else {
                descriptorNameTV.setText(descriptor.getName());
            }
            descriptorNameTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            descriptorNameTV.setTextColor(ContextCompat.getColor(this, R.color.silabs_primary_text));
            descriptorLinearLayout.addView(descriptorNameTV);


            LinearLayout uuidLL = new LinearLayout(this);
            uuidLL.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            uuidLL.setOrientation(LinearLayout.HORIZONTAL);

            TextView uuidLabelTV = new TextView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMarginEnd((int) (getResources().getDisplayMetrics().density * 4));
            uuidLabelTV.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            uuidLabelTV.setText(getResources().getText(R.string.UUID_colon));
            uuidLabelTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            uuidLabelTV.setLayoutParams(params);
            uuidLL.addView(uuidLabelTV);

            TextView uuidTV = new TextView(this);
            uuidTV.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            if (descriptor != null) {
                uuidTV.setText(Common.getUuidText(descriptor.getUuid()));
            } else {
                uuidTV.setText(getResources().getString(R.string.unknown));
            }

            uuidTV.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
            uuidTV.setTextColor(ContextCompat.getColor(this, R.color.silabs_primary_text));
            uuidLL.addView(uuidTV);

            descriptorLinearLayout.addView(uuidLL);
        }
    }

}
 
Example 20
Source File: InfoFragment.java    From Bluefruit_LE_Connect_Android_V2 with MIT License 4 votes vote down vote up
private void refreshData() {
        // Remove old data
        mInfoData.clear();

        // Services
        List<BluetoothGattService> services = mBlePeripheral == null ? null : mBlePeripheral.getServices();     // Check if mBlePeripheral is null (crash detected on Google logs)

        if (services != null) {
            // Order services so "DIS" is at the top (if present)
            Collections.sort(services, (serviceA, serviceB) -> {
                final boolean isServiceADis = serviceA.getUuid().equals(kDisServiceUUID);
                final boolean isServiceBDis = serviceB.getUuid().equals(kDisServiceUUID);
                return isServiceADis ? -1 : (isServiceBDis ? 1 : serviceA.getUuid().compareTo(serviceB.getUuid()));
            });

            final Handler mainHandler = new Handler(Looper.getMainLooper());
            // Discover characteristics and descriptors
            for (BluetoothGattService service : services) {
                // Service
                final UUID serviceUuid = service.getUuid();
                final int instanceId = service.getInstanceId();
                String serviceUUIDString = BleUtils.uuidToString(serviceUuid);
                String serviceName = BleUUIDNames.getNameForUUID(getContext(), serviceUUIDString);
                String finalServiceName = serviceName != null ? serviceName : LocalizationManager.getInstance().getString(getContext(), "info_type_service");
                ElementPath serviceElementPath = new ElementPath(serviceUuid, instanceId, null, null, finalServiceName, serviceUUIDString);
                mInfoData.mServices.add(serviceElementPath);

                // Characteristics
                List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
                List<ElementPath> characteristicNamesList = new ArrayList<>(characteristics.size());
                for (final BluetoothGattCharacteristic characteristic : characteristics) {
                    final UUID characteristicUuid = characteristic.getUuid();
                    final String characteristicUuidString = BleUtils.uuidToString(characteristicUuid);
                    String characteristicName = BleUUIDNames.getNameForUUID(getContext(), characteristicUuidString);
                    String finalCharacteristicName = characteristicName != null ? characteristicName : characteristicUuidString;
                    final ElementPath characteristicElementPath = new ElementPath(serviceUuid, instanceId, characteristicUuid, null, finalCharacteristicName, characteristicUuidString);
                    characteristicNamesList.add(characteristicElementPath);

                    // Read characteristic
                    if (BlePeripheral.isCharacteristicReadable(service, characteristicUuid)) {
                        final String characteristicKey = characteristicElementPath.getKey();
                        mBlePeripheral.readCharacteristic(service, characteristicUuid, (status, data) -> {
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                mInfoData.mValuesMap.put(characteristicKey, data);

                                // Update UI
                                mainHandler.post(this::updateUI);
                            }
                        });

                        /*
                        mBlePeripheral.readCharacteristic(service, characteristicUuid, status -> {
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                mInfoData.mValuesMap.put(characteristicKey, characteristic.getValue());

                                // Update UI
                                mainHandler.post(this::updateUI);
                            }
                        });*/
                    }

                    // Descriptors
                    List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors();
                    List<ElementPath> descriptorNamesList = new ArrayList<>(descriptors.size());
                    for (final BluetoothGattDescriptor descriptor : descriptors) {
                        final UUID descriptorUuid = descriptor.getUuid();
                        final String descriptorUuidString = BleUtils.uuidToString(descriptorUuid);
                        String descriptorName = BleUUIDNames.getNameForUUID(getContext(), descriptorUuidString);
                        String finalDescriptorName = descriptorName != null ? descriptorName : descriptorUuidString;
                        final ElementPath descriptorElementPath = new ElementPath(serviceUuid, instanceId, characteristicUuid, descriptorUuid, finalDescriptorName, descriptorUuidString);
                        descriptorNamesList.add(descriptorElementPath);

                        // Read descriptor
//                    if (BlePeripheral.isDescriptorReadable(service, characteristicUuid, descriptorUuid)) {
                        final String descriptorKey = descriptorElementPath.getKey();
                        mBlePeripheral.readDescriptor(service, characteristicUuid, descriptorUuid, status -> {
                            if (status == BluetoothGatt.GATT_SUCCESS) {
                                mInfoData.mValuesMap.put(descriptorKey, descriptor.getValue());

                                // Update UI
                                mainHandler.post(this::updateUI);
                            }
                        });
//                    }
                    }

                    mInfoData.mDescriptors.put(characteristicElementPath.getKey(), descriptorNamesList);
                }
                mInfoData.mCharacteristics.put(serviceElementPath.getKey(), characteristicNamesList);
            }
        }

        updateUI();
    }