1

我正在尝试编写一个使用 WinRT 蓝牙 LE API(Windows.Devices.Bluetooth 命名空间)的 C# 应用程序。该应用程序是 Windows 经典桌面应用程序(WPF,而不是UWP)。在创意者更新之前运行 Windows 10 版本时,这些 API 会按预期运行。但是,在运行 Creators Update 时,应该向蓝牙设备发送数据的 API 不起作用。具体来说,以下方法返回成功状态代码,但不通过蓝牙无线电传输任何数据(使用蓝牙流量嗅探器进行验证):

  • GattCharacteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync
  • GattCharacteristic.WriteValueAsync

因此,任何为特征注册 ValueChanged 处理程序的尝试都不起作用。由于注册从未发送到蓝牙 LE 设备,因此应用程序不会收到任何通知。

我知道并非所有 UWP API 都可以从非 UWP 应用程序中使用,但我希望有人已经成功开发了这种配置的 BLE 应用程序(或者至少现在可以确认这是不可能的)。在创作者更新之前,我能够从 BLE 设备连接和读取数据以及将数据写入到 BLE 设备,并且只有在这个最新版本的 Windows 10 中才会出现上述问题。(注意:示例代码中使用的 Async API 是在 Creators Update 中添加的。我们的应用程序的早期版本使用的是较旧的 BLE API,但在运行 Creators Update 时它们也不起作用。)

具体来说,我的问题是:鉴于以下项目参考列表和示例代码,我是否可以尝试在运行非 UWP 应用程序的 Creators Update 的 Windows 10 上实现蓝牙 LE 连接?请注意,“将应用程序转换为 UWP 应用程序”的明显答案对我们不起作用,因为我们与其他硬件和文件的交互方式在 UWP 沙箱中是不可能的。

该项目配置了以下参考:

  • System.Runtime.WindowsRuntime,位于:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
  • Windows,位于:C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.WinMD
  • Windows.Foundation.FoundationContract,位于:C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.Foundation.FoundationContract\3.0.0.0\Windows.Foundation.FoundationContract.winmd
  • Windows.Foundation.UniversalApiContract,位于:C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.Foundation.UniversalApiContract\4.0.0.0\Windows.Foundation.UniversalApiContract.winmd

以下是我的应用程序中蓝牙代码的一个非常精简的版本。请注意,为了清楚起见,已经删除了很多错误处理等,但它应该让我大致了解我正在尝试做的事情:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Storage.Streams;
using System.Threading;

namespace BLEMinimumApp
{
    class Program
    {
        private List<string> foundDevices = new List<string>(5);

        static void Main(string[] args)
        {
            new Program().Execute();
        }

        private void Execute()
        {
            Console.WriteLine("Starting device watcher...");

            string[] requestedProperties = { "System.Devices.Aep.IsConnected" };
            String query = "";
            //query for Bluetooth LE devices
            query += "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
            //query for devices with controllers' name
            query += " AND (System.ItemNameDisplay:=\"GPLeft\" OR System.ItemNameDisplay:=\"GPRight\")";

            var deviceWatcher = DeviceInformation.CreateWatcher(query, requestedProperties, DeviceInformationKind.AssociationEndpoint);
            deviceWatcher.Added += DeviceWatcher_OnAdded;
            deviceWatcher.Start();

            Console.ReadLine();
        }

        private async void DeviceWatcher_OnAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
        {
            lock (foundDevices)
            {
                if (foundDevices.Contains(deviceInfo.Name))
                {
                    return;
                }
                foundDevices.Add(deviceInfo.Name);
            }

            Console.WriteLine($"[{deviceInfo.Name}] DeviceWatcher_OnAdded...");
            await ConnectTo(deviceInfo);
        }

        private async Task ConnectTo(DeviceInformation deviceInfo)
        {
            try
            {
                // get the device
                BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
                Console.WriteLine($"[{device.Name}] Device found: connectionStatus={device?.ConnectionStatus}");

                // get the GATT service
                Thread.Sleep(150);
                Console.WriteLine($"[{device.Name}] Get GATT Services");
                var gattServicesResult = await device.GetGattServicesForUuidAsync(new Guid("<GUID REMOVED FOR SO POST"));
                Console.WriteLine($"[{device.Name}] GATT services result: status={gattServicesResult?.Status}, count={gattServicesResult?.Services?.Count}, cx={device.ConnectionStatus}");

                if (gattServicesResult == null 
                    || gattServicesResult.Status != GattCommunicationStatus.Success 
                    || gattServicesResult.Services == null 
                    || gattServicesResult.Services?.Count < 1)
                {
                    Console.WriteLine($"[{device.Name}] Failed to find GATT service.");
                    return;
                }

                var service = gattServicesResult.Services[0];
                Console.WriteLine($"[{device?.Name}] GATT service found: gattDeviceService={service.Uuid}");

                // get the GATT characteristic
                Thread.Sleep(150);
                Console.WriteLine($"[{device.Name}] Get GATT characteristics");
                var gattCharacteristicsResult = await service.GetCharacteristicsForUuidAsync(new Guid("<GUID REMOVED FOR SO POST>"));
                Console.WriteLine($"[{device.Name}] GATT Characteristics result: status={gattCharacteristicsResult?.Status}, count={gattCharacteristicsResult?.Characteristics?.Count}, cx={device.ConnectionStatus}");

                if (gattCharacteristicsResult == null
                    || gattCharacteristicsResult.Status != GattCommunicationStatus.Success
                    || gattCharacteristicsResult.Characteristics == null
                    || gattCharacteristicsResult.Characteristics?.Count < 1)
                {
                    Console.WriteLine($"[{device.Name}] Failed to find GATT characteristic.");
                    return;
                }

                var characteristic = gattCharacteristicsResult.Characteristics[0];

                // register for notifications
                Thread.Sleep(150);

                characteristic.ValueChanged += (sender, args) =>
                {
                    Console.WriteLine($"[{device.Name}] Received notification containing {args.CharacteristicValue.Length} bytes");
                };
                Console.WriteLine($"[{device.Name}] Writing CCCD...");
                GattWriteResult result =
                    await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
                Console.WriteLine($"[{device?.Name}] Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}");

                // send configuration to device 
                await SendConfiguration(device, characteristic);
            }
            catch (Exception ex) when((uint) ex.HResult == 0x800710df)
            {
                Console.WriteLine("bluetooth error 1");
                // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
            }
        }

        private async Task SendConfiguration(BluetoothLEDevice device, GattCharacteristic characteristic)
        {
            if (characteristic != null)
            {
                var writer = new DataWriter();
                // CONFIGURATION REMOVED, but this code writes device-specific bytes to the DataWriter

                await SendMessage(device, characteristic, writer.DetachBuffer());
            }
        }

        private async Task SendMessage(BluetoothLEDevice device, GattCharacteristic characteristic, IBuffer message)
        {
            if (characteristic != null && device.ConnectionStatus.Equals(BluetoothConnectionStatus.Connected) && message != null)
            {
                Console.WriteLine($"[{device.Name}] Sending message...");
                GattCommunicationStatus result = await characteristic.WriteValueAsync(message);
                Console.WriteLine($"[{device.Name}] Result: {result}");
            }
        }
    }
}
4

2 回答 2

1

COM 安全可能会阻止您的应用接收通知。请参阅以下线程以获取解决方案。我建议使用注册表黑客。

https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/bluetooth-bluetoothledevicefromidasync-does-not-complete-on-10015063?forum=wdk

我遇到了类似的问题,并且通过上述注册表更改,我的应用程序收到的通知很少,并且没有任何明显的原因停止。在这个问题上浪费了很多时间,等待微软的补丁。

于 2017-08-30T14:59:53.033 回答
1

最新的更新更正了这一点。您还可以使用 Matt Beaver 在另一张海报引用的链接上的说明解决此问题。

基本上要么:

  1. 为您的应用程序指定AppId
  2. 在您的应用程序中调用CoInitializeSecurity以允许我们回调
于 2017-08-31T01:21:31.477 回答