USB-Meter / USB Meter / Views / Meter / Tabs / Live / ChargerStandbyPowerWizardView.swift
Newer Older
916 lines | 38.162kb
Bogdan Timofte authored a month ago
1
//
2
//  ChargerStandbyPowerWizardView.swift
3
//  USB Meter
4
//
5
//  Created by Codex on 13/04/2026.
6
//
7

            
8
import SwiftUI
9

            
10
struct ChargerStandbyPowerWizardView: View {
11
    @EnvironmentObject private var appData: AppData
12

            
13
    @State private var chargerLibraryVisibility = false
14
    @State private var discardConfirmationVisibility = false
15
    @State private var selectedMeterMACAddress: String?
16
    @State private var selectedChargerID: UUID?
17

            
18
    let preferredMeterMACAddress: String?
19
    let preferredChargerID: UUID?
20
    let locksChargerSelection: Bool
21

            
22
    init(
23
        preferredMeterMACAddress: String? = nil,
24
        preferredChargerID: UUID? = nil,
25
        locksChargerSelection: Bool = false
26
    ) {
27
        self.preferredMeterMACAddress = preferredMeterMACAddress
28
        self.preferredChargerID = preferredChargerID
29
        self.locksChargerSelection = locksChargerSelection
30
        _selectedMeterMACAddress = State(initialValue: nil)
31
        _selectedChargerID = State(initialValue: preferredChargerID)
32
    }
33

            
34
    var body: some View {
35
        ScrollView {
36
            VStack(spacing: 18) {
37
                if let session = activeSession {
38
                    activeMeasurementCard(session)
39
                    liveSessionCard(session)
40
                } else {
41
                    newMeasurementWizardCard
42
                }
43
            }
44
            .padding()
45
        }
46
        .background(
47
            LinearGradient(
48
                colors: [.orange.opacity(0.16), Color.clear],
49
                startPoint: .topLeading,
50
                endPoint: .bottomTrailing
51
            )
52
            .ignoresSafeArea()
53
        )
54
        .navigationTitle(navigationTitleText)
55
        .sheet(isPresented: $chargerLibraryVisibility) {
56
            ChargedDeviceLibrarySheetView(
57
                visibility: $chargerLibraryVisibility,
58
                meterMACAddress: selectedMeterSummary?.macAddress ?? "",
59
                meterTint: selectedMeter?.color ?? .orange,
60
                mode: .charger
61
            )
62
            .environmentObject(appData)
63
        }
64
        .confirmationDialog(
65
            "Discard the current standby measurement?",
66
            isPresented: $discardConfirmationVisibility,
67
            titleVisibility: .visible
68
        ) {
69
            Button("Discard", role: .destructive) {
70
                if let activeSession {
71
                    _ = appData.finishChargerStandbyMeasurement(for: activeSession.meterMACAddress, save: false)
72
                }
73
            }
74
            Button("Cancel", role: .cancel) {}
75
        } message: {
76
            Text("The current sample set will be removed and nothing will be saved for this charger.")
77
        }
78
    }
79

            
80
    private var liveMeterSummaries: [AppData.MeterSummary] {
81
        appData.meterSummaries.filter { $0.meter != nil }
82
    }
83

            
84
    private var availableChargers: [ChargedDeviceSummary] {
85
        appData.chargerSummaries
86
    }
87

            
88
    private var preferredChargerMeterMACAddress: String? {
89
        preferredChargerID.flatMap { appData.chargedDeviceSummary(id: $0)?.lastAssociatedMeterMAC }
90
    }
91

            
92
    private var activeSession: ChargerStandbyPowerMonitorSession? {
93
        let candidateMACAddresses = [
94
            selectedMeterMACAddress ?? "",
95
            preferredMeterMACAddress ?? "",
96
            preferredChargerMeterMACAddress ?? ""
97
        ]
98
        .filter { $0.isEmpty == false }
99

            
100
        for macAddress in candidateMACAddresses {
101
            if let session = appData.chargerStandbyMeasurementSession(for: macAddress) {
102
                return session
103
            }
104
        }
105

            
106
        for meterSummary in liveMeterSummaries {
107
            if let session = appData.chargerStandbyMeasurementSession(for: meterSummary.macAddress) {
108
                return session
109
            }
110
        }
111

            
112
        return nil
113
    }
114

            
115
    private var suggestedMeterSummary: AppData.MeterSummary? {
116
        if let preferredMeterMACAddress {
117
            return liveMeterSummaries.first(where: { $0.macAddress == preferredMeterMACAddress })
118
        }
119

            
120
        if let preferredChargerMeterMACAddress {
121
            return liveMeterSummaries.first(where: { $0.macAddress == preferredChargerMeterMACAddress })
122
        }
123

            
124
        return liveMeterSummaries.count == 1 ? liveMeterSummaries.first : nil
125
    }
126

            
127
    private var selectedMeterSummary: AppData.MeterSummary? {
128
        if let activeSession {
129
            return liveMeterSummaries.first(where: { $0.macAddress == activeSession.meterMACAddress })
130
        }
131

            
132
        guard let selectedMeterMACAddress else {
133
            return nil
134
        }
135

            
136
        return liveMeterSummaries.first(where: { $0.macAddress == selectedMeterMACAddress })
137
    }
138

            
139
    private var selectedMeter: Meter? {
140
        selectedMeterSummary?.meter
141
    }
142

            
143
    private var isChargerSelectionLocked: Bool {
144
        locksChargerSelection || preferredChargerID != nil
145
    }
146

            
147
    private var meterSelectionBinding: Binding<String?> {
148
        Binding(
149
            get: { selectedMeterMACAddress },
150
            set: { selectedMeterMACAddress = $0 }
151
        )
152
    }
153

            
154
    private var selectedCharger: ChargedDeviceSummary? {
155
        if let activeSession {
156
            return appData.chargedDeviceSummary(id: activeSession.chargerID)
157
        }
158

            
159
        guard let selectedChargerID else {
160
            return nil
161
        }
162

            
163
        return appData.chargedDeviceSummary(id: selectedChargerID)
164
    }
165

            
166
    private var chargerSelectionBinding: Binding<UUID?> {
167
        Binding(
168
            get: { selectedChargerID },
169
            set: { selectedChargerID = $0 }
170
        )
171
    }
172

            
173
    private var preferredChargerSummary: ChargedDeviceSummary? {
174
        guard let preferredChargerID else {
175
            return nil
176
        }
177
        return appData.chargedDeviceSummary(id: preferredChargerID)
178
    }
179

            
180
    private var navigationTitleText: String {
181
        "New Standby Consumption Measurement"
182
    }
183

            
184
    private var wizardCardTitle: String {
185
        if let selectedMeterSummary {
186
            return selectedMeterSummary.displayName
187
        }
188

            
189
        if let suggestedMeterSummary {
190
            return suggestedMeterSummary.displayName
191
        }
192

            
193
        return "Use Meter"
194
    }
195

            
196
    private var newMeasurementWizardCard: some View {
197
        MeterInfoCardView(
198
            title: wizardCardTitle,
199
            tint: .orange
200
        ) {
201
            if liveMeterSummaries.isEmpty {
202
                Text("Connect a live meter first. Standby measurement uses a live feed, so meter selection happens here in the wizard.")
203
                    .font(.footnote)
204
                    .foregroundColor(.secondary)
205
                    .frame(maxWidth: .infinity, alignment: .leading)
206
            } else {
207
                VStack(alignment: .leading, spacing: 12) {
208
                    if isChargerSelectionLocked == false {
209
                        HStack(spacing: 8) {
210
                            Text("Charger")
211
                                .font(.subheadline.weight(.semibold))
212
                            ContextInfoButton(
213
                                title: "Charger",
214
                                message: "Choose the charger whose standby consumption you want to measure in this run."
215
                            )
216
                        }
217

            
218
                        if availableChargers.isEmpty {
219
                            Text("No charger available yet. Open the charger library to create one first.")
220
                                .font(.caption)
221
                                .foregroundColor(.secondary)
222
                        } else {
223
                            Picker("Charger", selection: chargerSelectionBinding) {
224
                                Text("Select Charger").tag(Optional<UUID>.none)
225
                                ForEach(availableChargers) { charger in
226
                                    Text(charger.name).tag(Optional(charger.id))
227
                                }
228
                            }
229
                            .pickerStyle(.menu)
230
                        }
231
                    }
232

            
233
                    HStack(spacing: 8) {
234
                        Text("Use Meter")
235
                            .font(.subheadline.weight(.semibold))
236
                        ContextInfoButton(
237
                            title: "Use Meter",
238
                            message: "Choose the live meter explicitly. Standby consumption can vary with the upstream source or when the charger is connected to a computer, so re-run after setup changes."
239
                        )
240
                    }
241

            
242
                    Picker("Use Meter", selection: meterSelectionBinding) {
243
                        Text("Select Meter").tag(Optional<String>.none)
244
                        ForEach(liveMeterSummaries) { meterSummary in
245
                            Text(meterSummary.displayName).tag(Optional(meterSummary.macAddress))
246
                        }
247
                    }
248
                    .pickerStyle(.menu)
249
                    .disabled(activeSession != nil)
250

            
251
                    if activeSession == nil, let suggestedMeterSummary, selectedMeterSummary == nil {
252
                        Text("Suggested from the current context: \(suggestedMeterSummary.displayName). Select it explicitly if this is the meter you want to use.")
253
                            .font(.caption)
254
                            .foregroundColor(.secondary)
255
                    }
256

            
257
                    HStack(spacing: 12) {
258
                        if isChargerSelectionLocked == false {
259
                            Button("Manage Charger Library") {
260
                                chargerLibraryVisibility = true
261
                            }
262
                            .disabled(selectedMeter == nil)
263
                        }
264

            
265
                        Button("Start Measurement") {
266
                            startMeasurement()
267
                        }
268
                        .disabled(selectedCharger == nil || selectedMeter == nil)
269
                    }
270
                    .buttonStyle(.borderedProminent)
271
                }
272
            }
273

            
274
            if selectedMeter == nil {
275
                Text("Choose the live meter explicitly before starting. The wizard no longer auto-confirms a suggested meter.")
276
                    .font(.caption)
277
                    .foregroundColor(.secondary)
278
            } else if activeSession == nil, selectedCharger == nil {
279
                Text("Select the charger you want to measure, then start the run.")
280
                    .font(.caption)
281
                    .foregroundColor(.secondary)
282
            } else if activeSession == nil, selectedMeter?.operationalState != .dataIsAvailable {
283
                Text("The wizard can start now, but samples will only be captured while live meter data is available.")
284
                    .font(.caption)
285
                    .foregroundColor(.secondary)
286
            } else if let activeSession {
287
                Text(
288
                    "\(activeSession.readinessDescription) • \(formattedDuration(Date().timeIntervalSince(activeSession.startedAt))) • \(activeSession.sampleCount) samples"
289
                )
290
                .font(.caption)
291
                .foregroundColor(.secondary)
292
            }
293
        }
294
    }
295

            
296
    private func activeMeasurementCard(_ session: ChargerStandbyPowerMonitorSession) -> some View {
297
        MeterInfoCardView(
298
            title: "Measurement Running",
299
            infoMessage: "The run keeps collecting samples while this meter stays live. Save when you are happy with the sample set, or discard to cancel it.",
300
            tint: .orange
301
        ) {
302
            MeterInfoRowView(label: "Meter", value: selectedMeterSummary?.displayName ?? session.meterMACAddress)
303
            MeterInfoRowView(label: "Charger", value: selectedCharger?.name ?? "Selected charger")
304
            MeterInfoRowView(label: "Status", value: session.readinessDescription)
305
            MeterInfoRowView(label: "Samples", value: "\(session.sampleCount)")
306

            
307
            HStack(spacing: 12) {
308
                Button("Save Result") {
309
                    _ = appData.finishChargerStandbyMeasurement(for: session.meterMACAddress, save: true)
310
                }
311
                .disabled(session.hasSamples == false)
312

            
313
                Button("Discard") {
314
                    discardConfirmationVisibility = true
315
                }
316
                .foregroundColor(.red)
317
            }
318
            .buttonStyle(.borderedProminent)
319
        }
320
    }
321

            
322
    private func liveSessionCard(_ session: ChargerStandbyPowerMonitorSession) -> some View {
323
        VStack(spacing: 18) {
324
            if let statistics = session.statistics {
325
                stabilityCard(
326
                    isStable: statistics.isStable,
327
                    averagePowerWatts: statistics.averagePowerWatts,
328
                    stabilityDeltaWatts: statistics.stabilityDeltaWatts,
329
                    stabilityToleranceWatts: statistics.stabilityToleranceWatts,
330
                    sampleCount: statistics.sampleCount
331
                )
332

            
333
                projectionCard(
334
                    averagePowerWatts: statistics.averagePowerWatts,
335
                    projectedDailyEnergyWh: statistics.projectedDailyEnergyWh,
336
                    projectedWeeklyEnergyWh: statistics.projectedWeeklyEnergyWh,
337
                    projectedMonthlyEnergyWh: statistics.projectedMonthlyEnergyWh,
338
                    projectedYearlyEnergyWh: statistics.projectedYearlyEnergyWh
339
                )
340

            
341
                distributionCard(
342
                    histogram: statistics.histogram,
343
                    averagePowerWatts: statistics.averagePowerWatts,
344
                    standardDeviationPowerWatts: statistics.standardDeviationPowerWatts,
345
                    tint: .orange
346
                )
347

            
348
                statisticsCard(
349
                    averagePowerWatts: statistics.averagePowerWatts,
350
                    medianPowerWatts: statistics.medianPowerWatts,
351
                    minimumPowerWatts: statistics.minimumPowerWatts,
352
                    maximumPowerWatts: statistics.maximumPowerWatts,
353
                    standardDeviationPowerWatts: statistics.standardDeviationPowerWatts,
354
                    coefficientOfVariation: statistics.coefficientOfVariation,
355
                    averageCurrentAmps: statistics.averageCurrentAmps,
356
                    averageVoltageVolts: statistics.averageVoltageVolts
357
                )
358
            } else {
359
                MeterInfoCardView(title: "Live Stats", tint: .orange) {
360
                    Text("Waiting for the first valid power samples from the meter.")
361
                        .font(.footnote)
362
                        .foregroundColor(.secondary)
363
                }
364
            }
365
        }
366
    }
367

            
368
    private func stabilityCard(
369
        isStable: Bool,
370
        averagePowerWatts: Double,
371
        stabilityDeltaWatts: Double,
372
        stabilityToleranceWatts: Double,
373
        sampleCount: Int,
374
        subtitle: String? = nil
375
    ) -> some View {
376
        VStack(alignment: .leading, spacing: 10) {
377
            HStack {
378
                VStack(alignment: .leading, spacing: 4) {
379
                    Text(isStable ? "Enough Samples" : "Still Settling")
380
                        .font(.headline)
381
                    Text(subtitle ?? (isStable ? "The running average has stabilised." : "The wizard is still watching the average drift."))
382
                        .font(.caption)
383
                        .foregroundColor(.secondary)
384
                }
385

            
386
                Spacer()
387

            
388
                Text(isStable ? "Ready" : "Live")
389
                    .font(.caption.weight(.semibold))
390
                    .padding(.horizontal, 10)
391
                    .padding(.vertical, 6)
392
                    .foregroundColor(isStable ? .green : .orange)
393
                    .meterCard(
394
                        tint: isStable ? .green : .orange,
395
                        fillOpacity: 0.10,
396
                        strokeOpacity: 0.16,
397
                        cornerRadius: 999
398
                    )
399
            }
400

            
401
            Text("\(averagePowerWatts.format(decimalDigits: 3)) W")
402
                .font(.system(.largeTitle, design: .rounded).weight(.bold))
403
                .monospacedDigit()
404

            
405
            Text(
406
                "Recent drift: \((stabilityDeltaWatts * 1000).format(decimalDigits: 2)) mW, tolerance \((stabilityToleranceWatts * 1000).format(decimalDigits: 2)) mW over \(sampleCount) samples."
407
            )
408
            .font(.footnote)
409
            .foregroundColor(.secondary)
410
        }
411
        .frame(maxWidth: .infinity, alignment: .leading)
412
        .padding(18)
413
        .meterCard(tint: isStable ? .green : .orange, fillOpacity: 0.18, strokeOpacity: 0.24)
414
    }
415

            
416
    private func projectionCard(
417
        averagePowerWatts: Double,
418
        projectedDailyEnergyWh: Double,
419
        projectedWeeklyEnergyWh: Double,
420
        projectedMonthlyEnergyWh: Double,
421
        projectedYearlyEnergyWh: Double
422
    ) -> some View {
423
        MeterInfoCardView(
424
            title: "Consumption Projection",
425
            infoMessage: "These projections extrapolate only from the measured standby average. They do not say anything about charger behaviour under load.",
426
            tint: .teal
427
        ) {
428
            MeterInfoRowView(label: "Average Power", value: "\(averagePowerWatts.format(decimalDigits: 3)) W")
429
            MeterInfoRowView(label: "24 Hours", value: standbyEnergyLabel(projectedDailyEnergyWh))
430
            MeterInfoRowView(label: "7 Days", value: standbyEnergyLabel(projectedWeeklyEnergyWh))
431
            MeterInfoRowView(label: "30 Days", value: standbyEnergyLabel(projectedMonthlyEnergyWh))
432
            MeterInfoRowView(label: "1 Year", value: standbyEnergyLabel(projectedYearlyEnergyWh))
433
        }
434
    }
435

            
436
    private func distributionCard(
437
        histogram: [ChargerStandbyPowerDistributionBin],
438
        averagePowerWatts: Double,
439
        standardDeviationPowerWatts: Double,
440
        tint: Color
441
    ) -> some View {
442
        MeterInfoCardView(
443
            title: "Distribution",
444
            infoMessage: "Bars show how often each power interval appeared. The curve overlays a normal approximation around the observed mean and deviation.",
445
            tint: tint
446
        ) {
447
            StandbyPowerHistogramView(
448
                histogram: histogram,
449
                averagePowerWatts: averagePowerWatts,
450
                standardDeviationPowerWatts: standardDeviationPowerWatts,
451
                tint: tint
452
            )
453
            .frame(height: 220)
454

            
455
            if let firstBin = histogram.first, let lastBin = histogram.last {
Bogdan Timofte authored a month ago
456
                let midpointWatts = (firstBin.lowerBoundWatts + lastBin.upperBoundWatts) / 2
Bogdan Timofte authored a month ago
457
                HStack {
458
                    Text("\(firstBin.lowerBoundWatts.format(decimalDigits: 3)) W")
459
                    Spacer()
Bogdan Timofte authored a month ago
460
                    Text("\(midpointWatts.format(decimalDigits: 3)) W")
461
                    Spacer()
Bogdan Timofte authored a month ago
462
                    Text("\(lastBin.upperBoundWatts.format(decimalDigits: 3)) W")
463
                }
464
                .font(.caption)
465
                .foregroundColor(.secondary)
466
                .monospacedDigit()
467
            }
468
        }
469
    }
470

            
471
    private func statisticsCard(
472
        averagePowerWatts: Double,
473
        medianPowerWatts: Double,
474
        minimumPowerWatts: Double,
475
        maximumPowerWatts: Double,
476
        standardDeviationPowerWatts: Double,
477
        coefficientOfVariation: Double,
478
        averageCurrentAmps: Double,
479
        averageVoltageVolts: Double
480
    ) -> some View {
481
        MeterInfoCardView(title: "Interesting Stats", tint: .indigo) {
482
            MeterInfoRowView(label: "Median", value: "\(medianPowerWatts.format(decimalDigits: 3)) W")
483
            MeterInfoRowView(label: "Minimum", value: "\(minimumPowerWatts.format(decimalDigits: 3)) W")
484
            MeterInfoRowView(label: "Maximum", value: "\(maximumPowerWatts.format(decimalDigits: 3)) W")
485
            MeterInfoRowView(label: "Spread σ", value: "\(standardDeviationPowerWatts.format(decimalDigits: 4)) W")
486
            MeterInfoRowView(label: "Variation", value: "\(Int((coefficientOfVariation * 100).rounded()))%")
487
            MeterInfoRowView(label: "Mean Current", value: "\(averageCurrentAmps.format(decimalDigits: 3)) A")
488
            MeterInfoRowView(label: "Mean Voltage", value: "\(averageVoltageVolts.format(decimalDigits: 3)) V")
489
            MeterInfoRowView(label: "Power Density", value: "\(averagePowerWatts.format(decimalDigits: 3)) W steady")
490
        }
491
    }
492

            
493
    private func startMeasurement() {
494
        guard let selectedCharger, let selectedMeter else {
495
            return
496
        }
497

            
498
        _ = appData.startChargerStandbyMeasurement(for: selectedCharger.id, on: selectedMeter)
499
    }
500

            
501
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
502
        if wattHours >= 1000 {
503
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
504
        }
505
        return "\(wattHours.format(decimalDigits: 2)) Wh"
506
    }
507

            
508
    private func formattedDuration(_ duration: TimeInterval) -> String {
509
        let formatter = DateComponentsFormatter()
510
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
511
        formatter.unitsStyle = .abbreviated
512
        formatter.zeroFormattingBehavior = .pad
513
        return formatter.string(from: max(duration, 0)) ?? "0s"
514
    }
515

            
516
}
517

            
518
private struct StandbyPowerHistogramView: View {
519
    let histogram: [ChargerStandbyPowerDistributionBin]
520
    let averagePowerWatts: Double
521
    let standardDeviationPowerWatts: Double
522
    let tint: Color
523

            
524
    var body: some View {
525
        GeometryReader { proxy in
526
            let maxCount = max(Double(histogram.map(\.count).max() ?? 1), 1)
527

            
528
            ZStack {
529
                HStack(alignment: .bottom, spacing: 6) {
530
                    ForEach(histogram) { bin in
531
                        RoundedRectangle(cornerRadius: 8, style: .continuous)
532
                            .fill(tint.opacity(0.24))
533
                            .overlay(
534
                                RoundedRectangle(cornerRadius: 8, style: .continuous)
535
                                    .stroke(tint.opacity(0.22), lineWidth: 1)
536
                            )
537
                            .frame(height: max(10, (Double(bin.count) / maxCount) * proxy.size.height))
538
                    }
539
                }
540
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
541

            
542
                gaussianCurve(in: proxy.size)
543
                    .stroke(tint, style: StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))
544

            
545
                meanMarker(in: proxy.size)
546
                    .stroke(tint.opacity(0.9), style: StrokeStyle(lineWidth: 1.5, dash: [6, 4]))
547
            }
548
        }
549
    }
550

            
551
    private func gaussianCurve(in size: CGSize) -> Path {
552
        guard histogram.count > 1,
553
              standardDeviationPowerWatts > 0,
554
              let firstBin = histogram.first,
555
              let lastBin = histogram.last else {
556
            return Path()
557
        }
558

            
559
        let minimum = firstBin.lowerBoundWatts
560
        let maximum = lastBin.upperBoundWatts
561
        let span = max(maximum - minimum, 0.000_001)
562
        let sampleCount = 48
563
        let peakDensity = 1 / (standardDeviationPowerWatts * sqrt(2 * .pi))
564

            
565
        return Path { path in
566
            for index in 0...sampleCount {
567
                let progress = Double(index) / Double(sampleCount)
568
                let value = minimum + (span * progress)
569
                let zScore = (value - averagePowerWatts) / standardDeviationPowerWatts
570
                let density = exp(-0.5 * zScore * zScore) / (standardDeviationPowerWatts * sqrt(2 * .pi))
571
                let normalizedHeight = density / peakDensity
572

            
573
                let x = progress * size.width
574
                let y = size.height - (normalizedHeight * (Double(size.height) * 0.92))
575
                let point = CGPoint(x: x, y: y)
576

            
577
                if index == 0 {
578
                    path.move(to: point)
579
                } else {
580
                    path.addLine(to: point)
581
                }
582
            }
583
        }
584
    }
585

            
586
    private func meanMarker(in size: CGSize) -> Path {
587
        guard let firstBin = histogram.first, let lastBin = histogram.last else {
588
            return Path()
589
        }
590

            
591
        let minimum = firstBin.lowerBoundWatts
592
        let maximum = lastBin.upperBoundWatts
593
        let span = max(maximum - minimum, 0.000_001)
594
        let normalizedX = min(max((averagePowerWatts - minimum) / span, 0), 1)
595
        let x = normalizedX * size.width
596

            
597
        return Path { path in
598
            path.move(to: CGPoint(x: x, y: 0))
599
            path.addLine(to: CGPoint(x: x, y: size.height))
600
        }
601
    }
602
}
603

            
604
struct ChargerStandbyPowerMeasurementsView: View {
605
    @EnvironmentObject private var appData: AppData
Bogdan Timofte authored a month ago
606
    @State private var selectedMeasurementIDs = Set<UUID>()
Bogdan Timofte authored a month ago
607

            
608
    let chargerID: UUID
609

            
610
    var body: some View {
611
        Group {
612
            if let charger = appData.chargedDeviceSummary(id: chargerID) {
Bogdan Timofte authored a month ago
613
                measurementsList(for: charger)
Bogdan Timofte authored a month ago
614
            } else {
615
                Text("This charger is no longer available.")
616
                    .foregroundColor(.secondary)
617
                    .navigationTitle("Saved Measurements")
618
            }
619
        }
620
    }
621

            
Bogdan Timofte authored a month ago
622
    @ViewBuilder
623
    private func measurementsList(for charger: ChargedDeviceSummary) -> some View {
624
        let content = List(selection: $selectedMeasurementIDs) {
625
            if charger.standbyPowerMeasurements.isEmpty {
626
                Text("No standby measurements saved yet.")
627
                    .foregroundColor(.secondary)
628
            } else {
629
                ForEach(charger.standbyPowerMeasurements) { measurement in
630
                    NavigationLink(
631
                        destination: ChargerStandbyPowerMeasurementDetailView(
632
                            chargerID: charger.id,
633
                            measurementID: measurement.id
634
                        )
635
                    ) {
636
                        VStack(alignment: .leading, spacing: 6) {
637
                            HStack {
638
                                Text(measurement.endedAt.format())
639
                                    .font(.subheadline.weight(.semibold))
640
                                Spacer()
641
                                Text("\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
642
                                    .font(.subheadline.weight(.bold))
643
                                    .monospacedDigit()
644
                            }
645

            
646
                            Text(
647
                                "\(formattedDuration(measurement.duration)) • \(measurement.sampleCount) samples • \(standbyEnergyLabel(measurement.projectedYearlyEnergyWh)) / year"
648
                            )
649
                            .font(.caption)
650
                            .foregroundColor(.secondary)
651
                        }
652
                        .frame(maxWidth: .infinity, alignment: .leading)
653
                    }
654
                    .tag(measurement.id)
655
                }
656
                .onDelete { offsets in
657
                    let measurements = charger.standbyPowerMeasurements
658
                    for index in offsets {
659
                        guard measurements.indices.contains(index) else { continue }
660
                        let measurement = measurements[index]
661
                        _ = appData.deleteChargerStandbyMeasurement(
662
                            id: measurement.id,
663
                            chargerID: charger.id
664
                        )
665
                    }
666
                }
667
            }
668
        }
669
        .navigationTitle("Saved Measurements")
670
        .toolbar {
671
            ToolbarItem(placement: .primaryAction) {
672
                EditButton()
673
            }
674
        }
675

            
676
        if selectedMeasurementIDs.isEmpty {
677
            content
678
        } else {
679
            content.toolbar {
680
                ToolbarItem(placement: .destructiveAction) {
681
                    Button(role: .destructive) {
682
                        deleteMeasurements(
683
                            ids: selectedMeasurementIDs,
684
                            for: charger.id
685
                        )
686
                    } label: {
687
                        Image(systemName: "trash")
688
                    }
689
                }
690
            }
691
        }
692
    }
693

            
Bogdan Timofte authored a month ago
694
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
695
        if wattHours >= 1000 {
696
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
697
        }
698
        return "\(wattHours.format(decimalDigits: 2)) Wh"
699
    }
700

            
701
    private func formattedDuration(_ duration: TimeInterval) -> String {
702
        let formatter = DateComponentsFormatter()
703
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
704
        formatter.unitsStyle = .abbreviated
705
        formatter.zeroFormattingBehavior = .pad
706
        return formatter.string(from: max(duration, 0)) ?? "0s"
707
    }
Bogdan Timofte authored a month ago
708

            
709
    private func deleteMeasurements(ids: Set<UUID>, for chargerID: UUID) {
710
        for id in ids {
711
            _ = appData.deleteChargerStandbyMeasurement(id: id, chargerID: chargerID)
712
        }
713
        selectedMeasurementIDs.removeAll()
714
    }
Bogdan Timofte authored a month ago
715
}
716

            
717
struct ChargerStandbyPowerMeasurementDetailView: View {
718
    @EnvironmentObject private var appData: AppData
Bogdan Timofte authored a month ago
719
    @Environment(\.dismiss) private var dismiss
720

            
721
    @State private var deleteConfirmationVisibility = false
Bogdan Timofte authored a month ago
722

            
723
    let chargerID: UUID
724
    let measurementID: UUID
725

            
726
    var body: some View {
727
        Group {
728
            if let charger = appData.chargedDeviceSummary(id: chargerID),
729
               let measurement = charger.standbyPowerMeasurements.first(where: { $0.id == measurementID }) {
730
                ScrollView {
731
                    VStack(spacing: 18) {
732
                        MeterInfoCardView(title: charger.name, tint: .orange) {
733
                            MeterInfoRowView(label: "Saved", value: measurement.endedAt.format())
734
                            MeterInfoRowView(label: "Average", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
735
                            MeterInfoRowView(label: "Samples", value: "\(measurement.sampleCount)")
736
                            MeterInfoRowView(label: "Duration", value: formattedDuration(measurement.duration))
737
                        }
738

            
739
                        ChargerStandbyPowerMeasurementSnapshotView(measurement: measurement)
740
                    }
741
                    .padding()
742
                }
743
                .background(
744
                    LinearGradient(
745
                        colors: [.orange.opacity(0.16), Color.clear],
746
                        startPoint: .topLeading,
747
                        endPoint: .bottomTrailing
Bogdan Timofte authored a month ago
748
                )
749
                .ignoresSafeArea()
Bogdan Timofte authored a month ago
750
                )
751
                .navigationTitle("Measurement")
Bogdan Timofte authored a month ago
752
                .toolbar {
753
                    ToolbarItem(placement: .primaryAction) {
754
                        Button(role: .destructive) {
755
                            deleteConfirmationVisibility = true
756
                        } label: {
757
                            Label("Delete Measurement", systemImage: "trash")
758
                        }
759
                    }
760
                }
761
                .confirmationDialog(
762
                    "Delete this measurement?",
763
                    isPresented: $deleteConfirmationVisibility,
764
                    titleVisibility: .visible
765
                ) {
766
                    Button("Delete", role: .destructive) {
767
                        let didDelete = appData.deleteChargerStandbyMeasurement(
768
                            id: measurement.id,
769
                            chargerID: charger.id
770
                        )
771
                        if didDelete {
772
                            dismiss()
773
                        }
774
                    }
775
                    Button("Cancel", role: .cancel) {}
776
                } message: {
777
                    Text("This removes the saved standby measurement from the charger history and iCloud sync.")
778
                }
Bogdan Timofte authored a month ago
779
            } else {
780
                Text("This measurement is no longer available.")
781
                    .foregroundColor(.secondary)
782
                    .navigationTitle("Measurement")
783
            }
784
        }
785
    }
786

            
787
    private func formattedDuration(_ duration: TimeInterval) -> String {
788
        let formatter = DateComponentsFormatter()
789
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
790
        formatter.unitsStyle = .abbreviated
791
        formatter.zeroFormattingBehavior = .pad
792
        return formatter.string(from: max(duration, 0)) ?? "0s"
793
    }
794
}
795

            
796
private struct ChargerStandbyPowerMeasurementSnapshotView: View {
797
    let measurement: ChargerStandbyPowerMeasurementSummary
798

            
799
    var body: some View {
800
        VStack(spacing: 18) {
801
            stabilityCard
802
            projectionCard
803
            distributionCard
804
            statisticsCard
805
        }
806
    }
807

            
808
    private var stabilityCard: some View {
809
        VStack(alignment: .leading, spacing: 10) {
810
            HStack {
811
                VStack(alignment: .leading, spacing: 4) {
812
                    Text(measurement.isStable ? "Enough Samples" : "Still Settling")
813
                        .font(.headline)
814
                    Text("Saved \(measurement.endedAt.format())")
815
                        .font(.caption)
816
                        .foregroundColor(.secondary)
817
                }
818

            
819
                Spacer()
820

            
821
                Text(measurement.isStable ? "Ready" : "Live")
822
                    .font(.caption.weight(.semibold))
823
                    .padding(.horizontal, 10)
824
                    .padding(.vertical, 6)
825
                    .foregroundColor(measurement.isStable ? .green : .orange)
826
                    .meterCard(
827
                        tint: measurement.isStable ? .green : .orange,
828
                        fillOpacity: 0.10,
829
                        strokeOpacity: 0.16,
830
                        cornerRadius: 999
831
                    )
832
            }
833

            
834
            Text("\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
835
                .font(.system(.largeTitle, design: .rounded).weight(.bold))
836
                .monospacedDigit()
837

            
838
            Text(
839
                "Recent drift: \((measurement.stabilityDeltaWatts * 1000).format(decimalDigits: 2)) mW, tolerance \((measurement.stabilityToleranceWatts * 1000).format(decimalDigits: 2)) mW over \(measurement.sampleCount) samples."
840
            )
841
            .font(.footnote)
842
            .foregroundColor(.secondary)
843
        }
844
        .frame(maxWidth: .infinity, alignment: .leading)
845
        .padding(18)
846
        .meterCard(
847
            tint: measurement.isStable ? .green : .orange,
848
            fillOpacity: 0.18,
849
            strokeOpacity: 0.24
850
        )
851
    }
852

            
853
    private var projectionCard: some View {
854
        MeterInfoCardView(
855
            title: "Consumption Projection",
856
            infoMessage: "These projections extrapolate only from the measured standby average. They do not say anything about charger behaviour under load.",
857
            tint: .teal
858
        ) {
859
            MeterInfoRowView(label: "Average Power", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
860
            MeterInfoRowView(label: "24 Hours", value: standbyEnergyLabel(measurement.projectedDailyEnergyWh))
861
            MeterInfoRowView(label: "7 Days", value: standbyEnergyLabel(measurement.projectedWeeklyEnergyWh))
862
            MeterInfoRowView(label: "30 Days", value: standbyEnergyLabel(measurement.projectedMonthlyEnergyWh))
863
            MeterInfoRowView(label: "1 Year", value: standbyEnergyLabel(measurement.projectedYearlyEnergyWh))
864
        }
865
    }
866

            
867
    private var distributionCard: some View {
868
        MeterInfoCardView(
869
            title: "Distribution",
870
            infoMessage: "Bars show how often each power interval appeared. The curve overlays a normal approximation around the observed mean and deviation.",
871
            tint: .orange
872
        ) {
873
            StandbyPowerHistogramView(
874
                histogram: measurement.histogram,
875
                averagePowerWatts: measurement.averagePowerWatts,
876
                standardDeviationPowerWatts: measurement.standardDeviationPowerWatts,
877
                tint: .orange
878
            )
879
            .frame(height: 220)
880

            
881
            if let firstBin = measurement.histogram.first, let lastBin = measurement.histogram.last {
Bogdan Timofte authored a month ago
882
                let midpointWatts = (firstBin.lowerBoundWatts + lastBin.upperBoundWatts) / 2
Bogdan Timofte authored a month ago
883
                HStack {
884
                    Text("\(firstBin.lowerBoundWatts.format(decimalDigits: 3)) W")
885
                    Spacer()
Bogdan Timofte authored a month ago
886
                    Text("\(midpointWatts.format(decimalDigits: 3)) W")
887
                    Spacer()
Bogdan Timofte authored a month ago
888
                    Text("\(lastBin.upperBoundWatts.format(decimalDigits: 3)) W")
889
                }
890
                .font(.caption)
891
                .foregroundColor(.secondary)
892
                .monospacedDigit()
893
            }
894
        }
895
    }
896

            
897
    private var statisticsCard: some View {
898
        MeterInfoCardView(title: "Interesting Stats", tint: .indigo) {
899
            MeterInfoRowView(label: "Median", value: "\(measurement.medianPowerWatts.format(decimalDigits: 3)) W")
900
            MeterInfoRowView(label: "Minimum", value: "\(measurement.minimumPowerWatts.format(decimalDigits: 3)) W")
901
            MeterInfoRowView(label: "Maximum", value: "\(measurement.maximumPowerWatts.format(decimalDigits: 3)) W")
902
            MeterInfoRowView(label: "Spread σ", value: "\(measurement.standardDeviationPowerWatts.format(decimalDigits: 4)) W")
903
            MeterInfoRowView(label: "Variation", value: "\(Int((measurement.coefficientOfVariation * 100).rounded()))%")
904
            MeterInfoRowView(label: "Mean Current", value: "\(measurement.averageCurrentAmps.format(decimalDigits: 3)) A")
905
            MeterInfoRowView(label: "Mean Voltage", value: "\(measurement.averageVoltageVolts.format(decimalDigits: 3)) V")
906
            MeterInfoRowView(label: "Power Density", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W steady")
907
        }
908
    }
909

            
910
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
911
        if wattHours >= 1000 {
912
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
913
        }
914
        return "\(wattHours.format(decimalDigits: 2)) Wh"
915
    }
916
}