Проблемы с перечислением устройств BLE в приложении Win32 для настольных ПК с использованием UWP API - PullRequest
0 голосов
/ 02 февраля 2019

Я пытаюсь добавить функциональность BLE в классическое (WinForms?) Настольное приложение C # и добавила ссылки (Windows.winmd и System.Runtime.WindowsRuntime), чтобы позволить мне получить доступ к новому API BLE, недавно представленному Microsoft дляПриложения для Windows 10 UWP.Мне нужно создать классическое настольное приложение, так как мне нужно использовать более старую оболочку устройства драйвера (teVirtualMIDI) и я хочу создать .exe, а не пакет приложения.

Я ссылаюсь на вышеупомянутые библиотеки из следующихместоположения ...

C: \ Program Files (x86) \ Windows Kits \ 10 \ UnionMetadata \ Facade \ Windows.WinMD

C: \ Program Files (x86) \ Справочные сборки \ Microsoft\ Framework.NETCore \ v4.5 \ System.Runtime.WindowsRuntime.dll

C: \ Program Files (x86) \ Справочные сборки \ Microsoft \ Framework.NETCore \ v4.5 \ System.Runtime.WindowsRuntime.UI.Xaml.dll

На данный момент я просто хочу иметь возможность просматривать подключенные службы и характеристики в окне вывода отладки, как это сделано в этом сообщении в блоге ...

https://blogs.msdn.microsoft.com/cdndevs/2017/04/28/uwp-working-with-bluetooth-devices-part-1/

Кажется, что я получаю ошибки, потому что API BLE должен выполнять асинхронные операции, но я, честно говоря, в растерянности.Код, который я написал, приведен ниже.По сути, я получаю ошибки при попытке вызвать метод «GetGattServicesAsync ()», так как Visual Studio говорит, что класс «BluetoothLEDevice» не содержит такого определения.Однако этот метод включен в онлайн-документацию, и мне интересно, почему я не могу получить к нему доступ.

Я надеюсь, что предоставил достаточно информации, и любая помощь в решении этой проблемы будет более чем признательна.Спасибо всем за полезные советы, которые вы даете!

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Windows.Devices.Bluetooth;
using Windows.Devices.Midi;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace BDBMidiClient
{
    public class BLEHandlingDiscovery : Page
    {
    //private ObservableCollection<BluetoothLEAttributeDisplay> ServiceCollection = new ObservableCollection<BluetoothLEAttributeDisplay>();
    //private ObservableCollection<BluetoothLEAttributeDisplay> CharacteristicCollection = new ObservableCollection<BluetoothLEAttributeDisplay>();
    public ObservableCollection<BluetoothLEDeviceDisplay> KnownDevices = new ObservableCollection<BluetoothLEDeviceDisplay>();
    //private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();
    //private DeviceWatcher deviceWatcher;
    //private BluetoothLEDevice bluetoothLeDevice = null;
    //private GattCharacteristic selectedCharacteristic;

    private void StartBLEDeviceWatcher()
    {
        string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

        DeviceWatcher deviceWatcher =
                    DeviceInformation.CreateWatcher(
                            BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                            requestedProperties,
                            DeviceInformationKind.AssociationEndpoint);
        /*
        DeviceWatcher deviceWatcher =
        DeviceInformation.CreateWatcher(
                "System.ItemNameDisplay:~~\"BDB\"",
                requestedProperties,
                DeviceInformationKind.AssociationEndpoint);*/


        deviceWatcher.Added += DeviceWatcher_Added;
        deviceWatcher.Updated += DeviceWatcher_Updated;
        deviceWatcher.Removed += DeviceWatcher_Removed;

        deviceWatcher.Start();

        //Debug.WriteLine(requestedProperties);
    }


    private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
    {
        Guid gattService = new Guid();

        var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
        var services=await device.GetGattServicesAsync();
        foreach (var service in services.Services)
        {
            Debug.WriteLine($"Service: {service.Uuid}");
            var characteristics = await service.GetCharacteristicsAsync();
            foreach (var character in characteristics.Characteristics)
            {
                Debug.WriteLine($"Characteristic: {character.Uuid}");
            }
        }
    }


    private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
    {

    }


    private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
    {

    }

    async void ConnectToBLEDevice(DeviceInformation deviceInformation)
    {
        BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BDB");
    }


    private BluetoothLEDeviceDisplay FindBluetoothLEDeviceDisplay(string id)
    {
        foreach (BluetoothLEDeviceDisplay bleDeviceDisplay in KnownDevices)
        {
            if (bleDeviceDisplay.Id == id)
            {
                return bleDeviceDisplay;
            }
        }
        return null;
    }
}

1 Ответ

0 голосов
/ 04 февраля 2019

В документе сказано, что API принадлежит «Обновлению создателей Windows 10 (введено 10.0.15063.0)».Поэтому, пожалуйста, попробуйте добавить один из "C: \ Program Files (x86) \ Windows Kits \ 10 \ UnionMetadata \ 10.0.15063.0 \ Windows.winmd"

Вот результат из моего проекта enter image description here Вы видите, что мой код работает хорошо.

...