How can read all characteristic's value of my BLE device?

后端 未结 3 1225
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-07 06:10

I\'m building an app with Android Studio that can read the value from a device BLE. This device, have 4 services. The fourth services have 3 characteristic. I want to read t

相关标签:
3条回答
  • 2021-01-07 06:33

    First store your read characteristics, and ghatt objects. and if you want to read a value from characteristic call this method:

    private fun readDataFromCharacteristic(ghatt: BluetoothGhatt? , characteristic:BluetoothGhattCharacteristic) {
            Log.d(TAG, " readDataFromCharacteristic")
            ghatt?.readCharacteristic(characteristic)
        }
    

    if you call readCharacteristic(characteristic) on ghatt , below method will give result

    override fun onCharacteristicRead(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) {}
    
    0 讨论(0)
  • 2021-01-07 06:46

    You can achive multiple reads with the following code: First create a List

    private int ReadQueueIndex;
    private List<BluetoothGattCharacteristic> ReadQueue;
    

    In onServicesDiscovered add characteristics in ReadQueue:

    ReadQueue = new ArrayList<>();
    ReadQueue.add(characteristicsList.get(2));        
    ReadQueue.add(characteristicsList.get(1));            
    ReadQueue.add(characteristicsList.get(0));
    ReadQueueIndex = 2;
    ReadCharacteristics(ReadQueueIndex);
    

    Create ReadCharacteristics method

    private void ReadCharacteristics(int index){
       bluetoothGatt.readCharacteristic(ReadQueue.get(index));
    }
    

    Then in your onCharacteristicRead callback:

    String value =  Arrays.toString(characteristic.getValue());
    if(characteristic.getUuid().equals(characteristicsList.get(0).getUuid())){
      Log.i("Characteristic 0:", value);
    } else if(characteristic.getUuid().equals(characteristicsList.get(1).getUuid())){
      Log.i("Characteristic 1:", value);
    } else if(characteristic.getUuid().equals(characteristicsList.get(2).getUuid())){
      Log.i("Characteristic 2:", value);
    }
    ReadQueue.remove(ReadQueue.get(ReadQueueIndex));
    if (ReadQueue.size() >= 0) {
        ReadQueueIndex--;
        if (ReadQueueIndex == -1) {
           Log.i("Read Queue: ", "Complete");
        }
        else {
           ReadCharacteristics(ReadQueueIndex);
        }
     }
    

    Hope its helpful.

    0 讨论(0)
  • 2021-01-07 06:48

    You should not read whole list of characteristics in onServicesDiscovered method, because ble device could havent a time to performs all requests from android client.

    I offer you:

    1. Keep all characteristics in onServicesDiscovered
    2. By turns try reading characteristics in onCharacteristicRead method (at first you read first characteristic, after characteristic has been read, try reading second characteristic and ... )
    0 讨论(0)
提交回复
热议问题