Search code examples
androidbluetooth-lowenergyandroid-blebluetooth-gatt

BLE writeCharacteristic issue


I'm trying to writeCharacteristic() to a BLE device.

I used Google example app to establish the connection, the connection is fine. I can see the BLE Services and the services Characteristics.

The writeCharacteristic() method return true and the onCharacteristicWrite() callback return status BluetoothGatt.GATT_SUCCESS but nothing happening with the device: I tried all the solutions in stack overflow and nothing helps. Here is my code:

In the BluetoothLeService class i have sendData() method, which gets a byte[] I'm sending each command separately because of the maximum payload of 33 bytes.

public void sendData(byte[] data) {

        String lService = "71387664-eb78-11e6-b006-92361f002671";
        String lCharacteristic = "71387663-eb78-11e6-b006-92361f002671";

        BluetoothGattService mBluetoothLeService = null;
        BluetoothGattCharacteristic mBluetoothGattCharacteristic = null;

        if (mBluetoothGattCharacteristic == null) {
            mBluetoothGattCharacteristic = mBluetoothGatt.getService(UUID.fromString(lService)).getCharacteristic(UUID.fromString(lCharacteristic));

        }

        mBluetoothGattCharacteristic.setValue(data);

        boolean write = mBluetoothGatt.writeCharacteristic(mBluetoothGattCharacteristic);
    }

Solution

  • I found the issue. Hope my answer will help others. The issue was that, I was sending byte[] array bigger than it's allow(20 byte). Also, I needed to add "\r" inside this byte[] array, thats way, the BLE Devise knows it's the end of the command. Another thing, I needed to create a queue and pop from it after I get response in onCharacteristicRead().

    class DataQueues {  
    
            private ArrayList<byte[]> queueArray;
            private int queuSize;   
    
            protected DataQueues() {
                queueArray = new ArrayList<>();
            }    
            protected void addToQueue(byte[] bytesArr) {
                queueArray.add(bytesArr);    
            }  
    
            protected byte[] popQueue() {    
                if (queueArray.size() >= 0)
                    return queueArray.remove(0);
                else {
                    return null;
                }    
            }    
            protected int getArrSize() {
                return queueArray.size();
            }
        }
    

    Hope this will help some one.