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

The following examples show how to use android.bluetooth.BluetoothGatt#readCharacteristic() . 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: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    Log.d(TAG, "characteristic wrote " + status);
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.d(TAG, "Wrote a characteristic successfully " + characteristic.getUuid());
        if (mAuthenticationCharacteristic.getUuid().equals(characteristic.getUuid())) {
            state_authSucess = true;
            gatt.readCharacteristic(mHeartBeatCharacteristic);
        }
    } else if ((status & BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) != 0 || (status & BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION) != 0) {
        if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
            device = gatt.getDevice();
            state_authInProgress = true;
            bondDevice();
        } else {
            Log.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug? Have the dexcom forget whatever device it was previously paired to: oncharacteristicwrite code: "+status+ "bond: "+gatt.getDevice().getBondState());
        }
    } else {
        Log.e(TAG, "Unknown error writing Characteristic");
    }
}
 
Example 2
Source File: UpdateService.java    From Android-nRF-Beacon-for-Eddystone with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void start(BluetoothGatt bluetoothGatt) {
    switch (requestType) {
        case READ_CHARACTERISTIC:
            if (!bluetoothGatt.readCharacteristic(characteristic)) {
                throw new IllegalArgumentException("Characteristic is not valid: " + characteristic.getUuid().toString());
            }
            break;
        case READ_DESCRIPTOR:
            if (!bluetoothGatt.readDescriptor(descriptor)) {
                throw new IllegalArgumentException("Descriptor is not valid");
            }
            break;
        case WRITE_CHARACTERISTIC:
            if (!bluetoothGatt.writeCharacteristic(characteristic)) {
                throw new IllegalArgumentException("Characteristic is not valid");
            }
            break;
        case WRITE_DESCRIPTOR:
            if (!bluetoothGatt.writeDescriptor(descriptor)) {
                throw new IllegalArgumentException("Characteristic is not valid");
            }
            break;
    }
}
 
Example 3
Source File: BluetoothSite.java    From physical-web with Apache License 2.0 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
    int status) {
  // Make sure the site is running.  It can stop if the dialog is dismissed very quickly.
  if (!isRunning()) {
    close();
    return;
  }

  // Make sure the read was successful.
  if (status != BluetoothGatt.GATT_SUCCESS) {
    Log.i(TAG, "onCharacteristicRead unsuccessful: " + status);
    close();
    Toast.makeText(activity, R.string.ble_download_error_message, Toast.LENGTH_SHORT).show();
    return;
  }

  // Record the data.
  Log.i(TAG, "onCharacteristicRead successful");
  try {
    mHtml.write(characteristic.getValue());
  } catch (IOException e) {
    Log.e(TAG, "Could not write to buffer", e);
    close();
    return;
  }

  // Request a new read if we are not done.
  if (characteristic.getValue().length == transferRate) {
    gatt.readCharacteristic(this.characteristic);
    return;
  }

  // At this point we are done.  Show the file.
  Log.i(TAG, "transfer is complete");
  close();
  openInChrome(getHtmlFile());
}
 
Example 4
Source File: CharacteristicReadOperation.java    From tap-android-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public void onExecute(@NonNull BluetoothGatt gatt) {
    BluetoothGattCharacteristic c = extractCharacteristic(gatt);
    if (c == null) {
        postOnNotFound(ErrorStrings.NO_CHARACTERISTIC + ": " + this.characteristic.toString());
        return;
    }

    if (!gatt.readCharacteristic(c)) {
        postOnError(ErrorStrings.WRITE_OP_INIT_FAIL);
    }
}
 
Example 5
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.v(TAG, "Characteristic Read " + characteristic.getUuid());
        if(mHeartBeatCharacteristic.getUuid().equals(characteristic.getUuid())) {
            Log.v(TAG, "Characteristic Read " + characteristic.getUuid() + " " + characteristic.getValue());
            setCharacteristicNotification(mHeartBeatCharacteristic);
        }
        gatt.readCharacteristic(mHeartBeatCharacteristic);
    } else {
        Log.e(TAG, "Characteristic failed to read");
    }
}
 
Example 6
Source File: BluetoothUtilImpl.java    From android-ponewheel with MIT License 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    Timber.i( "onDescriptorWrite: " + status + ",descriptor=" + descriptor.getUuid().toString() +
            ",descriptor_characteristic=" + descriptor.getCharacteristic().getUuid().toString());

    if (isGemini && descriptor.getCharacteristic().getUuid().toString().equals(OWDevice.OnewheelCharacteristicUartSerialRead)) {
        Timber.d("Stability Step 3: if isGemini and the characteristic descriptor that was written was Serial Write" +
                "then trigger the 20 byte input key over multiple serial ble notification stream by writing the firmware version onto itself");
        gatt.writeCharacteristic(owGatService.getCharacteristic(UUID.fromString(OWDevice.OnewheelCharacteristicFirmwareRevision)));
    }

    //DeviceCharacteristic dc = mOWDevice.characteristics.get(descriptor.getCharacteristic().getUuid().toString());
    //if (dc != null && (dc.state == 0 || dc.state == 1)) {
    //    gatt.setCharacteristicNotification(  owGatService.getCharacteristic(UUID.fromString(dc.uuid.get())), true);
    //
    // }

    if (descriptorWriteQueue.size() > 0) {
        descriptorWriteQueue.remove();
        if (descriptorWriteQueue.size() > 0) {
            gatt.writeDescriptor(descriptorWriteQueue.element());
        } else if (characteristicReadQueue.size() > 0) {
            gatt.readCharacteristic(characteristicReadQueue.element());
        }
    }

    // Step 3: In OnDescriptorWrite, if isGemini and the characteristic descriptor that was
    // written was Serial Write, then trigger the byte stream by writing the firmware version
    // onto itself.
    /*
    if (isGemini && (descriptor.equals(OWDevice.OnewheelCharacteristicUartSerialWrite))) {
        Timber.d("Step 3: Is Gemini, writing the descriptor onto itself");
        gatt.writeDescriptor(descriptor);
    }
    */
}
 
Example 7
Source File: HealthThermometerActivity.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    boolean startNotificationForCharacteristicFromHere = true;
    List<BluetoothGattService> services = gatt.getServices();
    if (services != null) {
        for (BluetoothGattService s : services) {
            if (s.getCharacteristics() != null) {
                for (BluetoothGattCharacteristic ch : s.getCharacteristics()) {
                    if (GattCharacteristic.TemperatureType.uuid.equals(ch.getUuid())) {
                        startNotificationForCharacteristicFromHere = false;
                        gatt.readCharacteristic(ch);
                        break;
                    }

                }
            }
        }
    }

    if (startNotificationForCharacteristicFromHere) {
        BLEUtils.SetNotificationForCharacteristic(gatt, GattService.HealthThermometer,
                GattCharacteristic.Temperature,
                BLEUtils.Notifications.INDICATE);
    }

}
 
Example 8
Source File: BleManagerHandler.java    From Android-BLE-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean internalReadCharacteristic(@Nullable final BluetoothGattCharacteristic characteristic) {
	final BluetoothGatt gatt = bluetoothGatt;
	if (gatt == null || characteristic == null || !connected)
		return false;

	// Check characteristic property.
	final int properties = characteristic.getProperties();
	if ((properties & BluetoothGattCharacteristic.PROPERTY_READ) == 0)
		return false;

	log(Log.VERBOSE, "Reading characteristic " + characteristic.getUuid());
	log(Log.DEBUG, "gatt.readCharacteristic(" + characteristic.getUuid() + ")");
	return gatt.readCharacteristic(characteristic);
}
 
Example 9
Source File: GattClient.java    From blefun-androidthings with Apache License 2.0 5 votes vote down vote up
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
    if (DESCRIPTOR_CONFIG.equals(descriptor.getUuid())) {
        BluetoothGattCharacteristic characteristic = gatt.getService(SERVICE_UUID).getCharacteristic(CHARACTERISTIC_COUNTER_UUID);
        gatt.readCharacteristic(characteristic);
    }
}
 
Example 10
Source File: ReadAllCommand.java    From neatle with MIT License 5 votes vote down vote up
private void readNext(BluetoothGatt gatt) {
    BluetoothGattCharacteristic characteristic = queue.poll();
    if (characteristic == null) {
        finish(CommandResult.createEmptySuccess(null));
        return;
    }
    if (!gatt.readCharacteristic(characteristic)) {
        finish(CommandResult.createErrorResult(null, BluetoothGatt.GATT_FAILURE));
    }
}
 
Example 11
Source File: DexShareCollectionService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.v(TAG, "Characteristic Read " + characteristic.getUuid());
        if(mHeartBeatCharacteristic.getUuid().equals(characteristic.getUuid())) {
            Log.v(TAG, "Characteristic Read " + characteristic.getUuid() + " " + characteristic.getValue());
            setCharacteristicNotification(mHeartBeatCharacteristic);
        }
        gatt.readCharacteristic(mHeartBeatCharacteristic);
    } else {
        Log.e(TAG, "Characteristic failed to read");
    }
}
 
Example 12
Source File: BleUtils.java    From thunderboard-android with Apache License 2.0 5 votes vote down vote up
public static boolean readCharacteristic(BluetoothGatt gatt, UUID serviceUuid, UUID characteristicUuid) {
    if (gatt == null) {
        return false;
    }
    BluetoothGattService service = gatt.getService(serviceUuid);
    if (service == null) {
        return false;
    }
    BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUuid);
    if (characteristic == null) {
        return false;
    }
    return gatt.readCharacteristic(characteristic);
}
 
Example 13
Source File: AndroidBle.java    From GizwitsBLE with Apache License 2.0 5 votes vote down vote up
public boolean readCharacteristic(String address,
		BleGattCharacteristic characteristic) {
	BluetoothGatt gatt = mBluetoothGatts.get(address);
	if (gatt == null) {
		return false;
	}

	return gatt.readCharacteristic(characteristic.getGattCharacteristicA());
}
 
Example 14
Source File: DexShareCollectionService.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
    if (status == BluetoothGatt.GATT_SUCCESS) {
        Log.v(TAG, "Characteristic Read " + characteristic.getUuid());
        if(mHeartBeatCharacteristic.getUuid().equals(characteristic.getUuid())) {
            Log.v(TAG, "Characteristic Read " + characteristic.getUuid() + " " + characteristic.getValue());
            setCharacteristicNotification(mHeartBeatCharacteristic);
        }
        gatt.readCharacteristic(mHeartBeatCharacteristic);
    } else {
        Log.e(TAG, "Characteristic failed to read");
    }
}
 
Example 15
Source File: MyBleService.java    From science-journal with Apache License 2.0 5 votes vote down vote up
void readValue(String address, BluetoothGattCharacteristic theCharacteristic) {
  BluetoothGatt bluetoothGatt = addressToGattClient.get(address);
  if (bluetoothGatt == null) {
    Log.w(TAG, "No connection found for: " + address);
    sendGattBroadcast(address, BleEvents.READ_CHAR_FAIL, null);
    return;
  }
  bluetoothGatt.readCharacteristic(theCharacteristic);
}
 
Example 16
Source File: BluetoothLeUart.java    From Adafruit_Android_BLE_UART with MIT License 4 votes vote down vote up
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    super.onServicesDiscovered(gatt, status);
    // Notify connection failure if service discovery failed.
    if (status == BluetoothGatt.GATT_FAILURE) {
        connectFailure();
        return;
    }

    // Save reference to each UART characteristic.
    tx = gatt.getService(UART_UUID).getCharacteristic(TX_UUID);
    rx = gatt.getService(UART_UUID).getCharacteristic(RX_UUID);

    // Save reference to each DIS characteristic.
    disManuf = gatt.getService(DIS_UUID).getCharacteristic(DIS_MANUF_UUID);
    disModel = gatt.getService(DIS_UUID).getCharacteristic(DIS_MODEL_UUID);
    disHWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_HWREV_UUID);
    disSWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_SWREV_UUID);

    // Add device information characteristics to the read queue
    // These need to be queued because we have to wait for the response to the first
    // read request before a second one can be processed (which makes you wonder why they
    // implemented this with async logic to begin with???)
    readQueue.offer(disManuf);
    readQueue.offer(disModel);
    readQueue.offer(disHWRev);
    readQueue.offer(disSWRev);

    // Request a dummy read to get the device information queue going
    gatt.readCharacteristic(disManuf);

    // Setup notifications on RX characteristic changes (i.e. data received).
    // First call setCharacteristicNotification to enable notification.
    if (!gatt.setCharacteristicNotification(rx, true)) {
        // Stop if the characteristic notification setup failed.
        connectFailure();
        return;
    }
    // Next update the RX characteristic's client descriptor to enable notifications.
    BluetoothGattDescriptor desc = rx.getDescriptor(CLIENT_UUID);
    if (desc == null) {
        // Stop if the RX characteristic has no client descriptor.
        connectFailure();
        return;
    }
    desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
    if (!gatt.writeDescriptor(desc)) {
        // Stop if the client descriptor could not be written.
        connectFailure();
        return;
    }
    // Notify of connection completion.
    notifyOnConnected(this);
}
 
Example 17
Source File: CharacteristicReadOperation.java    From RxAndroidBle with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean startOperation(BluetoothGatt bluetoothGatt) {
    return bluetoothGatt.readCharacteristic(bluetoothGattCharacteristic);
}
 
Example 18
Source File: PBluetoothLEClientBak.java    From PHONK with GNU General Public License v3.0 4 votes vote down vote up
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
    MLog.d(TAG, "onServicesDiscovered " + gatt + " " + status);
    ReturnObject ret = new ReturnObject();

    if (status == BluetoothGatt.GATT_SUCCESS) {
        List<BluetoothGattService> services = gatt.getServices();
        PhonkNativeArray retServicesArray = new PhonkNativeArray(services.size());
        ret.put("services", retServicesArray);

        int countServices = 0;
        for (BluetoothGattService service : services) {
            MLog.d(TAG, "service " + service.getUuid() + " " + service.getType());

            ReturnObject retService = new ReturnObject();
            retService.put("uuid", service.getUuid());
            retService.put("type", service.getType());
            retServicesArray.addPE(countServices++, retService);

            List<BluetoothGattCharacteristic> gattCharacteristic = service.getCharacteristics();
            PhonkNativeArray retCharArray = new PhonkNativeArray(gattCharacteristic.size());
            retService.put("characteristics", retCharArray);

            int counterCharacteristics = 0;
            for (BluetoothGattCharacteristic characteristic : gattCharacteristic) {
                MLog.d(TAG, "Characteristics" + characteristic.getUuid() + " " + characteristic.getProperties() + " " + characteristic.getWriteType() + " " + characteristic.getValue());
                gatt.readCharacteristic(characteristic);

                ReturnObject retChar = new ReturnObject();
                retChar.put("uuid", characteristic.getUuid());
                retChar.put("writeType", characteristic.getWriteType());
                /*
                retChar.put("descriptors", characteristic.getDescriptors());
                */
                retCharArray.addPE(counterCharacteristics++, retChar);
            }

        }

        if (mCallbackServices != null) {
            mCallbackServices.event(ret);
        }
    } else {
        MLog.d(TAG, "onServicesDiscovered received: " + status);
    }
}
 
Example 19
Source File: SerialInterface_BLE.java    From PodEmu with GNU General Public License v3.0 4 votes vote down vote up
@Override
@TargetApi(21)
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status)
{
    PodEmuLog.debug("SIBLE: GATT onServiceDiscovered with status=" + status);
    super.onServicesDiscovered(gatt, status);
    boolean isSerialSupported = false;

    for (BluetoothGattService service : gatt.getServices())
    {
        PodEmuLog.debug("SIBLE: Service: " + service.getUuid());
        //if (Arrays.asList(BLE_UUIDS).contains(service.getUuid()))
        if(SERVICE_UUID.equals(service.getUuid()))
        {
            PodEmuLog.debug("SIBLE: BLE found serial device!");

            //gatt.readCharacteristic(service.getCharacteristic(CHARACTERISTIC_VERSION_UUID));
            //gatt.readCharacteristic(service.getCharacteristic(CHARACTERISTIC_DESC_UUID));
            //gatt.setCharacteristicNotification(service.getCharacteristic(CHARACTERISTIC_MESSAGE_UUID), true);
            //gatt.setCharacteristicNotification(service.getCharacteristic(CHARACTERISTIC_RFCOMM_TRANSFER_UUID), true);

            BluetoothGattCharacteristic bleGattCharacteristic = service.getCharacteristic(CHARACTERISTIC_SERIAL_UUID);

            if(bleGattCharacteristic != null)
            {
                isSerialSupported = true;
                gatt.readCharacteristic(service.getCharacteristic(CHARACTERISTIC_SERIAL_UUID));
                gatt.setCharacteristicNotification(bleGattCharacteristic, true);
            }
        }
    }

    if(isSerialSupported)
    {
        PodEmuLog.debug("SIBLE: BLE serial supported!");
    }
    else
    {
        PodEmuLog.debug("SIBLE: BLE serial NOT supported!");
    }
}
 
Example 20
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());
    }

}