-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReceiverConnection.swift
More file actions
207 lines (181 loc) · 7.61 KB
/
Copy pathReceiverConnection.swift
File metadata and controls
207 lines (181 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@preconcurrency @unsafe import ExternalAccessory
import Foundation
import OSLog
/// This error will be thrown if `EASession` or `Stream` cannot be opened for one of the required MFi protocols.
struct ConnectionFailure: Error {}
final class ReceiverConnection: NSObject, @unchecked Sendable {
private static let threadWorker = ThreadWorker(name: "MFi-worker-thread")
private static let nmeaProtocol = "com.emlid.nmea"
private static let correctionsProtocol = "com.emlid.corrections"
private let nmeaSessionKey: String
private let nmeaStreamKey: String
private let correctionsSessionKey: String
private let correctionsStreamKey: String
private let nmeaInputBuffer: String
private let accessory: EAAccessory
private let nmeaContinuation: AsyncStream<String>.Continuation
let nmeaStream: AsyncStream<String>
var name: String {
return accessory.name
}
var serialNumber: String {
return accessory.serialNumber
}
var firmwareVersion: String {
return accessory.firmwareRevision
}
var model: String {
return accessory.modelNumber
}
private let logger = Logger(subsystem: "Connection", category: "service")
init(accessory: EAAccessory) async throws {
self.accessory = accessory
nmeaSessionKey = "nmea-session-\(accessory.connectionID)"
nmeaStreamKey = "nmea-stream-\(accessory.connectionID)"
correctionsSessionKey = "corrections-session-\(accessory.connectionID)"
correctionsStreamKey = "corrections-stream-\(accessory.connectionID)"
nmeaInputBuffer = "nmea-input-buffer-\(accessory.connectionID)"
(nmeaStream, nmeaContinuation) = AsyncStream.makeStream()
super.init()
try await openStreams()
}
deinit {
Self.threadWorker.runSync(closeStreams)
nmeaContinuation.finish()
}
func send(corrections: Data) {
Self.threadWorker.runAsync {
self.sendCorrections(data: corrections)
}
}
private func openStreams() async throws {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
Self.threadWorker.runAsync { [unowned self] in
guard
let nmeaSession = EASession(accessory: self.accessory, forProtocol: Self.nmeaProtocol),
let nmeaInputStream = nmeaSession.inputStream,
let correctionsSession = EASession(
accessory: self.accessory,
forProtocol: Self.correctionsProtocol),
let correctionsOutputStream = correctionsSession.outputStream
else {
continuation.resume(throwing: ConnectionFailure())
return
}
let thread = Thread.current
thread.threadDictionary.setValue(nmeaSession, forKey: nmeaSessionKey)
thread.threadDictionary.setValue(correctionsSession, forKey: correctionsSessionKey)
thread.threadDictionary.setValue(nmeaInputStream, forKey: nmeaStreamKey)
thread.threadDictionary.setValue(correctionsOutputStream, forKey: correctionsStreamKey)
unsafe nmeaInputStream.delegate = self
nmeaInputStream.schedule(in: .current, forMode: .default)
nmeaInputStream.open()
unsafe correctionsOutputStream.delegate = self
correctionsOutputStream.schedule(in: .current, forMode: .default)
correctionsOutputStream.open()
continuation.resume()
}
}
}
private func closeStreams() {
let thread = Thread.current
guard
let nmeaSession = thread.threadDictionary[nmeaSessionKey] as? EASession,
let correctionsSession = thread.threadDictionary[correctionsSessionKey] as? EASession
else {
return
}
let streams = [nmeaSession.inputStream, correctionsSession.outputStream]
for case .some(let stream) in streams {
unsafe stream.delegate = nil
stream.close()
stream.remove(from: .current, forMode: .default)
}
thread.threadDictionary.removeObjects(forKeys: [
nmeaSessionKey,
nmeaStreamKey,
correctionsSessionKey,
correctionsStreamKey,
nmeaInputBuffer
])
}
private func sendCorrections(data: Data) {
let thread = Thread.current
guard
let correctionsOutputStream = thread.threadDictionary[correctionsStreamKey] as? OutputStream,
correctionsOutputStream.streamStatus == .open,
correctionsOutputStream.hasSpaceAvailable
else {
return
}
let writeStatus = unsafe data.withUnsafeBytes { bytes in
unsafe correctionsOutputStream.write(bytes.baseAddress!, maxLength: bytes.count)
}
switch writeStatus {
case -1:
logger.error("Failed to send corrections data to receiver \(correctionsOutputStream.streamError!)")
case 0:
logger.notice("Correction buffer is at capacity")
case ...Int.max:
logger.trace("Corrections sent to receiver")
default:
break
}
}
private func handleNmeaInput(nmeaInputStream: InputStream, _ eventCode: Stream.Event) {
var currentMessage: Data
if let existingBuffer = Thread.current.threadDictionary[nmeaInputBuffer] as? Data {
currentMessage = existingBuffer
} else {
currentMessage = Data()
}
switch eventCode {
case .hasBytesAvailable:
var bytes = [UInt8](repeating: 0, count: 1024)
let bytesRead = unsafe nmeaInputStream.read(&bytes, maxLength: 1024)
if bytesRead != -1 {
for byte in bytes.prefix(bytesRead) {
switch byte {
// Each NMEA message ends with "\r\n", so we can split messages by "\n".
case Character("\n").asciiValue:
nmeaContinuation.yield(String(decoding: currentMessage, as: UTF8.self))
currentMessage.removeAll(keepingCapacity: true)
// And safely drop "\r".
case Character("\r").asciiValue:
continue
default:
currentMessage.append(byte)
}
}
} else if let error = nmeaInputStream.streamError {
logger.error("Failed to read bytes from stream with error \(error)")
}
case .errorOccurred:
logger.error("NMEA stream failed \(nmeaInputStream.streamError!)")
nmeaContinuation.finish()
case .endEncountered:
nmeaContinuation.finish()
default:
break
}
Thread.current.threadDictionary[nmeaInputBuffer] = currentMessage
}
static func checkAccessoryIsSupported(_ accessory: EAAccessory) -> Bool {
return accessory
.protocolStrings
.count { protocolString in
protocolString == correctionsProtocol || protocolString == nmeaProtocol
} == 2
}
}
extension ReceiverConnection: StreamDelegate {
func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch aStream {
case Thread.current.threadDictionary[nmeaStreamKey] as? InputStream:
let stream = aStream as! InputStream
handleNmeaInput(nmeaInputStream: stream, eventCode)
default:
break
}
}
}