0

I've been trying to access the data in a BLE service characteristic value for a few days now. I thought figuring out how to translate the Temperature Sensor example to Swift would be helpful, but I get stuck at the same spot.

How do I translate the 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;
}

to Swift 3?

Instead of a CGFloat, in my code I am using the struct:

struct MPUData {
    let x: Int16
    let y: Int16
    let z: Int16
}

and am receiving an 8 byte value from the characteristic with the first six being the x, y, and z components (i.e 0x0D0E0F00 where x = 0x0D, y = 0x0E, z = 0x0F and the last byte is unused)

I have no idea how to traverse the bits and store them as their Int16 values. Any help would be greatly appreciated.

jjatie
  • 5,152
  • 5
  • 34
  • 56

1 Answers1

2

Try using 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
OOPer
  • 47,149
  • 6
  • 107
  • 142
  • 1
    The only thing I'd add is that I'd stick it in a init?(data: Data) constructor and return nil if the you don't get the expected buffer size, because thats usually a sign that you have the wrong data: guard data.count == MemoryLayout.size * 3 else {return nil} – Josh Homann Oct 26 '16 at 23:28
  • Looks like this will work. Hopefully I'll get a chance to test/vote up today. – jjatie Oct 27 '16 at 14:02