Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor CBPeripheral state changes

So there's a way to monitor state changes of CBCentralManager via centralManagerDidUpdateState(). But is there a similar method call to monitor state changes for CBPeripheral? I couldn't find anything exposed in CoreBluetooth library, and I want to call a function whenever CBPeripheralState changes.

Right now all I have is a switch statement which checks the peripheral state, but it'll always just return either connected or disconnected. How would I get to the connecting/disconnecting cases? I've tried placing my switch statement in various parts of my code, from the bleInit() method, to startScanning(), connectToPeripheral(), etc

switch(peripheral.state){
case .disconnected:
    print("disconnected")
case .connecting:
    print("connecting")
case .connected:
    print("connected")
case .disconnecting:
    print("disconnecting")
default: break
}
like image 258
Alfred Ly Avatar asked Apr 05 '17 19:04

Alfred Ly


2 Answers

The connecting and disconnecting states are transitionary states. Your connection will only be in those states for a very brief time; which is why you will never see those states.

If your app is acting as a central then peripheral connection state is notified via the CBCentralManager's didConnect and didDisconnectPeripheral methods.

like image 162
Paulw11 Avatar answered Sep 28 '22 21:09

Paulw11


CBPeripheral's state property is KVO-compliant, hence you can easily add an object as observer and monitor all state transitions.

Note though that for some reason some state transitions are strange, i.e. when a peripheral moves from disconnected to disconnecting without any intermediate states. I'm afraid that's bugs in the CoreBluetooth stack.

like image 23
DrMickeyLauer Avatar answered Sep 28 '22 20:09

DrMickeyLauer