首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在BLE设备中值变化时如何更新BatteryLevel

在BLE设备中值变化时如何更新BatteryLevel
EN

Stack Overflow用户
提问于 2017-08-22 15:23:34
回答 1查看 1K关注 0票数 0
代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2017-08-22 15:44:31

我认为您需要在方法func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)中读取值。

使用Objective,您可以在委托方法中这样做:

代码语言:javascript
复制
- (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 
        }


    }

在另一种委托方法中:

代码语言:javascript
复制
- (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]);
    }
}

我使用上述方法成功地获取了BLE设备的电池信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45821614

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档