diff --git a/app/src/main/java/com/geeksville/mesh/service/BluetoothInterface.kt b/app/src/main/java/com/geeksville/mesh/service/BluetoothInterface.kt index 5a3cac3b7..235a6e58c 100644 --- a/app/src/main/java/com/geeksville/mesh/service/BluetoothInterface.kt +++ b/app/src/main/java/com/geeksville/mesh/service/BluetoothInterface.kt @@ -354,42 +354,46 @@ class BluetoothInterface(val service: RadioInterfaceService, val address: String private var isFirstTime = true private fun doDiscoverServicesAndInit() { - safe!!.asyncDiscoverServices { discRes -> - try { - discRes.getOrThrow() + val s = safe + if (s == null) + warn("Interface is shutting down, so skipping discover") + else + s.asyncDiscoverServices { discRes -> + try { + discRes.getOrThrow() - service.serviceScope.handledLaunch { - try { - debug("Discovered services!") - delay(1000) // android BLE is buggy and needs a 500ms sleep before calling getChracteristic, or you might get back null + service.serviceScope.handledLaunch { + try { + debug("Discovered services!") + delay(1000) // android BLE is buggy and needs a 500ms sleep before calling getChracteristic, or you might get back null - /* if (isFirstTime) { - isFirstTime = false - throw BLEException("Faking a BLE failure") - } */ + /* if (isFirstTime) { + isFirstTime = false + throw BLEException("Faking a BLE failure") + } */ - fromNum = getCharacteristic(BTM_FROMNUM_CHARACTER) + fromNum = getCharacteristic(BTM_FROMNUM_CHARACTER) - // We treat the first send by a client as special - isFirstSend = true + // We treat the first send by a client as special + isFirstSend = true - // Now tell clients they can (finally use the api) - service.onConnect() + // Now tell clients they can (finally use the api) + service.onConnect() - // Immediately broadcast any queued packets sitting on the device - doReadFromRadio(true) - } catch (ex: BLEException) { - scheduleReconnect( - "Unexpected error in initial device enumeration, forcing disconnect $ex" - ) + // Immediately broadcast any queued packets sitting on the device + doReadFromRadio(true) + } catch (ex: BLEException) { + scheduleReconnect( + "Unexpected error in initial device enumeration, forcing disconnect $ex" + ) + } } + } catch (ex: BLEException) { + scheduleReconnect( + "Unexpected error discovering services, forcing disconnect $ex" + ) } - } catch (ex: BLEException) { - scheduleReconnect( - "Unexpected error discovering services, forcing disconnect $ex" - ) } - } } private var needForceRefresh = true