Skip to content

Commit add12a4

Browse files
authored
Merge pull request #467 from loopandlearn/bt-reconnect
BLE: Delay reconnect 2s after disconnect
2 parents 6644846 + 46e86b8 commit add12a4

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

LoopFollow/BackgroundRefresh/BT/BluetoothDevice.swift

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,23 @@ class BluetoothDevice: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
223223

224224
func centralManager(_: CBCentralManager, didDisconnectPeripheral _: CBPeripheral, error _: Error?) {
225225
timeStampLastStatusUpdate = Date()
226-
227226
bluetoothDeviceDelegate?.didDisconnectFrom(bluetoothDevice: self)
227+
cancelConnectionTimer()
228+
229+
guard let ownPeripheral = peripheral else { return }
228230

229-
if let ownPeripheral = peripheral {
230-
centralManager?.connect(ownPeripheral, options: nil)
231+
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
232+
guard let self = self,
233+
let manager = self.centralManager,
234+
manager.state == .poweredOn else { return }
235+
236+
switch ownPeripheral.state {
237+
case .connected, .connecting:
238+
// Already (re)connecting; do nothing
239+
break
240+
default:
241+
manager.connect(ownPeripheral, options: nil)
242+
}
231243
}
232244
}
233245

0 commit comments

Comments
 (0)