jordanebelanger / SwiftyBluetooth

Closures based APIs for CoreBluetooth
MIT License
209 stars 66 forks source link

Had to do a fix to solve service discovery timeouts #54

Closed ir-fuel closed 1 year ago

ir-fuel commented 2 years ago

For some reason the device discovery callback reported the same device multiple times.

Every time it was discovered it was added to the array in this code:

            let peripheral = Peripheral(peripheral: peripheral)
            scanRequest.peripherals.append(peripheral)

in

    func centralManager(_ central: CBCentralManager,
                        didDiscover peripheral: CBPeripheral,
                        advertisementData: [String: Any],
                        rssi RSSI: NSNumber)

So I had the same device multiple times there and that created problems.

When I took the first one out of that list (of the 6 pointing to the same device) I got timeouts when trying to discover its services. I presume because maybe the CBPeripheral instance was the same, but the PeripheralProxy wasn't, and inside that proxy you do cbPeripheral.delegate = self so it ends up pointing to an instance I am not using (if that all makes sense :) )

I solved this by doing this:

        if scanRequest.peripherals.first (where: { $0.identifier == peripheral.identifier }) == nil {
            let peripheral = Peripheral(peripheral: peripheral)
            scanRequest.peripherals.append(peripheral)

            var rssiOptional: Int? = Int(truncating: RSSI)
            if let rssi = rssiOptional, rssi == 127 {
                rssiOptional = nil
            }

            scanRequest.callback(.scanResult(peripheral: peripheral, advertisementData: advertisementData, RSSI: rssiOptional))
        }

Just FYI ;)

DamonOehlman commented 1 year ago

I know this is an older issue, but just wondering if this has been fixed by #60 and by version 3.1.0. We have been hitting a similar issue in our app and are hoping it all goes away nicely with the upgrade :)

jordanebelanger commented 1 year ago

I know this is an older issue, but just wondering if this has been fixed by #60 and by version 3.1.0. We have been hitting a similar issue in our app and are hoping it all goes away nicely with the upgrade :)

Yes the two problems were linked, you should be good now.