简体   繁体   English

如何以编程方式配对蓝牙设备

[英]How to programmatically pair a bluetooth device

I recently bought a Lilypad Simblee BLE Board and I'd like to pair it programmatically to my computer (using the 32feet.NET library in C#).我最近买了一个Lilypad Simblee BLE 板,我想以编程方式将它与我的计算机配对(使用 C# 中的32feet.NET库)。

I'm aware the " How to programmatically pair a bluetooth device " has already been asked on StackOverflow ( here for example), however for some reason, all my attempts to pair the device programmatically have failed.我知道已经在 StackOverflow 上询问了“如何以编程方式配对蓝牙设备”(例如此处),但是由于某种原因,我以编程方式配对设备的所有尝试都失败了。 Indeed, I successfully paired the device with the " Manage Bluetooth devices " window in Windows 10 Settings panel ( Settings > Devices > Bluetooth ).事实上,我成功地将设备与 Windows 10 设置面板设置>设备>蓝牙)中的“管理蓝牙设备”窗口配对

Firstly, I don't know the pairing method (either legacy or SSP ) to use with my device.首先,我不知道与我的设备一起使用的配对方法旧版SSP )。 Windows never asked me for a PIN or something, so I guess it's SSP, but I'm unsure. Windows 从来没有要求我提供 PIN 或其他东西,所以我猜是 SSP,但我不确定。

I searched on Google how to do a SSP pairing request with 32feet.NET: I found this .我在 Google 上搜索了如何使用 32feet.NET 执行SSP配对请求:我找到了这个

However, once it discovered my device (the device discovery works properly), the pairing request instantly fails.但是,一旦它发现了我的设备(设备发现正常工作),配对请求就会立即失败。

My code:我的代码:

using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;

namespace HLK_Client
{
    class HLKBoard
    {
        public event HLKBoardEventHandler HLKBoardConnectionComplete;
        public delegate void HLKBoardEventHandler(object sender, HLKBoardEventArgs e);

        private BluetoothClient _bluetoothClient;
        private BluetoothComponent _bluetoothComponent;
        private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
        private BluetoothDeviceInfo _hlkBoardDevice;
        private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
        private BluetoothWin32Authentication _bluetoothAuthenticator;


        public HLKBoard()
        {
            _bluetoothClient = new BluetoothClient();
            _bluetoothComponent = new BluetoothComponent(_bluetoothClient);
            _inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
            _bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
            _bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);

            _bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
            _bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
        }


        public void ConnectAsync()
        {
            _inRangeBluetoothDevices.Clear();
            _hlkBoardDevice = null;
            _bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
        }


        private void PairWithBoard()
        {
            Console.WriteLine("Pairing...");

            bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);

            if (pairResult)
            {
                Console.WriteLine("Success");
            }

            else
            {
                Console.WriteLine("Fail"); // Instantly fails
            }
        }


        private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
        {
            _inRangeBluetoothDevices.AddRange(e.Devices);
        }

        private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
        {
            for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i)
            {
                if (_inRangeBluetoothDevices[i].DeviceName == "HLK")
                {
                    _hlkBoardDevice = _inRangeBluetoothDevices[i];
                    PairWithBoard();

                    return;
                }
            }

            HLKBoardConnectionComplete(this, new HLKBoardEventArgs(false, "Didn't found any \"HLK\" discoverable device"));
        }

        private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e)
        {
            e.Confirm = true; // Never reach this line
        }
    }
}

Why does the pairing request fail?为什么配对请求失败?

The answer to the question you linked has a plausible suggestion... did you read it?您链接的问题的答案有一个似是而非的建议……您阅读了吗?

Also you should look at this question as well .你也应该看看这个问题

32feet library is built around legacy pairing, so that you either need to know the pin of the device you are connecting to, or you supply it with a null to get a popup window to enter a pin. 32feet 库是围绕传统配对构建的,因此您要么需要知道要连接的设备的引脚,要么为其提供空值以获取弹出窗口以输入引脚。

It also says that the windows function used by 32feet is deprecated in newer versions of windows.它还说 32feet 使用的 windows 函数在较新版本的 windows 中已弃用。 If that's true, the reason it's failing instantly is because you've passed a null pin in your pairing request and for it to proceed windows needs to show a dialog which no longer exists.如果这是真的,那么它立即失败的原因是因为您在配对请求中传递了一个空引脚,并且它要继续进行 Windows 需要显示一个不再存在的对话框。

What happens if you try to connect with the pin "0000" or "1234" ?如果您尝试连接引脚“0000”或“1234”会发生什么?

I'm looking at the source code of WindowsBluetoothSecurity.cs in 32feet.net and I see if a pairing request fails, it logs the error code to Debug.WriteLine , any chance you could post that error code here?我正在 32feet.net 中查看WindowsBluetoothSecurity.cs的源代码,如果配对请求失败,它将错误代码记录到Debug.WriteLine ,您是否有机会在此处发布该错误代码?

One good work around to this problem might be to import BluetoothAuthenticateDeviceEx and use that manually to complete the pairing request.解决此问题的一个好方法可能是导入BluetoothAuthenticateDeviceEx并手动使用它来完成配对请求。 If you don't want to do this manually, it looks like in the latest version of the 32feet source, there is actually a SSP pairing method that utilises this method but it's not public and it's not used anywhere so you'll need to access it via reflection:如果您不想手动执行此操作,看起来在最新版本的 32feet 源中,实际上有一种使用此方法的 SSP 配对方法,但它不是公开的,也未在任何地方使用,因此您需要访问它通过反射:

typeof(BluetoothSecurity)
    .GetMethod("PairRequest", BindingFlags.Static | BindingFlags.NonPublic)
    .Invoke(null, new object[] { _hlkBoardDevice.DeviceAddress, BluetoothAuthenticationRequirements.MITMProtectionNotRequired });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM