Newer Older
1138 lines | 40.831kb
Bogdan Timofte authored 2 months ago
1
//
2
//  File.swift
3
//  USB Meter
4
//
5
//  Created by Bogdan Timofte on 03/03/2020.
6
//  Copyright © 2020 Bogdan Timofte. All rights reserved.
7
//
8
//MARK: Store and documentation: https://www.aliexpress.com/item/32968303350.html
9
//MARK: Protocol: https://sigrok.org/wiki/RDTech_UM_series
10
//MARK: Pithon Code: https://github.com/rfinnie/rdserialtool
11
//MARK: HM-10 Code: https://github.com/hoiberg/HM10-BluetoothSerial-iOS
12
//MARK: Package dependency https://github.com/krzyzanowskim/CryptoSwift
13

            
14
import CoreBluetooth
15
import SwiftUI
16

            
17
/**
18
 Supprted USB Meters
19
 # UM25C
20
 # TC66
21
 * Reverse Engineering
22
 [UM Series](https://sigrok.org/wiki/RDTech_UM_series)
23
 [TC66C](https://sigrok.org/wiki/RDTech_TC66C)
24
 */
Bogdan Timofte authored a month ago
25
enum Model: CaseIterable, Hashable {
Bogdan Timofte authored 2 months ago
26
    case UM25C
27
    case UM34C
28
    case TC66C
29
}
30

            
Bogdan Timofte authored 2 months ago
31
enum TemperatureUnitPreference: String, CaseIterable, Identifiable {
32
    case celsius
33
    case fahrenheit
34

            
35
    var id: String { rawValue }
36

            
37
    var title: String {
38
        switch self {
39
        case .celsius:
40
            return "Celsius"
41
        case .fahrenheit:
42
            return "Fahrenheit"
43
        }
44
    }
45

            
46
    var symbol: String {
47
        switch self {
48
        case .celsius:
49
            return "℃"
50
        case .fahrenheit:
51
            return "℉"
52
        }
53
    }
54
}
55

            
Bogdan Timofte authored 2 months ago
56
private extension TemperatureUnitPreference {
57
    var localeTitle: String {
58
        switch self {
59
        case .celsius:
60
            return "System (Celsius)"
61
        case .fahrenheit:
62
            return "System (Fahrenheit)"
63
        }
64
    }
65
}
66

            
Bogdan Timofte authored 2 months ago
67
enum ChargeRecordState {
68
    case waitingForStart
69
    case active
70
    case completed
71
}
72

            
Bogdan Timofte authored 2 months ago
73
class Meter : NSObject, ObservableObject, Identifiable {
74

            
Bogdan Timofte authored 2 months ago
75
    private static func shouldLogOperationalStateTransition(from oldValue: OperationalState, to newValue: OperationalState) -> Bool {
76
        switch (oldValue, newValue) {
77
        case (.comunicating, .dataIsAvailable), (.dataIsAvailable, .comunicating):
78
            return false
79
        default:
80
            return true
81
        }
82
    }
83

            
Bogdan Timofte authored 2 months ago
84
    enum OperationalState: Int, Comparable {
85
        case notPresent
86
        case peripheralNotConnected
87
        case peripheralConnectionPending
88
        case peripheralConnected
89
        case peripheralReady
90
        case comunicating
91
        case dataIsAvailable
92

            
93
        static func < (lhs: OperationalState, rhs: OperationalState) -> Bool {
94
            return lhs.rawValue < rhs.rawValue
95
        }
96
    }
97

            
98
    @Published var operationalState = OperationalState.peripheralNotConnected {
99
        didSet {
Bogdan Timofte authored 2 months ago
100
            guard operationalState != oldValue else { return }
Bogdan Timofte authored 2 months ago
101
            if Self.shouldLogOperationalStateTransition(from: oldValue, to: operationalState) {
102
                track("\(name) - Operational state changed from \(oldValue) to \(operationalState)")
103
            }
Bogdan Timofte authored 2 months ago
104
            switch operationalState {
105
            case .notPresent:
Bogdan Timofte authored 2 months ago
106
                cancelPendingDataDumpRequest(reason: "meter missing")
Bogdan Timofte authored 2 months ago
107
                break
108
            case .peripheralNotConnected:
Bogdan Timofte authored 2 months ago
109
                cancelPendingDataDumpRequest(reason: "peripheral disconnected")
Bogdan Timofte authored 2 months ago
110
                handleMeasurementDiscontinuity(at: Date())
Bogdan Timofte authored 2 months ago
111
                if !commandQueue.isEmpty {
112
                    track("\(name) - Clearing \(commandQueue.count) queued commands after disconnect")
113
                    commandQueue.removeAll()
114
                }
Bogdan Timofte authored 2 months ago
115
                if enableAutoConnect {
116
                    track("\(name) - Reconnecting...")
117
                    btSerial.connect()
118
                }
119
            case .peripheralConnectionPending:
Bogdan Timofte authored 2 months ago
120
                cancelPendingDataDumpRequest(reason: "connection pending")
Bogdan Timofte authored 2 months ago
121
                break
122
            case .peripheralConnected:
Bogdan Timofte authored 2 months ago
123
                cancelPendingDataDumpRequest(reason: "services not ready yet")
Bogdan Timofte authored 2 months ago
124
                break
125
            case .peripheralReady:
Bogdan Timofte authored 2 months ago
126
                scheduleDataDumpRequest(after: 0.5, reason: "peripheral ready")
Bogdan Timofte authored 2 months ago
127
            case .comunicating:
128
                break
129
            case .dataIsAvailable:
130
                break
131
            }
132
        }
133
    }
134

            
135
    static func operationalColor(for state: OperationalState) -> Color {
136
        switch state {
137
        case .notPresent:
138
            return .red
139
        case .peripheralNotConnected:
140
            return .blue
141
        case .peripheralConnectionPending:
142
            return .yellow
143
        case .peripheralConnected:
144
            return .yellow
145
        case .peripheralReady:
146
            return .orange
147
        case .comunicating:
148
            return .orange
149
        case .dataIsAvailable:
150
            return .green
151
        }
152
    }
153

            
154
    private var wdTimer: Timer?
155

            
Bogdan Timofte authored 2 months ago
156
    @Published var lastSeen: Date? {
Bogdan Timofte authored 2 months ago
157
        didSet {
158
            wdTimer?.invalidate()
Bogdan Timofte authored 2 months ago
159
            guard lastSeen != nil else { return }
160
            appData.noteMeterSeen(at: lastSeen!, macAddress: btSerial.macAddress.description)
Bogdan Timofte authored 2 months ago
161
            if operationalState == .peripheralNotConnected {
162
                wdTimer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false, block: {_ in
163
                    track("\(self.name) - Lost advertisments...")
164
                    self.operationalState = .notPresent
165
                })
166
            } else if operationalState == .notPresent {
167
               operationalState = .peripheralNotConnected
168
            }
169
        }
170
    }
171

            
172
    var uuid: UUID
173
    var model: Model
174
    var modelString: String
175

            
Bogdan Timofte authored 2 months ago
176
    private var isSyncingNameFromStore = false
177

            
178
    @Published var name: String {
Bogdan Timofte authored 2 months ago
179
        didSet {
Bogdan Timofte authored 2 months ago
180
            guard !isSyncingNameFromStore else { return }
181
            guard oldValue != name else { return }
182
            appData.setMeterName(name, for: btSerial.macAddress.description)
Bogdan Timofte authored 2 months ago
183
        }
184
    }
Bogdan Timofte authored 2 months ago
185

            
Bogdan Timofte authored 2 months ago
186
    var preferredTabIdentifier: String = "home"
187

            
Bogdan Timofte authored 2 months ago
188
    @Published private(set) var lastConnectedAt: Date?
Bogdan Timofte authored 2 months ago
189

            
190
    var color : Color {
191
        get {
Bogdan Timofte authored 2 months ago
192
            return model.color
Bogdan Timofte authored 2 months ago
193
        }
194
    }
195

            
Bogdan Timofte authored 2 months ago
196
    var capabilities: MeterCapabilities {
197
        model.capabilities
198
    }
199

            
Bogdan Timofte authored 2 months ago
200
    var availableDataGroupIDs: [UInt8] {
Bogdan Timofte authored 2 months ago
201
        capabilities.availableDataGroupIDs
Bogdan Timofte authored 2 months ago
202
    }
203

            
204
    var supportsDataGroupCommands: Bool {
Bogdan Timofte authored 2 months ago
205
        capabilities.supportsDataGroupCommands
Bogdan Timofte authored 2 months ago
206
    }
207

            
Bogdan Timofte authored 2 months ago
208
    var supportsRecordingView: Bool {
209
        capabilities.supportsRecordingView
210
    }
211

            
Bogdan Timofte authored 2 months ago
212
    var supportsUMSettings: Bool {
Bogdan Timofte authored 2 months ago
213
        capabilities.supportsScreenSettings
Bogdan Timofte authored 2 months ago
214
    }
215

            
216
    var supportsRecordingThreshold: Bool {
Bogdan Timofte authored 2 months ago
217
        capabilities.supportsRecordingThreshold
Bogdan Timofte authored 2 months ago
218
    }
219

            
Bogdan Timofte authored 2 months ago
220
    var reportsCurrentScreenIndex: Bool {
221
        capabilities.reportsCurrentScreenIndex
222
    }
223

            
224
    var showsDataGroupEnergy: Bool {
225
        capabilities.showsDataGroupEnergy
226
    }
227

            
228
    var highlightsActiveDataGroup: Bool {
229
        if model == .TC66C {
230
            return hasObservedActiveDataGroup
231
        }
232
        return capabilities.highlightsActiveDataGroup
233
    }
234

            
Bogdan Timofte authored 2 months ago
235
    var supportsFahrenheit: Bool {
Bogdan Timofte authored 2 months ago
236
        capabilities.supportsFahrenheit
Bogdan Timofte authored 2 months ago
237
    }
238

            
Bogdan Timofte authored 2 months ago
239
    var supportsManualTemperatureUnitSelection: Bool {
240
        model == .TC66C
241
    }
242

            
Bogdan Timofte authored 2 months ago
243
    var supportsChargerDetection: Bool {
Bogdan Timofte authored 2 months ago
244
        capabilities.supportsChargerDetection
245
    }
246

            
Bogdan Timofte authored 2 months ago
247
    var dataGroupsTitle: String {
248
        capabilities.dataGroupsTitle
249
    }
250

            
Bogdan Timofte authored 2 months ago
251
    var documentedWorkingVoltage: String {
252
        capabilities.documentedWorkingVoltage
253
    }
254

            
Bogdan Timofte authored 2 months ago
255
    var chargerTypeDescription: String {
256
        capabilities.chargerTypeDescription(for: chargerTypeIndex)
Bogdan Timofte authored 2 months ago
257
    }
258

            
Bogdan Timofte authored 2 months ago
259
    var temperatureUnitDescription: String {
260
        if supportsManualTemperatureUnitSelection {
Bogdan Timofte authored 2 months ago
261
            return "Device-defined"
Bogdan Timofte authored 2 months ago
262
        }
Bogdan Timofte authored 2 months ago
263
        return systemTemperatureUnitPreference.localeTitle
Bogdan Timofte authored 2 months ago
264
    }
265

            
266
    var primaryTemperatureDescription: String {
Bogdan Timofte authored 2 months ago
267
        let value = displayedTemperatureValue.format(decimalDigits: 0)
Bogdan Timofte authored 2 months ago
268
        if supportsManualTemperatureUnitSelection {
Bogdan Timofte authored 2 months ago
269
            return "\(value)°"
Bogdan Timofte authored 2 months ago
270
        }
Bogdan Timofte authored 2 months ago
271
        return "\(value)\(systemTemperatureUnitPreference.symbol)"
Bogdan Timofte authored 2 months ago
272
    }
273

            
274
    var secondaryTemperatureDescription: String? {
Bogdan Timofte authored 2 months ago
275
        nil
276
    }
277

            
278
    var displayedTemperatureValue: Double {
279
        if supportsManualTemperatureUnitSelection {
280
            return temperatureCelsius
281
        }
282
        switch systemTemperatureUnitPreference {
283
        case .celsius:
284
            return displayedTemperatureCelsius
285
        case .fahrenheit:
286
            return displayedTemperatureFahrenheit
287
        }
288
    }
289

            
290
    private var displayedTemperatureCelsius: Double {
291
        if supportsManualTemperatureUnitSelection {
292
            switch tc66TemperatureUnitPreference {
293
            case .celsius:
294
                return temperatureCelsius
295
            case .fahrenheit:
296
                return (temperatureCelsius - 32) * 5 / 9
297
            }
298
        }
299
        return temperatureCelsius
300
    }
301

            
302
    private var displayedTemperatureFahrenheit: Double {
303
        if supportsManualTemperatureUnitSelection {
304
            switch tc66TemperatureUnitPreference {
305
            case .celsius:
306
                return (temperatureCelsius * 9 / 5) + 32
307
            case .fahrenheit:
308
                return temperatureCelsius
309
            }
310
        }
311
        if supportsFahrenheit, temperatureFahrenheit.isFinite {
312
            return temperatureFahrenheit
313
        }
314
        return (temperatureCelsius * 9 / 5) + 32
315
    }
316

            
317
    private var systemTemperatureUnitPreference: TemperatureUnitPreference {
318
        let locale = Locale.autoupdatingCurrent
319
        if #available(iOS 16.0, *) {
320
            switch locale.measurementSystem {
321
            case .us:
322
                return .fahrenheit
323
            default:
324
                return .celsius
325
            }
326
        }
327

            
328
        let regionCode = locale.regionCode ?? ""
329
        let fahrenheitRegions: Set<String> = ["US", "BS", "BZ", "KY", "PW", "LR", "FM", "MH"]
330
        return fahrenheitRegions.contains(regionCode) ? .fahrenheit : .celsius
Bogdan Timofte authored 2 months ago
331
    }
332

            
Bogdan Timofte authored 2 months ago
333
    var currentScreenDescription: String {
Bogdan Timofte authored 2 months ago
334
        guard reportsCurrentScreenIndex else {
335
            return "Page Controls"
336
        }
Bogdan Timofte authored 2 months ago
337
        if let label = capabilities.screenDescription(for: currentScreen) {
338
            return "Screen \(currentScreen): \(label)"
339
        }
340
        return "Screen \(currentScreen)"
341
    }
342

            
Bogdan Timofte authored 2 months ago
343
    var deviceModelName: String {
Bogdan Timofte authored 2 months ago
344
        if !reportedModelName.isEmpty {
345
            return reportedModelName
346
        }
347
        return model.canonicalName
Bogdan Timofte authored 2 months ago
348
    }
349

            
Bogdan Timofte authored 2 months ago
350
    var deviceModelSummary: String {
Bogdan Timofte authored 2 months ago
351
        let baseName = deviceModelName
Bogdan Timofte authored 2 months ago
352
        if modelNumber != 0 {
353
            return "\(baseName) (\(modelNumber))"
354
        }
355
        return baseName
356
    }
357

            
Bogdan Timofte authored 2 months ago
358
    var recordingDurationDescription: String {
359
        let totalSeconds = Int(recordingDuration)
360
        let hours = totalSeconds / 3600
361
        let minutes = (totalSeconds % 3600) / 60
362
        let seconds = totalSeconds % 60
363

            
364
        if hours > 0 {
365
            return String(format: "%d:%02d:%02d", hours, minutes, seconds)
366
        }
367
        return String(format: "%02d:%02d", minutes, seconds)
368
    }
369

            
Bogdan Timofte authored 2 months ago
370
    var chargeRecordDurationDescription: String {
371
        let totalSeconds = Int(chargeRecordDuration)
372
        let hours = totalSeconds / 3600
373
        let minutes = (totalSeconds % 3600) / 60
374
        let seconds = totalSeconds % 60
375

            
376
        if hours > 0 {
377
            return String(format: "%d:%02d:%02d", hours, minutes, seconds)
378
        }
379
        return String(format: "%02d:%02d", minutes, seconds)
380
    }
381

            
382
    var chargeRecordTimeRange: ClosedRange<Date>? {
383
        guard let start = chargeRecordStartTimestamp else { return nil }
384
        let end = chargeRecordEndTimestamp ?? chargeRecordLastTimestamp
385
        guard let end else { return nil }
386
        return start...end
387
    }
388

            
389
    var chargeRecordStatusText: String {
390
        switch chargeRecordState {
391
        case .waitingForStart:
392
            return "Waiting"
393
        case .active:
394
            return "Active"
395
        case .completed:
396
            return "Completed"
397
        }
398
    }
399

            
400
    var chargeRecordStatusColor: Color {
401
        switch chargeRecordState {
402
        case .waitingForStart:
403
            return .secondary
404
        case .active:
405
            return .red
406
        case .completed:
407
            return .green
408
        }
409
    }
410

            
Bogdan Timofte authored 2 months ago
411
    var dataGroupsHint: String? {
Bogdan Timofte authored 2 months ago
412
        if model == .TC66C {
413
            if hasObservedActiveDataGroup {
414
                return "The active memory is inferred from the totals that are currently increasing."
415
            }
416
            return "The device exposes two read-only memories. The active memory is inferred once one total starts increasing."
417
        }
418
        return capabilities.dataGroupsHint
419
    }
420

            
421
    func dataGroupLabel(for id: UInt8) -> String {
422
        supportsDataGroupCommands ? "\(id)" : "M\(Int(id) + 1)"
Bogdan Timofte authored 2 months ago
423
    }
424

            
425
    var recordingThresholdHint: String? {
426
        capabilities.recordingThresholdHint
427
    }
428

            
Bogdan Timofte authored 2 months ago
429
    var btSerial: BluetoothSerial
Bogdan Timofte authored 2 months ago
430

            
Bogdan Timofte authored 2 months ago
431
    var measurements = Measurements()
Bogdan Timofte authored 2 months ago
432

            
433
    private var commandQueue: [Data] = []
434
    private var dataDumpRequestTimestamp = Date()
Bogdan Timofte authored 2 months ago
435
    private var pendingDataDumpWorkItem: DispatchWorkItem?
Bogdan Timofte authored 2 months ago
436

            
437
    class DataGroupRecord {
Bogdan Timofte authored 2 months ago
438
        var ah: Double
439
        var wh: Double
Bogdan Timofte authored 2 months ago
440
        init(ah: Double, wh: Double) {
441
            self.ah = ah
442
            self.wh = wh
443
        }
444
    }
Bogdan Timofte authored 2 months ago
445
    private(set) var selectedDataGroup: UInt8 = 0
446
    private(set) var dataGroupRecords: [Int : DataGroupRecord] = [:]
447
    private(set) var chargeRecordAH: Double = 0
448
    private(set) var chargeRecordWH: Double = 0
449
    private(set) var chargeRecordDuration: TimeInterval = 0
Bogdan Timofte authored 2 months ago
450
    @Published var chargeRecordStopThreshold: Double = 0.05
451
    @Published var tc66TemperatureUnitPreference: TemperatureUnitPreference = .celsius {
452
        didSet {
453
            guard supportsManualTemperatureUnitSelection else { return }
454
            guard oldValue != tc66TemperatureUnitPreference else { return }
Bogdan Timofte authored 2 months ago
455
            appData.setTemperatureUnitPreference(tc66TemperatureUnitPreference, for: btSerial.macAddress.description)
Bogdan Timofte authored 2 months ago
456
        }
457
    }
Bogdan Timofte authored 2 months ago
458

            
459
    @Published var screenBrightness: Int = -1 {
460
        didSet {
461
            if oldValue != screenBrightness {
462
                screenBrightnessTimestamp = Date()
463
                if oldValue != -1 {
464
                    setSceeenBrightness(to: UInt8(screenBrightness))
465
                }
466
            }
467
        }
468
    }
469
    private var screenBrightnessTimestamp = Date()
470

            
471
    @Published var screenTimeout: Int = -1 {
472
        didSet {
473
            if oldValue != screenTimeout {
474
                screenTimeoutTimestamp = Date()
475
                if oldValue != -1 {
476
                    setScreenSaverTimeout(to: UInt8(screenTimeout))
477
                }
478
            }
479
        }
480
    }
481
    private var screenTimeoutTimestamp = Date()
482

            
Bogdan Timofte authored 2 months ago
483
    private(set) var voltage: Double = 0
484
    private(set) var current: Double = 0
485
    private(set) var power: Double = 0
486
    private(set) var temperatureCelsius: Double = 0
487
    private(set) var temperatureFahrenheit: Double = 0
488
    private(set) var usbPlusVoltage: Double = 0
489
    private(set) var usbMinusVoltage: Double = 0
490
    private(set) var recordedAH: Double = 0
491
    private(set) var recordedWH: Double = 0
492
    private(set) var recording: Bool = false
Bogdan Timofte authored 2 months ago
493
    @Published var recordingTreshold: Double = 0 {
Bogdan Timofte authored 2 months ago
494
        didSet {
Bogdan Timofte authored 2 months ago
495
            guard recordingTreshold != oldValue else { return }
496
            if isApplyingRecordingThresholdFromDevice {
497
                return
Bogdan Timofte authored 2 months ago
498
            }
Bogdan Timofte authored 2 months ago
499
            recordingThresholdTimestamp = Date()
500
            guard recordingThresholdLoadedFromDevice else { return }
501
            setrecordingTreshold(to: (recordingTreshold * 100).uInt8Value)
Bogdan Timofte authored 2 months ago
502
        }
Bogdan Timofte authored 2 months ago
503
    }
Bogdan Timofte authored 2 months ago
504
    private(set) var currentScreen: UInt16 = 0
505
    private(set) var recordingDuration: UInt32 = 0
506
    private(set) var loadResistance: Double = 0
507
    private(set) var modelNumber: UInt16 = 0
508
    private(set) var chargerTypeIndex: UInt16 = 0
509
    private(set) var reportedModelName: String = ""
510
    private(set) var firmwareVersion: String = ""
511
    private(set) var serialNumber: UInt32 = 0
512
    private(set) var bootCount: UInt32 = 0
Bogdan Timofte authored 2 months ago
513
    private var enableAutoConnect: Bool = false
Bogdan Timofte authored 2 months ago
514
    private var recordingThresholdTimestamp = Date()
515
    private var recordingThresholdLoadedFromDevice = false
516
    private var isApplyingRecordingThresholdFromDevice = false
Bogdan Timofte authored 2 months ago
517
    private(set) var chargeRecordState = ChargeRecordState.waitingForStart
Bogdan Timofte authored 2 months ago
518
    private var chargeRecordStartTimestamp: Date?
519
    private var chargeRecordEndTimestamp: Date?
520
    private var chargeRecordLastTimestamp: Date?
521
    private var chargeRecordLastCurrent: Double = 0
522
    private var chargeRecordLastPower: Double = 0
Bogdan Timofte authored 2 months ago
523
    private let volatileMemoryDecreaseEpsilon = 0.0005
524
    private let initiatedVolatileMemoryResetGraceWindow: TimeInterval = 12
525
    private var hasSeenUMSnapshot = false
Bogdan Timofte authored 2 months ago
526
    private var hasObservedActiveDataGroup = false
527
    private var hasSeenTC66Snapshot = false
Bogdan Timofte authored 2 months ago
528
    private var pendingVolatileMemoryResetIgnoreCount = 0
529
    private var pendingVolatileMemoryResetDeadline: Date?
Bogdan Timofte authored 2 months ago
530
    private var liveDataChanged = false
Bogdan Timofte authored a month ago
531
    private var restoredChargeSessionID: UUID?
Bogdan Timofte authored 2 months ago
532

            
Bogdan Timofte authored 2 months ago
533
    @discardableResult
534
    private func setIfChanged<T: Equatable>(_ keyPath: ReferenceWritableKeyPath<Meter, T>, to value: T) -> Bool {
535
        guard self[keyPath: keyPath] != value else { return false }
536
        self[keyPath: keyPath] = value
537
        liveDataChanged = true
538
        return true
539
    }
540

            
541
    private func updateDataGroupRecord(index: Int, ah: Double, wh: Double) {
542
        if let existing = dataGroupRecords[index] {
543
            if existing.ah != ah { existing.ah = ah; liveDataChanged = true }
544
            if existing.wh != wh { existing.wh = wh; liveDataChanged = true }
545
        } else {
546
            dataGroupRecords[index] = DataGroupRecord(ah: ah, wh: wh)
547
            liveDataChanged = true
548
        }
549
    }
550

            
Bogdan Timofte authored 2 months ago
551
    init ( model: Model, with serialPort: BluetoothSerial ) {
552
        uuid = serialPort.peripheral.identifier
553
        //dataStore.meterUUIDS.append(serialPort.peripheral.identifier)
554
        modelString = serialPort.peripheral.name!
555
        self.model = model
556
        btSerial = serialPort
Bogdan Timofte authored 2 months ago
557
        name = appData.meterName(for: serialPort.macAddress.description) ?? serialPort.macAddress.description
Bogdan Timofte authored 2 months ago
558
        lastSeen = appData.lastSeen(for: serialPort.macAddress.description)
559
        lastConnectedAt = appData.lastConnected(for: serialPort.macAddress.description)
Bogdan Timofte authored 2 months ago
560
        super.init()
561
        btSerial.delegate = self
Bogdan Timofte authored 2 months ago
562
        reloadTemperatureUnitPreference()
Bogdan Timofte authored 2 months ago
563
        //name = dataStore.meterNames[macAddress.description] ?? peripheral.name!
564
        for index in stride(from: 0, through: 9, by: 1) {
565
            dataGroupRecords[index] = DataGroupRecord(ah:0, wh: 0)
566
        }
567
    }
Bogdan Timofte authored 2 months ago
568

            
569
    func reloadTemperatureUnitPreference() {
570
        guard supportsManualTemperatureUnitSelection else { return }
Bogdan Timofte authored 2 months ago
571
        let persistedPreference = appData.temperatureUnitPreference(for: btSerial.macAddress.description)
Bogdan Timofte authored 2 months ago
572
        if tc66TemperatureUnitPreference != persistedPreference {
573
            tc66TemperatureUnitPreference = persistedPreference
574
        }
575
    }
Bogdan Timofte authored 2 months ago
576

            
Bogdan Timofte authored 2 months ago
577
    func updateNameFromStore(_ newName: String) {
578
        guard newName != name else { return }
579
        isSyncingNameFromStore = true
580
        name = newName
581
        isSyncingNameFromStore = false
582
    }
583

            
Bogdan Timofte authored 2 months ago
584
    private func noteConnectionEstablished(at date: Date) {
585
        lastConnectedAt = date
586
        appData.noteMeterConnected(at: date, macAddress: btSerial.macAddress.description)
587
    }
588

            
Bogdan Timofte authored 2 months ago
589
    private func handleMeasurementDiscontinuity(at timestamp: Date) {
590
        measurements.markDiscontinuity(at: timestamp)
591

            
592
        guard chargeRecordState == .active else { return }
593
        chargeRecordLastTimestamp = nil
594
        chargeRecordLastCurrent = 0
595
        chargeRecordLastPower = 0
596
    }
597

            
Bogdan Timofte authored a month ago
598
    private func currentEnergySample() -> (groupID: UInt8, value: Double)? {
599
        guard showsDataGroupEnergy else { return nil }
600

            
601
        if model == .TC66C && !hasObservedActiveDataGroup {
602
            return nil
603
        }
604

            
605
        let groupID = selectedDataGroup
606
        guard let record = dataGroupRecords[Int(groupID)] else { return nil }
607
        return (groupID, record.wh)
608
    }
609

            
Bogdan Timofte authored a month ago
610
    private func currentChargeSample() -> (groupID: UInt8, value: Double)? {
611
        guard showsDataGroupEnergy else { return nil }
612

            
613
        if model == .TC66C && !hasObservedActiveDataGroup {
614
            return nil
615
        }
616

            
617
        let groupID = selectedDataGroup
618
        guard let record = dataGroupRecords[Int(groupID)] else { return nil }
619
        return (groupID, record.ah)
620
    }
621

            
622
    func chargingMonitorSnapshot(at observedAt: Date) -> ChargingMonitorSnapshot? {
Bogdan Timofte authored a month ago
623
        let usesNativeRecordingCounters = supportsRecordingView
624
        let nativeChargeCounter = usesNativeRecordingCounters ? recordedAH : nil
625
        let nativeEnergyCounter = usesNativeRecordingCounters ? recordedWH : nil
626

            
627
        return ChargingMonitorSnapshot(
Bogdan Timofte authored a month ago
628
            meterMACAddress: btSerial.macAddress.description,
629
            meterName: name,
630
            meterModel: deviceModelSummary,
631
            observedAt: observedAt,
632
            voltageVolts: voltage,
633
            currentAmps: current,
634
            powerWatts: power,
Bogdan Timofte authored a month ago
635
            selectedDataGroup: usesNativeRecordingCounters ? nil : (currentEnergySample()?.groupID ?? currentChargeSample()?.groupID),
636
            meterChargeCounterAh: nativeChargeCounter ?? currentChargeSample()?.value,
637
            meterEnergyCounterWh: nativeEnergyCounter ?? currentEnergySample()?.value,
638
            fallbackStopThresholdAmps: supportsRecordingThreshold ? recordingTreshold : chargeRecordStopThreshold
Bogdan Timofte authored a month ago
639
        )
640
    }
641

            
642
    var chargingMonitorSnapshot: ChargingMonitorSnapshot? {
643
        chargingMonitorSnapshot(at: Date())
644
    }
645

            
Bogdan Timofte authored 2 months ago
646
    private func cancelPendingDataDumpRequest(reason: String) {
647
        guard let pendingDataDumpWorkItem else { return }
648
        track("\(name) - Cancel scheduled data request (\(reason))")
649
        pendingDataDumpWorkItem.cancel()
650
        self.pendingDataDumpWorkItem = nil
651
    }
652

            
653
    private func scheduleDataDumpRequest(after delay: TimeInterval, reason: String) {
654
        cancelPendingDataDumpRequest(reason: "reschedule")
655

            
656
        let workItem = DispatchWorkItem { [weak self] in
657
            guard let self else { return }
658
            self.pendingDataDumpWorkItem = nil
659
            self.dataDumpRequest()
660
        }
661
        pendingDataDumpWorkItem = workItem
662
        track("\(name) - Schedule data request in \(String(format: "%.2f", delay))s (\(reason))")
663
        DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem)
664
    }
Bogdan Timofte authored 2 months ago
665

            
666
    private func noteInitiatedVolatileMemoryResetIfNeeded(for groupID: UInt8) {
667
        guard groupID == 0 else { return }
668
        pendingVolatileMemoryResetIgnoreCount += 1
669
        pendingVolatileMemoryResetDeadline = Date().addingTimeInterval(initiatedVolatileMemoryResetGraceWindow)
670
        track("\(name) - Will ignore the next volatile memory drop caused by an app reset request.")
671
    }
672

            
673
    private func pendingInitiatedVolatileMemoryResetIsActive(at timestamp: Date) -> Bool {
674
        guard let pendingVolatileMemoryResetDeadline else { return false }
675
        guard pendingVolatileMemoryResetIgnoreCount > 0 else {
676
            self.pendingVolatileMemoryResetDeadline = nil
677
            return false
678
        }
679
        guard timestamp <= pendingVolatileMemoryResetDeadline else {
680
            track("\(name) - Expiring stale volatile memory reset ignore state.")
681
            pendingVolatileMemoryResetIgnoreCount = 0
682
            self.pendingVolatileMemoryResetDeadline = nil
683
            return false
684
        }
685
        return true
686
    }
687

            
688
    private func shouldIgnoreVolatileMemoryDrop(at timestamp: Date) -> Bool {
689
        guard pendingInitiatedVolatileMemoryResetIsActive(at: timestamp) else { return false }
690
        pendingVolatileMemoryResetIgnoreCount -= 1
691
        if pendingVolatileMemoryResetIgnoreCount == 0 {
692
            pendingVolatileMemoryResetDeadline = nil
693
        }
694
        track("\(name) - Ignoring volatile memory drop after an app-initiated reset.")
695
        return true
696
    }
697

            
698
    private func didUMVolatileMemoryDecrease(in snapshot: UMSnapshot) -> Bool {
699
        guard hasSeenUMSnapshot else { return false }
700
        guard let previousRecord = dataGroupRecords[0], let nextRecord = snapshot.dataGroupRecords[0] else {
701
            return false
702
        }
703

            
704
        return nextRecord.ah < (previousRecord.ah - volatileMemoryDecreaseEpsilon)
705
            || nextRecord.wh < (previousRecord.wh - volatileMemoryDecreaseEpsilon)
706
    }
707

            
708
    private func didUMDeviceReboot(with snapshot: UMSnapshot, at timestamp: Date) -> Bool {
709
        defer { hasSeenUMSnapshot = true }
710

            
711
        guard didUMVolatileMemoryDecrease(in: snapshot) else { return false }
712
        guard !shouldIgnoreVolatileMemoryDrop(at: timestamp) else { return false }
713

            
714
        track("\(name) - Inferred UM reboot because volatile memory dropped.")
715
        return true
716
    }
717

            
718
    private func didTC66DeviceReboot(with snapshot: TC66Snapshot) -> Bool {
719
        guard hasSeenTC66Snapshot else { return false }
720
        guard snapshot.bootCount != bootCount else { return false }
721

            
722
        track("\(name) - Inferred TC66 reboot because bootCount changed from \(bootCount) to \(snapshot.bootCount).")
723
        return true
724
    }
725

            
726
    private func updateChargerTypeLatch(observedIndex: UInt16, didDetectDeviceReset: Bool) {
727
        if didDetectDeviceReset, chargerTypeIndex != 0 {
Bogdan Timofte authored 2 months ago
728
            setIfChanged(\.chargerTypeIndex, to: 0)
Bogdan Timofte authored 2 months ago
729
        }
730

            
731
        guard supportsChargerDetection else { return }
732

            
733
        if chargerTypeIndex == 0 {
Bogdan Timofte authored 2 months ago
734
            setIfChanged(\.chargerTypeIndex, to: observedIndex)
Bogdan Timofte authored 2 months ago
735
            return
736
        }
737

            
738
        guard observedIndex != 0, observedIndex != chargerTypeIndex else { return }
739
        track("\(name) - Ignoring charger type change from \(chargerTypeIndex) to \(observedIndex) until the device reboots.")
740
    }
Bogdan Timofte authored 2 months ago
741

            
742
    func dataDumpRequest() {
Bogdan Timofte authored 2 months ago
743
        guard operationalState >= .peripheralReady else {
744
            track("\(name) - Skip data request while state is \(operationalState)")
745
            return
746
        }
Bogdan Timofte authored 2 months ago
747
        if commandQueue.isEmpty {
748
            switch model {
749
            case .UM25C:
Bogdan Timofte authored 2 months ago
750
                btSerial.write(UMProtocol.snapshotRequest, expectedResponseLength: 130)
Bogdan Timofte authored 2 months ago
751
            case .UM34C:
Bogdan Timofte authored 2 months ago
752
                btSerial.write(UMProtocol.snapshotRequest, expectedResponseLength: 130)
Bogdan Timofte authored 2 months ago
753
            case .TC66C:
Bogdan Timofte authored 2 months ago
754
                btSerial.write(TC66Protocol.snapshotRequest, expectedResponseLength: 192)
Bogdan Timofte authored 2 months ago
755
            }
756
            dataDumpRequestTimestamp = Date()
757
            // track("\(name) - Request sent!")
758
        } else {
759
            track("Request delayed for: \(commandQueue.first!.hexEncodedStringValue)")
760
            btSerial.write( commandQueue.first! )
761
            commandQueue.removeFirst()
Bogdan Timofte authored 2 months ago
762
            scheduleDataDumpRequest(after: 1, reason: "queued command")
Bogdan Timofte authored 2 months ago
763
        }
764
    }
765

            
766
    /**
767
     received data parser
768
     - parameter buffer cotains response for data dump request
769
     - Decription metod for TC66C AES ECB response  found [here](https:github.com/krzyzanowskim/CryptoSwift/issues/693)
770
     */
771
    func parseData ( from buffer: Data) {
772
        //track("\(name)")
Bogdan Timofte authored 2 months ago
773
        liveDataChanged = false
Bogdan Timofte authored 2 months ago
774
        switch model {
775
        case .UM25C:
Bogdan Timofte authored 2 months ago
776
            do {
777
                apply(umSnapshot: try UMProtocol.parseSnapshot(from: buffer, model: model))
778
            } catch {
779
                track("\(name) - Error: \(error)")
780
            }
Bogdan Timofte authored 2 months ago
781
        case .UM34C:
Bogdan Timofte authored 2 months ago
782
            do {
783
                apply(umSnapshot: try UMProtocol.parseSnapshot(from: buffer, model: model))
784
            } catch {
785
                track("\(name) - Error: \(error)")
786
            }
Bogdan Timofte authored 2 months ago
787
        case .TC66C:
Bogdan Timofte authored 2 months ago
788
            do {
789
                apply(tc66Snapshot: try TC66Protocol.parseSnapshot(from: buffer))
790
            } catch {
791
                track("\(name) - Error: \(error)")
792
            }
Bogdan Timofte authored 2 months ago
793
        }
Bogdan Timofte authored 2 months ago
794
        updateChargeRecord(at: dataDumpRequestTimestamp)
Bogdan Timofte authored a month ago
795
        if supportsRecordingView {
796
            measurements.captureEnergyValue(
797
                timestamp: dataDumpRequestTimestamp,
798
                value: recordedWH,
799
                groupID: .max
800
            )
801
        } else if let energySample = currentEnergySample() {
Bogdan Timofte authored a month ago
802
            measurements.captureEnergyValue(
803
                timestamp: dataDumpRequestTimestamp,
804
                value: energySample.value,
805
                groupID: energySample.groupID
806
            )
807
        }
Bogdan Timofte authored 2 months ago
808
        measurements.addValues(
809
            timestamp: dataDumpRequestTimestamp,
810
            power: power,
811
            voltage: voltage,
812
            current: current,
813
            temperature: displayedTemperatureValue,
814
            rssi: Double(btSerial.averageRSSI)
815
        )
Bogdan Timofte authored a month ago
816
        appData.observeChargeSnapshot(from: self, observedAt: dataDumpRequestTimestamp)
Bogdan Timofte authored 2 months ago
817
//        DispatchQueue.global(qos: .userInitiated).asyncAfter( deadline: .now() + 0.33 ) {
818
//            //track("\(name) - Scheduled new request.")
819
//        }
Bogdan Timofte authored 2 months ago
820
        if operationalState != .dataIsAvailable {
821
            operationalState = .dataIsAvailable
822
        } else if liveDataChanged {
823
            objectWillChange.send()
824
        }
Bogdan Timofte authored 2 months ago
825
        dataDumpRequest()
826
    }
827

            
Bogdan Timofte authored 2 months ago
828
    private func apply(umSnapshot snapshot: UMSnapshot) {
Bogdan Timofte authored 2 months ago
829
        let didDetectDeviceReset = didUMDeviceReboot(with: snapshot, at: dataDumpRequestTimestamp)
Bogdan Timofte authored 2 months ago
830
        setIfChanged(\.modelNumber, to: snapshot.modelNumber)
831
        setIfChanged(\.voltage, to: snapshot.voltage)
832
        setIfChanged(\.current, to: snapshot.current)
833
        setIfChanged(\.power, to: snapshot.power)
834
        setIfChanged(\.temperatureCelsius, to: snapshot.temperatureCelsius)
835
        setIfChanged(\.temperatureFahrenheit, to: snapshot.temperatureFahrenheit)
836
        setIfChanged(\.selectedDataGroup, to: snapshot.selectedDataGroup)
Bogdan Timofte authored 2 months ago
837
        for (index, record) in snapshot.dataGroupRecords {
Bogdan Timofte authored 2 months ago
838
            updateDataGroupRecord(index: index, ah: record.ah, wh: record.wh)
Bogdan Timofte authored 2 months ago
839
        }
Bogdan Timofte authored 2 months ago
840
        setIfChanged(\.usbPlusVoltage, to: snapshot.usbPlusVoltage)
841
        setIfChanged(\.usbMinusVoltage, to: snapshot.usbMinusVoltage)
Bogdan Timofte authored 2 months ago
842
        updateChargerTypeLatch(observedIndex: snapshot.chargerTypeIndex, didDetectDeviceReset: didDetectDeviceReset)
Bogdan Timofte authored 2 months ago
843
        setIfChanged(\.recordedAH, to: snapshot.recordedAH)
844
        setIfChanged(\.recordedWH, to: snapshot.recordedWH)
Bogdan Timofte authored 2 months ago
845

            
846
        if recordingThresholdTimestamp < dataDumpRequestTimestamp || !recordingThresholdLoadedFromDevice {
847
            recordingThresholdLoadedFromDevice = true
848
            if recordingTreshold != snapshot.recordingThreshold {
849
                isApplyingRecordingThresholdFromDevice = true
850
                recordingTreshold = snapshot.recordingThreshold
851
                isApplyingRecordingThresholdFromDevice = false
852
            }
853
        } else {
854
            track("\(name) - Skip updating recordingThreshold (changed after request).")
855
        }
Bogdan Timofte authored 2 months ago
856
        setIfChanged(\.recordingDuration, to: snapshot.recordingDuration)
857
        setIfChanged(\.recording, to: snapshot.recording)
Bogdan Timofte authored 2 months ago
858

            
Bogdan Timofte authored 2 months ago
859
        if screenTimeoutTimestamp < dataDumpRequestTimestamp {
Bogdan Timofte authored 2 months ago
860
            if screenTimeout != snapshot.screenTimeout {
861
                screenTimeout = snapshot.screenTimeout
Bogdan Timofte authored 2 months ago
862
            }
863
        } else {
864
            track("\(name) - Skip updating screenTimeout (changed after request).")
865
        }
866

            
867
        if screenBrightnessTimestamp < dataDumpRequestTimestamp {
Bogdan Timofte authored 2 months ago
868
            if screenBrightness != snapshot.screenBrightness {
869
                screenBrightness = snapshot.screenBrightness
Bogdan Timofte authored 2 months ago
870
            }
871
        } else {
872
            track("\(name) - Skip updating screenBrightness (changed after request).")
873
        }
874

            
Bogdan Timofte authored 2 months ago
875
        setIfChanged(\.currentScreen, to: snapshot.currentScreen)
876
        setIfChanged(\.loadResistance, to: snapshot.loadResistance)
Bogdan Timofte authored 2 months ago
877
    }
878

            
Bogdan Timofte authored 2 months ago
879
    private func apply(tc66Snapshot snapshot: TC66Snapshot) {
Bogdan Timofte authored 2 months ago
880
        let didDetectDeviceReset = didTC66DeviceReboot(with: snapshot)
Bogdan Timofte authored 2 months ago
881
        if hasSeenTC66Snapshot {
882
            inferTC66ActiveDataGroup(from: snapshot)
883
        } else {
884
            hasSeenTC66Snapshot = true
885
        }
Bogdan Timofte authored 2 months ago
886
        setIfChanged(\.reportedModelName, to: snapshot.modelName)
887
        setIfChanged(\.firmwareVersion, to: snapshot.firmwareVersion)
888
        setIfChanged(\.serialNumber, to: snapshot.serialNumber)
889
        setIfChanged(\.bootCount, to: snapshot.bootCount)
Bogdan Timofte authored 2 months ago
890
        updateChargerTypeLatch(observedIndex: 0, didDetectDeviceReset: didDetectDeviceReset)
Bogdan Timofte authored 2 months ago
891
        setIfChanged(\.voltage, to: snapshot.voltage)
892
        setIfChanged(\.current, to: snapshot.current)
893
        setIfChanged(\.power, to: snapshot.power)
894
        setIfChanged(\.loadResistance, to: snapshot.loadResistance)
Bogdan Timofte authored 2 months ago
895
        for (index, record) in snapshot.dataGroupRecords {
Bogdan Timofte authored 2 months ago
896
            updateDataGroupRecord(index: index, ah: record.ah, wh: record.wh)
Bogdan Timofte authored 2 months ago
897
        }
Bogdan Timofte authored 2 months ago
898
        setIfChanged(\.temperatureCelsius, to: snapshot.temperatureCelsius)
899
        setIfChanged(\.usbPlusVoltage, to: snapshot.usbPlusVoltage)
900
        setIfChanged(\.usbMinusVoltage, to: snapshot.usbMinusVoltage)
Bogdan Timofte authored 2 months ago
901
    }
Bogdan Timofte authored 2 months ago
902

            
903
    private func inferTC66ActiveDataGroup(from snapshot: TC66Snapshot) {
904
        let candidate = snapshot.dataGroupRecords.compactMap { entry -> (UInt8, Double)? in
905
            let index = entry.key
906
            let record = entry.value
907
            guard let previous = dataGroupRecords[index] else { return nil }
908
            let deltaAH = max(record.ah - previous.ah, 0)
909
            let deltaWH = max(record.wh - previous.wh, 0)
910
            let score = deltaAH + deltaWH
911
            guard score > 0 else { return nil }
912
            return (UInt8(index), score)
913
        }
914
        .max { lhs, rhs in lhs.1 < rhs.1 }
915

            
916
        if let candidate {
917
            selectedDataGroup = candidate.0
918
            hasObservedActiveDataGroup = true
919
        }
920
    }
921

            
922
    private func updateChargeRecord(at timestamp: Date) {
923
        switch chargeRecordState {
924
        case .waitingForStart:
925
            guard current > chargeRecordStopThreshold else { return }
926
            chargeRecordState = .active
927
            chargeRecordStartTimestamp = timestamp
928
            chargeRecordEndTimestamp = timestamp
929
            chargeRecordLastTimestamp = timestamp
930
            chargeRecordLastCurrent = current
931
            chargeRecordLastPower = power
932
        case .active:
933
            if let lastTimestamp = chargeRecordLastTimestamp {
934
                let deltaSeconds = max(timestamp.timeIntervalSince(lastTimestamp), 0)
935
                chargeRecordAH += chargeRecordLastCurrent * deltaSeconds / 3600
936
                chargeRecordWH += chargeRecordLastPower * deltaSeconds / 3600
937
                chargeRecordDuration += deltaSeconds
938
            }
939
            chargeRecordEndTimestamp = timestamp
940
            chargeRecordLastTimestamp = timestamp
941
            chargeRecordLastCurrent = current
942
            chargeRecordLastPower = power
943
            if current <= chargeRecordStopThreshold {
944
                chargeRecordState = .completed
945
            }
946
        case .completed:
947
            break
948
        }
949
    }
950

            
951
    func resetChargeRecord() {
952
        chargeRecordAH = 0
953
        chargeRecordWH = 0
954
        chargeRecordDuration = 0
955
        chargeRecordState = .waitingForStart
956
        chargeRecordStartTimestamp = nil
957
        chargeRecordEndTimestamp = nil
958
        chargeRecordLastTimestamp = nil
959
        chargeRecordLastCurrent = 0
960
        chargeRecordLastPower = 0
Bogdan Timofte authored 2 months ago
961
        objectWillChange.send()
Bogdan Timofte authored 2 months ago
962
    }
963

            
964
    func resetChargeRecordGraph() {
965
        let cutoff = Date()
966
        resetChargeRecord()
967
        measurements.trim(before: cutoff)
968
    }
Bogdan Timofte authored a month ago
969

            
970
    func restoreChargeRecordIfNeeded(from activeSession: ChargeSessionSummary) {
971
        guard chargeRecordState == .waitingForStart else { return }
972
        guard chargeRecordStartTimestamp == nil else { return }
973
        guard chargeRecordAH == 0, chargeRecordWH == 0, chargeRecordDuration == 0 else { return }
974

            
975
        chargeRecordState = .active
976
        chargeRecordAH = activeSession.measuredChargeAh
977
        chargeRecordWH = activeSession.measuredEnergyWh
978
        chargeRecordDuration = max(activeSession.lastObservedAt.timeIntervalSince(activeSession.startedAt), 0)
979
        chargeRecordStopThreshold = activeSession.stopThresholdAmps
980
        chargeRecordStartTimestamp = activeSession.startedAt
981
        chargeRecordEndTimestamp = activeSession.lastObservedAt
982
        chargeRecordLastTimestamp = nil
983
        chargeRecordLastCurrent = 0
984
        chargeRecordLastPower = 0
985
        if let selectedDataGroup = activeSession.selectedDataGroup {
986
            self.selectedDataGroup = selectedDataGroup
987
        }
988
        objectWillChange.send()
989
    }
990

            
991
    func restoreChargeMonitoringIfNeeded(from activeSession: ChargeSessionSummary) {
992
        restoreChargeRecordIfNeeded(from: activeSession)
993

            
994
        guard restoredChargeSessionID != activeSession.id else {
995
            return
996
        }
997

            
998
        restoredChargeSessionID = activeSession.id
999
        enableAutoConnect = true
1000

            
1001
        guard operationalState < .peripheralConnectionPending else {
1002
            return
1003
        }
1004

            
1005
        track("\(name) - Restoring active charge session and reconnecting to meter")
1006
        btSerial.connect()
1007
    }
Bogdan Timofte authored 2 months ago
1008

            
1009
    func nextScreen() {
1010
        switch model {
1011
        case .UM25C:
Bogdan Timofte authored 2 months ago
1012
            commandQueue.append(UMProtocol.nextScreen)
Bogdan Timofte authored 2 months ago
1013
        case .UM34C:
Bogdan Timofte authored 2 months ago
1014
            commandQueue.append(UMProtocol.nextScreen)
Bogdan Timofte authored 2 months ago
1015
        case .TC66C:
Bogdan Timofte authored 2 months ago
1016
            commandQueue.append(TC66Protocol.nextPage)
Bogdan Timofte authored 2 months ago
1017
        }
1018
    }
1019

            
1020
    func rotateScreen() {
1021
        switch model {
1022
        case .UM25C:
Bogdan Timofte authored 2 months ago
1023
            commandQueue.append(UMProtocol.rotateScreen)
Bogdan Timofte authored 2 months ago
1024
        case .UM34C:
Bogdan Timofte authored 2 months ago
1025
            commandQueue.append(UMProtocol.rotateScreen)
Bogdan Timofte authored 2 months ago
1026
        case .TC66C:
Bogdan Timofte authored 2 months ago
1027
            commandQueue.append(TC66Protocol.rotateScreen)
Bogdan Timofte authored 2 months ago
1028
        }
1029
    }
1030

            
1031
    func previousScreen() {
1032
        switch model {
1033
        case .UM25C:
Bogdan Timofte authored 2 months ago
1034
            commandQueue.append(UMProtocol.previousScreen)
Bogdan Timofte authored 2 months ago
1035
        case .UM34C:
Bogdan Timofte authored 2 months ago
1036
            commandQueue.append(UMProtocol.previousScreen)
Bogdan Timofte authored 2 months ago
1037
        case .TC66C:
Bogdan Timofte authored 2 months ago
1038
            commandQueue.append(TC66Protocol.previousPage)
Bogdan Timofte authored 2 months ago
1039
        }
1040
    }
1041

            
1042
    func clear() {
Bogdan Timofte authored 2 months ago
1043
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1044
        noteInitiatedVolatileMemoryResetIfNeeded(for: selectedDataGroup)
Bogdan Timofte authored 2 months ago
1045
        commandQueue.append(UMProtocol.clearCurrentGroup)
Bogdan Timofte authored 2 months ago
1046
    }
1047

            
1048
    func clear(group id: UInt8) {
Bogdan Timofte authored 2 months ago
1049
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1050
        commandQueue.append(UMProtocol.selectDataGroup(id))
Bogdan Timofte authored 2 months ago
1051
        noteInitiatedVolatileMemoryResetIfNeeded(for: id)
1052
        commandQueue.append(UMProtocol.clearCurrentGroup)
Bogdan Timofte authored 2 months ago
1053
        commandQueue.append(UMProtocol.selectDataGroup(selectedDataGroup))
Bogdan Timofte authored 2 months ago
1054
    }
1055

            
1056
    func selectDataGroup ( id: UInt8) {
Bogdan Timofte authored 2 months ago
1057
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1058
        track("\(name) - \(id)")
1059
        selectedDataGroup = id
Bogdan Timofte authored 2 months ago
1060
        objectWillChange.send()
Bogdan Timofte authored 2 months ago
1061
        commandQueue.append(UMProtocol.selectDataGroup(selectedDataGroup))
Bogdan Timofte authored 2 months ago
1062
    }
1063

            
1064
    private func setSceeenBrightness ( to value: UInt8) {
1065
        track("\(name) - \(value)")
Bogdan Timofte authored 2 months ago
1066
        guard supportsUMSettings else { return }
Bogdan Timofte authored 2 months ago
1067
        commandQueue.append(UMProtocol.setScreenBrightness(value))
Bogdan Timofte authored 2 months ago
1068
    }
1069
    private func setScreenSaverTimeout ( to value: UInt8) {
1070
        track("\(name) - \(value)")
Bogdan Timofte authored 2 months ago
1071
        guard supportsUMSettings else { return }
Bogdan Timofte authored 2 months ago
1072
        commandQueue.append(UMProtocol.setScreenSaverTimeout(value))
Bogdan Timofte authored 2 months ago
1073
    }
1074
    func setrecordingTreshold ( to value: UInt8) {
Bogdan Timofte authored 2 months ago
1075
        guard supportsRecordingThreshold else { return }
Bogdan Timofte authored 2 months ago
1076
        commandQueue.append(UMProtocol.setRecordingThreshold(value))
Bogdan Timofte authored 2 months ago
1077
    }
1078

            
1079
    /**
1080
     Connect to meter.
1081
     1. It calls BluetoothSerial.connect
1082
     */
1083
    func connect() {
1084
        enableAutoConnect = true
1085
        btSerial.connect()
1086
    }
1087

            
1088
    /**
1089
     Disconnect from meter.
1090
        It calls BluetoothSerial.disconnect
1091
     */
1092
    func disconnect() {
1093
        enableAutoConnect = false
1094
        btSerial.disconnect()
1095
    }
1096
}
1097

            
1098
extension Meter : SerialPortDelegate {
1099

            
1100
    func opertionalStateChanged(to serialPortOperationalState: BluetoothSerial.OperationalState) {
Bogdan Timofte authored 2 months ago
1101
        let applyStateChange = {
1102
            self.lastSeen = Date()
1103
            switch serialPortOperationalState {
1104
            case .peripheralNotConnected:
1105
                self.operationalState = .peripheralNotConnected
1106
            case .peripheralConnectionPending:
1107
                self.operationalState = .peripheralConnectionPending
1108
            case .peripheralConnected:
Bogdan Timofte authored 2 months ago
1109
                self.noteConnectionEstablished(at: Date())
Bogdan Timofte authored 2 months ago
1110
                self.operationalState = .peripheralConnected
1111
            case .peripheralReady:
1112
                self.operationalState = .peripheralReady
1113
            }
1114
        }
1115

            
1116
        if Thread.isMainThread {
1117
            applyStateChange()
1118
        } else {
1119
            DispatchQueue.main.async(execute: applyStateChange)
Bogdan Timofte authored 2 months ago
1120
        }
1121
    }
1122

            
1123
    func didReceiveData(_ data: Data) {
Bogdan Timofte authored 2 months ago
1124
        let applyData = {
1125
            self.lastSeen = Date()
Bogdan Timofte authored 2 months ago
1126
            if self.operationalState < .comunicating {
1127
                self.operationalState = .comunicating
1128
            }
Bogdan Timofte authored 2 months ago
1129
            self.parseData(from: data)
1130
        }
1131

            
1132
        if Thread.isMainThread {
1133
            applyData()
1134
        } else {
1135
            DispatchQueue.main.async(execute: applyData)
1136
        }
Bogdan Timofte authored 2 months ago
1137
    }
1138
}