How do you get a BLE Advertisment callback in a desktop .NET app?

泄露秘密 提交于 2019-12-10 11:16:53

问题


I am trying to get a BLE advertisement callback from a .NET Windows desktop application. I am able to call into the APIs, however the Received event is never called from the OS in a WPF or Command line application. I do get events when the code is called from a Unit Test in VS2015, or universal Windows app. However, I need to do other things not available in universal Windows. Here is the code:

    using Windows.Devices.Bluetooth.Advertisement;
    public static void ScanForAdvertisments()
    {
        mWatcher = new BluetoothLEAdvertisementWatcher();           
        mWatcher.Received += OnAdvertismentReceived;
        mWatcher.ScanningMode = BluetoothLEScanningMode.Active;
        mWatcher.Start();
    }

    public static void OnAdvertismentReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
    {

        ulong address = args.BluetoothAddress;
        short rssi = args.RawSignalStrengthInDBm;
    }
  • I've referenced Windows.winmd in order to include the BLE/UWP namespaces.
  • I am using framework version 4.6.1 on Windows 10 Anniversary Edition, I had the same problem on the previous windows build as well.
  • Using a UWP app I set the DeviceCapability for bluetooth in the appxmanifest. The unit test project seems not to require this and I'm not sure how to apply appxmanifests to desktop projects.
  • The status property reports the scanner is running and the stopped event is also never triggered.

Anyway, is this a Windows bug? Is there a way to workaround it? I tried looking into app services but they seem not to be set up to call into desktop code very well and calling desktop code from UWP seems complex to deploy. Thanks.


回答1:


Just tried this out with a Console .NET 4.6.1 app and the advertisement callback is coming through. I wrote up a GitHub Sample of this a bit ago, which might help out. They key for getting WinRT APIs working are two references:

To use the WinRT APIs, add two references:

  1. C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd

  2. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

It sounds like you may be missing the second reference. I was able to use the v4.5 .NetCore framework with 4.6.1.



来源:https://stackoverflow.com/questions/38819116/how-do-you-get-a-ble-advertisment-callback-in-a-desktop-net-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!