Add noise floor

This commit is contained in:
Benjamin Faershtein 2026-01-17 19:30:01 -08:00
parent b30dc8645a
commit 8d74d06672
12 changed files with 492 additions and 4 deletions

View file

@ -2110,4 +2110,40 @@ extension AccessoryManager {
try await sendAdminMessageToRadio(meshPacket: meshPacket, adminDescription: messageDescription)
}
func sendLocalStatsRequest(destNum: Int64, wantResponse: Bool) async throws {
guard let fromNodeNum = self.activeConnection?.device.num else {
Logger.services.error("Error while sending local stats request. No active device.")
throw AccessoryError.ioFailed("No active device")
}
var telemetryPacket = Telemetry()
telemetryPacket.localStats = LocalStats()
var meshPacket = MeshPacket()
meshPacket.id = UInt32.random(in: UInt32(UInt8.max)..<UInt32.max)
meshPacket.to = UInt32(destNum)
meshPacket.from = UInt32(fromNodeNum)
meshPacket.wantAck = true
meshPacket.decoded.wantResponse = wantResponse
var dataMessage = DataMessage()
if let serializedData: Data = try? telemetryPacket.serializedData() {
dataMessage.payload = serializedData
dataMessage.portnum = PortNum.telemetryApp
dataMessage.wantResponse = wantResponse
meshPacket.decoded = dataMessage
} else {
throw AccessoryError.ioFailed("sendLocalStatsRequest: Unable to serialize telemetry packet")
}
var toRadio: ToRadio!
toRadio = ToRadio()
toRadio.packet = meshPacket
let logString = String.localizedStringWithFormat("📊 Sent Local Stats Request from: %@ to: %@".localized, String(fromNodeNum), String(destNum))
try await send(toRadio, debugDescription: logString)
Logger.mesh.info("📊 \(logString, privacy: .public)")
}
}

View file

@ -65,6 +65,33 @@ func telemetryToCsvFile<S: Sequence>(telemetry: S, metricsType: Int) -> String w
csvString += ", "
csvString += dm.time?.formattedDate(format: dateFormatString) ?? "Unknown Age".localized
}
} else if metricsType == 4 {
// Create Local Stats Header
csvString = "Noise Floor, Uptime, Relayed, Canceled, Dupes, Packets Tx, Packets Rx, Bad Rx, Nodes Online, Total Nodes, \("Timestamp".localized)"
for dm in telemetry where dm.metricsType == 4 {
csvString += "\n"
csvString += dm.noiseFloor?.formatted(.number.grouping(.never)) ?? ""
csvString += ", "
csvString += dm.uptimeSeconds?.formatted(.number.grouping(.never)) ?? ""
csvString += ", "
csvString += dm.numTxRelay.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numTxRelayCanceled.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numRxDupe.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numPacketsTx.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numPacketsRx.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numPacketsRxBad.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numOnlineNodes.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.numTotalNodes.formatted(.number.grouping(.never))
csvString += ", "
csvString += dm.time?.formattedDate(format: dateFormatString) ?? "Unknown Age".localized
}
}
return csvString
}

View file

@ -806,8 +806,9 @@ func telemetryPacket(packet: MeshPacket, connectedNode: Int64, context: NSManage
telemetry.numTxRelayCanceled = Int32(truncatingIfNeeded: telemetryMessage.localStats.numTxRelayCanceled)
telemetry.numOnlineNodes = Int32(truncatingIfNeeded: telemetryMessage.localStats.numOnlineNodes)
telemetry.numTotalNodes = Int32(truncatingIfNeeded: telemetryMessage.localStats.numTotalNodes)
telemetry.noiseFloor = telemetryMessage.localStats.noiseFloor
telemetry.metricsType = 4
Logger.statistics.info("📈 [Mesh Statistics] Channel Utilization: \(telemetryMessage.localStats.channelUtilization, privacy: .public) Airtime: \(telemetryMessage.localStats.airUtilTx, privacy: .public) Packets Sent: \(telemetryMessage.localStats.numPacketsTx, privacy: .public) Packets Received: \(telemetryMessage.localStats.numPacketsRx, privacy: .public) Bad Packets Received: \(telemetryMessage.localStats.numPacketsRxBad, privacy: .public) Nodes Online: \(telemetryMessage.localStats.numOnlineNodes, privacy: .public) of \(telemetryMessage.localStats.numTotalNodes, privacy: .public) nodes for Node: \(packet.from.toHex(), privacy: .public)")
Logger.statistics.info("📈 [Mesh Statistics] Channel Utilization: \(telemetryMessage.localStats.channelUtilization, privacy: .public) Airtime: \(telemetryMessage.localStats.airUtilTx, privacy: .public) Packets Sent: \(telemetryMessage.localStats.numPacketsTx, privacy: .public) Packets Received: \(telemetryMessage.localStats.numPacketsRx, privacy: .public) Bad Packets Received: \(telemetryMessage.localStats.numPacketsRxBad, privacy: .public) Noise Floor: \(telemetryMessage.localStats.noiseFloor, privacy: .public) Nodes Online: \(telemetryMessage.localStats.numOnlineNodes, privacy: .public) of \(telemetryMessage.localStats.numTotalNodes, privacy: .public) nodes for Node: \(packet.from.toHex(), privacy: .public)")
} else if telemetryMessage.variant == Telemetry.OneOf_Variant.powerMetrics(telemetryMessage.powerMetrics) {
Logger.data.info("📈 [Telemetry] Power Metrics Received for Node: \(packet.from.toHex(), privacy: .public)")
telemetry.powerCh1Voltage = telemetryMessage.powerMetrics.hasCh1Voltage.then(telemetryMessage.powerMetrics.ch1Voltage)

View file

@ -406,6 +406,7 @@
<attribute name="irLux" optional="YES" attributeType="Float" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="lux" optional="YES" attributeType="Float" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="metricsType" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="noiseFloor" optional="YES" attributeType="Float" defaultValueString="0.0" usesScalarValueType="YES"/>
<attribute name="numOnlineNodes" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="numPacketsRx" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>
<attribute name="numPacketsRxBad" optional="YES" attributeType="Integer 32" defaultValueString="0" usesScalarValueType="YES"/>

View file

@ -44,6 +44,7 @@ public class TelemetryEntity: NSManagedObject, Identifiable {
@ManagedAttribute<Float>(attributeName: "windSpeed") public var windSpeed: Float?
@ManagedAttribute<Float>(attributeName: "irLux") public var irLux: Float?
@ManagedAttribute<Float>(attributeName: "lux") public var lux: Float?
@ManagedAttribute<Float>(attributeName: "noiseFloor") public var noiseFloor: Float?
@ManagedAttribute<Float>(attributeName: "uvLux") public var uvLux: Float?
@ManagedAttribute<Float>(attributeName: "whiteLux") public var whiteLux: Float?
@ManagedAttribute<Float>(attributeName: "radiation") public var radiation: Float?

View file

@ -0,0 +1,51 @@
import SwiftUI
import OSLog
struct RequestLocalStatsButton: View {
@EnvironmentObject var accessoryManager: AccessoryManager
var node: NodeInfoEntity
@State
private var isPresentingLocalStatsSentAlert: Bool = false
var body: some View {
RateLimitedButton(key: "localstats", rateLimit: 30.0) {
Task {
do {
try await accessoryManager.sendLocalStatsRequest(
destNum: node.user?.num ?? 0,
wantResponse: true
)
Task {
isPresentingLocalStatsSentAlert = true
}
} catch {
Logger.mesh.warning("Failed to send local stats request: \(error)")
}
}
} label: { completion in
if let completion, completion.percentComplete > 0.0 {
Label {
Text("Local Stats (in \(Int(completion.secondsRemaining))s)")
.foregroundStyle(.secondary)
} icon: {
Image("progress.ring.dashed", variableValue: completion.percentComplete)
.foregroundStyle(.secondary)
}.disabled(true)
} else {
Label {
Text("Request Local Stats")
} icon: {
Image(systemName: "chart.bar")
.symbolRenderingMode(.hierarchical)
}
}
}
.alert("Local Stats Requested", isPresented: $isPresentingLocalStatsSentAlert) {
Button("OK", role: .cancel) { }
} message: {
Text("A local stats request has been sent to \(node.user?.longName ?? "this node"). Responses can some time.")
}
}
}

View file

@ -424,6 +424,17 @@ struct NodeDetail: View {
}
}
.disabled(!node.hasDetectionSensorMetrics)
NavigationLink {
LocalStatsLog(node: node)
} label: {
Label {
Text("Local Stats Log")
} icon: {
Image(systemName: "chart.bar")
.symbolRenderingMode(.multicolor)
}
}
.disabled(node.telemetries?.filtered(using: NSPredicate(format: "metricsType == 4")).count ?? 0 == 0)
if node.hasPax {
NavigationLink {
PaxCounterLog(node: node)
@ -464,6 +475,7 @@ struct NodeDetail: View {
node: node,
connectedNode: connectedNode
)
RequestLocalStatsButton(node: node)
TraceRouteButton(
node: node
)

View file

@ -0,0 +1,266 @@
//
// LocalStatsLog.swift
// Meshtastic
//
// Copyright(c) Benjamin Faershtein 1/17/26.
//
import SwiftUI
import Charts
import OSLog
struct LocalStatsLog: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var accessoryManager: AccessoryManager
private var idiom: UIUserInterfaceIdiom { UIDevice.current.userInterfaceIdiom }
@State private var isPresentingClearLogConfirm: Bool = false
@State var isExporting = false
@State var exportString = ""
@ObservedObject var node: NodeInfoEntity
@State private var sortOrder = [KeyPathComparator(\TelemetryEntity.time, order: .reverse)]
@State private var selection: TelemetryEntity.ID?
@State private var chartSelection: Date?
private var localStats: [TelemetryEntity] {
let filtered = node.telemetries?.filtered(using: NSPredicate(format: "metricsType == 4"))
return (filtered?.reversed() as? [TelemetryEntity]) ?? []
}
private var hasLocalStats: Bool {
!localStats.isEmpty
}
private var chartData: [TelemetryEntity] {
let oneWeekAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
return localStats.filter { $0.time != nil && $0.time! >= oneWeekAgo! }.sorted { $0.time! < $1.time! }
}
private var hasChartData: Bool {
!chartData.isEmpty
}
private var dateFormatString: String {
let localeDateFormat = DateFormatter.dateFormat(fromTemplate: "yyMdjmma", options: 0, locale: Locale.current)
return (localeDateFormat ?? "M/d/YY j:mma").replacingOccurrences(of: ",", with: "")
}
var body: some View {
VStack {
if hasLocalStats {
if hasChartData {
chartView
}
tableView
buttonView
} else {
ContentUnavailableView("No Local Stats", systemImage: "waveform")
}
}
.navigationTitle("Local Stats Log")
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(trailing:
ZStack {
ConnectedDevice(deviceConnected: accessoryManager.isConnected, name: accessoryManager.activeConnection?.device.shortName ?? "?")
})
.fileExporter(
isPresented: $isExporting,
document: CsvDocument(emptyCsv: exportString),
contentType: .commaSeparatedText,
defaultFilename: String("\(node.user?.longName ?? "Node") \("Local Stats Log".localized)"),
onCompletion: { result in
switch result {
case .success:
self.isExporting = false
Logger.services.info("Local stats log download succeeded.")
case .failure(let error):
Logger.services.error("Local stats log download failed: \(error.localizedDescription, privacy: .public)")
}
}
)
}
private var chartView: some View {
GroupBox(label: Label("\(localStats.count) Readings Total", systemImage: "waveform")) {
Chart(chartData) { point in
if let pointTime = point.time, let noiseFloor = point.noiseFloor {
LineMark(
x: .value("Time", pointTime),
y: .value("Noise Floor", noiseFloor)
)
.foregroundStyle(Color.accentColor)
.interpolationMethod(.linear)
}
RuleMark(y: .value("Icky", -85))
.lineStyle(StrokeStyle(lineWidth: 1, dash: [5, 5]))
.foregroundStyle(.red)
}
.chartXAxis(content: {
AxisMarks(position: .top)
})
.chartXSelection(value: $chartSelection)
.chartYScale(domain: -130 ... -60)
.chartForegroundStyleScale([
"Noise Floor": Color.accentColor
])
.chartLegend(position: .automatic, alignment: .bottom)
}
.frame(minHeight: 240)
}
@ViewBuilder
private var tableView: some View {
if idiom == .phone {
phoneTableView
} else {
macTableView
}
}
private var phoneTableView: some View {
Table(localStats, selection: $selection, sortOrder: $sortOrder) {
TableColumn("Local Stats") { ls in
HStack {
Text(ls.time?.formattedDate(format: dateFormatString) ?? "Unknown Age".localized)
.font(.caption)
.fontWeight(.semibold)
Spacer()
}
HStack {
if let noiseFloor = ls.noiseFloor, noiseFloor != 0 {
Text("Noise Floor \(noiseFloor.formatted(.number.precision(.fractionLength(1)))) dBm")
.foregroundColor(noiseFloorColor(noiseFloor))
} else {
Text("Noise Floor No Reading")
.foregroundColor(.gray)
}
Spacer()
}
HStack {
Text("Relayed: \(ls.numTxRelay)")
Text("Canceled: \(ls.numTxRelayCanceled)")
Text("Dupes: \(ls.numRxDupe)")
Spacer()
}
.font(.caption)
}
.width(ideal: 200, max: .infinity)
}
}
private var macTableView: some View {
Table(localStats, selection: $selection, sortOrder: $sortOrder) {
TableColumn("Noise Floor") { ls in
if let noiseFloor = ls.noiseFloor, noiseFloor != 0 {
Text("\(noiseFloor.formatted(.number.precision(.fractionLength(1)))) dBm")
.foregroundColor(noiseFloorColor(noiseFloor))
} else {
Text("No Reading")
.foregroundColor(.gray)
}
}
TableColumn("Uptime") { ls in
if let uptimeSeconds = ls.uptimeSeconds {
let now = Date.now
let later = now + TimeInterval(uptimeSeconds)
let components = (now..<later).formatted(.components(style: .narrow))
Text(components)
} else {
Text(Constants.nilValueIndicator)
}
}
.width(min: 100)
TableColumn("Relayed") { ls in
Text("\(ls.numTxRelay)")
}
.width(min: 80)
TableColumn("Canceled") { ls in
Text("\(ls.numTxRelayCanceled)")
}
.width(min: 80)
TableColumn("Dupes") { ls in
Text("\(ls.numRxDupe)")
}
.width(min: 80)
TableColumn("Packets Tx") { ls in
Text("\(ls.numPacketsTx)")
}
.width(min: 80)
TableColumn("Packets Rx") { ls in
Text("\(ls.numPacketsRx)")
}
.width(min: 80)
TableColumn("Bad Rx") { ls in
Text("\(ls.numPacketsRxBad)")
}
.width(min: 80)
TableColumn("Nodes Online") { ls in
Text("\(ls.numOnlineNodes)")
}
.width(min: 100)
TableColumn("Timestamp") { ls in
Text(ls.time?.formattedDate(format: dateFormatString) ?? "Unknown Age".localized)
}
.width(min: 180)
}
}
private var buttonView: some View {
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("Delete all local stats?", role: .destructive) {
if clearTelemetry(destNum: node.num, metricsType: 4, context: context) {
Logger.data.notice("Cleared Local Stats for \(node.num, privacy: .public)")
} else {
Logger.data.error("Clear Local Stats Log Failed")
}
}
}
Button {
exportString = telemetryToCsvFile(telemetry: localStats, metricsType: 4)
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 = localStats.first(where: { $0.id == newSelection }) else {
return
}
chartSelection = metrics.time
}
}
private func noiseFloorColor(_ value: Float) -> Color {
if value < -100 {
return .green
} else if value < -95 {
return .green
} else if value < -90 {
return .orange
} else {
return .red
}
}
}