Meshtastic-Apple/Meshtastic/Views/Nodes/DeviceMetricsLog.swift

235 lines
7.1 KiB
Swift
Raw Normal View History

//
// DeviceMetricsLog.swift
// Meshtastic
//
// Copyright(c) Garth Vander Houwen 7/7/22.
//
import SwiftUI
import Charts
struct DeviceMetricsLog: View {
2023-04-04 19:29:03 -07:00
@Environment(\.managedObjectContext) var context
@EnvironmentObject var bleManager: BLEManager
2023-04-04 19:29:03 -07:00
@State private var isPresentingClearLogConfirm: Bool = false
@State var isExporting = false
@State var exportString = ""
2023-04-04 23:34:34 -07:00
@State private var batteryChartColor: Color = .blue
@State private var airtimeChartColor: Color = .orange
@State private var channelUtilizationChartColor: Color = .green
var node: NodeInfoEntity
2023-04-04 19:29:03 -07:00
var body: some View {
2023-03-30 18:38:33 -07:00
2023-08-06 17:41:46 -07:00
let oneWeekAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
2023-03-30 21:09:21 -07:00
let deviceMetrics = node.telemetries?.filtered(using: NSPredicate(format: "metricsType == 0")).reversed() as? [TelemetryEntity] ?? []
2023-03-31 12:08:42 -07:00
let chartData = deviceMetrics
2023-08-06 17:41:46 -07:00
.filter { $0.time != nil && $0.time! >= oneWeekAgo! }
2023-04-04 23:34:34 -07:00
.sorted { $0.time! < $1.time! }
NavigationStack {
2023-03-30 21:09:21 -07:00
2023-04-04 19:29:03 -07:00
if chartData.count > 0 {
2023-04-04 23:34:34 -07:00
GroupBox(label: Label("\(deviceMetrics.count) Readings Total", systemImage: "chart.xyaxis.line")) {
2023-04-04 19:29:03 -07:00
2023-04-04 23:34:34 -07:00
Chart {
2023-03-31 12:08:42 -07:00
2023-04-04 23:34:34 -07:00
ForEach(chartData, id: \.self) { point in
Plot {
LineMark(
x: .value("x", point.time!),
y: .value("y", point.batteryLevel)
)
}
.accessibilityLabel("Line Series")
.accessibilityValue("X: \(point.time!), Y: \(point.batteryLevel)")
.foregroundStyle(batteryChartColor)
2023-04-05 12:10:31 -07:00
.interpolationMethod(.cardinal)
2023-08-06 17:41:46 -07:00
//.interpolationMethod(.catmullRom(alpha: 1.0))
2023-04-04 23:34:34 -07:00
Plot {
PointMark(
x: .value("x", point.time!),
y: .value("y", point.channelUtilization)
)
}
.accessibilityLabel("Line Series")
.accessibilityValue("X: \(point.time!), Y: \(point.channelUtilization)")
.foregroundStyle(channelUtilizationChartColor)
RuleMark(y: .value("Limit", 10))
.lineStyle(StrokeStyle(lineWidth: 1, dash: [5, 10]))
.foregroundStyle(airtimeChartColor)
Plot {
PointMark(
x: .value("x", point.time!),
y: .value("y", point.airUtilTx)
)
}
.accessibilityLabel("Line Series")
.accessibilityValue("X: \(point.time!), Y: \(point.airUtilTx)")
.foregroundStyle(airtimeChartColor)
}
}
2023-04-04 23:34:34 -07:00
.chartXAxis(content: {
AxisMarks(position: .top)
})
.chartXAxis(.automatic)
2023-04-07 19:47:24 -07:00
.chartYScale(domain: 0...100)
2023-04-04 19:29:03 -07:00
.chartForegroundStyleScale([
2023-03-31 12:08:42 -07:00
"Battery Level" : .blue,
2023-04-01 03:46:32 -07:00
"Channel Utilization": .green,
2023-04-01 03:42:46 -07:00
"Airtime": .orange
2023-04-04 19:29:03 -07:00
])
.chartLegend(position: .automatic, alignment: .bottom)
}
2023-04-04 23:34:34 -07:00
.frame(minHeight: 250)
}
2022-12-31 00:26:59 -08:00
let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMMddjmma", options: 0, locale: Locale.current)
2023-01-12 07:57:24 -08:00
let dateFormatString = (localeDateFormat ?? "MM/dd/YY j:mma").replacingOccurrences(of: ",", with: "")
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
2023-03-30 18:38:33 -07:00
2023-03-06 10:33:18 -08:00
// Add a table for mac and ipad
2023-03-30 18:38:33 -07:00
//Table(Array(deviceMetrics),id: \.self) {
Table(deviceMetrics) {
2022-12-31 02:23:21 -08:00
TableColumn("battery.level") { dm in
2023-03-30 18:38:33 -07:00
if dm.batteryLevel > 100 {
Text("Powered")
} else {
Text("\(String(dm.batteryLevel))%")
}
}
2022-12-31 02:23:21 -08:00
TableColumn("voltage") { dm in
2023-03-30 18:38:33 -07:00
Text("\(String(format: "%.2f", dm.voltage))")
}
2022-12-31 02:23:21 -08:00
TableColumn("channel.utilization") { dm in
2023-04-22 22:55:58 -07:00
Text("\(String(format: "%.2f", dm.channelUtilization))%")
}
2022-12-31 02:23:21 -08:00
TableColumn("airtime") { dm in
2023-03-30 18:38:33 -07:00
Text("\(String(format: "%.2f", dm.airUtilTx))%")
}
2022-12-31 02:23:21 -08:00
TableColumn("timestamp") { dm in
Text(dm.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized)
}
.width(min: 180)
}
} else {
ScrollView {
let columns = [
//GridItem(.flexible(minimum: 30, maximum: 60), spacing: 0.1),
GridItem(.flexible(minimum: 30, maximum: 45), spacing: 0.1),
GridItem(.flexible(minimum: 30, maximum: 50), spacing: 0.1),
GridItem(.flexible(minimum: 30, maximum: 70), spacing: 0.1),
GridItem(.flexible(minimum: 30, maximum: 65), spacing: 0.1),
GridItem(.flexible(minimum: 130, maximum: 200), spacing: 0.1)
]
LazyVGrid(columns: columns, alignment: .leading, spacing: 1) {
GridRow {
Text("Batt")
.font(.caption)
.fontWeight(.bold)
2022-12-31 00:26:59 -08:00
Text("Volt")
.font(.caption)
.fontWeight(.bold)
Text("ChUtil")
.font(.caption)
.fontWeight(.bold)
Text("AirTm")
.font(.caption)
.fontWeight(.bold)
2022-12-31 02:23:21 -08:00
Text("timestamp")
.font(.caption)
.fontWeight(.bold)
}
2023-03-30 18:38:33 -07:00
ForEach(deviceMetrics) { dm in
GridRow {
if dm.batteryLevel > 100 {
2023-03-30 21:09:21 -07:00
Text("PWD")
.font(.caption)
2023-03-30 18:38:33 -07:00
} else {
Text("\(String(dm.batteryLevel))%")
.font(.caption)
2022-09-14 07:29:31 -07:00
}
2023-03-30 18:38:33 -07:00
Text(String(dm.voltage))
.font(.caption)
Text("\(String(format: "%.2f", dm.channelUtilization))%")
.font(.caption)
Text("\(String(format: "%.2f", dm.airUtilTx))%")
.font(.caption)
Text(dm.time?.formattedDate(format: dateFormatString) ?? "Unknown time")
.font(.caption)
}
}
}
.padding(.leading, 15)
.padding(.trailing, 5)
}
}
}
HStack {
Button(role: .destructive) {
isPresentingClearLogConfirm = true
} label: {
Label("clear.log", systemImage: "trash.fill")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding(.bottom)
.padding(.trailing)
.confirmationDialog(
2022-12-13 08:47:14 -08:00
"are.you.sure",
isPresented: $isPresentingClearLogConfirm,
titleVisibility: .visible
) {
Button("device.metrics.delete", role: .destructive) {
if clearTelemetry(destNum: node.num, metricsType: 0, context: context) {
print("Cleared Device Metrics for \(node.num)")
} else {
print("Clear Device Metrics Log Failed")
}
}
}
Button {
2023-04-05 21:26:53 -07:00
exportString = telemetryToCsvFile(telemetry: deviceMetrics, metricsType: 0)
isExporting = true
} label: {
2022-12-12 20:35:38 -08:00
Label("save", systemImage: "square.and.arrow.down")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding(.bottom)
.padding(.trailing)
}
.navigationTitle("device.metrics.log")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing:
ZStack {
ConnectedDevice(bluetoothOn: bleManager.isSwitchedOn, deviceConnected: bleManager.connectedPeripheral != nil, name: (bleManager.connectedPeripheral != nil) ? bleManager.connectedPeripheral.shortName : "????")
})
.onAppear {
self.bleManager.context = context
}
.fileExporter(
isPresented: $isExporting,
document: CsvDocument(emptyCsv: exportString),
contentType: .commaSeparatedText,
defaultFilename: String("\(node.user?.longName ?? "Node") \("device.metrics.log".localized)"),
onCompletion: { result in
if case .success = result {
print("Device metrics log download succeeded.")
self.isExporting = false
} else {
print("Device metrics log download failed: \(result).")
}
}
)
}
}