UWP Bluetooth LE InvalidCastException

Я хочу подключить браслет myo к гололинзам. Это конечная цель, но я в любом случае близок к этому :-/

Идея состоит в том, чтобы настроить соединение Bluetooth LE с UWP. Я хотел сделать это, как описано в этом документе Microsoft.

Поиск устройств работает нормально, но при попытке подключиться к устройству эта строка (Пункт "Подключение к устройству"): GattDeviceServicesResult result = await device.GetGattServicesAsync();

вызывает ошибку:

System.InvalidCastException: «Невозможно привести объект типа Windows.Devices.Bluetooth.BluetoothLEDevice к типу Windows.Devices.Bluetooth.IBluetoothLEDevice3».

Я понятия не имею, что там должен делать IBluetoothLEDevice3 :-) Мне не удалось найти решение для этого в документации Microsoft или в Интернете :-/

Я работаю на Visual Studio 2017, сборка для Windows 10 (15063) и Bluetooth включен в манифесте.

Это мой код, так что прощайте. Я добавил только одну вещь, и это Задача. Я хотел убедиться, что BluetoothLEDDevice не является нулевым или чем-то еще, поскольку он не синхронизирован. Без него тоже не работает.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth.Advertisement;


// Die Elementvorlage "Leere Seite" wird unter https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x407 dokumentiert.

namespace Bluetooth17
{
    /// <summary>
    /// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann.
    /// </summary>
    public sealed partial class MainPage : Page    
    {


        public MainPage()
        {
            this.InitializeComponent();

            blue();

        }



        void blue()
        {
            // Query for extra properties you want returned
            string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };

            DeviceWatcher deviceWatcher =
                        DeviceInformation.CreateWatcher(
                                BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
                                requestedProperties,
                                DeviceInformationKind.AssociationEndpoint);

            // Register event handlers before starting the watcher.
            // Added, Updated and Removed are required to get all nearby devices
            deviceWatcher.Added += DeviceWatcher_Added;
            deviceWatcher.Updated += DeviceWatcher_Updated;
            deviceWatcher.Removed += DeviceWatcher_Removed;

            // EnumerationCompleted and Stopped are optional to implement.
            deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
            deviceWatcher.Stopped += DeviceWatcher_Stopped;

            // Start the watcher.
            deviceWatcher.Start();
        }

        private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
        {
            Debug.WriteLine("Stopped");
        }

        private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
        {
            Debug.WriteLine("Enum complete");
        }

        private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
        {
            Debug.WriteLine(args.Id + "  Removed");
        }

        private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
        {
            Debug.WriteLine(args.Id + " Update");
        }

        private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
        {
            Debug.WriteLine(args.Id + "       " + args.Name);

            if (args.Name.Equals("Myo"))
            {
                Debug.WriteLine("Try to connect to Myo");
                getServices(args);
            }
        }

        async Task<BluetoothLEDevice> ConnectDevice(DeviceInformation deviceInfo)
        {
            Debug.WriteLine("Asyc");
            // Note: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
             return await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);


        }


        async void getServices(DeviceInformation deviceInfo)
           {

            Task<BluetoothLEDevice> task = ConnectDevice(deviceInfo);

            task.Wait();

            BluetoothLEDevice device = task.Result;

            GattDeviceServicesResult result = await device.GetGattServicesAsync();

            if (result.Status == GattCommunicationStatus.Success)
            {
                var services = result.Services;
                // ...
            }

        }
    }
}

Спасибо


person Marcel    schedule 25.05.2017    source источник
comment
Какая у вас версия hololens?   -  person Rita Han    schedule 26.05.2017
comment
Это 10.0.14393.0, но в данный момент я не работаю над HoloLens. Я пытаюсь настроить его на обычном компьютере с Windows 10, и здесь возникает ошибка.   -  person Marcel    schedule 26.05.2017


Ответы (1)


Если вы нацеливаете свое приложение на сборку 15063 и знаете устройство, к которому подключаетесь, чем просто используйте:

device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);  

Это гораздо более стабильно, чем ваш код, и вам не нужен наблюдатель за устройствами. Вот пример, который работает для моего устройства (не MIO, а HM10):

using System;
using System.Diagnostics;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.UI.Xaml.Controls;

namespace App1
{    
   public sealed partial class MainPage : Page
   {
      private BluetoothLEDevice device;
      GattDeviceServicesResult serviceResult = null;
      public MainPage()
      {
         this.InitializeComponent();
         StartDevice();
      }

      private async void StartDevice()
      {
         //To get your blueToothAddress add: ulong blueToothAddress = device.BluetoothAddress to your old code.
         ulong blueToothAddress = 88396936323791; //fill in your device address!!
         device = await BluetoothLEDevice.FromBluetoothAddressAsync(blueToothAddress);         
         if (device != null)
         {
            string deviceName = device.DeviceInformation.Name;
            Debug.WriteLine(deviceName);
            int servicesCount = 3;//Fill in the amount of services from your device!!
            int tryCount = 0;
            bool connected = false;
            while (!connected)//This is to make sure all services are found.
            {
               tryCount++;
               serviceResult = await device.GetGattServicesAsync();

               if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount)
               {
                  connected = true;
                  Debug.WriteLine("Connected in " + tryCount + " tries");
               }
               if (tryCount > 5)//make this larger if faild
               {
                  Debug.WriteLine("Failed to connect to device ");
                  return;
               }
            }
         }
      }
   }
}
person GrooverFromHolland    schedule 28.05.2017