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

The following examples show how to use android.bluetooth.BluetoothGattCharacteristic#getUuid() . 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: BatteryServiceFragment.java    From ble-test-peripheral-android with Apache License 2.0 6 votes vote down vote up
@Override
public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
  if (characteristic.getUuid() != BATTERY_LEVEL_UUID) {
    return;
  }
  if (indicate) {
    return;
  }
  getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
      Toast.makeText(getActivity(), R.string.notificationsEnabled, Toast.LENGTH_SHORT)
          .show();
    }
  });
}
 
Example 2
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    UUID charUuid = characteristic.getUuid();
    Log.d(TAG, "Characteristic Update Received: " + charUuid);
    if (charUuid.compareTo(mReceiveDataCharacteristic.getUuid()) == 0) {
        Log.d(TAG, "mCharReceiveData Update");
        byte[] value = characteristic.getValue();
        if (value != null) {
            Observable.just(characteristic.getValue()).subscribe(mDataResponseListener);
        }
    } else if (charUuid.compareTo(mHeartBeatCharacteristic.getUuid()) == 0) {
        long heartbeat = System.currentTimeMillis();
        Log.d(TAG, "Heartbeat delta: " + (heartbeat - lastHeartbeat));
        if ((heartbeat-lastHeartbeat < 59000) || heartbeatCount > 5) {
            Log.d(TAG, "Early heartbeat.  Fetching data.");
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarm.cancel(pendingIntent);
            heartbeatCount = 0;
            attemptConnection();
        }
        heartbeatCount += 1;
        lastHeartbeat = heartbeat;
    }
}
 
Example 3
Source File: P_BleDevice_Listeners.java    From SweetBlue with GNU General Public License v3.0 6 votes vote down vote up
private void onCharacteristicRead_updateThread(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int gattStatus, final byte[] value)
{
    final UUID uuid = characteristic.getUuid();
    logger().i(logger().charName(uuid));
    logger().log_status(gattStatus);

    final P_Task_Read readTask = m_queue.getCurrent(P_Task_Read.class, m_device);

    if (readTask != null && readTask.isFor(characteristic))
    {
        readTask.onCharacteristicRead(gatt, characteristic.getUuid(), value, gattStatus);
    }
    else
    {
        final P_Task_BatteryLevel batteryTask = m_queue.getCurrent(P_Task_BatteryLevel.class, m_device);
        if (batteryTask != null)
        {
            batteryTask.onCharacteristicRead(gatt, characteristic.getUuid(), value, gattStatus);
        }
        else
        {
            fireUnsolicitedEvent(new BleCharacteristicWrapper(characteristic), BleDescriptorWrapper.NULL, BleDevice.ReadWriteListener.Type.READ, BleDevice.ReadWriteListener.Target.CHARACTERISTIC, value, gattStatus);
        }
    }
}
 
Example 4
Source File: DexShareCollectionService.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    UUID charUuid = characteristic.getUuid();
    Log.d(TAG, "Characteristic Update Received: " + charUuid);
    if (charUuid.compareTo(mReceiveDataCharacteristic.getUuid()) == 0) {
        Log.d(TAG, "mCharReceiveData Update");
        byte[] value = characteristic.getValue();
        if (value != null) {
            Observable.just(characteristic.getValue()).subscribe(mDataResponseListener);
        }
    } else if (charUuid.compareTo(mHeartBeatCharacteristic.getUuid()) == 0) {
        long heartbeat = System.currentTimeMillis();
        Log.d(TAG, "Heartbeat delta: " + (heartbeat - lastHeartbeat));
        if ((heartbeat-lastHeartbeat < 59000) || heartbeatCount > 5) {
            Log.d(TAG, "Early heartbeat.  Fetching data.");
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarm.cancel(pendingIntent);
            heartbeatCount = 0;
            attemptConnection();
        }
        heartbeatCount += 1;
        lastHeartbeat = heartbeat;
    }
}
 
Example 5
Source File: P_BleDevice_Listeners.java    From AsteroidOSSync with GNU General Public License v3.0 6 votes vote down vote up
private void onCharacteristicRead_updateThread(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int gattStatus, final byte[] value)
{
    final UUID uuid = characteristic.getUuid();
    logger().i(logger().charName(uuid));
    logger().log_status(gattStatus);

    final P_Task_Read readTask = m_queue.getCurrent(P_Task_Read.class, m_device);

    if (readTask != null && readTask.isFor(characteristic))
    {
        readTask.onCharacteristicRead(gatt, characteristic.getUuid(), value, gattStatus);
    }
    else
    {
        final P_Task_BatteryLevel batteryTask = m_queue.getCurrent(P_Task_BatteryLevel.class, m_device);
        if (batteryTask != null)
        {
            batteryTask.onCharacteristicRead(gatt, characteristic.getUuid(), value, gattStatus);
        }
        else
        {
            fireUnsolicitedEvent(new BleCharacteristicWrapper(characteristic), BleDescriptorWrapper.NULL, BleDevice.ReadWriteListener.Type.READ, BleDevice.ReadWriteListener.Target.CHARACTERISTIC, value, gattStatus);
        }
    }
}
 
Example 6
Source File: HealthThermometerServiceFragment.java    From ble-test-peripheral-android with Apache License 2.0 6 votes vote down vote up
@Override
public void notificationsEnabled(BluetoothGattCharacteristic characteristic, boolean indicate) {
  if (characteristic.getUuid() != TEMPERATURE_MEASUREMENT_UUID) {
    return;
  }
  if (!indicate) {
    return;
  }
  getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
      int newMeasurementInterval = Integer.parseInt(mEditTextMeasurementInterval.getText()
          .toString());
      if (isValidMeasurementIntervalValue(newMeasurementInterval)) {
        mMeasurementIntervalCharacteristic.setValue(newMeasurementInterval,
            MEASUREMENT_INTERVAL_FORMAT,
          /* offset */ 0);
        resetTimer(newMeasurementInterval);
        mTextViewNotifications.setText(R.string.notificationsEnabled);
      }
    }
  });
}
 
Example 7
Source File: ThrowingIllegalOperationHandler.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
/**
 * This method logs an error and returns a {@link BleIllegalOperationException}.
 * @param characteristic the characteristic upon which the operation was requested
 * @param neededProperties bitmask of properties needed by the operation
 */
@Override
public BleIllegalOperationException handleMismatchData(BluetoothGattCharacteristic characteristic, int neededProperties) {
    String message = messageCreator.createMismatchMessage(characteristic, neededProperties);
    return new BleIllegalOperationException(message,
            characteristic.getUuid(),
            characteristic.getProperties(),
            neededProperties);
}
 
Example 8
Source File: BtBand.java    From sony-smartband-open-api with MIT License 5 votes vote down vote up
public void onDescriptorWrite( BluetoothGattCharacteristic characteristic, BluetoothGattDescriptor descriptor ) {
    BluetoothGattService service = characteristic.getService();
    BaseProfile serviceProfile = Profiles.getService( service.getUuid() );

    Log.d( CLASS, "onDescriptorWrite: " + getDescriptorInfo( descriptor ) );

    UUID uuid = characteristic.getUuid();

    if( serviceProfile.getClass().equals( AHServiceProfile.class ) ) {
        if( uuid.equals( AHServiceProfile.DATA_UUID ) ) {
            mDataNotificationsEnabled = !mDataNotificationsEnabled;
        } else if( uuid.equals( AHServiceProfile.DEBUG_UUID ) ) {
            mDebugNotificationsEnabled = !mDebugNotificationsEnabled;
        } else if( uuid.equals( AHServiceProfile.EVENT_UUID ) ) {
            mEventNotificationsEnabled = !mEventNotificationsEnabled;
        } else if( uuid.equals( AHServiceProfile.ACCEL_DATA_UUID ) ) {
            mAccNotificationsEnabled = !mAccNotificationsEnabled ;
        } else {
            Log.w( CLASS, "onCharacteristicChanged: unhandled event. uuid=" + uuid
                    + " class=" + serviceProfile.getClass() );
        }
    } else {
        Log.w( CLASS, "onCharacteristicChanged: unhandled event. class=" + serviceProfile.getClass() );
    }

    processQueue();
}
 
Example 9
Source File: ShareTest.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    Log.i(TAG, "Characteristic changed");
    UUID charUuid = characteristic.getUuid();
    Log.i(TAG, "Characteristic Update Received: " + charUuid);
    if(charUuid.compareTo(mResponseCharacteristic.getUuid()) == 0) {
        Log.i(TAG, "mResponseCharacteristic Update");
    }
    if(charUuid.compareTo(mCommandCharacteristic.getUuid()) == 0) {
        Log.i(TAG, "mCommandCharacteristic Update");
    }
    if(charUuid.compareTo(mHeartBeatCharacteristic.getUuid()) == 0) {
        Log.i(TAG, "mHeartBeatCharacteristic Update");
    }
    if(charUuid.compareTo(mReceiveDataCharacteristic.getUuid()) == 0) {
        Log.i(TAG, "mReceiveDataCharacteristic Update");
        byte[] value = characteristic.getValue();
        if(value != null) {
            Log.i(TAG, "Characteristic: " + value);
            Log.i(TAG, "Characteristic: " + value.toString());
            Log.i(TAG, "Characteristic getstring: " + characteristic.getStringValue(0));
            Log.i(TAG, "SUBSCRIBED TO RESPONSE LISTENER");
            Observable.just(characteristic.getValue()).subscribe(mDataResponseListener);
        } else {
            Log.w(TAG, "Characteristic was null");
        }
    }
    Log.i(TAG, "NEW VALUE: " + characteristic.getValue().toString());
}
 
Example 10
Source File: BatteryServiceFragment.java    From ble-test-peripheral-android with Apache License 2.0 5 votes vote down vote up
@Override
public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
  if (characteristic.getUuid() != BATTERY_LEVEL_UUID) {
    return;
  }
  getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
      Toast.makeText(getActivity(), R.string.notificationsNotEnabled, Toast.LENGTH_SHORT)
          .show();
    }
  });
}
 
Example 11
Source File: BTConnectionManager.java    From Mi-Band with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
    super.onCharacteristicChanged(gatt, characteristic);
    if (io.notifyListeners.containsKey(characteristic.getUuid())) {
        io.notifyListeners.get(characteristic.getUuid()).onNotify(characteristic.getValue());
    }

    UUID characteristicUUID = characteristic.getUuid();
    if (Profile.UUID_CHAR_ACTIVITY_DATA.equals(characteristicUUID)) {
        io.handleActivityNotif(characteristic.getValue());
    }

    toggleNotifications(false);
}
 
Example 12
Source File: LoggerUtil.java    From RxAndroidBle with Apache License 2.0 5 votes vote down vote up
public static void logCallback(String callbackName, BluetoothGatt gatt, int status, BluetoothGattCharacteristic characteristic,
                               boolean valueMatters) {
    if (!RxBleLog.isAtLeast(LogConstants.INFO)) {
        return;
    }
    AttributeLogWrapper value = new AttributeLogWrapper(characteristic.getUuid(), characteristic.getValue(), valueMatters);
    RxBleLog.i(commonMacMessage(gatt) + commonCallbackMessage() + commonStatusMessage() + commonValueMessage(),
            callbackName, status, value);
}
 
Example 13
Source File: GattServerCallback.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
private boolean checkCharacteristicAndCharacteristicService(GattServerConnection conn, BluetoothDevice device, @Nullable BluetoothGattCharacteristic characteristic, int requestId, int offset) {
    BluetoothGattServer server = conn.getServer();
    if (characteristic == null) {
        Timber.w("[%s] The characteristic wasn't attached to the descriptor! Returning error", device);
        returnErrorToRemoteClient(conn, device, requestId, offset);
        return true;
    }
    UUID charUuid = characteristic.getUuid();
    BluetoothGattService referencedService = characteristic.getService();
    if (referencedService == null) {
        Timber.w("[%s] The expected service wasn't attached to the characteristic! Returning error", device);
        returnErrorToRemoteClient(conn, device, requestId, offset);
        return true;
    }
    if (server.getService(referencedService.getUuid()) == null) {
        Timber.w("[%s] The expected service wasn't hosted! Returning error", device);
        returnErrorToRemoteClient(conn, device, requestId, offset);
        return true;
    }
    BluetoothGattService hostedService = server.getService(referencedService.getUuid());
    if (hostedService.getCharacteristic(charUuid) == null) {
        Timber.w("[%s] The expected characteristic wasn't hosted! Returning error", device);
        returnErrorToRemoteClient(conn, device, requestId, offset);
        return true;
    }
    return false;
}
 
Example 14
Source File: HealthThermometerServiceFragment.java    From ble-test-peripheral-android with Apache License 2.0 5 votes vote down vote up
@Override
public void notificationsDisabled(BluetoothGattCharacteristic characteristic) {
  if (characteristic.getUuid() != TEMPERATURE_MEASUREMENT_UUID) {
    return;
  }
  cancelTimer();
  getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
      mTextViewNotifications.setText(R.string.notificationsNotEnabled);
    }
  });
}
 
Example 15
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 16
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 17
Source File: BleCannotSetCharacteristicNotificationException.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
private static String createMessage(BluetoothGattCharacteristic bluetoothGattCharacteristic, @Reason int reason) {
    return reasonDescription(reason) + " (code "
            + reason + ") with characteristic UUID " + bluetoothGattCharacteristic.getUuid();
}
 
Example 18
Source File: CommandResult.java    From neatle with MIT License 4 votes vote down vote up
@RestrictTo(RestrictTo.Scope.LIBRARY)
public static CommandResult createCharacteristicChanged(BluetoothGattCharacteristic characteristic) {
    long when = System.currentTimeMillis();
    return new CommandResult(characteristic.getUuid(), characteristic.getValue(), BluetoothGatt.GATT_SUCCESS, when);
}
 
Example 19
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();
    }
 
Example 20
Source File: BtBand.java    From sony-smartband-open-api with MIT License 4 votes vote down vote up
private void handleBatteryCallback( BluetoothGattCharacteristic characteristic ) {
    UUID uuid = characteristic.getUuid();
    if( uuid .equals( BatteryProfile.BATTERY_LEVEL_UUID ) ) {
        handleBatteryReadLevel( characteristic );
    }
}