I'm working with BLE device. Device is sending values in specific UUID.
Here is my code for converting Data to Int or String for display.
...
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)
}
I've checked in BLE Scanner iOS app, that is displaying 0x2b01
as value and it also display 43 as a battery %.
I wrote 3-4 kind of code as you see above.
But none of them are giving me 43 as a value.
Please help me find where I've done something wrong or which I'm missing to meet my requirement.
swift 3
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let value = [UInt8](characteristic.value!)
print("Battery ", value[0], "%")
}