如何使用CoreBluetooth从1822 PulseOximeter的Bluetooth LE数据中提取SFLOAT值

时间:2018-07-09 15:41:37

标签: ios swift bluetooth-lowenergy core-bluetooth gatt

我正在开发一个iOS应用,该应用将使用 iOS 11.4 上的 CoreBluetooth 从启用了 Bluetooth LE 的设备中读取脉搏血氧仪数据>在 Swift 4.1 中。

我已找到 CBCentralManager ,搜索外围设备,找到了感兴趣的 CBPeripheral ,我确认它具有 0x1822 脉搏血氧仪服务,如Bluetooth SIG here所述。 (您可能需要向Bluetooth SIG注册才能访问该链接。它是免费的,但需要一两天。)

然后,我连接到它,然后发现服务:

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.discoverServices(nil)
}

然后在我的 peripheral:didDiscoverServices 中,我发现了GATT的特征:

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){
    for service in peripheral.services ?? [] {
        if service.uuid.uuidString == "1822" {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
}

从中,我看到可用的以下特征( CBCharacteristic.uuid ):0x2A5F,0x2A5E,0x2a60和0x2A52。然后,我订阅 0x2A5F 的更新,这是 PLX连续测量,其描述为here

if service.uuid.uuidString == "1822" && characteristic.uuid.uuidString == "2A5F" {
    // pulseox continuous
    print("[SUBSCRIBING TO UPDATES FOR SERVICE 1822 'PulseOx' for Characteristic 2A5F 'PLX Continuous']")
    peripheral.setNotifyValue(true, for: characteristic)    
}

然后,我开始通过 peripheral:didUpdateValueFor 方法接收回20字节的数据包:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

    if characteristic.service.uuid.uuidString == "1822" && characteristic.uuid.uuidString == "2A5F" {
        if let data = characteristic.value {
            var values = [UInt8](repeating:0, count:data.count)
            data.copyBytes(to: &values, count: data.count)
        }
    }
}

从参考文档中可以看到,第一个字节是一堆位域,描述了包中包含哪些可选值。接下来的2个字节是 SpO2PR-Normal-SpO2 (充氧)读数的 SFLOAT 值,接下来的2个字节是另一个 SFLOAT 值为了 SpO2PR-Normal-PR (脉冲率)值。

蓝牙SIG列出了 SFLOAT 作为 IEEE-11073 16位SFLOAT here。 IEEE的document on IEEE-11073并未公开列出,而是available for purchase,但我希望避免这种情况。

任何想法如何解码?我在堆栈溢出中发现了另一个问题,该问题引用了正常的32-bit Float,但该问题是针对另一种类型的Float,其答案不适用。

2 个答案:

答案 0 :(得分:2)

这里是:

Xcode 9.4.1 Xcode 10.0 beta 3

iOS 11.4.1 iOS 12.0 beta 3

Swift 4.1.2 Swift 4.2

func floatFromTwosComplementUInt16(_ value: UInt16, havingBitsInValueIncludingSign bitsInValueIncludingSign: Int) -> Float {
    // calculate a signed float from a two's complement signed value
    // represented in the lowest n ("bitsInValueIncludingSign") bits
    // of the UInt16 value
    let signMask: UInt16 = UInt16(0x1) << (bitsInValueIncludingSign - 1)
    let signMultiplier: Float = (value & signMask == 0) ? 1.0 : -1.0

    var valuePart = value
    if signMultiplier < 0 {
        // Undo two's complement if it's negative
        var valueMask = UInt16(1)
        for _ in 0 ..< bitsInValueIncludingSign - 2 {
            valueMask = valueMask << 1
            valueMask += 1
        }
        valuePart = ((~value) & valueMask) &+ 1
    }

    let floatValue = Float(valuePart) * signMultiplier

    return floatValue
}

func extractSFloat(values: [UInt8], startingIndex index: Int) -> Float {
    // IEEE-11073 16-bit SFLOAT -> Float
    let full = UInt16(values[index+1]) * 256 + UInt16(values[index])

    // Check special values defined by SFLOAT first
    if full == 0x07FF {
        return Float.nan
    } else if full == 0x800 {
        return Float.nan // This is really NRes, "Not at this Resolution"
    } else if full == 0x7FE {
        return Float.infinity
    } else if full == 0x0802 {
        return -Float.infinity // This is really negative infinity
    } else if full == 0x801 {
        return Float.nan // This is really RESERVED FOR FUTURE USE
    }

    // Get exponent (high 4 bits)
    let expo = (full & 0xF000) >> 12
    let expoFloat = floatFromTwosComplementUInt16(expo, havingBitsInValueIncludingSign: 4)

    // Get mantissa (low 12 bits)
    let mantissa = full & 0x0FFF
    let mantissaFloat = floatFromTwosComplementUInt16(mantissa, havingBitsInValueIncludingSign: 12)

    // Put it together
    let finalValue = mantissaFloat * pow(10.0, expoFloat)

    return finalValue
}

extraSFloat 方法采用Uint8数组和该数组的索引来指示SFLOAT的位置。例如,如果数组是两个字节(仅是SFLOAT的两个字节),那么您会说:

let floatValue = extractSFloat(values: array, startingIndex: 0)

之所以这样做,是因为在处理Bluetooth数据时,我总是以一个包含我需要解码的数据的 UInt8 值数组结束。

答案 1 :(得分:0)

这就是我在 Swift 5 (XCode 12.4) 中的做法

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard characteristic.service.uuid == CBUUID(string: "1822"),
              characteristic.uuid == CBUUID(string: "2A5F"),
              let data = characteristic.value else {
            return
        }
        
        let numberOfBytes = data.count
        var byteArray = [UInt8](repeating: 0, count: numberOfBytes)
        (data as NSData).getBytes(&byteArray, length: numberOfBytes)
        
        logger.debug("Data: \(byteArray)")
        
        let oxygenation = byteArray[1]
        let heartRate = byteArray[3]
    }

摘自我的教程 "Reverse Engineering Bluetooth Devices - An Introduction to CoreBluetooth"