我是蓝牙LE编程中的新手。我已经构建了正在为Android开发的程序,现在我正在尝试将其移植到C#/Windows IoT。
我正在尝试阅读以BLE广告包中发送的健康温度计数据。每次我尝试访问设备的Gatt服务时,我的代码都会引发一个例外:
private TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs> OnAdvertisementReceived = async (w, eventArgs) =>
{
BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
try
{
var SERVICEUUID = eventArgs.Advertisement.ServiceUuids.FirstOrDefault();
var CHARACUUID = new Guid("00001809-0000-1000-8000-00805f9b34fb");
//FIXME: Getting invalid cast exception at this point
var gatt = await device.GetGattServicesForUuidAsync(SERVICEUUID);
Debug.WriteLine($"{device.Name} Services: {gatt.Services.Count}, {gatt.Status}, {gatt.ProtocolError}");
var characs = await gatt.Services.Single(s => s.Uuid == SERVICEUUID).GetCharacteristicsAsync();
var charac = characs.Characteristics.Single(c => c.Uuid == CHARACUUID);
//TODO: Parse temperature value to float
var val = await charac.ReadValueAsync();
}
catch (Exception e)
{
Debug.WriteLine("Error getting characteristics: " + e);
}
};
我得到的例外是:
System.InvalidCastException: Unable to cast object of type 'Windows.Devices.Bluetooth.BluetoothLEDevice' to type 'Windows.Devices.Bluetooth.IBluetoothLEDevice3'
at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)
at Windows.Devices.Bluetooth.BluetoothLEDevice.GetGattServicesForUuidAsync(Guid serviceUuid)
蓝牙神灵显然实现了ibluetoothledevice3接口,因此我不明白如何无法施放它。关于为什么会发生这种情况的任何帮助。如果这很重要,我的设备是覆盆子PI3。预先感谢!
更新:
在调试代码时,我看到蓝牙的deviceAccessInformation属性会引发异常,并将其传播到最高级别:
deviceaccessInformation ='device.deviceaccessinformation' 类型" system.invalidcastException"
的例外
update2
当我尝试直接访问Gatt服务时,我会得到不同的例外:
BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
var gattService = await GattDeviceService.FromIdAsync(device.DeviceId);
在这种情况下的例外是
system.io.io.filenotfoundexception:系统找不到文件 指定的。(Hresult的例外:0x80070002( system.runtime.compilerservices.taskawaiter.throwfornonsuccess(任务 任务( system.runtime.compilerservices.taskawaiter.handlenonsuccessanddebuggernotification(任务 任务( 在stemphub.startuptask。&lt;> c。
GetGattServicesForUuidAsync()
API是在v10.0.14965中新引入的,但在此版本中未实现,并且在15003年实现,您可以检查Windows 10 SDK Preview build build 14965释放和Windows 10 SDK Preview 15003 build 15003 build 15003 build 15003发行。
因此,您可能需要Windows Iot Core版本15003或更高版本。