USB-Meter / USB Meter / Model / ChargeInsightsStore.swift
Newer Older
2806 lines | 122.813kb
Bogdan Timofte authored a month ago
1
//
2
//  ChargeInsightsStore.swift
3
//  USB Meter
4
//
5
//  Created by Codex on 10/04/2026.
6
//
7

            
8
import CoreData
9
import Foundation
10

            
11
final class ChargeInsightsStore {
12
    private enum EntityName {
13
        static let chargedDevice = "ChargedDevice"
14
        static let chargeSession = "ChargeSession"
15
        static let chargeCheckpoint = "ChargeCheckpoint"
16
        static let chargeSessionSample = "ChargeSessionSample"
17
    }
18

            
19
    private enum MeterAssignmentKind {
20
        case chargedDevice
21
        case charger
22

            
23
        var expectsChargerClass: Bool {
24
            switch self {
25
            case .chargedDevice:
26
                return false
27
            case .charger:
28
                return true
29
            }
30
        }
31
    }
32

            
33
    private static let persistedSamplesPerHour = 300
34
    private static let aggregatedSampleBucketDuration = 3600.0 / Double(persistedSamplesPerHour)
35

            
36
    private let context: NSManagedObjectContext
37
    private let stopDetectionHoldDuration: TimeInterval = 20
38
    private let maximumLiveIntegrationGap: TimeInterval = 20
39
    private let activeSessionSaveInterval: TimeInterval = 15
Bogdan Timofte authored a month ago
40
    private let aggregatedSampleSaveInterval: TimeInterval = 5
Bogdan Timofte authored a month ago
41
    private let counterDecreaseTolerance = 0.002
42
    private let completionConfirmationCooldown: TimeInterval = 15 * 60
Bogdan Timofte authored a month ago
43
    private let pausedSessionTimeout: TimeInterval = 10 * 60
Bogdan Timofte authored a month ago
44
    private let defaultCompletionPercentThreshold = 95.0
45
    private let completionContradictionTolerancePercent = 2.0
46
    private let minimumWirelessEfficiencyFactor = 0.35
47
    private let maximumWirelessEfficiencyFactor = 0.95
48
    private let lowWirelessEfficiencyThreshold = 0.72
Bogdan Timofte authored a month ago
49
    private let unresolvedFlatBatteryPercent = -1.0
Bogdan Timofte authored a month ago
50

            
51
    init(context: NSManagedObjectContext) {
52
        self.context = context
53
    }
54

            
55
    func refreshContext() {
56
        context.performAndWait {
57
            context.processPendingChanges()
58
        }
59
    }
60

            
61
    @discardableResult
62
    func flushPendingChanges() -> Bool {
63
        var didSave = false
64
        context.performAndWait {
65
            context.processPendingChanges()
66
            didSave = saveContext()
67
        }
68
        return didSave
69
    }
70

            
71
    @discardableResult
Bogdan Timofte authored a month ago
72
    func createDevice(
Bogdan Timofte authored a month ago
73
        name: String,
74
        deviceClass: ChargedDeviceClass,
Bogdan Timofte authored a month ago
75
        chargingStateAvailability: ChargingStateAvailability,
Bogdan Timofte authored a month ago
76
        supportsWiredCharging: Bool,
77
        supportsWirelessCharging: Bool,
78
        wirelessChargingProfile: WirelessChargingProfile,
Bogdan Timofte authored a month ago
79
        configuredCompletionCurrents: [ChargeSessionKind: Double],
Bogdan Timofte authored a month ago
80
        notes: String?,
81
        assignTo meterMACAddress: String?
82
    ) -> Bool {
Bogdan Timofte authored a month ago
83
        guard deviceClass.kind == .device else { return false }
Bogdan Timofte authored a month ago
84
        let normalizedName = normalizedText(name)
85
        guard !normalizedName.isEmpty else { return false }
86
        guard supportsWiredCharging || supportsWirelessCharging else { return false }
87

            
88
        var didSave = false
89
        context.performAndWait {
90
            guard let entity = NSEntityDescription.entity(forEntityName: EntityName.chargedDevice, in: context) else {
91
                return
92
            }
93

            
94
            let object = NSManagedObject(entity: entity, insertInto: context)
95
            let now = Date()
96
            object.setValue(UUID().uuidString, forKey: "id")
97
            object.setValue(normalizedName, forKey: "name")
98
            object.setValue(deviceClass.rawValue, forKey: "deviceClassRawValue")
Bogdan Timofte authored a month ago
99
            object.setValue(chargingStateAvailability.rawValue, forKey: "chargingStateAvailabilityRawValue")
100
            object.setValue(chargingStateAvailability.supportsChargingWhileOff, forKey: "supportsChargingWhileOff")
Bogdan Timofte authored a month ago
101
            object.setValue(supportsWiredCharging, forKey: "supportsWiredCharging")
102
            object.setValue(supportsWirelessCharging, forKey: "supportsWirelessCharging")
103
            object.setValue(wirelessChargingProfile.rawValue, forKey: "wirelessChargingProfileRawValue")
Bogdan Timofte authored a month ago
104
            object.setValue(encodedCompletionCurrents(configuredCompletionCurrents), forKey: "configuredCompletionCurrentsRawValue")
105
            object.setValue(legacyConfiguredCompletionCurrent(for: configuredCompletionCurrents, chargingTransportMode: .wired), forKey: "wiredChargeCompletionCurrentAmps")
106
            object.setValue(legacyConfiguredCompletionCurrent(for: configuredCompletionCurrents, chargingTransportMode: .wireless), forKey: "wirelessChargeCompletionCurrentAmps")
Bogdan Timofte authored a month ago
107
            object.setValue(normalizedOptionalText(notes), forKey: "notes")
108
            object.setValue(generateQRIdentifier(), forKey: "qrIdentifier")
109
            object.setValue(normalizedOptionalText(meterMACAddress), forKey: "lastAssociatedMeterMAC")
110
            object.setValue(now, forKey: "createdAt")
111
            object.setValue(now, forKey: "updatedAt")
112
            didSave = saveContext()
113
        }
114
        return didSave
115
    }
116

            
117
    @discardableResult
Bogdan Timofte authored a month ago
118
    func createCharger(
119
        name: String,
120
        notes: String?,
121
        assignTo meterMACAddress: String?
122
    ) -> Bool {
123
        let normalizedName = normalizedText(name)
124
        guard !normalizedName.isEmpty else { return false }
125

            
126
        var didSave = false
127
        context.performAndWait {
128
            guard let entity = NSEntityDescription.entity(forEntityName: EntityName.chargedDevice, in: context) else {
129
                return
130
            }
131

            
132
            let object = NSManagedObject(entity: entity, insertInto: context)
133
            let now = Date()
134
            object.setValue(UUID().uuidString, forKey: "id")
135
            object.setValue(normalizedName, forKey: "name")
136
            object.setValue(ChargedDeviceClass.charger.rawValue, forKey: "deviceClassRawValue")
137
            object.setValue(ChargingStateAvailability.onOnly.rawValue, forKey: "chargingStateAvailabilityRawValue")
138
            object.setValue(false, forKey: "supportsChargingWhileOff")
139
            object.setValue(false, forKey: "supportsWiredCharging")
140
            object.setValue(true, forKey: "supportsWirelessCharging")
141
            object.setValue(WirelessChargingProfile.genericQi.rawValue, forKey: "wirelessChargingProfileRawValue")
142
            object.setValue(encodedCompletionCurrents([:]), forKey: "configuredCompletionCurrentsRawValue")
143
            object.setValue(nil, forKey: "wiredChargeCompletionCurrentAmps")
144
            object.setValue(nil, forKey: "wirelessChargeCompletionCurrentAmps")
145
            object.setValue(normalizedOptionalText(notes), forKey: "notes")
146
            object.setValue(generateQRIdentifier(), forKey: "qrIdentifier")
147
            object.setValue(normalizedOptionalText(meterMACAddress), forKey: "lastAssociatedMeterMAC")
148
            object.setValue(now, forKey: "createdAt")
149
            object.setValue(now, forKey: "updatedAt")
150
            didSave = saveContext()
151
        }
152
        return didSave
153
    }
154

            
155
    @discardableResult
156
    func updateDevice(
Bogdan Timofte authored a month ago
157
        id: UUID,
158
        name: String,
159
        deviceClass: ChargedDeviceClass,
Bogdan Timofte authored a month ago
160
        chargingStateAvailability: ChargingStateAvailability,
Bogdan Timofte authored a month ago
161
        supportsWiredCharging: Bool,
162
        supportsWirelessCharging: Bool,
163
        wirelessChargingProfile: WirelessChargingProfile,
Bogdan Timofte authored a month ago
164
        configuredCompletionCurrents: [ChargeSessionKind: Double],
Bogdan Timofte authored a month ago
165
        notes: String?
166
    ) -> Bool {
Bogdan Timofte authored a month ago
167
        guard deviceClass.kind == .device else { return false }
Bogdan Timofte authored a month ago
168
        let normalizedName = normalizedText(name)
169
        guard !normalizedName.isEmpty else { return false }
170
        guard supportsWiredCharging || supportsWirelessCharging else { return false }
171

            
172
        var didSave = false
173
        context.performAndWait {
174
            guard let object = fetchChargedDeviceObject(id: id.uuidString) else {
175
                return
176
            }
Bogdan Timofte authored a month ago
177
            guard isChargerObject(object) == false else {
178
                return
179
            }
Bogdan Timofte authored a month ago
180

            
181
            let previousSupportsChargingWhileOff = boolValue(object, key: "supportsChargingWhileOff")
Bogdan Timofte authored a month ago
182
            let previousChargingStateAvailability = self.chargingStateAvailability(for: object)
Bogdan Timofte authored a month ago
183
            let previousSupportsWiredCharging = self.supportsWiredCharging(for: object)
184
            let previousSupportsWirelessCharging = self.supportsWirelessCharging(for: object)
185
            let now = Date()
186

            
187
            object.setValue(normalizedName, forKey: "name")
188
            object.setValue(deviceClass.rawValue, forKey: "deviceClassRawValue")
Bogdan Timofte authored a month ago
189
            object.setValue(chargingStateAvailability.rawValue, forKey: "chargingStateAvailabilityRawValue")
190
            object.setValue(chargingStateAvailability.supportsChargingWhileOff, forKey: "supportsChargingWhileOff")
Bogdan Timofte authored a month ago
191
            object.setValue(supportsWiredCharging, forKey: "supportsWiredCharging")
192
            object.setValue(supportsWirelessCharging, forKey: "supportsWirelessCharging")
193
            object.setValue(wirelessChargingProfile.rawValue, forKey: "wirelessChargingProfileRawValue")
Bogdan Timofte authored a month ago
194
            object.setValue(encodedCompletionCurrents(configuredCompletionCurrents), forKey: "configuredCompletionCurrentsRawValue")
195
            object.setValue(legacyConfiguredCompletionCurrent(for: configuredCompletionCurrents, chargingTransportMode: .wired), forKey: "wiredChargeCompletionCurrentAmps")
196
            object.setValue(legacyConfiguredCompletionCurrent(for: configuredCompletionCurrents, chargingTransportMode: .wireless), forKey: "wirelessChargeCompletionCurrentAmps")
Bogdan Timofte authored a month ago
197
            object.setValue(normalizedOptionalText(notes), forKey: "notes")
198
            object.setValue(now, forKey: "updatedAt")
199

            
Bogdan Timofte authored a month ago
200
            let supportsChargingWhileOff = chargingStateAvailability.supportsChargingWhileOff
Bogdan Timofte authored a month ago
201
            let shouldRecalculateSessionCapacity = previousSupportsChargingWhileOff != supportsChargingWhileOff
202
            let shouldRefreshActiveSessions = shouldRecalculateSessionCapacity
Bogdan Timofte authored a month ago
203
                || previousChargingStateAvailability != chargingStateAvailability
Bogdan Timofte authored a month ago
204
                || previousSupportsWiredCharging != supportsWiredCharging
205
                || previousSupportsWirelessCharging != supportsWirelessCharging
206

            
207
            if shouldRecalculateSessionCapacity || shouldRefreshActiveSessions {
208
                let sessions = fetchSessions(forChargedDeviceID: id.uuidString)
209
                for session in sessions {
Bogdan Timofte authored a month ago
210
                    let isOpen = statusValue(session, key: "statusRawValue")?.isOpen == true
Bogdan Timofte authored a month ago
211

            
212
                    if shouldRecalculateSessionCapacity {
213
                        session.setValue(supportsChargingWhileOff, forKey: "supportsChargingWhileOff")
214
                        updateCapacityEstimate(for: session)
215
                        session.setValue(now, forKey: "updatedAt")
216
                    }
217

            
Bogdan Timofte authored a month ago
218
                    guard isOpen, shouldRefreshActiveSessions else {
Bogdan Timofte authored a month ago
219
                        continue
220
                    }
221

            
222
                    let resolvedSessionChargingTransportMode = resolvedPreferredChargingTransportMode(
223
                        chargingTransportMode(for: session),
224
                        supportsWiredCharging: supportsWiredCharging,
225
                        supportsWirelessCharging: supportsWirelessCharging
226
                    )
Bogdan Timofte authored a month ago
227
                    let resolvedSessionChargingStateMode = resolvedChargingStateMode(
228
                        chargingStateMode(for: session),
229
                        availability: chargingStateAvailability
230
                    )
231
                    let charger = stringValue(session, key: "chargerID").flatMap(fetchChargedDeviceObject(id:))
Bogdan Timofte authored a month ago
232

            
233
                    session.setValue(supportsChargingWhileOff, forKey: "supportsChargingWhileOff")
234
                    session.setValue(resolvedSessionChargingTransportMode.rawValue, forKey: "chargingTransportRawValue")
Bogdan Timofte authored a month ago
235
                    session.setValue(resolvedSessionChargingStateMode.rawValue, forKey: "chargingStateRawValue")
Bogdan Timofte authored a month ago
236
                    session.setValue(
237
                        resolvedStopThreshold(
238
                            for: object,
239
                            chargingTransportMode: resolvedSessionChargingTransportMode,
Bogdan Timofte authored a month ago
240
                            chargingStateMode: resolvedSessionChargingStateMode,
241
                            charger: charger,
242
                            fallback: optionalDoubleValue(session, key: "stopThresholdAmps")
243
                        ) ?? 0,
Bogdan Timofte authored a month ago
244
                        forKey: "stopThresholdAmps"
245
                    )
246
                    session.setValue(now, forKey: "updatedAt")
247
                    updateCapacityEstimate(for: session)
248
                }
249
            }
250

            
251
            refreshDerivedMetrics(forChargedDeviceID: id.uuidString)
252
            didSave = saveContext()
253
        }
254
        return didSave
255
    }
256

            
Bogdan Timofte authored a month ago
257
    @discardableResult
258
    func updateCharger(
259
        id: UUID,
260
        name: String,
261
        notes: String?
262
    ) -> Bool {
263
        let normalizedName = normalizedText(name)
264
        guard !normalizedName.isEmpty else { return false }
265

            
266
        var didSave = false
267
        context.performAndWait {
268
            guard let object = fetchChargedDeviceObject(id: id.uuidString) else {
269
                return
270
            }
271
            guard isChargerObject(object) else {
272
                return
273
            }
274

            
275
            object.setValue(normalizedName, forKey: "name")
276
            object.setValue(normalizedOptionalText(notes), forKey: "notes")
277
            object.setValue(Date(), forKey: "updatedAt")
278
            didSave = saveContext()
279
        }
280

            
281
        return didSave
282
    }
283

            
Bogdan Timofte authored a month ago
284
    @discardableResult
285
    func assignChargedDevice(id: UUID, to meterMACAddress: String) -> Bool {
286
        assign(itemWithID: id, to: meterMACAddress, kind: .chargedDevice)
287
    }
288

            
289
    @discardableResult
290
    func assignCharger(id: UUID, to meterMACAddress: String) -> Bool {
291
        assign(itemWithID: id, to: meterMACAddress, kind: .charger)
292
    }
293

            
294
    @discardableResult
295
    private func assign(
296
        itemWithID id: UUID,
297
        to meterMACAddress: String,
298
        kind: MeterAssignmentKind
299
    ) -> Bool {
300
        let normalizedMAC = normalizedMACAddress(meterMACAddress)
301
        guard !normalizedMAC.isEmpty else { return false }
302

            
303
        var didSave = false
304
        context.performAndWait {
305
            guard let object = fetchChargedDeviceObject(id: id.uuidString) else {
306
                return
307
            }
308

            
309
            let isCharger = ChargedDeviceClass(rawValue: stringValue(object, key: "deviceClassRawValue") ?? "") == .charger
310
            guard isCharger == kind.expectsChargerClass else {
311
                return
312
            }
313

            
314
            let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargedDevice)
315
            request.predicate = NSPredicate(
316
                format: "lastAssociatedMeterMAC == %@ AND id != %@",
317
                normalizedMAC,
318
                id.uuidString
319
            )
320
            let previouslyAssignedDevices = (try? context.fetch(request)) ?? []
321
            for previousDevice in previouslyAssignedDevices {
322
                let previousIsCharger = ChargedDeviceClass(rawValue: stringValue(previousDevice, key: "deviceClassRawValue") ?? "") == .charger
323
                guard previousIsCharger == kind.expectsChargerClass else {
324
                    continue
325
                }
326
                previousDevice.setValue(nil, forKey: "lastAssociatedMeterMAC")
327
                previousDevice.setValue(Date(), forKey: "updatedAt")
328
            }
329

            
330
            object.setValue(normalizedMAC, forKey: "lastAssociatedMeterMAC")
331
            object.setValue(Date(), forKey: "updatedAt")
332

            
333
            if kind == .charger,
Bogdan Timofte authored a month ago
334
               let openSession = fetchOpenSessionObject(forMeterMACAddress: normalizedMAC),
335
               chargingTransportMode(for: openSession) == .wireless {
336
                openSession.setValue(id.uuidString, forKey: "chargerID")
337
                openSession.setValue(Date(), forKey: "updatedAt")
Bogdan Timofte authored a month ago
338
            }
339

            
340
            didSave = saveContext()
341
        }
342
        return didSave
343
    }
344

            
345
    @discardableResult
Bogdan Timofte authored a month ago
346
    func startSession(
347
        for snapshot: ChargingMonitorSnapshot,
348
        chargedDeviceID: UUID,
349
        chargerID: UUID?,
350
        chargingTransportMode: ChargingTransportMode,
351
        chargingStateMode: ChargingStateMode,
352
        autoStopEnabled: Bool,
Bogdan Timofte authored a month ago
353
        initialBatteryPercent: Double?,
354
        startsFromFlatBattery: Bool
Bogdan Timofte authored a month ago
355
    ) -> Bool {
Bogdan Timofte authored a month ago
356
        if let initialBatteryPercent,
357
           (initialBatteryPercent.isFinite == false || initialBatteryPercent < 0 || initialBatteryPercent > 100) {
Bogdan Timofte authored a month ago
358
            return false
359
        }
360

            
Bogdan Timofte authored a month ago
361
        var didSave = false
362
        context.performAndWait {
Bogdan Timofte authored a month ago
363
            guard let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID.uuidString) else {
Bogdan Timofte authored a month ago
364
                return
365
            }
Bogdan Timofte authored a month ago
366
            guard isChargerObject(chargedDevice) == false else {
367
                return
368
            }
Bogdan Timofte authored a month ago
369

            
Bogdan Timofte authored a month ago
370
            guard fetchOpenSessionObject(forMeterMACAddress: snapshot.meterMACAddress) == nil else {
Bogdan Timofte authored a month ago
371
                return
372
            }
373

            
Bogdan Timofte authored a month ago
374
            let resolvedChargingTransportMode = resolvedPreferredChargingTransportMode(
375
                chargingTransportMode,
376
                supportsWiredCharging: supportsWiredCharging(for: chargedDevice),
377
                supportsWirelessCharging: supportsWirelessCharging(for: chargedDevice)
Bogdan Timofte authored a month ago
378
            )
Bogdan Timofte authored a month ago
379
            let resolvedChargingStateMode = resolvedChargingStateMode(
380
                chargingStateMode,
381
                availability: chargingStateAvailability(for: chargedDevice)
382
            )
383
            let charger = resolvedChargingTransportMode == .wireless
384
                ? chargerID.flatMap { fetchChargedDeviceObject(id: $0.uuidString) }
385
                : nil
Bogdan Timofte authored a month ago
386
            if let charger, isChargerObject(charger) == false {
387
                return
388
            }
Bogdan Timofte authored a month ago
389
            guard resolvedChargingTransportMode == .wired || charger != nil else {
Bogdan Timofte authored a month ago
390
                return
391
            }
Bogdan Timofte authored a month ago
392
            let stopThreshold = resolvedStopThreshold(
Bogdan Timofte authored a month ago
393
                for: chargedDevice,
394
                chargingTransportMode: resolvedChargingTransportMode,
395
                chargingStateMode: resolvedChargingStateMode,
396
                charger: charger,
Bogdan Timofte authored a month ago
397
                fallback: snapshot.fallbackStopThresholdAmps > 0 ? snapshot.fallbackStopThresholdAmps : nil
398
            )
Bogdan Timofte authored a month ago
399
            guard let session = createSessionObject(
400
                for: chargedDevice,
Bogdan Timofte authored a month ago
401
                charger: charger,
402
                snapshot: snapshot,
403
                stopThreshold: stopThreshold,
Bogdan Timofte authored a month ago
404
                chargingTransportMode: resolvedChargingTransportMode,
405
                chargingStateMode: resolvedChargingStateMode,
406
                autoStopEnabled: autoStopEnabled
407
            ) else {
408
                return
409
            }
410

            
Bogdan Timofte authored a month ago
411
            if startsFromFlatBattery {
412
                session.setValue(unresolvedFlatBatteryPercent, forKey: "startBatteryPercent")
413
                session.setValue(nil, forKey: "endBatteryPercent")
414
            } else if let initialBatteryPercent {
415
                guard insertBatteryCheckpoint(
416
                    percent: initialBatteryPercent,
417
                    label: "Start",
418
                    timestamp: snapshot.observedAt,
419
                    to: session
420
                ) != nil else {
421
                    return
422
                }
Bogdan Timofte authored a month ago
423
            }
Bogdan Timofte authored a month ago
424
            didSave = saveContext()
425
        }
426
        return didSave
427
    }
428

            
Bogdan Timofte authored a month ago
429
    @discardableResult
430
    func pauseSession(id sessionID: UUID, observedAt: Date) -> Bool {
431
        var didSave = false
432
        context.performAndWait {
433
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
434
                return
435
            }
436

            
437
            guard statusValue(session, key: "statusRawValue") == .active else {
438
                return
439
            }
440

            
441
            session.setValue(ChargeSessionStatus.paused.rawValue, forKey: "statusRawValue")
442
            session.setValue(observedAt, forKey: "pausedAt")
443
            session.setValue(nil, forKey: "belowThresholdSince")
444
            clearCompletionConfirmationState(for: session)
445
            session.setValue(observedAt, forKey: "updatedAt")
446
            didSave = saveContext()
447
        }
448
        return didSave
449
    }
450

            
451
    @discardableResult
452
    func resumeSession(id sessionID: UUID, snapshot: ChargingMonitorSnapshot?) -> Bool {
453
        var didSave = false
454
        context.performAndWait {
455
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
456
                return
457
            }
458

            
459
            guard statusValue(session, key: "statusRawValue") == .paused else {
460
                return
461
            }
462

            
463
            let pausedAt = dateValue(session, key: "pausedAt") ?? Date()
464
            let resumedAt = snapshot?.observedAt ?? Date()
465
            if resumedAt.timeIntervalSince(pausedAt) >= pausedSessionTimeout {
466
                finishSession(
467
                    session,
468
                    observedAt: pausedAt.addingTimeInterval(pausedSessionTimeout),
469
                    finalBatteryPercent: nil,
470
                    label: nil,
471
                    status: .completed
472
                )
473
                guard saveContext() else {
474
                    return
475
                }
476
                if let deviceID = stringValue(session, key: "chargedDeviceID") {
477
                    refreshDerivedMetrics(forChargedDeviceID: deviceID)
478
                    didSave = saveContext()
479
                } else {
480
                    didSave = true
481
                }
482
                return
483
            }
484

            
485
            session.setValue(ChargeSessionStatus.active.rawValue, forKey: "statusRawValue")
486
            session.setValue(nil, forKey: "pausedAt")
487
            session.setValue(nil, forKey: "belowThresholdSince")
488
            clearCompletionConfirmationState(for: session)
489
            session.setValue(resumedAt, forKey: "lastObservedAt")
490
            if let snapshot {
491
                session.setValue(snapshot.currentAmps, forKey: "lastObservedCurrentAmps")
492
                session.setValue(snapshot.powerWatts, forKey: "lastObservedPowerWatts")
493
                session.setValue(
494
                    chargingTransportMode(for: session) == .wired ? snapshot.voltageVolts : nil,
495
                    forKey: "lastObservedVoltageVolts"
496
                )
497
            } else {
498
                session.setValue(0, forKey: "lastObservedCurrentAmps")
499
                session.setValue(0, forKey: "lastObservedPowerWatts")
500
                session.setValue(nil, forKey: "lastObservedVoltageVolts")
501
            }
502
            session.setValue(resumedAt, forKey: "updatedAt")
503
            didSave = saveContext()
504
        }
505
        return didSave
506
    }
507

            
508
    @discardableResult
509
    func stopSession(
510
        id sessionID: UUID,
511
        finalBatteryPercent: Double,
512
        label: String?
513
    ) -> Bool {
514
        guard finalBatteryPercent.isFinite, finalBatteryPercent >= 0, finalBatteryPercent <= 100 else {
515
            return false
516
        }
517

            
518
        var didSave = false
519
        context.performAndWait {
520
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
521
                return
522
            }
523

            
524
            guard statusValue(session, key: "statusRawValue")?.isOpen == true else {
525
                return
526
            }
527

            
528
            let observedAt = snapshotDateForManualStop(session)
529
            finishSession(
530
                session,
531
                observedAt: observedAt,
532
                finalBatteryPercent: finalBatteryPercent,
533
                label: label,
534
                status: .completed
535
            )
536

            
537
            guard saveContext() else {
538
                return
539
            }
540

            
541
            if let deviceID = stringValue(session, key: "chargedDeviceID") {
542
                refreshDerivedMetrics(forChargedDeviceID: deviceID)
543
                didSave = saveContext()
544
            } else {
545
                didSave = true
546
            }
547
        }
548
        return didSave
549
    }
550

            
Bogdan Timofte authored a month ago
551
    @discardableResult
552
    func addBatteryCheckpoint(
553
        percent: Double,
554
        label: String?,
Bogdan Timofte authored a month ago
555
        for meterMACAddress: String,
556
        measuredEnergyWh: Double? = nil,
557
        measuredChargeAh: Double? = nil
Bogdan Timofte authored a month ago
558
    ) -> Bool {
559
        guard percent.isFinite, percent >= 0, percent <= 100 else {
560
            return false
561
        }
562

            
563
        var didSave = false
564
        context.performAndWait {
Bogdan Timofte authored a month ago
565
            guard let session = fetchOpenSessionObject(forMeterMACAddress: meterMACAddress) else {
Bogdan Timofte authored a month ago
566
                return
567
            }
568

            
Bogdan Timofte authored a month ago
569
            didSave = addBatteryCheckpoint(
570
                percent: percent,
571
                label: label,
572
                measuredEnergyWh: measuredEnergyWh,
573
                measuredChargeAh: measuredChargeAh,
574
                to: session
575
            )
Bogdan Timofte authored a month ago
576
        }
577
        return didSave
578
    }
579

            
580
    @discardableResult
581
    func addBatteryCheckpoint(
582
        percent: Double,
583
        label: String?,
584
        for sessionID: UUID
585
    ) -> Bool {
586
        guard percent.isFinite, percent >= 0, percent <= 100 else {
587
            return false
588
        }
589

            
590
        var didSave = false
591
        context.performAndWait {
592
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
593
                return
594
            }
595

            
596
            didSave = addBatteryCheckpoint(percent: percent, label: label, to: session)
597
        }
598
        return didSave
599
    }
600

            
Bogdan Timofte authored a month ago
601
    @discardableResult
602
    func deleteBatteryCheckpoint(
603
        id checkpointID: UUID,
604
        from sessionID: UUID
605
    ) -> Bool {
606
        var didSave = false
607
        context.performAndWait {
608
            guard let session = fetchSessionObject(id: sessionID.uuidString),
609
                  let checkpoint = fetchCheckpointObject(
610
                    id: checkpointID.uuidString,
611
                    sessionID: sessionID.uuidString
612
                  ) else {
613
                return
614
            }
615

            
616
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID")
617
            context.delete(checkpoint)
618
            refreshCheckpointDerivedValues(for: session)
619

            
620
            guard saveContext() else {
621
                return
622
            }
623

            
624
            if let chargedDeviceID {
625
                refreshDerivedMetrics(forChargedDeviceID: chargedDeviceID)
626
                didSave = saveContext()
627
            } else {
628
                didSave = true
629
            }
630
        }
631
        return didSave
632
    }
633

            
Bogdan Timofte authored a month ago
634
    @discardableResult
635
    func setTargetBatteryPercent(_ percent: Double?, for sessionID: UUID) -> Bool {
636
        if let percent, (!percent.isFinite || percent <= 0 || percent > 100) {
637
            return false
638
        }
639

            
640
        var didSave = false
641
        context.performAndWait {
642
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
643
                return
644
            }
645

            
646
            session.setValue(percent, forKey: "targetBatteryPercent")
647
            session.setValue(nil, forKey: "targetBatteryAlertTriggeredAt")
648
            session.setValue(Date(), forKey: "updatedAt")
649
            didSave = saveContext()
650
        }
651
        return didSave
652
    }
653

            
654
    @discardableResult
655
    func confirmCompletion(for sessionID: UUID) -> Bool {
656
        var didSave = false
657
        context.performAndWait {
658
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
659
                return
660
            }
661

            
662
            guard statusValue(session, key: "statusRawValue") == .active else {
663
                return
664
            }
665

            
Bogdan Timofte authored a month ago
666
            finishSession(
667
                session,
668
                observedAt: dateValue(session, key: "lastObservedAt") ?? Date(),
669
                finalBatteryPercent: nil,
670
                label: nil,
671
                status: .completed
672
            )
Bogdan Timofte authored a month ago
673

            
674
            if saveContext() {
675
                if let deviceID = stringValue(session, key: "chargedDeviceID") {
676
                    refreshDerivedMetrics(forChargedDeviceID: deviceID)
677
                    didSave = saveContext()
678
                } else {
679
                    didSave = true
680
                }
681
            }
682
        }
683
        return didSave
684
    }
685

            
686
    @discardableResult
687
    func continueMonitoringDespiteCompletionContradiction(for sessionID: UUID) -> Bool {
688
        var didSave = false
689
        context.performAndWait {
690
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
691
                return
692
            }
693

            
694
            guard statusValue(session, key: "statusRawValue") == .active else {
695
                return
696
            }
697

            
698
            clearCompletionConfirmationState(for: session)
699
            session.setValue(Date().addingTimeInterval(completionConfirmationCooldown), forKey: "completionConfirmationCooldownUntil")
700
            session.setValue(Date(), forKey: "updatedAt")
701
            didSave = saveContext()
702
        }
703
        return didSave
704
    }
705

            
706
    @discardableResult
707
    func deleteChargeSession(id sessionID: UUID) -> Bool {
708
        var didSave = false
709
        context.performAndWait {
710
            guard let session = fetchSessionObject(id: sessionID.uuidString) else {
711
                return
712
            }
713

            
714
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID")
715

            
716
            fetchCheckpointObjects(forSessionID: sessionID.uuidString).forEach(context.delete)
717
            fetchSessionSampleObjects(forSessionID: sessionID.uuidString).forEach(context.delete)
718
            context.delete(session)
719

            
720
            guard saveContext() else {
721
                return
722
            }
723

            
724
            if let chargedDeviceID {
725
                refreshDerivedMetrics(forChargedDeviceID: chargedDeviceID)
726
                didSave = saveContext()
727
            } else {
728
                didSave = true
729
            }
730
        }
731
        return didSave
732
    }
733

            
734
    @discardableResult
735
    func deleteChargedDevice(id chargedDeviceID: UUID) -> Bool {
736
        var didSave = false
737

            
738
        context.performAndWait {
739
            guard let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID.uuidString) else {
740
                return
741
            }
742

            
743
            let deviceClass = ChargedDeviceClass(rawValue: stringValue(chargedDevice, key: "deviceClassRawValue") ?? "")
744
            let deviceSessions = fetchSessions(forChargedDeviceID: chargedDeviceID.uuidString)
745
            let linkedWirelessSessions = fetchSessions(forChargerID: chargedDeviceID.uuidString)
746

            
747
            var impactedChargedDeviceIDs = Set<String>()
748

            
749
            for session in deviceSessions {
750
                if let impactedID = stringValue(session, key: "chargedDeviceID") {
751
                    impactedChargedDeviceIDs.insert(impactedID)
752
                }
753
                if let impactedChargerID = stringValue(session, key: "chargerID") {
754
                    impactedChargedDeviceIDs.insert(impactedChargerID)
755
                }
756
                if let sessionID = stringValue(session, key: "id") {
757
                    fetchCheckpointObjects(forSessionID: sessionID).forEach(context.delete)
758
                    fetchSessionSampleObjects(forSessionID: sessionID).forEach(context.delete)
759
                }
760
                context.delete(session)
761
            }
762

            
763
            if deviceClass == .charger {
764
                for session in linkedWirelessSessions {
765
                    guard stringValue(session, key: "chargedDeviceID") != chargedDeviceID.uuidString else {
766
                        continue
767
                    }
768
                    if let impactedID = stringValue(session, key: "chargedDeviceID") {
769
                        impactedChargedDeviceIDs.insert(impactedID)
770
                    }
771
                    session.setValue(nil, forKey: "chargerID")
772
                    session.setValue(Date(), forKey: "updatedAt")
773
                }
774
            }
775

            
776
            context.delete(chargedDevice)
777

            
778
            guard saveContext() else {
779
                return
780
            }
781

            
782
            impactedChargedDeviceIDs.remove(chargedDeviceID.uuidString)
783
            for impactedID in impactedChargedDeviceIDs {
784
                refreshDerivedMetrics(forChargedDeviceID: impactedID)
785
            }
786
            didSave = saveContext()
787
        }
788

            
789
        return didSave
790
    }
791

            
792
    @discardableResult
793
    func observe(snapshot: ChargingMonitorSnapshot) -> Bool {
794
        var didSave = false
795

            
796
        context.performAndWait {
Bogdan Timofte authored a month ago
797
            guard let session = fetchOpenSessionObject(forMeterMACAddress: snapshot.meterMACAddress),
798
                  let resolvedDevice = stringValue(session, key: "chargedDeviceID").flatMap(fetchChargedDeviceObject(id:)) else {
799
                return
800
            }
Bogdan Timofte authored a month ago
801

            
Bogdan Timofte authored a month ago
802
            if statusValue(session, key: "statusRawValue") == .paused {
803
                if maybeCompletePausedSession(session, observedAt: snapshot.observedAt) {
804
                    didSave = true
805
                }
Bogdan Timofte authored a month ago
806
                return
807
            }
808

            
Bogdan Timofte authored a month ago
809
            let chargingTransportMode = self.chargingTransportMode(for: session)
810
            let chargingStateMode = self.chargingStateMode(for: session)
Bogdan Timofte authored a month ago
811
            let charger = chargingTransportMode == .wireless
Bogdan Timofte authored a month ago
812
                ? stringValue(session, key: "chargerID").flatMap(fetchChargedDeviceObject(id:))
Bogdan Timofte authored a month ago
813
                : nil
814
            guard chargingTransportMode == .wired || charger != nil else {
815
                return
816
            }
817
            let stopThreshold = resolvedStopThreshold(
818
                for: resolvedDevice,
819
                chargingTransportMode: chargingTransportMode,
Bogdan Timofte authored a month ago
820
                chargingStateMode: chargingStateMode,
821
                charger: charger,
822
                fallback: optionalDoubleValue(session, key: "stopThresholdAmps")
Bogdan Timofte authored a month ago
823
            )
824

            
Bogdan Timofte authored a month ago
825
            update(session: session, with: snapshot, stopThreshold: stopThreshold, charger: charger)
Bogdan Timofte authored a month ago
826
            let aggregatedSample = updateAggregatedSample(session: session, with: snapshot)
Bogdan Timofte authored a month ago
827

            
828
            let saveReason = saveReason(for: session, observedAt: snapshot.observedAt)
Bogdan Timofte authored a month ago
829
            let shouldPersistAggregatedCurve = aggregatedSample.map {
830
                shouldPersistAggregatedSample($0, observedAt: snapshot.observedAt)
831
            } ?? false
832

            
833
            guard saveReason != .none || shouldPersistAggregatedCurve else {
Bogdan Timofte authored a month ago
834
                return
835
            }
836

            
837
            session.setValue(snapshot.observedAt, forKey: "updatedAt")
838

            
839
            if saveContext() {
840
                if saveReason == .completed, let deviceID = stringValue(session, key: "chargedDeviceID") {
841
                    refreshDerivedMetrics(forChargedDeviceID: deviceID)
842
                    didSave = saveContext()
843
                } else {
844
                    didSave = true
845
                }
846
            }
847
        }
848

            
849
        return didSave
850
    }
851

            
852
    func fetchChargedDeviceSummaries() -> [ChargedDeviceSummary] {
853
        var summaries: [ChargedDeviceSummary] = []
854

            
855
        context.performAndWait {
856
            let devices = fetchObjects(entityName: EntityName.chargedDevice)
857
            let sessions = fetchObjects(entityName: EntityName.chargeSession)
858
            let checkpoints = fetchObjects(entityName: EntityName.chargeCheckpoint)
859
            let sessionSamples = fetchObjects(entityName: EntityName.chargeSessionSample)
860

            
861
            let checkpointsBySessionID = Dictionary(grouping: checkpoints) { stringValue($0, key: "sessionID") ?? "" }
862
            let samplesBySessionID = Dictionary(grouping: sessionSamples) { stringValue($0, key: "sessionID") ?? "" }
863
            let sessionsByDeviceID = Dictionary(grouping: sessions) { stringValue($0, key: "chargedDeviceID") ?? "" }
864
            let sessionsByChargerID = Dictionary(grouping: sessions) { stringValue($0, key: "chargerID") ?? "" }
865

            
866
            summaries = devices.compactMap { device in
867
                guard
868
                    let id = uuidValue(device, key: "id"),
869
                    let name = stringValue(device, key: "name"),
870
                    let qrIdentifier = stringValue(device, key: "qrIdentifier"),
871
                    let rawClass = stringValue(device, key: "deviceClassRawValue"),
872
                    let deviceClass = ChargedDeviceClass(rawValue: rawClass)
873
                else {
874
                    return nil
875
                }
876

            
877
                let sessionObjects = relevantSessionObjects(
878
                    for: id.uuidString,
879
                    deviceClass: deviceClass,
880
                    sessionsByDeviceID: sessionsByDeviceID,
881
                    sessionsByChargerID: sessionsByChargerID
882
                )
883
                let sessionSummaries = sessionObjects
884
                    .compactMap { session in
885
                        makeSessionSummary(
886
                            from: session,
887
                            checkpoints: checkpointsBySessionID[stringValue(session, key: "id") ?? ""] ?? [],
888
                            samples: samplesBySessionID[stringValue(session, key: "id") ?? ""] ?? []
889
                        )
890
                    }
891
                    .sorted { lhs, rhs in
Bogdan Timofte authored a month ago
892
                        if lhs.status.isOpen && !rhs.status.isOpen {
Bogdan Timofte authored a month ago
893
                            return true
894
                        }
Bogdan Timofte authored a month ago
895
                        if !lhs.status.isOpen && rhs.status.isOpen {
896
                            return false
897
                        }
898
                        if lhs.status == .active && rhs.status == .paused {
899
                            return true
900
                        }
901
                        if lhs.status == .paused && rhs.status == .active {
Bogdan Timofte authored a month ago
902
                            return false
903
                        }
904
                        return lhs.startedAt > rhs.startedAt
905
                    }
906

            
907
                return ChargedDeviceSummary(
908
                    id: id,
909
                    qrIdentifier: qrIdentifier,
910
                    name: name,
911
                    deviceClass: deviceClass,
912
                    supportsChargingWhileOff: boolValue(device, key: "supportsChargingWhileOff"),
Bogdan Timofte authored a month ago
913
                    chargingStateAvailability: chargingStateAvailability(for: device),
Bogdan Timofte authored a month ago
914
                    supportsWiredCharging: supportsWiredCharging(for: device),
915
                    supportsWirelessCharging: supportsWirelessCharging(for: device),
916
                    wirelessChargingProfile: wirelessChargingProfile(for: device),
Bogdan Timofte authored a month ago
917
                    configuredCompletionCurrents: decodedCompletionCurrents(from: device, key: "configuredCompletionCurrentsRawValue"),
918
                    learnedCompletionCurrents: decodedCompletionCurrents(from: device, key: "learnedCompletionCurrentsRawValue"),
Bogdan Timofte authored a month ago
919
                    wirelessChargerEfficiencyFactor: optionalDoubleValue(device, key: "wirelessChargerEfficiencyFactor"),
920
                    wiredChargeCompletionCurrentAmps: optionalDoubleValue(device, key: "wiredChargeCompletionCurrentAmps"),
921
                    wirelessChargeCompletionCurrentAmps: optionalDoubleValue(device, key: "wirelessChargeCompletionCurrentAmps"),
922
                    chargerObservedVoltageSelections: decodedObservedVoltageSelections(from: device),
923
                    chargerIdleCurrentAmps: optionalDoubleValue(device, key: "chargerIdleCurrentAmps"),
924
                    chargerEfficiencyFactor: optionalDoubleValue(device, key: "chargerEfficiencyFactor"),
925
                    chargerMaximumPowerWatts: optionalDoubleValue(device, key: "chargerMaximumPowerWatts"),
926
                    notes: stringValue(device, key: "notes"),
927
                    minimumCurrentAmps: optionalDoubleValue(device, key: "minimumCurrentAmps"),
928
                    estimatedBatteryCapacityWh: optionalDoubleValue(device, key: "estimatedBatteryCapacityWh"),
929
                    wiredMinimumCurrentAmps: optionalDoubleValue(device, key: "wiredMinimumCurrentAmps"),
930
                    wirelessMinimumCurrentAmps: optionalDoubleValue(device, key: "wirelessMinimumCurrentAmps"),
931
                    wiredEstimatedBatteryCapacityWh: optionalDoubleValue(device, key: "wiredEstimatedBatteryCapacityWh"),
932
                    wirelessEstimatedBatteryCapacityWh: optionalDoubleValue(device, key: "wirelessEstimatedBatteryCapacityWh"),
933
                    lastAssociatedMeterMAC: stringValue(device, key: "lastAssociatedMeterMAC"),
934
                    createdAt: dateValue(device, key: "createdAt") ?? .distantPast,
935
                    updatedAt: dateValue(device, key: "updatedAt") ?? .distantPast,
936
                    sessions: sessionSummaries,
937
                    capacityHistory: buildCapacityHistory(from: sessionSummaries),
Bogdan Timofte authored a month ago
938
                    typicalCurve: buildTypicalCurve(from: sessionSummaries),
939
                    standbyPowerMeasurements: []
Bogdan Timofte authored a month ago
940
                )
941
            }
942
            .sorted { lhs, rhs in
943
                if lhs.activeSession != nil && rhs.activeSession == nil {
944
                    return true
945
                }
946
                if lhs.activeSession == nil && rhs.activeSession != nil {
947
                    return false
948
                }
949
                if lhs.updatedAt != rhs.updatedAt {
950
                    return lhs.updatedAt > rhs.updatedAt
951
                }
952
                return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending
953
            }
954
        }
955

            
956
        return summaries
957
    }
958

            
959
    func resolvedChargedDeviceSummary(forMeterMACAddress meterMACAddress: String) -> ChargedDeviceSummary? {
960
        let normalizedMAC = normalizedMACAddress(meterMACAddress)
961
        guard !normalizedMAC.isEmpty else { return nil }
962

            
963
        let summaries = fetchChargedDeviceSummaries().filter { !$0.isCharger }
964

            
965
        if let activeMatch = summaries.first(where: { summary in
966
            summary.activeSession?.meterMACAddress == normalizedMAC
967
        }) {
968
            return activeMatch
969
        }
970

            
971
        return summaries.first(where: { $0.lastAssociatedMeterMAC == normalizedMAC })
972
    }
973

            
974
    func activeChargeSessionSummary(forMeterMACAddress meterMACAddress: String) -> ChargeSessionSummary? {
975
        let normalizedMAC = normalizedMACAddress(meterMACAddress)
976
        guard !normalizedMAC.isEmpty else { return nil }
977

            
Bogdan Timofte authored a month ago
978
        var summary: ChargeSessionSummary?
979

            
980
        context.performAndWait {
981
            guard let session = fetchActiveSessionObject(forMeterMACAddress: normalizedMAC),
982
                  let sessionID = stringValue(session, key: "id") else {
983
                return
984
            }
985

            
986
            summary = makeSessionSummary(
987
                from: session,
988
                checkpoints: fetchCheckpointObjects(forSessionID: sessionID),
989
                samples: fetchSessionSampleObjects(forSessionID: sessionID)
990
            )
991
        }
992

            
993
        return summary
Bogdan Timofte authored a month ago
994
    }
995

            
996
    private func createSessionObject(
997
        for chargedDevice: NSManagedObject,
998
        charger: NSManagedObject?,
999
        snapshot: ChargingMonitorSnapshot,
Bogdan Timofte authored a month ago
1000
        stopThreshold: Double?,
1001
        chargingTransportMode: ChargingTransportMode,
1002
        chargingStateMode: ChargingStateMode,
1003
        autoStopEnabled: Bool
Bogdan Timofte authored a month ago
1004
    ) -> NSManagedObject? {
1005
        guard
1006
            let entity = NSEntityDescription.entity(forEntityName: EntityName.chargeSession, in: context),
1007
            let chargedDeviceID = stringValue(chargedDevice, key: "id")
1008
        else {
1009
            return nil
1010
        }
1011

            
1012
        let session = NSManagedObject(entity: entity, insertInto: context)
1013
        let now = snapshot.observedAt
1014
        session.setValue(UUID().uuidString, forKey: "id")
1015
        session.setValue(chargedDeviceID, forKey: "chargedDeviceID")
1016
        session.setValue(charger.flatMap { stringValue($0, key: "id") }, forKey: "chargerID")
1017
        session.setValue(snapshot.meterMACAddress, forKey: "meterMACAddress")
1018
        session.setValue(snapshot.meterName, forKey: "meterName")
1019
        session.setValue(snapshot.meterModel, forKey: "meterModel")
1020
        session.setValue(now, forKey: "startedAt")
1021
        session.setValue(now, forKey: "lastObservedAt")
1022
        session.setValue(ChargeSessionStatus.active.rawValue, forKey: "statusRawValue")
Bogdan Timofte authored a month ago
1023
        let usesMeterCounters = snapshot.meterEnergyCounterWh != nil || snapshot.meterChargeCounterAh != nil
1024
        session.setValue(
1025
            (usesMeterCounters ? ChargeSessionSourceMode.offline : .live).rawValue,
1026
            forKey: "sourceModeRawValue"
1027
        )
Bogdan Timofte authored a month ago
1028
        session.setValue(chargingTransportMode.rawValue, forKey: "chargingTransportRawValue")
Bogdan Timofte authored a month ago
1029
        session.setValue(chargingStateMode.rawValue, forKey: "chargingStateRawValue")
1030
        session.setValue(autoStopEnabled, forKey: "autoStopEnabled")
1031
        session.setValue(stopThreshold ?? 0, forKey: "stopThresholdAmps")
Bogdan Timofte authored a month ago
1032
        session.setValue(snapshot.voltageVolts, forKey: "selectedSourceVoltageVolts")
1033
        session.setValue(snapshot.currentAmps, forKey: "lastObservedCurrentAmps")
1034
        session.setValue(snapshot.powerWatts, forKey: "lastObservedPowerWatts")
1035
        session.setValue(
1036
            chargingTransportMode == .wired ? snapshot.voltageVolts : nil,
1037
            forKey: "lastObservedVoltageVolts"
1038
        )
Bogdan Timofte authored a month ago
1039
        session.setValue(
1040
            hasObservedChargeFlow(
1041
                currentAmps: snapshot.currentAmps,
1042
                chargingTransportMode: chargingTransportMode,
1043
                charger: charger,
1044
                stopThreshold: stopThreshold
1045
            ),
1046
            forKey: "hasObservedChargeFlow"
1047
        )
Bogdan Timofte authored a month ago
1048
        session.setValue(snapshot.currentAmps, forKey: "minimumObservedCurrentAmps")
1049
        session.setValue(snapshot.currentAmps, forKey: "maximumObservedCurrentAmps")
1050
        session.setValue(snapshot.powerWatts, forKey: "maximumObservedPowerWatts")
1051
        session.setValue(
1052
            chargingTransportMode == .wired ? snapshot.voltageVolts : nil,
1053
            forKey: "maximumObservedVoltageVolts"
1054
        )
1055
        session.setValue(boolValue(chargedDevice, key: "supportsChargingWhileOff"), forKey: "supportsChargingWhileOff")
1056
        if let selectedDataGroup = snapshot.selectedDataGroup {
1057
            session.setValue(Int16(selectedDataGroup), forKey: "selectedDataGroup")
1058
        }
1059
        if let meterEnergyCounterWh = snapshot.meterEnergyCounterWh {
1060
            session.setValue(meterEnergyCounterWh, forKey: "meterEnergyBaselineWh")
1061
            session.setValue(meterEnergyCounterWh, forKey: "meterLastEnergyWh")
1062
        }
1063
        if let meterChargeCounterAh = snapshot.meterChargeCounterAh {
1064
            session.setValue(meterChargeCounterAh, forKey: "meterChargeBaselineAh")
1065
            session.setValue(meterChargeCounterAh, forKey: "meterLastChargeAh")
1066
        }
Bogdan Timofte authored a month ago
1067
        if let meterRecordingDurationSeconds = snapshot.meterRecordingDurationSeconds {
1068
            setValue(meterRecordingDurationSeconds, on: session, key: "meterDurationBaselineSeconds")
1069
            setValue(meterRecordingDurationSeconds, on: session, key: "meterLastDurationSeconds")
1070
        }
Bogdan Timofte authored a month ago
1071
        session.setValue(now, forKey: "createdAt")
1072
        session.setValue(now, forKey: "updatedAt")
1073

            
1074
        chargedDevice.setValue(snapshot.meterMACAddress, forKey: "lastAssociatedMeterMAC")
1075
        chargedDevice.setValue(now, forKey: "updatedAt")
1076
        return session
1077
    }
1078

            
1079
    private func update(
1080
        session: NSManagedObject,
1081
        with snapshot: ChargingMonitorSnapshot,
Bogdan Timofte authored a month ago
1082
        stopThreshold: Double?,
1083
        charger: NSManagedObject?
Bogdan Timofte authored a month ago
1084
    ) {
1085
        let sessionChargingTransportMode = chargingTransportMode(for: session)
1086
        let lastObservedAt = dateValue(session, key: "lastObservedAt")
1087
        let previousPower = doubleValue(session, key: "lastObservedPowerWatts")
1088
        let previousCurrent = doubleValue(session, key: "lastObservedCurrentAmps")
1089
        var measuredEnergyWh = doubleValue(session, key: "measuredEnergyWh")
1090
        var measuredChargeAh = doubleValue(session, key: "measuredChargeAh")
1091
        var sourceMode = ChargeSessionSourceMode(rawValue: stringValue(session, key: "sourceModeRawValue") ?? "") ?? .live
1092
        var usedOfflineMeterCounters = boolValue(session, key: "usedOfflineMeterCounters")
1093

            
1094
        if let lastObservedAt {
1095
            let deltaSeconds = max(snapshot.observedAt.timeIntervalSince(lastObservedAt), 0)
1096
            if deltaSeconds > 0, deltaSeconds <= maximumLiveIntegrationGap {
1097
                measuredEnergyWh += max(previousPower, 0) * deltaSeconds / 3600
1098
                measuredChargeAh += max(previousCurrent, 0) * deltaSeconds / 3600
1099
                if sourceMode == .offline {
1100
                    sourceMode = .blended
1101
                }
1102
            }
1103
        }
1104

            
1105
        if let counterGroup = snapshot.selectedDataGroup,
1106
           let storedGroup = optionalInt16Value(session, key: "selectedDataGroup"),
1107
           UInt8(storedGroup) != counterGroup {
1108
            session.setValue(Int16(counterGroup), forKey: "selectedDataGroup")
1109
            session.setValue(snapshot.meterEnergyCounterWh, forKey: "meterEnergyBaselineWh")
1110
            session.setValue(snapshot.meterChargeCounterAh, forKey: "meterChargeBaselineAh")
1111
        }
1112

            
1113
        if let meterEnergyCounterWh = snapshot.meterEnergyCounterWh {
1114
            let baselineEnergy = optionalDoubleValue(session, key: "meterEnergyBaselineWh") ?? meterEnergyCounterWh
1115
            let lastEnergy = optionalDoubleValue(session, key: "meterLastEnergyWh")
1116
            if optionalDoubleValue(session, key: "meterEnergyBaselineWh") == nil {
1117
                session.setValue(baselineEnergy, forKey: "meterEnergyBaselineWh")
1118
            }
1119

            
1120
            if meterEnergyCounterWh + counterDecreaseTolerance >= baselineEnergy {
1121
                let offlineEnergy = meterEnergyCounterWh - baselineEnergy
Bogdan Timofte authored a month ago
1122
                measuredEnergyWh = max(offlineEnergy, 0)
Bogdan Timofte authored a month ago
1123
                usedOfflineMeterCounters = true
Bogdan Timofte authored a month ago
1124
                sourceMode = .offline
Bogdan Timofte authored a month ago
1125
            } else if let lastEnergy, meterEnergyCounterWh > lastEnergy {
1126
                let delta = meterEnergyCounterWh - lastEnergy
1127
                if delta > 0 {
1128
                    measuredEnergyWh += delta
1129
                    usedOfflineMeterCounters = true
1130
                    sourceMode = .blended
1131
                }
1132
            }
1133
            session.setValue(meterEnergyCounterWh, forKey: "meterLastEnergyWh")
1134
        }
1135

            
1136
        if let meterChargeCounterAh = snapshot.meterChargeCounterAh {
1137
            let baselineCharge = optionalDoubleValue(session, key: "meterChargeBaselineAh") ?? meterChargeCounterAh
1138
            let lastCharge = optionalDoubleValue(session, key: "meterLastChargeAh")
1139
            if optionalDoubleValue(session, key: "meterChargeBaselineAh") == nil {
1140
                session.setValue(baselineCharge, forKey: "meterChargeBaselineAh")
1141
            }
1142

            
1143
            if meterChargeCounterAh + counterDecreaseTolerance >= baselineCharge {
1144
                let offlineCharge = meterChargeCounterAh - baselineCharge
Bogdan Timofte authored a month ago
1145
                measuredChargeAh = max(offlineCharge, 0)
Bogdan Timofte authored a month ago
1146
                usedOfflineMeterCounters = true
1147
            } else if let lastCharge, meterChargeCounterAh > lastCharge {
1148
                let delta = meterChargeCounterAh - lastCharge
1149
                if delta > 0 {
1150
                    measuredChargeAh += delta
1151
                    usedOfflineMeterCounters = true
1152
                }
1153
            }
1154
            session.setValue(meterChargeCounterAh, forKey: "meterLastChargeAh")
1155
        }
1156

            
Bogdan Timofte authored a month ago
1157
        if let meterRecordingDurationSeconds = snapshot.meterRecordingDurationSeconds {
1158
            let baselineDuration = optionalDoubleValue(session, key: "meterDurationBaselineSeconds") ?? meterRecordingDurationSeconds
1159
            if optionalDoubleValue(session, key: "meterDurationBaselineSeconds") == nil {
1160
                setValue(baselineDuration, on: session, key: "meterDurationBaselineSeconds")
1161
            }
1162
            setValue(meterRecordingDurationSeconds, on: session, key: "meterLastDurationSeconds")
1163
        }
1164

            
Bogdan Timofte authored a month ago
1165
        let existingMinimum = optionalDoubleValue(session, key: "minimumObservedCurrentAmps")
1166
        let updatedMinimum: Double
1167
        if snapshot.currentAmps > 0 {
1168
            updatedMinimum = min(existingMinimum ?? snapshot.currentAmps, snapshot.currentAmps)
1169
        } else {
1170
            updatedMinimum = existingMinimum ?? 0
1171
        }
1172

            
Bogdan Timofte authored a month ago
1173
        let effectiveCurrent = effectiveCurrentAmps(
1174
            fromMeasuredCurrent: snapshot.currentAmps,
1175
            chargingTransportMode: sessionChargingTransportMode,
1176
            charger: charger
1177
        )
1178
        let observedChargeFlow = boolValue(session, key: "hasObservedChargeFlow")
1179
            || hasObservedChargeFlow(
1180
                currentAmps: snapshot.currentAmps,
1181
                chargingTransportMode: sessionChargingTransportMode,
1182
                charger: charger,
1183
                stopThreshold: stopThreshold
1184
            )
1185

            
Bogdan Timofte authored a month ago
1186
        session.setValue(measuredEnergyWh, forKey: "measuredEnergyWh")
1187
        session.setValue(measuredChargeAh, forKey: "measuredChargeAh")
1188
        session.setValue(updatedMinimum, forKey: "minimumObservedCurrentAmps")
Bogdan Timofte authored a month ago
1189
        session.setValue(stopThreshold ?? 0, forKey: "stopThresholdAmps")
Bogdan Timofte authored a month ago
1190
        session.setValue(snapshot.observedAt, forKey: "lastObservedAt")
1191
        session.setValue(snapshot.currentAmps, forKey: "lastObservedCurrentAmps")
1192
        session.setValue(snapshot.powerWatts, forKey: "lastObservedPowerWatts")
1193
        session.setValue(
1194
            sessionChargingTransportMode == .wired ? snapshot.voltageVolts : nil,
1195
            forKey: "lastObservedVoltageVolts"
1196
        )
Bogdan Timofte authored a month ago
1197
        session.setValue(observedChargeFlow, forKey: "hasObservedChargeFlow")
Bogdan Timofte authored a month ago
1198
        session.setValue(
1199
            max(optionalDoubleValue(session, key: "maximumObservedCurrentAmps") ?? snapshot.currentAmps, snapshot.currentAmps),
1200
            forKey: "maximumObservedCurrentAmps"
1201
        )
1202
        session.setValue(
1203
            max(optionalDoubleValue(session, key: "maximumObservedPowerWatts") ?? snapshot.powerWatts, snapshot.powerWatts),
1204
            forKey: "maximumObservedPowerWatts"
1205
        )
1206
        session.setValue(
1207
            sessionChargingTransportMode == .wired
1208
                ? max(optionalDoubleValue(session, key: "maximumObservedVoltageVolts") ?? snapshot.voltageVolts, snapshot.voltageVolts)
1209
                : nil,
1210
            forKey: "maximumObservedVoltageVolts"
1211
        )
1212
        session.setValue(usedOfflineMeterCounters, forKey: "usedOfflineMeterCounters")
1213
        session.setValue(sourceMode.rawValue, forKey: "sourceModeRawValue")
1214
        maybeTriggerTargetBatteryAlert(for: session, observedAt: snapshot.observedAt)
1215

            
Bogdan Timofte authored a month ago
1216
        guard boolValue(session, key: "autoStopEnabled"), let stopThreshold, stopThreshold > 0, observedChargeFlow else {
1217
            session.setValue(nil, forKey: "belowThresholdSince")
1218
            clearCompletionConfirmationState(for: session)
1219
            session.setValue(nil, forKey: "completionConfirmationCooldownUntil")
1220
            return
1221
        }
1222

            
1223
        if effectiveCurrent <= stopThreshold {
Bogdan Timofte authored a month ago
1224
            let belowThresholdSince = dateValue(session, key: "belowThresholdSince") ?? snapshot.observedAt
1225
            session.setValue(belowThresholdSince, forKey: "belowThresholdSince")
1226
            if snapshot.observedAt.timeIntervalSince(belowThresholdSince) >= stopDetectionHoldDuration {
1227
                if boolValue(session, key: "requiresCompletionConfirmation") {
1228
                    // Leave the session active until the user explicitly confirms or charging resumes.
1229
                    return
1230
                }
1231

            
1232
                if shouldRequireCompletionConfirmation(for: session, observedAt: snapshot.observedAt) {
1233
                    requestCompletionConfirmation(for: session, observedAt: snapshot.observedAt)
1234
                } else {
Bogdan Timofte authored a month ago
1235
                    finishSession(
1236
                        session,
1237
                        observedAt: snapshot.observedAt,
1238
                        finalBatteryPercent: nil,
1239
                        label: nil,
1240
                        status: .completed
1241
                    )
Bogdan Timofte authored a month ago
1242
                }
1243
            }
1244
        } else {
1245
            session.setValue(nil, forKey: "belowThresholdSince")
1246
            clearCompletionConfirmationState(for: session)
1247
            session.setValue(nil, forKey: "completionConfirmationCooldownUntil")
1248
        }
1249
    }
1250

            
1251
    private func updateAggregatedSample(
1252
        session: NSManagedObject,
1253
        with snapshot: ChargingMonitorSnapshot
Bogdan Timofte authored a month ago
1254
    ) -> NSManagedObject? {
Bogdan Timofte authored a month ago
1255
        guard
1256
            let sessionID = stringValue(session, key: "id"),
1257
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
1258
            let startedAt = dateValue(session, key: "startedAt"),
1259
            let entity = NSEntityDescription.entity(forEntityName: EntityName.chargeSessionSample, in: context)
1260
        else {
Bogdan Timofte authored a month ago
1261
            return nil
Bogdan Timofte authored a month ago
1262
        }
1263

            
1264
        let elapsed = max(snapshot.observedAt.timeIntervalSince(startedAt), 0)
1265
        let bucketIndex = Int32(floor(elapsed / Self.aggregatedSampleBucketDuration))
1266
        let bucketStart = startedAt.addingTimeInterval(Double(bucketIndex) * Self.aggregatedSampleBucketDuration)
1267
        let bucketIdentifier = "\(sessionID)-\(bucketIndex)"
1268
        let sample = fetchSessionSampleObject(sessionID: sessionID, bucketIndex: bucketIndex)
1269
            ?? NSManagedObject(entity: entity, insertInto: context)
1270
        let sessionChargingTransportMode = chargingTransportMode(for: session)
1271
        let sampleVoltage = sessionChargingTransportMode == .wired ? snapshot.voltageVolts : nil
1272

            
1273
        let existingCount = max(optionalInt16Value(sample, key: "sampleCount") ?? 0, 0)
1274
        let updatedCount = existingCount + 1
1275

            
1276
        sample.setValue(bucketIdentifier, forKey: "id")
1277
        sample.setValue(sessionID, forKey: "sessionID")
1278
        sample.setValue(chargedDeviceID, forKey: "chargedDeviceID")
1279
        sample.setValue(bucketIndex, forKey: "bucketIndex")
1280
        sample.setValue(max(snapshot.observedAt, bucketStart), forKey: "timestamp")
1281
        sample.setValue(
1282
            runningAverage(
1283
                currentAverage: optionalDoubleValue(sample, key: "averageCurrentAmps") ?? snapshot.currentAmps,
1284
                currentCount: Int(existingCount),
1285
                newValue: snapshot.currentAmps
1286
            ),
1287
            forKey: "averageCurrentAmps"
1288
        )
1289
        sample.setValue(
1290
            sampleVoltage.flatMap { voltage in
1291
                runningAverage(
1292
                    currentAverage: optionalDoubleValue(sample, key: "averageVoltageVolts") ?? voltage,
1293
                    currentCount: Int(existingCount),
1294
                    newValue: voltage
1295
                )
1296
            },
1297
            forKey: "averageVoltageVolts"
1298
        )
1299
        sample.setValue(
1300
            runningAverage(
1301
                currentAverage: optionalDoubleValue(sample, key: "averagePowerWatts") ?? snapshot.powerWatts,
1302
                currentCount: Int(existingCount),
1303
                newValue: snapshot.powerWatts
1304
            ),
1305
            forKey: "averagePowerWatts"
1306
        )
1307
        sample.setValue(doubleValue(session, key: "measuredEnergyWh"), forKey: "measuredEnergyWh")
1308
        sample.setValue(doubleValue(session, key: "measuredChargeAh"), forKey: "measuredChargeAh")
1309
        sample.setValue(Int16(updatedCount), forKey: "sampleCount")
1310
        sample.setValue(dateValue(sample, key: "createdAt") ?? snapshot.observedAt, forKey: "createdAt")
1311
        sample.setValue(snapshot.observedAt, forKey: "updatedAt")
Bogdan Timofte authored a month ago
1312
        return sample
Bogdan Timofte authored a month ago
1313
    }
1314

            
1315
    private func maybeTriggerTargetBatteryAlert(for session: NSManagedObject, observedAt: Date) {
1316
        guard dateValue(session, key: "targetBatteryAlertTriggeredAt") == nil else {
1317
            return
1318
        }
1319

            
1320
        guard let targetBatteryPercent = optionalDoubleValue(session, key: "targetBatteryPercent") else {
1321
            return
1322
        }
1323

            
1324
        let predictedBatteryPercent = predictedBatteryPercent(for: session)
1325
            ?? optionalDoubleValue(session, key: "endBatteryPercent")
1326

            
1327
        guard let predictedBatteryPercent, predictedBatteryPercent >= targetBatteryPercent else {
1328
            return
1329
        }
1330

            
1331
        session.setValue(observedAt, forKey: "targetBatteryAlertTriggeredAt")
1332
    }
1333

            
1334
    private func shouldRequireCompletionConfirmation(
1335
        for session: NSManagedObject,
1336
        observedAt: Date
1337
    ) -> Bool {
1338
        if let cooldownUntil = dateValue(session, key: "completionConfirmationCooldownUntil"),
1339
           cooldownUntil > observedAt {
1340
            return false
1341
        }
1342

            
1343
        guard let predictedBatteryPercent = predictedBatteryPercent(for: session) else {
1344
            return false
1345
        }
1346

            
1347
        let expectedCompletionPercent = optionalDoubleValue(session, key: "targetBatteryPercent")
1348
            ?? defaultCompletionPercentThreshold
1349

            
1350
        return predictedBatteryPercent + completionContradictionTolerancePercent < expectedCompletionPercent
1351
    }
1352

            
1353
    private func requestCompletionConfirmation(for session: NSManagedObject, observedAt: Date) {
1354
        guard !boolValue(session, key: "requiresCompletionConfirmation") else {
1355
            return
1356
        }
1357

            
1358
        session.setValue(true, forKey: "requiresCompletionConfirmation")
1359
        session.setValue(observedAt, forKey: "completionConfirmationRequestedAt")
1360
        session.setValue(predictedBatteryPercent(for: session), forKey: "completionContradictionPercent")
1361
    }
1362

            
1363
    private func clearCompletionConfirmationState(for session: NSManagedObject) {
1364
        session.setValue(false, forKey: "requiresCompletionConfirmation")
1365
        session.setValue(nil, forKey: "completionConfirmationRequestedAt")
1366
        session.setValue(nil, forKey: "completionContradictionPercent")
1367
    }
1368

            
Bogdan Timofte authored a month ago
1369
    private func snapshotDateForManualStop(_ session: NSManagedObject) -> Date {
1370
        if statusValue(session, key: "statusRawValue") == .paused {
1371
            return dateValue(session, key: "pausedAt")
1372
                ?? dateValue(session, key: "lastObservedAt")
1373
                ?? Date()
1374
        }
1375
        return dateValue(session, key: "lastObservedAt") ?? Date()
1376
    }
1377

            
1378
    @discardableResult
1379
    private func maybeCompletePausedSession(_ session: NSManagedObject, observedAt: Date) -> Bool {
1380
        guard statusValue(session, key: "statusRawValue") == .paused else {
1381
            return false
1382
        }
1383

            
1384
        guard let pausedAt = dateValue(session, key: "pausedAt"),
1385
              observedAt.timeIntervalSince(pausedAt) >= pausedSessionTimeout else {
1386
            return false
1387
        }
1388

            
1389
        finishSession(
1390
            session,
1391
            observedAt: pausedAt.addingTimeInterval(pausedSessionTimeout),
1392
            finalBatteryPercent: nil,
1393
            label: nil,
1394
            status: .completed
1395
        )
1396

            
1397
        guard saveContext() else {
1398
            return false
1399
        }
1400

            
1401
        if let chargedDeviceID = stringValue(session, key: "chargedDeviceID") {
1402
            refreshDerivedMetrics(forChargedDeviceID: chargedDeviceID)
1403
            return saveContext()
1404
        }
1405

            
1406
        return true
1407
    }
1408

            
1409
    private func completionCurrentForSessionEnd(_ session: NSManagedObject) -> Double? {
1410
        let chargingTransportMode = chargingTransportMode(for: session)
1411
        let measuredCurrent = optionalDoubleValue(session, key: "lastObservedCurrentAmps")
1412
            ?? doubleValue(session, key: "lastObservedCurrentAmps")
1413

            
1414
        guard measuredCurrent > 0 else {
1415
            return nil
1416
        }
1417

            
1418
        let charger = chargingTransportMode == .wireless
1419
            ? stringValue(session, key: "chargerID").flatMap(fetchChargedDeviceObject(id:))
1420
            : nil
1421

            
1422
        if chargingTransportMode == .wireless, chargerIdleCurrent(for: charger) == nil {
1423
            return nil
1424
        }
1425

            
1426
        let effectiveCurrent = effectiveCurrentAmps(
1427
            fromMeasuredCurrent: measuredCurrent,
1428
            chargingTransportMode: chargingTransportMode,
1429
            charger: charger
1430
        )
1431
        guard effectiveCurrent > 0 else {
1432
            return nil
1433
        }
1434
        return effectiveCurrent
1435
    }
1436

            
1437
    private func finishSession(
1438
        _ session: NSManagedObject,
1439
        observedAt: Date,
1440
        finalBatteryPercent: Double?,
1441
        label: String?,
1442
        status: ChargeSessionStatus
1443
    ) {
1444
        if let finalBatteryPercent {
1445
            _ = insertBatteryCheckpoint(
1446
                percent: finalBatteryPercent,
1447
                label: label,
1448
                timestamp: observedAt,
1449
                to: session
1450
            )
1451
        }
1452

            
1453
        session.setValue(status.rawValue, forKey: "statusRawValue")
1454
        session.setValue(nil, forKey: "pausedAt")
1455
        session.setValue(nil, forKey: "belowThresholdSince")
1456
        session.setValue(observedAt, forKey: "endedAt")
1457
        session.setValue(observedAt, forKey: "lastObservedAt")
1458
        session.setValue(completionCurrentForSessionEnd(session), forKey: "completionCurrentAmps")
1459
        clearCompletionConfirmationState(for: session)
1460
        session.setValue(nil, forKey: "completionConfirmationCooldownUntil")
1461
        updateCapacityEstimate(for: session)
1462
        session.setValue(observedAt, forKey: "updatedAt")
1463
    }
1464

            
Bogdan Timofte authored a month ago
1465
    private func predictedBatteryPercent(for session: NSManagedObject) -> Double? {
1466
        guard
1467
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
1468
            let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID),
1469
            let estimatedCapacityWh = resolvedEstimatedBatteryCapacityWh(for: session, chargedDevice: chargedDevice),
1470
            estimatedCapacityWh > 0
1471
        else {
1472
            return nil
1473
        }
1474

            
1475
        let measuredEnergyWh = optionalDoubleValue(session, key: "effectiveBatteryEnergyWh")
1476
            ?? doubleValue(session, key: "measuredEnergyWh")
1477
        let sessionID = stringValue(session, key: "id") ?? ""
1478

            
1479
        struct Anchor {
1480
            let percent: Double
1481
            let energyWh: Double
Bogdan Timofte authored a month ago
1482
            let timestamp: Date
1483
            let isCheckpoint: Bool
Bogdan Timofte authored a month ago
1484
        }
1485

            
1486
        var anchors: [Anchor] = []
Bogdan Timofte authored a month ago
1487
        if let startBatteryPercent = optionalDoubleValue(session, key: "startBatteryPercent"),
1488
           startBatteryPercent >= 0 {
1489
            anchors.append(
1490
                Anchor(
1491
                    percent: startBatteryPercent,
1492
                    energyWh: 0,
1493
                    timestamp: dateValue(session, key: "startedAt") ?? Date.distantPast,
1494
                    isCheckpoint: false
1495
                )
1496
            )
Bogdan Timofte authored a month ago
1497
        }
1498

            
1499
        let checkpointAnchors = fetchCheckpointObjects(forSessionID: sessionID)
1500
            .compactMap(makeCheckpointSummary(from:))
1501
            .sorted { lhs, rhs in
1502
                if lhs.measuredEnergyWh != rhs.measuredEnergyWh {
1503
                    return lhs.measuredEnergyWh < rhs.measuredEnergyWh
1504
                }
1505
                return lhs.timestamp < rhs.timestamp
1506
            }
Bogdan Timofte authored a month ago
1507
            .filter { $0.batteryPercent >= 0 }
1508
            .map {
1509
                Anchor(
1510
                    percent: $0.batteryPercent,
1511
                    energyWh: $0.measuredEnergyWh,
1512
                    timestamp: $0.timestamp,
1513
                    isCheckpoint: true
1514
                )
1515
            }
Bogdan Timofte authored a month ago
1516
        anchors.append(contentsOf: checkpointAnchors)
1517

            
1518
        guard !anchors.isEmpty else {
1519
            return optionalDoubleValue(session, key: "endBatteryPercent")
1520
        }
1521

            
1522
        let anchor = anchors.filter { $0.energyWh <= measuredEnergyWh + 0.05 }.last ?? anchors.first!
Bogdan Timofte authored a month ago
1523
        return BatteryLevelPredictionTuning.predictedPercent(
1524
            anchorPercent: anchor.percent,
1525
            anchorEnergyWh: anchor.energyWh,
1526
            anchorTimestamp: anchor.timestamp,
1527
            anchorIsCheckpoint: anchor.isCheckpoint,
1528
            effectiveEnergyWh: measuredEnergyWh,
1529
            referenceTimestamp: dateValue(session, key: "lastObservedAt") ?? anchor.timestamp,
1530
            estimatedCapacityWh: estimatedCapacityWh
Bogdan Timofte authored a month ago
1531
        )
1532
    }
1533

            
1534
    private func resolvedEstimatedBatteryCapacityWh(
1535
        for session: NSManagedObject,
1536
        chargedDevice: NSManagedObject
1537
    ) -> Double? {
1538
        if let sessionCapacityEstimate = optionalDoubleValue(session, key: "capacityEstimateWh"),
1539
           sessionCapacityEstimate > 0 {
1540
            return sessionCapacityEstimate
1541
        }
1542

            
1543
        switch chargingTransportMode(for: session) {
1544
        case .wired:
1545
            return optionalDoubleValue(chargedDevice, key: "wiredEstimatedBatteryCapacityWh")
1546
                ?? optionalDoubleValue(chargedDevice, key: "estimatedBatteryCapacityWh")
1547
        case .wireless:
1548
            return optionalDoubleValue(chargedDevice, key: "wirelessEstimatedBatteryCapacityWh")
1549
                ?? optionalDoubleValue(chargedDevice, key: "estimatedBatteryCapacityWh")
1550
        }
1551
    }
1552

            
1553
    private func updateCapacityEstimate(for session: NSManagedObject) {
1554
        guard
1555
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
1556
            let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID)
1557
        else {
1558
            session.setValue(nil, forKey: "effectiveBatteryEnergyWh")
1559
            session.setValue(nil, forKey: "capacityEstimateWh")
1560
            return
1561
        }
1562

            
1563
        let measuredEnergyWh = doubleValue(session, key: "measuredEnergyWh")
1564
        let chargingMode = chargingTransportMode(for: session)
1565
        let wirelessResolution = chargingMode == .wireless
1566
            ? resolvedWirelessEfficiency(for: session, chargedDevice: chargedDevice)
1567
            : nil
1568
        let effectiveBatteryEnergyWh = chargingMode == .wired
1569
            ? measuredEnergyWh
1570
            : wirelessResolution.map { measuredEnergyWh * $0.factor }
1571

            
1572
        session.setValue(effectiveBatteryEnergyWh, forKey: "effectiveBatteryEnergyWh")
1573
        session.setValue(wirelessResolution?.factor, forKey: "wirelessEfficiencyFactor")
1574
        session.setValue(wirelessResolution?.usesEstimated ?? false, forKey: "usesEstimatedWirelessEfficiency")
1575
        session.setValue(wirelessResolution?.shouldWarn ?? false, forKey: "shouldWarnAboutLowWirelessEfficiency")
1576

            
1577
        guard
1578
            let startBatteryPercent = optionalDoubleValue(session, key: "startBatteryPercent"),
1579
            let endBatteryPercent = optionalDoubleValue(session, key: "endBatteryPercent")
1580
        else {
1581
            session.setValue(nil, forKey: "capacityEstimateWh")
1582
            return
1583
        }
1584

            
Bogdan Timofte authored a month ago
1585
        guard startBatteryPercent >= 0, endBatteryPercent >= 0 else {
1586
            session.setValue(nil, forKey: "capacityEstimateWh")
1587
            return
1588
        }
1589

            
Bogdan Timofte authored a month ago
1590
        let percentDelta = endBatteryPercent - startBatteryPercent
1591
        let supportsChargingWhileOff = boolValue(chargedDevice, key: "supportsChargingWhileOff")
1592

            
1593
        guard percentDelta >= 20, let effectiveBatteryEnergyWh, effectiveBatteryEnergyWh > 0 else {
1594
            session.setValue(nil, forKey: "capacityEstimateWh")
1595
            return
1596
        }
1597

            
1598
        if !supportsChargingWhileOff && endBatteryPercent >= 99.5 {
1599
            session.setValue(nil, forKey: "capacityEstimateWh")
1600
            return
1601
        }
1602

            
1603
        let capacityEstimateWh = effectiveBatteryEnergyWh / (percentDelta / 100)
1604
        session.setValue(capacityEstimateWh, forKey: "capacityEstimateWh")
1605
    }
1606

            
1607
    @discardableResult
Bogdan Timofte authored a month ago
1608
    private func insertBatteryCheckpoint(
Bogdan Timofte authored a month ago
1609
        percent: Double,
1610
        label: String?,
Bogdan Timofte authored a month ago
1611
        timestamp: Date = Date(),
Bogdan Timofte authored a month ago
1612
        measuredEnergyWhOverride: Double? = nil,
1613
        measuredChargeAhOverride: Double? = nil,
Bogdan Timofte authored a month ago
1614
        to session: NSManagedObject
Bogdan Timofte authored a month ago
1615
    ) -> String? {
Bogdan Timofte authored a month ago
1616
        guard
1617
            let sessionID = stringValue(session, key: "id"),
1618
            let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
1619
            let entity = NSEntityDescription.entity(forEntityName: EntityName.chargeCheckpoint, in: context)
1620
        else {
Bogdan Timofte authored a month ago
1621
            return nil
Bogdan Timofte authored a month ago
1622
        }
1623

            
1624
        let checkpoint = NSManagedObject(entity: entity, insertInto: context)
Bogdan Timofte authored a month ago
1625
        let checkpointEnergyWh = measuredEnergyWhOverride
1626
            ?? optionalDoubleValue(session, key: "effectiveBatteryEnergyWh")
Bogdan Timofte authored a month ago
1627
            ?? doubleValue(session, key: "measuredEnergyWh")
Bogdan Timofte authored a month ago
1628
        let checkpointChargeAh = measuredChargeAhOverride
1629
            ?? doubleValue(session, key: "measuredChargeAh")
Bogdan Timofte authored a month ago
1630
        checkpoint.setValue(UUID().uuidString, forKey: "id")
1631
        checkpoint.setValue(sessionID, forKey: "sessionID")
1632
        checkpoint.setValue(chargedDeviceID, forKey: "chargedDeviceID")
Bogdan Timofte authored a month ago
1633
        checkpoint.setValue(timestamp, forKey: "timestamp")
Bogdan Timofte authored a month ago
1634
        checkpoint.setValue(percent, forKey: "batteryPercent")
1635
        checkpoint.setValue(checkpointEnergyWh, forKey: "measuredEnergyWh")
Bogdan Timofte authored a month ago
1636
        checkpoint.setValue(checkpointChargeAh, forKey: "measuredChargeAh")
Bogdan Timofte authored a month ago
1637
        checkpoint.setValue(doubleValue(session, key: "lastObservedCurrentAmps"), forKey: "currentAmps")
1638
        checkpoint.setValue(
1639
            chargingTransportMode(for: session) == .wired ? optionalDoubleValue(session, key: "lastObservedVoltageVolts") : nil,
1640
            forKey: "voltageVolts"
1641
        )
1642
        checkpoint.setValue(normalizedOptionalText(label), forKey: "label")
Bogdan Timofte authored a month ago
1643
        checkpoint.setValue(timestamp, forKey: "createdAt")
Bogdan Timofte authored a month ago
1644

            
Bogdan Timofte authored a month ago
1645
        let existingStartBatteryPercent = optionalDoubleValue(session, key: "startBatteryPercent")
1646
        if existingStartBatteryPercent == nil || ((existingStartBatteryPercent ?? 0) < 0 && percent > 0) {
Bogdan Timofte authored a month ago
1647
            session.setValue(percent, forKey: "startBatteryPercent")
1648
        }
Bogdan Timofte authored a month ago
1649
        if (existingStartBatteryPercent ?? 0) >= 0 || percent > 0 {
1650
            session.setValue(percent, forKey: "endBatteryPercent")
1651
        }
Bogdan Timofte authored a month ago
1652
        session.setValue(timestamp, forKey: "updatedAt")
Bogdan Timofte authored a month ago
1653
        updateCapacityEstimate(for: session)
1654

            
Bogdan Timofte authored a month ago
1655
        return chargedDeviceID
1656
    }
1657

            
Bogdan Timofte authored a month ago
1658
    private func refreshCheckpointDerivedValues(for session: NSManagedObject) {
1659
        guard let sessionID = stringValue(session, key: "id") else {
1660
            return
1661
        }
1662

            
1663
        let remainingCheckpoints = fetchCheckpointObjects(forSessionID: sessionID)
1664
        if let latestCheckpoint = remainingCheckpoints.last {
1665
            session.setValue(doubleValue(latestCheckpoint, key: "batteryPercent"), forKey: "endBatteryPercent")
1666
        } else if let startBatteryPercent = optionalDoubleValue(session, key: "startBatteryPercent"),
1667
                  startBatteryPercent >= 0 {
1668
            session.setValue(startBatteryPercent, forKey: "endBatteryPercent")
1669
        } else {
1670
            session.setValue(nil, forKey: "endBatteryPercent")
1671
        }
1672

            
1673
        session.setValue(Date(), forKey: "updatedAt")
1674
        updateCapacityEstimate(for: session)
1675
    }
1676

            
Bogdan Timofte authored a month ago
1677
    @discardableResult
1678
    private func addBatteryCheckpoint(
1679
        percent: Double,
1680
        label: String?,
Bogdan Timofte authored a month ago
1681
        measuredEnergyWh: Double? = nil,
1682
        measuredChargeAh: Double? = nil,
Bogdan Timofte authored a month ago
1683
        to session: NSManagedObject,
1684
        timestamp: Date = Date()
1685
    ) -> Bool {
Bogdan Timofte authored a month ago
1686
        if let measuredEnergyWh, measuredEnergyWh.isFinite {
1687
            session.setValue(max(measuredEnergyWh, 0), forKey: "measuredEnergyWh")
1688
        }
1689
        if let measuredChargeAh, measuredChargeAh.isFinite {
1690
            session.setValue(max(measuredChargeAh, 0), forKey: "measuredChargeAh")
1691
        }
1692

            
Bogdan Timofte authored a month ago
1693
        guard let chargedDeviceID = insertBatteryCheckpoint(
1694
            percent: percent,
1695
            label: label,
1696
            timestamp: timestamp,
Bogdan Timofte authored a month ago
1697
            measuredEnergyWhOverride: measuredEnergyWh,
1698
            measuredChargeAhOverride: measuredChargeAh,
Bogdan Timofte authored a month ago
1699
            to: session
1700
        ) else {
1701
            return false
1702
        }
1703

            
Bogdan Timofte authored a month ago
1704
        guard saveContext() else {
1705
            return false
1706
        }
1707

            
1708
        refreshDerivedMetrics(forChargedDeviceID: chargedDeviceID)
1709
        return saveContext()
1710
    }
1711

            
1712
    private func resolvedWirelessEfficiency(
1713
        for session: NSManagedObject,
1714
        chargedDevice: NSManagedObject
1715
    ) -> (factor: Double, usesEstimated: Bool, shouldWarn: Bool)? {
1716
        if let storedFactor = optionalDoubleValue(session, key: "wirelessEfficiencyFactor"),
1717
           storedFactor > 0 {
1718
            return (
1719
                factor: storedFactor,
1720
                usesEstimated: boolValue(session, key: "usesEstimatedWirelessEfficiency"),
1721
                shouldWarn: boolValue(session, key: "shouldWarnAboutLowWirelessEfficiency")
1722
            )
1723
        }
1724

            
1725
        let chargingProfile = wirelessChargingProfile(for: chargedDevice)
1726
        let measuredEnergyWh = doubleValue(session, key: "measuredEnergyWh")
1727
        guard measuredEnergyWh > 0 else {
1728
            return nil
1729
        }
1730

            
1731
        if chargingProfile == .magsafe,
1732
           let calibratedFactor = optionalDoubleValue(chargedDevice, key: "wirelessChargerEfficiencyFactor"),
1733
           calibratedFactor > 0 {
1734
            return (factor: calibratedFactor, usesEstimated: false, shouldWarn: false)
1735
        }
1736

            
1737
        guard
1738
            let startBatteryPercent = optionalDoubleValue(session, key: "startBatteryPercent"),
1739
            let endBatteryPercent = optionalDoubleValue(session, key: "endBatteryPercent")
1740
        else {
1741
            return nil
1742
        }
1743

            
1744
        let percentDelta = endBatteryPercent - startBatteryPercent
1745
        guard percentDelta >= 20 else {
1746
            return nil
1747
        }
1748

            
1749
        guard let wiredCapacityWh = optionalDoubleValue(chargedDevice, key: "wiredEstimatedBatteryCapacityWh")
Bogdan Timofte authored a month ago
1750
            ?? ((fallbackChargingTransportMode(for: chargedDevice) == .wired)
Bogdan Timofte authored a month ago
1751
                ? optionalDoubleValue(chargedDevice, key: "estimatedBatteryCapacityWh")
1752
                : nil),
1753
              wiredCapacityWh > 0
1754
        else {
1755
            return nil
1756
        }
1757

            
1758
        let deliveredBatteryEnergyWh = wiredCapacityWh * (percentDelta / 100)
1759
        let rawFactor = deliveredBatteryEnergyWh / measuredEnergyWh
1760
        let clampedFactor = min(max(rawFactor, minimumWirelessEfficiencyFactor), maximumWirelessEfficiencyFactor)
1761
        let usesEstimated = chargingProfile != .magsafe
1762
        let shouldWarn = usesEstimated && clampedFactor < lowWirelessEfficiencyThreshold
1763

            
1764
        return (factor: clampedFactor, usesEstimated: usesEstimated, shouldWarn: shouldWarn)
1765
    }
1766

            
1767
    private func refreshDerivedMetrics(forChargedDeviceID chargedDeviceID: String) {
1768
        guard let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID) else {
1769
            return
1770
        }
1771

            
1772
        let supportsChargingWhileOff = boolValue(chargedDevice, key: "supportsChargingWhileOff")
Bogdan Timofte authored a month ago
1773
        let chargingStateAvailability = chargingStateAvailability(for: chargedDevice)
Bogdan Timofte authored a month ago
1774
        let wirelessProfile = wirelessChargingProfile(for: chargedDevice)
1775
        let deviceClass = ChargedDeviceClass(rawValue: stringValue(chargedDevice, key: "deviceClassRawValue") ?? "") ?? .other
1776
        let sessions = relevantSessionObjects(
1777
            for: chargedDeviceID,
1778
            deviceClass: deviceClass,
1779
            sessionsByDeviceID: [chargedDeviceID: fetchSessions(forChargedDeviceID: chargedDeviceID)],
1780
            sessionsByChargerID: [chargedDeviceID: fetchSessions(forChargerID: chargedDeviceID)]
1781
        )
Bogdan Timofte authored a month ago
1782
        let learnedCompletionCurrents = derivedCompletionCurrents(from: sessions)
Bogdan Timofte authored a month ago
1783
        let wiredMinimumCurrent = derivedMinimumCurrent(
1784
            from: sessions,
1785
            chargingTransportMode: .wired
1786
        )
1787
        let wirelessMinimumCurrent = derivedMinimumCurrent(
1788
            from: sessions,
1789
            chargingTransportMode: .wireless
1790
        )
1791

            
1792
        let wiredCapacity = derivedCapacity(
1793
            from: sessions,
1794
            chargingTransportMode: .wired,
1795
            supportsChargingWhileOff: supportsChargingWhileOff
1796
        )
1797
        let wirelessCapacity = derivedCapacity(
1798
            from: sessions,
1799
            chargingTransportMode: .wireless,
1800
            supportsChargingWhileOff: supportsChargingWhileOff
1801
        )
1802
        let wirelessEfficiency = derivedWirelessEfficiency(
1803
            from: sessions,
1804
            chargingProfile: wirelessProfile
1805
        )
Bogdan Timofte authored a month ago
1806
        let configuredCompletionCurrents = decodedCompletionCurrents(
1807
            from: chargedDevice,
1808
            key: "configuredCompletionCurrentsRawValue"
1809
        )
Bogdan Timofte authored a month ago
1810
        let configuredWiredCompletionCurrent = optionalDoubleValue(chargedDevice, key: "wiredChargeCompletionCurrentAmps")
1811
        let configuredWirelessCompletionCurrent = optionalDoubleValue(chargedDevice, key: "wirelessChargeCompletionCurrentAmps")
1812
        let chargerObservedVoltages = deviceClass == .charger ? derivedObservedVoltageSelections(from: sessions) : []
1813
        let chargerIdleCurrent = deviceClass == .charger ? derivedIdleCurrent(from: sessions) : nil
1814
        let chargerEfficiency = deviceClass == .charger ? derivedChargerEfficiency(from: sessions) : nil
1815
        let chargerMaximumPower = deviceClass == .charger ? derivedMaximumPower(from: sessions) : nil
1816

            
Bogdan Timofte authored a month ago
1817
        let preferredChargingTransportMode = fallbackChargingTransportMode(for: chargedDevice)
Bogdan Timofte authored a month ago
1818
        let preferredChargingStateMode = chargingStateAvailability.supportedModes.first ?? .on
Bogdan Timofte authored a month ago
1819
        let preferredMinimumCurrent: Double?
1820
        let preferredCapacity: Double?
1821
        switch preferredChargingTransportMode {
1822
        case .wired:
Bogdan Timofte authored a month ago
1823
            preferredMinimumCurrent = configuredCompletionCurrents[
1824
                ChargeSessionKind(chargingTransportMode: .wired, chargingStateMode: preferredChargingStateMode)
1825
            ] ?? learnedCompletionCurrents[
1826
                ChargeSessionKind(chargingTransportMode: .wired, chargingStateMode: preferredChargingStateMode)
1827
            ] ?? configuredWiredCompletionCurrent ?? wiredMinimumCurrent ?? configuredWirelessCompletionCurrent ?? wirelessMinimumCurrent
Bogdan Timofte authored a month ago
1828
            preferredCapacity = wiredCapacity ?? wirelessCapacity
1829
        case .wireless:
Bogdan Timofte authored a month ago
1830
            preferredMinimumCurrent = configuredCompletionCurrents[
1831
                ChargeSessionKind(chargingTransportMode: .wireless, chargingStateMode: preferredChargingStateMode)
1832
            ] ?? learnedCompletionCurrents[
1833
                ChargeSessionKind(chargingTransportMode: .wireless, chargingStateMode: preferredChargingStateMode)
1834
            ] ?? configuredWirelessCompletionCurrent ?? wirelessMinimumCurrent ?? configuredWiredCompletionCurrent ?? wiredMinimumCurrent
Bogdan Timofte authored a month ago
1835
            preferredCapacity = wirelessCapacity ?? wiredCapacity
1836
        }
1837

            
Bogdan Timofte authored a month ago
1838
        setValue(wiredMinimumCurrent, on: chargedDevice, key: "wiredMinimumCurrentAmps")
1839
        setValue(wirelessMinimumCurrent, on: chargedDevice, key: "wirelessMinimumCurrentAmps")
1840
        setValue(encodedCompletionCurrents(learnedCompletionCurrents), on: chargedDevice, key: "learnedCompletionCurrentsRawValue")
1841
        setValue(wiredCapacity, on: chargedDevice, key: "wiredEstimatedBatteryCapacityWh")
1842
        setValue(wirelessCapacity, on: chargedDevice, key: "wirelessEstimatedBatteryCapacityWh")
1843
        setValue(wirelessEfficiency, on: chargedDevice, key: "wirelessChargerEfficiencyFactor")
1844
        setValue(encodedObservedVoltageSelections(chargerObservedVoltages), on: chargedDevice, key: "chargerObservedVoltageSelectionsRawValue")
1845
        setValue(chargerIdleCurrent, on: chargedDevice, key: "chargerIdleCurrentAmps")
1846
        setValue(chargerEfficiency, on: chargedDevice, key: "chargerEfficiencyFactor")
1847
        setValue(chargerMaximumPower, on: chargedDevice, key: "chargerMaximumPowerWatts")
1848
        setValue(preferredMinimumCurrent, on: chargedDevice, key: "minimumCurrentAmps")
1849
        setValue(preferredCapacity, on: chargedDevice, key: "estimatedBatteryCapacityWh")
1850
        setValue(Date(), on: chargedDevice, key: "updatedAt")
Bogdan Timofte authored a month ago
1851
    }
1852

            
1853
    private func buildCapacityHistory(from sessions: [ChargeSessionSummary]) -> [CapacityTrendPoint] {
1854
        sessions
1855
            .filter { $0.status == .completed }
1856
            .compactMap { session in
1857
                guard let capacityEstimateWh = session.capacityEstimateWh else { return nil }
1858
                let timestamp = session.endedAt ?? session.lastObservedAt
1859
                return CapacityTrendPoint(
1860
                    sessionID: session.id,
1861
                    timestamp: timestamp,
1862
                    capacityWh: capacityEstimateWh,
1863
                    chargingTransportMode: session.chargingTransportMode
1864
                )
1865
            }
1866
            .sorted { $0.timestamp < $1.timestamp }
1867
    }
1868

            
1869
    private func buildTypicalCurve(from sessions: [ChargeSessionSummary]) -> [TypicalChargeCurvePoint] {
1870
        var groupedEnergyByBin: [Int: [Double]] = [:]
1871
        var groupedChargeByBin: [Int: [Double]] = [:]
1872

            
1873
        for session in sessions where session.status == .completed {
1874
            var points = session.checkpoints
1875

            
1876
            if let startBatteryPercent = session.startBatteryPercent {
1877
                points.append(
1878
                    ChargeCheckpointSummary(
1879
                        id: UUID(),
1880
                        sessionID: session.id,
1881
                        chargedDeviceID: session.chargedDeviceID,
1882
                        timestamp: session.startedAt,
1883
                        batteryPercent: startBatteryPercent,
1884
                        measuredEnergyWh: 0,
1885
                        measuredChargeAh: 0,
1886
                        currentAmps: 0,
1887
                        voltageVolts: nil,
1888
                        label: "Start"
1889
                    )
1890
                )
1891
            }
1892

            
1893
            if let endBatteryPercent = session.endBatteryPercent {
1894
                points.append(
1895
                    ChargeCheckpointSummary(
1896
                        id: UUID(),
1897
                        sessionID: session.id,
1898
                        chargedDeviceID: session.chargedDeviceID,
1899
                        timestamp: session.endedAt ?? session.lastObservedAt,
1900
                        batteryPercent: endBatteryPercent,
1901
                        measuredEnergyWh: session.effectiveBatteryEnergyWh ?? session.measuredEnergyWh,
1902
                        measuredChargeAh: session.measuredChargeAh,
1903
                        currentAmps: 0,
1904
                        voltageVolts: nil,
1905
                        label: "End"
1906
                    )
1907
                )
1908
            }
1909

            
1910
            for point in points {
1911
                let percentBin = Int((point.batteryPercent / 10).rounded(.toNearestOrEven)) * 10
1912
                groupedEnergyByBin[percentBin, default: []].append(point.measuredEnergyWh)
1913
                groupedChargeByBin[percentBin, default: []].append(point.measuredChargeAh)
1914
            }
1915
        }
1916

            
1917
        return groupedEnergyByBin.keys.sorted().compactMap { percentBin in
1918
            guard
1919
                let energies = groupedEnergyByBin[percentBin],
1920
                let charges = groupedChargeByBin[percentBin],
1921
                !energies.isEmpty,
1922
                !charges.isEmpty
1923
            else {
1924
                return nil
1925
            }
1926

            
1927
            return TypicalChargeCurvePoint(
1928
                percentBin: percentBin,
1929
                averageEnergyWh: energies.reduce(0, +) / Double(energies.count),
1930
                averageChargeAh: charges.reduce(0, +) / Double(charges.count),
1931
                sampleCount: min(energies.count, charges.count)
1932
            )
1933
        }
1934
    }
1935

            
1936
    private func makeSessionSummary(
1937
        from object: NSManagedObject,
1938
        checkpoints: [NSManagedObject],
1939
        samples: [NSManagedObject]
1940
    ) -> ChargeSessionSummary? {
1941
        let chargingTransportMode = chargingTransportMode(for: object)
1942

            
1943
        guard
1944
            let id = uuidValue(object, key: "id"),
1945
            let chargedDeviceID = uuidValue(object, key: "chargedDeviceID"),
1946
            let startedAt = dateValue(object, key: "startedAt"),
1947
            let lastObservedAt = dateValue(object, key: "lastObservedAt"),
1948
            let status = statusValue(object, key: "statusRawValue"),
1949
            let sourceMode = ChargeSessionSourceMode(rawValue: stringValue(object, key: "sourceModeRawValue") ?? "")
1950
        else {
1951
            return nil
1952
        }
1953

            
1954
        let checkpointSummaries = checkpoints.compactMap(makeCheckpointSummary(from:))
1955
            .sorted { $0.timestamp < $1.timestamp }
1956
        let sampleSummaries = samples.compactMap(makeChargeSessionSampleSummary(from:))
1957
            .sorted { lhs, rhs in
1958
                if lhs.bucketIndex != rhs.bucketIndex {
1959
                    return lhs.bucketIndex < rhs.bucketIndex
1960
                }
1961
                return lhs.timestamp < rhs.timestamp
1962
            }
1963

            
1964
        return ChargeSessionSummary(
1965
            id: id,
1966
            chargedDeviceID: chargedDeviceID,
1967
            chargerID: uuidValue(object, key: "chargerID"),
1968
            meterMACAddress: stringValue(object, key: "meterMACAddress"),
1969
            meterName: stringValue(object, key: "meterName"),
1970
            meterModel: stringValue(object, key: "meterModel"),
1971
            startedAt: startedAt,
1972
            endedAt: dateValue(object, key: "endedAt"),
1973
            lastObservedAt: lastObservedAt,
Bogdan Timofte authored a month ago
1974
            pausedAt: dateValue(object, key: "pausedAt"),
Bogdan Timofte authored a month ago
1975
            status: status,
1976
            sourceMode: sourceMode,
1977
            chargingTransportMode: chargingTransportMode,
Bogdan Timofte authored a month ago
1978
            chargingStateMode: chargingStateMode(for: object),
1979
            autoStopEnabled: boolValue(object, key: "autoStopEnabled"),
Bogdan Timofte authored a month ago
1980
            measuredEnergyWh: doubleValue(object, key: "measuredEnergyWh"),
1981
            effectiveBatteryEnergyWh: optionalDoubleValue(object, key: "effectiveBatteryEnergyWh"),
1982
            measuredChargeAh: doubleValue(object, key: "measuredChargeAh"),
Bogdan Timofte authored a month ago
1983
            meterEnergyBaselineWh: optionalDoubleValue(object, key: "meterEnergyBaselineWh"),
1984
            meterChargeBaselineAh: optionalDoubleValue(object, key: "meterChargeBaselineAh"),
Bogdan Timofte authored a month ago
1985
            meterDurationBaselineSeconds: optionalDoubleValue(object, key: "meterDurationBaselineSeconds"),
1986
            meterLastDurationSeconds: optionalDoubleValue(object, key: "meterLastDurationSeconds"),
Bogdan Timofte authored a month ago
1987
            minimumObservedCurrentAmps: optionalDoubleValue(object, key: "minimumObservedCurrentAmps"),
1988
            maximumObservedCurrentAmps: optionalDoubleValue(object, key: "maximumObservedCurrentAmps"),
1989
            maximumObservedPowerWatts: optionalDoubleValue(object, key: "maximumObservedPowerWatts"),
1990
            maximumObservedVoltageVolts: chargingTransportMode == .wired
1991
                ? optionalDoubleValue(object, key: "maximumObservedVoltageVolts")
1992
                : nil,
1993
            selectedSourceVoltageVolts: optionalDoubleValue(object, key: "selectedSourceVoltageVolts"),
1994
            completionCurrentAmps: optionalDoubleValue(object, key: "completionCurrentAmps"),
1995
            stopThresholdAmps: doubleValue(object, key: "stopThresholdAmps"),
1996
            startBatteryPercent: optionalDoubleValue(object, key: "startBatteryPercent"),
1997
            endBatteryPercent: optionalDoubleValue(object, key: "endBatteryPercent"),
1998
            capacityEstimateWh: optionalDoubleValue(object, key: "capacityEstimateWh"),
1999
            wirelessEfficiencyFactor: optionalDoubleValue(object, key: "wirelessEfficiencyFactor"),
2000
            usesEstimatedWirelessEfficiency: boolValue(object, key: "usesEstimatedWirelessEfficiency"),
2001
            shouldWarnAboutLowWirelessEfficiency: boolValue(object, key: "shouldWarnAboutLowWirelessEfficiency"),
2002
            supportsChargingWhileOff: boolValue(object, key: "supportsChargingWhileOff"),
2003
            usedOfflineMeterCounters: boolValue(object, key: "usedOfflineMeterCounters"),
2004
            targetBatteryPercent: optionalDoubleValue(object, key: "targetBatteryPercent"),
2005
            targetBatteryAlertTriggeredAt: dateValue(object, key: "targetBatteryAlertTriggeredAt"),
2006
            requiresCompletionConfirmation: boolValue(object, key: "requiresCompletionConfirmation"),
2007
            completionConfirmationRequestedAt: dateValue(object, key: "completionConfirmationRequestedAt"),
2008
            completionContradictionPercent: optionalDoubleValue(object, key: "completionContradictionPercent"),
2009
            selectedDataGroup: optionalInt16Value(object, key: "selectedDataGroup").map(UInt8.init),
2010
            checkpoints: checkpointSummaries,
2011
            aggregatedSamples: sampleSummaries
2012
        )
2013
    }
2014

            
2015
    private func makeCheckpointSummary(from object: NSManagedObject) -> ChargeCheckpointSummary? {
2016
        guard
2017
            let id = uuidValue(object, key: "id"),
2018
            let sessionID = uuidValue(object, key: "sessionID"),
2019
            let chargedDeviceID = uuidValue(object, key: "chargedDeviceID"),
2020
            let timestamp = dateValue(object, key: "timestamp")
2021
        else {
2022
            return nil
2023
        }
2024

            
2025
        return ChargeCheckpointSummary(
2026
            id: id,
2027
            sessionID: sessionID,
2028
            chargedDeviceID: chargedDeviceID,
2029
            timestamp: timestamp,
2030
            batteryPercent: doubleValue(object, key: "batteryPercent"),
2031
            measuredEnergyWh: doubleValue(object, key: "measuredEnergyWh"),
2032
            measuredChargeAh: doubleValue(object, key: "measuredChargeAh"),
2033
            currentAmps: doubleValue(object, key: "currentAmps"),
2034
            voltageVolts: optionalDoubleValue(object, key: "voltageVolts"),
2035
            label: stringValue(object, key: "label")
2036
        )
2037
    }
2038

            
2039
    private func makeChargeSessionSampleSummary(from object: NSManagedObject) -> ChargeSessionSampleSummary? {
2040
        guard
2041
            let sessionID = uuidValue(object, key: "sessionID"),
2042
            let chargedDeviceID = uuidValue(object, key: "chargedDeviceID"),
2043
            let timestamp = dateValue(object, key: "timestamp")
2044
        else {
2045
            return nil
2046
        }
2047

            
2048
        return ChargeSessionSampleSummary(
2049
            sessionID: sessionID,
2050
            chargedDeviceID: chargedDeviceID,
2051
            bucketIndex: Int(optionalInt32Value(object, key: "bucketIndex") ?? 0),
2052
            timestamp: timestamp,
2053
            averageCurrentAmps: doubleValue(object, key: "averageCurrentAmps"),
2054
            averageVoltageVolts: optionalDoubleValue(object, key: "averageVoltageVolts"),
2055
            averagePowerWatts: doubleValue(object, key: "averagePowerWatts"),
2056
            measuredEnergyWh: doubleValue(object, key: "measuredEnergyWh"),
2057
            measuredChargeAh: doubleValue(object, key: "measuredChargeAh"),
2058
            sampleCount: Int(optionalInt16Value(object, key: "sampleCount") ?? 0)
2059
        )
2060
    }
2061

            
Bogdan Timofte authored a month ago
2062
    private func fetchOpenSessionObject(forMeterMACAddress meterMACAddress: String) -> NSManagedObject? {
Bogdan Timofte authored a month ago
2063
        fetchSessionObject(
2064
            predicate: NSPredicate(
Bogdan Timofte authored a month ago
2065
                format: "meterMACAddress == %@ AND (statusRawValue == %@ OR statusRawValue == %@)",
Bogdan Timofte authored a month ago
2066
                normalizedMACAddress(meterMACAddress),
Bogdan Timofte authored a month ago
2067
                ChargeSessionStatus.active.rawValue,
2068
                ChargeSessionStatus.paused.rawValue
Bogdan Timofte authored a month ago
2069
            )
2070
        )
2071
    }
2072

            
Bogdan Timofte authored a month ago
2073
    private func fetchActiveSessionObject(forMeterMACAddress meterMACAddress: String) -> NSManagedObject? {
Bogdan Timofte authored a month ago
2074
        fetchSessionObject(
2075
            predicate: NSPredicate(
Bogdan Timofte authored a month ago
2076
                format: "meterMACAddress == %@ AND statusRawValue == %@",
2077
                normalizedMACAddress(meterMACAddress),
2078
                ChargeSessionStatus.active.rawValue
Bogdan Timofte authored a month ago
2079
            )
2080
        )
2081
    }
2082

            
2083
    private func fetchSessionObject(predicate: NSPredicate) -> NSManagedObject? {
2084
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeSession)
2085
        request.predicate = predicate
2086
        request.fetchLimit = 1
2087
        request.sortDescriptors = [NSSortDescriptor(key: "startedAt", ascending: false)]
2088
        return (try? context.fetch(request))?.first
2089
    }
2090

            
2091
    private func fetchSessionObject(id: String) -> NSManagedObject? {
2092
        fetchSessionObject(
2093
            predicate: NSPredicate(format: "id == %@", id)
2094
        )
2095
    }
2096

            
2097
    private func fetchSessionSampleObject(sessionID: String, bucketIndex: Int32) -> NSManagedObject? {
2098
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeSessionSample)
2099
        request.predicate = NSPredicate(
2100
            format: "sessionID == %@ AND bucketIndex == %d",
2101
            sessionID,
2102
            bucketIndex
2103
        )
2104
        request.fetchLimit = 1
2105
        return (try? context.fetch(request))?.first
2106
    }
2107

            
2108
    private func fetchSessionSampleObjects(forSessionID sessionID: String) -> [NSManagedObject] {
2109
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeSessionSample)
2110
        request.predicate = NSPredicate(format: "sessionID == %@", sessionID)
2111
        return (try? context.fetch(request)) ?? []
2112
    }
2113

            
Bogdan Timofte authored a month ago
2114
    private func fetchCheckpointObject(id: String, sessionID: String) -> NSManagedObject? {
2115
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeCheckpoint)
2116
        request.predicate = NSPredicate(format: "id == %@ AND sessionID == %@", id, sessionID)
2117
        request.fetchLimit = 1
2118
        return (try? context.fetch(request))?.first
2119
    }
2120

            
Bogdan Timofte authored a month ago
2121
    private func fetchCheckpointObjects(forSessionID sessionID: String) -> [NSManagedObject] {
2122
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeCheckpoint)
2123
        request.predicate = NSPredicate(format: "sessionID == %@", sessionID)
2124
        request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)]
2125
        return (try? context.fetch(request)) ?? []
2126
    }
2127

            
2128
    private func fetchSessions(forChargedDeviceID chargedDeviceID: String) -> [NSManagedObject] {
2129
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeSession)
2130
        request.predicate = NSPredicate(format: "chargedDeviceID == %@", chargedDeviceID)
2131
        request.sortDescriptors = [NSSortDescriptor(key: "startedAt", ascending: true)]
2132
        return (try? context.fetch(request)) ?? []
2133
    }
2134

            
2135
    private func fetchSessions(forChargerID chargerID: String) -> [NSManagedObject] {
2136
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargeSession)
2137
        request.predicate = NSPredicate(format: "chargerID == %@", chargerID)
2138
        request.sortDescriptors = [NSSortDescriptor(key: "startedAt", ascending: true)]
2139
        return (try? context.fetch(request)) ?? []
2140
    }
2141

            
2142
    private func relevantSessionObjects(
2143
        for chargedDeviceID: String,
2144
        deviceClass: ChargedDeviceClass,
2145
        sessionsByDeviceID: [String: [NSManagedObject]],
2146
        sessionsByChargerID: [String: [NSManagedObject]]
2147
    ) -> [NSManagedObject] {
2148
        let directSessions = sessionsByDeviceID[chargedDeviceID] ?? []
2149
        guard deviceClass == .charger else {
2150
            return directSessions
2151
        }
2152

            
2153
        var seenSessionIDs = Set<String>()
2154
        return (directSessions + (sessionsByChargerID[chargedDeviceID] ?? []))
2155
            .filter { session in
2156
                let sessionID = stringValue(session, key: "id") ?? UUID().uuidString
2157
                return seenSessionIDs.insert(sessionID).inserted
2158
            }
2159
            .sorted {
2160
                let lhsDate = dateValue($0, key: "startedAt") ?? .distantPast
2161
                let rhsDate = dateValue($1, key: "startedAt") ?? .distantPast
2162
                return lhsDate < rhsDate
2163
            }
2164
    }
2165

            
2166
    private func resolvedDeviceObject(for meterMACAddress: String) -> NSManagedObject? {
2167
        resolvedAssignedObject(for: meterMACAddress, expectsChargerClass: false)
2168
    }
2169

            
2170
    private func resolvedChargerObject(for meterMACAddress: String) -> NSManagedObject? {
2171
        resolvedAssignedObject(for: meterMACAddress, expectsChargerClass: true)
2172
    }
2173

            
2174
    private func resolvedAssignedObject(
2175
        for meterMACAddress: String,
2176
        expectsChargerClass: Bool
2177
    ) -> NSManagedObject? {
2178
        let normalizedMAC = normalizedMACAddress(meterMACAddress)
2179
        guard !normalizedMAC.isEmpty else { return nil }
2180

            
2181
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargedDevice)
2182
        request.predicate = NSPredicate(format: "lastAssociatedMeterMAC == %@", normalizedMAC)
2183
        request.sortDescriptors = [NSSortDescriptor(key: "updatedAt", ascending: false)]
2184
        let matches = (try? context.fetch(request)) ?? []
2185
        return matches.first { object in
Bogdan Timofte authored a month ago
2186
            isChargerObject(object) == expectsChargerClass
Bogdan Timofte authored a month ago
2187
        }
2188
    }
2189

            
Bogdan Timofte authored a month ago
2190
    private func isChargerObject(_ object: NSManagedObject) -> Bool {
2191
        ChargedDeviceClass(rawValue: stringValue(object, key: "deviceClassRawValue") ?? "") == .charger
2192
    }
2193

            
Bogdan Timofte authored a month ago
2194
    private func fetchChargedDeviceObject(id: String) -> NSManagedObject? {
2195
        let request = NSFetchRequest<NSManagedObject>(entityName: EntityName.chargedDevice)
2196
        request.predicate = NSPredicate(format: "id == %@", id)
2197
        request.fetchLimit = 1
2198
        return (try? context.fetch(request))?.first
2199
    }
2200

            
2201
    private func fetchObjects(entityName: String) -> [NSManagedObject] {
2202
        let request = NSFetchRequest<NSManagedObject>(entityName: entityName)
2203
        return (try? context.fetch(request)) ?? []
2204
    }
2205

            
2206
    private func resolvedStopThreshold(
2207
        for chargedDevice: NSManagedObject,
2208
        chargingTransportMode: ChargingTransportMode,
Bogdan Timofte authored a month ago
2209
        chargingStateMode: ChargingStateMode,
2210
        charger: NSManagedObject?,
2211
        fallback: Double?
2212
    ) -> Double? {
2213
        if chargingTransportMode == .wireless, chargerIdleCurrent(for: charger) == nil {
2214
            return nil
2215
        }
2216

            
2217
        let sessionKind = ChargeSessionKind(
2218
            chargingTransportMode: chargingTransportMode,
2219
            chargingStateMode: chargingStateMode
2220
        )
2221
        let configuredCurrents = decodedCompletionCurrents(
2222
            from: chargedDevice,
2223
            key: "configuredCompletionCurrentsRawValue"
2224
        )
2225
        let learnedCurrents = decodedCompletionCurrents(
2226
            from: chargedDevice,
2227
            key: "learnedCompletionCurrentsRawValue"
2228
        )
2229
        let legacyCurrent: Double?
Bogdan Timofte authored a month ago
2230
        switch chargingTransportMode {
2231
        case .wired:
Bogdan Timofte authored a month ago
2232
            legacyCurrent = optionalDoubleValue(chargedDevice, key: "wiredChargeCompletionCurrentAmps")
Bogdan Timofte authored a month ago
2233
                ?? optionalDoubleValue(chargedDevice, key: "wiredMinimumCurrentAmps")
2234
                ?? optionalDoubleValue(chargedDevice, key: "minimumCurrentAmps")
2235
        case .wireless:
Bogdan Timofte authored a month ago
2236
            legacyCurrent = optionalDoubleValue(chargedDevice, key: "wirelessChargeCompletionCurrentAmps")
Bogdan Timofte authored a month ago
2237
                ?? optionalDoubleValue(chargedDevice, key: "wirelessMinimumCurrentAmps")
2238
                ?? optionalDoubleValue(chargedDevice, key: "minimumCurrentAmps")
2239
        }
Bogdan Timofte authored a month ago
2240

            
2241
        let resolvedCurrent = configuredCurrents[sessionKind]
2242
            ?? learnedCurrents[sessionKind]
2243
            ?? legacyCurrent
2244
            ?? fallback
2245
        guard let resolvedCurrent, resolvedCurrent > 0 else {
2246
            return nil
2247
        }
2248
        return max(resolvedCurrent, 0.01)
Bogdan Timofte authored a month ago
2249
    }
2250

            
Bogdan Timofte authored a month ago
2251
    private func fallbackChargingTransportMode(for chargedDevice: NSManagedObject) -> ChargingTransportMode {
Bogdan Timofte authored a month ago
2252
        let supportsWiredCharging = supportsWiredCharging(for: chargedDevice)
2253
        let supportsWirelessCharging = supportsWirelessCharging(for: chargedDevice)
2254
        return resolvedPreferredChargingTransportMode(
Bogdan Timofte authored a month ago
2255
            .wired,
Bogdan Timofte authored a month ago
2256
            supportsWiredCharging: supportsWiredCharging,
2257
            supportsWirelessCharging: supportsWirelessCharging
2258
        )
2259
    }
2260

            
2261
    private func supportsWiredCharging(for chargedDevice: NSManagedObject) -> Bool {
2262
        if chargedDevice.value(forKey: "supportsWiredCharging") == nil {
2263
            return true
2264
        }
2265
        return boolValue(chargedDevice, key: "supportsWiredCharging")
2266
    }
2267

            
2268
    private func supportsWirelessCharging(for chargedDevice: NSManagedObject) -> Bool {
2269
        if chargedDevice.value(forKey: "supportsWirelessCharging") == nil {
2270
            return false
2271
        }
2272
        return boolValue(chargedDevice, key: "supportsWirelessCharging")
2273
    }
2274

            
Bogdan Timofte authored a month ago
2275
    private func chargingStateAvailability(for chargedDevice: NSManagedObject) -> ChargingStateAvailability {
2276
        if let rawValue = stringValue(chargedDevice, key: "chargingStateAvailabilityRawValue"),
2277
           let availability = ChargingStateAvailability(rawValue: rawValue) {
2278
            return availability
2279
        }
2280
        return ChargingStateAvailability.fallback(
2281
            for: boolValue(chargedDevice, key: "supportsChargingWhileOff")
2282
        )
2283
    }
2284

            
2285
    private func chargingStateMode(for session: NSManagedObject) -> ChargingStateMode {
2286
        if let rawValue = stringValue(session, key: "chargingStateRawValue"),
2287
           let chargingStateMode = ChargingStateMode(rawValue: rawValue) {
2288
            return chargingStateMode
2289
        }
2290

            
2291
        if let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
2292
           let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID) {
2293
            return chargingStateAvailability(for: chargedDevice).supportedModes.first ?? .on
2294
        }
2295

            
2296
        return .on
2297
    }
2298

            
2299
    private func resolvedChargingStateMode(
2300
        _ chargingStateMode: ChargingStateMode,
2301
        availability: ChargingStateAvailability
2302
    ) -> ChargingStateMode {
2303
        if availability.supportedModes.contains(chargingStateMode) {
2304
            return chargingStateMode
2305
        }
2306
        return availability.supportedModes.first ?? .on
2307
    }
2308

            
Bogdan Timofte authored a month ago
2309
    private func wirelessChargingProfile(for chargedDevice: NSManagedObject) -> WirelessChargingProfile {
2310
        guard let rawValue = stringValue(chargedDevice, key: "wirelessChargingProfileRawValue"),
2311
              let profile = WirelessChargingProfile(rawValue: rawValue) else {
2312
            return .genericQi
2313
        }
2314
        return profile
2315
    }
2316

            
2317
    private func resolvedPreferredChargingTransportMode(
2318
        _ preferredChargingTransportMode: ChargingTransportMode,
2319
        supportsWiredCharging: Bool,
2320
        supportsWirelessCharging: Bool
2321
    ) -> ChargingTransportMode {
2322
        switch preferredChargingTransportMode {
2323
        case .wired where supportsWiredCharging:
2324
            return .wired
2325
        case .wireless where supportsWirelessCharging:
2326
            return .wireless
2327
        default:
2328
            if supportsWiredCharging {
2329
                return .wired
2330
            }
2331
            if supportsWirelessCharging {
2332
                return .wireless
2333
            }
2334
            return .wired
2335
        }
2336
    }
2337

            
Bogdan Timofte authored a month ago
2338
    private func encodedCompletionCurrents(_ currents: [ChargeSessionKind: Double]) -> String? {
2339
        let payload = Dictionary(
2340
            uniqueKeysWithValues: currents.map { key, value in
2341
                (key.rawValue, value)
2342
            }
2343
        )
2344
        guard let data = try? JSONSerialization.data(withJSONObject: payload, options: [.sortedKeys]) else {
2345
            return nil
2346
        }
2347
        return String(data: data, encoding: .utf8)
2348
    }
2349

            
2350
    private func decodedCompletionCurrents(
2351
        from object: NSManagedObject,
2352
        key: String
2353
    ) -> [ChargeSessionKind: Double] {
2354
        guard let rawValue = stringValue(object, key: key),
2355
              let data = rawValue.data(using: .utf8),
2356
              let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Double] else {
2357
            return [:]
2358
        }
2359

            
2360
        return payload.reduce(into: [ChargeSessionKind: Double]()) { result, entry in
2361
            guard let sessionKind = ChargeSessionKind(rawValue: entry.key), entry.value > 0 else {
2362
                return
2363
            }
2364
            result[sessionKind] = entry.value
2365
        }
2366
    }
2367

            
2368
    private func legacyConfiguredCompletionCurrent(
2369
        for currents: [ChargeSessionKind: Double],
2370
        chargingTransportMode: ChargingTransportMode
2371
    ) -> Double? {
2372
        let candidates = currents
2373
            .filter { $0.key.chargingTransportMode == chargingTransportMode }
2374
            .sorted { lhs, rhs in
2375
                lhs.key.rawValue < rhs.key.rawValue
2376
            }
2377
            .map(\.value)
2378
        return candidates.first
2379
    }
2380

            
2381
    private func chargerIdleCurrent(for charger: NSManagedObject?) -> Double? {
2382
        guard let charger else {
2383
            return nil
2384
        }
2385
        let idleCurrent = optionalDoubleValue(charger, key: "chargerIdleCurrentAmps")
2386
        guard let idleCurrent, idleCurrent >= 0 else {
2387
            return nil
2388
        }
2389
        return idleCurrent
2390
    }
2391

            
2392
    private func effectiveCurrentAmps(
2393
        fromMeasuredCurrent currentAmps: Double,
2394
        chargingTransportMode: ChargingTransportMode,
2395
        charger: NSManagedObject?
2396
    ) -> Double {
2397
        switch chargingTransportMode {
2398
        case .wired:
2399
            return max(currentAmps, 0)
2400
        case .wireless:
2401
            guard let idleCurrent = chargerIdleCurrent(for: charger) else {
2402
                return max(currentAmps, 0)
2403
            }
2404
            return max(currentAmps - idleCurrent, 0)
2405
        }
2406
    }
2407

            
2408
    private func hasObservedChargeFlow(
2409
        currentAmps: Double,
2410
        chargingTransportMode: ChargingTransportMode,
2411
        charger: NSManagedObject?,
2412
        stopThreshold: Double?
2413
    ) -> Bool {
2414
        let effectiveCurrent = effectiveCurrentAmps(
2415
            fromMeasuredCurrent: currentAmps,
2416
            chargingTransportMode: chargingTransportMode,
2417
            charger: charger
2418
        )
2419
        return effectiveCurrent > max(stopThreshold ?? 0, 0.05)
2420
    }
2421

            
Bogdan Timofte authored a month ago
2422
    private func derivedMinimumCurrent(
2423
        from sessions: [NSManagedObject],
2424
        chargingTransportMode: ChargingTransportMode
2425
    ) -> Double? {
2426
        let completionCurrents = sessions.compactMap { session -> Double? in
2427
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2428
            guard self.chargingTransportMode(for: session) == chargingTransportMode else {
2429
                return nil
2430
            }
Bogdan Timofte authored a month ago
2431
            guard (optionalDoubleValue(session, key: "endBatteryPercent") ?? 0) >= 99.5 else {
2432
                return nil
2433
            }
Bogdan Timofte authored a month ago
2434
            guard let completionCurrent = optionalDoubleValue(session, key: "completionCurrentAmps"), completionCurrent > 0 else {
2435
                return nil
2436
            }
2437
            return completionCurrent
2438
        }
2439

            
2440
        let recentCompletionCurrents = Array(completionCurrents.suffix(5))
2441
        guard !recentCompletionCurrents.isEmpty else { return nil }
2442
        return recentCompletionCurrents.reduce(0, +) / Double(recentCompletionCurrents.count)
2443
    }
2444

            
Bogdan Timofte authored a month ago
2445
    private func derivedCompletionCurrents(from sessions: [NSManagedObject]) -> [ChargeSessionKind: Double] {
2446
        var groupedCurrents: [ChargeSessionKind: [Double]] = [:]
2447

            
2448
        for session in sessions {
2449
            guard statusValue(session, key: "statusRawValue") == .completed else {
2450
                continue
2451
            }
2452
            guard (optionalDoubleValue(session, key: "endBatteryPercent") ?? 0) >= 99.5 else {
2453
                continue
2454
            }
2455
            guard let completionCurrent = optionalDoubleValue(session, key: "completionCurrentAmps"),
2456
                  completionCurrent > 0 else {
2457
                continue
2458
            }
2459

            
2460
            let sessionKind = ChargeSessionKind(
2461
                chargingTransportMode: chargingTransportMode(for: session),
2462
                chargingStateMode: chargingStateMode(for: session)
2463
            )
2464
            groupedCurrents[sessionKind, default: []].append(completionCurrent)
2465
        }
2466

            
2467
        return groupedCurrents.reduce(into: [ChargeSessionKind: Double]()) { result, entry in
2468
            let recentCurrents = Array(entry.value.suffix(5))
2469
            guard !recentCurrents.isEmpty else {
2470
                return
2471
            }
2472
            result[entry.key] = recentCurrents.reduce(0, +) / Double(recentCurrents.count)
2473
        }
2474
    }
2475

            
Bogdan Timofte authored a month ago
2476
    private func derivedCapacity(
2477
        from sessions: [NSManagedObject],
2478
        chargingTransportMode: ChargingTransportMode,
2479
        supportsChargingWhileOff: Bool
2480
    ) -> Double? {
2481
        let capacityCandidates = sessions.compactMap { session -> Double? in
2482
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2483
            guard self.chargingTransportMode(for: session) == chargingTransportMode else {
2484
                return nil
2485
            }
2486
            guard let capacityEstimate = optionalDoubleValue(session, key: "capacityEstimateWh"), capacityEstimate > 0 else {
2487
                return nil
2488
            }
2489
            if supportsChargingWhileOff {
2490
                return capacityEstimate
2491
            }
2492
            guard let endBatteryPercent = optionalDoubleValue(session, key: "endBatteryPercent"), endBatteryPercent < 99.5 else {
2493
                return nil
2494
            }
2495
            return capacityEstimate
2496
        }
2497

            
2498
        let recentCapacityCandidates = Array(capacityCandidates.suffix(6))
2499
        guard !recentCapacityCandidates.isEmpty else { return nil }
2500
        return recentCapacityCandidates.reduce(0, +) / Double(recentCapacityCandidates.count)
2501
    }
2502

            
2503
    private func derivedWirelessEfficiency(
2504
        from sessions: [NSManagedObject],
2505
        chargingProfile: WirelessChargingProfile
2506
    ) -> Double? {
2507
        guard chargingProfile == .magsafe else {
2508
            return nil
2509
        }
2510

            
2511
        let candidates = sessions.compactMap { session -> Double? in
2512
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2513
            guard chargingTransportMode(for: session) == .wireless else { return nil }
2514
            guard boolValue(session, key: "usesEstimatedWirelessEfficiency") == false else { return nil }
2515
            guard let factor = optionalDoubleValue(session, key: "wirelessEfficiencyFactor"), factor > 0 else {
2516
                return nil
2517
            }
2518
            return factor
2519
        }
2520

            
2521
        let recentCandidates = Array(candidates.suffix(6))
2522
        guard !recentCandidates.isEmpty else { return nil }
2523
        return recentCandidates.reduce(0, +) / Double(recentCandidates.count)
2524
    }
2525

            
2526
    private func derivedObservedVoltageSelections(from sessions: [NSManagedObject]) -> [Double] {
2527
        let candidates = sessions.compactMap { session -> Double? in
2528
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2529
            guard let sourceVoltage = optionalDoubleValue(session, key: "selectedSourceVoltageVolts"), sourceVoltage > 0 else {
2530
                return nil
2531
            }
2532
            return (sourceVoltage * 10).rounded() / 10
2533
        }
2534

            
2535
        let counts = Dictionary(grouping: candidates, by: { $0 }).mapValues(\.count)
2536
        return counts.keys.sorted()
2537
    }
2538

            
2539
    private func derivedIdleCurrent(from sessions: [NSManagedObject]) -> Double? {
2540
        let candidates = sessions.compactMap { session -> Double? in
2541
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2542
            guard let minimumObservedCurrent = optionalDoubleValue(session, key: "minimumObservedCurrentAmps"), minimumObservedCurrent > 0 else {
2543
                return nil
2544
            }
2545
            return minimumObservedCurrent
2546
        }
2547

            
2548
        let recentCandidates = Array(candidates.suffix(6))
2549
        guard !recentCandidates.isEmpty else { return nil }
2550
        return recentCandidates.reduce(0, +) / Double(recentCandidates.count)
2551
    }
2552

            
2553
    private func derivedChargerEfficiency(from sessions: [NSManagedObject]) -> Double? {
2554
        let candidates = sessions.compactMap { session -> Double? in
2555
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2556
            guard let factor = optionalDoubleValue(session, key: "wirelessEfficiencyFactor"), factor > 0 else {
2557
                return nil
2558
            }
2559
            return factor
2560
        }
2561

            
2562
        let recentCandidates = Array(candidates.suffix(6))
2563
        guard !recentCandidates.isEmpty else { return nil }
2564
        return recentCandidates.reduce(0, +) / Double(recentCandidates.count)
2565
    }
2566

            
2567
    private func derivedMaximumPower(from sessions: [NSManagedObject]) -> Double? {
2568
        sessions.compactMap { session -> Double? in
2569
            guard statusValue(session, key: "statusRawValue") == .completed else { return nil }
2570
            guard let maximumObservedPower = optionalDoubleValue(session, key: "maximumObservedPowerWatts"), maximumObservedPower > 0 else {
2571
                return nil
2572
            }
2573
            return maximumObservedPower
2574
        }
2575
        .max()
2576
    }
2577

            
2578
    private func chargingTransportMode(for session: NSManagedObject) -> ChargingTransportMode {
2579
        if let persistedChargingTransportMode = chargingTransportModeValue(session, key: "chargingTransportRawValue") {
2580
            return persistedChargingTransportMode
2581
        }
2582

            
2583
        if let chargedDeviceID = stringValue(session, key: "chargedDeviceID"),
2584
           let chargedDevice = fetchChargedDeviceObject(id: chargedDeviceID) {
Bogdan Timofte authored a month ago
2585
            return fallbackChargingTransportMode(for: chargedDevice)
Bogdan Timofte authored a month ago
2586
        }
2587

            
2588
        return .wired
2589
    }
2590

            
2591
    private func saveReason(for session: NSManagedObject, observedAt: Date) -> ObservationSaveReason {
2592
        if session.isInserted {
2593
            return .created
2594
        }
2595

            
2596
        let committedValues = session.committedValues(
2597
            forKeys: [
2598
                "statusRawValue",
2599
                "updatedAt",
2600
                "targetBatteryAlertTriggeredAt",
2601
                "requiresCompletionConfirmation"
2602
            ]
2603
        )
2604
        let committedStatus = (committedValues["statusRawValue"] as? String).flatMap(ChargeSessionStatus.init(rawValue:))
2605
        let currentStatus = statusValue(session, key: "statusRawValue")
2606
        let committedTargetAlertTriggeredAt = committedValues["targetBatteryAlertTriggeredAt"] as? Date
2607
        let currentTargetAlertTriggeredAt = dateValue(session, key: "targetBatteryAlertTriggeredAt")
2608
        let committedRequiresCompletionConfirmation = (committedValues["requiresCompletionConfirmation"] as? NSNumber)?.boolValue
2609
            ?? (committedValues["requiresCompletionConfirmation"] as? Bool)
2610
            ?? false
2611
        let currentRequiresCompletionConfirmation = boolValue(session, key: "requiresCompletionConfirmation")
2612

            
2613
        if currentStatus == .completed, committedStatus != .completed {
2614
            return .completed
2615
        }
2616

            
Bogdan Timofte authored a month ago
2617
        if currentStatus != committedStatus {
2618
            return .event
2619
        }
2620

            
Bogdan Timofte authored a month ago
2621
        if committedTargetAlertTriggeredAt != currentTargetAlertTriggeredAt
2622
            || committedRequiresCompletionConfirmation != currentRequiresCompletionConfirmation {
2623
            return .event
2624
        }
2625

            
2626
        let lastPersistedAt = (committedValues["updatedAt"] as? Date)
2627
            ?? dateValue(session, key: "createdAt")
2628
            ?? observedAt
2629

            
2630
        if observedAt.timeIntervalSince(lastPersistedAt) >= activeSessionSaveInterval {
2631
            return .periodic
2632
        }
2633

            
2634
        return .none
2635
    }
2636

            
Bogdan Timofte authored a month ago
2637
    private func shouldPersistAggregatedSample(
2638
        _ sample: NSManagedObject,
2639
        observedAt: Date
2640
    ) -> Bool {
2641
        if sample.isInserted {
2642
            return true
2643
        }
2644

            
2645
        let committedValues = sample.committedValues(forKeys: ["updatedAt"])
2646
        let lastPersistedAt = (committedValues["updatedAt"] as? Date)
2647
            ?? dateValue(sample, key: "createdAt")
2648
            ?? observedAt
2649

            
2650
        return observedAt.timeIntervalSince(lastPersistedAt) >= aggregatedSampleSaveInterval
2651
    }
2652

            
Bogdan Timofte authored a month ago
2653
    private func generateQRIdentifier() -> String {
2654
        "device:\(UUID().uuidString)"
2655
    }
2656

            
2657
    @discardableResult
2658
    private func saveContext() -> Bool {
2659
        guard context.hasChanges else { return true }
2660
        do {
2661
            try context.save()
2662
            return true
2663
        } catch {
2664
            track("Failed saving charge insights context: \(error)")
2665
            context.rollback()
2666
            return false
2667
        }
2668
    }
2669

            
2670
    private func normalizedText(_ text: String) -> String {
2671
        text.trimmingCharacters(in: .whitespacesAndNewlines)
2672
    }
2673

            
2674
    private func normalizedOptionalText(_ text: String?) -> String? {
2675
        guard let text else { return nil }
2676
        let normalized = normalizedText(text)
2677
        return normalized.isEmpty ? nil : normalized
2678
    }
2679

            
2680
    private func normalizedMACAddress(_ macAddress: String) -> String {
2681
        normalizedText(macAddress).uppercased()
2682
    }
2683

            
Bogdan Timofte authored a month ago
2684
    private func rawValue(_ object: NSManagedObject, key: String) -> Any? {
2685
        guard object.entity.propertiesByName[key] != nil else {
2686
            return nil
2687
        }
2688
        return object.value(forKey: key)
2689
    }
2690

            
2691
    private func setValue(_ value: Any?, on object: NSManagedObject, key: String) {
2692
        guard object.entity.propertiesByName[key] != nil else {
2693
            return
2694
        }
2695
        object.setValue(value, forKey: key)
2696
    }
2697

            
Bogdan Timofte authored a month ago
2698
    private func stringValue(_ object: NSManagedObject, key: String) -> String? {
Bogdan Timofte authored a month ago
2699
        guard let value = rawValue(object, key: key) as? String else { return nil }
Bogdan Timofte authored a month ago
2700
        let normalized = normalizedOptionalText(value)
2701
        return normalized
2702
    }
2703

            
2704
    private func dateValue(_ object: NSManagedObject, key: String) -> Date? {
Bogdan Timofte authored a month ago
2705
        rawValue(object, key: key) as? Date
Bogdan Timofte authored a month ago
2706
    }
2707

            
2708
    private func doubleValue(_ object: NSManagedObject, key: String) -> Double {
Bogdan Timofte authored a month ago
2709
        if let value = rawValue(object, key: key) as? Double {
Bogdan Timofte authored a month ago
2710
            return value
2711
        }
Bogdan Timofte authored a month ago
2712
        if let value = rawValue(object, key: key) as? NSNumber {
Bogdan Timofte authored a month ago
2713
            return value.doubleValue
2714
        }
2715
        return 0
2716
    }
2717

            
2718
    private func optionalDoubleValue(_ object: NSManagedObject, key: String) -> Double? {
Bogdan Timofte authored a month ago
2719
        let value = rawValue(object, key: key)
2720
        if value == nil {
Bogdan Timofte authored a month ago
2721
            return nil
2722
        }
2723
        return doubleValue(object, key: key)
2724
    }
2725

            
2726
    private func optionalInt16Value(_ object: NSManagedObject, key: String) -> Int16? {
Bogdan Timofte authored a month ago
2727
        if let value = rawValue(object, key: key) as? Int16 {
Bogdan Timofte authored a month ago
2728
            return value
2729
        }
Bogdan Timofte authored a month ago
2730
        if let value = rawValue(object, key: key) as? NSNumber {
Bogdan Timofte authored a month ago
2731
            return value.int16Value
2732
        }
2733
        return nil
2734
    }
2735

            
2736
    private func optionalInt32Value(_ object: NSManagedObject, key: String) -> Int32? {
Bogdan Timofte authored a month ago
2737
        if let value = rawValue(object, key: key) as? Int32 {
Bogdan Timofte authored a month ago
2738
            return value
2739
        }
Bogdan Timofte authored a month ago
2740
        if let value = rawValue(object, key: key) as? NSNumber {
Bogdan Timofte authored a month ago
2741
            return value.int32Value
2742
        }
2743
        return nil
2744
    }
2745

            
2746
    private func boolValue(_ object: NSManagedObject, key: String) -> Bool {
Bogdan Timofte authored a month ago
2747
        if let value = rawValue(object, key: key) as? Bool {
Bogdan Timofte authored a month ago
2748
            return value
2749
        }
Bogdan Timofte authored a month ago
2750
        if let value = rawValue(object, key: key) as? NSNumber {
Bogdan Timofte authored a month ago
2751
            return value.boolValue
2752
        }
2753
        return false
2754
    }
2755

            
2756
    private func uuidValue(_ object: NSManagedObject, key: String) -> UUID? {
2757
        guard let value = stringValue(object, key: key) else { return nil }
2758
        return UUID(uuidString: value)
2759
    }
2760

            
2761
    private func statusValue(_ object: NSManagedObject, key: String) -> ChargeSessionStatus? {
2762
        guard let value = stringValue(object, key: key) else { return nil }
2763
        return ChargeSessionStatus(rawValue: value)
2764
    }
2765

            
2766
    private func chargingTransportModeValue(_ object: NSManagedObject, key: String) -> ChargingTransportMode? {
2767
        guard let value = stringValue(object, key: key) else { return nil }
2768
        return ChargingTransportMode(rawValue: value)
2769
    }
2770

            
2771
    private func decodedObservedVoltageSelections(from object: NSManagedObject) -> [Double] {
2772
        guard let rawValue = stringValue(object, key: "chargerObservedVoltageSelectionsRawValue") else {
2773
            return []
2774
        }
2775
        return rawValue
2776
            .split(separator: ",")
2777
            .compactMap { Double($0) }
2778
            .sorted()
2779
    }
2780

            
2781
    private func encodedObservedVoltageSelections(_ voltages: [Double]) -> String? {
2782
        let uniqueVoltages = Array(Set(voltages)).sorted()
2783
        guard !uniqueVoltages.isEmpty else {
2784
            return nil
2785
        }
2786
        return uniqueVoltages
2787
            .map { String(format: "%.1f", $0) }
2788
            .joined(separator: ",")
2789
    }
2790

            
2791
    private func runningAverage(currentAverage: Double, currentCount: Int, newValue: Double) -> Double {
2792
        guard currentCount > 0 else {
2793
            return newValue
2794
        }
2795
        let total = (currentAverage * Double(currentCount)) + newValue
2796
        return total / Double(currentCount + 1)
2797
    }
2798
}
2799

            
2800
private enum ObservationSaveReason {
2801
    case none
2802
    case created
2803
    case periodic
2804
    case completed
2805
    case event
2806
}