Explorar o código

BLE: Delay reconnect 2s after disconnect

Jonas Björkert hai 9 meses
pai
achega
46e86b80b7
Modificáronse 1 ficheiros con 15 adicións e 3 borrados
  1. 15 3
      LoopFollow/BackgroundRefresh/BT/BluetoothDevice.swift

+ 15 - 3
LoopFollow/BackgroundRefresh/BT/BluetoothDevice.swift

@@ -223,11 +223,23 @@ class BluetoothDevice: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
 
 
     func centralManager(_: CBCentralManager, didDisconnectPeripheral _: CBPeripheral, error _: Error?) {
     func centralManager(_: CBCentralManager, didDisconnectPeripheral _: CBPeripheral, error _: Error?) {
         timeStampLastStatusUpdate = Date()
         timeStampLastStatusUpdate = Date()
-
         bluetoothDeviceDelegate?.didDisconnectFrom(bluetoothDevice: self)
         bluetoothDeviceDelegate?.didDisconnectFrom(bluetoothDevice: self)
+        cancelConnectionTimer()
+
+        guard let ownPeripheral = peripheral else { return }
 
 
-        if let ownPeripheral = peripheral {
-            centralManager?.connect(ownPeripheral, options: nil)
+        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
+            guard let self = self,
+                  let manager = self.centralManager,
+                  manager.state == .poweredOn else { return }
+
+            switch ownPeripheral.state {
+            case .connected, .connecting:
+                // Already (re)connecting; do nothing
+                break
+            default:
+                manager.connect(ownPeripheral, options: nil)
+            }
         }
         }
     }
     }