2014-11-05 59 views
2

我一直在實現模塊,通過BLE將每個字節以20個字節發送到MCU設備。當寫入超過60個字節的字節等時,最後一個字節塊(通常小於20個字節)通常會被忽略。因此,MCU設備無法獲取校驗和並寫入數值。我已經修改回調到Thread.sleep(200)來改變它,但它有時寫61字節或有時不工作。你能告訴我有沒有任何同步方法來寫入塊的字節?以下是我的工作:Android BLE:寫入> 20字節缺少最後一個字節數組的特徵

@Override 
    public void onCharacteristicWrite(BluetoothGatt gatt, 
      BluetoothGattCharacteristic characteristic, int status) { 

     try { 
      Thread.sleep(300); 
      if (status != BluetoothGatt.GATT_SUCCESS) { 
       disconnect(); 
       return; 
      } 

      if(status == BluetoothGatt.GATT_SUCCESS) { 
       System.out.println("ok"); 
       broadcastUpdate(ACTION_DATA_READ, mReadCharacteristic, status); 
      } 
      else { 
       System.out.println("fail"); 
       broadcastUpdate(ACTION_DATA_WRITE, characteristic, status); 
      } 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 



public synchronized boolean writeCharacteristicData(BluetoothGattCharacteristic characteristic , 
     byte [] byteResult) { 
    if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
     return false; 
    } 
    boolean status = false; 
    characteristic.setValue(byteResult); 
    characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); 

    status = mBluetoothGatt.writeCharacteristic(characteristic); 
    return status; 

} 

private void sendCommandData(final byte [] commandByte) { 
     // TODO Auto-generated method stub 

    if(commandByte.length > 20){ 
     final List<byte[]> bytestobeSent = splitInChunks(commandByte); 
     for(int i = 0 ; i < bytestobeSent.size() ; i ++){ 
      for(int k = 0 ; k < bytestobeSent.get(i).length ; k++){ 
       System.out.println("LumChar bytes : "+ bytestobeSent.get(i)[k]); 
      } 

      BluetoothGattService LumService = mBluetoothGatt.getService(A_SERVICE); 
      if (LumService == null) { return; } 
      BluetoothGattCharacteristic LumChar = LumService.getCharacteristic(AW_CHARACTERISTIC); 
      if (LumChar == null) { System.out.println("LumChar"); return; } 
      //Thread.sleep(500); 
      writeCharacteristicData(LumChar , bytestobeSent.get(i)); 
     } 
    }else{ 

....

回答

0

你需要等待onCharacteristicWrite()回調發送下一寫入之前被調用。典型的解決方案是做一個工作隊列,併爲每個回調獲得onCharacteristicWrite(),onCharacteristicRead()

排隊等待,換句話說,你不能在for循環中這樣做,除非你想要在進行下一次迭代之前設置某種等待回調的鎖。根據我的經驗,工作隊列是一個更清潔的通用解決方案。

+0

我已經爲不同類型的命令設置了線程睡眠但沒有任何工作。 – 2014-11-14 02:15:38

+0

由於寫入時間有多變,特別是在長距離等惡劣條件下,我不會因爲Thread.sleep()而搞亂。你有沒有試過我建議的?在執行下一次寫入之前等待先前的寫入完成? – 2014-11-14 14:42:17

+0

這意味着使用相同的全局writeCharacteristics可能會覆蓋要發送的字節,所以我們必須將寫入部分實現爲隊列?如何使用BLocking隊列實現同步寫入特性? http://stackoverflow.com/questions/21791948/android-ble-gatt-characteristic-write-type-no-response-not-working – 2014-11-17 03:43:50

相關問題