Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CentralManager state reported as unsupported if already connected to a peripheral. Errors thrown are sometimes CoreBluetooth errors instead of PeripheralError. #62

Closed
Soulphalanx opened this issue Apr 26, 2017 · 6 comments

Comments

@Soulphalanx
Copy link
Contributor

If I connect to, discover services and characteristics, notify and receive notification updates with a peripheral and I use the same central to attempt to connect and do the same with another peripheral, the state of the CentralManager is unsupported, yet if I forgo the state checking and connect anyway, it works as intended.

I am running this on an iPhone 7 Plus 256GB running iOS 10.3.2 beta 4.

Here is my code for the connection, discovery, etc.:

func connect() {
        let dataUpdateFuture = self.central.whenStateChanges().flatMap { [unowned self] state -> FutureStream<Void> in
            
            switch state {
            case .poweredOn:
                return self.peripheral.connect(connectionTimeout: 10.0)
            case .poweredOff:
                throw BLEError.poweredOff
            case .unauthorized:
                throw BLEError.unauthorized
            case .unsupported:
                throw BLEError.unsupported
            case .resetting:
                throw BLEError.resetting
            case .unknown:
                throw BLEError.unknown
            }
 
            return self.peripheral.connect(connectionTimeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                //Update UI
                self.peripheral.startPollingRSSI(period: 0.25, capacity: 10).onSuccess { rssi in
                    BLE.sharedInstance.invoke(method: { $0.didUpdateRSSI?(rssi) })
                }
                BLE.sharedInstance.invoke(method: { $0.didGetPeripheralUUID?(self.peripheral.identifier.uuidString) })
                self.uuid = self.peripheral.identifier.uuidString

                print("Discovering services")
                return self.peripheral.discoverServices([s2UUID], timeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                guard let service = self.peripheral.services(withUUID: s2UUID)?.first else {
                    throw AppError.serviceNotFound
                }
                print("Discovering characteristics")
                return service.discoverCharacteristics([rawUUID], timeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                guard let service = self.peripheral.services(withUUID: s2UUID)?.first else {
                    throw BLEError.serviceNotFound
                }
                guard let rawCharacteristic = service.characteristics(withUUID: rawUUID)?.first else {
                    throw BLEError.rawDataCharacteristicNotFound
                }
                print("Start notifying raw characteristic")
                self.rawDataCharacteristic = rawCharacteristic
                return rawCharacteristic.startNotifying()
            }.flatMap { [unowned self] () -> FutureStream<Data?> in
                guard let rawCharacteristic = self.rawDataCharacteristic else {
                    throw BLEError.rawDataCharacteristicNotFound
                }
                print("Receiving raw characteristic notification update")
                return rawCharacteristic.receiveNotificationUpdates(capacity: 30)
        }

As for errors being thrown, I have to use CBErrors to catch some of them, like so:

dataUpdateFuture.onFailure { error in
            print("Data update error: \(error)")
            switch error {
            case BLEError.serviceNotFound:
                self.disconnect()
            case PeripheralError.disconnected, PeripheralError.connectionTimeout, CBError.connectionTimeout, CBError.connectionFailed:
                self.connect()
            default:
                break
            }
        }
@Soulphalanx Soulphalanx changed the title CentralManager state reported as unsupported if already connected to a peripheral. Errors thrown are something CoreBluetooth errors. CentralManager state reported as unsupported if already connected to a peripheral. Errors thrown are sometimes CoreBluetooth errors instead of PeripheralError. Apr 26, 2017
@troystribling
Copy link
Owner

troystribling commented Apr 27, 2017

Look at this code. https://github.com/troystribling/BlueCap/blob/master/Examples/CentralManager/CentralManager/ViewController.swift#L113-L178.

I do not see how your example works. Where does self.peripheral come from? You need to start a scan and then connect to the discovered peripheral with something like this,

let dataUpdateFuture = manager.whenStateChanges().flatMap { [unowned self] state -> FutureStream<Peripheral> in
                switch state {
                case .poweredOn:
                    self.activateSwitch.isOn = true
                    return self.manager.startScanning(forServiceUUIDs: [serviceUUID], capacity: 10)
                case .poweredOff:
                    throw AppError.poweredOff
                case .unauthorized, .unsupported:
                    throw AppError.invalidState
                case .resetting:
                    throw AppError.resetting
                case .unknown:
                    throw AppError.unknown
                }
        }.flatMap { [unowned self] peripheral -> FutureStream<Void> in
            self.manager.stopScanning()
            self.peripheral = peripheral
            return peripheral.connect(connectionTimeout: 10.0)
        }

I have only seen the CentralManager state become unsupported after a crash of the system BluetoothService. Sometimes you will see a state of resetting reported also. The system CoreBluetooth service can crash because of a CBPeripheral memory leak of if you are connected to more than a few peripherals simultaneously. I have seen crashes when connected to 3.

central.whenStateChanges() does not do anything except return the current state and the framework does not manipulate the state.

How may peripherals are you connect to? What are the reported errors.

@Soulphalanx
Copy link
Contributor Author

Soulphalanx commented Apr 27, 2017

I do a scan in another class for a list of peripherals which then populates a tableView. Then, after selecting one in the list, I have another class object that gets instantiated for each Peripheral chosen, which is the self.peripheral variable. I start off with central.whenStateChanges() to make sure that the Bluetooth is in a valid state before connecting, discovering, etc. I can post some more code if you need a little more context.

I can connect to one peripheral fine, and then I get an unsupported state when I attempt to do the same thing again with a second peripheral. Cutting out the central.whenStateChanges() state check still allows me to connect to the second peripheral just fine.

Most of the time I get CBError.connectionTimeout, so I just had to include it in the switch case and it seems to handle it fine. I just wasn't sure if it was just leaking through and not being caught by BlueCap, or just being thrown somewhere that isn't capturable.

@troystribling
Copy link
Owner

troystribling commented Apr 27, 2017

Can you send me a link to your app?

If you call manager.whenStateChanges() any futures persisted from other calls will no longer work with he current implementation?

It is better to just check the state.

You should be able to see the CoreBluetooth reset event in the system log. Monitor the log when you run the app and see if you see the event.

How many peripherals did you discover? Having a large number of CBPeripherals can also cause a CoreBluetooth crash.

@Soulphalanx
Copy link
Contributor Author

I can't send you the link, but here's the portions pertaining to it:

Scanning and passing array to a delegate:

func scan() -> FutureStream<Peripheral> {
        print("Scanning")

        let scanFuture = BLE.sharedInstance.s2Central.startScanning(forServiceUUIDs: [BLE.sharedInstance.s2UUID], capacity: 30, timeout: 30)

        scanFuture.onFailure { error in
            print("Scan failure: \(error)")
            //Also fails when it times out, checking to make sure it actually is a timeout, then sending sorted list by RSSI to delegates
            BLE.sharedInstance.invoke(method: { $0.scanFailed?() })
            guard let error = error as? CentralManagerError, error == .serviceScanTimeout else { return }
            print("Scan timed out")
            BLE.sharedInstance.invoke(method: { $0.scanDidTimeOut?() })
        }

        return scanFuture
    }

    var scanTimer: Timer?
    func scan() {
        let scan = self.connectStream.scan()

        scan.onSuccess { peripheral in
            self.discoveredPeripherals.insert(peripheral)
            if self.scanTimer != nil {
                self.scanTimer?.invalidate()
                self.scanTimer = nil
            }
            DispatchQueue.main.async {
                self.scanTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(self.scanSuccessTimeout), userInfo: nil, repeats: false)
            }
            print("Discovered \(self.discoveredPeripherals.count) peripherals")

            if self.discoveredPeripherals.count >= 50 {
                self.scanSuccessTimeout()
            }
        }
    }

    @objc func scanSuccessTimeout() {
       // streamQueue.sync {
            self.scanTimer?.invalidate()
            self.scanTimer = nil
            print("Stopping scan. Found \(self.discoveredPeripherals.count) peripherals.")
            self.central.stopScanning()
            let peripheralArray = self.discoveredPeripherals.sorted(by: { (a, b) -> Bool in
                return a.RSSI > b.RSSI
            }).map {$0}
            self.delegateQueue.async {
                self.invoke(method: { $0.didDiscoverPeripherals?(peripherals: peripheralArray) })
            }

This is called when selecting a peripheral from a list after a scan.

func connect(_ peripheral: Peripheral) {
        streamQueue.async {
            let stream = Stream(central: self.s2Central, peripheral: peripheral)
        }
    }
//
//  Stream.swift
//  BLEXploration
//
//  Created by Justice Hsiung on 4/25/17.
//  Copyright © 2017 Spire, Inc. All rights reserved.
//

import Foundation
import BlueCapKit
import CoreBluetooth

public enum BLEError : Error {
    case rawDataCharacteristicNotFound
    case serviceNotFound
    case invalidState
    case unauthorized
    case unsupported
    case resetting
    case poweredOff
    case unknown
    case unlikely
}

let rawUUID = CBUUID(string: <redacted>)

class Stream : Hashable, Equatable {
    let peripheral: Peripheral
    let central: CentralManager = CentralManager(options: [CBCentralManagerOptionRestoreIdentifierKey:"test"])

    var rawDataCharacteristic: Characteristic?
    var peripheralInfoCache = NSCache<AnyObject, AnyObject>()

    var uuid: String?

    static var streams = Dictionary<Int, Stream>()

    class func streamFor(peripheral: Peripheral) -> Stream? {
        if let stream = streams[peripheral.hashValue] {
            return stream
        } else {
            return nil
        }
    }

    class func connectedPeripherals() -> [Peripheral] {
        return Stream.streams.map { (_, value) -> Peripheral in
            return value.peripheral
        }
    }

    var hashValue: Int {
        return peripheral.hashValue
    }

    static func == (lhs: Stream, rhs: Stream) -> Bool {
        return lhs.peripheral.hashValue == rhs.peripheral.hashValue
    }

    init(central: CentralManager, peripheral: Peripheral) {
        self.peripheral = peripheral
        //self.central = central

        self.connect()

        Stream.streams.updateValue(self, forKey: peripheral.hashValue)
    }

    fileprivate func connect() {
        let dataUpdateFuture = self.central.whenStateChanges().flatMap { [unowned self] state -> FutureStream<Void> in
            /*
            switch state {
            case .poweredOn:
                return self.peripheral.connect(connectionTimeout: 10.0)
            case .poweredOff:
                throw BLEError.poweredOff
            case .unauthorized:
                throw BLEError.unauthorized
            case .unsupported:
                throw BLEError.unsupported
            case .resetting:
                throw BLEError.resetting
            case .unknown:
                throw BLEError.unknown
            }
 */
            return self.peripheral.connect(connectionTimeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                //Update UI
                self.peripheral.startPollingRSSI(period: 0.25, capacity: 10).onSuccess { rssi in
                    if let uuid = self.uuid {
                        BLE.sharedInstance.invoke(method: { $0.didUpdateRSSI?(rssi, forUUID: uuid) })
                    }
                }
                BLE.sharedInstance.invoke(method: { $0.didGetPeripheralUUID?(self.peripheral.identifier.uuidString) })
                self.uuid = self.peripheral.identifier.uuidString

                print("Discovering services")
                return self.peripheral.discoverServices([s2UUID], timeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                guard let service = self.peripheral.services(withUUID: s2UUID)?.first else {
                    throw AppError.serviceNotFound
                }
                print("Discovering characteristics")
                return service.discoverCharacteristics([rawUUID], timeout: 10.0)
            }.flatMap { [unowned self] () -> Future<Void> in
                guard let service = self.peripheral.services(withUUID: s2UUID)?.first else {
                    throw BLEError.serviceNotFound
                }
                guard let rawCharacteristic = service.characteristics(withUUID: rawUUID)?.first else {
                    throw BLEError.rawDataCharacteristicNotFound
                }
                print("Start notifying raw characteristic")
                self.rawDataCharacteristic = rawCharacteristic
                return rawCharacteristic.startNotifying()
            }.flatMap { [unowned self] () -> FutureStream<Data?> in
                guard let rawCharacteristic = self.rawDataCharacteristic else {
                    throw BLEError.rawDataCharacteristicNotFound
                }
                print("Receiving raw characteristic notification update")
                return rawCharacteristic.receiveNotificationUpdates(capacity: 30)
        }

        dataUpdateFuture.onFailure { error in
            print("Data update error: \(error)")
            switch error {
            case BLEError.serviceNotFound:
                self.disconnect()
            case PeripheralError.disconnected, PeripheralError.connectionTimeout, CBError.connectionTimeout, CBError.connectionFailed:
                self.connect()
            default:
                break
            }
        }

        dataUpdateFuture.onSuccess { [unowned self] data in
            print("New raw notification update from \(self.uuid ?? "")")
            dump(data)
        }
    }
    
    func pollUUID() {
        BLE.sharedInstance.invoke(method: { $0.didGetPeripheralUUID?(self.peripheral.identifier.uuidString) })
    }

    func disconnect() {
        peripheral.disconnect()
        Stream.streams.removeValue(forKey: self.hashValue)
        print("Disconnecting from peripheral \(uuid ?? "")")
    }
}

In these particular cases, only two peripherals were discovered, and only two were attempted to be connected to.

@troystribling
Copy link
Owner

troystribling commented Apr 27, 2017

I am not able to reproduce your problem. I tested this code successfully which calls whenStateChanges() before trying to connect. It scans until 10 peripherals are discovered then connects to each sequentially.

    func activate() {
        let dataUpdateFuture = manager.whenStateChanges().flatMap { [unowned self] state -> FutureStream<Peripheral> in
                switch state {
                case .poweredOn:
                    self.activateSwitch.isOn = true
                    return self.manager.startScanning(capacity: 10)
                case .poweredOff:
                    throw AppError.poweredOff
                case .unauthorized, .unsupported:
                    throw AppError.invalidState
                case .resetting:
                    throw AppError.resetting
                case .unknown:
                    throw AppError.unknown
                }
        }
        dataUpdateFuture.onSuccess { [unowned self] peripheral in
            if self.discoveredPeripherals.count > 10 {
                self.manager.stopScanning()
                Logger.debug("Stop scanning and connect peripherals")
                self.connect(connectingPeripheral: self.discoveredPeripherals.removeLast())
            }
            Logger.debug("Discovered: \(peripheral.identifier)")
            self.discoveredPeripherals.append(peripheral)
        }
        dataUpdateFuture.onFailure { [unowned self] error in
            self.present(UIAlertController.alertOnError(error), animated:true, completion:nil)
        }
    }
    
    func connect(connectingPeripheral: Peripheral?) {
        guard let connectingPeripheral = connectingPeripheral else {
            Logger.debug("Connected all")
            return
        }
        Logger.debug("Trying to connect to: \(connectingPeripheral.identifier)")
        let dataUpdateFuture = manager.whenStateChanges().flatMap { state -> FutureStream<Void> in
            switch state {
            case .poweredOn:
                Logger.debug("Powered on connecting to: \(connectingPeripheral.identifier)")
                return connectingPeripheral.connect(connectionTimeout: 10.0)
            case .poweredOff:
                throw AppError.poweredOff
            case .unauthorized, .unsupported:
                throw AppError.invalidState
            case .resetting:
                throw AppError.resetting
            case .unknown:
                throw AppError.unknown
            }
        }

        dataUpdateFuture.onFailure { [unowned self] error in
            switch error {
            case AppError.invalidState:
                self.present(UIAlertController.alertWithMessage("Invalid state"), animated: true, completion: nil)
            case AppError.resetting:
                self.manager.reset()
                self.present(UIAlertController.alertWithMessage("Bluetooth service resetting"), animated: true, completion: nil)
            case AppError.poweredOff:
                self.present(UIAlertController.alertWithMessage("Bluetooth powered off"), animated: true, completion: nil)
            case AppError.unknown:
                break
            case PeripheralError.disconnected:
                connectingPeripheral.reconnect()
            case PeripheralError.forcedDisconnect:
                Logger.debug("Disconnected from: \(connectingPeripheral.identifier)")
                let nextPeripheral = self.discoveredPeripherals.count > 0 ? self.discoveredPeripherals.removeLast() : nil
                self.connect(connectingPeripheral: nextPeripheral)
            case PeripheralError.connectionTimeout:
                Logger.debug("Connection timeout: \(connectingPeripheral.identifier)")
                Logger.debug("Disconnected from: \(connectingPeripheral.identifier)")
                connectingPeripheral.disconnect()
            default:
                self.present(UIAlertController.alertOnError(error), animated:true, completion:nil)
            }
            self.updateUIStatus()
        }

        dataUpdateFuture.onSuccess {
            Logger.debug("Connected to: \(connectingPeripheral.identifier)")
            Logger.debug("Disconnected from: \(connectingPeripheral.identifier)")
            connectingPeripheral.disconnect()
        }
    }

I think you are somehow crashing CoreBluetooth by either leaking CBPeripherals or have too many open connections.

Did you check the logs for a crash?

@Soulphalanx
Copy link
Contributor Author

Soulphalanx commented Apr 27, 2017

It looks like I had instantiated another central with the same restore identifier key elsewhere and that's why it returned a unsupported state. Sorry for the trouble. I will update my code and see if I can get it working properly. Thanks for your help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants