【问题标题】:UWP Bluetooth LE InvalidCastExceptionUWP 蓝牙 LE InvalidCastException
【发布时间】:2017-10-26 14:03:30
【问题描述】:

我想将 myo 腕带连接到 hololens。这是最终目标,但无论如何我已经接近了:-/

这个想法是与 UWP 建立蓝牙 LE 连接。 我想这样做,正如Microsoft Document中所解释的@

设备的搜索工作正常,但是当我尝试连接到设备时,这条线(点“连接到设备” ):GattDeviceServicesResult result = await device.GetGattServicesAsync();

引发错误:

System.InvalidCastException:“无法转换类型的对象 'Windows.Devices.Bluetooth.BluetoothLEDevice' 输入 'Windows.Devices.Bluetooth.IBluetoothLEDevice3'。"

我不知道 IBluetoothLEDevice3 必须在那里做什么 :-) 我无法在微软文档或互联网上找到解决方案:-/

我在 Visual Studio 2017 上工作,为 Windows 10 (15063) 构建,并且在清单中启用了蓝牙。

这是我的代码。我只添加了一件事,那就是任务。我想确保 BluetoothLEDDevice 不是 null 或任何东西,因为它不是同步的。没有它也不起作用。

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;
                // ...
            }

        }
    }
}

谢谢

【问题讨论】:

  • 你的 hololens 操作系统版本是多少?
  • 它的 10.0.14393.0 但我目前不在 HoloLens 上工作。我正在尝试在普通的 Windows 10 计算机上进行设置,这就是发生错误的地方。

标签: c# visual-studio uwp bluetooth-lowenergy myo


【解决方案1】:

如果您将应用程序定位到 Build 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;
               }
            }
         }
      }
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 2018-03-02
    • 2015-06-09
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多