Meshtastic-Apple/Meshtastic/Views/Settings/Config/Module/MQTTConfig.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

466 lines
18 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// MQTT.swift
// Meshtastic
//
// Copyright (c) Garth Vander Houwen 9/4/22.
//
import CoreLocation
import MeshtasticProtobufs
import OSLog
import SwiftUI
struct MQTTConfig: View {
@Environment(\.managedObjectContext) var context
@EnvironmentObject var accessoryManager: AccessoryManager
@Environment(\.dismiss) private var goBack
var node: NodeInfoEntity?
@State private var isPresentingSaveConfirm: Bool = false
@State var hasChanges: Bool = false
@State var enabled = false
@State var proxyToClientEnabled = false
@State var address = ""
@State var defaultServer = true
@State var showTls = true
@State var username = ""
@State var password = ""
@State var encryptionEnabled = true
@State var jsonEnabled = false
@State var tlsEnabled = false
@State var root = "msh"
@State var selectedTopic = ""
@State var mqttConnected: Bool = false
@State var defaultTopic = "msh/US"
@State var nearbyTopics = [String]()
@State var mapReportingEnabled = false
@AppStorage("mapReportingOptIn") private var mapReportingOptIn: Bool = false
@State private var mapPublishIntervalSecs: UpdateInterval = UpdateInterval(from: 3600)
@State var mapPositionPrecision: Double = 14.0
let locale = Locale.current
var body: some View {
VStack {
Form {
if node != nil && node?.loRaConfig != nil {
let rc = RegionCodes(rawValue: Int(node?.loRaConfig?.regionCode ?? 0))
if rc?.dutyCycle ?? 0 > 0 && rc?.dutyCycle ?? 0 < 100 {
Text("Your region has a \(rc?.dutyCycle ?? 0)% duty cycle. MQTT is not advised when you are duty cycle restricted, the extra traffic will quickly overwhelm your LoRa mesh.")
.font(.callout)
.foregroundColor(.red)
}
}
ConfigHeader(title: "MQTT", config: \.mqttConfig, node: node, onAppear: setMqttValues)
Section(header: Text("Options")) {
Toggle(isOn: $enabled) {
Label("Enabled", systemImage: "dot.radiowaves.up.forward")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
Toggle(isOn: $proxyToClientEnabled) {
Label("MQTT Client Proxy", systemImage: "iphone.radiowaves.left.and.right")
Text("Utilizes the network connection on your phone to connect to MQTT.")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if enabled && proxyToClientEnabled && node?.mqttConfig?.proxyToClientEnabled ?? false == true {
Toggle(isOn: $mqttConnected) {
Label("Connect to MQTT via Proxy", systemImage: "server.rack")
if accessoryManager.mqttError.count > 0 {
Text(accessoryManager.mqttError)
.fixedSize(horizontal: false, vertical: true)
.foregroundColor(.red)
}
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
Toggle(isOn: $encryptionEnabled) {
Label("Encryption Enabled", systemImage: "lock.icloud")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if !proxyToClientEnabled {
Toggle(isOn: $jsonEnabled) {
Label("JSON Enabled", systemImage: "ellipsis.curlybraces")
Text("JSON mode is a limited, unencrypted MQTT output for locally integrating with home assistant")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
}
Section(header: Text("Map Report")) {
Toggle(isOn: $mapReportingEnabled) {
Label("Enabled", systemImage: "map")
Text("Your node will periodically send an unencrypted map report packet to the configured MQTT server, this includes id, short and long name, approximate location, hardware model, role, firmware version, LoRa region, modem preset and primary channel name.")
.foregroundColor(.gray)
.font(.caption)
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
if mapReportingEnabled {
Text("Consent to Share Unencrypted Node Data via MQTT")
Text("By enabling this feature, you acknowledge and expressly consent to the transmission of your devices real-time geographic location over the MQTT protocol without encryption. This location data may be used for purposes such as live map reporting, device tracking, and related telemetry functions.")
.foregroundColor(.gray)
.font(.caption)
Text("Please be advised that because the map report is not encrypted, your data may be stored and displayed permanently by third parties. Meshtastic does not assume responsibility for any such storage, display or disclosure of this data.")
.foregroundColor(.gray)
.font(.caption)
Toggle(isOn: $mapReportingOptIn) {
Label("I have read and understand the above. I voluntarily consent to the unencrypted transmission of my node data via MQTT.", systemImage: "hand.raised")
.foregroundColor(.gray)
.font(.callout)
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
if mapReportingEnabled && mapReportingOptIn {
UpdateIntervalPicker(
config: .broadcastMedium,
pickerLabel: "Map Publish Interval",
selectedInterval: $mapPublishIntervalSecs
)
VStack(alignment: .leading) {
Label("Approximate Location", systemImage: "location.slash.circle.fill")
Text("To comply with privacy laws like CCPA and GDPR, we avoid sharing exact location data. Instead, we use anonymized or approximate (imprecise) location information to protect your privacy.")
.foregroundColor(.gray)
.font(.callout)
Slider(value: $mapPositionPrecision, in: 12...15, step: 1) {
} minimumValueLabel: {
Image(systemName: "plus")
} maximumValueLabel: {
Image(systemName: "minus")
}
Text(PositionPrecision(rawValue: Int(mapPositionPrecision))?.description ?? "")
.foregroundColor(.gray)
.font(.callout)
}
}
}
Section(header: Text("Root Topic")) {
HStack {
Label("Root Topic", systemImage: "tree")
TextField("Root Topic", text: $root)
.foregroundColor(.gray)
.onChange(of: root) {
var totalBytes = root.utf8.count
// Only mess with the value if it is too big
while totalBytes > 30 {
root = String(root.dropLast())
totalBytes = root.utf8.count
}
}
.foregroundColor(.gray)
}
.keyboardType(.asciiCapable)
.disableAutocorrection(true)
.listRowSeparator(.hidden)
Text("The root topic to use for MQTT.")
.foregroundColor(.gray)
.font(.callout)
if nearbyTopics.count > 0 {
Picker("Nearby Topics", selection: $selectedTopic ) {
ForEach(nearbyTopics, id: \.self) { nt in
Text(nt)
}
}
.pickerStyle(InlinePickerStyle())
.listRowSeparator(.hidden)
Text("If the default region topic is too busy you can choose a more local topic.")
.foregroundColor(.gray)
.font(.callout)
}
}
Section(header: Text("Server")) {
HStack {
Label("Address", systemImage: "server.rack")
TextField("Server Address", text: $address)
.foregroundColor(.gray)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: address) {
var totalBytes = address.utf8.count
// Only mess with the value if it is too big
while totalBytes > 62 {
address = String(address.dropLast())
totalBytes = address.utf8.count
}
hasChanges = true
}
.keyboardType(.default)
}
.autocorrectionDisabled()
if !defaultServer {
HStack {
Label("Username", systemImage: "person.text.rectangle")
TextField("Username", text: $username)
.foregroundColor(.gray)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: username) {
var totalBytes = username.utf8.count
// Only mess with the value if it is too big
while totalBytes > 62 {
username = String(username.dropLast())
totalBytes = username.utf8.count
}
hasChanges = true
}
.foregroundColor(.gray)
}
.keyboardType(.default)
HStack {
Label("Password", systemImage: "wallet.pass")
TextField("Password", text: $password)
.foregroundColor(.gray)
.autocapitalization(.none)
.disableAutocorrection(true)
.onChange(of: password) {
var totalBytes = password.utf8.count
// Only mess with the value if it is too big
while totalBytes > 30 {
password = String(password.dropLast())
totalBytes = password.utf8.count
}
hasChanges = true
}
.foregroundColor(.gray)
}
.keyboardType(.default)
.listRowSeparator(/*@START_MENU_TOKEN@*/.visible/*@END_MENU_TOKEN@*/)
}
if showTls {
Toggle(isOn: $tlsEnabled) {
Label("TLS Enabled", systemImage: "checkmark.shield.fill")
Text("Your MQTT Server must support TLS.")
}
.toggleStyle(SwitchToggleStyle(tint: .accentColor))
}
}
Text("For all Mqtt functionality other than the map report you must also set uplink and downlink for each channel you want to bridge over Mqtt.")
.font(.callout)
}
.scrollDismissesKeyboard(.immediately)
.disabled(!accessoryManager.isConnected || node?.mqttConfig == nil)
.safeAreaInset(edge: .bottom, alignment: .center) {
HStack(spacing: 0) {
SaveConfigButton(node: node, hasChanges: $hasChanges) {
let connectedNode = getNodeInfo(id: accessoryManager.activeDeviceNum ?? -1, context: context)
if connectedNode != nil {
var mqtt = ModuleConfig.MQTTConfig()
mqtt.enabled = self.enabled
mqtt.proxyToClientEnabled = self.proxyToClientEnabled
mqtt.address = self.address
mqtt.username = self.username
mqtt.password = self.password
mqtt.root = self.root
mqtt.encryptionEnabled = self.encryptionEnabled
mqtt.jsonEnabled = self.jsonEnabled
mqtt.tlsEnabled = self.tlsEnabled
mqtt.mapReportingEnabled = self.mapReportingEnabled
mqtt.mapReportSettings.shouldReportLocation = UserDefaults.mapReportingOptIn
mqtt.mapReportSettings.positionPrecision = UInt32(self.mapPositionPrecision)
mqtt.mapReportSettings.publishIntervalSecs = UInt32(self.mapPublishIntervalSecs.intValue)
Task {
do {
_ = try await accessoryManager.saveMQTTConfig(config: mqtt, fromUser: connectedNode!.user!, toUser: node!.user!)
Task { @MainActor in
// Should show a saved successfully alert once I know that to be true
// for now just disable the button after a successful save
hasChanges = false
goBack()
}
}
}
}
}
}
}.onChange(of: enabled) { _, newEnabled in
if newEnabled != node?.mqttConfig?.enabled { hasChanges = true }
}
.onChange(of: proxyToClientEnabled) { _, newProxyToClientEnabled in
if newProxyToClientEnabled {
jsonEnabled = false
tlsEnabled = false
}
if newProxyToClientEnabled != node?.mqttConfig?.proxyToClientEnabled { hasChanges = true }
}
.onChange(of: address) { _, newAddress in
if address.lowercased() == "mqtt.meshtastic.org" {
username = "meshdev"
password = "large4cats"
defaultServer = true
if proxyToClientEnabled {
showTls = false
}
} else {
defaultServer = false
showTls = true
}
if newAddress != node?.mqttConfig?.address ?? "" { hasChanges = true }
}
.onChange(of: username) { _, newUsername in
if newUsername != node?.mqttConfig?.username ?? "" { hasChanges = true }
}
.onChange(of: password) { _, newPassword in
if newPassword != node?.mqttConfig?.password ?? "" { hasChanges = true }
}
.onChange(of: root) { _, newRoot in
if newRoot != node?.mqttConfig?.root ?? "" { hasChanges = true }
}
.onChange(of: selectedTopic) { _, newSelectedTopic in
root = newSelectedTopic
}
.onChange(of: encryptionEnabled) { _, newEncryptionEnabled in
if newEncryptionEnabled != node?.mqttConfig?.encryptionEnabled { hasChanges = true }
}
.onChange(of: jsonEnabled) { _, newJsonEnabled in
if newJsonEnabled {
proxyToClientEnabled = false
}
if newJsonEnabled != node?.mqttConfig?.jsonEnabled { hasChanges = true }
}
.onChange(of: tlsEnabled) { _, newTlsEnabled in
if defaultServer {
tlsEnabled = false
} else {
if newTlsEnabled != node?.mqttConfig?.tlsEnabled { hasChanges = true }
}
}
.onChange(of: mqttConnected) { _, newMqttConnected in
if newMqttConnected == false {
if accessoryManager.mqttProxyConnected {
accessoryManager.mqttManager.disconnect()
}
} else {
if !accessoryManager.mqttProxyConnected && node != nil {
accessoryManager.mqttManager.connectFromConfigSettings(node: node!)
}
}
}
.onChange(of: mapReportingEnabled) { _, newMapReportingEnabled in
if newMapReportingEnabled != node?.mqttConfig?.mapReportingEnabled { hasChanges = true }
}
.onChange(of: mapPublishIntervalSecs.intValue) { _, newMapPublishIntervalSecs in
if newMapPublishIntervalSecs != node?.mqttConfig?.mapPublishIntervalSecs ?? -1 { hasChanges = true }
}
}
.navigationTitle("MQTT Config")
.navigationBarItems(
trailing: ZStack {
ConnectedDevice(
deviceConnected: accessoryManager.isConnected,
name: accessoryManager.activeConnection?.device.shortName ?? "?"
)
}
)
.onFirstAppear {
// Need to request a MqttModuleConfig from the remote node before allowing changes
if let deviceNum = accessoryManager.activeDeviceNum, let node {
let connectedNode = getNodeInfo(id: deviceNum, context: context)
if let connectedNode {
if node.num != deviceNum {
if UserDefaults.enableAdministration && node.num != deviceNum {
/// 2.5 Administration with session passkey
let expiration = node.sessionExpiration ?? Date()
if expiration < Date() || node.mqttConfig == nil {
Task {
do {
Logger.mesh.info("⚙️ Empty or expired mqtt module config requesting via PKI admin")
try await accessoryManager.requestMqttModuleConfig(fromUser: connectedNode.user!, toUser: node.user!)
} catch {
Logger.mesh.error("🚨 Mqtt module config request failed")
}
}
}
} else {
/// Legacy Administration
Logger.mesh.info("☠️ Using insecure legacy admin that is no longer supported, please upgrade your firmware.")
}
}
}
}
}
}
func setMqttValues() {
nearbyTopics = []
let geocoder = CLGeocoder()
if LocationsHandler.shared.locationsArray.count > 0 {
let region = RegionCodes(rawValue: Int(node?.loRaConfig?.regionCode ?? 0))
defaultTopic = "msh/" + (region?.topic ?? "UNSET")
geocoder.reverseGeocodeLocation(LocationsHandler.shared.locationsArray.first!, completionHandler: {(placemarks, error) in
if let error {
Logger.services.error("Failed to reverse geocode location: \(error.localizedDescription, privacy: .public)")
return
}
if let placemarks = placemarks, let placemark = placemarks.first {
/// Country Topic unless your region is a country
if !(region?.isCountry ?? false) {
let countryTopic = defaultTopic + "/" + (placemark.isoCountryCode ?? "")
if !countryTopic.isEmpty {
nearbyTopics.append(countryTopic)
}
}
let stateTopic = defaultTopic + "/" + (placemark.administrativeArea ?? "")
if !stateTopic.isEmpty {
nearbyTopics.append(stateTopic)
}
let countyTopic = defaultTopic + "/" + (placemark.administrativeArea ?? "") + "/" + (placemark.subAdministrativeArea?.lowercased().replacingOccurrences(of: " ", with: "") ?? "")
if !countyTopic.isEmpty {
nearbyTopics.append(countyTopic)
}
let cityTopic = defaultTopic + "/" + (placemark.administrativeArea ?? "") + "/" + (placemark.locality?.lowercased().replacingOccurrences(of: " ", with: "") ?? "")
if !cityTopic.isEmpty {
nearbyTopics.append(cityTopic)
}
let neightborhoodTopic = defaultTopic + "/" + (placemark.administrativeArea ?? "") + "/" + (placemark.subLocality?.lowercased()
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "'", with: "") ?? "")
if !neightborhoodTopic.isEmpty {
nearbyTopics.append(neightborhoodTopic)
}
} else {
Logger.services.debug("No Location")
}
})
}
self.enabled = node?.mqttConfig?.enabled ?? false
self.proxyToClientEnabled = node?.mqttConfig?.proxyToClientEnabled ?? false
self.address = node?.mqttConfig?.address ?? ""
if address.lowercased().contains("mqtt.meshtastic.org") {
defaultServer = true
} else {
defaultServer = false
}
self.username = node?.mqttConfig?.username ?? ""
self.password = node?.mqttConfig?.password ?? ""
self.root = node?.mqttConfig?.root ?? "msh"
self.encryptionEnabled = node?.mqttConfig?.encryptionEnabled ?? false
self.jsonEnabled = node?.mqttConfig?.jsonEnabled ?? false
self.tlsEnabled = node?.mqttConfig?.tlsEnabled ?? false
self.mqttConnected = accessoryManager.mqttProxyConnected
self.mapReportingEnabled = node?.mqttConfig?.mapReportingEnabled ?? false
if node?.mqttConfig?.mapPublishIntervalSecs ?? 0 < 3600 {
self.mapPublishIntervalSecs = UpdateInterval(from: 3600)
} else {
self.mapPublishIntervalSecs = UpdateInterval(from: Int(node?.mqttConfig?.mapPublishIntervalSecs ?? 3600))
}
self.mapPositionPrecision = Double(node?.mqttConfig?.mapPositionPrecision ?? 14)
self.mapReportingOptIn = UserDefaults.mapReportingOptIn
if mapPositionPrecision < 11 || mapPositionPrecision > 14 {
self.mapPositionPrecision = 14
self.hasChanges = true
} else {
self.hasChanges = false
}
}
}