我一直试图在BLE服务特征值中访问数据几天。我想找出如何将Temperature Sensor示例翻译成Swift会有所帮助,但我会陷入同一地点。
如何翻译Obj-C:
- (CGFloat) maximumTemperature
{
CGFloat result = NAN;
int16_t value = 0;
if (maxTemperatureCharacteristic) {
[[maxTemperatureCharacteristic value] getBytes:&value length:sizeof (value)];
result = (CGFloat)value / 10.0f;
}
return result;
}
到Swift 3?
而不是CGFloat,在我的代码中我使用的是struct:
struct MPUData {
let x: Int16
let y: Int16
let z: Int16
}
并从特征中接收8字节值,前六个是x,y和z分量(即0x0D0E0F00
其中x = 0x0D
,y = 0x0E
,{{1}并且最后一个字节未使用)
我不知道如何遍历这些位并将它们存储为Int16值。任何帮助将不胜感激。
答案 0 :(得分:2)
尝试使用withUnsafeBytes
:
//Assuming `data` as `someCharacteristic.value!`
//Create 4 Int16 data in little endian
let data = Data(bytes: [0x0D, 0, 0x0E, 0, 0x0F, 0, 0, 0])
struct MPUData {
let x: Int16
let y: Int16
let z: Int16
}
let mpuData = data.withUnsafeBytes {(int16Ptr: UnsafePointer<Int16>)->MPUData in
MPUData(x: Int16(littleEndian: int16Ptr[0]),
y: Int16(littleEndian: int16Ptr[1]),
z: Int16(littleEndian: int16Ptr[2]))
}
print(mpuData.x,mpuData.y,mpuData.z) //->13 14 15