USB-Meter / USB Meter / Model / BluetoothSerial.swift
Newer Older
c34c6eb 17 hours ago History
423 lines | 16.843kb
Bogdan Timofte authored 2 weeks ago
1
//
2
//  bluetoothSerial.swift
3
//  USB Meter
4
//
5
//  Created by Bogdan Timofte on 17/03/2020.
6
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
7
//
8
//  https://github.com/hoiberg/HM10-BluetoothSerial-iOS
9
import CoreBluetooth
10

            
11
final class BluetoothSerial : NSObject, ObservableObject {
12

            
13
    enum AdministrativeState {
14
        case down
15
        case up
16
    }
17
    enum OperationalState: Int, Comparable {
18
        case peripheralNotConnected
19
        case peripheralConnectionPending
20
        case peripheralConnected
21
        case peripheralReady
22

            
23
        static func < (lhs: OperationalState, rhs: OperationalState) -> Bool {
24
            return lhs.rawValue < rhs.rawValue
25
        }
26
    }
27

            
28
    private var administrativeState = AdministrativeState.down
29
    private var operationalState = OperationalState.peripheralNotConnected {
30
        didSet {
31
            delegate?.opertionalStateChanged(to: operationalState)
32
        }
33
    }
34

            
35
    var macAddress: MACAddress
36
    private var manager: CBCentralManager
37
    private var radio: BluetoothRadio
Bogdan Timofte authored 2 weeks ago
38
    private(set) var rawRSSI: Int
39
    private var rssiSamples: [Int] = []
40
    private let rssiAveragingWindow = 3
41
    @Published private(set) var averageRSSI: Int
42
    private(set) var minRSSI: Int
43
    private(set) var maxRSSI: Int
Bogdan Timofte authored 2 weeks ago
44

            
45
    private var expectedResponseLength = 0
46
    private var wdTimer: Timer?
47

            
48
    var peripheral: CBPeripheral
49

            
Bogdan Timofte authored 2 weeks ago
50
    /// The characteristic used for writes on the connected peripheral.
Bogdan Timofte authored 2 weeks ago
51
    private var writeCharacteristic: CBCharacteristic?
Bogdan Timofte authored 2 weeks ago
52
    /// The characteristic used for notifications on the connected peripheral.
53
    private var notifyCharacteristic: CBCharacteristic?
Bogdan Timofte authored 2 weeks ago
54

            
55
    private var buffer = Data()
56

            
57
    weak var delegate: SerialPortDelegate?
58

            
59
    init( peripheral: CBPeripheral, radio: BluetoothRadio, with macAddress: MACAddress, managedBy manager: CBCentralManager, RSSI: Int ) {
60

            
61
        self.peripheral = peripheral
62
        self.macAddress = macAddress
63
        self.radio = radio
64
        self.manager = manager
Bogdan Timofte authored 2 weeks ago
65
        self.rawRSSI = RSSI
66
        self.rssiSamples = [RSSI]
67
        self.averageRSSI = RSSI
Bogdan Timofte authored 2 weeks ago
68
        self.minRSSI = RSSI
69
        self.maxRSSI = RSSI
Bogdan Timofte authored 2 weeks ago
70
        Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: {_ in
71
            if peripheral.state == .connected {
72
                peripheral.readRSSI()
73
            }
74
        })
75
        super.init()
76
        peripheral.delegate = self
77
    }
Bogdan Timofte authored 2 weeks ago
78

            
Bogdan Timofte authored 2 weeks ago
79
    func updateRSSI(_ value: Int) {
80
        rawRSSI = value
81
        rssiSamples.append(value)
82
        if rssiSamples.count > rssiAveragingWindow {
83
            rssiSamples.removeFirst()
84
        }
85
        let newAverage = rssiSamples.reduce(0, +) / rssiSamples.count
86
        minRSSI = Swift.min(minRSSI, newAverage)
87
        maxRSSI = Swift.max(maxRSSI, newAverage)
88
        if newAverage != averageRSSI {
89
            averageRSSI = newAverage
90
        }
91
    }
92

            
Bogdan Timofte authored 2 weeks ago
93
    private func resetCommunicationState(reason: String, clearCharacteristics: Bool) {
94
        if wdTimer != nil {
95
            track("Reset communication state (\(reason)) - invalidating watchdog")
96
        }
97
        wdTimer?.invalidate()
98
        wdTimer = nil
99

            
100
        if expectedResponseLength != 0 || !buffer.isEmpty {
101
            track("Reset communication state (\(reason)) - expected: \(expectedResponseLength), buffered: \(buffer.count)")
102
        }
103
        expectedResponseLength = 0
104
        buffer.removeAll()
105

            
106
        if clearCharacteristics {
107
            writeCharacteristic = nil
108
            notifyCharacteristic = nil
109
        }
110
    }
Bogdan Timofte authored 17 hours ago
111

            
112
    private func forceNotConnected(reason: String, clearCharacteristics: Bool = true) {
113
        resetCommunicationState(reason: reason, clearCharacteristics: clearCharacteristics)
114
        guard operationalState != .peripheralNotConnected else {
115
            return
116
        }
117
        operationalState = .peripheralNotConnected
118
    }
Bogdan Timofte authored 2 weeks ago
119

            
120
    func connect() {
121
        administrativeState = .up
Bogdan Timofte authored 17 hours ago
122
        guard manager.state == .poweredOn else {
123
            track("Connect requested for '\(peripheral.identifier)' but central state is \(manager.state)")
124
            forceNotConnected(reason: "connect() while central is \(manager.state)")
125
            return
126
        }
Bogdan Timofte authored 2 weeks ago
127
        if operationalState < .peripheralConnected {
Bogdan Timofte authored 2 weeks ago
128
            resetCommunicationState(reason: "connect()", clearCharacteristics: true)
Bogdan Timofte authored 2 weeks ago
129
            operationalState = .peripheralConnectionPending
Bogdan Timofte authored 2 weeks ago
130
            track("Connect called for '\(peripheral.identifier)' while peripheral state is \(peripheral.state.rawValue)")
Bogdan Timofte authored 2 weeks ago
131
            manager.connect(peripheral, options: nil)
132
        } else {
133
            track("Peripheral allready connected: \(operationalState)")
134
        }
135
    }
136

            
137
    func disconnect() {
Bogdan Timofte authored 2 weeks ago
138
        administrativeState = .down
139
        resetCommunicationState(reason: "disconnect()", clearCharacteristics: true)
140
        if peripheral.state != .disconnected || operationalState != .peripheralNotConnected {
141
            track("Disconnect requested for '\(peripheral.identifier)' while peripheral state is \(peripheral.state.rawValue)")
Bogdan Timofte authored 17 hours ago
142
            guard manager.state == .poweredOn else {
143
                track("Skipping central cancel for '\(peripheral.identifier)' because central state is \(manager.state)")
144
                forceNotConnected(reason: "disconnect() while central is \(manager.state)", clearCharacteristics: false)
145
                return
146
            }
Bogdan Timofte authored 2 weeks ago
147
            manager.cancelPeripheralConnection(peripheral)
148
        }
149
    }
150

            
151
    /**
152
     Send data
153

            
154
     - parameter data: Data to be sent.
155
     - parameter expectedResponseLength: Optional If message sent require a respnse the length for that response must be provideed. Incomming data will be buffered before calling delegate.didReceiveData
156
     */
157
    func write(_ data: Data, expectedResponseLength: Int = 0) {
158
        //track("\(self.expectedResponseLength)")
159
        //track(data.hexEncodedStringValue)
160
        guard operationalState == .peripheralReady else {
161
            track("Guard: \(operationalState)")
162
            return
163
        }
164
        guard self.expectedResponseLength == 0 else {
165
            track("Guard: \(self.expectedResponseLength)")
166
            return
167
        }
168

            
169
        self.expectedResponseLength = expectedResponseLength
170

            
171
//        track("Sending...")
Bogdan Timofte authored 2 weeks ago
172
        guard let writeCharacteristic else {
173
            track("Missing write characteristic for \(radio)")
174
            self.expectedResponseLength = 0
175
            return
Bogdan Timofte authored 2 weeks ago
176
        }
Bogdan Timofte authored 2 weeks ago
177

            
178
        let writeType: CBCharacteristicWriteType = writeCharacteristic.properties.contains(.writeWithoutResponse) ? .withoutResponse : .withResponse
179
        peripheral.writeValue(data, for: writeCharacteristic, type: writeType)
Bogdan Timofte authored 2 weeks ago
180
//        track("Sent!")
181
        if self.expectedResponseLength != 0 {
182
            setWDT()
183
        }
184
    }
185

            
186
    func connectionEstablished () {
Bogdan Timofte authored 2 weeks ago
187
        resetCommunicationState(reason: "connectionEstablished()", clearCharacteristics: true)
188
        track("Connection established for '\(peripheral.identifier)'")
Bogdan Timofte authored 2 weeks ago
189
        rssiSamples = [rawRSSI]
190
        averageRSSI = rawRSSI
191
        minRSSI = rawRSSI
192
        maxRSSI = rawRSSI
Bogdan Timofte authored 2 weeks ago
193
        operationalState = .peripheralConnected
194
        peripheral.discoverServices(BluetoothRadioServicesUUIDS[radio])
195
    }
196

            
197
    func connectionClosed () {
Bogdan Timofte authored 2 weeks ago
198
        track("Connection closed for '\(peripheral.identifier)' while peripheral state is \(peripheral.state.rawValue)")
199
        resetCommunicationState(reason: "connectionClosed()", clearCharacteristics: true)
Bogdan Timofte authored 2 weeks ago
200
        rssiSamples = [rawRSSI]
201
        averageRSSI = rawRSSI
202
        minRSSI = rawRSSI
203
        maxRSSI = rawRSSI
Bogdan Timofte authored 2 weeks ago
204
        operationalState = .peripheralNotConnected
205
    }
206

            
Bogdan Timofte authored 17 hours ago
207
    func centralStateChanged(to newState: CBManagerState) {
208
        switch newState {
209
        case .poweredOn:
210
            if administrativeState == .up,
211
               operationalState == .peripheralNotConnected,
212
               peripheral.state == .disconnected {
213
                track("Central returned to poweredOn. Restoring connection to '\(peripheral.identifier)'")
214
                connect()
215
            }
216
        case .poweredOff, .resetting, .unauthorized, .unknown, .unsupported:
217
            if operationalState != .peripheralNotConnected || expectedResponseLength != 0 || !buffer.isEmpty {
218
                track("Central changed to \(newState). Forcing '\(peripheral.identifier)' to not connected.")
219
            }
220
            forceNotConnected(reason: "centralStateChanged(\(newState))")
221
        @unknown default:
222
            track("Central changed to an unknown state. Forcing '\(peripheral.identifier)' to not connected.")
223
            forceNotConnected(reason: "centralStateChanged(@unknown default)")
224
        }
225
    }
226

            
Bogdan Timofte authored 2 weeks ago
227
    func setWDT() {
228
        wdTimer?.invalidate()
229
        wdTimer = Timer.scheduledTimer(withTimeInterval: 10, repeats: false, block: {_ in
230
            track("Response timeout. Expected: \(self.expectedResponseLength) - buffer: \(self.buffer.count)")
231
            self.expectedResponseLength = 0
232
            self.disconnect()
233
        })
234
    }
235

            
Bogdan Timofte authored 2 weeks ago
236
    private func refreshOperationalStateIfReady() {
Bogdan Timofte authored 2 weeks ago
237
        guard let notifyCharacteristic, let writeCharacteristic else {
Bogdan Timofte authored 2 weeks ago
238
            return
239
        }
Bogdan Timofte authored 2 weeks ago
240
        guard notifyCharacteristic.isNotifying else {
241
            track("Waiting for notifications on '\(notifyCharacteristic.uuid)' before marking peripheral ready")
242
            return
243
        }
244
        track("Peripheral ready with notify '\(notifyCharacteristic.uuid)' and write '\(writeCharacteristic.uuid)'")
Bogdan Timofte authored 2 weeks ago
245
        operationalState = .peripheralReady
246
    }
247

            
248
    private func updateBT18Characteristics(for service: CBService) {
249
        for characteristic in service.characteristics ?? [] {
250
            switch characteristic.uuid {
251
            case CBUUID(string: "FFE1"):
252
                if characteristic.properties.contains(.notify) || characteristic.properties.contains(.indicate) {
253
                    peripheral.setNotifyValue(true, for: characteristic)
254
                    notifyCharacteristic = characteristic
255
                }
256
                if writeCharacteristic == nil &&
257
                    (characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse)) {
258
                    writeCharacteristic = characteristic
259
                }
260
            case CBUUID(string: "FFE2"):
261
                if characteristic.properties.contains(.write) || characteristic.properties.contains(.writeWithoutResponse) {
262
                    // DX-BT18 documents FFE2 as the preferred write-only endpoint when present.
263
                    writeCharacteristic = characteristic
264
                }
265
            default:
266
                track ("Unexpected characteristic discovered: '\(characteristic)'")
267
            }
268
        }
269
        refreshOperationalStateIfReady()
270
    }
271

            
272
    private func updatePW0316Characteristics(for service: CBService) {
273
        for characteristic in service.characteristics ?? [] {
274
            switch characteristic.uuid {
275
            case CBUUID(string: "FFE9"): // TX from BLE side into UART
276
                writeCharacteristic = characteristic
277
            case CBUUID(string: "FFE4"): // RX notifications from UART side into BLE
278
                peripheral.setNotifyValue(true, for: characteristic)
279
                notifyCharacteristic = characteristic
280
            default:
281
                track ("Unexpected characteristic discovered: '\(characteristic)'")
282
            }
283
        }
284
        refreshOperationalStateIfReady()
285
    }
286

            
Bogdan Timofte authored 2 weeks ago
287
}
288

            
289
//  MARK:   CBPeripheralDelegate
290
extension BluetoothSerial : CBPeripheralDelegate {
291

            
292
    //  MARK:   didReadRSSI
293
    func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
294
        if error != nil {
295
            track( "Error: \(error!)" )
296
        }
Bogdan Timofte authored 2 weeks ago
297
        updateRSSI(RSSI.intValue)
Bogdan Timofte authored 2 weeks ago
298
    }
299

            
300
    //  MARK:   didDiscoverServices
301
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
302
        track("\(String(describing: peripheral.services))")
303
        if error != nil {
304
            track( "Error: \(error!)" )
305
        }
306
        switch radio {
307
        case .BT18:
308
            for service in peripheral.services! {
309
                switch service.uuid {
310
                case CBUUID(string: "FFE0"):
Bogdan Timofte authored 2 weeks ago
311
                    peripheral.discoverCharacteristics(Array(Set((BluetoothRadioNotifyUUIDs[radio] ?? []) + (BluetoothRadioWriteUUIDs[radio] ?? []))), for: service)
Bogdan Timofte authored 2 weeks ago
312
                default:
313
                    track ("Unexpected service discovered: '\(service)'")
314
                }
315
            }
316
        case .PW0316:
317
            for service in peripheral.services! {
318
                switch service.uuid {
319
                case CBUUID(string: "FFE0"):
Bogdan Timofte authored 2 weeks ago
320
                    peripheral.discoverCharacteristics(BluetoothRadioNotifyUUIDs[radio], for: service)
Bogdan Timofte authored 2 weeks ago
321
                case CBUUID(string: "FFE5"):
Bogdan Timofte authored 2 weeks ago
322
                    peripheral.discoverCharacteristics(BluetoothRadioWriteUUIDs[radio], for: service)
Bogdan Timofte authored 2 weeks ago
323
                default:
324
                    track ("Unexpected service discovered: '\(service)'")
325
                }
326
            }
327
        default:
328
            track("Radio \(radio) Not Implemented!")
329
        }
330
    }
331

            
332
    //  MARK:   didDiscoverCharacteristicsFor
333
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
334
        if error != nil {
335
            track( "Error: \(error!)" )
336
        }
337
        track("\(String(describing: service.characteristics))")
338
        switch radio {
339
        case .BT18:
Bogdan Timofte authored 2 weeks ago
340
            updateBT18Characteristics(for: service)
Bogdan Timofte authored 2 weeks ago
341
        case .PW0316:
Bogdan Timofte authored 2 weeks ago
342
            updatePW0316Characteristics(for: service)
Bogdan Timofte authored 2 weeks ago
343
        default:
344
            track("Radio \(radio) Not Implemented!")
345
        }
346
    }
Bogdan Timofte authored 2 weeks ago
347

            
348
    func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
349
        if error != nil {
350
            track("Error updating notification state for '\(characteristic.uuid)': \(error!)")
351
        }
352
        track("Notification state updated for '\(characteristic.uuid)' - isNotifying: \(characteristic.isNotifying)")
353
        if characteristic.uuid == notifyCharacteristic?.uuid {
354
            refreshOperationalStateIfReady()
355
        }
356
    }
Bogdan Timofte authored 2 weeks ago
357

            
358
    //  MARK:   didUpdateValueFor
359
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
360
//        track("")
361
        if error != nil {
362
            track( "Error: \(error!)" )
363
        }
Bogdan Timofte authored 2 weeks ago
364
        let incomingData = characteristic.value ?? Data()
365
        guard !incomingData.isEmpty else {
366
            track("Received empty update for '\(characteristic.uuid)'")
367
            return
368
        }
369
        guard expectedResponseLength > 0 else {
370
            if !buffer.isEmpty {
371
                track("Dropping unsolicited data (\(incomingData.count) bytes) for '\(characteristic.uuid)' with residual buffer: \(buffer.count)")
372
                buffer.removeAll()
373
            } else {
374
                track("Dropping unsolicited data (\(incomingData.count) bytes) for '\(characteristic.uuid)' while no response is expected")
375
            }
376
            return
377
        }
378

            
379
        let previousBufferCount = buffer.count
380
        buffer.append(incomingData)
Bogdan Timofte authored 2 weeks ago
381
//        track("\n\(buffer.hexEncodedStringValue)")
382
        switch buffer.count {
383
        case let x where x < expectedResponseLength:
384
            setWDT()
385
            //track("buffering")
386
            break;
387
        case let x where x == expectedResponseLength:
388
            //track("buffer ready")
389
            wdTimer?.invalidate()
390
            expectedResponseLength = 0
391
            delegate?.didReceiveData(buffer)
392
            buffer.removeAll()
393
        case let x where x > expectedResponseLength:
394
            // MARK: De unde stim că asta a fost tot? Probabil o deconectare ar rezolva problema
Bogdan Timofte authored 2 weeks ago
395
            let expectedLength = expectedResponseLength
396
            track("Buffer overflow for '\(characteristic.uuid)'. Chunk: \(incomingData.count), previous buffer: \(previousBufferCount), total: \(x), expected: \(expectedLength). Disconnecting to recover.")
397
            disconnect()
Bogdan Timofte authored 2 weeks ago
398
        default:
399
            track("This is not possible!")
400
        }
401
    }
402

            
403
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
404
        if error != nil { track( "Error: \(error!)" ) }
405
    }
406

            
407
    func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
408
        //track("")
409
    }
410

            
411
}
412

            
413
// MARK: SerialPortDelegate
414
protocol SerialPortDelegate: AnyObject {
415
    // MARK: State Changed
416
    func opertionalStateChanged( to newOperationalState: BluetoothSerial.OperationalState )
417
    // MARK: Data was received
418
    func didReceiveData(_ data: Data)
419
}
420

            
421
// MARK: SerialPortDelegate Optionals
422
extension SerialPortDelegate {
423
}