简体   繁体   English

如何使用C#手动绑定到WinForm中的蓝牙低能耗设备?

[英]How to Bind manually to a BlueTooth Low Energy Device in a WinForm using C#?

This question is mostly answered by: Windows UWP connect to BLE device after discovery 这个问题通常由以下问题回答: Windows UWP发现后连接到BLE设备

I am writing a custom service and testing,for now, using a C#.NET WinForm on Windows 10 to connect to a Bluetooth Low Energy (BLE) device. 我目前正在编写自定义服务和测试,使用Windows 10上的C#.NET WinForm连接到低功耗蓝牙(BLE)设备。 I am using Framework 4.6.1. 我正在使用Framework 4.6.1。 We are using a TI SmartRF06 Evaluation Board with a TI CC2650 BLE daughter card. 我们正在使用带有TI CC2650 BLE子卡的TI SmartRF06评估板 Another developer is handling the Firmware of the Board. 另一位开发人员正在处理主板的固件。

Currently using methods similar to the reference answer above I am able to connect to an already bound BLE device. 当前我使用的方法类似于上面的参考答案,因此我能够连接到已经绑定的BLE设备。 This device was manually bound and Windows did require me to enter a PIN. 该设备是手动绑定的,Windows确实要求我输入PIN。 Since the device has no PIN simply entering "0" allowed the device to connect. 由于设备没有PIN,只需输入“ 0”就可以连接设备。 Once connected, in this manner, I can get to all the GATT services and do what I need to do. 一旦建立连接,我就可以使用所有GATT服务并做我需要做的事情。 So I have no issues with finding and getting a hold of a Advertising BLE device. 因此,我对找到并持有Advertising BLE设备没有任何问题。

The issue is that how do I connect to BLE device that has not already been paired? 问题是如何连接尚未配对的BLE设备? I have gone through the net and found many examples of BLE code but nothing specific to showing how the pairing in code is done. 我遍历网络,发现了许多BLE代码示例,但没有具体说明如何完成代码配对。 Not sure I even need it to pair but Windows seems to only show my the GATT services on paired devices. 不确定我什至不需要配对,但Windows似乎仅在配对设备上显示我的GATT服务。

When I do this with unpaired device: 当我使用未配对的设备执行此操作时:

private void BleWatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{       
    var dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
    // dev.DeviceInformation.Pairing.CanPair is true
    // dpr.Status is Failed
    DevicePairingResult dpr = await dev.DeviceInformation.Pairing.PairAsync(DevicePairingProtectionLevel.None);
    var service = await GattDeviceService.FromIdAsync(dev.DeviceInformation.Id);
}

The result of dpr is always failed when device has not been manually paired. 当未手动配对设备时,dpr的结果总是失败。 Which results in the GattDeviceServices being empty. 这导致GattDeviceServices为空。 But I am able to get the advertisement and the properties of the BLE device. 但是我能够获得BLE设备的广告和属性。

There is also this type of method to connect but I can't figure out how to use it: 还有这种类型的连接方法,但我不知道如何使用它:

var prslt = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None,IDevicePairingSettings);

IdeviceParingSettings is an Interface. IdeviceParingSettings是一个接口。 Not sure what Class to use with it. 不确定要使用哪个类。 I am thinking this is where I can set the PIN of "O" that I might need? 我在想这是我可能需要设置“ O”的PIN的地方?

Has anyone had any luck pairing to a BLE device in Windows using C# where the BLE device has no security. 在Windows中使用BLE设备没有安全性的情况下,是否有人能够与Windows中的BLE设备配对。 Basically it should be wide open. 基本上,它应该是开放的。 I feel like I am missing something simple or this is simply not possible (which I have seen some posts claiming that is the case. Most of those were many years old). 我觉得我缺少一些简单的东西,或者根本不可能(我看到一些帖子声称是这种情况。其中大多数都已经有很多年了)。

I did try the methods described in the mentioned post without any difference in result. 我确实尝试了上述文章中描述的方法,但结果没有任何差异。

Any help is appreciated. 任何帮助表示赞赏。 If you need more of the code please look at the link I provided at top as that is what I started with. 如果您需要更多代码,请查看我在顶部提供的链接,因为这是我开始的地方。 I will be happy to provide all of my actual code if there is, perhaps, a sequence that I am doing out of place. 如果有可能我做错了一个序列,我将很乐意提供我所有的实际代码。

I figured it out. 我想到了。 I was on the right track. 我走在正确的轨道上。

After you connect using: 使用以下连接后:

var dev = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);

You need to do a custom Pairing: 您需要执行自定义配对:

var prslt = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None);

But that would simply give you an error. 但这只会给您一个错误。 You must also create a device.DeviceInformation.Pairing.Custom.PairingRequested event handler. 您还必须创建device.DeviceInformation.Pairing.Custom.PairingRequested事件处理程序。

So I created this handler: 所以我创建了这个处理程序:

private void handlerPairingReq(DeviceInformationCustomPairing CP, DevicePairingRequestedEventArgs DPR)
        {
            //so we get here for custom pairing request.
            //this is the magic place where your pin goes.
            //my device actually does not require a pin but
            //windows requires at least a "0".  So this solved 
            //it.  This does not pull up the Windows UI either.
            DPR.Accept("0");


}

Hooked it up just before the PairAsync call Like: 在PairAsync调用之前将其连接起来,例如:

device.DeviceInformation.Pairing.Custom.PairingRequested += handlerPairingRequested;

Example code for the BlueToothAdvertisementWatcher Code that does my connection: 连接我的BlueToothAdvertisementWatcher代码的示例代码:

    private BluetoothLEAdvertisementWatcher BTWatch = new BluetoothLEAdvertisementWatcher();

    private void Inits() 
        {
           BTWatch.Received += new TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs>(BtAddRx);
           BTWatch.Start();
        }

    private async void BtAddRx(BluetoothLEAdvertisementWatcher bw, BluetoothLEAdvertisementReceivedEventArgs args)
        {
            GattCommunicationStatus srslt;
            GattReadResult rslt;
            bw.Stop();//Stop this while inside.

            device = await BluetoothLEDevice.FromBluetoothAddressAsync(args.BluetoothAddress);
                if (device.DeviceInformation.Pairing.IsPaired == false)
                {   

                    /* Optional Below - Some examples say use FromIdAsync
                    to get the device. I don't think that it matters.   */            
                    var did = device.DeviceInformation.Id; //I reuse did to reload later.
                    device.Dispose();
                    device = null;
                    device = await BluetoothLEDevice.FromIdAsync(did);
                    /* end optional */
                    var handlerPairingRequested = new TypedEventHandler<DeviceInformationCustomPairing, DevicePairingRequestedEventArgs>(handlerPairingReq);
                    device.DeviceInformation.Pairing.Custom.PairingRequested += handlerPairingRequested;
                    log("Pairing to device now...."); 

                    var prslt = await device.DeviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin, DevicePairingProtectionLevel.None);                  
                    log("Custom PAIR complete status: " + prslt.Status.ToString() + " Connection Status: " + device.ConnectionStatus.ToString());

                    device.DeviceInformation.Pairing.Custom.PairingRequested -= handlerPairingRequested; //Don't need it anymore once paired.


                    if (prslt.Status != DevicePairingResultStatus.Paired)
                    { //This should not happen. If so we exit to try again.
                        log("prslt exiting.  prslt.status=" + prslt.Status.ToString());// so the status may have updated.  lets drop out of here and get the device again.  should be paired the 2nd time around?
                        bw.Start();//restart this watcher.
                        return;
                    }
                    else
                    {
                        // The pairing takes some time to complete. If you don't wait you may have issues. 5 seconds seems to do the trick.

                        System.Threading.Thread.Sleep(5000); //try 5 second lay.
                        device.Dispose();
                       //Reload device so that the GATT services are there. This is why we wait.                     
                       device = await BluetoothLEDevice.FromIdAsync(did);

                    }
 var services = device.GattServices;
//then more code to finish it up.
}

If you wish to disconnect just use: 如果您想断开连接,请使用:

await device.DeviceInformation.Pairing.UnpairAsync();

Sorry for the messy Code. 抱歉,代码混乱。 If there is anyone that finds is useful or has question let me know. 如果发现有人有用或有疑问,请告诉我。 I could not find any WinForm examples of this code anywhere. 我在任何地方都找不到此代码的任何WinForm示例。 Actually I could not find any code to show how to pair with PIN without the UI. 实际上,在没有UI的情况下,我找不到任何代码来显示如何与PIN配对。 So I hope this helps anyone that might get stuck. 因此,我希望这对任何可能陷入困境的人有所帮助。

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

相关问题 Windows 10 低功耗蓝牙连接 c# - Windows 10 Bluetooth Low Energy Connection c# 用于Windows桌面C#应用程序的蓝牙4.0(低能耗)API - Bluetooth 4.0 (low energy) API for windows desktop C# application 如何在Winform C#中获取Bluetooth Device Com串行端口? - How to get Bluetooth Device Com serial Port in winform C#? C#建立从笔记本电脑内部蓝牙4.0到蓝牙低功耗(BLE)外设的流 - C# Establishing stream from laptop internal bluetooth 4.0 to Bluetooth Low Energy (BLE) peripheral 低功耗蓝牙连接 - Bluetooth Low Energy connection C# Winform 使用 IP 连接到设备 - C# Winform to Connect to Device Using IP 蓝牙设备被检测为低功耗且具有相同 MAC 地址和名称的普通蓝牙设备 - Bluetooth device is detected as a Low Energy and an ordinary Bluetooth device with the same MAC address and name 如何在Windows UWP App中正确订阅蓝牙低能耗设备的GattCharacteristic.ValueChanged通知(指示)? - How do I correctly subscribe to a bluetooth low energy device's GattCharacteristic.ValueChanged notification (indication) in a Windows UWP App? 如何在Windows桌面APP中通过低功耗蓝牙发送阵列? - How to send array via Bluetooth Low Energy in Windows Desktop APP? 无法使用 C# 连接蓝牙设备 - Unable to connect Bluetooth device using c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM