diff --git a/Localizable.xcstrings b/Localizable.xcstrings index 6fdfdd7f..6884e096 100644 --- a/Localizable.xcstrings +++ b/Localizable.xcstrings @@ -22432,6 +22432,28 @@ } } }, + "power.metrics.delete" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Delete all power metrics?" + } + } + } + }, + "power.metrics.log" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Power Metrics Log" + } + } + } + }, "Powered" : { "localizations" : { "de" : { diff --git a/Meshtastic.xcodeproj/project.pbxproj b/Meshtastic.xcodeproj/project.pbxproj index 672c6f72..76639ad7 100644 --- a/Meshtastic.xcodeproj/project.pbxproj +++ b/Meshtastic.xcodeproj/project.pbxproj @@ -38,6 +38,7 @@ 6DEDA55A2A957B8E00321D2E /* DetectionSensorLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DEDA5592A957B8E00321D2E /* DetectionSensorLog.swift */; }; 6DEDA55C2A9592F900321D2E /* MessageEntityExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DEDA55B2A9592F900321D2E /* MessageEntityExtension.swift */; }; 8D3F8A3F2D44BB02009EAAA4 /* PowerMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3F8A3E2D44BB02009EAAA4 /* PowerMetrics.swift */; }; + 8D3F8A412D44C2A6009EAAA4 /* PowerMetricsLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D3F8A402D44C2A6009EAAA4 /* PowerMetricsLog.swift */; }; B399E8A42B6F486400E4488E /* RetryButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B399E8A32B6F486400E4488E /* RetryButton.swift */; }; B3E905B12B71F7F300654D07 /* TextMessageField.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3E905B02B71F7F300654D07 /* TextMessageField.swift */; }; BCB613812C67290800485544 /* SendWaypointIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = BCB613802C67290800485544 /* SendWaypointIntent.swift */; }; @@ -293,6 +294,7 @@ 6DEDA55B2A9592F900321D2E /* MessageEntityExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageEntityExtension.swift; sourceTree = ""; }; 8D3F8A3D2D44B137009EAAA4 /* MeshtasticDataModelV 49.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = "MeshtasticDataModelV 49.xcdatamodel"; sourceTree = ""; }; 8D3F8A3E2D44BB02009EAAA4 /* PowerMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PowerMetrics.swift; sourceTree = ""; }; + 8D3F8A402D44C2A6009EAAA4 /* PowerMetricsLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PowerMetricsLog.swift; sourceTree = ""; }; B399E8A32B6F486400E4488E /* RetryButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RetryButton.swift; sourceTree = ""; }; B3E905B02B71F7F300654D07 /* TextMessageField.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TextMessageField.swift; sourceTree = ""; }; BCB613802C67290800485544 /* SendWaypointIntent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SendWaypointIntent.swift; sourceTree = ""; }; @@ -709,6 +711,7 @@ 6DEDA5592A957B8E00321D2E /* DetectionSensorLog.swift */, DD15E4F42B8BFC8E00654F61 /* PaxCounterLog.swift */, DDE5B4032B2279A700FCDD05 /* TraceRouteLog.swift */, + 8D3F8A402D44C2A6009EAAA4 /* PowerMetricsLog.swift */, ); path = Nodes; sourceTree = ""; @@ -1480,6 +1483,7 @@ DD1925B928CDA93900720036 /* SerialConfigEnums.swift in Sources */, 251926852C3BA97800249DF5 /* FavoriteNodeButton.swift in Sources */, D9C983A02B79D0E800BDBE6A /* AlertButton.swift in Sources */, + 8D3F8A412D44C2A6009EAAA4 /* PowerMetricsLog.swift in Sources */, DD86D4112881D16900BAEB7A /* WriteCsvFile.swift in Sources */, DD6F65762C6EA5490053C113 /* AckErrors.swift in Sources */, DDDB445029F8AC9C00EE2349 /* UIImage.swift in Sources */, diff --git a/Meshtastic/Export/WriteCsvFile.swift b/Meshtastic/Export/WriteCsvFile.swift index 56776554..40913ea7 100644 --- a/Meshtastic/Export/WriteCsvFile.swift +++ b/Meshtastic/Export/WriteCsvFile.swift @@ -46,6 +46,25 @@ func telemetryToCsvFile(telemetry: [TelemetryEntity], metricsType: Int) -> Strin csvString += ", " csvString += dm.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized } + } else if metricsType == 2 { + // Create Power Metrics Header + csvString = "Channel 1 Voltage, Channel 1 Current, Channel 2 Voltage, Channel 2 Current, Channel 3 Voltage, Channel 3 Current, \("timestamp".localized)" + for dm in telemetry where dm.metricsType == 2 { + csvString += "\n" + csvString += String(dm.powerCh1Voltage) + csvString += ", " + csvString += String(dm.powerCh1Current) + csvString += ", " + csvString += String(dm.powerCh2Voltage) + csvString += ", " + csvString += String(dm.powerCh2Current) + csvString += ", " + csvString += String(dm.powerCh3Voltage) + csvString += ", " + csvString += String(dm.powerCh3Current) + csvString += ", " + csvString += dm.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized + } } return csvString } diff --git a/Meshtastic/Views/Nodes/PowerMetricsLog.swift b/Meshtastic/Views/Nodes/PowerMetricsLog.swift index 9feb4b98..4e0629a6 100644 --- a/Meshtastic/Views/Nodes/PowerMetricsLog.swift +++ b/Meshtastic/Views/Nodes/PowerMetricsLog.swift @@ -8,23 +8,51 @@ import Foundation import SwiftUI import Charts +import OSLog struct PowerMetricsLog: View { + @Environment(\.managedObjectContext) var context + @EnvironmentObject var bleManager: BLEManager @ObservedObject var node: NodeInfoEntity private var idiom: UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom } @State private var sortOrder = [KeyPathComparator(\TelemetryEntity.time, order: .reverse)] @State private var selection: TelemetryEntity.ID? @State private var chartSelection: Date? + @State private var isPresentingClearLogConfirm: Bool = false + @State var isExporting = false + @State var exportString = "" @State private var channelSelection = 0 + var powerMetrics: [TelemetryEntity] { + let telemetries = node.telemetries?.filtered(using: NSPredicate(format: "metricsType == 2")) + return (telemetries?.reversed() as? [TelemetryEntity]) ?? [] + } + + var minMax: (min: Double, max: Double) { + let allValues = powerMetrics.flatMap { [ + $0.powerCh1Voltage, + $0.powerCh1Current, + $0.powerCh2Voltage, + $0.powerCh2Current, + $0.powerCh3Voltage, + $0.powerCh3Current + ]} + + guard !allValues.isEmpty else { + return (min: -10, max: 10) + } + + return (min: floor(Double(allValues.min()!)), max: ceil(Double(allValues.max()!))) + } + var body: some View { VStack { if node.hasPowerMetrics { let oneWeekAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date()) - let powerMetrics = node.telemetries?.filtered(using: NSPredicate(format: "metricsType == 2")).reversed() as? [TelemetryEntity] ?? [] + let chartData = powerMetrics .filter { $0.time != nil && $0.time! >= oneWeekAgo! } .sorted { $0.time! < $1.time! } @@ -75,19 +103,85 @@ struct PowerMetricsLog: View { }) .chartXAxis(.automatic) .chartXSelection(value: $chartSelection) - .chartYScale(domain: -10...10) + .chartYScale(domain: minMax.min...minMax.max) .chartForegroundStyleScale([ "Voltage": .blue, "Current": .green ]) .chartLegend(position: .automatic, alignment: .bottom) - } } let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMdjmma", options: 0, locale: Locale.current) let dateFormatString = (localeDateFormat ?? "M/d/YY j:mma").replacingOccurrences(of: ",", with: "") if idiom == .phone { + Table(powerMetrics, selection: $selection, sortOrder: $sortOrder) { + TableColumn("Timestamp") { m in + HStack { + Text(m.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized) + Spacer() + HStack { + VStack { + Text("Channel 1") + HStack { + Image(systemName: "powerplug.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh1Voltage))V") + } + HStack { + Image(systemName: "bolt.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh1Current))mA") + } + } + } + Spacer() + HStack { + VStack { + Text("Channel 2") + HStack { + Image(systemName: "powerplug.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh2Voltage))V") + } + HStack { + Image(systemName: "bolt.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh2Current))mA") + } + } + } + Spacer() + HStack { + VStack { + Text("Channel 3") + HStack { + Image(systemName: "powerplug.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh3Voltage))V") + } + HStack { + Image(systemName: "bolt.fill") + .font(.caption) + .symbolRenderingMode(.multicolor) + Text("\(String(format: "%.2f", m.powerCh3Current))mA") + } + } + } + } + } + } + .onChange(of: selection) { _, newSelection in + guard let metrics = powerMetrics.first(where: { $0.id == newSelection }) else { + return + } + chartSelection = metrics.time + } } else { Table(powerMetrics, selection: $selection, sortOrder: $sortOrder) { TableColumn("Ch1 Voltage") { dm in @@ -126,9 +220,74 @@ struct PowerMetricsLog: View { } chartSelection = metrics.time } - } + HStack { + Button(role: .destructive) { + isPresentingClearLogConfirm = true + } label: { + Label("clear.log", systemImage: "trash.fill") + } + .buttonStyle(.bordered) + .buttonBorderShape(.capsule) + .controlSize(idiom == .phone ? .regular : .large) + .padding(.bottom) + .padding(.leading) + .confirmationDialog( + "are.you.sure", + isPresented: $isPresentingClearLogConfirm, + titleVisibility: .visible + ) { + Button("power.metrics.delete", role: .destructive) { + if clearTelemetry(destNum: node.num, metricsType: 2, context: context) { + Logger.data.notice("Cleared Power Metrics for \(node.num)") + } else { + Logger.data.error("Clear Power Metrics Log Failed") + } + } + } + + Button { + exportString = telemetryToCsvFile(telemetry: powerMetrics, metricsType: 2) + isExporting = true + } label: { + Label("save", systemImage: "square.and.arrow.down") + } + .buttonStyle(.bordered) + .buttonBorderShape(.capsule) + .controlSize(idiom == .phone ? .regular : .large) + .padding(.bottom) + .padding(.trailing) + } + .onChange(of: selection) { _, newSelection in + guard let metrics = powerMetrics.first(where: { $0.id == newSelection }) else { + return + } + chartSelection = metrics.time + } + } else { + ContentUnavailableView("No Power Metrics", systemImage: "slash.circle") } } + .navigationTitle("power.metrics.log") + .navigationBarTitleDisplayMode(.inline) + .navigationBarItems(trailing: + ZStack { + ConnectedDevice(bluetoothOn: bleManager.isSwitchedOn, deviceConnected: bleManager.connectedPeripheral != nil, name: (bleManager.connectedPeripheral != nil) ? bleManager.connectedPeripheral.shortName : "?") + }) + .fileExporter( + isPresented: $isExporting, + document: CsvDocument(emptyCsv: exportString), + contentType: .commaSeparatedText, + defaultFilename: String("\(node.user?.longName ?? "Node") \("power.metrics.log".localized)"), + onCompletion: { result in + switch result { + case .success: + self.isExporting = false + Logger.services.info("Power metrics log download succeeded.") + case .failure(let error): + Logger.services.error("Power metrics log download failed: \(error.localizedDescription)") + } + } + ) } }