CoreBluetooth - 获取 BLE 通用属性配置文件原始字节

CoreBluetooth - get BLE Genertic Attribute Profile raw bytes

我有一个视图控制器,它扫描 广告的 BLE 信标,现在允许传入连接。通过检查广告的服务数据部分 (CBAdvertisementDataServiceDataKey),我可以看到我想要的字节,但实际上我无法访问数据的原始字节作为变量。

这是 CM 回调:

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    var advBytes: String!
    
    if let dictionary = advertisementData[CBAdvertisementDataServiceDataKey] as? [String: Any] {
        if let gatt = dictionary["Generic Attribute Profile"] as? [String: String] {
            advBytes = gatt["bytes"]?[2...]
        } else {
            print("Can't convert byte array to string")
        }
    }
    else {
        print("Couldn't decode advertisement \(advertisementData[CBAdvertisementDataServiceDataKey])")
    }

当代码为运行时,控制台输出:

Couldn't decode advertisement Optional({
    "Generic Attribute Profile" = {length = 7, bytes = 0x6413000a000000};
})

如何将 GATT 的 bytes 部分作为变量访问?

根据 CBAdvertisementDataServiceDataKey 的文档,该值为 [CBUUID: Data]

所以应该是:

if let dictionary = advertisementData[CBAdvertisementDataServiceDataKey] as? [CBUUID: Data] {

}

现在,如果我没记错的话,您要查找 GATT 的服务 ID 是 1801。只是 Apple 自动将其翻译成人类可读的“通用属性配置文件”。你可以用这个来测试它:

let service = CBUUID(string: "1801")
print("Service UUID: \(service.uuidString) - \(service)")

他们必须覆盖 CBUUID 的描述才能在已知 UUID 时打印“单词”。

现在,您可以这样做:

let genericAttributeProfileData = dictionary[CBUUID(string: "1801")]
let subData = genericAttributeProfileData[0...0]
// etc.