Complete pax counter log

This commit is contained in:
Garth Vander Houwen 2024-02-25 21:40:25 -08:00
parent 003b6dbf18
commit 505e1128ed
8 changed files with 286 additions and 15 deletions

View file

@ -68,6 +68,27 @@ func detectionsToCsv(detections: [MessageEntity]) -> String {
return csvString
}
func paxToCsvFile(pax: [PaxCounterEntity]) -> String {
var csvString: String = ""
let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMMddjmma", options: 0, locale: Locale.current)
let dateFormatString = (localeDateFormat ?? "MM/dd/YY j:mma").replacingOccurrences(of: ",", with: "")
// Create PAX Header
csvString = "BLE, WiFi, Total Pax, Uptime, \("timestamp".localized)"
for p in pax {
csvString += "\n"
csvString += String(p.ble)
csvString += ", "
csvString += String(p.wifi)
csvString += ", "
csvString += String(p.ble + p.wifi)
csvString += ", "
csvString += String(p.uptime)
csvString += ", "
csvString += p.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized
}
return csvString
}
func positionToCsvFile(positions: [PositionEntity]) -> String {
var csvString: String = ""
let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMMddjmma", options: 0, locale: Locale.current)

View file

@ -31,6 +31,11 @@ extension NodeInfoEntity {
return traceRoutes?.count ?? 0 > 0
}
var hasPax: Bool {
return pax?.count ?? 0 > 0
}
var isStoreForwardRouter: Bool {
return storeForwardConfig?.isRouter ?? false
}

View file

@ -569,6 +569,7 @@ func paxCounterPacket (packet: MeshPacket, context: NSManagedObjectContext) {
return
}
mutablePax.add(newPax)
fetchedNode![0].pax = mutablePax
do {
try context.save()
} catch {

View file

@ -81,18 +81,6 @@ struct NodeDetail: View {
}
.disabled(!node.hasEnvironmentMetrics)
Divider()
NavigationLink {
DetectionSensorLog(node: node)
} label: {
Image(systemName: "sensor")
.symbolRenderingMode(.hierarchical)
.font(.title)
Text("Detection Sensor Log")
.font(.title3)
}
.disabled(!node.hasDetectionSensorMetrics)
Divider()
if #available(iOS 17.0, macOS 14.0, *) {
NavigationLink {
TraceRouteLog(node: node)
@ -107,6 +95,32 @@ struct NodeDetail: View {
.disabled(node.traceRoutes?.count ?? 0 == 0)
Divider()
}
NavigationLink {
DetectionSensorLog(node: node)
} label: {
Image(systemName: "sensor")
.symbolRenderingMode(.hierarchical)
.font(.title)
Text("Detection Sensor Log")
.font(.title3)
}
.disabled(!node.hasDetectionSensorMetrics)
Divider()
if node.hasPax {
NavigationLink {
PaxCounterLog(node: node)
} label: {
Image(systemName: "figure.walk.motion")
.symbolRenderingMode(.hierarchical)
.font(.title)
Text("paxcounter.log")
.font(.title3)
}
.disabled(!node.hasPax)
Divider()
}
}
if self.bleManager.connectedPeripheral != nil && node.metadata != nil {
HStack {

View file

@ -5,4 +5,227 @@
// Created by Garth Vander Houwen on 2/25/24.
//
import Foundation
import SwiftUI
import Charts
struct PaxCounterLog: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var bleManager: BLEManager
@State private var isPresentingClearLogConfirm: Bool = false
@State var isExporting = false
@State var exportString = ""
@State private var bleChartColor: Color = .blue
@State private var wifiChartColor: Color = .orange
@State private var paxChartColor: Color = .green
@ObservedObject var node: NodeInfoEntity
var body: some View {
VStack {
if node.hasPax {
let oneWeekAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
let pax = node.pax?.reversed() as? [PaxCounterEntity] ?? []
let chartData = pax
.filter { $0.time != nil && $0.time! >= oneWeekAgo! }
.sorted { $0.time! < $1.time! }
let maxValue = (chartData.map{ $0.wifi }.max() ?? 0) + (chartData.map{ $0.ble }.max() ?? 0) + 5
if chartData.count > 0 {
GroupBox(label: Label("\(pax.count) Readings Total", systemImage: "chart.xyaxis.line")) {
Chart {
ForEach(chartData, id: \.self) { point in
Plot {
PointMark(
x: .value("x", point.time!),
y: .value("y", (point.wifi + point.ble))
)
}
.accessibilityLabel("paxcounter.total")
.accessibilityValue("X: \(point.time!), Y: \(point.wifi + point.ble)")
.foregroundStyle(paxChartColor)
.interpolationMethod(.cardinal)
Plot {
PointMark(
x: .value("x", point.time!),
y: .value("y", point.wifi)
)
}
.accessibilityLabel("paxcounter.wifi")
.accessibilityValue("X: \(point.time!), Y: \(point.wifi)")
.foregroundStyle(wifiChartColor)
Plot {
PointMark(
x: .value("x", point.time!),
y: .value("y", point.ble)
)
}
.accessibilityLabel("paxcounter.ble")
.accessibilityValue("X: \(point.time!), Y: \(point.ble)")
.foregroundStyle(bleChartColor)
}
}
.chartXAxis(content: {
AxisMarks(position: .top)
})
.chartXAxis(.automatic)
.chartYScale(domain: 0...maxValue)
.chartForegroundStyleScale([
"BLE": .blue,
"WiFi": .orange,
"paxcounter.total".localized: .green
])
.chartLegend(position: .automatic, alignment: .bottom)
}
.frame(minHeight: 250)
}
let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMMddjmma", options: 0, locale: Locale.current)
let dateFormatString = (localeDateFormat ?? "MM/dd/YY j:mma").replacingOccurrences(of: ",", with: "")
if UIScreen.main.bounds.size.width > 768 && (UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac) {
// Add a table for mac and ipad
Table(pax) {
TableColumn("paxcounter.ble") { pc in
Text("\(pc.ble)")
}
TableColumn("paxcounter.wifi") { pc in
Text("\(pc.wifi)")
}
TableColumn("paxcounter.total") { pc in
Text("\(pc.wifi + pc.ble)")
}
TableColumn("paxcounter.uptime") { pc in
let now = Date.now
let later = now + TimeInterval(pc.uptime)
let components = (now..<later).formatted(.components(style: .condensedAbbreviated))
Text(components)
}
TableColumn("timestamp") { pc in
Text(pc.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized)
}
.width(min: 180)
}
} else {
ScrollView {
let columns = [
GridItem(.flexible(minimum: 20, maximum: 55), spacing: 0.1),
GridItem(.flexible(minimum: 20, maximum: 55), spacing: 0.1),
GridItem(.flexible(minimum: 20, maximum: 55), spacing: 0.1),
GridItem(.flexible(minimum: 60, maximum: 100), spacing: 0.1),
GridItem(.flexible(minimum: 130, maximum: 200), spacing: 0.1)
]
LazyVGrid(columns: columns, alignment: .leading, spacing: 1) {
GridRow {
Text("paxcounter.ble")
.font(.caption)
.fontWeight(.bold)
Text("paxcounter.wifi")
.font(.caption)
.fontWeight(.bold)
Text("Total")
.font(.caption)
.fontWeight(.bold)
Text("paxcounter.uptime")
.font(.caption)
.fontWeight(.bold)
Text("timestamp")
.font(.caption)
.fontWeight(.bold)
}
ForEach(pax) { pc in
GridRow {
Text(String(pc.ble))
.font(.caption)
Text(String(pc.wifi))
.font(.caption)
Text(String(pc.ble + pc.wifi))
.font(.caption)
let now = Date.now
let later = now + TimeInterval(pc.uptime)
let components = (now..<later).formatted(.components(style: .condensedAbbreviated))
Text(components)
.font(.caption)
Text(pc.time?.formattedDate(format: dateFormatString) ?? "unknown.age".localized)
.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(.leading)
.confirmationDialog(
"are.you.sure",
isPresented: $isPresentingClearLogConfirm,
titleVisibility: .visible
) {
Button("paxcounter.delete", role: .destructive) {
if clearTelemetry(destNum: node.num, metricsType: 0, context: context) {
print("Cleared Pax Counter for \(node.num)")
} else {
print("Clear Pax Counter Log Failed")
}
}
}
Button {
exportString = paxToCsvFile(pax: pax)
isExporting = true
} label: {
Label("save", systemImage: "square.and.arrow.down")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding(.bottom)
.padding(.trailing)
}
} else {
if #available (iOS 17, *) {
ContentUnavailableView("paxcounter.content.unavailable", systemImage: "slash.circle")
} else {
Text("paxcounter.content.unavailable")
}
}
}
.navigationTitle("paxcounter.log")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing:
ZStack {
ConnectedDevice(bluetoothOn: bleManager.isSwitchedOn, deviceConnected: bleManager.connectedPeripheral != nil, name: (bleManager.connectedPeripheral != nil) ? bleManager.connectedPeripheral.shortName : "?")
})
.onAppear {
if self.bleManager.context == nil {
self.bleManager.context = context
}
}
.fileExporter(
isPresented: $isExporting,
document: CsvDocument(emptyCsv: exportString),
contentType: .commaSeparatedText,
defaultFilename: String("\(node.user?.longName ?? "Node") \("paxcounter.log".localized)"),
onCompletion: { result in
if case .success = result {
print("PAX Counter log download succeeded.")
self.isExporting = false
} else {
print("PAX Counter log download failed: \(result).")
}
}
)
}
}

View file

@ -24,7 +24,7 @@ struct PaxCounterConfig: View {
Section {
Toggle(isOn: $enabled) {
Label("enabled", systemImage: "figure.walk.departure")
Label("enabled", systemImage: "figure.walk.motion")
Text("config.module.paxcounter.enabled.description")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))

View file

@ -290,7 +290,7 @@ struct Settings: View {
NavigationLink {
PaxCounterConfig(node: nodes.first(where: { $0.num == selectedNode }))
} label: {
Image(systemName: "figure.walk.departure")
Image(systemName: "figure.walk.motion")
.symbolRenderingMode(.hierarchical)
Text("config.module.paxcounter.settings")
}

View file

@ -251,6 +251,13 @@
"options"="Options";
"password"="Password";
"pause"="Pause";
"paxcounter.ble"="BLE";
"paxcounter.delete"="Delete all pax data?";
"paxcounter.wifi"="WiFi";
"paxcounter.uptime"="Uptime";
"paxcounter.content.unavailable"="No PAX Counter Logs";
"paxcounter.log"="PAX Counter Log";
"paxcounter.total"="Total PAX";
"phone.gps"="Phone GPS";
"phone.gps.interval.description"="How frequently your phone will send your location to the device, location updates to the mesh are managed by the device.";
"position"="Position";