2

我一直在实现模块以块的形式发送字节,每个 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{

……

4

1 回答 1

0

您需要等待onCharacteristicWrite()回调被调用,然后再发送下一次写入。典型的解决方案是创建一个作业队列,并为您获得的每个回调从队列中弹出一个作业onCharacteristicWrite()onCharacteristicRead()等等。

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

于 2014-11-13T19:41:21.913 回答