0

Я разрабатываю приложение BLE, основанное на примере проекта Gatt, предоставленном google: https://developer.android.com/samples/BluetoothLeGatt/index.html. Таким образом, я могу отправить запись данных в характеристику успешно. Теперь мне нужно знать, когда эта характеристика меняет свою ценность.Подпишитесь на описание и поймите на это значение.

DeviceActivity

private void displayGattServices(List<BluetoothGattService> gattServices) 
{ 
    // get services & characteristics 
    ................ 

final BluetoothGattCharacteristic characteristic = mGattCharacteristics.get(2).get(0); 
     final int charaProp = characteristic.getProperties(); 
     mWriteCharacteristic = characteristic; 
     mBluetoothLeService.setCharacteristicNotification(mWriteCharacteristic, true); 

    // write in the characteristic to send a reset command to BLE device 

    // Start the read method, that permit subscribe to the characteristic 
    BluetoothLeService.read(mWriteCharacteristic); 
    BluetoothLeService.set(mWriteCharacteristic,true); 
}; 

BluetoothLeService

public static void read(BluetoothGattCharacteristic characteristic) 
    { 
     if (mBluetoothAdapter == null || mBluetoothGatt == null) 
     { 
      Log.w("BluetoothAdapter not initialized"); 
      return; 
     }; 

     mBluetoothGatt.readCharacteristic(characteristic); 
    }; 

    public static void set(BluetoothGattCharacteristic characteristic, boolean enabled) 
    { 
     if(mBluetoothAdapter == null || mBluetoothGatt == null) 
     { 
      Log.w("BluetoothAdapter not initialized"); 
      return; 
     }; 

     mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); 

     UUID uuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); 
     BluetoothGattDescriptor descriptor = characteristic.getDescriptor(uuid); 
     descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); 
     mBluetoothGatt.writeDescriptor(descriptor); 
    }; 

Но я не знаю, как я могу поймать значение для чтения характеристика. На самом деле, я не знаю, подходит ли мой код к признаку или нет. Кто-нибудь может мне помочь? Как я могу проверить, действительно ли значение характерного изменения? И как я могу отобразить новое значение этого признака на экране? Правильно ли мой код, или мне нужно добавить, изменить или удалить что-то? Thaks заранее. I руководство по этому вопросу: Reading multiple characteristics from a BLE device synchronously (Recommended Method for Android)

ответ

0

Вам необходимо запустить цикл внутри этой функции - displayGattServices (Список gattServices) и получить целые службы и характеристики подключенной BLE устройства.

Для определения характеристики имя и свойства на основе значения UUID вы можете обратиться к BLE characteristics

После того, как вы определили, какие характеристики применимы для BLE устройства, добавьте его в очереди и чтение/набор их.

@ ваш DeviceActivity класса

List <BluetoothGattCharacteristic> bluetoothGattCharacteristic = new ArrayList<BluetoothGattCharacteristic>(); 
Queue<BluetoothGattCharacteristic> mWriteCharacteristic = new LinkedList<BluetoothGattCharacteristic>(); 

private void displayGattServices(List<BluetoothGattService> gattServices) 
{ 
    for(BluetoothGattService service : gattServices) 
    { 
     Log.i(TAG, "Service UUID = " + service.getUuid()); 

     bluetoothGattCharacteristic = service.getCharacteristics(); 

     for(BluetoothGattCharacteristic character: bluetoothGattCharacteristic) 
     { 
      Log.i(TAG, "Service Character UUID = " + character.getUuid());  

      // Add your **preferred characteristic** in a Queue 
      mWriteCharacteristic.add(character); 
     } 
    } 

    if(mWriteCharacteristic.size() > 0) 
    { 
     read_Characteristic(); 
    }; 
}; 

Добавьте ниже функции также в вашем DeviceActivity класса,

// make sure this method is called when there is more than one characteristic to read & set 
    private void read_Characteristic() 
    { 

     BluetoothLeService.read(mWriteCharacteristic.element()); 
     BluetoothLeService.set(mWriteCharacteristic.element(),true); 
     mWriteCharacteristic.remove(); 
    }; 

После установки их в методе Service, вы должны иметь вещания приемник в вашем DeviceActivity класс активности для обработки различных событий, запущенных вашим BluetoothLeService класс обслуживания.

private final BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() 
{ 
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     // TODO Auto-generated method stub 
     final String action = intent.getAction(); 

     if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) 
     { 
      // Connection with the BLE device successful     
      ................ 
      ................ 
     } 
     else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) 
     { 
      // BLE device is disconnected 
      ................ 
      ................ 
     } 
     else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) 
     { 
      displayGattServices(BluetoothLeService.getSupportedGattServices()); 
     } 
     else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) 
     { 
      Log.i(TAG, "Collecting data"); 

     ................ 
     ................ 

     // If there are more than one characteristic call this method again 
     if(mWriteCharacteristic.size() > 0) 
     { 
      read_Characteristic(); 
     }; 
     }; 
    }; 
}; 

Если дополнительно нужен пример кода, чтобы направлять вас через, вы можете обратиться к BLE sample code

Смежные вопросы