在Android 4.4+上编程配对BLE设备

40

有没有人能提供一个完整的工作示例,演示如何在Android 4.4或更高版本中以编程方式与使用密码输入(即6位数字PIN码)或数字比较的BLE(不是蓝牙经典)设备进行配对?我所说的'以编程方式’是指我告诉Android PIN码,而不需要提示用户。

虽然SO上有许多类似的问题,但它们要么是关于蓝牙经典的,要么过时了(在setPin()createBond()公开之前),或者没有回答。

我的理解如下:

  1. 连接到设备并发现其服务。
  2. 尝试读取'受保护'的特性。
  3. 设备返回身份验证错误。
  4. Android以某种方式启动配对流程,并告诉它PIN码。
  5. 现在可以读取该特性。
我已经使用mBednRF51-DK上创建了一个设备,并为其设置了一个特征。
我这样设置了安全参数:
ble.securityManager().init(
    true, // Enable bonding (though I don't really need this)
    true, // Require MitM protection. I assume you don't get a PIN prompt without this, though I'm not 100% sure.
    SecurityManager::IO_CAPS_DISPLAY_ONLY, // This makes it us the Passkey Entry (PIN) pairing method.
    "123456"); // Static PIN

然后在特性中我使用了

requireSecurity(SecurityManager::SECURITY_MODE_ENCRYPTION_WITH_MITM);

现在当我尝试使用 Nordic Master Control Panel阅读它时,会收到这样的配对请求通知:

pairing request

passkey entry

我可以输入这个 PIN 码,然后 MCP 会显示我已经连接成功,并且可以读取特征。

但是,在我的应用中,我希望避免用户输入 PIN 码,因为我已经知道了。有没有最近的完整示例可以告诉我如何做到这一点?

编辑:顺便提一下,this 是我在 SO 上找到的最相关的问题,但那里的答案似乎不起作用。


Android SDK允许在未通知/请求用户确认的情况下进行配对吗?听起来好像你可能做不到... - Florian Castellane
1
是的。 它有一个专门用于此的 setPin() 方法,我已经让它工作了,但是“配对请求”通知仍然显示。 - Timmmm
我不确定这是否有帮助,但值得阅读。https://dev59.com/gWMl5IYBdhLWcg3w_bDj - Maytham Fahmi
是的,我也看到了。那里也没有答案。 :-/ - Timmmm
你能回答我的问题吗?在https://security.stackexchange.com/questions/179298/how-to-enforce-android-bluetooth-protocol-stack-to-work-only-in-secure-modes。 - ofskyMohsen
@Timmmm,你能否对我的问题进行一些解释? - Tejas Pandya
2个回答

41

我几乎已经做到了。它可以通过编程配对,但我无法摆脱“配对请求”通知。一些回答这个问题的人声称可以使用隐藏方法cancelPairingUserInput()在显示后立即隐藏它,但这对我似乎不起作用。

编辑:成功!

最终我阅读了BluetoothPairingRequest发送配对请求广播的代码的源代码,并意识到我应该拦截ACTION_PAIRING_REQUEST。幸运的是,这是一个有序的意图广播,所以你可以在系统之前拦截它。

以下是步骤。

  1. 注册接收BluetoothDevice.ACTION_PAIRING_REQUEST更改广播意图。使用高优先级!
  2. 连接设备。
  3. 发现服务。
  4. 如果你现在已经断开连接,那么很可能是因为债券信息不正确(例如外围设备清除了它)。在这种情况下,使用隐藏方法(谷歌真的很认真)删除债券信息,并重新连接。
  5. 尝试读取需要加密MitM保护的特性。
  6. ACTION_PAIRING_REQUEST广播接收器中,检查配对类型是否为BluetoothDevice.PAIRING_VARIANT_PIN,如果是,则调用setPin()abortBroadcast()。否则,你可以让系统处理它,或者显示错误或其他内容。

以下是代码。

/* This implements the BLE connection logic. Things to watch out for:

1. If the bond information is wrong (e.g. it has been deleted on the peripheral) then
   discoverServices() will cause a disconnect. You need to delete the bonding information and reconnect.

2. If the user ignores the PIN request, you get the undocumented GATT_AUTH_FAILED code.

 */
public class ConnectActivityLogic extends Fragment
{
    // The connection to the device, if we are connected.
    private BluetoothGatt mGatt;

    // This is used to allow GUI fragments to subscribe to state change notifications.
    public static class StateObservable extends Observable
    {
        private void notifyChanged() {
            setChanged();
            notifyObservers();
        }
    };

    // When the logic state changes, State.notifyObservers(this) is called.
    public final StateObservable State = new StateObservable();

    public ConnectActivityLogic()
    {
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Tell the framework to try to keep this fragment around
        // during a configuration change.
        setRetainInstance(true);

        // Actually set it in response to ACTION_PAIRING_REQUEST.
        final IntentFilter pairingRequestFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
        pairingRequestFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY - 1);
        getActivity().getApplicationContext().registerReceiver(mPairingRequestRecevier, pairingRequestFilter);

        // Update the UI.
        State.notifyChanged();

        // Note that we don't actually need to request permission - all apps get BLUETOOTH and BLUETOOTH_ADMIN permissions.
        // LOCATION_COARSE is only used for scanning which I don't need (MAC is hard-coded).

        // Connect to the device.
        connectGatt();
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();

        // Disconnect from the device if we're still connected.
        disconnectGatt();

        // Unregister the broadcast receiver.
        getActivity().getApplicationContext().unregisterReceiver(mPairingRequestRecevier);
    }

    // The state used by the UI to show connection progress.
    public ConnectionState getConnectionState()
    {
        return mState;
    }

    // Internal state machine.
    public enum ConnectionState
    {
        IDLE,
        CONNECT_GATT,
        DISCOVER_SERVICES,
        READ_CHARACTERISTIC,
        FAILED,
        SUCCEEDED,
    }
    private ConnectionState mState = ConnectionState.IDLE;

    // When this fragment is created it is given the MAC address and PIN to connect to.
    public byte[] macAddress()
    {
        return getArguments().getByteArray("mac");
    }
    public int pinCode()
    {
        return getArguments().getInt("pin", -1);
    }

    // Start the connection process.
    private void connectGatt()
    {
        // Disconnect if we are already connected.
        disconnectGatt();

        // Update state.
        mState = ConnectionState.CONNECT_GATT;
        State.notifyChanged();

        BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(macAddress());

        // Connect!
        mGatt = device.connectGatt(getActivity(), false, mBleCallback);
    }

    private void disconnectGatt()
    {
        if (mGatt != null)
        {
            mGatt.disconnect();
            mGatt.close();
            mGatt = null;
        }
    }

    // See https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/master/stack/include/gatt_api.h
    private static final int GATT_ERROR = 0x85;
    private static final int GATT_AUTH_FAIL = 0x89;

    private android.bluetooth.BluetoothGattCallback mBleCallback = new BluetoothGattCallback()
    {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
        {
            super.onConnectionStateChange(gatt, status, newState);
            switch (newState)
            {
            case BluetoothProfile.STATE_CONNECTED:
                // Connected to the device. Try to discover services.
                if (gatt.discoverServices())
                {
                    // Update state.
                    mState = ConnectionState.DISCOVER_SERVICES;
                    State.notifyChanged();
                }
                else
                {
                    // Couldn't discover services for some reason. Fail.
                    disconnectGatt();
                    mState = ConnectionState.FAILED;
                    State.notifyChanged();
                }
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                // If we try to discover services while bonded it seems to disconnect.
                // We need to debond and rebond...

                switch (mState)
                {
                    case IDLE:
                        // Do nothing in this case.
                        break;
                    case CONNECT_GATT:
                        // This can happen if the bond information is incorrect. Delete it and reconnect.
                        deleteBondInformation(gatt.getDevice());
                        connectGatt();
                        break;
                    case DISCOVER_SERVICES:
                        // This can also happen if the bond information is incorrect. Delete it and reconnect.
                        deleteBondInformation(gatt.getDevice());
                        connectGatt();
                        break;
                    case READ_CHARACTERISTIC:
                        // Disconnected while reading the characteristic. Probably just a link failure.
                        gatt.close();
                        mState = ConnectionState.FAILED;
                        State.notifyChanged();
                        break;
                    case FAILED:
                    case SUCCEEDED:
                        // Normal disconnection.
                        break;
                }
                break;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status)
        {
            super.onServicesDiscovered(gatt, status);

            // Services have been discovered. Now I try to read a characteristic that requires MitM protection.
            // This triggers pairing and bonding.

            BluetoothGattService nameService = gatt.getService(UUIDs.NAME_SERVICE);
            if (nameService == null)
            {
                // Service not found.
                disconnectGatt();
                mState = ConnectionState.FAILED;
                State.notifyChanged();
                return;
            }
            BluetoothGattCharacteristic characteristic = nameService.getCharacteristic(UUIDs.NAME_CHARACTERISTIC);
            if (characteristic == null)
            {
                // Characteristic not found.
                disconnectGatt();
                mState = ConnectionState.FAILED;
                State.notifyChanged();
                return;
            }

            // Read the characteristic.
            gatt.readCharacteristic(characteristic);
            mState = ConnectionState.READ_CHARACTERISTIC;
            State.notifyChanged();
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status)
        {
            super.onCharacteristicRead(gatt, characteristic, status);

            if (status == BluetoothGatt.GATT_SUCCESS)
            {
                // Characteristic read. Check it is the right one.
                if (!UUIDs.NAME_CHARACTERISTIC.equals(characteristic.getUuid()))
                {
                    // Read the wrong characteristic. This shouldn't happen.
                    disconnectGatt();
                    mState = ConnectionState.FAILED;
                    State.notifyChanged();
                    return;
                }

                // Get the name (the characteristic I am reading just contains the device name).
                byte[] value = characteristic.getValue();
                if (value == null)
                {
                    // Hmm...
                }

                disconnectGatt();
                mState = ConnectionState.SUCCEEDED;
                State.notifyChanged();

                // Success! Save it to the database or whatever...
            }
            else if (status == BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION)
            {
                // This is where the tricky part comes
                if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_NONE)
                {
                    // Bonding required.
                    // The broadcast receiver should be called.
                }
                else
                {
                    // ?
                }
            }
            else if (status == GATT_AUTH_FAIL)
            {
                // This can happen because the user ignored the pairing request notification for too long.
                // Or presumably if they put the wrong PIN in.
                disconnectGatt();
                mState = ConnectionState.FAILED;
                State.notifyChanged();
            }
            else if (status == GATT_ERROR)
            {
                // I thought this happened if the bond information was wrong, but now I'm not sure.
                disconnectGatt();
                mState = ConnectionState.FAILED;
                State.notifyChanged();
            }
            else
            {
                // That's weird.
                disconnectGatt();
                mState = ConnectionState.FAILED;
                State.notifyChanged();
            }
        }
    };


    private final BroadcastReceiver mPairingRequestRecevier = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(intent.getAction()))
            {
                final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);

                if (type == BluetoothDevice.PAIRING_VARIANT_PIN)
                {
                    device.setPin(Util.IntToPasskey(pinCode()));
                    abortBroadcast();
                }
                else
                {
                    L.w("Unexpected pairing type: " + type);
                }
            }
        }
    };

    public static void deleteBondInformation(BluetoothDevice device)
    {
        try
        {
            // FFS Google, just unhide the method.
            Method m = device.getClass().getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        }
        catch (Exception e)
        {
            L.e(e.getMessage());
        }
    }
}

如果我们不为BluetoothDevice.ACTION_PAIRING_REQUEST设置高优先级会发生什么? - anticafe
我认为这是因为它是一个有序广播,会先发送到优先级最高的广播接收器。他们可以终止广播,所以如果有其他应用程序(或系统)比您的应用程序优先级更高,则您可能无法收到广播。现在我想起来了,应该有一些代码来检查配对请求是否确实是您负责的 - 否则,当用户尝试与完全不相关的设备配对时,它可能会打开您的应用程序!虽然不知道怎么做。 - Timmmm
这里的UUIDs是什么? - Bishwajyoti Roy
这只是一个充满静态成员的类,列出了你感兴趣的BLE服务和特征的UUID。 - Timmmm
1
@Timmmm 我搞不清楚你放在UUIDs里面的是什么,我将静态变量初始化为空值,但是它导致错误。你能否给我展示一种方法? - Tejas Pandya
显示剩余19条评论

7

我也遇到了同样的问题,在进行了所有研究后,我找到了以下解决方案,可以在不进行任何手动干预的情况下配对到BLE。

(已测试并正常工作!!!)

我基本上是在寻找特定的蓝牙设备(我知道MAC地址),一旦找到它就与它配对。首先要做的是使用广播接收器创建配对请求,并按如下方式处理该请求。

IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
                intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
                registerReceiver(broadCastReceiver,intentFilter);

你需要编写广播接收器并按以下方式处理它。
String BLE_PIN = "1234"
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
        {
            BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            bluetoothDevice.setPin(BLE_PIN.getBytes());
            Log.e(TAG,"Auto-entering pin: " + BLE_PIN);
            bluetoothDevice.createBond();
            Log.e(TAG,"pin entered and request sent...");
        }
    }
};

看,你应该可以不需要任何手动操作就连接到蓝牙设备了。

希望这能帮助你 :-) 如果它对你有用,请将其标记为正确答案。


这似乎与我的答案完全相同。 - Timmmm
2
我只是简化了它并添加了一些内容,以避免人们的困惑。 - Varun A M
4
好的,你应该这样说,并解释一下更改,比如删除 abortBroadcast() 并添加 createBond() - Timmmm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接