zorro
zorro

Reputation: 95

iOS SWIFT - Detect peripheral turning off from central

Is there any way from the Central app to detect when a peripheral for example runs out of power and consequently disconnects?

I tried using this: func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { bleCentralManagerDelegate?.disconnectFromDeviceBLEResult(result: true)}

But this event gets called only if the peripheral requests an actual disconnection, and does NOT get called if the peripheral randomly turns off.

Thanks

Upvotes: 3

Views: 1848

Answers (2)

app4g
app4g

Reputation: 840

Is this what you're looking for?

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    let cState = central.state
    
    switch cState {
    case .unknown:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .unknown")
      }
      
    case .resetting:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .resetting")
      }
      
    case .unsupported:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .unsupported")
      }
      
    case .unauthorized:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .unauthorized")
      }
      
    case .poweredOff:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .poweredOff")
      }
      
    case .poweredOn:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is .poweredOn")
      }
      centralManager.scanForPeripherals(withServices: servicesInterested)
      
    @unknown default:
      if ( preLogLevel == "LOGLEVEL" ) {
        CSVfuncs.writeLog(">>BT central.state is Unknown Default")
      }
      break
    // unknown default
    }
  }

Upvotes: 0

Youssif Saeed
Youssif Saeed

Reputation: 13285

Unfortunately there isn't. A generic BLE disconnection usually has the "disconnection reason" as part of the disconnection event (see this), but this is not reliable and in any case CoreBluetooth does not directly expose this. I say "not directly expose this" because you do get the error parameter as part of the event, but this is not a direct mapping to the actual disconnection reason happening on the stack.

The only workaround you can do is if you add the intelligence yourself. In other words, when the peripheral is about to turn off or when it has very low battery, it can send that information to the central (via a GATT write/notification) to let it know that it is about to disconnect because the battery is low.

Have a look at the links below for more information:-

Upvotes: 2

Related Questions