BluetoothLEAdvertisementDataSection (ArgumentException)

BluetoothLEAdvertisementDataSection (ArgumentException)

我正在尝试宣传 Eddystone 信标,但我的代码在 advertisementData.Data 处失败并出现 A​​rgumentException:

Value does not fall within the expected range.

知道发生了什么事吗?

// ...
using (var memoryStream = new MemoryStream())
{
    byte messageLengthByte = Convert.ToByte(message.Length);
    memoryStream.WriteByte(messageLengthByte);

    memoryStream.Write(message, 0, message.Length);

    fullMessage = memoryStream.ToArray();
}

while (fullMessage.Length < 32)
{
    byte[] newArray = new byte[fullMessage.Length + 1];
    fullMessage.CopyTo(newArray, 0);
    newArray[fullMessage.Length] = 0x00;
    fullMessage = newArray;
}

var writer = new DataWriter();
writer.WriteBytes(fullMessage);

var advertisementData = new BluetoothLEAdvertisementDataSection();
advertisementData.Data = writer.DetachBuffer(); // Error!
publisher.Advertisement.DataSections.Add(advertisementData);
publisher.Start();

很可能您正试图容纳比 BLE 数据包允许的更多字节。最大大小为 32 字节,但其中包括:

  • 3 个字节用于 "flags" 数据部分,我认为这是强制性的并且可能由 Windows 10 BLE API
  • 自动设置
  • 每增加一个节,节的长度为 1 个字节,节的类型为 1 个字节

如果您只广播一个部分,那么该部分的实际有效载荷将剩下 27 个字节。