Skip to content

Commit

Permalink
Fix disconnect cleanup for bg task (#130)
Browse files Browse the repository at this point in the history
* Transfer disconnect clean up responsibility to the background task if there is one

Also fixes incorrect assumptions on what the states should be initially for auto reconnect, and when calling cancel everything - cancel everything is not the same as calling disconnect explicitly.

* Bump version to 0.4.2

* Clear disconnect clean up after running it
  • Loading branch information
Jeremy Chiang authored Feb 5, 2018
1 parent 5be5d50 commit 19ac7af
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 16 deletions.
4 changes: 2 additions & 2 deletions Bluejay.podspec
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
Pod::Spec.new do |spec|
spec.name = 'Bluejay'
spec.version = '0.4.1'
spec.version = '0.4.2'
spec.license = { type: 'MIT', file: 'LICENSE' }
spec.homepage = 'https://github.com/steamclock/bluejay'
spec.authors = { 'Jeremy Chiang' => 'jeremy@steamclock.com' }
spec.summary = 'Bluejay is a simple Swift framework for building reliable Bluetooth apps.'
spec.homepage = 'https://github.com/steamclock/bluejay'
spec.source = { git: 'https://github.com/steamclock/bluejay.git', tag: 'v0.4.1' }
spec.source = { git: 'https://github.com/steamclock/bluejay.git', tag: 'v0.4.2' }
spec.source_files = 'Bluejay/Bluejay/*.{h,swift}'
spec.framework = 'SystemConfiguration'
spec.platform = :ios, '9.3'
Expand Down
60 changes: 47 additions & 13 deletions Bluejay/Bluejay/Bluejay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public class Bluejay: NSObject {
/// Reference to a peripheral that is connected. If this is nil, then the peripheral should either be disconnected or still connecting. This is used to help determine the state of the peripheral's connection.
private var connectedPeripheral: Peripheral?

/// Allowing or disallowing reconnection attempts upon a disconnection. It should only be set to true after a successful connection to a peripheral, and remain true unless there is an explicit and expected disconnection.
private var shouldAutoReconnect = false
/// Allowing or disallowing reconnection attempts upon a disconnection. It should only be set to false after an explicit and expected disconnection.
private var shouldAutoReconnect = true

/// Reference to the background task used for supporting state restoration.
private var startupBackgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
Expand All @@ -45,6 +45,8 @@ public class Bluejay: NSObject {
/// True when background task is running, and helps prevent calling regular read/write/listen.
private var isRunningBackgroundTask = false

private var disconnectCleanUp: (() -> Void)?

// MARK: - Internal Properties

/// Contains the operations to execute in FIFO order.
Expand Down Expand Up @@ -192,8 +194,6 @@ public class Bluejay: NSObject {
- Parameter error: If nil, all tasks in the queue will be cancelled without any errors. If an error is provided, all tasks in the queue will be failed with the supplied error.
*/
public func cancelEverything(_ error: Error? = nil) {
shouldAutoReconnect = false

queue.cancelAll(error)

if isConnecting {
Expand Down Expand Up @@ -591,6 +591,11 @@ public class Bluejay: NSObject {
weakSelf.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
weakSelf.unregister(observer: synchronizedPeripheral)

if error == BluejayError.notConnected as NSError {
weakSelf.disconnectCleanUp?()
weakSelf.disconnectCleanUp = nil
}
}
}
}
Expand Down Expand Up @@ -644,6 +649,11 @@ public class Bluejay: NSObject {
weakSelf.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
weakSelf.unregister(observer: synchronizedPeripheral)

if error == BluejayError.notConnected as NSError {
weakSelf.disconnectCleanUp?()
weakSelf.disconnectCleanUp = nil
}
}
}
}
Expand Down Expand Up @@ -699,6 +709,11 @@ public class Bluejay: NSObject {
weakSelf.isRunningBackgroundTask = false
completionOnMainThread(.failure(error))
weakSelf.unregister(observer: synchronizedPeripheral)

if error == BluejayError.notConnected as NSError {
weakSelf.disconnectCleanUp?()
weakSelf.disconnectCleanUp = nil
}
}
}
}
Expand Down Expand Up @@ -893,6 +908,7 @@ extension Bluejay: CBCentralManagerDelegate {
}

shouldAutoReconnect = true
log("Should auto-reconnect: \(shouldAutoReconnect)")

queue.process(event: .didConnectPeripheral(peripheral), error: nil)

Expand Down Expand Up @@ -934,17 +950,35 @@ extension Bluejay: CBCentralManagerDelegate {
}
}

connectingPeripheral = nil
connectedPeripheral = nil

log("Should auto-reconnect: \(shouldAutoReconnect)")

if shouldAutoReconnect {
log("Issuing reconnect to: \(peripheral.name ?? peripheral.identifier.uuidString)")
connect(PeripheralIdentifier(uuid: peripheral.identifier), timeout: previousConnectionTimeout ?? .none, completion: {_ in })
disconnectCleanUp = { [weak self] in
guard let weakSelf = self else {
return
}

log("Disconnect clean up.")

weakSelf.connectingPeripheral = nil
weakSelf.connectedPeripheral = nil

log("Should auto-reconnect: \(weakSelf.shouldAutoReconnect)")

if weakSelf.shouldAutoReconnect {
log("Issuing reconnect to: \(peripheral.name ?? peripheral.identifier.uuidString)")
weakSelf.connect(
PeripheralIdentifier(uuid: peripheral.identifier),
timeout: weakSelf.previousConnectionTimeout ?? .none,
completion: {_ in }
)
}

UIApplication.shared.endBackgroundTask(backgroundTask)
}

UIApplication.shared.endBackgroundTask(backgroundTask)
if isRunningBackgroundTask {
log("Delaying disconnect clean up due to running background task.")
} else {
disconnectCleanUp?()
}
}

/**
Expand Down
2 changes: 1 addition & 1 deletion Bluejay/Bluejay/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>0.4.1</string>
<string>0.4.2</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
Expand Down

0 comments on commit 19ac7af

Please sign in to comment.