gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:12:56 36 4
gpt4 key购买 nike

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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com