Meshtastic-Apple/Meshtastic/Views/Nodes/Helpers/NodeListItem.swift
Garth Vander Houwen 9797eb9a0e
2.7.4 Working Changes (#1415)
* Update messaging list separator insets

* Dont show unread messages or notifications for emoji reactions matching iMessage.

* Restore ble state method (#1416)

* Restore BLE State

* Log privacy

* AccessoryManager to handle restored connection

* Comment task out

* Update restore state function based on conversation with jake

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Two Column Node List (#1425)

* Restore BLE State

* Log privacy

* AccessoryManager to handle restored connection

* Comment task out

* Switch the node list to a two column layout

* Keep asian translations of channel details string

* Update restore state function based on conversation with jake

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLETransport.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* always show node list search bar

* Update auto correct modifier

* Dont show online animations for ios 17, remove online animation from node map, remove online circle from position popover

* Work in progress.

* Update detents

* Gate the discovery process while restoring

* Use geometry reader to size weather tiles on node details

* Update BLE Transport

* Update location weather condistion styles

* Log privacy in didReceive

* Remove extra dividers from admin key config, fix onboarding typo

* Bump minimum catalyst target

* Bump mac target version

* Use @FetchRequest for UserList to try and use less memory on ios 17

* Revert change to @fetchrequest

* Stab in the dark for Devices crash

* Updated UserList (back?) to @FetchRequest

* Set mac minimum to 15

* Nil out continuation after use

* Use @FetchRequest for the node list to stop crashes on iOS 17

* Handle failed connections during restoration

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update protos

* Update protos

* Remove stale keys

* Serbian translations update (#1422)

* Log privacy

* Add Serbian translations

---------

Co-authored-by: Garth Vander Houwen <garthvh@yahoo.com>

* Clarify public key sub-text in security settings (#1412)

* Clarify public key sub-text in settings

* Trigger lint

* freq slot num pad (#1410)

* kill keyboard toolbar on lora config

* delete extranious scrollDismissesKeyboard

* Properly set catalyst target

* Update Meshtastic/Views/Onboarding/DeviceOnboarding.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Views/Settings/Config/SecurityConfig.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update Meshtastic/Enums/DeviceEnums.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Make current location nilable, remove log spam

* clean up toUser logic

* Fix telemetry entity not added in nodeInfoPacket

* fix typo: powerMetrics.hasChXCurrent mismatch

* Duplicate decoding of telemetry.current removed

* Clean up mesh map fetch request and distance filter logic

* Revert attempt to fix message logic

* Bump datadog version

* Missing message fix, attempt #2 (#1431)

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>

* Retry fewer times for longer

* Revert "Missing message fix, attempt #2 (#1431)" (#1432)

This reverts commit a96d318adb.

* Make retry 2 seconds

* Add back link to node details from position popover without navigation stack and link, clear notifications when deleting database

* Add clear notifications function

* Link from channel messages to node info

* Link to node details

* Discovery on retry fix

* Discovery on retry fix fix

* Add contact to device node db if you get an encrypted send faild routing error

* Seperate channel message view into two views for better performance.

* Refactor User Message List

* Update device hardware

Add liquid glass to config save button

* Save button cleanup

* Update button structure on users view

* Move encrypted send logic out of the router. Update protos

* Restore node long- and short- names (#1442)

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>

* Update Meshtastic/Accessory/Transports/Bluetooth Low Energy/BLEConnection.swift

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Revert routing error

* Toggle for enabling device telemetry broadcast enable

* Update

* Enhancements for interval dropdowns (#1445)

* Cleanup

* Fix core data version

* Add never to update interval

* Device telemetry Enabled Boolean (#1446)

* Update core data and interval picker

* Move formatter

* Rework to nest options under enabled

* Clearer names

* Safer devicehardware api call, remove node history filter from mesh map

* Fix build

* Simplify mesh map filter

* Remove stale translation keys

---------

Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Nikola Dašić <dasic.nikola@yandex.com>
Co-authored-by: Spencer Smith <dontaskspencer@gmail.com>
Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
2025-10-05 17:51:18 -07:00

310 lines
10 KiB
Swift

//
// NodeListItem.swift
// Meshtastic
//
// Created by Garth Vander Houwen on 9/8/23.
//
import SwiftUI
import CoreLocation
import Foundation
struct NodeListItem: View {
private var accessibilityDescription: String {
var desc = ""
if let shortName = node.user?.shortName {
desc = shortName.formatNodeNameForVoiceOver()
} else if let longName = node.user?.longName {
desc = longName
} else {
desc = "Unknown".localized + " " + "Node".localized
}
if isDirectlyConnected {
desc += ", currently connected"
}
if node.favorite {
desc += ", favorite"
}
if node.lastHeard != nil {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let relative = formatter.localizedString(for: node.lastHeard!, relativeTo: Date())
desc += ", last heard " + relative
}
if node.isOnline {
desc += ", online"
} else {
desc += ", offline"
}
let role = DeviceRoles(rawValue: Int(node.user?.role ?? 0))
if let roleName = role?.name {
desc += ", role: \(roleName)"
}
if node.hopsAway > 0 {
desc += ", \(node.hopsAway) hops away"
}
if let battery = node.latestDeviceMetrics?.batteryLevel {
if battery > 100 {
desc += ", " + "Plugged in".localized
} else if battery == 100 {
desc += ", " + "Charging".localized
} else {
desc += ", battery \(battery)%"
}
}
if !isDirectlyConnected, let (lastPosition, myCoord) = locationData {
let nodeCoord = CLLocation(latitude: lastPosition.nodeCoordinate!.latitude, longitude: lastPosition.nodeCoordinate!.longitude)
let metersAway = nodeCoord.distance(from: myCoord)
let distanceFormatter = LengthFormatter()
distanceFormatter.unitStyle = .medium
let formattedDistance = distanceFormatter.string(fromMeters: metersAway)
desc += ", " + String(format: "%@: %@", "Distance".localized, formattedDistance)
let trueBearing = getBearingBetweenTwoPoints(point1: myCoord, point2: nodeCoord)
let heading = Measurement(value: trueBearing, unit: UnitAngle.degrees)
let formattedHeading = heading.formatted(.measurement(width: .narrow, numberFormatStyle: .number.precision(.fractionLength(0))))
desc += ", " + "Heading".localized + " " + formattedHeading
}
if node.snr != 0 && !node.viaMqtt {
let signalStrength: BLESignalStrength
if node.snr < -10 {
signalStrength = .weak
} else if node.snr < 5 {
signalStrength = .normal
} else {
signalStrength = .strong
}
let signalString: String
switch signalStrength {
case .weak:
signalString = "Signal strength weak".localized
case .normal:
signalString = "Signal strength normal".localized
case .strong:
signalString = "Signal strength strong".localized
}
desc += ", " + signalString
}
return desc
}
@ObservedObject var node: NodeInfoEntity
var isDirectlyConnected: Bool
var connectedNode: Int64
var modemPreset: ModemPresets = ModemPresets(rawValue: UserDefaults.modemPreset) ?? ModemPresets.longFast
var userKeyStatus: (String, Color) {
var image = "lock.open.fill"
var color = Color.yellow
if node.user?.pkiEncrypted ?? false {
if !(node.user?.keyMatch ?? false) {
image = "key.slash"
color = .red
} else {
image = "lock.fill"
color = .green
}
}
return (image, color)
}
var locationData: (PositionEntity, CLLocation)? {
guard let lastPostion = node.positions?.lastObject as? PositionEntity else {
return nil
}
guard let currentLocation = LocationsHandler.shared.locationsArray.last else {
return nil
}
let myCoord = CLLocation(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude)
if lastPostion.nodeCoordinate != nil && myCoord.coordinate.longitude != LocationsHandler.DefaultLocation.longitude && myCoord.coordinate.latitude != LocationsHandler.DefaultLocation.latitude {
return (lastPostion, myCoord)
}
return nil
}
var body: some View {
LazyVStack(alignment: .leading) {
HStack {
VStack(alignment: .center) {
CircleText(text: node.user?.shortName ?? "?", color: Color(UIColor(hex: UInt32(node.num))), circleSize: 70)
.padding(.trailing, 5)
if node.latestDeviceMetrics != nil {
BatteryCompact(batteryLevel: node.latestDeviceMetrics?.batteryLevel ?? 0, font: .caption, iconFont: .callout, color: .accentColor)
.padding(.trailing, 5)
}
}
VStack(alignment: .leading) {
HStack {
let (image, color) = userKeyStatus
IconAndText(systemName: image,
imageColor: color,
text: node.user?.longName?.addingVariationSelectors ?? "Unknown".localized,
textColor: .primary)
if node.favorite {
Spacer()
Image(systemName: "star.fill")
.symbolRenderingMode(.multicolor)
}
}
if isDirectlyConnected {
IconAndText(systemName: "antenna.radiowaves.left.and.right.circle.fill",
imageColor: .green,
text: "Connected".localized)
}
if node.lastHeard?.timeIntervalSince1970 ?? 0 > 0 && node.lastHeard! < Calendar.current.date(byAdding: .year, value: 1, to: Date())! {
IconAndText(systemName: node.isOnline ? "checkmark.circle.fill" : "moon.circle.fill",
imageColor: node.isOnline ? .green : .orange,
text: node.lastHeard?.formatted() ?? "Unknown Age".localized)
}
let role = DeviceRoles(rawValue: Int(node.user?.role ?? 0))
IconAndText(systemName: role?.systemName ?? "figure",
text: "Role: \(role?.name ?? "Unknown".localized)")
if node.user?.unmessagable ?? false {
IconAndText(systemName: "iphone.slash",
renderingMode: .multicolor,
text: "Unmonitored")
}
if node.isStoreForwardRouter {
IconAndText(systemName: "envelope.arrow.triangle.branch",
renderingMode: .multicolor,
text: "Store & Forward".localized)
}
if node.positions?.count ?? 0 > 0 && connectedNode != node.num {
HStack {
if let (lastPostion, myCoord) = locationData {
let nodeCoord = CLLocation(latitude: lastPostion.nodeCoordinate!.latitude, longitude: lastPostion.nodeCoordinate!.longitude)
let metersAway = nodeCoord.distance(from: myCoord)
Image(systemName: "lines.measurement.horizontal")
.font(.callout)
.symbolRenderingMode(.multicolor)
.frame(width: 30)
DistanceText(meters: metersAway)
.font(UIDevice.current.userInterfaceIdiom == .phone ? .callout : .caption)
.foregroundColor(.gray)
let trueBearing = getBearingBetweenTwoPoints(point1: myCoord, point2: nodeCoord)
let headingDegrees = Measurement(value: trueBearing, unit: UnitAngle.degrees)
Image(systemName: "location.north")
.font(.callout)
.symbolRenderingMode(.multicolor)
.clipShape(Circle())
.rotationEffect(Angle(degrees: headingDegrees.value))
let heading = Measurement(value: trueBearing, unit: UnitAngle.degrees)
Text("\(heading.formatted(.measurement(width: .narrow, numberFormatStyle: .number.precision(.fractionLength(0)))))")
.font(UIDevice.current.userInterfaceIdiom == .phone ? .callout : .caption)
.foregroundColor(.gray)
}
}
}
HStack {
if node.channel > 0 {
IconAndText(systemName: "\(node.channel).circle.fill", text: "Channel")
}
if node.viaMqtt && connectedNode != node.num {
IconAndText(systemName: "dot.radiowaves.up.forward",
renderingMode: .multicolor,
text: "MQTT")
}
}
if node.hasPositions || node.hasEnvironmentMetrics || node.hasDetectionSensorMetrics || node.hasTraceRoutes {
HStack {
IconAndText(systemName: "scroll", text: "Logs:")
if node.hasDeviceMetrics {
DefaultIcon(systemName: "flipphone")
}
if node.hasPositions {
DefaultIcon(systemName: "mappin.and.ellipse")
}
if node.hasEnvironmentMetrics {
DefaultIcon(systemName: "cloud.sun.rain")
}
if node.hasDetectionSensorMetrics {
DefaultIcon(systemName: "sensor")
}
if node.hasTraceRoutes {
DefaultIcon(systemName: "signpost.right.and.left")
}
}
}
if node.hopsAway > 0 {
HStack {
IconAndText(systemName: "hare", text: "Hops Away:")
Image(systemName: "\(node.hopsAway).square")
.font(.title2)
}
} else {
if node.snr != 0 && !node.viaMqtt {
LoRaSignalStrengthMeter(snr: node.snr, rssi: node.rssi, preset: modemPreset, compact: true)
.padding(.top, node.hasPositions || node.hasEnvironmentMetrics || node.hasDetectionSensorMetrics || node.hasTraceRoutes ? 0 : 15)
}
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(.top, 4)
.padding(.bottom, 4)
.accessibilityElement(children: .ignore)
.accessibilityLabel(accessibilityDescription)
}
}
struct DefaultIcon: View {
let systemName: String
var body: some View {
Image(systemName: systemName)
.symbolRenderingMode(.hierarchical)
.font(.callout)
}
}
struct IconAndText: View {
let systemName: String
var imageColor: Color?
var renderingMode: SymbolRenderingMode = .hierarchical
let text: String
var textColor: Color = .gray
@ViewBuilder
var image: some View {
if let color = imageColor {
Image(systemName: systemName)
.foregroundColor(color)
} else {
Image(systemName: systemName)
}
}
var body: some View {
HStack {
image
.font(.callout)
.symbolRenderingMode(renderingMode)
.frame(width: 30)
Text(text)
.font(UIDevice.current.userInterfaceIdiom == .phone ? .callout : .caption)
.foregroundColor(textColor)
.allowsTightening(true)
}
}
}
#Preview {
VStack(alignment: .leading) {
IconAndText(systemName: "antenna.radiowaves.left.and.right.circle.fill", text: "foo")
IconAndText(systemName: "antenna.radiowaves.left.and.right.circle", text: "bar")
NodeListItem(node: {
let context = PersistenceController.preview.container.viewContext
let nodeInfo = NodeInfoEntity(context: context)
let user = UserEntity(context: context)
user.longName = "Test User"
user.shortName = "TU"
nodeInfo.user = user
return nodeInfo
}(), isDirectlyConnected: true, connectedNode: 0, modemPreset: .longFast)
}
}