USB-Meter / USB Meter / Views / Meter / Tabs / Live / ChargerStandbyPowerWizardView.swift
Newer Older
833 lines | 34.985kb
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 {
456
                HStack {
457
                    Text("\(firstBin.lowerBoundWatts.format(decimalDigits: 3)) W")
458
                    Spacer()
459
                    Text("\(lastBin.upperBoundWatts.format(decimalDigits: 3)) W")
460
                }
461
                .font(.caption)
462
                .foregroundColor(.secondary)
463
                .monospacedDigit()
464
            }
465
        }
466
    }
467

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

            
490
    private func startMeasurement() {
491
        guard let selectedCharger, let selectedMeter else {
492
            return
493
        }
494

            
495
        _ = appData.startChargerStandbyMeasurement(for: selectedCharger.id, on: selectedMeter)
496
    }
497

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

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

            
513
}
514

            
515
private struct StandbyPowerHistogramView: View {
516
    let histogram: [ChargerStandbyPowerDistributionBin]
517
    let averagePowerWatts: Double
518
    let standardDeviationPowerWatts: Double
519
    let tint: Color
520

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

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

            
539
                gaussianCurve(in: proxy.size)
540
                    .stroke(tint, style: StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))
541

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

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

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

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

            
570
                let x = progress * size.width
571
                let y = size.height - (normalizedHeight * (Double(size.height) * 0.92))
572
                let point = CGPoint(x: x, y: y)
573

            
574
                if index == 0 {
575
                    path.move(to: point)
576
                } else {
577
                    path.addLine(to: point)
578
                }
579
            }
580
        }
581
    }
582

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

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

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

            
601
struct ChargerStandbyPowerMeasurementsView: View {
602
    @EnvironmentObject private var appData: AppData
603

            
604
    let chargerID: UUID
605

            
606
    var body: some View {
607
        Group {
608
            if let charger = appData.chargedDeviceSummary(id: chargerID) {
609
                List {
610
                    if charger.standbyPowerMeasurements.isEmpty {
611
                        Text("No standby measurements saved yet.")
612
                            .foregroundColor(.secondary)
613
                    } else {
614
                        ForEach(charger.standbyPowerMeasurements) { measurement in
615
                            NavigationLink(
616
                                destination: ChargerStandbyPowerMeasurementDetailView(
617
                                    chargerID: charger.id,
618
                                    measurementID: measurement.id
619
                                )
620
                            ) {
621
                                VStack(alignment: .leading, spacing: 6) {
622
                                    HStack {
623
                                        Text(measurement.endedAt.format())
624
                                            .font(.subheadline.weight(.semibold))
625
                                        Spacer()
626
                                        Text("\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
627
                                            .font(.subheadline.weight(.bold))
628
                                            .monospacedDigit()
629
                                    }
630

            
631
                                    Text(
632
                                        "\(formattedDuration(measurement.duration)) • \(measurement.sampleCount) samples • \(standbyEnergyLabel(measurement.projectedYearlyEnergyWh)) / year"
633
                                    )
634
                                    .font(.caption)
635
                                    .foregroundColor(.secondary)
636
                                }
637
                                .frame(maxWidth: .infinity, alignment: .leading)
638
                            }
639
                        }
640
                    }
641
                }
642
                .navigationTitle("Saved Measurements")
643
            } else {
644
                Text("This charger is no longer available.")
645
                    .foregroundColor(.secondary)
646
                    .navigationTitle("Saved Measurements")
647
            }
648
        }
649
    }
650

            
651
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
652
        if wattHours >= 1000 {
653
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
654
        }
655
        return "\(wattHours.format(decimalDigits: 2)) Wh"
656
    }
657

            
658
    private func formattedDuration(_ duration: TimeInterval) -> String {
659
        let formatter = DateComponentsFormatter()
660
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute, .second] : [.minute, .second]
661
        formatter.unitsStyle = .abbreviated
662
        formatter.zeroFormattingBehavior = .pad
663
        return formatter.string(from: max(duration, 0)) ?? "0s"
664
    }
665
}
666

            
667
struct ChargerStandbyPowerMeasurementDetailView: View {
668
    @EnvironmentObject private var appData: AppData
669

            
670
    let chargerID: UUID
671
    let measurementID: UUID
672

            
673
    var body: some View {
674
        Group {
675
            if let charger = appData.chargedDeviceSummary(id: chargerID),
676
               let measurement = charger.standbyPowerMeasurements.first(where: { $0.id == measurementID }) {
677
                ScrollView {
678
                    VStack(spacing: 18) {
679
                        MeterInfoCardView(title: charger.name, tint: .orange) {
680
                            MeterInfoRowView(label: "Saved", value: measurement.endedAt.format())
681
                            MeterInfoRowView(label: "Average", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
682
                            MeterInfoRowView(label: "Samples", value: "\(measurement.sampleCount)")
683
                            MeterInfoRowView(label: "Duration", value: formattedDuration(measurement.duration))
684
                        }
685

            
686
                        ChargerStandbyPowerMeasurementSnapshotView(measurement: measurement)
687
                    }
688
                    .padding()
689
                }
690
                .background(
691
                    LinearGradient(
692
                        colors: [.orange.opacity(0.16), Color.clear],
693
                        startPoint: .topLeading,
694
                        endPoint: .bottomTrailing
695
                    )
696
                    .ignoresSafeArea()
697
                )
698
                .navigationTitle("Measurement")
699
            } else {
700
                Text("This measurement is no longer available.")
701
                    .foregroundColor(.secondary)
702
                    .navigationTitle("Measurement")
703
            }
704
        }
705
    }
706

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

            
716
private struct ChargerStandbyPowerMeasurementSnapshotView: View {
717
    let measurement: ChargerStandbyPowerMeasurementSummary
718

            
719
    var body: some View {
720
        VStack(spacing: 18) {
721
            stabilityCard
722
            projectionCard
723
            distributionCard
724
            statisticsCard
725
        }
726
    }
727

            
728
    private var stabilityCard: some View {
729
        VStack(alignment: .leading, spacing: 10) {
730
            HStack {
731
                VStack(alignment: .leading, spacing: 4) {
732
                    Text(measurement.isStable ? "Enough Samples" : "Still Settling")
733
                        .font(.headline)
734
                    Text("Saved \(measurement.endedAt.format())")
735
                        .font(.caption)
736
                        .foregroundColor(.secondary)
737
                }
738

            
739
                Spacer()
740

            
741
                Text(measurement.isStable ? "Ready" : "Live")
742
                    .font(.caption.weight(.semibold))
743
                    .padding(.horizontal, 10)
744
                    .padding(.vertical, 6)
745
                    .foregroundColor(measurement.isStable ? .green : .orange)
746
                    .meterCard(
747
                        tint: measurement.isStable ? .green : .orange,
748
                        fillOpacity: 0.10,
749
                        strokeOpacity: 0.16,
750
                        cornerRadius: 999
751
                    )
752
            }
753

            
754
            Text("\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
755
                .font(.system(.largeTitle, design: .rounded).weight(.bold))
756
                .monospacedDigit()
757

            
758
            Text(
759
                "Recent drift: \((measurement.stabilityDeltaWatts * 1000).format(decimalDigits: 2)) mW, tolerance \((measurement.stabilityToleranceWatts * 1000).format(decimalDigits: 2)) mW over \(measurement.sampleCount) samples."
760
            )
761
            .font(.footnote)
762
            .foregroundColor(.secondary)
763
        }
764
        .frame(maxWidth: .infinity, alignment: .leading)
765
        .padding(18)
766
        .meterCard(
767
            tint: measurement.isStable ? .green : .orange,
768
            fillOpacity: 0.18,
769
            strokeOpacity: 0.24
770
        )
771
    }
772

            
773
    private var projectionCard: some View {
774
        MeterInfoCardView(
775
            title: "Consumption Projection",
776
            infoMessage: "These projections extrapolate only from the measured standby average. They do not say anything about charger behaviour under load.",
777
            tint: .teal
778
        ) {
779
            MeterInfoRowView(label: "Average Power", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W")
780
            MeterInfoRowView(label: "24 Hours", value: standbyEnergyLabel(measurement.projectedDailyEnergyWh))
781
            MeterInfoRowView(label: "7 Days", value: standbyEnergyLabel(measurement.projectedWeeklyEnergyWh))
782
            MeterInfoRowView(label: "30 Days", value: standbyEnergyLabel(measurement.projectedMonthlyEnergyWh))
783
            MeterInfoRowView(label: "1 Year", value: standbyEnergyLabel(measurement.projectedYearlyEnergyWh))
784
        }
785
    }
786

            
787
    private var distributionCard: some View {
788
        MeterInfoCardView(
789
            title: "Distribution",
790
            infoMessage: "Bars show how often each power interval appeared. The curve overlays a normal approximation around the observed mean and deviation.",
791
            tint: .orange
792
        ) {
793
            StandbyPowerHistogramView(
794
                histogram: measurement.histogram,
795
                averagePowerWatts: measurement.averagePowerWatts,
796
                standardDeviationPowerWatts: measurement.standardDeviationPowerWatts,
797
                tint: .orange
798
            )
799
            .frame(height: 220)
800

            
801
            if let firstBin = measurement.histogram.first, let lastBin = measurement.histogram.last {
802
                HStack {
803
                    Text("\(firstBin.lowerBoundWatts.format(decimalDigits: 3)) W")
804
                    Spacer()
805
                    Text("\(lastBin.upperBoundWatts.format(decimalDigits: 3)) W")
806
                }
807
                .font(.caption)
808
                .foregroundColor(.secondary)
809
                .monospacedDigit()
810
            }
811
        }
812
    }
813

            
814
    private var statisticsCard: some View {
815
        MeterInfoCardView(title: "Interesting Stats", tint: .indigo) {
816
            MeterInfoRowView(label: "Median", value: "\(measurement.medianPowerWatts.format(decimalDigits: 3)) W")
817
            MeterInfoRowView(label: "Minimum", value: "\(measurement.minimumPowerWatts.format(decimalDigits: 3)) W")
818
            MeterInfoRowView(label: "Maximum", value: "\(measurement.maximumPowerWatts.format(decimalDigits: 3)) W")
819
            MeterInfoRowView(label: "Spread σ", value: "\(measurement.standardDeviationPowerWatts.format(decimalDigits: 4)) W")
820
            MeterInfoRowView(label: "Variation", value: "\(Int((measurement.coefficientOfVariation * 100).rounded()))%")
821
            MeterInfoRowView(label: "Mean Current", value: "\(measurement.averageCurrentAmps.format(decimalDigits: 3)) A")
822
            MeterInfoRowView(label: "Mean Voltage", value: "\(measurement.averageVoltageVolts.format(decimalDigits: 3)) V")
823
            MeterInfoRowView(label: "Power Density", value: "\(measurement.averagePowerWatts.format(decimalDigits: 3)) W steady")
824
        }
825
    }
826

            
827
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
828
        if wattHours >= 1000 {
829
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
830
        }
831
        return "\(wattHours.format(decimalDigits: 2)) Wh"
832
    }
833
}