在Swift for Mac上,BLE的数据类型转换

时间:2016-07-02 09:13:07

标签: ios swift macos bluetooth-lowenergy core-bluetooth

我有一个问题。我正在尝试与Mi Band接口。在github上找到这段代码,效果很好。但是,我不明白数据类型转换发生了什么。

            var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory

来自此代码块:

    func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {

    output("Data for "+characteristic.UUID.UUIDString, data: characteristic.value!)

    if(characteristic.UUID.UUIDString == "FF06") {
        spinnerView.hidden = true
        let u16 = UnsafePointer<Int>(characteristic.value!.bytes).memory
        stepsView.stringValue = ("\(u16) steps")
    } else if(characteristic.UUID.UUIDString == "FF0C") {
        spinnerView.hidden = true
        var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory
        u16 =  u16 & 0xff
        batteryView.stringValue = ("\(u16) % charged")
    } 


}

有人可以向我解释一下吗?谢谢!

2 个答案:

答案 0 :(得分:0)

此部分获取内存中的地址:

characteristic.value!.bytes

.bytes的返回类型为UnsafePointer<Void>,因此将其转换为UnsafePointer<Int32>类型,即Swift等效于指向32位整数的C指针(int32_t* ptr;)。

UnsafePointer<Int32>(characteristic.value!.bytes)

在Swift中,您可以使用.memory获取此类指针的内容(在C中它将是*ptr)。因此u16变量是类型Int32的值(该内存位置的内容,解释为Int32)。

var u16 = UnsafePointer<Int32>(characteristic.value!.bytes).memory

下一行屏蔽所有高24位,只留下该值的最低8位,然后将其打印为电池百分比。

答案 1 :(得分:0)

Swift 3

  if you have this kind of characteristic :

 <CBCharacteristic: 0x26e42b42, UUID = Battery, properties = 0x33, 
  value = <4d455348 54454348 204153>, notifying = NO>


  then use this type code:
  let value = [UInt8](characteristic.value!)
相关问题