如何在Swift 4中获得蓝牙低功耗的电池寿命?

时间:2017-11-23 00:27:40

标签: ios swift bluetooth

我可以通过以下问题获得BLE电池续航时间的价值:

Read data from BLE device

Reading a BLE Peripheral Characteristic and checking its value?

但我不确定它是否会返回正确的值?它返回18,我也不确定根据百分比确定电池寿命的最大数量。这意味着18个小时吗?

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

    print("-CBService is: \(service.uuid.description)")

    if compare(service.uuid, uuid2: CBUUID(string:BluetoothConstants.TI_KEYFOB_BATT_SERVICE_UUID)) {
        print("Battyer Life determination")

        for characteristic: CBCharacteristic in service.characteristics! {
            if characteristic.uuid == CBUUID(string: BluetoothConstants.TI_KEYFOB_LEVEL_SERVICE_UUID) {
                print(characteristic.properties.rawValue)
            }
        }
    }
}

以下行是打印字符:

CBCharacteristic: 0x1c00be8a0, UUID = Battery Level, properties =
0x12, value = (null), notifying = NO>

我在这里尝试了大部分答案,但他们不适用于Swift 4.

1 个答案:

答案 0 :(得分:0)

我不确定Swift 4是什么,但是这是我使用Swift 5弄清楚的方式。feature.properties中的值不是电池电量。您需要请求从设备读取电池电量特性(0x2A19):

if characteristic.uuid == CBUUID(string: "0x2A19") {
   peripheral.readValue(for: characteristic)
}

然后,您还需要将didUpdateValueFor添加为CBPeripheralDelegate的一部分:

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
   print("Battery level: \(characteristic.value![0])")
}

我用一个旧的3V电压进行了测试,该电压为2.76V(几乎被认为是没电的),它的值为3。然后我装了一个新电池,其值为100。 >