我遇到了来自Windows 10蓝牙低功耗(BLE)API的BluetoothLEAdvertisementDataSection.BluetoothLEAdvertisementDataSection class问题.
如果我使用以下代码检查IBuffer成员数据的长度:
var myDataSection = new BluetoothLEAdvertisementDataSection();
Debug.WriteLine($"Data Capacity: {myDataSection.Data.Capacity}"); //Looks like SO needs to update for C# 6.0
我得到了预期的输出:
Data Capacity: 29
有关BLE数据包的更多信息,我建议访问this great blog post.
现在让我们说我已经声明了一个名为myPayload的byte [],它长29个字节.以下代码抛出异常:
DataWriter writer = new DataWriter();
writer.WriteBytes(myPayload);
myDataSection.Data = writer.DetachBuffer(); //throws ArgumentException
ArgumentException非常有用地表明了这一点
“Value does not fall within the expected range.”
实际上,20个字节的myPayload的任何大小都会导致相同的错误.但是,如果我把它设为19个字节,我就没有错误.
是的,当this answer没有帮助时,我感到非常沮丧.
解决方法:
这真的很难过……但实际上我错误地计算了我添加的字节数. 29个字节确实有效. 30没有.这不是API问题.
static readonly byte[] myPayload =
{0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF, //8 bytes
0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF, //8 bytes
0x01,0x23,0x45,0x67,0x89,0xAB,0xCD,0xEF, //8 bytes
0x00,0x00,0x00,0x00,0x00}; //5 bytes Total:29 bytes
……会工作得很好.