Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 43 additions & 33 deletions Facett/BLEConnectionHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,19 @@ class BLEConnectionHandler {

// UI updates must happen on main thread
DispatchQueue.main.async {
let wasEmpty = bleManager.connectedGoPros.isEmpty

bleManager.connectedGoPros[uuid] = gopro // Move to connected list
bleManager.connectingGoPros.removeValue(forKey: uuid) // Remove from connecting list
bleManager.discoveredGoPros.removeValue(forKey: uuid) // Remove from discovered list

// Reset initialization flag for new connection
gopro.hasReceivedInitialStatus = false

if wasEmpty {
bleManager.startKeepAliveTimer()
}

// Notify that camera is connected
bleManager.onCameraConnected?(uuid)
}
Expand All @@ -55,31 +61,39 @@ class BLEConnectionHandler {
guard let bleManager = bleManager else { return }

let uuid = peripheral.identifier
ErrorHandler.info("\(CameraIdentityManager.shared.getDisplayName(for: uuid, currentName: peripheral.name)) disconnected.")
let cameraName = CameraIdentityManager.shared.getDisplayName(for: uuid, currentName: peripheral.name)
ErrorHandler.info("\(cameraName) disconnected.")

// Cancel any pending connection retry timers
bleManager.connectionManager.cancelConnectionRetry(for: uuid)

bleManager.cleanupDeviceState(for: uuid)

DispatchQueue.main.async {
let isSleeping = bleManager.isDeviceSleeping(uuid)
let wasConnected = bleManager.connectedGoPros[uuid] != nil

if let gopro = bleManager.connectedGoPros[uuid] {
bleManager.connectedGoPros.removeValue(forKey: uuid)
if !isSleeping {
bleManager.discoveredGoPros[uuid] = gopro
} else {
ErrorHandler.info("\(CameraIdentityManager.shared.getDisplayName(for: uuid, currentName: peripheral.name)) is sleeping - not moving to discovered list")
ErrorHandler.debug("\(cameraName) is sleeping - not moving to discovered list")
}
} else if let gopro = bleManager.connectingGoPros[uuid] {
bleManager.connectingGoPros.removeValue(forKey: uuid)
if !isSleeping {
bleManager.discoveredGoPros[uuid] = gopro
} else {
ErrorHandler.info("\(CameraIdentityManager.shared.getDisplayName(for: uuid, currentName: peripheral.name)) is sleeping - not moving to discovered list")
ErrorHandler.debug("\(cameraName) is sleeping - not moving to discovered list")
}
}

if bleManager.connectedGoPros.isEmpty {
bleManager.stopKeepAliveTimer()
}

if wasConnected && !isSleeping {
bleManager.scheduleReconnectIfNeeded(for: uuid)
}
}
}

Expand All @@ -104,7 +118,7 @@ class BLEConnectionHandler {
// Iterate through discovered services
for service in services {
if service.uuid == BLEManager.Constants.UUIDs.goproService {
ErrorHandler.info("Discovered GoPro service for \(peripheral.name ?? "a device")")
ErrorHandler.debug("Discovered GoPro service for \(peripheral.name ?? "a device")")

// Discover characteristics for the GoPro service
peripheral.discoverCharacteristics(
Expand All @@ -119,7 +133,7 @@ class BLEConnectionHandler {
for: service
)
} else if service.uuid == BLEManager.Constants.UUIDs.goproWiFiService {
ErrorHandler.info("Discovered GoPro WiFi Access Point service for \(peripheral.name ?? "a device")")
ErrorHandler.debug("Discovered GoPro WiFi Access Point service for \(peripheral.name ?? "a device")")

// Discover characteristics for the GoPro WiFi service
peripheral.discoverCharacteristics(
Expand Down Expand Up @@ -152,75 +166,71 @@ class BLEConnectionHandler {
return
}

let deviceName = peripheral.name ?? "a device"
var discoveredNames: [String] = []

for characteristic in characteristics {
switch characteristic.uuid {
case BLEManager.Constants.UUIDs.query:
ErrorHandler.info("Discovered 'Query' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Query")

case BLEManager.Constants.UUIDs.queryResponse:
ErrorHandler.info("Discovered 'Query Response' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Query Response")
if characteristic.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: characteristic) // Enable notifications
ErrorHandler.info("Subscribed to notifications for 'Query Response'")
peripheral.setNotifyValue(true, for: characteristic)
}

case BLEManager.Constants.UUIDs.command:
ErrorHandler.info("Discovered 'Command' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Command")

case BLEManager.Constants.UUIDs.commandResponse:
ErrorHandler.info("Discovered 'Command Response' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Command Response")
if characteristic.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: characteristic) // Enable notifications
ErrorHandler.info("Subscribed to notifications for 'Command Response'")
peripheral.setNotifyValue(true, for: characteristic)
}

case BLEManager.Constants.UUIDs.settings:
ErrorHandler.info("Discovered 'Settings' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Settings")

case BLEManager.Constants.UUIDs.settingsResponse:
ErrorHandler.info("Discovered 'Settings Response' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("Settings Response")
if characteristic.properties.contains(.notify) {
peripheral.setNotifyValue(true, for: characteristic) // Enable notifications
ErrorHandler.info("Subscribed to notifications for 'Settings Response'")
peripheral.setNotifyValue(true, for: characteristic)
}

// GoPro WiFi Access Point characteristics
case BLEManager.Constants.UUIDs.wifiAPSSID:
ErrorHandler.info("Discovered 'WiFi AP SSID' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("WiFi SSID")
if characteristic.properties.contains(.read) {
// Read the current WiFi SSID
peripheral.readValue(for: characteristic)
ErrorHandler.info("Reading WiFi AP SSID from \(peripheral.name ?? "a device")")
}

case BLEManager.Constants.UUIDs.wifiAPPassword:
ErrorHandler.info("Discovered 'WiFi AP Password' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("WiFi Password")
if characteristic.properties.contains(.read) {
// Read the current WiFi password
peripheral.readValue(for: characteristic)
ErrorHandler.info("Reading WiFi AP Password from \(peripheral.name ?? "a device")")
}

case BLEManager.Constants.UUIDs.wifiAPPower:
ErrorHandler.info("Discovered 'WiFi AP Power' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("WiFi Power")

case BLEManager.Constants.UUIDs.wifiAPState:
ErrorHandler.info("Discovered 'WiFi AP State' characteristic for \(peripheral.name ?? "a device")")
discoveredNames.append("WiFi State")
if characteristic.properties.contains(.read) {
// Read the current WiFi AP state
peripheral.readValue(for: characteristic)
ErrorHandler.info("Reading WiFi AP State from \(peripheral.name ?? "a device")")
}
if characteristic.properties.contains(.indicate) {
peripheral.setNotifyValue(true, for: characteristic) // Enable indications
ErrorHandler.info("Subscribed to indications for 'WiFi AP State'")
peripheral.setNotifyValue(true, for: characteristic)
}

default:
ErrorHandler.info("Discovered unknown characteristic \(characteristic.uuid) for \(peripheral.name ?? "a device")")
ErrorHandler.debug("Unknown characteristic \(characteristic.uuid) for \(deviceName)")
}
}

if !discoveredNames.isEmpty {
ErrorHandler.debug("Configured \(discoveredNames.count) characteristics for \(deviceName): \(discoveredNames.joined(separator: ", "))")
}

bleManager.claimControl(for: peripheral.identifier)
}
}
10 changes: 5 additions & 5 deletions Facett/BLEConnectionManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class BLEConnectionManager: ObservableObject {
private var connectionRetryTimers: [UUID: Timer] = [:]
private var connectionAttemptTimers: [UUID: Timer] = [:]
private var maxRetryAttempts = 3
private var connectionTimeout: TimeInterval = 30.0
private var connectionTimeout: TimeInterval = 15.0

// Callbacks
var onConnectionSuccess: ((UUID) -> Void)?
Expand All @@ -91,7 +91,7 @@ class BLEConnectionManager: ObservableObject {

/// Start connection retry process for a device
func startConnectionRetry(for uuid: UUID, maxAttempts: Int = 3) {
ErrorHandler.info("Starting connection retry for device \(uuid)")
ErrorHandler.debug("Starting connection retry for device \(uuid)")

connectionRetryCount[uuid] = 0
maxRetryAttempts = maxAttempts
Expand All @@ -104,7 +104,7 @@ class BLEConnectionManager: ObservableObject {
private func attemptConnection(_ uuid: UUID) {
guard let currentAttempt = connectionRetryCount[uuid] else { return }

ErrorHandler.info("Connection attempt \(currentAttempt + 1)/\(maxRetryAttempts) for device \(uuid)")
ErrorHandler.debug("Connection attempt \(currentAttempt + 1)/\(maxRetryAttempts) for device \(uuid)")

// Start connection timeout timer
connectionAttemptTimers[uuid] = Timer.scheduledTimer(withTimeInterval: connectionTimeout, repeats: false) { [weak self] _ in
Expand All @@ -121,7 +121,7 @@ class BLEConnectionManager: ObservableObject {

/// Handle successful connection
func handleConnectionSuccess(_ uuid: UUID) {
ErrorHandler.info("Connection successful for device \(uuid)")
ErrorHandler.debug("Connection successful for device \(uuid)")

// Cancel timers
connectionAttemptTimers[uuid]?.invalidate()
Expand Down Expand Up @@ -173,7 +173,7 @@ class BLEConnectionManager: ObservableObject {

/// Cancel connection retry for a device
func cancelConnectionRetry(for uuid: UUID) {
ErrorHandler.info("Cancelling connection retry for device \(uuid)")
ErrorHandler.debug("Cancelling connection retry for device \(uuid)")

connectionRetryTimers[uuid]?.invalidate()
connectionAttemptTimers[uuid]?.invalidate()
Expand Down
Loading