我一直在通过分析广告数据来确定BLE设备是否可连接.这是我的代码示例和学习指南



我正在使用Ionic React。从设备接收到的广告数据是ArrayBuffer格式的,我从ArrayBuff中获取UInt8Array,然后使用以下函数对其进行解析:

function asHexString(i: any) {
var hex;
hex = i.toString(16);
// zero padding
if (hex.length === 1) {
hex = "0" + hex;
}
return "0x" + hex;
}
export const parseAdvertisingData = (buffer: any) => {
var length, type, data, i = 0, advertisementData = {};
var bytes = new Uint8Array(buffer);
while (length !== 0) {
length = bytes[i] & 0xFF;
i++;
// decode type constants from https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile
type = bytes[i] & 0xFF;
i++;
data = bytes.slice(i, i + length - 1).buffer; // length includes type byte, but not length byte
i += length - 2;  // move to end of data
i++;
// @ts-ignore
advertisementData[asHexString(type)] = data;
}
return advertisementData;
}

这返回了ArrayBuffer的对象,其中一个具有键0x19(外观数据(,另一个具有0xff(制造商数据(

然后我转换了两个ArrayBuffer->UInt8数组到十六进制字符串,得到以下结果:

收到的播发原始数据:0x031919001AFF580015E8FF000000000C0011D400000000000000001010000

Len
30x190x1900
260x260x580015E8FF000000000C0011D400000000000000001010000

正在检查的缓冲区中的播发数据是有效负载的一部分,不包含PDU标头中的信息。PDU类型指示它是否可连接。我不知道你的javascript BLE库中是如何公开哪些BLE功能的,但至少在Android上你可以使用https://developer.android.com/reference/android/bluetooth/le/ScanResult#isConnectable((来确定它是否可连接。

最新更新