I am trying to read values from a Bluetooth 4.0 LE scale on iOS. How do I convert the Bluetooth Characteristics measurements received as NSData to dedicated Swift objects?
As a specification I know that …
Bit 0 to Bit 12 → weight (0 to 5000 g)
Bit 15 → positive/negative weight value
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
let value:NSData = characteristic.value
let weight:Double = … ?
let negative:Bool = … ?
one more piece of information – looking at
value.length
it looks like I am always getting 1 or 2 bytes (?) of data from the device. However I am still not sure how to extract the data/values I was looking for. I'd appreciate any advice.
Here's what works a little bit so far …
var bin16:UInt16 = 0
characteristic.value.getBytes(&bin16, range: NSRange(location: 0,length: 1))
println("Bytes \(characteristic.value.bytes) Length \(characteristic.value.length)")
println("Value \(bin16)")
– Doing this I manage to get some weight reading. It seems to work unless the value is bigger than 255 or negative. Here are some examples:
75 grammes
Bytes 0x1655e458 Length 1 Value 75
367 grammes
Bytes 0x1765cbc8 Length 2 Value 161
-6 grammes
Bytes 0x17670f18 Length 2 Value 32
Also this gets transmitted more often in between – it doesn't stand for 160 gramme in this case. Maybe some sort of error code?!
Bytes 0x146528b8 Length 2 Value 160