Отправка байтового массива через BLE в MCU - PullRequest
0 голосов
/ 03 июля 2018

Я работаю над передачей содержимого байтового массива из мобильного приложения Android в MCU. Я могу успешно передавать данные побайтово (несколько пакетов), но я не могу успешно отправить массив целиком (как один пакет). Следует отметить, что данные будут передаваться через профиль GATT и что массив успешно передается в эту часть кода.

    public void writeCustomUsernameCharacteristic(byte[] byteArray) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("00002a37-0000-1000-8000-00805f9b34fb"));

        if (mCustomService == null) {
            Log.w(TAG, "Custom BLE Service not found");
            return;
        }
        mBluetoothGatt.requestMtu(244); 

        for (int i = 0; i < credentials.length; i++) {
            individualBytes = byteArray[i];

            BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")); 
            mWriteCharacteristic.setValue(individualBytes, BluetoothGattCharacteristic.FORMAT_UINT8, 0);  
            mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                System.out.println("got interrupted!");
            }
            if (mBluetoothGatt.writeCharacteristic(mWriteCharacteristic) == false) {
                Log.w(TAG, "Failed to write characteristic");
            }
        }
    }

Однако, если я пытаюсь установить значение для самого байтового массива, я не могу отправить информацию. Следует отметить, что об ошибках не сообщается на стороне приложения, и сторона MCU не сообщает о полученных пакетах.

public void writeCustomUsernameCharacteristic(byte[] byteArray) {
        if (mBluetoothAdapter == null || mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothAdapter not initialized");
            return;
        }
        BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("4880c12c-fdcb-4077-8920-a450d7f9b907"));

        if (mCustomService == null) {
            Log.w(TAG, "Custom BLE Service not found");
            return;
        }
        mBluetoothGatt.requestMtu(244);

        BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("fec26ec4-6d71-4442-9f81-55bc21d658d6"));
        mWriteCharacteristic.setValue(byteArray);
        mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
        mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);
    }

Может ли кто-нибудь предоставить какие-либо предложения по передаче этого байтового массива в пакете? Заранее спасибо.

В ответ на возможный дубликат. Похоже, что ссылка ссылается на код, который я уже пытался во втором блоке. Проблема заключается в том, что mBluetoothGatt.writeCharacteristic (mWriteCharacteristic); не отправляет пакеты в MCU.

public void writeCustomUsernameCharacteristic(byte[] byteArray) {
            if (mBluetoothAdapter == null || mBluetoothGatt == null) {
                Log.w(TAG, "BluetoothAdapter not initialized");
                return;
            }
            BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString("4880c12c-fdcb-4077-8920-a450d7f9b907"));

            if (mCustomService == null) {
                Log.w(TAG, "Custom BLE Service not found");
                return;
            }
            mBluetoothGatt.requestMtu(244);

            BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString("fec26ec4-6d71-4442-9f81-55bc21d658d6"));
            mWriteCharacteristic.setValue(byteArray);
            mWriteCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                System.out.println("got interrupted!");
            }

Ответы [ 2 ]

0 голосов
/ 03 июля 2018

Одновременно может быть только один ожидающий запрос GATT. Вам нужно дождаться обратного вызова onMtuChanged, прежде чем вы сможете выполнить запись. Затем вам нужно дождаться обратного вызова onCharacteristicWrite, прежде чем выполнять другую запись.

См. Мой ответ на Android BLE BluetoothGatt.writeDescriptor () возвращает иногда false для более подробного объяснения.

0 голосов
/ 03 июля 2018

Если вы можете отправлять байты за байтом и устройство принимает MTU, это так просто:

mCustomService.writeCharacteristic(mWriteCharacteristic,byteArray );

или

mBluetoothGatt.writeCharacteristic(mWriteCharacteristic,byteArray);

Чтобы проверить, есть ли проблема размера MTU, отправьте небольшой (<20 байтов) байтовый массив. </p>

...