Emparejamiento de Baja Energía Bluetooth Android


Cómo emparejar un dispositivo Bluetooth de baja energía(BLE) con Android para leer datos cifrados.

Usando la información en la página Android BLE, puedo descubrir el dispositivo, conectarme a él, descubrir servicios y leer características no cifradas.

Cuando intento leer una característica cifrada (una que hará que iOS muestre una ventana emergente pidiendo emparejar y luego completar la lectura), recibo un código de error 5 , que corresponde a Autenticación insuficiente.

No estoy seguro cómo emparejar el dispositivo o cómo proporcionar la información de autenticación para completar la lectura.

Jugué con BluetoothGattCharacteristics al intentar agregar descriptores, pero eso tampoco funcionó.
Cualquier ayuda es apreciada!

Author: Shiva, 2013-08-13

3 answers

Cuando obtienes el error GATT_INSUFFICIENT_AUTHENTICATION, el sistema inicia el proceso de unión por ti. En el siguiente ejemplo, estoy tratando de habilitar las notificaciones e indicaciones en glucose monitor. Primero estoy habilitando las notificaciones sobre la característica de medición de glucosa que puede causar que aparezca el error.

@Override
    public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            if (GM_CHARACTERISTIC.equals(descriptor.getCharacteristic().getUuid())) {
                mCallbacks.onGlucoseMeasurementNotificationEnabled();

                if (mGlucoseMeasurementContextCharacteristic != null) {
                    enableGlucoseMeasurementContextNotification(gatt);
                } else {
                    enableRecordAccessControlPointIndication(gatt);
                }
            }

            if (GM_CONTEXT_CHARACTERISTIC.equals(descriptor.getCharacteristic().getUuid())) {
                mCallbacks.onGlucoseMeasurementContextNotificationEnabled();
                enableRecordAccessControlPointIndication(gatt);
            }

            if (RACP_CHARACTERISTIC.equals(descriptor.getCharacteristic().getUuid())) {
                mCallbacks.onRecordAccessControlPointIndicationsEnabled();
            }
        } else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION) {
            // this is where the tricky part comes

            if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
                mCallbacks.onBondingRequired();

                // I'm starting the Broadcast Receiver that will listen for bonding process changes

                final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                mContext.registerReceiver(mBondingBroadcastReceiver, filter);
            } else {
                // this situation happens when you try to connect for the second time to already bonded device
                // it should never happen, in my opinion
                Logger.e(TAG, "The phone is trying to read from paired device without encryption. Android Bug?");
                // I don't know what to do here
                // This error was found on Nexus 7 with KRT16S build of Andorid 4.4. It does not appear on Samsung S4 with Andorid 4.3.
            }
        } else {
            mCallbacks.onError(ERROR_WRITE_DESCRIPTOR, status);
        }
    };

Donde está el mBondingBroadcastReceiver:

private BroadcastReceiver mBondingBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
        final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);

        Logger.d(TAG, "Bond state changed for: " + device.getAddress() + " new state: " + bondState + " previous: " + previousBondState);

        // skip other devices
        if (!device.getAddress().equals(mBluetoothGatt.getDevice().getAddress()))
            return;

        if (bondState == BluetoothDevice.BOND_BONDED) {
            // Continue to do what you've started before
            enableGlucoseMeasurementNotification(mBluetoothGatt);

            mContext.unregisterReceiver(this);
            mCallbacks.onBonded();
        }
    }
};

Recuerde anular el registro del receptor de difusión al salir de la actividad. Puede no haber sido no registrado por el propio recibidor.

 23
Author: philips77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-19 14:45:15

Creo que el nuevo Android 4.4 proporciona el método de emparejamiento. el mismo problema que ya estoy enfrentando, así que espere la actualización y espere por el método createBond() resuelto .

Http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#setPairingConfirmation%28boolean%29

 1
Author: mcd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-03 14:00:10

Es posible que necesite comprobar el smp del núcleo.archivo c, qué método de paring invoca para el paring. 1) passkey 2) Apenas trabajo o etc. supongo que si será capaz de invocar el nivel de seguridad MIMT y passkey , no habrá ningún problema de autenticación. Asegúrese de que todos los indicadores estén configurados para invocar los métodos de clave de acceso SMP. pista poniendo un poco de impresión en smp.archivo c.

Una solución que funciona en ICS : con la herramienta btmgmt en Android y conectándola en API de cifrado. con passkey o cualquier otro método. se obrar. Es posible que deba agregar las API de clave de acceso en btmgmt desde el último código de bluez.

 0
Author: RobinSingh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-01 07:43:54