Не работает writeCharacteristic после установки notification в android bluetooth le

до этого я не имел опыта работы с bluetooth le в android. Проблема заключается в том, что после успешного поиска и connectGatt работает или запись в characteristic, или notification. В соответствии с этой статьёй и этим ответом я должен сначала установить notification и потом записать данные в характеристику. Но это не работает. Также вынес запись характеристики в отдельный поток, читал тут что это помогло при записи данных больше 20 байт, хотя мне надо записать всего 2.

private BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
        if (status == GATT_SUCCESS) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "We successfully connected, proceed with service discovery");
                stopScan();
                gatt.discoverServices();

            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.i(TAG, "We successfully disconnected on our own request");
                gatt.close();
            } else { }
        } else {
            // An error happened
            gatt.close();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        Log.i(TAG, "We are onServiceDiscovered");
        BluetoothGattCharacteristic characteristic =
                gatt.getService(Beacon.BEACON_SERVICE_UUID)
                        .getCharacteristic(Beacon.BEACON_CHAR_UUID);
        gatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor =
                characteristic.getDescriptor(convertFromInteger(0x2902));

        descriptor.setValue(
                BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

        gatt.writeDescriptor(descriptor);

        writeCharacteristic();
    }

функция записи:

private void writeCharacteristic() {

    class writeTask implements Runnable {
        byte [] bytes;
        writeTask(byte[] to_write){bytes = to_write;}

        public void run() {
            if (gatt == null) {
                Log.e(TAG, "lost connection");
            }

            if (gatt.getService(Beacon.BEACON_SERVICE_UUID) == null) {
                Log.e(TAG, "service not found!");
            }

            if (gatt.getService(Beacon.BEACON_SERVICE_UUID).getCharacteristic(Beacon.BEACON_CHAR_UUID) == null) {
                Log.e(TAG, "char not found!");
            }
            BluetoothGattCharacteristic characteristic = gatt.getService(Beacon.BEACON_SERVICE_UUID).getCharacteristic(Beacon.BEACON_CHAR_UUID);

            characteristic.setWriteType(WRITE_TYPE_DEFAULT);
            characteristic.setValue(bytes);
            if (gatt.writeCharacteristic(characteristic)) {
                Log.i(TAG, "Char written" + flag);
                flag++;
            } else {
                Log.e(TAG, "Char writing failure");
            }
        }
    }
    Thread t = new Thread(new writeTask(new byte[] {(byte)0x05, (byte)0x01}));
    t.start();
    try {
        t.sleep(150);
    } catch (InterruptedException e) {
        Log.i(TAG, "interrupted exception");
    }

}

в ней writeCharacteristic() возвращает false как будто устройство занято, если сначала записать данные в характеристику, то потом невозможно настроить notification. Не понимаю почему так происходит, помогите, пожалуйста.


Ответы (0 шт):