Java Code Examples for android.bluetooth.BluetoothGatt#setCharacteristicNotification()

The following examples show how to use android.bluetooth.BluetoothGatt#setCharacteristicNotification() . 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: 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 3
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 4
Source File: BLEUtils.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
/**
 * Set a Notification Setting for The Matching Characteristic of a Service
 *
 * @param gatt               The Bluetooth GATT
 * @param gattService        the service we must find and match
 * @param gattCharacteristic the characteristic we must find and match
 * @param gattDescriptor     the descriptor we must write to we must find and match
 * @param value              The exact setting we are setting
 * @return Whether the instruction to write passed or failed.
 */
public static boolean SetNotificationForCharacteristic(BluetoothGatt gatt, GattService gattService, GattCharacteristic gattCharacteristic, UUID gattDescriptor, Notifications value) {
    boolean written = false;
    List<BluetoothGattService> services = gatt.getServices();
    for (BluetoothGattService service : services) {
        BluetoothGattCharacteristic characteristic = BLEUtils.getCharacteristic(service, gattService, gattCharacteristic);
        if (characteristic != null) {
            gatt.setCharacteristicNotification(characteristic, value.isEnabled());
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(gattDescriptor);
            if (descriptor != null) {
                //writing this descriptor causes the device to send updates
                descriptor.setValue(value.getDescriptorValue());
                written = gatt.writeDescriptor(descriptor);
            }
            return written;
        }
    }

    return false;
}
 
Example 5
Source File: BluetoothLEGatt.java    From EFRConnect-android with Apache License 2.0 6 votes vote down vote up
void addCharacteristics(BluetoothGatt gatt, List<BluetoothGattCharacteristic> gattCharacteristics) {
    // Loops through available Characteristics.
    for (BluetoothGattCharacteristic characteristic : gattCharacteristics) {
        if (BuildConfig.DEBUG) {
            String characteristicName = getCharacteristicName(characteristic.getUuid());
            Timber.d("    char: " + characteristicName);
            //Log.d("addCharacteristics"," char: " + characteristicName);
        }

        final int characteristicID = getIdentification(characteristic.getUuid());
        this.gattCharacteristics.put(characteristicID, characteristic);
        this.values.put(characteristicID, null);

        int properties = characteristic.getProperties();
        if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
            gatt.setCharacteristicNotification(characteristic, true);
        }
    }
}
 
Example 6
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean internalEnableNotifications(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

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

		descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
		log(Log.VERBOSE, "Enabling notifications for " + characteristic.getUuid());
		log(Log.DEBUG, "gatt.writeDescriptor(" +
				BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x01-00)");
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
Example 7
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean internalEnableIndications(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

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

		descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
		log(Log.VERBOSE, "Enabling indications for " + characteristic.getUuid());
		log(Log.DEBUG, "gatt.writeDescriptor(" +
				BleManager.CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID + ", value=0x02-00)");
		return internalWriteDescriptorWorkaround(descriptor);
	}
	return false;
}
 
Example 8
Source File: G5CollectionService.java    From xDrip-plus with GNU General Public License v3.0 5 votes vote down vote up
private synchronized void doDisconnectMessage(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
       Log.d(TAG, "doDisconnectMessage() start");
       gatt.setCharacteristicNotification(controlCharacteristic, false);
       final DisconnectTxMessage disconnectTx = new DisconnectTxMessage();
       characteristic.setValue(disconnectTx.byteSequence);
       gatt.writeCharacteristic(characteristic);
       gatt.disconnect();
       Log.d(TAG, "doDisconnectMessage() finished");
}
 
Example 9
Source File: SerialSocket.java    From SimpleBluetoothLeTerminal with MIT License 5 votes vote down vote up
private void connectCharacteristics3(BluetoothGatt gatt) {
    int writeProperties = writeCharacteristic.getProperties();
    if((writeProperties & (BluetoothGattCharacteristic.PROPERTY_WRITE +     // Microbit,HM10-clone have WRITE
            BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE)) ==0) { // HM10,TI uart,Telit have only WRITE_NO_RESPONSE
        onSerialConnectError(new IOException("write characteristic not writable"));
        return;
    }
    if(!gatt.setCharacteristicNotification(readCharacteristic,true)) {
        onSerialConnectError(new IOException("no notification for read characteristic"));
        return;
    }
    BluetoothGattDescriptor readDescriptor = readCharacteristic.getDescriptor(BLUETOOTH_LE_CCCD);
    if(readDescriptor == null) {
        onSerialConnectError(new IOException("no CCCD descriptor for read characteristic"));
        return;
    }
    int readProperties = readCharacteristic.getProperties();
    if((readProperties & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
        Log.d(TAG, "enable read indication");
        readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
    }else if((readProperties & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
        Log.d(TAG, "enable read notification");
        readDescriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        onSerialConnectError(new IOException("no indication/notification for read characteristic ("+readProperties+")"));
        return;
    }
    Log.d(TAG,"writing read characteristic descriptor");
    if(!gatt.writeDescriptor(readDescriptor)) {
        onSerialConnectError(new IOException("read characteristic CCCD descriptor not writable"));
    }
    // continues asynchronously in onDescriptorWrite()
}
 
Example 10
Source File: GattSetNotificationOperation.java    From puck-central-android with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(BluetoothGatt gatt) {
    BluetoothGattCharacteristic characteristic = gatt.getService(mServiceUuid).getCharacteristic(mCharacteristicUuid);
    boolean enable = true;
    gatt.setCharacteristicNotification(characteristic, enable);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(mDescriptorUuid);
    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    gatt.writeDescriptor(descriptor);
}
 
Example 11
Source File: BleUtils.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
public static boolean setCharacteristicNotification(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, boolean enable) {
    if (gatt == null) {
        return false;
    }
    BluetoothGattService service = gatt.getService(serviceUuid);
    if (service == null) {
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    if (characteristic == null) {
        Timber.d("could not get characteristic: %s for service: %s", characteristicUuid.toString(), serviceUuid.toString());
        return false;
    }

    if (!gatt.setCharacteristicNotification(characteristic, true)) {
        Timber.d("was not able to setCharacteristicNotification");
        return false;
    }

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
    if (descriptor == null) {
        Timber.d("was not able to getDescriptor");
        return false;
    }

    if (enable) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    }
    return gatt.writeDescriptor(descriptor);
}
 
Example 12
Source File: Ble.java    From JayPS-AndroidApp 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.
     */
    private void setCharacteristicNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
                                              boolean enabled) {
        Log.d(TAG, display(gatt) + " setCharacteristicNotification " + display(characteristic));
        if (mBluetoothAdapter == null || gatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        //if (debug) Log.w(TAG, "setCharacteristicNotification");
        gatt.setCharacteristicNotification(characteristic, enabled);
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        // This is specific to Heart Rate Measurement.
        /*if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())
            || UUID_CSC_MEASUREMENT.equals(characteristic.getUuid())
            || UUID_RSC_MEASUREMENT.equals(characteristic.getUuid())
        ) {*/
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(BLESampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            writeGattDescriptor(gatt, descriptor);
        /*} else {
            if (debug) Log.i(TAG, "unused characteristics2:" + display(gatt, characteristic));
        }*/
    }
 
Example 13
Source File: BleUtils.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
public static boolean unsetCharacteristicNotification(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid, UUID descriptorUuid, boolean enable) {
    if (gatt == null) {
        return false;
    }
    BluetoothGattService service = gatt.getService(serviceUuid);
    if (service == null) {
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);

    if (characteristic == null) {
        Timber.d("could not get characteristic: %s for service: %s", characteristicUuid.toString(), serviceUuid.toString());
        return false;
    }

    if (!gatt.setCharacteristicNotification(characteristic, false)) {
        Timber.d("was not able to setCharacteristicNotification");
        return false;
    }

    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUuid);
    if (descriptor == null) {
        Timber.d("was not able to getDescriptor");
        return false;
    }

    if (enable) {
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    } else {
        descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
    }

    return gatt.writeDescriptor(descriptor);
}
 
Example 14
Source File: BLEUtils.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
public static boolean SetNotificationForCharacteristic(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, UUID gattDescriptor, Notifications value) {
    boolean written = false;
    if (characteristic != null) {
        gatt.setCharacteristicNotification(characteristic, value.isEnabled());
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(gattDescriptor);
        if (descriptor != null) {
            //writing this descriptor causes the device to send updates
            descriptor.setValue(value.getDescriptorValue());
            written = gatt.writeDescriptor(descriptor);
        }
        return written;
    }

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

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

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

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

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

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

    if (mAborted)
        throw new UploadAbortedException();

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

    if (mConnectionState != STATE_CONNECTED_AND_READY)
        throw new DeviceDisconnectedException("Unable to set " + debugString + " state", mConnectionState);
}
 
Example 16
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 17
Source File: BluetoothUtilImpl.java    From android-ponewheel with MIT License 4 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic c, int status) {
    String characteristic_uuid = c.getUuid().toString();
    Timber.d( "BluetoothGattCallback.onCharacteristicRead: CharacteristicUuid=" +
            characteristic_uuid +
            ",status=" + status +
            ",isGemini=" + isGemini);
    if (characteristicReadQueue.size() > 0) {
        characteristicReadQueue.remove();
    }

    // Stability Step 2: In OnCharacteristicRead, if the value is of the char firmware version, parse it's value.
    // If its >= 4034, JUST write the descriptor for the Serial Read characteristic to Enable notifications,
    // and set notify to true with gatt. Otherwise its Andromeda or lower and we can call the method to
    // read & notify all the characteristics we want. (Although I learned doing this that some android devices
    // have a max of 12 notify characteristics at once for some reason. At least I'm pretty sure.)
    // I also set a class-wide boolean value isGemini to true here so I don't have to keep checking if its Andromeda
    // or Gemini later on.
    if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicFirmwareRevision)) {
        Timber.d("We have the firmware revision! Checking version.");
        if (unsignedShort(c.getValue()) >= 4034) {
            Timber.d("It's Gemini!");
            isGemini = true;
            Timber.d("Stability Step 2.1: JUST write the descriptor for the Serial Read characteristic to Enable notifications");
            BluetoothGattCharacteristic gC = owGatService.getCharacteristic(UUID.fromString(OWDevice.OnewheelCharacteristicUartSerialRead));
            gatt.setCharacteristicNotification(gC, true);
            Timber.d("and set notify to true with gatt...");
            BluetoothGattDescriptor descriptor = gC.getDescriptor(UUID.fromString(OWDevice.OnewheelConfigUUID));
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        } else {
            Timber.d("It's before Gemini, likely Andromeda - calling read and notify characteristics");
            isGemini = false;
            whenActuallyConnected();
        }
    } else if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicRidingMode)) {
         Timber.d( "Got ride mode from the main UI thread:" + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1));
    }

    //else if (characteristic_uuid.equals(OWDevice.OnewheelCharacteristicUartSerialRead)) {
    //    Timber.d("Got OnewheelCharacteristicUartSerialRead, calling unlockKeyGemini! ");
     //   unlockKeyGemini(gatt, c.getValue());
   // }



    if (BuildConfig.DEBUG) {
        byte[] v_bytes = c.getValue();
        StringBuilder sb = new StringBuilder();
        for (byte b : c.getValue()) {
            sb.append(String.format("%02x", b));
        }
        Timber.d( "HEX %02x: " + sb);
        Timber.d( "Arrays.toString() value: " + Arrays.toString(v_bytes));
        Timber.d( "String value: " + c.getStringValue(0));
        Timber.d( "Unsigned short: " + unsignedShort(v_bytes));
        Timber.d( "getIntValue(FORMAT_UINT8,0) " + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0));
        Timber.d( "getIntValue(FORMAT_UINT8,1) " + c.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1));
    }

    mOWDevice.processUUID(c);

    mOWDevice.setBatteryRemaining(mainActivity);

    // Callback to make sure the queue is drained

    if (characteristicReadQueue.size() > 0) {
        gatt.readCharacteristic(characteristicReadQueue.element());
    }

}
 
Example 18
Source File: BleConnector.java    From FastBle with Apache License 2.0 4 votes vote down vote up
/**
 * notify setting
 */
private boolean setCharacteristicNotification(BluetoothGatt gatt,
                                              BluetoothGattCharacteristic characteristic,
                                              boolean useCharacteristicDescriptor,
                                              boolean enable,
                                              BleNotifyCallback bleNotifyCallback) {
    if (gatt == null || characteristic == null) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(new OtherException("gatt or characteristic equal null"));
        return false;
    }

    boolean success1 = gatt.setCharacteristicNotification(characteristic, enable);
    if (!success1) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(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) {
        notifyMsgInit();
        if (bleNotifyCallback != null)
            bleNotifyCallback.onNotifyFailure(new OtherException("descriptor equals null"));
        return false;
    } else {
        descriptor.setValue(enable ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE :
                BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
        boolean success2 = gatt.writeDescriptor(descriptor);
        if (!success2) {
            notifyMsgInit();
            if (bleNotifyCallback != null)
                bleNotifyCallback.onNotifyFailure(new OtherException("gatt writeDescriptor fail"));
        }
        return success2;
    }
}
 
Example 19
Source File: CorePeripheral.java    From RxCentralBle with Apache License 2.0 4 votes vote down vote up
@Nullable
private PeripheralError setCharacteristicNotification(
    BluetoothGatt bluetoothGatt, BluetoothGattCharacteristic characteristic, boolean enable) {

  BluetoothGattDescriptor cccd = characteristic.getDescriptor(CCCD_UUID);
  if (cccd == null) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_CCCD_MISSING);
  }

  if (!bluetoothGatt.setCharacteristicNotification(characteristic, enable)) {
    return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_FAILED);
  }

  int properties = characteristic.getProperties();
  byte[] value;

  if (enable) {
    if ((properties & BluetoothGattCharacteristic.PROPERTY_NOTIFY)
        == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
      value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
    } else if ((properties & BluetoothGattCharacteristic.PROPERTY_INDICATE)
        == BluetoothGattCharacteristic.PROPERTY_INDICATE) {
      value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
    } else {
      return new PeripheralError(PeripheralError.Code.SET_CHARACTERISTIC_NOTIFICATION_MISSING_PROPERTY);
    }
  } else {
    value = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
  }

  characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

  if (!cccd.setValue(value)) {
    return new PeripheralError(CHARACTERISTIC_SET_VALUE_FAILED);
  }

  if (!bluetoothGatt.writeDescriptor(cccd)) {
    return new PeripheralError(PeripheralError.Code.WRITE_DESCRIPTOR_FAILED, ERROR_STATUS_CALL_FAILED);
  }

  return null;
}
 
Example 20
Source File: NukiCallback.java    From trigger with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    if (status == GATT_SUCCESS) {
        BluetoothGattService service = gatt.getService(this.service_uuid);
        if (service == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Service not found: " + this.service_uuid
            );
            return;
        }

        BluetoothGattCharacteristic characteristic = service.getCharacteristic(this.characteristic_uuid);
        if (characteristic == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Characteristic not found: " + this.characteristic_uuid
            );
            return;
        }

        gatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CCC_DESCRIPTOR_UUID);
        if (descriptor == null) {
            closeConnection(gatt);
            this.listener.onTaskResult(
                setup_id, ReplyCode.REMOTE_ERROR, "Descriptor not found: " + CCC_DESCRIPTOR_UUID
            );
            return;
        }
       
        //Log.i(TAG, "characteristic properties: " + NukiTools.getProperties(characteristic));
        descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
        boolean ok = gatt.writeDescriptor(descriptor);
        if (!ok) {
            Log.e(TAG, "descriptor write failed");
            closeConnection(gatt);
        }
    } else {
        closeConnection(gatt);
        this.listener.onTaskResult(
            setup_id, ReplyCode.LOCAL_ERROR, "Client not found: " + NukiRequestHandler.getGattStatus(status)
        );
    }
}