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

时间:2014-11-05 10:17:06

标签: bluetooth-lowenergy android-bluetooth characteristics

我一直在实现模块以块的形式发送字节,每个字节20个字节通过BLE发送到MCU设备。当写入超过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{

...

1 个答案:

答案 0 :(得分:0)

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

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