BLE BluetoothGattCallback получает STATE_DISCONNECTED, когда устройство все еще включено

Устройство Bluetooth: датчик Blue Maestro Tempo disk. (Датчик 23, температура+влажность+датчик точки росы)

Это ссылка на SDK поставщика, есть ошибка, которую я пытаюсь исправить.

Я подключаюсь к устройству Bluetooth, используя этот метод:

/**
     * Connects to the GATT server hosted on the Bluetooth LE device.
     *
     * @param address The device address of the destination device.
     *
     * @return Return true if the connection is initiated successfully. The connection result
     *         is reported asynchronously through the
     *         {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
     *         callback.
     */


      public boolean connect(final String address) {
        if (mBluetoothAdapter == null || address == null) {
            Log.e(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }

        // Previously connected device.  Try to reconnect.
        if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
                && mBluetoothGatt != null) {
            Log.e(TAG, "Trying to use an existing mBluetoothGatt for connection.");
            if (mBluetoothGatt.connect()) {
                mConnectionState = STATE_CONNECTING;
                return true;
            } else {
                return false;
            }
        }


        final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        if (device == null) {
            Log.e(TAG, "Device not found.  Unable to connect.");
            return false;
        }
        // We want to directly connect to the device, so we are setting the autoConnect
        // parameter to false.
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        Log.e(TAG, "Trying to create a new connection.");
        mBluetoothDeviceAddress = address;
        mConnectionState = STATE_CONNECTING;
        return true;
    }

Вот мой BluetoothGattCallback:

    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        String intentAction;
        Log.e(TAG, "In onConnectionStateChange and there has been a change of :" +newState);
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            intentAction = ACTION_GATT_CONNECTED;
            mConnectionState = STATE_CONNECTED;
            broadcastUpdate(intentAction);
            Log.e(TAG, "Connected to GATT server.");

            // Attempts to discover services after successful connection.
            Log.e(TAG, "Attempting to start service discovery:");
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Boolean discover = mBluetoothGatt.discoverServices();
            if (discover == true) {
                //Raise flag
                unstableBluetoothBehaviour = true;
                Log.e(TAG, "Service discovery returns true and is started");
            } else {
                Log.e(TAG, "Service discovery returns false and has stopped unexpectedly");
            }

        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            intentAction = ACTION_GATT_DISCONNECTED;
            mConnectionState = STATE_DISCONNECTED;
            if (unstableBluetoothBehaviour == true) {

                Log.e(TAG, "Unstable behaviour detected");

            }
            Log.e(TAG, "Disconnected from GATT server.");
            broadcastUpdate(intentAction);
            close();
        }
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        Log.e(TAG, "In onServicesDiscovered");
        if (status == BluetoothGatt.GATT_SUCCESS) {
            Log.e(TAG, "mBluetoothGatt = " + mBluetoothGatt);

            broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
        } else {
            Log.e(TAG, "onServicesDiscovered received: " + status);
        }
    }

    @Override
    public void onCharacteristicRead(BluetoothGatt gatt,
                                     BluetoothGattCharacteristic characteristic,
                                     int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        }


    }

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic characteristic) {
        broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
        Log.e(TAG, "Characteristic has been updated = " + characteristic);
    }


};

Проблема в том, что когда я вызываю Connect(), onConnectionChange() вызывается с STATE_CONNECTED. Затем он снова вызывается с STATE_DISCONNECTED!


Вот распечатка из Logcat, она может помочь вам разобраться в проблеме:

11-01 12:42:29.082 17969-17969/com.bluemaestro.tempo_utility D/ViewRootImpl: #3 mView = null
11-01 12:42:29.172 17969-17969/com.bluemaestro.tempo_utility D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 24 - 0, 0) vi=Rect(0, 24 - 0, 0) or=1
11-01 12:42:29.242 17969-17969/com.bluemaestro.tempo_utility E/BlueMaestro: onServiceConnected mService= com.bluemaestro.tempo_utility.delivery_monitor.MyUARTService@dd6c856
11-01 12:42:29.242 17969-17969/com.bluemaestro.tempo_utility D/BluetoothGatt: connect() - device: ED:90:ED:F9:4C:60, auto: false
    registerApp()
    registerApp() - UUID=b3664342-0b17-427b-b32b-048726bc32de
11-01 12:42:29.282 17969-17987/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
11-01 12:42:29.292 17969-17969/com.bluemaestro.tempo_utility E/MyUARTService: Trying to create a new connection.
11-01 12:42:29.322 17969-17969/com.bluemaestro.tempo_utility I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@574a141 time:88055063
    Timeline: Activity_idle id: android.os.BinderProxy@c3710fb time:88055065
11-01 12:42:29.512 17969-17969/com.bluemaestro.tempo_utility V/ActivityThread: updateVisibility : ActivityRecord{2870b81 token=android.os.BinderProxy@c3710fb {com.bluemaestro.tempo_utility/com.bluemaestro.tempo_utility.delivery_monitor.ConnectSensorActivity}} show : false
11-01 12:42:30.482 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=7 device=ED:90:ED:F9:4C:60
11-01 12:42:30.492 17969-17981/com.bluemaestro.tempo_utility E/MyUARTService: In onConnectionStateChange and there has been a change of :2
    Connected to GATT server.
    Attempting to start service discovery:
11-01 12:42:30.502 17969-17969/com.bluemaestro.tempo_utility E/BlueMaestro: UART_CONNECT_MSG
11-01 12:42:32.502 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: discoverServices() - device: ED:90:ED:F9:4C:60
11-01 12:42:32.502 17969-17981/com.bluemaestro.tempo_utility E/MyUARTService: Service discovery returns true and is started
11-01 12:42:32.502 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientConnParamsChanged() - Device=ED:90:ED:F9:4C:60 interval=6 status=0
    onClientConnParamsChanged() - Device=ED:90:ED:F9:4C:60 interval=39 status=0
11-01 12:42:32.512 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: onSearchComplete() = Device=ED:90:ED:F9:4C:60 Status=0
11-01 12:42:32.512 17969-17981/com.bluemaestro.tempo_utility E/MyUARTService: In onServicesDiscovered
    mBluetoothGatt = android.bluetooth.BluetoothGatt@e01b0d7
11-01 12:42:32.512 17969-17969/com.bluemaestro.tempo_utility E/BlueMaestro: ENABLETXNOTIFICATION
11-01 12:42:36.092 17969-17980/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientConnParamsChanged() - Device=ED:90:ED:F9:4C:60 interval=159 status=0
11-01 12:42:56.842 17969-17969/com.bluemaestro.tempo_utility D/BluetoothAdapter: stopLeScan()
    STATE_ON
    STATE_ON
    scan not started yet
11-01 12:43:00.762 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientConnectionState() - status=19 clientIf=7 device=ED:90:ED:F9:4C:60
11-01 12:43:00.762 17969-17981/com.bluemaestro.tempo_utility E/MyUARTService: In onConnectionStateChange and there has been a change of :0
    Unstable behaviour detected
    Disconnected from GATT server.
    mBluetoothGatt closed
11-01 12:43:00.762 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: close()
11-01 12:43:00.762 17969-17969/com.bluemaestro.tempo_utility E/BlueMaestro: UART_DISCONNECT_MSG
11-01 12:43:00.762 17969-17969/com.bluemaestro.tempo_utility E/MyUARTService: mBluetoothGatt closed
11-01 12:43:00.762 17969-17969/com.bluemaestro.tempo_utility D/BluetoothGatt: close()
11-01 12:43:00.772 17969-17981/com.bluemaestro.tempo_utility D/BluetoothGatt: unregisterApp() - mClientIf=7
11-01 12:43:00.772 17969-17969/com.bluemaestro.tempo_utility D/BluetoothGatt: unregisterApp() - mClientIf=7
11-01 12:44:28.422 17969-17969/com.bluemaestro.tempo_utility V/ActivityThread: updateVisibility : ActivityRecord{7e3fdc4 token=android.os.BinderProxy@574a141 {com.bluemaestro.tempo_utility/com.bluemaestro.tempo_utility.delivery_monitor.DashboardActivity}} show : true
11-01 12:49:51.792 17969-17969/com.bluemaestro.tempo_utility I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@574a141 time:88497537

Еще один журнальный кот, который я получаю без изменения кода:

11-01 14:07:25.892 21448-21448/com.bluemaestro.tempo_utility E/MyUARTService: Trying to create a new connection.
11-01 14:07:25.892 21448-21462/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
11-01 14:07:25.902 21448-21448/com.bluemaestro.tempo_utility I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@3cd6867 time:93151645
    Timeline: Activity_idle id: android.os.BinderProxy@a2ac28a time:93151645
11-01 14:07:26.112 21448-21448/com.bluemaestro.tempo_utility V/ActivityThread: updateVisibility : ActivityRecord{258b2e1 token=android.os.BinderProxy@a2ac28a {com.bluemaestro.tempo_utility/com.bluemaestro.tempo_utility.delivery_monitor.ConnectSensorActivity}} show : false
11-01 14:07:30.902 21448-21462/com.bluemaestro.tempo_utility D/BluetoothGatt: onClientConnectionState() - status=133 clientIf=7 device=ED:90:ED:F9:4C:60
11-01 14:07:30.902 21448-21462/com.bluemaestro.tempo_utility E/MyUARTService: In onConnectionStateChange and there has been a change of :0
11-01 14:07:30.902 21448-21462/com.bluemaestro.tempo_utility E/MyUARTService: Disconnected from GATT server.
    mBluetoothGatt closed
11-01 14:07:30.902 21448-21462/com.bluemaestro.tempo_utility D/BluetoothGatt: close()
    unregisterApp() - mClientIf=7
11-01 14:07:30.902 21448-21448/com.bluemaestro.tempo_utility E/BlueMaestro: UART_DISCONNECT_MSG
11-01 14:07:30.902 21448-21448/com.bluemaestro.tempo_utility E/MyUARTService: mBluetoothGatt closed
11-01 14:07:30.902 21448-21448/com.bluemaestro.tempo_utility D/BluetoothGatt: close()
11-01 14:07:30.912 21448-21448/com.bluemaestro.tempo_utility D/BluetoothGatt: unregisterApp() - mClientIf=7
11-01 14:07:50.572 21448-21448/com.bluemaestro.tempo_utility D/BluetoothAdapter: stopLeScan()
    STATE_ON
    STATE_ON
    scan not started yet

person Mena    schedule 01.11.2018    source источник
comment
вам, вероятно, следует stopLeScan перед подключением к устройству   -  person Vladyslav Matviienko    schedule 01.11.2018
comment
@VladyslavMatviienko Я убедился, что остановил LeScan перед вызовом метода Connect.   -  person Mena    schedule 01.11.2018
comment
согласно журналу, stopLeScan() вызывается намного позже, чем соединение   -  person Vladyslav Matviienko    schedule 01.11.2018
comment
@VladyslavMatviienko, вероятно, еще один вызов stopLeScan(), который уже не сканирует. Я убедился, вызвав stopLeScan() перед connect() после того, как вы мне сказали.   -  person Mena    schedule 01.11.2018
comment
это теоретически может быть проблемой, старайтесь избегать вызова stopScan, если он еще не сканирует.   -  person Vladyslav Matviienko    schedule 01.11.2018
comment
@VladyslavMatviienko Хорошо, я попытался найти источник этого stopLeScan, и он вызывается сразу после получения onClientConnParamsChanged() и классом BluetoothAdapter. Так что не из моего кода. Проверьте logcat и скажите мне, поняли ли вы то, что я пытаюсь вам сказать.   -  person Mena    schedule 01.11.2018
comment
да я понимаю, что вы имеете в виду. Вы говорите, что это не вы мешаете БТ сканировать, а система делает это сама, и может быть так. Тогда, вероятно, устройству, к которому вы подключаетесь, не нравится то, что вы делаете с включенными уведомлениями, и оно отключается из-за этого.   -  person Vladyslav Matviienko    schedule 01.11.2018
comment
@VladyslavMatviienko Я закомментировал код ENABLENOTIFICATION. Но все же....кстати. Иногда я получаю другой Logcat без изменения кода. Отключение происходит до проверки сервисов. Я разместил обновление выше.   -  person Mena    schedule 01.11.2018
comment
Нет необходимости, чтобы вы вызывали stopLeScan, это рекомендуется, хотя в любом случае это просто зависит от логики вашего приложения. Я работаю с несколькими дисками, отправляю команды приема и все время сканирую ble.   -  person Dushyant Suthar    schedule 27.12.2018
comment
@Mena Мена Получил ли ты решение, я тоже столкнулся с той же проблемой.   -  person Shubham Anand    schedule 11.02.2020


Ответы (1)


1- Убедитесь, что вы подключаетесь к правильному устройству. Сканер Bluetooth будет сканировать множество устройств и может найти устройство, к которому невозможно подключиться (так же, как мы подключаемся к устройству BLE).

2-Убедитесь, что вы не вызываете bluetoothLeScanner.stopScan, когда пытаетесь подключиться, до или после. Вместо этого позвоните после того, как вы успешно получите статус соединения 2 (подключено)

person MSaudi    schedule 14.10.2019
comment
Если вы имеете в виду остановку сканирования после подключения, я не думаю, что это важный шаг. Но если вы по какой-то причине решили вызвать stopScan, то совет в пункте 2 пригодится. - person MSaudi; 14.10.2019