troystribling / BlueCap

iOS Bluetooth LE framework
MIT License
714 stars 114 forks source link

Peripheral Connection Status Updates #74

Closed CImrie closed 6 years ago

CImrie commented 6 years ago

Hey!

Hopefully you can help... I need to know when the connection status of a peripheral is changed (either connected/disconnected).

Normally you set CBCentralManager.delegate to receive updates when this happens, but the BlueCapKit.CentralManager is already the delegate and implements both: public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?)

These methods both update properties on the individual peripheral object but the FutureStream for the connection status is fileprivate.

Is there any way for me to be able to be notified about a peripheral connection status change? I really don't want to poll Peripheral.state

Thanks in advance :)

troystribling commented 6 years ago

The FutureStream returned by a connection is called when the connection status changes. Here is a code snippet from he documentation.

let connectionFuture = scanFuture.flatMap { [weak manager] () -> FutureStream<Void> in
    manager?.stopScanning()
    discoveredPeripheral = peripheral
    return peripheral.connect(timeoutRetries:5, disconnectRetries:5, connectionTimeout: 10.0)
}

connectionFuture.onSuccess { [weak peripheral] in
      // handle successful connection
}

connectionFuture.onFailure { error in
    switch error {
    case PeripheralError.disconnected:
        discoveredPeripheral.reconnect()
        break
    case PeripheralError.forcedDisconnect:
        break
    case PeripheralError.connectionTimeout:
        break
    default:
        break
    }
}
CImrie commented 6 years ago

@troystribling I did scout over that but now that you've reiterated I have figured out exactly how I'm going to use it in my app. Thanks for the help!