-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMPCManager.swift
340 lines (297 loc) · 10.9 KB
/
MPCManager.swift
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//
// MPCManager.swift
// MPCFBandwidthTestApp
//
// Created by Alex Telegin on 24/11/2016.
// Copyright © 2016 Thali Project. All rights reserved.
//
import UIKit
import MultipeerConnectivity
public class MPCManager: NSObject, MCSessionDelegate, StreamDelegate {
let serviceType: String = "MPCF-out"
let returnServiceType: String = "MPCF-return"
var advertSession: MCSession! {
didSet {
advertSession.delegate = self
}
}
var browseSession: MCSession! {
didSet {
browseSession.delegate = self
}
}
var peerIDFirst: MCPeerID!
var peerIDSecond: MCPeerID!
var returnPeerID: MCPeerID!
var browser: Browser!
var advertiser: Advertiser!
var nameMaster: String!
var nameSlave: String!
var outputStreamFromAdvertiser: OutputStream?
var inputStreamToAdvertiser: InputStream?
var outputStreamFromBrowser: OutputStream?
var inputStreamToBrowser: InputStream?
var delegate: MPCManagerDelegate?
let maxReadBufferLength = 1024 * 1024
let bytesToSend: Int = 1024 * 1024
var startDate: Date!
var master = false
var returnSessionStarted = false
var outStreamOpen = false
var otherIDOne: MCPeerID!
var otherIDTwo: MCPeerID!
var numberOfConnections: Int = 0 {
didSet {
delegate?.peerCounterChanged()
}
}
// Singleton setup
init(master: Bool) {
super.init()
self.master = master
nameMaster = master ? "m1" : "m2"
nameSlave = master ? "s2" : "s1"
peerIDFirst = MCPeerID(displayName: nameMaster)
peerIDSecond = MCPeerID(displayName: nameSlave)
let advService = master ? serviceType : returnServiceType
let browserService = master ? returnServiceType : serviceType
// Advertiser
self.advertiser = Advertiser(peer: peerIDFirst, serviceType: advService, receivedInvitation: {
[weak self] session in
guard let strongSelf = self else { return }
strongSelf.advertSession = session.session
}, sessionNotConnected: {})
// Browser
self.browser = Browser(serviceType: browserService,
myPeerID: nameSlave,
foundPeer: handleFound,
lostPeer: handleLost)
}
func handleFound(_ peer: MCPeerID) {
do {
try browser!.inviteToConnect(peer, sessionConnected: {}, sessionNotConnected: {}, sessionCreated: {
[weak self] session in
guard let strongSelf = self else { return }
strongSelf.browseSession = session.session})
} catch {
print(MPCError.peerError)
}
}
func handleLost(_ peer: MCPeerID) {
}
func start() {
if master {
startAdvertising()
} else {
startBrowsing()
}
}
func stop() {
if master {
stopAdvertising()
} else {
stopBrowsing()
}
}
// MARK: - Session controls
func startAdvertising() {
self.advertiser.startAdvertising({_ in})
}
func stopAdvertising() {
self.advertiser.stopAdvertising()
}
func startBrowsing() {
self.browser.startListening { _ in }
}
func stopBrowsing() {
self.browser.stopListening()
}
func openStream(peer: MCPeerID) {
do {
guard let name = nameMaster else {
return
}
let stream = try advertSession.startStream(withName: "\(name)", toPeer: peer)
self.outputStreamFromAdvertiser = stream
self.outputStreamFromAdvertiser?.schedule(in: RunLoop.current,
forMode: RunLoopMode.defaultRunLoopMode)
self.outputStreamFromAdvertiser?.open()
RunLoop.current.run(until: Date.distantFuture)
} catch {
print("Couldn't open stream")
}
}
// func openReturnStreamAndSendData(peer: MCPeerID) {
// do {
// let stream = try advertSession.startStream(withName: "\(nameSlave)", toPeer: peer)
// self.outputStreamFromBrowser = stream
// self.outputStreamFromBrowser?.schedule(in: RunLoop.current,
// forMode: RunLoopMode.defaultRunLoopMode)
// self.outputStreamFromBrowser?.open()
// } catch {
// print("Couldn't open stream")
// }
// }
func sendData() {
// startDate = Date()
// let data = Data.generateDataBy(numberOfBytes: bytesToSend)
// dump(data)
//
// _ = data.withUnsafeBytes{ print(self.outputStreamFromAdvertiser?.write($0, maxLength: data.count) ?? 0.0 ) }
}
func sendReturnData() {
// let data = Data.generateDataBy(numberOfBytes: 1)
// dump(data)
//
// _ = data.withUnsafeBytes{ print(self.outputStreamFromBrowser?.write($0, maxLength: data.count) ?? 0.0 ) }
}
func readData() {
if let inputStream = self.inputStreamToBrowser {
// var buffer = [UInt8](repeating: 0, count: maxReadBufferLength)
//
// let bytesRead = inputStream.read(&buffer, maxLength: maxReadBufferLength)
// if bytesRead >= 0 {
// let data = Data(bytes: buffer, count: bytesRead)
// totalData += data.count
// print(totalData)
//
// if totalData == bytesToSend {
// print("Received all the data")
// self.inputStreamToBrowser?.close()
//// openReturnStreamAndSendData()
// }
// } else {
// closeStreams()
// }
}
}
func readReturnData() {
// if let returnInputStream = self.inputStreamToAdvertiser {
// var buffer = [UInt8](repeating: 0, count: maxReadBufferLength)
//
// let bytesRead = returnInputStream.read(&buffer, maxLength: maxReadBufferLength)
// if bytesRead >= 0 {
// let data = Data(bytes: buffer, count: bytesRead)
// let endDate = Date().timeIntervalSince(startDate as Date)
//
// print("Recieved in return \(data.count) byte. Time to send \(bytesToSend) bytes and get response: \(endDate) seconds")
// let speed = 1/endDate
// print("Transfer with confirmation speed: \(speed) MB/s")
// } else {
// closeStreams()
// }
// }
}
func closeStreams() {
// inputStreamToBrowser?.close()
// outputStreamFromAdvertiser?.close()
}
// MARK: - MCSessionDelegate
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
// if aStream == self.inputStreamToBrowser {
// switch eventCode {
// case Stream.Event.openCompleted:
// print("Main input - openCompleted")
// case Stream.Event.hasBytesAvailable:
// print("Main input - hasBytesAvailable")
// readData()
// case Stream.Event.hasSpaceAvailable:
// print("Main input - hasSpaceAvailable")
// case Stream.Event.errorOccurred:
// print("Main input - errorOccurred")
// case Stream.Event.endEncountered:
// print("Main input - errorOccurred")
// default:
// break
// }
// } else if aStream == self.inputStreamToAdvertiser {
// switch eventCode {
// case Stream.Event.openCompleted:
// print("Return input - Open Completed")
// case Stream.Event.hasBytesAvailable:
// print("Return input - hasBytesAvailable")
// readReturnData()
// case Stream.Event.hasSpaceAvailable:
// print("Return input - hasSpaceAvailable")
// case Stream.Event.errorOccurred:
// print("Return input - errorOccurred")
// case Stream.Event.endEncountered:
// print("Return input - endEncountered")
// default:
// break
// }
// }
}
// MARK: - MCSessionDelegate
public func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
// if session == session {
//
// } else if session == browseSession {
// print("hi")
// }
if state == .connected {
print("connected")
numberOfConnections += 1
if master {
if !outStreamOpen {
outStreamOpen = true
otherIDOne = peerID
stopAdvertising()
startBrowsing()
} else {
otherIDTwo = peerID
stopBrowsing()
openStream(peer: otherIDOne)
}
} else {
if !returnSessionStarted {
returnSessionStarted = true
otherIDOne = peerID
stopBrowsing()
startAdvertising()
} else {
otherIDTwo = peerID
stopAdvertising()
DispatchQueue.main.asyncAfter(deadline: .now()) {
self.openStream(peer: self.otherIDTwo)
}
}
}
// }
} else if state == .notConnected {
print("disconnected")
// if self.session.connectedPeers.contains(peerID) {
numberOfConnections -= 1
// }
}
}
public func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
}
public func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
print(streamName)
if streamName == "m1" {
print("Master stream received")
self.inputStreamToBrowser = stream
} else if streamName == "m2" {
print("Slave stream received")
self.inputStreamToBrowser = stream
}
// if streamName == "Outgoing \(peerID.displayName)" {
// self.inputStreamToBrowser = stream
// } else if streamName == "Return \(peerID.displayName)" {
// self.inputStreamToAdvertiser = stream
// }
// stream.schedule(in: RunLoop.current,
// forMode: RunLoopMode.defaultRunLoopMode)
// stream.open()
// stream.delegate = self
// RunLoop.current.run(until: Date.distantFuture)
}
public func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
public func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL, withError error: Error?) {
}
}
protocol MPCManagerDelegate {
func peerCounterChanged()
}