Android BLE:写入缺少最后一个字节数组的 >20 字节特征



我一直在实现模块,通过BLE将字节分块发送到MCU设备上,每个字节20个。当写入超过60个字节的字节时,等等,最后一块字节(通常小于20个字节)经常会丢失。因此,MCU设备无法获得校验和并写入值。我已经修改了对Thread.sleep(200)的调用来更改它,但它有时能写61个字节,有时不能。你能告诉我有没有同步的方法来把字节写成块吗?以下是我的工作:

    @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{

在发送下一次写入之前,您需要等待调用onCharacteristicWrite()回调。典型的解决方案是创建一个作业队列,并在每次回调onCharacteristicWrite()onCharacteristicRead()等时从队列中弹出一个作业。

换句话说,不幸的是,您不能在for循环中执行此操作,除非您想设置某种锁,在进行下一次迭代之前等待回调。根据我的经验,作业队列是一个更干净的通用解决方案。

最新更新