Newer Older
1128 lines | 40.245kb
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? {
623
        ChargingMonitorSnapshot(
624
            meterMACAddress: btSerial.macAddress.description,
625
            meterName: name,
626
            meterModel: deviceModelSummary,
627
            observedAt: observedAt,
628
            voltageVolts: voltage,
629
            currentAmps: current,
630
            powerWatts: power,
631
            selectedDataGroup: currentEnergySample()?.groupID ?? currentChargeSample()?.groupID,
632
            meterChargeCounterAh: currentChargeSample()?.value,
633
            meterEnergyCounterWh: currentEnergySample()?.value,
634
            fallbackStopThresholdAmps: chargeRecordStopThreshold
635
        )
636
    }
637

            
638
    var chargingMonitorSnapshot: ChargingMonitorSnapshot? {
639
        chargingMonitorSnapshot(at: Date())
640
    }
641

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

            
649
    private func scheduleDataDumpRequest(after delay: TimeInterval, reason: String) {
650
        cancelPendingDataDumpRequest(reason: "reschedule")
651

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

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

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

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

            
694
    private func didUMVolatileMemoryDecrease(in snapshot: UMSnapshot) -> Bool {
695
        guard hasSeenUMSnapshot else { return false }
696
        guard let previousRecord = dataGroupRecords[0], let nextRecord = snapshot.dataGroupRecords[0] else {
697
            return false
698
        }
699

            
700
        return nextRecord.ah < (previousRecord.ah - volatileMemoryDecreaseEpsilon)
701
            || nextRecord.wh < (previousRecord.wh - volatileMemoryDecreaseEpsilon)
702
    }
703

            
704
    private func didUMDeviceReboot(with snapshot: UMSnapshot, at timestamp: Date) -> Bool {
705
        defer { hasSeenUMSnapshot = true }
706

            
707
        guard didUMVolatileMemoryDecrease(in: snapshot) else { return false }
708
        guard !shouldIgnoreVolatileMemoryDrop(at: timestamp) else { return false }
709

            
710
        track("\(name) - Inferred UM reboot because volatile memory dropped.")
711
        return true
712
    }
713

            
714
    private func didTC66DeviceReboot(with snapshot: TC66Snapshot) -> Bool {
715
        guard hasSeenTC66Snapshot else { return false }
716
        guard snapshot.bootCount != bootCount else { return false }
717

            
718
        track("\(name) - Inferred TC66 reboot because bootCount changed from \(bootCount) to \(snapshot.bootCount).")
719
        return true
720
    }
721

            
722
    private func updateChargerTypeLatch(observedIndex: UInt16, didDetectDeviceReset: Bool) {
723
        if didDetectDeviceReset, chargerTypeIndex != 0 {
Bogdan Timofte authored 2 months ago
724
            setIfChanged(\.chargerTypeIndex, to: 0)
Bogdan Timofte authored 2 months ago
725
        }
726

            
727
        guard supportsChargerDetection else { return }
728

            
729
        if chargerTypeIndex == 0 {
Bogdan Timofte authored 2 months ago
730
            setIfChanged(\.chargerTypeIndex, to: observedIndex)
Bogdan Timofte authored 2 months ago
731
            return
732
        }
733

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

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

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

            
Bogdan Timofte authored 2 months ago
818
    private func apply(umSnapshot snapshot: UMSnapshot) {
Bogdan Timofte authored 2 months ago
819
        let didDetectDeviceReset = didUMDeviceReboot(with: snapshot, at: dataDumpRequestTimestamp)
Bogdan Timofte authored 2 months ago
820
        setIfChanged(\.modelNumber, to: snapshot.modelNumber)
821
        setIfChanged(\.voltage, to: snapshot.voltage)
822
        setIfChanged(\.current, to: snapshot.current)
823
        setIfChanged(\.power, to: snapshot.power)
824
        setIfChanged(\.temperatureCelsius, to: snapshot.temperatureCelsius)
825
        setIfChanged(\.temperatureFahrenheit, to: snapshot.temperatureFahrenheit)
826
        setIfChanged(\.selectedDataGroup, to: snapshot.selectedDataGroup)
Bogdan Timofte authored 2 months ago
827
        for (index, record) in snapshot.dataGroupRecords {
Bogdan Timofte authored 2 months ago
828
            updateDataGroupRecord(index: index, ah: record.ah, wh: record.wh)
Bogdan Timofte authored 2 months ago
829
        }
Bogdan Timofte authored 2 months ago
830
        setIfChanged(\.usbPlusVoltage, to: snapshot.usbPlusVoltage)
831
        setIfChanged(\.usbMinusVoltage, to: snapshot.usbMinusVoltage)
Bogdan Timofte authored 2 months ago
832
        updateChargerTypeLatch(observedIndex: snapshot.chargerTypeIndex, didDetectDeviceReset: didDetectDeviceReset)
Bogdan Timofte authored 2 months ago
833
        setIfChanged(\.recordedAH, to: snapshot.recordedAH)
834
        setIfChanged(\.recordedWH, to: snapshot.recordedWH)
Bogdan Timofte authored 2 months ago
835

            
836
        if recordingThresholdTimestamp < dataDumpRequestTimestamp || !recordingThresholdLoadedFromDevice {
837
            recordingThresholdLoadedFromDevice = true
838
            if recordingTreshold != snapshot.recordingThreshold {
839
                isApplyingRecordingThresholdFromDevice = true
840
                recordingTreshold = snapshot.recordingThreshold
841
                isApplyingRecordingThresholdFromDevice = false
842
            }
843
        } else {
844
            track("\(name) - Skip updating recordingThreshold (changed after request).")
845
        }
Bogdan Timofte authored 2 months ago
846
        setIfChanged(\.recordingDuration, to: snapshot.recordingDuration)
847
        setIfChanged(\.recording, to: snapshot.recording)
Bogdan Timofte authored 2 months ago
848

            
Bogdan Timofte authored 2 months ago
849
        if screenTimeoutTimestamp < dataDumpRequestTimestamp {
Bogdan Timofte authored 2 months ago
850
            if screenTimeout != snapshot.screenTimeout {
851
                screenTimeout = snapshot.screenTimeout
Bogdan Timofte authored 2 months ago
852
            }
853
        } else {
854
            track("\(name) - Skip updating screenTimeout (changed after request).")
855
        }
856

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

            
Bogdan Timofte authored 2 months ago
865
        setIfChanged(\.currentScreen, to: snapshot.currentScreen)
866
        setIfChanged(\.loadResistance, to: snapshot.loadResistance)
Bogdan Timofte authored 2 months ago
867
    }
868

            
Bogdan Timofte authored 2 months ago
869
    private func apply(tc66Snapshot snapshot: TC66Snapshot) {
Bogdan Timofte authored 2 months ago
870
        let didDetectDeviceReset = didTC66DeviceReboot(with: snapshot)
Bogdan Timofte authored 2 months ago
871
        if hasSeenTC66Snapshot {
872
            inferTC66ActiveDataGroup(from: snapshot)
873
        } else {
874
            hasSeenTC66Snapshot = true
875
        }
Bogdan Timofte authored 2 months ago
876
        setIfChanged(\.reportedModelName, to: snapshot.modelName)
877
        setIfChanged(\.firmwareVersion, to: snapshot.firmwareVersion)
878
        setIfChanged(\.serialNumber, to: snapshot.serialNumber)
879
        setIfChanged(\.bootCount, to: snapshot.bootCount)
Bogdan Timofte authored 2 months ago
880
        updateChargerTypeLatch(observedIndex: 0, didDetectDeviceReset: didDetectDeviceReset)
Bogdan Timofte authored 2 months ago
881
        setIfChanged(\.voltage, to: snapshot.voltage)
882
        setIfChanged(\.current, to: snapshot.current)
883
        setIfChanged(\.power, to: snapshot.power)
884
        setIfChanged(\.loadResistance, to: snapshot.loadResistance)
Bogdan Timofte authored 2 months ago
885
        for (index, record) in snapshot.dataGroupRecords {
Bogdan Timofte authored 2 months ago
886
            updateDataGroupRecord(index: index, ah: record.ah, wh: record.wh)
Bogdan Timofte authored 2 months ago
887
        }
Bogdan Timofte authored 2 months ago
888
        setIfChanged(\.temperatureCelsius, to: snapshot.temperatureCelsius)
889
        setIfChanged(\.usbPlusVoltage, to: snapshot.usbPlusVoltage)
890
        setIfChanged(\.usbMinusVoltage, to: snapshot.usbMinusVoltage)
Bogdan Timofte authored 2 months ago
891
    }
Bogdan Timofte authored 2 months ago
892

            
893
    private func inferTC66ActiveDataGroup(from snapshot: TC66Snapshot) {
894
        let candidate = snapshot.dataGroupRecords.compactMap { entry -> (UInt8, Double)? in
895
            let index = entry.key
896
            let record = entry.value
897
            guard let previous = dataGroupRecords[index] else { return nil }
898
            let deltaAH = max(record.ah - previous.ah, 0)
899
            let deltaWH = max(record.wh - previous.wh, 0)
900
            let score = deltaAH + deltaWH
901
            guard score > 0 else { return nil }
902
            return (UInt8(index), score)
903
        }
904
        .max { lhs, rhs in lhs.1 < rhs.1 }
905

            
906
        if let candidate {
907
            selectedDataGroup = candidate.0
908
            hasObservedActiveDataGroup = true
909
        }
910
    }
911

            
912
    private func updateChargeRecord(at timestamp: Date) {
913
        switch chargeRecordState {
914
        case .waitingForStart:
915
            guard current > chargeRecordStopThreshold else { return }
916
            chargeRecordState = .active
917
            chargeRecordStartTimestamp = timestamp
918
            chargeRecordEndTimestamp = timestamp
919
            chargeRecordLastTimestamp = timestamp
920
            chargeRecordLastCurrent = current
921
            chargeRecordLastPower = power
922
        case .active:
923
            if let lastTimestamp = chargeRecordLastTimestamp {
924
                let deltaSeconds = max(timestamp.timeIntervalSince(lastTimestamp), 0)
925
                chargeRecordAH += chargeRecordLastCurrent * deltaSeconds / 3600
926
                chargeRecordWH += chargeRecordLastPower * deltaSeconds / 3600
927
                chargeRecordDuration += deltaSeconds
928
            }
929
            chargeRecordEndTimestamp = timestamp
930
            chargeRecordLastTimestamp = timestamp
931
            chargeRecordLastCurrent = current
932
            chargeRecordLastPower = power
933
            if current <= chargeRecordStopThreshold {
934
                chargeRecordState = .completed
935
            }
936
        case .completed:
937
            break
938
        }
939
    }
940

            
941
    func resetChargeRecord() {
942
        chargeRecordAH = 0
943
        chargeRecordWH = 0
944
        chargeRecordDuration = 0
945
        chargeRecordState = .waitingForStart
946
        chargeRecordStartTimestamp = nil
947
        chargeRecordEndTimestamp = nil
948
        chargeRecordLastTimestamp = nil
949
        chargeRecordLastCurrent = 0
950
        chargeRecordLastPower = 0
Bogdan Timofte authored 2 months ago
951
        objectWillChange.send()
Bogdan Timofte authored 2 months ago
952
    }
953

            
954
    func resetChargeRecordGraph() {
955
        let cutoff = Date()
956
        resetChargeRecord()
957
        measurements.trim(before: cutoff)
958
    }
Bogdan Timofte authored a month ago
959

            
960
    func restoreChargeRecordIfNeeded(from activeSession: ChargeSessionSummary) {
961
        guard chargeRecordState == .waitingForStart else { return }
962
        guard chargeRecordStartTimestamp == nil else { return }
963
        guard chargeRecordAH == 0, chargeRecordWH == 0, chargeRecordDuration == 0 else { return }
964

            
965
        chargeRecordState = .active
966
        chargeRecordAH = activeSession.measuredChargeAh
967
        chargeRecordWH = activeSession.measuredEnergyWh
968
        chargeRecordDuration = max(activeSession.lastObservedAt.timeIntervalSince(activeSession.startedAt), 0)
969
        chargeRecordStopThreshold = activeSession.stopThresholdAmps
970
        chargeRecordStartTimestamp = activeSession.startedAt
971
        chargeRecordEndTimestamp = activeSession.lastObservedAt
972
        chargeRecordLastTimestamp = nil
973
        chargeRecordLastCurrent = 0
974
        chargeRecordLastPower = 0
975
        if let selectedDataGroup = activeSession.selectedDataGroup {
976
            self.selectedDataGroup = selectedDataGroup
977
        }
978
        objectWillChange.send()
979
    }
980

            
981
    func restoreChargeMonitoringIfNeeded(from activeSession: ChargeSessionSummary) {
982
        restoreChargeRecordIfNeeded(from: activeSession)
983

            
984
        guard restoredChargeSessionID != activeSession.id else {
985
            return
986
        }
987

            
988
        restoredChargeSessionID = activeSession.id
989
        enableAutoConnect = true
990

            
991
        guard operationalState < .peripheralConnectionPending else {
992
            return
993
        }
994

            
995
        track("\(name) - Restoring active charge session and reconnecting to meter")
996
        btSerial.connect()
997
    }
Bogdan Timofte authored 2 months ago
998

            
999
    func nextScreen() {
1000
        switch model {
1001
        case .UM25C:
Bogdan Timofte authored 2 months ago
1002
            commandQueue.append(UMProtocol.nextScreen)
Bogdan Timofte authored 2 months ago
1003
        case .UM34C:
Bogdan Timofte authored 2 months ago
1004
            commandQueue.append(UMProtocol.nextScreen)
Bogdan Timofte authored 2 months ago
1005
        case .TC66C:
Bogdan Timofte authored 2 months ago
1006
            commandQueue.append(TC66Protocol.nextPage)
Bogdan Timofte authored 2 months ago
1007
        }
1008
    }
1009

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

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

            
1032
    func clear() {
Bogdan Timofte authored 2 months ago
1033
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1034
        noteInitiatedVolatileMemoryResetIfNeeded(for: selectedDataGroup)
Bogdan Timofte authored 2 months ago
1035
        commandQueue.append(UMProtocol.clearCurrentGroup)
Bogdan Timofte authored 2 months ago
1036
    }
1037

            
1038
    func clear(group id: UInt8) {
Bogdan Timofte authored 2 months ago
1039
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1040
        commandQueue.append(UMProtocol.selectDataGroup(id))
Bogdan Timofte authored 2 months ago
1041
        noteInitiatedVolatileMemoryResetIfNeeded(for: id)
1042
        commandQueue.append(UMProtocol.clearCurrentGroup)
Bogdan Timofte authored 2 months ago
1043
        commandQueue.append(UMProtocol.selectDataGroup(selectedDataGroup))
Bogdan Timofte authored 2 months ago
1044
    }
1045

            
1046
    func selectDataGroup ( id: UInt8) {
Bogdan Timofte authored 2 months ago
1047
        guard supportsDataGroupCommands else { return }
Bogdan Timofte authored 2 months ago
1048
        track("\(name) - \(id)")
1049
        selectedDataGroup = id
Bogdan Timofte authored 2 months ago
1050
        objectWillChange.send()
Bogdan Timofte authored 2 months ago
1051
        commandQueue.append(UMProtocol.selectDataGroup(selectedDataGroup))
Bogdan Timofte authored 2 months ago
1052
    }
1053

            
1054
    private func setSceeenBrightness ( to value: UInt8) {
1055
        track("\(name) - \(value)")
Bogdan Timofte authored 2 months ago
1056
        guard supportsUMSettings else { return }
Bogdan Timofte authored 2 months ago
1057
        commandQueue.append(UMProtocol.setScreenBrightness(value))
Bogdan Timofte authored 2 months ago
1058
    }
1059
    private func setScreenSaverTimeout ( to value: UInt8) {
1060
        track("\(name) - \(value)")
Bogdan Timofte authored 2 months ago
1061
        guard supportsUMSettings else { return }
Bogdan Timofte authored 2 months ago
1062
        commandQueue.append(UMProtocol.setScreenSaverTimeout(value))
Bogdan Timofte authored 2 months ago
1063
    }
1064
    func setrecordingTreshold ( to value: UInt8) {
Bogdan Timofte authored 2 months ago
1065
        guard supportsRecordingThreshold else { return }
Bogdan Timofte authored 2 months ago
1066
        commandQueue.append(UMProtocol.setRecordingThreshold(value))
Bogdan Timofte authored 2 months ago
1067
    }
1068

            
1069
    /**
1070
     Connect to meter.
1071
     1. It calls BluetoothSerial.connect
1072
     */
1073
    func connect() {
1074
        enableAutoConnect = true
1075
        btSerial.connect()
1076
    }
1077

            
1078
    /**
1079
     Disconnect from meter.
1080
        It calls BluetoothSerial.disconnect
1081
     */
1082
    func disconnect() {
1083
        enableAutoConnect = false
1084
        btSerial.disconnect()
1085
    }
1086
}
1087

            
1088
extension Meter : SerialPortDelegate {
1089

            
1090
    func opertionalStateChanged(to serialPortOperationalState: BluetoothSerial.OperationalState) {
Bogdan Timofte authored 2 months ago
1091
        let applyStateChange = {
1092
            self.lastSeen = Date()
1093
            switch serialPortOperationalState {
1094
            case .peripheralNotConnected:
1095
                self.operationalState = .peripheralNotConnected
1096
            case .peripheralConnectionPending:
1097
                self.operationalState = .peripheralConnectionPending
1098
            case .peripheralConnected:
Bogdan Timofte authored 2 months ago
1099
                self.noteConnectionEstablished(at: Date())
Bogdan Timofte authored 2 months ago
1100
                self.operationalState = .peripheralConnected
1101
            case .peripheralReady:
1102
                self.operationalState = .peripheralReady
1103
            }
1104
        }
1105

            
1106
        if Thread.isMainThread {
1107
            applyStateChange()
1108
        } else {
1109
            DispatchQueue.main.async(execute: applyStateChange)
Bogdan Timofte authored 2 months ago
1110
        }
1111
    }
1112

            
1113
    func didReceiveData(_ data: Data) {
Bogdan Timofte authored 2 months ago
1114
        let applyData = {
1115
            self.lastSeen = Date()
Bogdan Timofte authored 2 months ago
1116
            if self.operationalState < .comunicating {
1117
                self.operationalState = .comunicating
1118
            }
Bogdan Timofte authored 2 months ago
1119
            self.parseData(from: data)
1120
        }
1121

            
1122
        if Thread.isMainThread {
1123
            applyData()
1124
        } else {
1125
            DispatchQueue.main.async(execute: applyData)
1126
        }
Bogdan Timofte authored 2 months ago
1127
    }
1128
}