簡體   English   中英

在Mac的Swift上,BLE的數據類型轉換

[英]On Swift for Mac, data type conversion for BLE

我有個問題。 我正在嘗試與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")
    } 


}

有人可以向我解釋嗎? 謝謝!

這部分獲取內存中的地址:

characteristic.value!.bytes

但是.bytes的返回類型為UnsafePointer<Void> ,因此將其轉換為UnsafePointer<Int32>類型,該類型與32位整數C指針的Swift等效( 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位,然后將其打印為電池百分比。

迅捷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!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM