我已连接到具有健康温度计服务(0x1809)的BLE设备。我正在尝试将温度测量特征(0x2A1C)从字节解码为摄氏温度。
按this old Swift 2 post进行操作,我相信代码的主要问题是由于Swift的Float类型和蓝牙Float类型不同。
感谢您的帮助!
private func temperatureMeasurement(from characteristic: CBCharacteristic) -> Float {
guard let characteristicData = characteristic.value else { return -1 }
var byteArray = [UInt8](characteristicData)
let flags = byteArray[0]
let temperatureIsInFahrenheit = (flags & 0x01) != 0
let hasTimestamp = (flags & 0x02) != 0
let hasTemperatureType = (flags & 0x04) != 0
let mantissa1 = Float(byteArray[1])
let mantissa2 = Float(byteArray[2]) * 256
let mantissa3 = Float(byteArray[3]) * 256 * 256
let mantissa = mantissa1 + mantissa2 + mantissa3
let exponent = Float(byteArray[4])
let temperatureMeasurement = mantissa * pow(10, exponent)
return temperatureMeasurement
}