2014-11-05 63 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

相关问题