ios - 当 BLE 设备中的值更改时如何更新 BatteryLevel

标签 ios swift core-bluetooth

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

    for c in service.characteristics!{
        print("---Characteristic found with UUID: \(c.uuid) \n")

        let uuid = CBUUID(string: "2A19")//Battery Level

        if c.uuid == uuid{
            peripheral.setNotifyValue(true, for: c)//Battery Level
        }
    }
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
/* Battery Level */
if (characteristic.uuid == CBUUID(string: "2A19")) && (characteristic.value != nil){
    let value = characteristic.value
    let valueUint8 = [UInt8](value!)
    print("\(valueUint8)")
    print("\(valueUint8[0])")
    let batteryLevel: Int32 = Int32(bitPattern: UInt32(valueUint8[0]))
    print("\(batteryLevel)")

}
}

我想在电池电量变化时获取当前电量,但即使设置了 setNotifyValue 也没有收到任何响应。

最佳答案

我认为您需要读取方法中的值 funcperipheral(_peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)

使用 Objective-C,您可以在委托(delegate)方法中执行以下操作:

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(nullable NSError *)error{
    for (CBCharacteristic *characteristic in service.characteristics) {

        [peripheral setNotifyValue:YES forCharacteristic:characteristic];

        // read battery
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A19"]]) {
            [peripheral readValueForCharacteristic:characteristic];//you miss the codes 
        }


    }

在另一个委托(delegate)方法中:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error{
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A19"]]) {
        Byte *batteryBytes=(Byte*)characteristic.value.bytes;
        int battery = bytesToInt(batteryBytes, 0)&0xff;
        NSLog(@"%@", [NSString stringWithFormat:@"battery left:%d",battery]);
    }
}

I used the above method to get the battery info of a BLE device successfully.

关于ios - 当 BLE 设备中的值更改时如何更新 BatteryLevel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45821614/

相关文章:

swift - 如何在约会 child 后从 Firebase 中读取内容?

ios - Swift 3.0 无法从 UITableView 中删除行

ios5 - CoreBluetooth writeValue :forDescriptor: issue

ios - 无限期地在后台传输心率?

ios - 推送 segue 在 IOS 8.0 上不起作用

objective-c - 使横向成为所有 View Controller 同时唯一的自动旋转方向

ios - 如何将 HKBloodType 枚举转换为字符串

ios - 从 Swift 3.0 转换为 Swift 2.3

iOS 13 > 当应用程序被杀死且不在后台时,通用应用程序链接不起作用