我正在使用BLE设备。设备正在发送特定UUID中的值。
这是我的代码,用于将数据转换为Int或String进行显示。

...
else if characteristic.uuid == CBUUID(string: UUID_CHANGEIN_BATTERY_LEVEL) {
//            let battery = UInt32(bigEndian: ((characteristic.value?.withUnsafeBytes { $0.pointee }) ?? 0))
            let array : [UInt8] = [0, 0, 0]
            var data = Data(bytes: array)
            if characteristic.value != nil {
                data.append(characteristic.value!)
            }
            let battery = UInt32(bigEndian: ((data.withUnsafeBytes { $0.pointee }) ?? 0))
            print("battery level changed\nNew level is \(getInt(fromData: characteristic.value!, start: 0))!")
//            lblBattery.text = (String(data: characteristic.value!, encoding: String.Encoding.utf8) ?? "0") + "%"
            lblBattery.text = "\(getInt(fromData: characteristic.value!, start: 0))%"

        }
...
func getInt(fromData data: Data, start: Int) -> Int32 {
        let intBits = data.withUnsafeBytes({(bytePointer: UnsafePointer<UInt8>) -> Int32 in
            bytePointer.advanced(by: start).withMemoryRebound(to: Int32.self, capacity: 4) { pointer in
                return pointer.pointee
            }
        })
        return Int32(bigEndian: intBits)
//        return Int32(littleEndian: intBits)
    }


我已经签入BLE Scanner iOS应用程序,该应用程序将0x2b01显示为值,并且还将43显示为电池百分比。
如上所示,我编写了3-4种代码。
但是他们都没有给我43的价值。

请帮助我找到我做错了什么地方或我想满足我的要求而错过的地方。

最佳答案

迅捷3

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

   let value = [UInt8](characteristic.value!)

   print("Battery ", value[0], "%")
}

07-25 23:20
查看更多