我试图按照这里的示例创建将充当蓝牙LE外围设备的UWP应用程序: https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-server 但尝试响应特征性读取请求与request.RespondWithValue我收到一个异常: System.Exception:'该对象已被提交。 (异常来自HRESULT:0x8000001E)”如何响应UWP应用程序中的蓝牙LE特征读取请求
如果我设置为特性的静态值,该值被正确读取
ReadParameters.StaticValue = (new byte[] { 0x21 }).AsBuffer();
我试图在Windows 10 PC和Windows 10物联网核心上的代码都并得到相同的例外。
是否还有其他需要响应读取请求?
public sealed partial class MainPage : Page
{
GattLocalCharacteristic _readCharacteristic;
GattServiceProvider _serviceProvider;
public MainPage()
{
this.InitializeComponent();
SetupBle();
}
public async Task<bool> SetupBle()
{
GattServiceProviderResult result = await GattServiceProvider.CreateAsync(GattServiceUuids.Battery);
if (result.Error == BluetoothError.Success)
{
_serviceProvider = result.ServiceProvider;
var ReadParameters = new GattLocalCharacteristicParameters();
ReadParameters.CharacteristicProperties = GattCharacteristicProperties.Read;
ReadParameters.UserDescription = "Battery service";
//ReadParameters.StaticValue = (new byte[] { 0x21 }).AsBuffer(); //if this is uncommented the static battery level value is read correctly
GattLocalCharacteristicResult characteristicResult = await _serviceProvider.Service.CreateCharacteristicAsync(GattCharacteristicUuids.BatteryLevel,
ReadParameters);
if (characteristicResult.Error != BluetoothError.Success)
{
return false;
}
_readCharacteristic = characteristicResult.Characteristic;
_readCharacteristic.ReadRequested += _readCharacteristic_ReadRequested;
GattServiceProviderAdvertisingParameters advParameters = new GattServiceProviderAdvertisingParameters
{
IsDiscoverable = true,
IsConnectable = true
};
_serviceProvider.StartAdvertising(advParameters);
return true;
}
return false;
}
private async void _readCharacteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
{
var writer = new DataWriter();
writer.WriteByte(0x21);
var request = await args.GetRequestAsync();
request.RespondWithValue(writer.DetachBuffer());//will throw System.Exception: 'The object has been committed. (Exception from HRESULT: 0x8000001E)'
}
}