我想从提供两种服务的BLE设备获取数据,其中一种提供3种特性,另一种提供2种特性。 您能解释一下如何从Swift中的设备中检索数据吗? 请看一下正确的代码
extension PeripheralConnectedViewController: CBPeripheralDelegate {
func centralManager(_ central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
if let error = error {
print("Error connecting peripheral: \(error.localizedDescription)")
}
}func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let error = error {
print("Error discovering services: \(error.localizedDescription)")
}
peripheral.services?.forEach({ (service) in
services.append(service)
tableView.reloadData()
peripheral.discoverCharacteristics(nil, for: service)
})
}func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if let error = error {
print("Error discovering service characteristics: \(error.localizedDescription)")
}
service.characteristics?.forEach({ characteristic in
if let descriptors = characteristic.descriptors {
print(descriptors)
}
print(characteristic.properties)
})
for newChar: CBCharacteristic in service.characteristics!{
peripheral.readValue(for: newChar)
peripheral.setNotifyValue(true, for: newChar)
}
}
func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
switch RSSI.intValue {
case -90 ... -60:
rssiLabel.textColor = .btOrange
break
case -200 ... -90:
rssiLabel.textColor = .btRed
break
default:
rssiLabel.textColor = .btGreen
}
rssiLabel.text = "\(RSSI)dB"
}func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if var enableValue = Character("?").asciiValue{
let enablyBytes = NSData(bytes: &enableValue, length: MemoryLayout<UInt8>.size)
self.peripheral.writeValue(enablyBytes as Data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
print(characteristic)
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
}