设备断开一段时间后无法获得特征

Posted

技术标签:

【中文标题】设备断开一段时间后无法获得特征【英文标题】:Device Disconnect After some time & Unable to get characteristic 【发布时间】:2019-04-26 06:35:55 【问题描述】:

我知道在堆栈上多次询问提到的断开连接错误,但接受的答案不是问题的实际解决方案

我正在尝试将 MI Band 3 与我的 swift 应用程序连接。它连接成功,但一段时间后它会自动断开连接

Error:  Error Domain=CBErrorDomain Code=7 "The specified device has disconnected from us." UserInfo=NSLocalizedDescription=The specified device has disconnected from us

我的应用要求:我需要获取 Apple Watch、Fitbit 和 MI 智能手表的心率和步行距离

我尝试在多个设备上连接相同的 MI Band 结果是相同的。但是那个特定的 MI 乐队可以与他们自己的应用完美配合

--> Connect Device - Kept reference of connected Device
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) 
        print("Connected With Peripheral: \(peripheral)")
        selectedPeripheral=peripheral
        self.delegate?.scannedPeripherals(Is: peripheral)

        /// Discover Services Provided By Device
        selectedPeripheral?.delegate=self
        selectedPeripheral?.discoverServices([heartRateServiceCBUUID])
    

---> After Discovering services With heart Rate CBUUID
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) 
        guard let characteristics = service.characteristics else  return 
        selectedPeripheral=peripheral
        for char in characteristics 
            print("Characterstics: \(char)")
            if char.properties.contains(.read) 
            
            if char.properties.contains(.notify) 
                /// ------------- Setting Notify to true but not never call required delegates ----------------
                peripheral.setNotifyValue(true, for: char)
                print("\(char.uuid): properties contains .notify")
                peripheral.readValue(for: char)
            
        
    


Calculating BPM from delegate
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) 
        switch characteristic.uuid 
        case bodySensorLocationCharacteristicCBUUID:
            let bodySensorLocation = bodyLocation(from: characteristic)
            print(bodySensorLocation)
        default:
            /// --------- here characteristic value is nil --------------
            let bpm = heartRate(from: characteristic)
            print("BPM: \(bpm)")
        
    

【问题讨论】:

【参考方案1】:

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

尝试删除peripheral.readValue(for: char)并重新测试!

【讨论】:

以上是关于设备断开一段时间后无法获得特征的主要内容,如果未能解决你的问题,请参考以下文章

如何从android中的BLE设备获取实际值?

CoreBluetooth:无法发现已发现外围设备的特征

无法从 BLE 设备读取特征值

无法使用 python 从 BLE 设备读取特定特征

无法从此设备复制符号

Quickblox:无法获得推送通知