我正在尝试按照此处的示例创建一个充当蓝牙LE外设的UWP应用程序: https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-server 但是当尝试使用request.RespondWithValue响应特征读取请求时,我得到一个异常: System.Exception:'该对象已提交。 (来自HRESULT的异常:0x8000001E)'
如果我为特征设置静态值,则正确读取值
ReadParameters.StaticValue = (new byte[] { 0x21 }).AsBuffer();
我在Windows 10 PC和Windows 10 IoT Core上都尝试了这些代码并得到了同样的例外。
响应读取请求还有其他需要吗?
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)'
}
}
答案 0 :(得分:0)
根据这里的评论 https://blogs.msdn.microsoft.com/btblog/2017/05/11/welcome-to-the-new-windows-bluetooth-core-team-blog/#comment-105 和评论https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/gatt-server 文档已经过时且不正确。
此代码适用于我:
private async void _readCharacteristic_ReadRequested(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
{
var deferral = args.GetDeferral();
var writer = new DataWriter();
writer.WriteByte(0x21);
var request = await args.GetRequestAsync();
request.RespondWithValue(writer.DetachBuffer());
deferral.Complete();
}