USB-Meter / USB Meter / Views / Meter / Tabs / Live / ChargerStandbyPowerWizardView.swift
Newer Older
926 lines | 38.585kb
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
    @State private var editMode: EditMode = .inactive
Bogdan Timofte authored a month ago
608

            
609
    let chargerID: UUID
610

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

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

            
647
                            Text(
648
                                "\(formattedDuration(measurement.duration)) • \(measurement.sampleCount) samples • \(standbyEnergyLabel(measurement.projectedYearlyEnergyWh)) / year"
649
                            )
650
                            .font(.caption)
651
                            .foregroundColor(.secondary)
652
                        }
653
                        .frame(maxWidth: .infinity, alignment: .leading)
654
                    }
655
                    .tag(measurement.id)
656
                }
657
                .onDelete { offsets in
658
                    let measurements = charger.standbyPowerMeasurements
659
                    for index in offsets {
660
                        guard measurements.indices.contains(index) else { continue }
661
                        let measurement = measurements[index]
662
                        _ = appData.deleteChargerStandbyMeasurement(
663
                            id: measurement.id,
664
                            chargerID: charger.id
665
                        )
666
                    }
667
                }
668
            }
669
        }
Bogdan Timofte authored a month ago
670
        .environment(\.editMode, $editMode)
Bogdan Timofte authored a month ago
671
        .navigationTitle("Saved Measurements")
672
        .toolbar {
673
            ToolbarItem(placement: .primaryAction) {
Bogdan Timofte authored a month ago
674
                Button(editMode.isEditing ? "Done" : "Select") {
675
                    if editMode.isEditing {
676
                        editMode = .inactive
677
                        selectedMeasurementIDs.removeAll()
678
                    } else {
679
                        editMode = .active
680
                    }
681
                }
Bogdan Timofte authored a month ago
682
            }
683
        }
684

            
685
        if selectedMeasurementIDs.isEmpty {
686
            content
687
        } else {
688
            content.toolbar {
689
                ToolbarItem(placement: .destructiveAction) {
690
                    Button(role: .destructive) {
691
                        deleteMeasurements(
692
                            ids: selectedMeasurementIDs,
693
                            for: charger.id
694
                        )
695
                    } label: {
696
                        Image(systemName: "trash")
697
                    }
698
                }
699
            }
700
        }
701
    }
702

            
Bogdan Timofte authored a month ago
703
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
704
        if wattHours >= 1000 {
705
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
706
        }
707
        return "\(wattHours.format(decimalDigits: 2)) Wh"
708
    }
709

            
710
    private func formattedDuration(_ duration: TimeInterval) -> String {
711
        let formatter = DateComponentsFormatter()
712
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
713
        formatter.unitsStyle = .abbreviated
714
        formatter.zeroFormattingBehavior = .pad
715
        return formatter.string(from: max(duration, 0)) ?? "0s"
716
    }
Bogdan Timofte authored a month ago
717

            
718
    private func deleteMeasurements(ids: Set<UUID>, for chargerID: UUID) {
719
        for id in ids {
720
            _ = appData.deleteChargerStandbyMeasurement(id: id, chargerID: chargerID)
721
        }
722
        selectedMeasurementIDs.removeAll()
Bogdan Timofte authored a month ago
723
        editMode = .inactive
Bogdan Timofte authored a month ago
724
    }
Bogdan Timofte authored a month ago
725
}
726

            
727
struct ChargerStandbyPowerMeasurementDetailView: View {
728
    @EnvironmentObject private var appData: AppData
Bogdan Timofte authored a month ago
729
    @Environment(\.dismiss) private var dismiss
730

            
731
    @State private var deleteConfirmationVisibility = false
Bogdan Timofte authored a month ago
732

            
733
    let chargerID: UUID
734
    let measurementID: UUID
735

            
736
    var body: some View {
737
        Group {
738
            if let charger = appData.chargedDeviceSummary(id: chargerID),
739
               let measurement = charger.standbyPowerMeasurements.first(where: { $0.id == measurementID }) {
740
                ScrollView {
741
                    VStack(spacing: 18) {
742
                        MeterInfoCardView(title: charger.name, tint: .orange) {
743
                            MeterInfoRowView(label: "Saved", value: measurement.endedAt.format())
744
                            MeterInfoRowView(label: "Average", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
745
                            MeterInfoRowView(label: "Samples", value: "\(measurement.sampleCount)")
746
                            MeterInfoRowView(label: "Duration", value: formattedDuration(measurement.duration))
747
                        }
748

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

            
797
    private func formattedDuration(_ duration: TimeInterval) -> String {
798
        let formatter = DateComponentsFormatter()
799
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
800
        formatter.unitsStyle = .abbreviated
801
        formatter.zeroFormattingBehavior = .pad
802
        return formatter.string(from: max(duration, 0)) ?? "0s"
803
    }
804
}
805

            
806
private struct ChargerStandbyPowerMeasurementSnapshotView: View {
807
    let measurement: ChargerStandbyPowerMeasurementSummary
808

            
809
    var body: some View {
810
        VStack(spacing: 18) {
811
            stabilityCard
812
            projectionCard
813
            distributionCard
814
            statisticsCard
815
        }
816
    }
817

            
818
    private var stabilityCard: some View {
819
        VStack(alignment: .leading, spacing: 10) {
820
            HStack {
821
                VStack(alignment: .leading, spacing: 4) {
822
                    Text(measurement.isStable ? "Enough Samples" : "Still Settling")
823
                        .font(.headline)
824
                    Text("Saved \(measurement.endedAt.format())")
825
                        .font(.caption)
826
                        .foregroundColor(.secondary)
827
                }
828

            
829
                Spacer()
830

            
831
                Text(measurement.isStable ? "Ready" : "Live")
832
                    .font(.caption.weight(.semibold))
833
                    .padding(.horizontal, 10)
834
                    .padding(.vertical, 6)
835
                    .foregroundColor(measurement.isStable ? .green : .orange)
836
                    .meterCard(
837
                        tint: measurement.isStable ? .green : .orange,
838
                        fillOpacity: 0.10,
839
                        strokeOpacity: 0.16,
840
                        cornerRadius: 999
841
                    )
842
            }
843

            
844
            Text("\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
845
                .font(.system(.largeTitle, design: .rounded).weight(.bold))
846
                .monospacedDigit()
847

            
848
            Text(
849
                "Recent drift: \((measurement.stabilityDeltaWatts * 1000).format(decimalDigits: 2)) mW, tolerance \((measurement.stabilityToleranceWatts * 1000).format(decimalDigits: 2)) mW over \(measurement.sampleCount) samples."
850
            )
851
            .font(.footnote)
852
            .foregroundColor(.secondary)
853
        }
854
        .frame(maxWidth: .infinity, alignment: .leading)
855
        .padding(18)
856
        .meterCard(
857
            tint: measurement.isStable ? .green : .orange,
858
            fillOpacity: 0.18,
859
            strokeOpacity: 0.24
860
        )
861
    }
862

            
863
    private var projectionCard: some View {
864
        MeterInfoCardView(
865
            title: "Consumption Projection",
866
            infoMessage: "These projections extrapolate only from the measured standby average. They do not say anything about charger behaviour under load.",
867
            tint: .teal
868
        ) {
869
            MeterInfoRowView(label: "Average Power", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
870
            MeterInfoRowView(label: "24 Hours", value: standbyEnergyLabel(measurement.projectedDailyEnergyWh))
871
            MeterInfoRowView(label: "7 Days", value: standbyEnergyLabel(measurement.projectedWeeklyEnergyWh))
872
            MeterInfoRowView(label: "30 Days", value: standbyEnergyLabel(measurement.projectedMonthlyEnergyWh))
873
            MeterInfoRowView(label: "1 Year", value: standbyEnergyLabel(measurement.projectedYearlyEnergyWh))
874
        }
875
    }
876

            
877
    private var distributionCard: some View {
878
        MeterInfoCardView(
879
            title: "Distribution",
880
            infoMessage: "Bars show how often each power interval appeared. The curve overlays a normal approximation around the observed mean and deviation.",
881
            tint: .orange
882
        ) {
883
            StandbyPowerHistogramView(
884
                histogram: measurement.histogram,
885
                averagePowerWatts: measurement.averagePowerWatts,
886
                standardDeviationPowerWatts: measurement.standardDeviationPowerWatts,
887
                tint: .orange
888
            )
889
            .frame(height: 220)
890

            
891
            if let firstBin = measurement.histogram.first, let lastBin = measurement.histogram.last {
Bogdan Timofte authored a month ago
892
                let midpointWatts = (firstBin.lowerBoundWatts + lastBin.upperBoundWatts) / 2
Bogdan Timofte authored a month ago
893
                HStack {
894
                    Text("\(firstBin.lowerBoundWatts.format(decimalDigits: 3)) W")
895
                    Spacer()
Bogdan Timofte authored a month ago
896
                    Text("\(midpointWatts.format(decimalDigits: 3)) W")
897
                    Spacer()
Bogdan Timofte authored a month ago
898
                    Text("\(lastBin.upperBoundWatts.format(decimalDigits: 3)) W")
899
                }
900
                .font(.caption)
901
                .foregroundColor(.secondary)
902
                .monospacedDigit()
903
            }
904
        }
905
    }
906

            
907
    private var statisticsCard: some View {
908
        MeterInfoCardView(title: "Interesting Stats", tint: .indigo) {
909
            MeterInfoRowView(label: "Median", value: "\(measurement.medianPowerWatts.format(decimalDigits: 3)) W")
910
            MeterInfoRowView(label: "Minimum", value: "\(measurement.minimumPowerWatts.format(decimalDigits: 3)) W")
911
            MeterInfoRowView(label: "Maximum", value: "\(measurement.maximumPowerWatts.format(decimalDigits: 3)) W")
912
            MeterInfoRowView(label: "Spread σ", value: "\(measurement.standardDeviationPowerWatts.format(decimalDigits: 4)) W")
913
            MeterInfoRowView(label: "Variation", value: "\(Int((measurement.coefficientOfVariation * 100).rounded()))%")
914
            MeterInfoRowView(label: "Mean Current", value: "\(measurement.averageCurrentAmps.format(decimalDigits: 3)) A")
915
            MeterInfoRowView(label: "Mean Voltage", value: "\(measurement.averageVoltageVolts.format(decimalDigits: 3)) V")
916
            MeterInfoRowView(label: "Power Density", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W steady")
917
        }
918
    }
919

            
920
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
921
        if wattHours >= 1000 {
922
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
923
        }
924
        return "\(wattHours.format(decimalDigits: 2)) Wh"
925
    }
926
}