Meshtastic-Apple/Meshtastic/Views/Settings/Channels.swift
Garth Vander Houwen b30dc8645a
2.7.6 Working Changes (#1479)
* Bump version

* Message list performance fixes into 2.7.6 (#1475)

* Remove extra want config call when adding a contact

* App badge and unnecessary notification fixes (#1455)

* - Fix for app badge not going to zero if a message arrives while you have that chat open
- Fix for push notifications popping up when a message is received while that chat is open

* Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message

* Fix: Channels help grammer fix (#1452)

* remove outdated TCP not available on Apple devices (#1450)

* Update initial onboarding view

* remove toggle gating for mac

* Update crash reporting opt out in real time

* Update onboarding text

* Use mDNS text records for node name

* TCP IP and port on the connection screen

* Hide app icon chooser on mac

* Infinite loop hang bugfixes and performance improvements for both `UserMessageList` and `ChannelMessageList` (#1465)

* 2.7.5 Working Changes (#1460)

* Remove extra want config call when adding a contact

* App badge and unnecessary notification fixes (#1455)

* - Fix for app badge not going to zero if a message arrives while you have that chat open
- Fix for push notifications popping up when a message is received while that chat is open

* Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message

* Fix: Channels help grammer fix (#1452)

* remove outdated TCP not available on Apple devices (#1450)

* Update initial onboarding view

* remove toggle gating for mac

* Update crash reporting opt out in real time

* Update onboarding text

---------

Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>

* UserEntity: add mostRecentMessage and unreadMessages with early exit when lastMessage is nil, and fetch 1 row (not N) otherwise

* UserList: replace 5 slow calls to user.messageList with new fast calls

* NodeList: always put the connected node at the top of list (if it matches the node filters)

* ChannelEntity: add faster mostRecentPrivateMessage and unreadMessages which fetch 1 row (not N)

* ChannelList: replace 5 calls to channel.allPrivateMessage with new fast calls

* Fix incorrect appState.unreadDirectMessages calculations

* MyInfoEntity: also fix unreadMessages count here to be fast, and use it for appState.unreadChannelMessages

* UserMessageList: use @FetchRequest to prevent the N^2 behavior that was happening in calls to allPrivateMessages

* Refactor ChannelEntityExtension and MyInfoEntityExtension to be more similar to UserEntityExtension

* Remove SwiftUI-infinite-loop-causing `.id(redrawTapbacksTrigger)` in ChannelMessageList and UserMessageList (duplicate row ids)

* MyInfoEntityExtension: exclude emoji tapbacks (which never get marked as read anyway) from unread message count

* Add SaveChannelLinkData so MessageText and MeshtasticApp can use .sheet(item: ...) and avoid infinite loop hang due to Binding rebuild

* ChannelMessageList and UserMessageList: switch to stable messageId for ForEach SwiftUI row identity

* ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification

* ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear

* ChannelMessageList and UserMessageList: block spurious markMessagesAsRead when this View is not active

---------

Co-authored-by: Garth Vander Houwen <garth@meshtastic.com>
Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>

* message-list-performance: revert scrolling changes (#1472)

* Revert e0f0b4a0f7 (ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear)

* Revert "ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification"

This reverts commit ee1a7c4415.

---------

Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>
Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu>

* Explicitly set unmessagable, seems unnessary

* Add back missing mesh map features

* Fix: "Retrieving nodes" significantly slower after reconnect  extracted from #1424 (#1477)

* Fix: "Retrieving nodes" significantly slower after reconnect (#1424)

The node database retrieval was calling context.save() for every single
NodeInfo packet received (250 saves for 250 nodes). This caused severe
performance degradation on reconnect when CoreData had accumulated state.

Root Cause:
- nodeInfoPacket() called context.save() immediately for each node
- With 250 nodes, this meant 250 individual CoreData save operations
- On first connection, CoreData is fresh and fast
- On reconnect, CoreData has accumulated change tracking, undo management,
  and memory pressure, making each save progressively slower
- This resulted in 10+ second retrieval times vs 1-2 seconds initially

Solution:
- Added deferSave parameter to nodeInfoPacket() function
- During database retrieval (.retrievingDatabase state), defer all saves
- Perform a single batch save when database retrieval completes
  (when NONCE_ONLY_DB configCompleteID is received)
- This reduces 250 saves to 1 save

Performance Impact:
- Eliminates N individual saves during node database sync
- Reduces database retrieval time back to 1-2 seconds on reconnect
- Matches first-connection performance consistently

Fixes #1424

* Revert *MessageListUnified files

---------

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

* Hide route lines filter from mesh map

* Mesh Map: fuzz imprecise locations so they're distinguishable and clickable at the highest zoom levels (#1478)

Co-authored-by: Garth Vander Houwen <garth@meshtastic.com>

* Fix bad merge

* Update Meshtastic/Extensions/CoreData/UserEntityExtension.swift

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

* Update Meshtastic/Views/Nodes/Helpers/Map/MapContent/MeshMapContent.swift

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

* Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift

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

* Update Meshtastic/Extensions/CoreData/MyInfoEntityExtension.swift

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

* Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift

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

* Keep list of previous manual connections (#1484)

* Keep list of previous manual connections

* More descriptive manual connection rows

* Merge fixes and new way to show IP on Connect view

---------

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

* Show who relayed messages (#1486)

* Add identification for node that relayed text messages and add count for ammount of relayers of your message

* Ack Relays

* upsertPositionPacket: don't use future timestamps to set node's lastHeard (#1488)

* R1 NEO

* Neo

* Update Meshtastic/Views/Settings/AppSettings.swift

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

* Remove bad if

* Git rid of extra environment variable

* Update Meshtastic/Accessory/Transports/TCP/TCPTransport.swift

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

* MeshMap performance: quick wins (#1490)

* MeshMap: change onMapCameraChange frequency to .onEnd so that zooming doesn't cause continuous SwiftUI reevaluation on every frame

* MeshMapContent: factor out reducedPrecisionMapCircles into a separate function

* MeshMapContent: when multiple reducedPrecisionCircles have the same (lat,lon,radius), just draw one (big perf boost in dense areas)

* NodeMap performance improvements for high # positions history (#1480)

* NodeMapContent: move Route Lines out of ForEach

* NodeMapContent: move Convex Hull out of ForEach

* NodeMapContent: Replace `position.nodePosition?` with `node`

* NodeMapContent: drop unnecessary LazyVStack in showNodeHistory

* NodeMapContent: hoist out nodeColorSwift

* Move lineCoords, loraCoords calculations within showRouteLines, showConvexHull respectively

* Hoist out repeated node.metadata?.positionFlags lookups / PositionFlags creation

* NodeMapContent: remove unused @State

* NodeMapSwiftUI: add NodeMapContentEquatableWrapper and NodeMapContentSignature to prevent frequent NodeMapContent recomputation and infinite render loops

* NodeMapSwiftUI: disable animation during SwiftUI transactions

* NodeMapContent: hoist nodeBorderColor and set allowsHitTesting(false) on history point views

* NodeMapContent: prerenderHistoryPointCircle and prerenderHistoryPointArrow to avoid thousands of vector draw operations

* NodeMapContent: Shared coordinate list for Route Lines and Convex Hull

* NodeMapContent.prerenderHistoryPointArrow: add .frame(width: 16, height: 16)

* Fix wantRangeTestPackets to correctly follow rangeTestConfig.enabled (#1489)

* Fix interval drop down formatter

* Clean up channel qr code functionality.

* perferredPeripheralId fix

* Set opt in

* Retry once 5 second timer. dont throw the error

* Queue for peripherals

* Fix: hoplimit of dms would always fallback to hops away of the node even when configured hops was higher (#1495)

* fix hops setting in dms

* Fix hops for exchange position

* Final fix

* Don't favorite client base

* Update device hardware

* Prevent nil environment metrics

* Bump datadog sdk

* fix setting device telemetry enabled (#1515)

* Update Muzi R1 Neo to actively supported

* fix setting device telemetry enabled

---------

Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Don't subscribe to mqtt topic if downlink is not on (#1501)

* Dont sub if no downlink

* moved reload mqtt connect config

* Preview enabled in connected devices (#1509)

* Update Muzi R1 Neo to actively supported

* Preview enabled in connected devices

* Fixing indentation

* Fixing indentation

---------

Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* UpdateCoreData.updateAnyPacketFrom: mirror firmware's lastHeard/snr/rssi/hopsAway update logic from NodeDB::updateFrom (#1492)

* `CLIENT_BASE` add-favorite/role-change confirmation dialog (#1493)

* FavoriteNodeButton: refactor task out

* AccessoryManager.connectedDeviceRole helper

* FavoriteNodeButton: show confirmation dialog when a CLIENT_BASE is trying to add a favorite

* addContactFromURL: add comment referencing upcoming change in https://github.com/meshtastic/firmware/pull/8495

* DeviceConfig: role picker: show a warning when selecting CLIENT_BASE, similar to warning shown for ROUTER

* Adjust device configuration Client Base warning text

* Compass view (#1521)

* Added compass view

* Added Compass View

* Node colors in compass

* Update Muzi R1 Neo to actively supported

* Update PositionPopover.swift

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

* Update CompassView.swift

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

* Update CompassView.swift

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

* Update Meshtastic/Views/Helpers/CompassView.swift

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

* Update Meshtastic/Views/Helpers/CompassView.swift

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

---------

Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com>
Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Remove discovery queue

* revert problematic retry functionalliy

* format file

* Update & improve zh-Hans translation (#1523)

* Update Muzi R1 Neo to actively supported

* update & improve zh-Hans translation

rt

---------

Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Update protobufs to 2.7.1

* Add long-turbo preset

* Disable Range Test module when primary channel is public/unsecured (#1512)

* Update Muzi R1 Neo to actively supported

* Disable Range Test module when primary channel is public/unsecured

Updated RangeTestConfig.swift to determine whether the primary channel (index 0) is operating without encryption or with a 1-byte minimal PSK.

Disabled Range Test UI controls when on a public/default channel to prevent user interaction.

Added safety enforcement in the save operation: Range Test enabled flag is automatically forced to false before sending updates to the device.

Introduced a computed property isPrimaryChannelPublic following existing code patterns and security indicators (e.g., hexDescription PSK length).

Matches the behavior implemented in the Android client for consistent policy across platforms.

---------

Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>

* Add new device images

* Remove print statement, get rid of cut and paste error

---------

Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com>
Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com>
Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com>
Co-authored-by: Jake-B <jake-b@users.noreply.github.com>
Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu>
Co-authored-by: Martin Bogomolni <martinbogo@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: jake-b <1012393+jake-b@users.noreply.github.com>
Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com>
Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz>
Co-authored-by: Ben Meadors <benmmeadors@gmail.com>
Co-authored-by: Charles Pinesky <25388414+Vaidios@users.noreply.github.com>
Co-authored-by: Radio <35003866+radiolee@users.noreply.github.com>
Co-authored-by: Jason Houk <dubsectordevelopment@gmail.com>
2025-12-21 12:15:01 -08:00

414 lines
13 KiB
Swift

//
// Channels.swift
// Meshtastic Apple
//
// Copyright(c) Garth Vander Houwen 4/8/22.
//
import CoreData
import MapKit
import MeshtasticProtobufs
import OSLog
import SwiftUI
import TipKit
func generateChannelKey(size: Int) -> String {
var keyData = Data(count: size)
_ = keyData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, size, $0.baseAddress!)
}
return keyData.base64EncodedString()
}
struct Channels: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var accessoryManager: AccessoryManager
@Environment(\.dismiss) private var goBack
@Environment(\.sizeCategory) var sizeCategory
@Environment(\.colorScheme) private var colorScheme
var node: NodeInfoEntity?
@State var hasChanges = false
@State var hasValidKey = true
@State private var isPresentingSaveConfirm: Bool = false
@State var channelIndex: Int32 = 0
@State var channelName = ""
@State var channelKeySize = 16
@State var channelKey = "AQ=="
@State var channelRole = 0
@State var uplink = false
@State var downlink = false
@State var positionPrecision = 32.0
@State var preciseLocation = true
@State var positionsEnabled = true
@State var supportedVersion = true
@State var selectedChannel: ChannelEntity?
/// Minimum Version for granular position configuration
@State var minimumVersion = "2.2.24"
@State private var showingHelp = false
@FetchRequest(
sortDescriptors: [NSSortDescriptor(key: "favorite", ascending: false),
NSSortDescriptor(key: "lastHeard", ascending: false),
NSSortDescriptor(key: "user.longName", ascending: true)],
animation: .default)
var nodes: FetchedResults<NodeInfoEntity>
var body: some View {
VStack {
List {
TipView(CreateChannelsTip(), arrowEdge: .bottom)
.tipBackground(colorScheme == .dark ? Color(.systemBackground) : Color(.secondarySystemBackground))
.listRowSeparator(.hidden)
if node != nil && node?.myInfo != nil {
ForEach(node?.myInfo?.channels?.array as? [ChannelEntity] ?? [], id: \.self) { (channel: ChannelEntity) in
Button(action: {
channelIndex = channel.index
channelRole = Int(channel.role)
channelKey = channel.psk?.base64EncodedString() ?? ""
if channelKey.count == 0 {
channelKeySize = 0
} else if channelKey == "AQ==" {
channelKeySize = -1
} else if channelKey.count == 4 {
channelKeySize = 1
} else if channelKey.count == 24 {
channelKeySize = 16
} else if channelKey.count == 32 {
channelKeySize = 24
} else if channelKey.count == 44 {
channelKeySize = 32
}
channelName = channel.name ?? ""
uplink = channel.uplinkEnabled
downlink = channel.downlinkEnabled
positionPrecision = Double(channel.positionPrecision)
if !supportedVersion && channelRole == 1 {
positionPrecision = 32
preciseLocation = true
positionsEnabled = true
if channelKey == "AQ==" {
positionPrecision = 14
preciseLocation = false
}
} else if !supportedVersion && channelRole == 2 {
positionPrecision = 0
preciseLocation = false
positionsEnabled = false
} else {
if channelKey == "AQ==" {
preciseLocation = false
if (positionPrecision > 0 && positionPrecision < 11) || positionPrecision > 14 {
positionPrecision = 14
}
} else if positionPrecision == 32 {
preciseLocation = true
positionsEnabled = true
} else {
preciseLocation = false
}
if positionPrecision == 0 {
positionsEnabled = false
} else {
positionsEnabled = true
}
}
hasChanges = false
selectedChannel = channel
}) {
VStack(alignment: .leading) {
HStack {
CircleText(text: String(channel.index), color: .accentColor, circleSize: 45)
.padding(.trailing, 5)
.brightness(0.1)
VStack {
HStack {
ChannelLock(channel: channel)
if channel.name?.isEmpty ?? false {
if channel.role == 1 {
Text(String("PrimaryChannel").camelCaseToWords()).font(.headline)
} else {
Text(String("Channel \(channel.index)").camelCaseToWords()).font(.headline)
}
} else {
Text(String(channel.name ?? "Channel \(channel.index)").camelCaseToWords()).font(.headline)
}
}
}
}
}
}
}
}
}
.sheet(item: $selectedChannel) { _ in
#if targetEnvironment(macCatalyst)
Text("Channel")
.font(.largeTitle)
.padding()
#endif
ChannelForm(channelIndex: $channelIndex, channelName: $channelName, channelKeySize: $channelKeySize, channelKey: $channelKey, channelRole: $channelRole, uplink: $uplink, downlink: $downlink, positionPrecision: $positionPrecision, preciseLocation: $preciseLocation, positionsEnabled: $positionsEnabled, hasChanges: $hasChanges, hasValidKey: $hasValidKey, supportedVersion: $supportedVersion)
.presentationDetents([.large])
.presentationDragIndicator(.visible)
.onFirstAppear {
supportedVersion = accessoryManager.checkIsVersionSupported(forVersion: minimumVersion)
}
HStack {
Button {
var channel = Channel()
channel.index = channelIndex
channel.role = ChannelRoles(rawValue: channelRole)?.protoEnumValue() ?? .secondary
channel.index = channelIndex
channel.settings.name = channelName
channel.settings.psk = Data(base64Encoded: channelKey) ?? Data()
channel.settings.uplinkEnabled = uplink
channel.settings.downlinkEnabled = downlink
channel.settings.moduleSettings.positionPrecision = UInt32(positionPrecision)
selectedChannel!.role = Int32(channelRole)
selectedChannel!.index = channelIndex
selectedChannel!.name = channelName
selectedChannel!.psk = Data(base64Encoded: channelKey) ?? Data()
selectedChannel!.uplinkEnabled = uplink
selectedChannel!.downlinkEnabled = downlink
selectedChannel!.positionPrecision = Int32(positionPrecision)
guard let mutableChannels = node?.myInfo?.channels?.mutableCopy() as? NSMutableOrderedSet else {
return
}
if mutableChannels.contains(selectedChannel as Any) {
let replaceChannel = mutableChannels.first(where: { selectedChannel?.psk == ($0 as AnyObject).psk && selectedChannel?.name == ($0 as AnyObject).name})
mutableChannels.replaceObject(at: mutableChannels.index(of: replaceChannel as Any), with: selectedChannel as Any)
} else {
mutableChannels.add(selectedChannel as Any)
}
node?.myInfo?.channels = mutableChannels.copy() as? NSOrderedSet
context.refresh(selectedChannel!, mergeChanges: true)
if channel.role != Channel.Role.disabled {
do {
try context.save()
Logger.data.info("💾 Saved Channel: \(channel.settings.name, privacy: .public)")
} catch {
context.rollback()
let nsError = error as NSError
Logger.data.error("Unresolved Core Data error in the channel editor. Error: \(nsError, privacy: .public)")
}
} else {
let objects = selectedChannel?.allPrivateMessages ?? []
for object in objects {
context.delete(object)
}
for node in nodes where node.channel == channel.index {
context.delete(node)
}
context.delete(selectedChannel!)
do {
try context.save()
Logger.data.info("💾 Deleted Channel: \(channel.settings.name, privacy: .public)")
} catch {
context.rollback()
let nsError = error as NSError
Logger.data.error("Unresolved Core Data error in the channel editor. Error: \(nsError, privacy: .public)")
}
}
Task {
_ = try await accessoryManager.saveChannel(channel: channel, fromUser: node!.user!, toUser: node!.user!)
Task { @MainActor in
selectedChannel = nil
channelName = ""
channelRole = 2
hasChanges = false
}
accessoryManager.mqttManager.connectFromConfigSettings(node: node!)
}
} label: {
Label("Save", systemImage: "square.and.arrow.down")
}
.disabled(!accessoryManager.isConnected)// || !hasChanges)// !hasValidKey)
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding(.bottom)
#if targetEnvironment(macCatalyst)
Button {
goBack()
} label: {
Label("Close", systemImage: "xmark")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding(.bottom)
#endif
}
}
if node?.myInfo?.channels?.array.count ?? 0 < 8 && node != nil {
Button {
let channelIndexes = node?.myInfo?.channels?.compactMap({(ch) -> Int in
return (ch as AnyObject).index
})
let firstChannelIndex = firstMissingChannelIndex(channelIndexes ?? [])
channelKeySize = 16
let key = generateChannelKey(size: channelKeySize)
channelName = ""
channelIndex = Int32(firstChannelIndex)
channelRole = 2
channelKey = key
positionsEnabled = false
preciseLocation = false
positionPrecision = 0
uplink = false
downlink = false
let newChannel = ChannelEntity(context: context)
newChannel.id = channelIndex
newChannel.index = channelIndex
newChannel.uplinkEnabled = uplink
newChannel.downlinkEnabled = downlink
newChannel.name = channelName
newChannel.role = Int32(channelRole)
newChannel.psk = Data(base64Encoded: channelKey) ?? Data()
newChannel.positionPrecision = Int32(positionPrecision)
selectedChannel = newChannel
hasChanges = true
} label: {
Label("Add Channel", systemImage: "plus.square")
}
.buttonStyle(.bordered)
.buttonBorderShape(.capsule)
.controlSize(.large)
.padding()
}
}
.sheet(isPresented: $showingHelp) {
ChannelsHelp()
.presentationDetents([.large])
.presentationDragIndicator(.visible)
}
.safeAreaInset(edge: .bottom, alignment: .leading) {
HStack {
Button(action: {
withAnimation {
showingHelp = !showingHelp
}
}) {
Image(systemName: !showingHelp ? "questionmark.circle" : "questionmark.circle.fill")
.padding(.vertical, 5)
}
.tint(Color(UIColor.secondarySystemBackground))
.foregroundColor(.accentColor)
.buttonStyle(.borderedProminent)
}
.controlSize(.regular)
.padding(5)
}
.padding(.bottom, 5)
.navigationTitle("Channels")
.navigationBarItems(trailing:
ZStack {
ConnectedDevice(deviceConnected: accessoryManager.isConnected, name: accessoryManager.activeConnection?.device.shortName ?? "?")
})
}
}
func firstMissingChannelIndex(_ indexes: [Int]) -> Int {
let smallestIndex = 1
if indexes.isEmpty { return smallestIndex }
if smallestIndex <= indexes.count {
for element in smallestIndex...indexes.count where !indexes.contains(element) {
return element
}
}
return indexes.count + 1
}
enum PositionPrecision: Int, CaseIterable, Identifiable {
case two = 2
case three = 3
case four = 4
case five = 5
case six = 6
case seven = 7
case eight = 8
case nine = 9
case ten = 10
case eleven = 11
case twelve = 12
case thirteen = 13
case fourteen = 14
case fifteen = 15
case sixteen = 16
case seventeen = 17
case eightteen = 18
case nineteen = 19
case twenty = 20
case twentyone = 21
case twentytwo = 22
case twentythree = 23
case twentyfour = 24
var id: Int { self.rawValue }
var precisionMeters: Double {
switch self {
case .two:
return 5976446.981252
case .three:
return 2988223.4850600003
case .four:
return 1494111.7369640006
case .five:
return 747055.8629159998
case .six:
return 373527.9258920002
case .seven:
return 186763.95738000044
case .eight:
return 93381.97312400135
case .nine:
return 46690.98099600022
case .ten:
return 23345.48493200123
case .eleven:
return 11672.736900000944
case .twelve:
return 5836.362884000802
case .thirteen:
return 2918.1758760007315
case .fourteen:
return 1459.0823719999053
case .fifteen:
return 729.5356200010741
case .sixteen:
return 364.7622440000765
case .seventeen:
return 182.37555600115968
case .eightteen:
return 91.1822120001193
case .nineteen:
return 45.58554000039009
case .twenty:
return 22.787204001316468
case .twentyone:
return 11.388036000988677
case .twentytwo:
return 5.688452000824781
case .twentythree:
return 2.8386600007428338
case .twentyfour:
return 1.413763999910884
}
}
var description: String {
let distanceFormatter = MKDistanceFormatter()
return String.localizedStringWithFormat("Within %@".localized, String(distanceFormatter.string(fromDistance: precisionMeters)))
}
}