Skip to content

Commit e4c60b5

Browse files
committed
more refactoring of reconnection logic
1 parent 56c8d4e commit e4c60b5

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

Sources/SwiftOCA/OCP.1/Ocp1Connection+Connect.swift

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ private extension Ocp1Error {
3333
}
3434
}
3535

36+
private extension Error {
37+
var ocp1ConnectionState: Ocp1ConnectionState {
38+
(self as? Ocp1Error)?.connectionState ?? .connectionFailed
39+
}
40+
}
41+
3642
private extension Ocp1ConnectionState {
3743
var error: Ocp1Error? {
3844
switch self {
@@ -120,12 +126,13 @@ extension Ocp1Connection {
120126

121127
/// reconnect to the OCA device with exponential backoff, updating
122128
/// connectionState
123-
private func reconnectDeviceWithBackoff() async throws {
129+
func reconnectDeviceWithBackoff() async throws {
124130
var lastError: Error?
125131
var backoff: Duration = options.reconnectPauseInterval
126132

127133
for i in 0..<options.reconnectMaxTries {
128134
do {
135+
logger.trace("reconnection attempt \(i + 1)")
129136
try await _connectDeviceWithTimeout()
130137
await _didConnect()
131138
break
@@ -142,9 +149,10 @@ extension Ocp1Connection {
142149

143150
if let lastError {
144151
logger.trace("gave up attempting to reconnect: \(lastError)")
152+
_updateConnectionState(lastError.ocp1ConnectionState)
145153
throw lastError
146154
} else if !isConnected {
147-
logger.trace("reconnection finished without connection being established")
155+
logger.trace("gave up attempting to reconnect")
148156
_updateConnectionState(.notConnected)
149157
throw Ocp1Error.notConnected
150158
}
@@ -233,7 +241,7 @@ public extension Ocp1Connection {
233241
try await _connectDeviceWithTimeout()
234242
} catch {
235243
logger.trace("connection failed: \(error)")
236-
_updateConnectionState((error as? Ocp1Error)?.connectionState ?? .connectionFailed)
244+
_updateConnectionState(error.ocp1ConnectionState)
237245
throw error
238246
}
239247

0 commit comments

Comments
 (0)