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。
发布于 2017-08-22 15:44:31
我认为您需要在方法func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?)中读取值。
使用Objective,您可以在委托方法中这样做:
- (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
}
}在另一种委托方法中:
- (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设备的电池信息。
https://stackoverflow.com/questions/45821614
复制相似问题