-
Notifications
You must be signed in to change notification settings - Fork 20
/
BluetoothSerial.swift
292 lines (225 loc) · 10.9 KB
/
BluetoothSerial.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
//
// BluetoothSerial.swift (originally DZBluetoothSerialHandler.swift)
// HM10 Serial
//
// Created by Alex on 09-08-15.
// Copyright (c) 2017 Hangar42. All rights reserved.
//
//
import UIKit
import CoreBluetooth
/// Global serial handler, don't forget to initialize it with init(delgate:)
var serial: BluetoothSerial!
// Delegate functions
protocol BluetoothSerialDelegate {
// ** Required **
/// Called when de state of the CBCentralManager changes (e.g. when bluetooth is turned on/off)
func serialDidChangeState()
/// Called when a peripheral disconnected
func serialDidDisconnect(_ peripheral: CBPeripheral, error: NSError?)
// ** Optionals **
/// Called when a message is received
func serialDidReceiveString(_ message: String)
/// Called when a message is received
func serialDidReceiveBytes(_ bytes: [UInt8])
/// Called when a message is received
func serialDidReceiveData(_ data: Data)
/// Called when the RSSI of the connected peripheral is read
func serialDidReadRSSI(_ rssi: NSNumber)
/// Called when a new peripheral is discovered while scanning. Also gives the RSSI (signal strength)
func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?)
/// Called when a peripheral is connected (but not yet ready for cummunication)
func serialDidConnect(_ peripheral: CBPeripheral)
/// Called when a pending connection failed
func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?)
/// Called when a peripheral is ready for communication
func serialIsReady(_ peripheral: CBPeripheral)
}
// Make some of the delegate functions optional
extension BluetoothSerialDelegate {
func serialDidReceiveString(_ message: String) {}
func serialDidReceiveBytes(_ bytes: [UInt8]) {}
func serialDidReceiveData(_ data: Data) {}
func serialDidReadRSSI(_ rssi: NSNumber) {}
func serialDidDiscoverPeripheral(_ peripheral: CBPeripheral, RSSI: NSNumber?) {}
func serialDidConnect(_ peripheral: CBPeripheral) {}
func serialDidFailToConnect(_ peripheral: CBPeripheral, error: NSError?) {}
func serialIsReady(_ peripheral: CBPeripheral) {}
}
final class BluetoothSerial: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
// MARK: Variables
/// The delegate object the BluetoothDelegate methods will be called upon
var delegate: BluetoothSerialDelegate!
/// The CBCentralManager this bluetooth serial handler uses for... well, everything really
var centralManager: CBCentralManager!
/// The peripheral we're trying to connect to (nil if none)
var pendingPeripheral: CBPeripheral?
/// The connected peripheral (nil if none is connected)
var connectedPeripheral: CBPeripheral?
/// The characteristic 0xFFE1 we need to write to, of the connectedPeripheral
weak var writeCharacteristic: CBCharacteristic?
/// Whether this serial is ready to send and receive data
var isReady: Bool {
get {
return centralManager.state == .poweredOn &&
connectedPeripheral != nil &&
writeCharacteristic != nil
}
}
/// Whether this serial is looking for advertising peripherals
var isScanning: Bool {
return centralManager.isScanning
}
/// Whether the state of the centralManager is .poweredOn
var isPoweredOn: Bool {
return centralManager.state == .poweredOn
}
/// UUID of the service to look for.
var serviceUUID = CBUUID(string: "FFE0")
/// UUID of the characteristic to look for.
var characteristicUUID = CBUUID(string: "FFE1")
/// Whether to write to the HM10 with or without response. Set automatically.
/// Legit HM10 modules (from JNHuaMao) require 'Write without Response',
/// while fake modules (e.g. from Bolutek) require 'Write with Response'.
private var writeType: CBCharacteristicWriteType = .withoutResponse
// MARK: functions
/// Always use this to initialize an instance
init(delegate: BluetoothSerialDelegate) {
super.init()
self.delegate = delegate
centralManager = CBCentralManager(delegate: self, queue: nil)
}
/// Start scanning for peripherals
func startScan() {
guard centralManager.state == .poweredOn else { return }
// start scanning for peripherals with correct service UUID
centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
// retrieve peripherals that are already connected
// see this stackoverflow question http://stackoverflow.com/questions/13286487
let peripherals = centralManager.retrieveConnectedPeripherals(withServices: [serviceUUID])
for peripheral in peripherals {
delegate.serialDidDiscoverPeripheral(peripheral, RSSI: nil)
}
}
/// Stop scanning for peripherals
func stopScan() {
centralManager.stopScan()
}
/// Try to connect to the given peripheral
func connectToPeripheral(_ peripheral: CBPeripheral) {
pendingPeripheral = peripheral
centralManager.connect(peripheral, options: nil)
}
/// Disconnect from the connected peripheral or stop connecting to it
func disconnect() {
if let p = connectedPeripheral {
centralManager.cancelPeripheralConnection(p)
} else if let p = pendingPeripheral {
centralManager.cancelPeripheralConnection(p) //TODO: Test whether its neccesary to set p to nil
}
}
/// The didReadRSSI delegate function will be called after calling this function
func readRSSI() {
guard isReady else { return }
connectedPeripheral!.readRSSI()
}
/// Send a string to the device
func sendMessageToDevice(_ message: String) {
guard isReady else { return }
if let data = message.data(using: String.Encoding.utf8) {
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
}
/// Send an array of bytes to the device
func sendBytesToDevice(_ bytes: [UInt8]) {
guard isReady else { return }
let data = Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
/// Send data to the device
func sendDataToDevice(_ data: Data) {
guard isReady else { return }
connectedPeripheral!.writeValue(data, for: writeCharacteristic!, type: writeType)
}
// MARK: CBCentralManagerDelegate functions
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// just send it to the delegate
delegate.serialDidDiscoverPeripheral(peripheral, RSSI: RSSI)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// set some stuff right
peripheral.delegate = self
pendingPeripheral = nil
connectedPeripheral = peripheral
// send it to the delegate
delegate.serialDidConnect(peripheral)
// Okay, the peripheral is connected but we're not ready yet!
// First get the 0xFFE0 service
// Then get the 0xFFE1 characteristic of this service
// Subscribe to it & create a weak reference to it (for writing later on),
// and find out the writeType by looking at characteristic.properties.
// Only then we're ready for communication
peripheral.discoverServices([serviceUUID])
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
connectedPeripheral = nil
pendingPeripheral = nil
// send it to the delegate
delegate.serialDidDisconnect(peripheral, error: error as NSError?)
}
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
pendingPeripheral = nil
// just send it to the delegate
delegate.serialDidFailToConnect(peripheral, error: error as NSError?)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
// note that "didDisconnectPeripheral" won't be called if BLE is turned off while connected
connectedPeripheral = nil
pendingPeripheral = nil
// send it to the delegate
delegate.serialDidChangeState()
}
// MARK: CBPeripheralDelegate functions
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
// discover the 0xFFE1 characteristic for all services (though there should only be one)
for service in peripheral.services! {
peripheral.discoverCharacteristics([characteristicUUID], for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// check whether the characteristic we're looking for (0xFFE1) is present - just to be sure
for characteristic in service.characteristics! {
if characteristic.uuid == characteristicUUID {
// subscribe to this value (so we'll get notified when there is serial data for us..)
peripheral.setNotifyValue(true, for: characteristic)
// keep a reference to this characteristic so we can write to it
writeCharacteristic = characteristic
// find out writeType
writeType = characteristic.properties.contains(.write) ? .withResponse : .withoutResponse
// notify the delegate we're ready for communication
delegate.serialIsReady(peripheral)
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// notify the delegate in different ways
// if you don't use one of these, just comment it (for optimum efficiency :])
let data = characteristic.value
guard data != nil else { return }
// first the data
delegate.serialDidReceiveData(data!)
// then the string
if let str = String(data: data!, encoding: String.Encoding.utf8) {
delegate.serialDidReceiveString(str)
} else {
//print("Received an invalid string!") uncomment for debugging
}
// now the bytes array
var bytes = [UInt8](repeating: 0, count: data!.count / MemoryLayout<UInt8>.size)
(data! as NSData).getBytes(&bytes, length: data!.count)
delegate.serialDidReceiveBytes(bytes)
}
func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
delegate.serialDidReadRSSI(RSSI)
}
}