diff --git a/.swiftlint.yml b/.swiftlint.yml index 665e90cc..f5682e26 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -51,3 +51,10 @@ nesting: type_level: warning: 3 +custom_rules: + disable_print: + included: ".*\\.swift" + name: "Disable `print()`" + regex: "((\\bprint)|(Swift\\.print))\\s*\\(" + message: "Consider using a dedicated log message or the Xcode debugger instead of using `print`. ex. logger.debug(...)" + severity: warning \ No newline at end of file diff --git a/Meshtastic.xcodeproj/project.pbxproj b/Meshtastic.xcodeproj/project.pbxproj index 2f62a9ee..4bc2d8c3 100644 --- a/Meshtastic.xcodeproj/project.pbxproj +++ b/Meshtastic.xcodeproj/project.pbxproj @@ -7,6 +7,7 @@ objects = { /* Begin PBXBuildFile section */ + 25183D462C0A6D97001E31D5 /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25183D452C0A6D97001E31D5 /* Logger.swift */; }; 6DA39D8E2A92DC52007E311C /* MeshtasticAppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DA39D8D2A92DC52007E311C /* MeshtasticAppDelegate.swift */; }; 6DEDA55A2A957B8E00321D2E /* DetectionSensorLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DEDA5592A957B8E00321D2E /* DetectionSensorLog.swift */; }; 6DEDA55C2A9592F900321D2E /* MessageEntityExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DEDA55B2A9592F900321D2E /* MessageEntityExtension.swift */; }; @@ -244,6 +245,7 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 25183D452C0A6D97001E31D5 /* Logger.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; }; 6DA39D8D2A92DC52007E311C /* MeshtasticAppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeshtasticAppDelegate.swift; sourceTree = ""; }; 6DEDA5592A957B8E00321D2E /* DetectionSensorLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DetectionSensorLog.swift; sourceTree = ""; }; 6DEDA55B2A9592F900321D2E /* MessageEntityExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageEntityExtension.swift; sourceTree = ""; }; @@ -943,6 +945,7 @@ DD964FBC296E6B01007C176F /* EmojiOnlyTextField.swift */, DDDB443C29F6592F00EE2349 /* NetworkManager.swift */, DD3619142B1EF9F900C41C8C /* LocationsHandler.swift */, + 25183D452C0A6D97001E31D5 /* Logger.swift */, ); path = Helpers; sourceTree = ""; @@ -1300,6 +1303,7 @@ D93068D32B8129510066FBC8 /* MessageContextMenuItems.swift in Sources */, DD0E20FE2B87090400F2D100 /* paxcount.pb.swift in Sources */, DD5E520A298EE33B00D21B61 /* channel.pb.swift in Sources */, + 25183D462C0A6D97001E31D5 /* Logger.swift in Sources */, DD8EBF43285058FA00426DCA /* DisplayConfig.swift in Sources */, DD964FC42974767D007C176F /* MapViewFitExtension.swift in Sources */, DD47E3D626F17ED900029299 /* CircleText.swift in Sources */, diff --git a/Meshtastic.xcodeproj/xcshareddata/xcschemes/WidgetsExtension.xcscheme b/Meshtastic.xcodeproj/xcshareddata/xcschemes/WidgetsExtension.xcscheme index bdda06e1..a5b2fa18 100644 --- a/Meshtastic.xcodeproj/xcshareddata/xcschemes/WidgetsExtension.xcscheme +++ b/Meshtastic.xcodeproj/xcshareddata/xcschemes/WidgetsExtension.xcscheme @@ -89,7 +89,6 @@ savedToolIdentifier = "" useCustomWorkingDirectory = "NO" debugDocumentVersioning = "YES" - askForAppToLaunch = "Yes" launchAutomaticallySubstyle = "2"> diff --git a/Meshtastic/Extensions/Color.swift b/Meshtastic/Extensions/Color.swift index 252eb361..7b7980f0 100644 --- a/Meshtastic/Extensions/Color.swift +++ b/Meshtastic/Extensions/Color.swift @@ -47,7 +47,6 @@ extension UIColor { let red = CGFloat((hex & 0xFF0000) >> 16) let green = CGFloat((hex & 0x00FF00) >> 8) let blue = CGFloat((hex & 0x0000FF)) - /// print("\(red) - \(green) - \(blue)") self.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: 1.0) } } diff --git a/Meshtastic/Extensions/FileManager.swift b/Meshtastic/Extensions/FileManager.swift index 175034ed..a5b5a78d 100644 --- a/Meshtastic/Extensions/FileManager.swift +++ b/Meshtastic/Extensions/FileManager.swift @@ -52,11 +52,13 @@ public extension FileManager { do { accumulatedSize += try contentItemURL.regularFileAllocatedSize() } catch { - print("đŸ’Ĩ File Manager Error: \(error.localizedDescription)") + logger.error("đŸ’Ĩ File Manager Error: \(error.localizedDescription)") } } - if let error = enumeratorError { print("đŸ’Ĩ AllocatedSizeOfDirectory enumeratorError = \(error.localizedDescription)") } + if let error = enumeratorError { + logger.error("đŸ’Ĩ AllocatedSizeOfDirectory enumeratorError = \(error.localizedDescription)") + } return Double(accumulatedSize).toBytes diff --git a/Meshtastic/Helpers/BLEManager.swift b/Meshtastic/Helpers/BLEManager.swift index 2ce38529..68267692 100644 --- a/Meshtastic/Helpers/BLEManager.swift +++ b/Meshtastic/Helpers/BLEManager.swift @@ -70,7 +70,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate func startScanning() { if isSwitchedOn { centralManager.scanForPeripherals(withServices: [meshtasticServiceCBUUID], options: [CBCentralManagerScanOptionAllowDuplicatesKey: false]) - print("✅ Scanning Started") + logger.info("✅ Scanning Started") } } @@ -78,7 +78,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate func stopScanning() { if centralManager.isScanning { centralManager.stopScan() - print("🛑 Stopped Scanning") + logger.info("🛑 Stopped Scanning") } } @@ -111,7 +111,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate self.timeoutTimerCount = 0 self.startScanning() } else { - print("🚨 BLE Connecting 2 Second Timeout Timer Fired \(timeoutTimerCount) Time(s): \(name)") + logger.info("🚨 BLE Connecting 2 Second Timeout Timer Fired \(self.timeoutTimerCount) Time(s): \(name)") } } @@ -124,7 +124,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate self.automaticallyReconnect = true } if connectedPeripheral != nil { - print("â„šī¸ BLE Disconnecting from: \(connectedPeripheral.name) to connect to \(peripheral.name ?? "Unknown")") + logger.info("â„šī¸ BLE Disconnecting from: \(self.connectedPeripheral.name) to connect to \(peripheral.name ?? "Unknown")") disconnectPeripheral() } @@ -138,7 +138,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate let context = ["name": "\(peripheral.name ?? "Unknown")"] timeoutTimer = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(timeoutTimerFired), userInfo: context, repeats: true) RunLoop.current.add(timeoutTimer!, forMode: .common) - print("â„šī¸ BLE Connecting: \(peripheral.name ?? "Unknown")") + logger.info("â„šī¸ BLE Connecting: \(peripheral.name ?? "Unknown")") } // Disconnect Connected Peripheral @@ -208,13 +208,13 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } // Discover Services peripheral.discoverServices([meshtasticServiceCBUUID]) - print("✅ BLE Connected: \(peripheral.name ?? "Unknown")") + logger.info("✅ BLE Connected: \(peripheral.name ?? "Unknown")") } // Called when a Peripheral fails to connect func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { cancelPeripheralConnection() - print("đŸšĢ BLE Failed to Connect: \(peripheral.name ?? "Unknown")") + logger.error("đŸšĢ BLE Failed to Connect: \(peripheral.name ?? "Unknown")") } // Disconnect Peripheral Event @@ -230,7 +230,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate if errorCode == 6 { // CBError.Code.connectionTimeout The connection has timed out unexpectedly. // Happens when device is manually reset / powered off lastConnectionError = "🚨" + String.localizedStringWithFormat("ble.errorcode.6 %@".localized, e.localizedDescription) - print("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") + logger.error("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") } else if errorCode == 7 { // CBError.Code.peripheralDisconnected The specified device has disconnected from us. // Seems to be what is received when a tbeam sleeps, immediately recconnecting does not work. if UserDefaults.preferredPeripheralId == peripheral.identifier.uuidString { @@ -247,11 +247,11 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate manager.schedule() } lastConnectionError = "🚨 \(e.localizedDescription)" - print("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") + logger.error("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") } else if errorCode == 14 { // Peer removed pairing information // Forgetting and reconnecting seems to be necessary so we need to show the user an error telling them to do that lastConnectionError = "🚨 " + String.localizedStringWithFormat("ble.errorcode.14 %@".localized, e.localizedDescription) - print("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(lastConnectionError)") + logger.error("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(self.lastConnectionError)") } else { if UserDefaults.preferredPeripheralId == peripheral.identifier.uuidString { manager.notifications = [ @@ -267,12 +267,12 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate manager.schedule() } lastConnectionError = "🚨 \(e.localizedDescription)" - print("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") + logger.error("🚨 BLE Disconnected: \(peripheral.name ?? "Unknown") Error Code: \(errorCode) Error: \(e.localizedDescription)") } } else { // Disconnected without error which indicates user intent to disconnect // Happens when swiping to disconnect - print("â„šī¸ BLE Disconnected: \(peripheral.name ?? "Unknown"): User Initiated Disconnect") + logger.info("â„šī¸ BLE Disconnected: \(peripheral.name ?? "Unknown"): User Initiated Disconnect") } // Start a scan so the disconnected peripheral is moved to the peripherals[] if it is awake self.startScanning() @@ -280,14 +280,14 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate // MARK: Peripheral Services functions func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { - if let e = error { - print("đŸšĢ Discover Services error \(e)") + if let error { + logger.error("đŸšĢ Discover Services error \(error.localizedDescription)") } guard let services = peripheral.services else { return } for service in services { if service.uuid == meshtasticServiceCBUUID { peripheral.discoverCharacteristics([TORADIO_UUID, FROMRADIO_UUID, FROMNUM_UUID], for: service) - print("✅ BLE Service for Meshtastic discovered by \(peripheral.name ?? "Unknown")") + logger.info("✅ BLE Service for Meshtastic discovered by \(peripheral.name ?? "Unknown")") } } } @@ -295,8 +295,8 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate // MARK: Discover Characteristics Event func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { - if let e = error { - print("đŸšĢ BLE Discover Characteristics error for \(peripheral.name ?? "Unknown") \(e) disconnecting device") + if let error { + logger.error("đŸšĢ BLE Discover Characteristics error for \(peripheral.name ?? "Unknown") \(error.localizedDescription) disconnecting device") // Try and stop crashes when this error occurs disconnectPeripheral() return @@ -308,16 +308,16 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate switch characteristic.uuid { case TORADIO_UUID: - print("✅ BLE did discover TORADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") + logger.info("✅ BLE did discover TORADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") TORADIO_characteristic = characteristic case FROMRADIO_UUID: - print("✅ BLE did discover FROMRADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") + logger.info("✅ BLE did discover FROMRADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") FROMRADIO_characteristic = characteristic peripheral.readValue(for: FROMRADIO_characteristic) case FROMNUM_UUID: - print("✅ BLE did discover FROMNUM (Notify) characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") + logger.info("✅ BLE did discover FROMNUM (Notify) characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") FROMNUM_characteristic = characteristic peripheral.setNotifyValue(true, for: characteristic) @@ -337,13 +337,13 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate func onMqttConnected() { mqttProxyConnected = true mqttError = "" - print("📲 Mqtt Client Proxy onMqttConnected now subscribing to \(mqttManager.topic).") + logger.info("📲 Mqtt Client Proxy onMqttConnected now subscribing to \(self.mqttManager.topic).") mqttManager.mqttClientProxy?.subscribe(mqttManager.topic) } func onMqttDisconnected() { mqttProxyConnected = false - print("MQTT Disconnected") + logger.info("MQTT Disconnected") } func onMqttMessageReceived(message: CocoaMQTTMessage) { @@ -369,7 +369,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate func onMqttError(message: String) { mqttProxyConnected = false mqttError = message - print("📲 Mqtt Client Proxy onMqttError: \(message)") + logger.info("📲 Mqtt Client Proxy onMqttError: \(message)") } // MARK: Protobuf Methods @@ -448,11 +448,11 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } do { try context!.save() - print("💾 Saved TraceRoute sent to node: \(String(receivingNode?.user?.longName ?? "unknown".localized))") + logger.info("💾 Saved TraceRoute sent to node: \(String(receivingNode?.user?.longName ?? "unknown".localized))") } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data BluetoothConfigEntity: \(nsError)") + logger.error("Error Updating Core Data BluetoothConfigEntity: \(nsError)") } let logString = String.localizedStringWithFormat("mesh.log.traceroute.sent %@".localized, String(destNum)) @@ -490,24 +490,22 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { - if let errorText = error?.localizedDescription { - print("đŸšĢ didUpdateNotificationStateFor error: \(errorText)") - } + logger.error("didUpdateNotificationStateFor error: \(error?.localizedDescription ?? "Unknown")") } // MARK: Data Read / Update Characteristic Event func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { - if let e = error { + if let error { - print("đŸšĢ didUpdateValueFor Characteristic error \(e)") - let errorCode = (e as NSError).code + logger.error("đŸšĢ didUpdateValueFor Characteristic error \(error.localizedDescription)") + let errorCode = (error as NSError).code if errorCode == 5 || errorCode == 15 { // BLE PIN connection errors // 5 CBATTErrorDomain Code=5 "Authentication is insufficient." // 15 CBATTErrorDomain Code=15 "Encryption is insufficient." - lastConnectionError = "🚨" + String.localizedStringWithFormat("ble.errorcode.pin %@".localized, e.localizedDescription) - print("🚨 \(e.localizedDescription) Please try connecting again and check the PIN carefully.") + lastConnectionError = "🚨" + String.localizedStringWithFormat("ble.errorcode.pin %@".localized, error.localizedDescription) + logger.error("\(error.localizedDescription) Please try connecting again and check the PIN carefully.") self.disconnectPeripheral(reconnect: false) } return @@ -526,7 +524,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate decodedInfo = try FromRadio(serializedData: characteristic.value!) } catch { - print(characteristic.value!) + logger.error("\(error.localizedDescription) \(characteristic.value!)") } // Publish mqttClientProxyMessages received on the from radio @@ -718,11 +716,11 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate traceRoute?.hops = NSOrderedSet(array: hopNodes) do { try context!.save() - print("💾 Saved Trace Route") + logger.info("💾 Saved Trace Route") } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data TraceRouteHOp: \(nsError)") + logger.error("Error Updating Core Data TraceRouteHOp: \(nsError)") } let logString = String.localizedStringWithFormat("mesh.log.traceroute.received.route %@".localized, routeString) MeshLogger.log("đŸĒ§ \(logString)") @@ -740,7 +738,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate case .UNRECOGNIZED: MeshLogger.log("đŸ•¸ī¸ MESH PACKET received for Other App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .max: - print("MAX PORT NUM OF 511") + logger.info("MAX PORT NUM OF 511") case .atakPlugin: MeshLogger.log("đŸ•¸ī¸ MESH PACKET received for ATAK Plugin App UNHANDLED \((try? decodedInfo.packet.jsonString()) ?? "JSON Decode Failure")") @@ -750,7 +748,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate invalidVersion = false lastConnectionError = "" isSubscribed = true - print("🤜 Want Config Complete. ID:\(decodedInfo.configCompleteID)") + logger.info("🤜 Want Config Complete. ID:\(decodedInfo.configCompleteID)") peripherals.removeAll(where: { $0.peripheral.state == CBPeripheralState.disconnected }) // Config conplete returns so we don't read the characteristic again @@ -786,7 +784,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } } catch { - print("Failed to find a node info for the connected node") + logger.error("Failed to find a node info for the connected node \(error.localizedDescription)") } } @@ -804,9 +802,9 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } case FROMNUM_UUID: - print("đŸ—žī¸ BLE (Notify) characteristic, value will be read next") + logger.info("đŸ—žī¸ BLE (Notify) characteristic, value will be read next") default: - print("🚨 Unhandled Characteristic UUID: \(characteristic.uuid)") + logger.error("Unhandled Characteristic UUID: \(characteristic.uuid)") } if FROMRADIO_characteristic != nil { // Either Read the config complete value or from num notify value @@ -836,7 +834,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } else if message.count < 1 { // Don't send an empty message - print("đŸšĢ Don't Send an Empty Message") + logger.info("đŸšĢ Don't Send an Empty Message") success = false } else { @@ -853,7 +851,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } if fetchedUsers.isEmpty { - print("đŸšĢ Message Users Not Found, Fail") + logger.error("đŸšĢ Message Users Not Found, Fail") success = false } else if fetchedUsers.count >= 1 { @@ -913,13 +911,13 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate MeshLogger.log("đŸ’Ŧ \(logString)") do { try context!.save() - print("💾 Saved a new sent message from \(connectedPeripheral.num) to \(toUserNum)") + logger.info("💾 Saved a new sent message from \(self.connectedPeripheral.num) to \(toUserNum)") success = true } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Unresolved Core Data error in Send Message Function your database is corrupted running a node db reset should clean up the data. Error: \(nsError)") + logger.error("Unresolved Core Data error in Send Message Function your database is corrupted running a node db reset should clean up the data. Error: \(nsError)") } } } @@ -984,11 +982,11 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } do { try context!.save() - print("💾 Updated Waypoint from Waypoint App Packet From: \(fromNodeNum)") + logger.info("💾 Updated Waypoint from Waypoint App Packet From: \(fromNodeNum)") } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving NodeInfoEntity from WAYPOINT_APP \(nsError)") + logger.error("Error Saving NodeInfoEntity from WAYPOINT_APP \(nsError)") } } return success @@ -1109,7 +1107,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) success = true let logString = String.localizedStringWithFormat("mesh.log.sharelocation %@".localized, String(fromNodeNum)) - print("📍 \(logString)") + logger.debug("📍 \(logString)") } return success } @@ -1348,7 +1346,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } } } catch { - print("Failed to find a node MyInfo to save these channels to") + logger.error("Failed to find a node MyInfo to save these channels to: \(error.localizedDescription)") } } @@ -1470,7 +1468,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error deleting node from core data: \(nsError)") + logger.error("Error deleting node from core data: \(nsError)") } } return false @@ -2623,12 +2621,12 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate do { connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) try context!.save() - print(adminDescription) + logger.debug("\(adminDescription)") return true } catch { context!.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error inserting new core data MessageEntity: \(nsError)") + logger.error("Error inserting new core data MessageEntity: \(nsError)") } } return false @@ -2659,7 +2657,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate let binaryData: Data = try! toRadio.serializedData() if connectedPeripheral?.peripheral.state ?? CBPeripheralState.disconnected == CBPeripheralState.connected { connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - print("📮 Sent a request for a Store & Forward Client History to \(toUser.num) for the last \(120) minutes.") + logger.debug("📮 Sent a request for a Store & Forward Client History to \(toUser.num) for the last \(120) minutes.") return true } return false @@ -2697,7 +2695,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save Store and Forward Router Error") + logger.error("Save Store and Forward Router Error") } } MeshLogger.log("💓 Store and Forward \(storeAndForwardMessage.rr) message received from \(packet.from)") @@ -2724,7 +2722,7 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save Store and Forward Router Error") + logger.error("Save Store and Forward Router Error") } MeshLogger.log("📜 Store and Forward \(storeAndForwardMessage.rr) message received from \(packet.from)") case .routerStats: @@ -2767,11 +2765,11 @@ class BLEManager: NSObject, CBPeripheralDelegate, MqttClientProxyManagerDelegate do { try context!.save() } catch { - print("Failed to clear existing channels from local app database") + logger.error("Failed to clear existing channels from local app database: \(error.localizedDescription)") } } } catch { - print("Failed to find a node MyInfo to save these channels to") + logger.error("Failed to find a node MyInfo to save these channels to: \(error.localizedDescription)") } } } @@ -2782,7 +2780,7 @@ extension BLEManager: CBCentralManagerDelegate { // MARK: Bluetooth enabled/disabled func centralManagerDidUpdateState(_ central: CBCentralManager) { if central.state == CBManagerState.poweredOn { - print("BLE powered on") + logger.debug("BLE powered on") isSwitchedOn = true startScanning() } else { @@ -2807,7 +2805,7 @@ extension BLEManager: CBCentralManagerDelegate { default: status = "default" } - print("BLEManager status: \(status)") + logger.debug("BLEManager status: \(status)") } // Called each time a peripheral is discovered @@ -2815,7 +2813,7 @@ extension BLEManager: CBCentralManagerDelegate { if self.automaticallyReconnect && peripheral.identifier.uuidString == UserDefaults.standard.object(forKey: "preferredPeripheralId") as? String ?? "" { self.connectTo(peripheral: peripheral) - print("â„šī¸ BLE Reconnecting to prefered peripheral: \(peripheral.name ?? "Unknown")") + logger.info("BLE Reconnecting to prefered peripheral: \(peripheral.name ?? "Unknown")") } let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String let device = Peripheral(id: peripheral.identifier.uuidString, num: 0, name: name ?? "Unknown", shortName: "?", longName: name ?? "Unknown", firmwareVersion: "Unknown", rssi: RSSI.intValue, lastUpdate: Date(), peripheral: peripheral) diff --git a/Meshtastic/Helpers/LocalNotificationManager.swift b/Meshtastic/Helpers/LocalNotificationManager.swift index 21e09942..6ebf1a05 100644 --- a/Meshtastic/Helpers/LocalNotificationManager.swift +++ b/Meshtastic/Helpers/LocalNotificationManager.swift @@ -60,7 +60,7 @@ class LocalNotificationManager { UNUserNotificationCenter.current().getPendingNotificationRequests { notifications in for notification in notifications { - print(notification) + logger.debug("\(notification)") } } } diff --git a/Meshtastic/Helpers/LocationHelper.swift b/Meshtastic/Helpers/LocationHelper.swift index 774ed7f4..db0526b4 100644 --- a/Meshtastic/Helpers/LocationHelper.swift +++ b/Meshtastic/Helpers/LocationHelper.swift @@ -70,6 +70,6 @@ class LocationHelper: NSObject, ObservableObject, CLLocationManagerDelegate { } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { - print("Location manager error: \(error.localizedDescription)") + logger.error("Location manager error: \(error.localizedDescription)") } } diff --git a/Meshtastic/Helpers/LocationsHandler.swift b/Meshtastic/Helpers/LocationsHandler.swift index f9279884..12d13310 100644 --- a/Meshtastic/Helpers/LocationsHandler.swift +++ b/Meshtastic/Helpers/LocationsHandler.swift @@ -49,7 +49,7 @@ import CoreLocation if self.manager.authorizationStatus == .notDetermined { self.manager.requestWhenInUseAuthorization() } - print("Starting location updates") + logger.info("Starting location updates") Task { do { self.updatesStarted = true @@ -69,14 +69,14 @@ import CoreLocation } } } catch { - print("Could not start location updates") + logger.error("Could not start location updates: \(error.localizedDescription)") } return } } func stopLocationUpdates() { - print("Stopping location updates") + logger.info("Stopping location updates") self.updatesStarted = false } @@ -84,15 +84,15 @@ import CoreLocation if smartPostion { let age = -location.timestamp.timeIntervalSinceNow if age > 10 { - print("Bad Location \(self.count): Too Old \(age) seconds ago \(location)") + logger.warning("Bad Location \(self.count): Too Old \(age) seconds ago \(location)") return false } if location.horizontalAccuracy < 0 { - print("Bad Location \(self.count): Horizontal Accuracy: \(location.horizontalAccuracy) \(location)") + logger.warning("Bad Location \(self.count): Horizontal Accuracy: \(location.horizontalAccuracy) \(location)") return false } if location.horizontalAccuracy > 5 { - print("Bad Location \(self.count): Horizontal Accuracy: \(location.horizontalAccuracy) \(location)") + logger.warning("Bad Location \(self.count): Horizontal Accuracy: \(location.horizontalAccuracy) \(location)") return false } } diff --git a/Meshtastic/Helpers/Logger.swift b/Meshtastic/Helpers/Logger.swift new file mode 100644 index 00000000..c648d9d4 --- /dev/null +++ b/Meshtastic/Helpers/Logger.swift @@ -0,0 +1,6 @@ +import OSLog + +public let logger = Logger( + subsystem: Bundle.main.bundleIdentifier!, + category: "debugging" +) diff --git a/Meshtastic/Helpers/Map/OfflineTileManager.swift b/Meshtastic/Helpers/Map/OfflineTileManager.swift index e3250e12..34ae93db 100644 --- a/Meshtastic/Helpers/Map/OfflineTileManager.swift +++ b/Meshtastic/Helpers/Map/OfflineTileManager.swift @@ -20,7 +20,7 @@ class OfflineTileManager: ObservableObject { } init() { - print("Documents Directory = \(documentsDirectory)") + logger.debug("Documents Directory = \(self.documentsDirectory.absoluteString)") createDirectoriesIfNecessary() } diff --git a/Meshtastic/Helpers/MeshLogger.swift b/Meshtastic/Helpers/MeshLogger.swift index f8699376..43310ab6 100644 --- a/Meshtastic/Helpers/MeshLogger.swift +++ b/Meshtastic/Helpers/MeshLogger.swift @@ -18,17 +18,22 @@ class MeshLogger { let formatter = DateFormatter() formatter.dateFormat = dateFormatString let timestamp = formatter.string(from: Date()) - guard let data = (message + " - " + timestamp + "\n").data(using: String.Encoding.utf8) else { return } - print(message) + guard let data = (message + " - " + timestamp + "\n").data(using: String.Encoding.utf8) else { + logger.error("Unable to create log data") + return + } - if FileManager.default.fileExists(atPath: logFile.path) { - if let fileHandle = try? FileHandle(forWritingTo: logFile) { + do { + if FileManager.default.fileExists(atPath: logFile.path) { + let fileHandle = try FileHandle(forWritingTo: logFile) fileHandle.seekToEndOfFile() fileHandle.write(data) fileHandle.closeFile() + } else { + try data.write(to: logFile, options: .atomicWrite) } - } else { - try? data.write(to: logFile, options: .atomicWrite) + } catch { + logger.error("Error writing log data: \(error.localizedDescription)") } } } diff --git a/Meshtastic/Helpers/MeshPackets.swift b/Meshtastic/Helpers/MeshPackets.swift index e02b7738..a54d562d 100644 --- a/Meshtastic/Helpers/MeshPackets.swift +++ b/Meshtastic/Helpers/MeshPackets.swift @@ -109,12 +109,12 @@ func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, context: NSManagedO myInfoEntity.rebootCount = Int32(myInfo.rebootCount) do { try context.save() - print("💾 Saved a new myInfo for node number: \(String(myInfo.myNodeNum))") + logger.info("💾 Saved a new myInfo for node number: \(String(myInfo.myNodeNum))") return myInfoEntity } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Inserting New Core Data MyInfoEntity: \(nsError)") + logger.error("Error Inserting New Core Data MyInfoEntity: \(nsError)") } } else { @@ -124,16 +124,16 @@ func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, context: NSManagedO do { try context.save() - print("💾 Updated myInfo for node number: \(String(myInfo.myNodeNum))") + logger.info("💾 Updated myInfo for node number: \(String(myInfo.myNodeNum))") return fetchedMyInfo[0] } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data MyInfoEntity: \(nsError)") + logger.error("Error Updating Core Data MyInfoEntity: \(nsError)") } } } catch { - print("đŸ’Ĩ Fetch MyInfo Error") + logger.error("Fetch MyInfo Error") } return nil } @@ -182,16 +182,16 @@ func channelPacket (channel: Channel, fromNum: Int64, context: NSManagedObjectCo do { try context.save() } catch { - print("Failed to save channel") + logger.error("Failed to save channel: \(error.localizedDescription)") } - print("💾 Updated MyInfo channel \(channel.index) from Channel App Packet For: \(fetchedMyInfo[0].myNodeNum)") + logger.info("💾 Updated MyInfo channel \(channel.index) from Channel App Packet For: \(fetchedMyInfo[0].myNodeNum)") } else if channel.role.rawValue > 0 { - print("đŸ’Ĩ Trying to save a channel to a MyInfo that does not exist: \(fromNum)") + logger.error("Trying to save a channel to a MyInfo that does not exist: \(fromNum)") } } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving MyInfo Channel from ADMIN_APP \(nsError)") + logger.error("Error Saving MyInfo Channel from ADMIN_APP \(nsError)") } } } @@ -235,13 +235,13 @@ func deviceMetadataPacket (metadata: DeviceMetadata, fromNum: Int64, context: NS do { try context.save() } catch { - print("Failed to save device metadata") + logger.error("Failed to save device metadata: \(error.localizedDescription)") } - print("💾 Updated Device Metadata from Admin App Packet For: \(fromNum)") + logger.info("💾 Updated Device Metadata from Admin App Packet For: \(fromNum)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving MyInfo Channel from ADMIN_APP \(nsError)") + logger.error("Error Saving MyInfo Channel from ADMIN_APP \(nsError)") } } } @@ -328,15 +328,15 @@ func nodeInfoPacket (nodeInfo: NodeInfo, channel: UInt32, context: NSManagedObje } do { try context.save() - print("💾 Saved a new Node Info For: \(String(nodeInfo.num))") + logger.info("💾 Saved a new Node Info For: \(String(nodeInfo.num))") return newNode } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving Core Data NodeInfoEntity: \(nsError)") + logger.error("Error Saving Core Data NodeInfoEntity: \(nsError)") } } catch { - print("đŸ’Ĩ Fetch MyInfo Error") + logger.error("Fetch MyInfo Error") } } else if nodeInfo.num > 0 { @@ -412,19 +412,19 @@ func nodeInfoPacket (nodeInfo: NodeInfo, channel: UInt32, context: NSManagedObje } do { try context.save() - print("💾 NodeInfo saved for \(nodeInfo.num)") + logger.info("💾 NodeInfo saved for \(nodeInfo.num)") return fetchedNode[0] } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving Core Data NodeInfoEntity: \(nsError)") + logger.error("Error Saving Core Data NodeInfoEntity: \(nsError)") } } catch { - print("đŸ’Ĩ Fetch MyInfo Error") + logger.error("Fetch MyInfo Error") } } } catch { - print("đŸ’Ĩ Fetch NodeInfoEntity Error") + logger.error("Fetch NodeInfoEntity Error") } return nil } @@ -457,15 +457,15 @@ func adminAppPacket (packet: MeshPacket, context: NSManagedObjectContext) { fetchedNode[0].cannedMessageConfig?.messages = messages do { try context.save() - print("💾 Updated Canned Messages Messages For: \(fetchedNode[0].num)") + logger.info("💾 Updated Canned Messages Messages For: \(fetchedNode[0].num)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving NodeInfoEntity from POSITION_APP \(nsError)") + logger.error("Error Saving NodeInfoEntity from POSITION_APP \(nsError)") } } } catch { - print("đŸ’Ĩ Error Deserializing ADMIN_APP packet.") + logger.error("Error Deserializing ADMIN_APP packet.") } } } @@ -542,11 +542,11 @@ func adminResponseAck (packet: MeshPacket, context: NSManagedObjectContext) { do { try context.save() } catch { - print("Failed to save admin message response as an ack") + logger.error("Failed to save admin message response as an ack: \(error.localizedDescription)") } } } catch { - print("Failed to fetch admin message by requestID") + logger.error("Failed to fetch admin message by requestID: \(error.localizedDescription)") } } func paxCounterPacket (packet: MeshPacket, context: NSManagedObjectContext) { @@ -577,10 +577,10 @@ func paxCounterPacket (packet: MeshPacket, context: NSManagedObjectContext) { do { try context.save() } catch { - print("Failed to save pax") + logger.error("Failed to save pax: \(error.localizedDescription)") } } else { - // Node Info Not Found + logger.info("Node Info Not Found") } } } catch { @@ -645,11 +645,11 @@ func routingPacket (packet: MeshPacket, connectedNodeNum: Int64, context: NSMana return } try context.save() - print("💾 ACK Saved for Message: \(packet.decoded.requestID)") + logger.info("💾 ACK Saved for Message: \(packet.decoded.requestID)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving ACK for message: \(packet.id) Error: \(nsError)") + logger.error("Error Saving ACK for message: \(packet.id) Error: \(nsError)") } } } @@ -710,7 +710,7 @@ func telemetryPacket(packet: MeshPacket, connectedNode: Int64, context: NSManage try context.save() // Only log telemetry from the mesh not the connected device if connectedNode != Int64(packet.from) { - print("💾 Telemetry Saved for Node: \(packet.from)") + logger.info("💾 Telemetry Saved for Node: \(packet.from)") } else if telemetry.metricsType == 0 { // Connected Device Metrics // ------------------------ @@ -743,7 +743,7 @@ func telemetryPacket(packet: MeshPacket, connectedNode: Int64, context: NSManage Task { await meshActivity?.update(updatedContent, alertConfiguration: alertConfiguration) // await meshActivity?.update(updatedContent) - print("Updated live activity.") + logger.debug("Updated live activity.") } } #endif @@ -751,10 +751,10 @@ func telemetryPacket(packet: MeshPacket, connectedNode: Int64, context: NSManage } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving Telemetry for Node \(packet.from) Error: \(nsError)") + logger.error("Error Saving Telemetry for Node \(packet.from) Error: \(nsError)") } } else { - print("đŸ’Ĩ Error Fetching NodeInfoEntity for Node \(packet.from)") + logger.error("Error Fetching NodeInfoEntity for Node \(packet.from)") } } @@ -833,7 +833,7 @@ func textMessageAppPacket(packet: MeshPacket, wantRangeTestPackets: Bool, connec do { try context.save() - print("💾 Saved a new message for \(newMessage.messageId)") + logger.info("💾 Saved a new message for \(newMessage.messageId)") messageSaved = true if messageSaved { @@ -862,7 +862,7 @@ func textMessageAppPacket(packet: MeshPacket, wantRangeTestPackets: Bool, connec ) ] manager.schedule() - print("đŸ’Ŧ iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "unknown".localized)") + logger.debug("iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "unknown".localized)") } } else if newMessage.fromUser != nil && newMessage.toUser == nil { @@ -894,7 +894,7 @@ func textMessageAppPacket(packet: MeshPacket, wantRangeTestPackets: Bool, connec path: "meshtastic://messages?channel=\(newMessage.channel)&messageId=\(newMessage.messageId)") ] manager.schedule() - print("đŸ’Ŧ iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "unknown".localized)") + logger.debug("iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "unknown".localized)") } } } @@ -906,10 +906,10 @@ func textMessageAppPacket(packet: MeshPacket, wantRangeTestPackets: Bool, connec } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Failed to save new MessageEntity \(nsError)") + logger.error("Failed to save new MessageEntity \(nsError)") } } catch { - print("đŸ’Ĩ Fetch Message To and From Users Error") + logger.error("Fetch Message To and From Users Error") } } } @@ -946,7 +946,7 @@ func waypointPacket (packet: MeshPacket, context: NSManagedObjectContext) { waypoint.created = Date() do { try context.save() - print("💾 Added Node Waypoint App Packet For: \(waypoint.id)") + logger.info("💾 Added Node Waypoint App Packet For: \(waypoint.id)") let manager = LocalNotificationManager() let icon = String(UnicodeScalar(Int(waypoint.icon)) ?? "📍") let latitude = Double(waypoint.latitudeI) / 1e7 @@ -961,12 +961,12 @@ func waypointPacket (packet: MeshPacket, context: NSManagedObjectContext) { path: "meshtastic://map?waypontid=\(waypoint.id)" ) ] - print("meshtastic://map?waypontid=\(waypoint.id)") + logger.debug("meshtastic://map?waypontid=\(waypoint.id)") manager.schedule() } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving WaypointEntity from WAYPOINT_APP \(nsError)") + logger.error("Error Saving WaypointEntity from WAYPOINT_APP \(nsError)") } } else { fetchedWaypoint[0].id = Int64(packet.id) @@ -984,15 +984,15 @@ func waypointPacket (packet: MeshPacket, context: NSManagedObjectContext) { fetchedWaypoint[0].lastUpdated = Date() do { try context.save() - print("💾 Updated Node Waypoint App Packet For: \(fetchedWaypoint[0].id)") + logger.info("💾 Updated Node Waypoint App Packet For: \(fetchedWaypoint[0].id)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving WaypointEntity from WAYPOINT_APP \(nsError)") + logger.error("Error Saving WaypointEntity from WAYPOINT_APP \(nsError)") } } } } catch { - print("đŸ’Ĩ Error Deserializing WAYPOINT_APP packet.") + logger.error("Error Deserializing WAYPOINT_APP packet.") } } diff --git a/Meshtastic/Helpers/Mqtt/MqttClientProxyManager.swift b/Meshtastic/Helpers/Mqtt/MqttClientProxyManager.swift index 13d22f4b..f74a1010 100644 --- a/Meshtastic/Helpers/Mqtt/MqttClientProxyManager.swift +++ b/Meshtastic/Helpers/Mqtt/MqttClientProxyManager.swift @@ -80,30 +80,28 @@ class MqttClientProxyManager { } } func subscribe(topic: String, qos: CocoaMQTTQoS) { - print("📲 MQTT Client Proxy subscribed to: " + topic) + logger.info("📲 MQTT Client Proxy subscribed to: \(topic)") mqttClientProxy?.subscribe(topic, qos: qos) } func unsubscribe(topic: String) { mqttClientProxy?.unsubscribe(topic) - print("📲 MQTT Client Proxy unsubscribe for: " + topic) + logger.info("📲 MQTT Client Proxy unsubscribe for: \(topic)") } func publish(message: String, topic: String, qos: CocoaMQTTQoS) { mqttClientProxy?.publish(topic, withString: message, qos: qos) - if debugLog { - print("📲 MQTT Client Proxy publish for: " + topic) - } + logger.debug("📲 MQTT Client Proxy publish for: \(topic)") } func disconnect() { if let client = mqttClientProxy { client.disconnect() - print("📲 MQTT Client Proxy Disconnected") + logger.info("📲 MQTT Client Proxy Disconnected") } } } extension MqttClientProxyManager: CocoaMQTTDelegate { func mqtt(_ mqtt: CocoaMQTT, didConnectAck ack: CocoaMQTTConnAck) { - print("📲 MQTT Client Proxy didConnectAck: \(ack)") + logger.info("📲 MQTT Client Proxy didConnectAck: \(ack)") if ack == .accept { delegate?.onMqttConnected() } else { @@ -125,13 +123,13 @@ extension MqttClientProxyManager: CocoaMQTTDelegate { default: errorDescription = "Unknown Error" } - print(errorDescription) + logger.error("\(errorDescription)") delegate?.onMqttError(message: errorDescription) self.disconnect() } } func mqttDidDisconnect(_ mqtt: CocoaMQTT, withError err: Error?) { - print("mqttDidDisconnect: \(err?.localizedDescription ?? "")") + logger.debug("mqttDidDisconnect: \(err?.localizedDescription ?? "")") if let error = err { delegate?.onMqttError(message: error.localizedDescription) @@ -139,32 +137,26 @@ extension MqttClientProxyManager: CocoaMQTTDelegate { delegate?.onMqttDisconnected() } func mqtt(_ mqtt: CocoaMQTT, didPublishMessage message: CocoaMQTTMessage, id: UInt16) { - if debugLog { - print("📲 MQTT Client Proxy didPublishMessage from MqttClientProxyManager: \(message)") - } + logger.debug("📲 MQTT Client Proxy didPublishMessage from MqttClientProxyManager: \(message)") } func mqtt(_ mqtt: CocoaMQTT, didPublishAck id: UInt16) { - if debugLog { - print("📲 MQTT Client Proxy didPublishAck from MqttClientProxyManager: \(id)") - } + logger.debug("📲 MQTT Client Proxy didPublishAck from MqttClientProxyManager: \(id)") } public func mqtt(_ mqtt: CocoaMQTT, didReceiveMessage message: CocoaMQTTMessage, id: UInt16) { delegate?.onMqttMessageReceived(message: message) - if debugLog { - print("📲 MQTT Client Proxy message received on topic: \(message.topic)") - } + logger.debug("📲 MQTT Client Proxy message received on topic: \(message.topic)") } func mqtt(_ mqtt: CocoaMQTT, didSubscribeTopics success: NSDictionary, failed: [String]) { - print("📲 MQTT Client Proxy didSubscribeTopics: \(success.allKeys.count) topics. failed: \(failed.count) topics") + logger.info("📲 MQTT Client Proxy didSubscribeTopics: \(success.allKeys.count) topics. failed: \(failed.count) topics") } func mqtt(_ mqtt: CocoaMQTT, didUnsubscribeTopics topics: [String]) { - print("didUnsubscribeTopics: \(topics.joined(separator: ", "))") + logger.info("didUnsubscribeTopics: \(topics.joined(separator: ", "))") } func mqttDidPing(_ mqtt: CocoaMQTT) { - print("📲 MQTT Client Proxy mqttDidPing") + logger.info("📲 MQTT Client Proxy mqttDidPing") } func mqttDidReceivePong(_ mqtt: CocoaMQTT) { - print("📲 MQTT Client Proxy mqttDidReceivePong") + logger.info("📲 MQTT Client Proxy mqttDidReceivePong") } } diff --git a/Meshtastic/Helpers/NetworkManager.swift b/Meshtastic/Helpers/NetworkManager.swift index 8e24cf49..f97a2159 100644 --- a/Meshtastic/Helpers/NetworkManager.swift +++ b/Meshtastic/Helpers/NetworkManager.swift @@ -16,7 +16,7 @@ class NetworkManager { pathMonitor.pathUpdateHandler = { guard $0.status == .satisfied else { // No network available - print("Network Not available") + logger.info("Network Not available") return pathMonitor.cancel() } pathMonitor.cancel() diff --git a/Meshtastic/MeshtasticApp.swift b/Meshtastic/MeshtasticApp.swift index fb5b79c9..9df03469 100644 --- a/Meshtastic/MeshtasticApp.swift +++ b/Meshtastic/MeshtasticApp.swift @@ -34,7 +34,7 @@ struct MeshtasticAppleApp: App { } .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { userActivity in - print("URL received \(userActivity)") + logger.debug("URL received \(userActivity)") self.incomingUrl = userActivity.webpageURL if (self.incomingUrl?.absoluteString.lowercased().contains("meshtastic.org/e/#")) != nil { @@ -44,25 +44,25 @@ struct MeshtasticAppleApp: App { } self.channelSettings = cs self.addChannels = Bool(self.incomingUrl?["add"] ?? "false") ?? false - print("Add Channel \(self.addChannels)") + logger.debug("Add Channel \(self.addChannels)") } self.saveChannels = true - print("User wants to open a Channel Settings URL: \(self.incomingUrl?.absoluteString ?? "No QR Code Link")") + logger.debug("User wants to open a Channel Settings URL: \(self.incomingUrl?.absoluteString ?? "No QR Code Link")") } if self.saveChannels { - print("User wants to open Channel Settings URL: \(String(describing: self.incomingUrl!.relativeString))") + logger.debug("User wants to open Channel Settings URL: \(String(describing: self.incomingUrl!.relativeString))") } } .onOpenURL(perform: { (url) in - print("Some sort of URL was received \(url)") + logger.debug("Some sort of URL was received \(url)") self.incomingUrl = url if url.absoluteString.lowercased().contains("meshtastic.org/e/#") { if let components = self.incomingUrl?.absoluteString.components(separatedBy: "#") { self.channelSettings = components.last! } self.saveChannels = true - print("User wants to open a Channel Settings URL: \(self.incomingUrl?.absoluteString ?? "No QR Code Link")") + logger.debug("User wants to open a Channel Settings URL: \(self.incomingUrl?.absoluteString ?? "No QR Code Link")") } else if url.absoluteString.lowercased().contains("meshtastic://") { appState.navigationPath = url.absoluteString let path = appState.navigationPath ?? "" @@ -74,7 +74,7 @@ struct MeshtasticAppleApp: App { } else { saveChannels = false - print("User wants to import a MBTILES offline map file: \(self.incomingUrl?.absoluteString ?? "No Tiles link")") + logger.debug("User wants to import a MBTILES offline map file: \(self.incomingUrl?.absoluteString ?? "No Tiles link")") } /// Only do the map tiles stuff if it is enabled @@ -94,24 +94,24 @@ struct MeshtasticAppleApp: App { // do we need to delete an old one? if fileManager.fileExists(atPath: destination.path) { - print("â„šī¸ Found an old map file. Deleting it") + logger.info("Found an old map file. Deleting it") try? fileManager.removeItem(atPath: destination.path) } do { try fileManager.copyItem(at: url, to: destination) } catch { - print("Copy MB Tile file failed. Error: \(error)") + logger.error("Copy MB Tile file failed. Error: \(error.localizedDescription)") } if fileManager.fileExists(atPath: destination.path) { - print("â„šī¸ Saved the map file") + logger.info("Saved the map file") // need to tell the map view that it needs to update and try loading the new overlay UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: "lastUpdatedLocalMapFile") } else { - print("đŸ’Ĩ Didn't save the map file") + logger.error("Didn't save the map file") } } } @@ -139,22 +139,22 @@ struct MeshtasticAppleApp: App { .onChange(of: scenePhase) { (newScenePhase) in switch newScenePhase { case .background: - print("â„šī¸ Scene is in the background") + logger.info("Scene is in the background") do { try persistenceController.container.viewContext.save() - print("💾 Saved CoreData ViewContext when the app went to the background.") + logger.info("💾 Saved CoreData ViewContext when the app went to the background.") } catch { - print("đŸ’Ĩ Failed to save viewContext when the app goes to the background.") + logger.error("Failed to save viewContext when the app goes to the background.") } case .inactive: - print("â„šī¸ Scene is inactive") + logger.info("Scene is inactive") case .active: - print("â„šī¸ Scene is active") + logger.info("Scene is active") @unknown default: - print("đŸ’Ĩ Apple must have changed something") + logger.error("Apple must have changed something") } } } diff --git a/Meshtastic/MeshtasticAppDelegate.swift b/Meshtastic/MeshtasticAppDelegate.swift index 3a99f6b8..bead46f8 100644 --- a/Meshtastic/MeshtasticAppDelegate.swift +++ b/Meshtastic/MeshtasticAppDelegate.swift @@ -9,7 +9,7 @@ import SwiftUI class MeshtasticAppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, ObservableObject { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { - print("🚀 Meshtstic Apple App launched!") + logger.info("🚀 Meshtstic Apple App launched!") // Default User Default Values UserDefaults.standard.register(defaults: ["meshMapRecentering": true]) UserDefaults.standard.register(defaults: ["meshMapShowNodeHistory": true]) diff --git a/Meshtastic/Persistence/Persistence.swift b/Meshtastic/Persistence/Persistence.swift index 13688f5c..99e53d6c 100644 --- a/Meshtastic/Persistence/Persistence.swift +++ b/Meshtastic/Persistence/Persistence.swift @@ -47,7 +47,7 @@ class PersistenceController { if let error = error as NSError? { - print("đŸ’Ĩ CoreData Error: \(error.localizedDescription). Now attempting to truncate CoreData database. All app data will be lost.") + logger.error("CoreData Error: \(error.localizedDescription). Now attempting to truncate CoreData database. All app data will be lost.") self.clearDatabase() } }) @@ -59,16 +59,16 @@ class PersistenceController { let persistentStoreCoordinator = self.container.persistentStoreCoordinator do { try persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: NSSQLiteStoreType, options: nil) - print("đŸ’Ĩ CoreData database truncated. All app data has been erased.") + logger.error("CoreData database truncated. All app data has been erased.") do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch let error { - print("đŸ’Ŗ Failed to re-create CoreData database: " + error.localizedDescription) + logger.error("Failed to re-create CoreData database: \(error.localizedDescription)") } } catch let error { - print("đŸ’Ŗ Failed to destroy CoreData database, delete the app and re-install to clear data. Attempted to clear persistent store: " + error.localizedDescription) + logger.error("Failed to destroy CoreData database, delete the app and re-install to clear data. Attempted to clear persistent store: \(error.localizedDescription)") } } } diff --git a/Meshtastic/Persistence/UpdateCoreData.swift b/Meshtastic/Persistence/UpdateCoreData.swift index 844957d4..e93e2927 100644 --- a/Meshtastic/Persistence/UpdateCoreData.swift +++ b/Meshtastic/Persistence/UpdateCoreData.swift @@ -26,7 +26,7 @@ public func clearPax(destNum: Int64, context: NSManagedObjectContext) -> Bool { return false } } catch { - print("đŸ’Ĩ Fetch NodeInfoEntity Error") + logger.error("Fetch NodeInfoEntity Error") return false } } @@ -51,7 +51,7 @@ public func clearPositions(destNum: Int64, context: NSManagedObjectContext) -> B return false } } catch { - print("đŸ’Ĩ Fetch NodeInfoEntity Error") + logger.error("Fetch NodeInfoEntity Error") return false } } @@ -76,7 +76,7 @@ public func clearTelemetry(destNum: Int64, metricsType: Int32, context: NSManage return false } } catch { - print("đŸ’Ĩ Fetch NodeInfoEntity Error") + logger.error("Fetch NodeInfoEntity Error") return false } } @@ -89,7 +89,7 @@ public func deleteChannelMessages(channel: ChannelEntity, context: NSManagedObje } try context.save() } catch let error as NSError { - print("Error: \(error.localizedDescription)") + logger.error("\(error.localizedDescription)") } } @@ -102,7 +102,7 @@ public func deleteUserMessages(user: UserEntity, context: NSManagedObjectContext } try context.save() } catch let error as NSError { - print("Error: \(error.localizedDescription)") + logger.error("\(error.localizedDescription)") } } @@ -125,8 +125,8 @@ public func clearCoreDataDatabase(context: NSManagedObjectContext, includeRoutes } do { try context.executeAndMergeChanges(using: deleteRequest) - } catch let error as NSError { - print(error) + } catch { + logger.error("\(error.localizedDescription)") } } } @@ -211,11 +211,11 @@ func upsertNodeInfoPacket (packet: MeshPacket, context: NSManagedObjectContext) myInfoEntity.rebootCount = 0 do { try context.save() - print("💾 Saved a new myInfo for node number: \(String(packet.from))") + logger.info("💾 Saved a new myInfo for node number: \(String(packet.from))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Inserting New Core Data MyInfoEntity: \(nsError)") + logger.error("Error Inserting New Core Data MyInfoEntity: \(nsError)") } newNode.myInfo = myInfoEntity @@ -265,15 +265,15 @@ func upsertNodeInfoPacket (packet: MeshPacket, context: NSManagedObjectContext) } do { try context.save() - print("💾 Updated NodeInfo from Node Info App Packet For: \(fetchedNode[0].num)") + logger.info("💾 Updated NodeInfo from Node Info App Packet For: \(fetchedNode[0].num)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving NodeInfoEntity from NODEINFO_APP \(nsError)") + logger.error("Error Saving NodeInfoEntity from NODEINFO_APP \(nsError)") } } } catch { - print("đŸ’Ĩ Error Fetching NodeInfoEntity for NODEINFO_APP") + logger.error("Error Fetching NodeInfoEntity for NODEINFO_APP") } } @@ -357,11 +357,11 @@ func upsertPositionPacket (packet: MeshPacket, context: NSManagedObjectContext) do { try context.save() - print("💾 Updated Node Position Coordinates, SNR and Time from Position App Packet For: \(fetchedNode[0].num)") + logger.info("💾 Updated Node Position Coordinates, SNR and Time from Position App Packet For: \(fetchedNode[0].num)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving NodeInfoEntity from POSITION_APP \(nsError)") + logger.error("Error Saving NodeInfoEntity from POSITION_APP \(nsError)") } } } else { @@ -369,13 +369,12 @@ func upsertPositionPacket (packet: MeshPacket, context: NSManagedObjectContext) if (try? NodeInfo(serializedData: packet.decoded.payload)) != nil { upsertNodeInfoPacket(packet: packet, context: context) } else { - print("đŸ’Ĩ Empty POSITION_APP Packet") - print((try? packet.jsonString()) ?? "JSON Decode Failure") + logger.error("Empty POSITION_APP Packet: \((try? packet.jsonString()) ?? "JSON Decode Failure")") } } } } catch { - print("đŸ’Ĩ Error Deserializing POSITION_APP packet.") + logger.error("Error Deserializing POSITION_APP packet.") } } @@ -406,18 +405,18 @@ func upsertBluetoothConfigPacket(config: Meshtastic.Config.BluetoothConfig, node } do { try context.save() - print("💾 Updated Bluetooth Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Bluetooth Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data BluetoothConfigEntity: \(nsError)") + logger.error("Error Updating Core Data BluetoothConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Bluetooth Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Bluetooth Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data BluetoothConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data BluetoothConfigEntity failed: \(nsError)") } } @@ -463,16 +462,16 @@ func upsertDeviceConfigPacket(config: Meshtastic.Config.DeviceConfig, nodeNum: I } do { try context.save() - print("💾 Updated Device Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Device Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data DeviceConfigEntity: \(nsError)") + logger.error("Error Updating Core Data DeviceConfigEntity: \(nsError)") } } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data DeviceConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data DeviceConfigEntity failed: \(nsError)") } } @@ -521,24 +520,24 @@ func upsertDisplayConfigPacket(config: Meshtastic.Config.DisplayConfig, nodeNum: do { try context.save() - print("💾 Updated Display Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Display Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data DisplayConfigEntity: \(nsError)") + logger.error("Error Updating Core Data DisplayConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Display Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Display Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data DisplayConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data DisplayConfigEntity failed: \(nsError)") } } @@ -594,18 +593,18 @@ func upsertLoRaConfigPacket(config: Meshtastic.Config.LoRaConfig, nodeNum: Int64 } do { try context.save() - print("💾 Updated LoRa Config for node number: \(String(nodeNum))") + logger.info("💾 Updated LoRa Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data LoRaConfigEntity: \(nsError)") + logger.error("Error Updating Core Data LoRaConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Lora Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Lora Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data LoRaConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data LoRaConfigEntity failed: \(nsError)") } } @@ -640,19 +639,19 @@ func upsertNetworkConfigPacket(config: Meshtastic.Config.NetworkConfig, nodeNum: do { try context.save() - print("💾 Updated Network Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Network Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data WiFiConfigEntity: \(nsError)") + logger.error("Error Updating Core Data WiFiConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Network Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Network Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data NetworkConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data NetworkConfigEntity failed: \(nsError)") } } @@ -704,18 +703,18 @@ func upsertPositionConfigPacket(config: Meshtastic.Config.PositionConfig, nodeNu } do { try context.save() - print("💾 Updated Position Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Position Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data PositionConfigEntity: \(nsError)") + logger.error("Error Updating Core Data PositionConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Position Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Position Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data PositionConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data PositionConfigEntity failed: \(nsError)") } } @@ -753,18 +752,18 @@ func upsertPowerConfigPacket(config: Meshtastic.Config.PowerConfig, nodeNum: Int } do { try context.save() - print("💾 Updated Power Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Power Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data PowerConfigEntity: \(nsError)") + logger.error("Error Updating Core Data PowerConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Power Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Power Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data PowerConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data PowerConfigEntity failed: \(nsError)") } } @@ -809,18 +808,18 @@ func upsertAmbientLightingModuleConfigPacket(config: Meshtastic.ModuleConfig.Amb do { try context.save() - print("💾 Updated Ambient Lighting Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Ambient Lighting Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data AmbientLightingConfigEntity: \(nsError)") + logger.error("Error Updating Core Data AmbientLightingConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Ambient Lighting Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Ambient Lighting Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data AmbientLightingConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data AmbientLightingConfigEntity failed: \(nsError)") } } @@ -873,18 +872,18 @@ func upsertCannedMessagesModuleConfigPacket(config: Meshtastic.ModuleConfig.Cann do { try context.save() - print("💾 Updated Canned Message Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Canned Message Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data CannedMessageConfigEntity: \(nsError)") + logger.error("Error Updating Core Data CannedMessageConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Canned Message Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Canned Message Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data CannedMessageConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data CannedMessageConfigEntity failed: \(nsError)") } } @@ -931,21 +930,21 @@ func upsertDetectionSensorModuleConfigPacket(config: Meshtastic.ModuleConfig.Det do { try context.save() - print("💾 Updated Detection Sensor Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Detection Sensor Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data DetectionSensorConfigEntity: \(nsError)") + logger.error("Error Updating Core Data DetectionSensorConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Detection Sensor Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Detection Sensor Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)") } } @@ -1004,18 +1003,18 @@ func upsertExternalNotificationModuleConfigPacket(config: Meshtastic.ModuleConfi do { try context.save() - print("💾 Updated External Notification Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated External Notification Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)") + logger.error("Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save External Notification Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save External Notification Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data ExternalNotificationConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data ExternalNotificationConfigEntity failed: \(nsError)") } } @@ -1049,18 +1048,18 @@ func upsertPaxCounterModuleConfigPacket(config: Meshtastic.ModuleConfig.Paxcount do { try context.save() - print("💾 Updated PAX Counter Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated PAX Counter Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)") + logger.error("Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save PAX Counter Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save PAX Counter Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data PaxCounterConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data PaxCounterConfigEntity failed: \(nsError)") } } @@ -1088,18 +1087,18 @@ func upsertRtttlConfigPacket(ringtone: String, nodeNum: Int64, context: NSManage } do { try context.save() - print("💾 Updated RTTTL Ringtone Config for node number: \(String(nodeNum))") + logger.info("💾 Updated RTTTL Ringtone Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data RtttlConfigEntity: \(nsError)") + logger.error("Error Updating Core Data RtttlConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save RTTTL Ringtone Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save RTTTL Ringtone Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data RtttlConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data RtttlConfigEntity failed: \(nsError)") } } @@ -1150,18 +1149,18 @@ func upsertMqttModuleConfigPacket(config: Meshtastic.ModuleConfig.MQTTConfig, no } do { try context.save() - print("💾 Updated MQTT Config for node number: \(String(nodeNum))") + logger.info("💾 Updated MQTT Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data MQTTConfigEntity: \(nsError)") + logger.error("Error Updating Core Data MQTTConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save MQTT Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save MQTT Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data MQTTConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data MQTTConfigEntity failed: \(nsError)") } } @@ -1193,18 +1192,18 @@ func upsertRangeTestModuleConfigPacket(config: Meshtastic.ModuleConfig.RangeTest } do { try context.save() - print("💾 Updated Range Test Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Range Test Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data RangeTestConfigEntity: \(nsError)") + logger.error("Error Updating Core Data RangeTestConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Range Test Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Range Test Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data RangeTestConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data RangeTestConfigEntity failed: \(nsError)") } } @@ -1249,25 +1248,25 @@ func upsertSerialModuleConfigPacket(config: Meshtastic.ModuleConfig.SerialConfig do { try context.save() - print("💾 Updated Serial Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Serial Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data SerialConfigEntity: \(nsError)") + logger.error("Error Updating Core Data SerialConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Serial Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Serial Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data SerialConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data SerialConfigEntity failed: \(nsError)") } } @@ -1306,18 +1305,18 @@ func upsertStoreForwardModuleConfigPacket(config: Meshtastic.ModuleConfig.StoreF } do { try context.save() - print("💾 Updated Store & Forward Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Store & Forward Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data StoreForwardConfigEntity: \(nsError)") + logger.error("Error Updating Core Data StoreForwardConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Store & Forward Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Store & Forward Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)") } } @@ -1363,20 +1362,20 @@ func upsertTelemetryModuleConfigPacket(config: Meshtastic.ModuleConfig.Telemetry do { try context.save() - print("💾 Updated Telemetry Module Config for node number: \(String(nodeNum))") + logger.info("💾 Updated Telemetry Module Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Updating Core Data TelemetryConfigEntity: \(nsError)") + logger.error("Error Updating Core Data TelemetryConfigEntity: \(nsError)") } } else { - print("đŸ’Ĩ No Nodes found in local database matching node number \(nodeNum) unable to save Telemetry Module Config") + logger.error("No Nodes found in local database matching node number \(nodeNum) unable to save Telemetry Module Config") } } catch { let nsError = error as NSError - print("đŸ’Ĩ Fetching node for core data TelemetryConfigEntity failed: \(nsError)") + logger.error("Fetching node for core data TelemetryConfigEntity failed: \(nsError)") } } diff --git a/Meshtastic/Views/Bluetooth/Connect.swift b/Meshtastic/Views/Bluetooth/Connect.swift index 438e3a00..e7b0abe2 100644 --- a/Meshtastic/Views/Bluetooth/Connect.swift +++ b/Meshtastic/Views/Bluetooth/Connect.swift @@ -34,9 +34,9 @@ struct Connect: View { if settings.authorizationStatus == .notDetermined { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { - print("Notifications are all set!") + logger.info("Notifications are all set!") } else if let error = error { - print(error.localizedDescription) + logger.error("\(error.localizedDescription)") } } } @@ -104,12 +104,12 @@ struct Connect: View { Button { if !liveActivityStarted { #if canImport(ActivityKit) - print("Start live activity.") + logger.info("Start live activity.") startNodeActivity() #endif } else { #if canImport(ActivityKit) - print("Stop live activity.") + logger.info("Stop live activity.") endActivity() #endif } @@ -123,7 +123,7 @@ struct Connect: View { Text("BLE RSSI: \(bleManager.connectedPeripheral.rssi)") Button { if !bleManager.sendShutdown(fromUser: node!.user!, toUser: node!.user!, adminIndex: node!.myInfo!.adminIndex) { - print("Shutdown Failed") + logger.error("Shutdown Failed") } } label: { @@ -346,9 +346,9 @@ struct Connect: View { do { let myActivity = try Activity.request(attributes: activityAttributes, content: activityContent, pushType: nil) - print(" Requested MyActivity live activity. ID: \(myActivity.id)") - } catch let error { - print("Error requesting live activity: \(error.localizedDescription)") + logger.info("Requested MyActivity live activity. ID: \(myActivity.id)") + } catch { + logger.error("Error requesting live activity: \(error.localizedDescription)") } } diff --git a/Meshtastic/Views/Helpers/Weather/NodeWeatherForecast.swift b/Meshtastic/Views/Helpers/Weather/NodeWeatherForecast.swift index 28dcfeb7..0b2f8220 100644 --- a/Meshtastic/Views/Helpers/Weather/NodeWeatherForecast.swift +++ b/Meshtastic/Views/Helpers/Weather/NodeWeatherForecast.swift @@ -34,7 +34,7 @@ struct NodeWeatherForecastView: View { ) }) } catch { - print("Could not load weather", error.localizedDescription) + logger.error("Could not load weather: \(error.localizedDescription)") } } } diff --git a/Meshtastic/Views/MapKitMap/Custom/LocalMBTileOverlay.swift b/Meshtastic/Views/MapKitMap/Custom/LocalMBTileOverlay.swift index 4c9dc828..d7408b40 100644 --- a/Meshtastic/Views/MapKitMap/Custom/LocalMBTileOverlay.swift +++ b/Meshtastic/Views/MapKitMap/Custom/LocalMBTileOverlay.swift @@ -83,7 +83,7 @@ class LocalMBTileOverlay: MKTileOverlay { self._boundingMapRect = MKMapRect(coordinates: coords) } catch { - print("đŸ’Ĩ Map tile error: \(error)") + logger.error("Map tile error: \(error)") return nil } } @@ -102,7 +102,7 @@ class LocalMBTileOverlay: MKTileOverlay { let data = Data(bytes: dataQuery[tileData].bytes, count: dataQuery[tileData].bytes.count)// dataQuery![tileData].bytes result(data, nil) } else { - print("đŸ’Ĩ No tile here: x:\(tileX) y:\(tileY) z:\(tileZ)") + logger.error("No tile here: x:\(tileX) y:\(tileY) z:\(tileZ)") let error = NSError(domain: "LocalMBTileOverlay", code: 1, userInfo: ["reason": "no_tile"]) result(nil, error) } diff --git a/Meshtastic/Views/MapKitMap/Custom/MapViewSwiftUI.swift b/Meshtastic/Views/MapKitMap/Custom/MapViewSwiftUI.swift index 20f62fbe..4cc8b941 100644 --- a/Meshtastic/Views/MapKitMap/Custom/MapViewSwiftUI.swift +++ b/Meshtastic/Views/MapKitMap/Custom/MapViewSwiftUI.swift @@ -144,13 +144,13 @@ struct MapViewSwiftUI: UIViewRepresentable { let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let tilePath = documentsDirectory.appendingPathComponent("offline_map.mbtiles", isDirectory: false).path if fileManager.fileExists(atPath: tilePath) { - print("Loading local map file") + logger.info("Loading local map file") if let overlay = LocalMBTileOverlay(mbTilePath: tilePath) { overlay.canReplaceMapContent = false// customMapOverlay.canReplaceMapContent mapView.addOverlay(overlay) } } else { - print("Couldn't find a local map file to load") + logger.info("Couldn't find a local map file to load") } } DispatchQueue.main.async { @@ -209,7 +209,7 @@ struct MapViewSwiftUI: UIViewRepresentable { } let annotationCount = waypoints.count + (showNodeHistory ? positions.count : latest.count) if annotationCount != mapView.annotations.count { - print("Annotation Count: \(annotationCount) Map Annotations: \(mapView.annotations.count)") + logger.info("Annotation Count: \(annotationCount) Map Annotations: \(mapView.annotations.count)") mapView.removeAnnotations(mapView.annotations) mapView.addAnnotations(waypoints) } diff --git a/Meshtastic/Views/MapKitMap/NodeMapMapkit.swift b/Meshtastic/Views/MapKitMap/NodeMapMapkit.swift index b1ad3945..59176569 100644 --- a/Meshtastic/Views/MapKitMap/NodeMapMapkit.swift +++ b/Meshtastic/Views/MapKitMap/NodeMapMapkit.swift @@ -126,7 +126,7 @@ struct NodeMapMapkit: View { attributionLogo = colorScheme == .light ? attribution.combinedMarkLightURL : attribution.combinedMarkDarkURL } } catch { - print("Could not gather weather information...", error.localizedDescription) + logger.error("Could not gather weather information: \(error.localizedDescription)") condition = .clear symbolName = "cloud.fill" } diff --git a/Meshtastic/Views/MapKitMap/WaypointFormMapKit.swift b/Meshtastic/Views/MapKitMap/WaypointFormMapKit.swift index f32300ea..3cba6773 100644 --- a/Meshtastic/Views/MapKitMap/WaypointFormMapKit.swift +++ b/Meshtastic/Views/MapKitMap/WaypointFormMapKit.swift @@ -152,7 +152,7 @@ struct WaypointFormMapKit: View { dismiss() } else { dismiss() - print("Send waypoint failed") + logger.error("Send waypoint failed") } } label: { Label("Send", systemImage: "arrow.up") @@ -212,7 +212,7 @@ struct WaypointFormMapKit: View { dismiss() } else { dismiss() - print("Send waypoint failed") + logger.error("Send waypoint failed") } }) } diff --git a/Meshtastic/Views/Messages/ChannelMessageList.swift b/Meshtastic/Views/Messages/ChannelMessageList.swift index 70e88d78..4df4240a 100644 --- a/Meshtastic/Views/Messages/ChannelMessageList.swift +++ b/Meshtastic/Views/Messages/ChannelMessageList.swift @@ -114,12 +114,12 @@ struct ChannelMessageList: View { message.read = true do { try context.save() - print("📖 Read message \(message.messageId) ") + logger.info("📖 Read message \(message.messageId) ") appState.unreadChannelMessages = myInfo.unreadMessages UIApplication.shared.applicationIconBadgeNumber = appState.unreadChannelMessages + appState.unreadDirectMessages context.refresh(myInfo, mergeChanges: true) } catch { - print("Failed to read message \(message.messageId)") + logger.error("Failed to read message \(message.messageId): \(error.localizedDescription)") } } } diff --git a/Meshtastic/Views/Messages/MessageText.swift b/Meshtastic/Views/Messages/MessageText.swift index 80d2cd05..7f31f29e 100644 --- a/Meshtastic/Views/Messages/MessageText.swift +++ b/Meshtastic/Views/Messages/MessageText.swift @@ -71,7 +71,7 @@ struct MessageText: View { do { try context.save() } catch { - print("Failed to delete message \(message.messageId)") + logger.error("Failed to delete message \(message.messageId): \(error.localizedDescription)") } } Button("Cancel", role: .cancel) {} diff --git a/Meshtastic/Views/Messages/Messages.swift b/Meshtastic/Views/Messages/Messages.swift index 919426a9..c875c1fa 100644 --- a/Meshtastic/Views/Messages/Messages.swift +++ b/Meshtastic/Views/Messages/Messages.swift @@ -75,12 +75,12 @@ struct Messages: View { let messageId = queryItems?.first(where: { $0.name == "messageId" })?.value let channel = queryItems?.first(where: { $0.name == "channel" })?.value - if channel == nil { - print("Channel not found") + if let channel { + logger.info("Channel \(channel)") + // selectedNode = nodes.first(where: { $0.num == Int64(nodeNum ?? "-1") }) + // AppState.shared.navigationPath = nil } else { - print("Channel \(channel)") - // selectedNode = nodes.first(where: { $0.num == Int64(nodeNum ?? "-1") }) - // AppState.shared.navigationPath = nil + logger.info("Channel not found") } } } diff --git a/Meshtastic/Views/Messages/RetryButton.swift b/Meshtastic/Views/Messages/RetryButton.swift index 1e2065bd..a6d00536 100644 --- a/Meshtastic/Views/Messages/RetryButton.swift +++ b/Meshtastic/Views/Messages/RetryButton.swift @@ -36,7 +36,7 @@ struct RetryButton: View { do { try context.save() } catch { - print("Failed to delete message \(messageID)") + logger.error("Failed to delete message \(messageID): \(error.localizedDescription)") } if !bleManager.sendMessage( message: payload, @@ -46,7 +46,7 @@ struct RetryButton: View { replyID: replyID ) { // Best effort, unlikely since we already checked BLE state - print("Failed to resend message \(messageID)") + logger.warning("Failed to resend message \(messageID)") } else { switch destination { case .user: diff --git a/Meshtastic/Views/Messages/TapbackResponses.swift b/Meshtastic/Views/Messages/TapbackResponses.swift index c5c21133..c5ba9dc7 100644 --- a/Meshtastic/Views/Messages/TapbackResponses.swift +++ b/Meshtastic/Views/Messages/TapbackResponses.swift @@ -30,10 +30,10 @@ struct TapbackResponses: View { tapback.read = true do { try context.save() - print("📖 Read tapback \(tapback.messageId) ") + logger.info("📖 Read tapback \(tapback.messageId) ") onRead() } catch { - print("Failed to read tapback \(tapback.messageId)") + logger.error("Failed to read tapback \(tapback.messageId): \(error.localizedDescription)") } } } diff --git a/Meshtastic/Views/Messages/TextMessageField/TextMessageField.swift b/Meshtastic/Views/Messages/TextMessageField/TextMessageField.swift index 4819e5be..6b10bf47 100644 --- a/Meshtastic/Views/Messages/TextMessageField/TextMessageField.swift +++ b/Meshtastic/Views/Messages/TextMessageField/TextMessageField.swift @@ -107,7 +107,7 @@ struct TextMessageField: View { wantResponse: destination.wantPositionResponse ) if positionSent { - print("Location Sent") + logger.info("Location Sent") } } } diff --git a/Meshtastic/Views/Messages/UserList.swift b/Meshtastic/Views/Messages/UserList.swift index ac3012c8..ac38c4bf 100644 --- a/Meshtastic/Views/Messages/UserList.swift +++ b/Meshtastic/Views/Messages/UserList.swift @@ -111,13 +111,13 @@ struct UserList: View { let success = bleManager.setFavoriteNode(node: user.userNode!, connectedNodeNum: Int64(node!.num)) if success { user.userNode?.favorite = !(user.userNode?.favorite ?? true) - print("Favorited a node") + logger.info("Favorited a node") } } else { let success = bleManager.removeFavoriteNode(node: user.userNode!, connectedNodeNum: Int64(node!.num)) if success { user.userNode?.favorite = !(user.userNode?.favorite ?? true) - print("Favorited a node") + logger.info("Favorited a node") } } context.refresh(user, mergeChanges: true) @@ -125,7 +125,7 @@ struct UserList: View { try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save Node Favorite Error") + logger.error("Save Node Favorite Error") } } label: { Label((user.userNode?.favorite ?? false) ? "Un-Favorite" : "Favorite", systemImage: (user.userNode?.favorite ?? false) ? "star.slash.fill" : "star.fill") @@ -136,7 +136,7 @@ struct UserList: View { try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save User Mute Error") + logger.error("Save User Mute Error") } } label: { Label(user.mute ? "Show Alerts" : "Hide Alerts", systemImage: user.mute ? "bell" : "bell.slash") @@ -206,7 +206,6 @@ struct UserList: View { } .onChange(of: selectedUserNum) { newUserNum in userSelection = users.first(where: { $0.num == newUserNum }) - print(userSelection) } .onAppear { if self.bleManager.context == nil { diff --git a/Meshtastic/Views/Messages/UserMessageList.swift b/Meshtastic/Views/Messages/UserMessageList.swift index bc9ef791..e2917d88 100644 --- a/Meshtastic/Views/Messages/UserMessageList.swift +++ b/Meshtastic/Views/Messages/UserMessageList.swift @@ -99,12 +99,12 @@ struct UserMessageList: View { message.read = true do { try context.save() - print("📖 Read message \(message.messageId) ") + logger.info("📖 Read message \(message.messageId) ") appState.unreadDirectMessages = user.unreadMessages UIApplication.shared.applicationIconBadgeNumber = appState.unreadChannelMessages + appState.unreadDirectMessages } catch { - print("Failed to read message \(message.messageId)") + logger.error("Failed to read message \(message.messageId): \(error.localizedDescription)") } } } diff --git a/Meshtastic/Views/Nodes/DetectionSensorLog.swift b/Meshtastic/Views/Nodes/DetectionSensorLog.swift index c59fd318..737ecfbc 100644 --- a/Meshtastic/Views/Nodes/DetectionSensorLog.swift +++ b/Meshtastic/Views/Nodes/DetectionSensorLog.swift @@ -133,11 +133,12 @@ struct DetectionSensorLog: View { contentType: .commaSeparatedText, defaultFilename: String("\(node.user?.longName ?? "Node") \("detection.sensor.log".localized)"), onCompletion: { result in - if case .success = result { - print("Detections metrics log download succeeded.") + switch result { + case .success: self.isExporting = false - } else { - print("Detections log download failed: \(result).") + logger.info("Detections metrics log download succeeded.") + case .failure(let error): + logger.error("Detections log download failed: \(error.localizedDescription).") } } ) diff --git a/Meshtastic/Views/Nodes/DeviceMetricsLog.swift b/Meshtastic/Views/Nodes/DeviceMetricsLog.swift index aa55a2b3..39e7f5f4 100644 --- a/Meshtastic/Views/Nodes/DeviceMetricsLog.swift +++ b/Meshtastic/Views/Nodes/DeviceMetricsLog.swift @@ -19,7 +19,7 @@ struct DeviceMetricsLog: View { @State private var batteryChartColor: Color = .blue @State private var airtimeChartColor: Color = .orange @State private var channelUtilizationChartColor: Color = .green - @ObservedObject var node: NodeInfoEntity + @ObservedObject var node: NodeInfoEntity var body: some View { VStack { @@ -188,9 +188,9 @@ struct DeviceMetricsLog: View { ) { Button("device.metrics.delete", role: .destructive) { if clearTelemetry(destNum: node.num, metricsType: 0, context: context) { - print("Cleared Device Metrics for \(node.num)") + logger.debug("Cleared Device Metrics for \(node.num)") } else { - print("Clear Device Metrics Log Failed") + logger.error("Clear Device Metrics Log Failed") } } } @@ -232,11 +232,12 @@ struct DeviceMetricsLog: View { contentType: .commaSeparatedText, defaultFilename: String("\(node.user?.longName ?? "Node") \("device.metrics.log".localized)"), onCompletion: { result in - if case .success = result { - print("Device metrics log download succeeded.") + switch result { + case .success: self.isExporting = false - } else { - print("Device metrics log download failed: \(result).") + logger.info("Device metrics log download succeeded.") + case .failure(let error): + logger.error("Device metrics log download failed: \(error.localizedDescription)") } } ) diff --git a/Meshtastic/Views/Nodes/EnvironmentMetricsLog.swift b/Meshtastic/Views/Nodes/EnvironmentMetricsLog.swift index 41d21db1..05804129 100644 --- a/Meshtastic/Views/Nodes/EnvironmentMetricsLog.swift +++ b/Meshtastic/Views/Nodes/EnvironmentMetricsLog.swift @@ -172,7 +172,7 @@ struct EnvironmentMetricsLog: View { ) { Button("Delete all environment metrics?", role: .destructive) { if clearTelemetry(destNum: node.num, metricsType: 1, context: context) { - print("Clear Environment Metrics Log Failed") + logger.error("Clear Environment Metrics Log Failed") } } } @@ -215,11 +215,12 @@ struct EnvironmentMetricsLog: View { contentType: .commaSeparatedText, defaultFilename: String("\(node.user?.longName ?? "Node") Environment Metrics Log"), onCompletion: { result in - if case .success = result { - print("Environment metrics log download succeeded.") + switch result { + case .success: self.isExporting = false - } else { - print("Environment metrics log download failed: \(result).") + logger.info("Environment metrics log download succeeded.") + case .failure(let error): + logger.error("Environment metrics log download failed: \(error.localizedDescription)") } } ) diff --git a/Meshtastic/Views/Nodes/Helpers/Map/WaypointForm.swift b/Meshtastic/Views/Nodes/Helpers/Map/WaypointForm.swift index 9a29e378..5e172152 100644 --- a/Meshtastic/Views/Nodes/Helpers/Map/WaypointForm.swift +++ b/Meshtastic/Views/Nodes/Helpers/Map/WaypointForm.swift @@ -157,7 +157,7 @@ struct WaypointForm: View { dismiss() } else { dismiss() - print("Send waypoint failed") + logger.warning("Send waypoint failed") } } label: { Label("Send", systemImage: "arrow.up") @@ -220,7 +220,7 @@ struct WaypointForm: View { dismiss() } else { dismiss() - print("Send waypoint failed") + logger.warning("Send waypoint failed") } }) } diff --git a/Meshtastic/Views/Nodes/Helpers/NodeDetail.swift b/Meshtastic/Views/Nodes/Helpers/NodeDetail.swift index 1505638a..412db86a 100644 --- a/Meshtastic/Views/Nodes/Helpers/NodeDetail.swift +++ b/Meshtastic/Views/Nodes/Helpers/NodeDetail.swift @@ -58,7 +58,7 @@ struct NodeDetail: View { Button { let adminMessageId = bleManager.requestDeviceMetadata(fromUser: connectedNode!.user!, toUser: node.user!, adminIndex: connectedNode!.myInfo!.adminIndex, context: context) if adminMessageId > 0 { - print("Sent node metadata request from node details") + logger.info("Sent node metadata request from node details") } } label: { Image(systemName: "arrow.clockwise") @@ -186,7 +186,7 @@ struct NodeDetail: View { ) { Button("Shutdown Node?", role: .destructive) { if !bleManager.sendShutdown(fromUser: connectedNode!.user!, toUser: node.user!, adminIndex: connectedNode!.myInfo!.adminIndex) { - print("Shutdown Failed") + logger.warning("Shutdown Failed") } } } @@ -206,7 +206,7 @@ struct NodeDetail: View { ) { Button("reboot.node", role: .destructive) { if !bleManager.sendReboot(fromUser: connectedNode!.user!, toUser: node.user!, adminIndex: connectedNode!.myInfo!.adminIndex) { - print("Reboot Failed") + logger.warning("Reboot Failed") } } } diff --git a/Meshtastic/Views/Nodes/MeshMap.swift b/Meshtastic/Views/Nodes/MeshMap.swift index 5787e3ea..4e4ec412 100644 --- a/Meshtastic/Views/Nodes/MeshMap.swift +++ b/Meshtastic/Views/Nodes/MeshMap.swift @@ -67,12 +67,12 @@ struct MeshMap: View { switch value { case let .second(_, tapValue): guard let point = tapValue?.location else { - print("Unable to retreive tap location from gesture data.") + logger.error("Unable to retreive tap location from gesture data.") return } guard let coordinate = reader.convert(point, from: .local) else { - print("Unable to convert local point to coordinate on map.") + logger.error("Unable to convert local point to coordinate on map.") return } @@ -84,7 +84,7 @@ struct MeshMap: View { editingWaypoint!.longitudeI = Int32((newWaypointCoord?.longitude ?? 0) * 1e7) editingWaypoint!.expire = Date.now.addingTimeInterval(60 * 480) editingWaypoint!.id = 0 - print("Long press occured at: \(coordinate)") + logger.debug("Long press occured at Lat: \(coordinate.latitude) Long: \(coordinate.longitude)") default: return } }) diff --git a/Meshtastic/Views/Nodes/NodeList.swift b/Meshtastic/Views/Nodes/NodeList.swift index 53cd2467..5ef7c8b1 100644 --- a/Meshtastic/Views/Nodes/NodeList.swift +++ b/Meshtastic/Views/Nodes/NodeList.swift @@ -72,9 +72,9 @@ struct NodeList: View { try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save Node Favorite Error") + logger.error("Save Node Favorite Error") } - print("Favorited a node") + logger.debug("Favorited a node") } } else { let success = bleManager.removeFavoriteNode(node: node, connectedNodeNum: Int64(connectedNodeNum)) @@ -84,9 +84,9 @@ struct NodeList: View { try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save Node Favorite Error") + logger.error("Save Node Favorite Error") } - print("Favorited a node") + logger.debug("Favorited a node") } } @@ -101,7 +101,7 @@ struct NodeList: View { try context.save() } catch { context.rollback() - print("đŸ’Ĩ Save User Mute Error") + logger.error("Save User Mute Error") } } label: { Label(node.user!.mute ? "Show Alerts" : "Hide Alerts", systemImage: node.user!.mute ? "bell" : "bell.slash") @@ -226,7 +226,7 @@ struct NodeList: View { if deleteNode != nil { let success = bleManager.removeNode(node: deleteNode!, connectedNodeNum: Int64(connectedNodeNum)) if !success { - print("Failed to delete node \(deleteNode?.user?.longName ?? "unknown".localized)") + logger.error("Failed to delete node \(deleteNode?.user?.longName ?? "unknown".localized)") } } } @@ -325,7 +325,7 @@ struct NodeList: View { let queryItems = urlComponent.queryItems let nodeNum = queryItems?.first(where: { $0.name == "nodenum" })?.value if nodeNum == nil { - print("nodeNum not found") + logger.debug("nodeNum not found") } else { selectedNode = nodes.first(where: { $0.num == Int64(nodeNum ?? "-1") }) AppState.shared.navigationPath = nil diff --git a/Meshtastic/Views/Nodes/PaxCounterLog.swift b/Meshtastic/Views/Nodes/PaxCounterLog.swift index f4e73c5a..81894abf 100644 --- a/Meshtastic/Views/Nodes/PaxCounterLog.swift +++ b/Meshtastic/Views/Nodes/PaxCounterLog.swift @@ -175,9 +175,9 @@ struct PaxCounterLog: View { ) { Button("paxcounter.delete", role: .destructive) { if clearPax(destNum: node.num, context: context) { - print("Cleared Pax Counter for \(node.num)") + logger.info("Cleared Pax Counter for \(node.num)") } else { - print("Clear Pax Counter Log Failed") + logger.error("Clear Pax Counter Log Failed") } } } @@ -219,11 +219,12 @@ struct PaxCounterLog: View { contentType: .commaSeparatedText, defaultFilename: String("\(node.user?.longName ?? "Node") \("paxcounter.log".localized)"), onCompletion: { result in - if case .success = result { - print("PAX Counter log download succeeded.") + switch result { + case .success: self.isExporting = false - } else { - print("PAX Counter log download failed: \(result).") + logger.info("PAX Counter log download succeeded") + case .failure(let error): + logger.error("PAX Counter log download failed: \(error.localizedDescription)") } } ) diff --git a/Meshtastic/Views/Nodes/PositionLog.swift b/Meshtastic/Views/Nodes/PositionLog.swift index f675e8dc..993a7e6a 100644 --- a/Meshtastic/Views/Nodes/PositionLog.swift +++ b/Meshtastic/Views/Nodes/PositionLog.swift @@ -130,9 +130,9 @@ struct PositionLog: View { ) { Button("Delete all positions?", role: .destructive) { if clearPositions(destNum: node.num, context: context) { - print("Successfully Cleared Position Log") + logger.info("Successfully Cleared Position Log") } else { - print("Clear Position Log Failed") + logger.error("Clear Position Log Failed") } } } @@ -154,11 +154,12 @@ struct PositionLog: View { contentType: .commaSeparatedText, defaultFilename: String("\(node.user?.longName ?? "Node") Position Log"), onCompletion: { result in - if case .success = result { - print("Position log download succeeded.") + switch result { + case .success: + logger.info("Position log download succeeded.") self.isExporting = false - } else { - print("Position log download failed: \(result).") + case .failure(let error): + logger.error("Position log download failed: \(error.localizedDescription)") } } ) diff --git a/Meshtastic/Views/Settings/AppSettings.swift b/Meshtastic/Views/Settings/AppSettings.swift index 5fbdc50a..22d18b3e 100644 --- a/Meshtastic/Views/Settings/AppSettings.swift +++ b/Meshtastic/Views/Settings/AppSettings.swift @@ -97,7 +97,7 @@ struct AppSettings: View { Button("Delete all map tiles?", role: .destructive) { tileManager.removeAll() totalDownloadedTileSize = tileManager.getAllDownloadedSize() - print("delete all tiles") + logger.debug("delete all tiles") } } } diff --git a/Meshtastic/Views/Settings/Channels.swift b/Meshtastic/Views/Settings/Channels.swift index b3792ec3..567aff6f 100644 --- a/Meshtastic/Views/Settings/Channels.swift +++ b/Meshtastic/Views/Settings/Channels.swift @@ -180,11 +180,11 @@ struct Channels: View { context.refresh(selectedChannel!, mergeChanges: true) do { try context.save() - print("💾 Saved Channel: \(channel.settings.name)") + logger.info("💾 Saved Channel: \(channel.settings.name)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Unresolved Core Data error in the channel editor. Error: \(nsError)") + logger.error("Unresolved Core Data error in the channel editor. Error: \(nsError)") } } else { guard let channelEntities = node?.myInfo?.channels as? [ChannelEntity], @@ -204,11 +204,11 @@ struct Channels: View { context.delete(channelEntity) do { try context.save() - print("💾 Deleted Channel: \(channel.settings.name)") + logger.info("💾 Deleted Channel: \(channel.settings.name)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Unresolved Core Data error in the channel editor. Error: \(nsError)") + logger.error("Unresolved Core Data error in the channel editor. Error: \(nsError)") } } diff --git a/Meshtastic/Views/Settings/Config/BluetoothConfig.swift b/Meshtastic/Views/Settings/Config/BluetoothConfig.swift index 6c1167a3..0757d958 100644 --- a/Meshtastic/Views/Settings/Config/BluetoothConfig.swift +++ b/Meshtastic/Views/Settings/Config/BluetoothConfig.swift @@ -100,7 +100,7 @@ struct BluetoothConfig: View { setBluetoothValues() // Need to request a BluetoothConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.bluetoothConfig == nil { - print("empty bluetooth config") + logger.info("empty bluetooth config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestBluetoothConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/DeviceConfig.swift b/Meshtastic/Views/Settings/Config/DeviceConfig.swift index 6fe96327..b5c74b4c 100644 --- a/Meshtastic/Views/Settings/Config/DeviceConfig.swift +++ b/Meshtastic/Views/Settings/Config/DeviceConfig.swift @@ -167,7 +167,7 @@ struct DeviceConfig: View { } } else { - print("NodeDB Reset Failed") + logger.error("NodeDB Reset Failed") } } } @@ -191,7 +191,7 @@ struct DeviceConfig: View { clearCoreDataDatabase(context: context, includeRoutes: false) } } else { - print("Factory Reset Failed") + logger.error("Factory Reset Failed") } } } @@ -241,7 +241,7 @@ struct DeviceConfig: View { setDeviceValues() // Need to request a LoRaConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.deviceConfig == nil { - print("empty device config") + logger.info("empty device config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral?.num ?? -1, context: context) if node != nil && connectedNode != nil && connectedNode?.user != nil { _ = bleManager.requestDeviceConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/DisplayConfig.swift b/Meshtastic/Views/Settings/Config/DisplayConfig.swift index 2b3531bc..f1a8caa9 100644 --- a/Meshtastic/Views/Settings/Config/DisplayConfig.swift +++ b/Meshtastic/Views/Settings/Config/DisplayConfig.swift @@ -164,7 +164,7 @@ struct DisplayConfig: View { // Need to request a LoRaConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.displayConfig == nil { - print("empty display config") + logger.info("empty display config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral?.num ?? 0, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestDisplayConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/LoRaConfig.swift b/Meshtastic/Views/Settings/Config/LoRaConfig.swift index f17cca5d..43ba0876 100644 --- a/Meshtastic/Views/Settings/Config/LoRaConfig.swift +++ b/Meshtastic/Views/Settings/Config/LoRaConfig.swift @@ -230,7 +230,7 @@ struct LoRaConfig: View { setLoRaValues() // Need to request a LoRaConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.loRaConfig == nil { - print("empty lora config") + logger.info("empty lora config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestLoRaConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/CannedMessagesConfig.swift b/Meshtastic/Views/Settings/Config/Module/CannedMessagesConfig.swift index ead273fe..af763bf3 100644 --- a/Meshtastic/Views/Settings/Config/Module/CannedMessagesConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/CannedMessagesConfig.swift @@ -233,7 +233,7 @@ struct CannedMessagesConfig: View { setCannedMessagesValues() // Need to request a CannedMessagesModuleConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.cannedMessageConfig == nil { - print("empty canned messages module config") + logger.info("empty canned messages module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestCannedMessagesModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/DetectionSensorConfig.swift b/Meshtastic/Views/Settings/Config/Module/DetectionSensorConfig.swift index 5eda232d..4034da37 100644 --- a/Meshtastic/Views/Settings/Config/Module/DetectionSensorConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/DetectionSensorConfig.swift @@ -189,7 +189,7 @@ struct DetectionSensorConfig: View { setDetectionSensorValues() // Need to request a Detection Sensor Module Config from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.detectionSensorConfig == nil { - print("empty detection sensor module config") + logger.info("empty detection sensor module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestDetectionSensorModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/ExternalNotificationConfig.swift b/Meshtastic/Views/Settings/Config/Module/ExternalNotificationConfig.swift index ec9aedcf..bbc0c9c4 100644 --- a/Meshtastic/Views/Settings/Config/Module/ExternalNotificationConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/ExternalNotificationConfig.swift @@ -199,7 +199,7 @@ struct ExternalNotificationConfig: View { setExternalNotificationValues() // Need to request a TelemetryModuleConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.externalNotificationConfig == nil { - print("empty external notification module config") + logger.info("empty external notification module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestExternalNotificationModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/MQTTConfig.swift b/Meshtastic/Views/Settings/Config/Module/MQTTConfig.swift index 6244debc..5d27ae82 100644 --- a/Meshtastic/Views/Settings/Config/Module/MQTTConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/MQTTConfig.swift @@ -361,7 +361,7 @@ struct MQTTConfig: View { setMqttValues() // Need to request a TelemetryModuleConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.mqttConfig == nil { - print("empty mqtt module config") + logger.info("empty mqtt module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestMqttModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) @@ -379,8 +379,8 @@ struct MQTTConfig: View { let region = RegionCodes(rawValue: Int(node?.loRaConfig?.regionCode ?? 0))?.topic defaultTopic = "msh/" + (region ?? "UNSET") geocoder.reverseGeocodeLocation(LocationsHandler.shared.locationsArray.first!, completionHandler: {(placemarks, error) in - if error != nil { - print("Failed to reverse geocode location") + if let error { + logger.error("Failed to reverse geocode location: \(error.localizedDescription)") return } @@ -412,7 +412,7 @@ struct MQTTConfig: View { nearbyTopics.append(neightborhoodTopic) } } else { - print("No Location") + logger.debug("No Location") } }) } diff --git a/Meshtastic/Views/Settings/Config/Module/RangeTestConfig.swift b/Meshtastic/Views/Settings/Config/Module/RangeTestConfig.swift index 425b41e4..7c8694f6 100644 --- a/Meshtastic/Views/Settings/Config/Module/RangeTestConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/RangeTestConfig.swift @@ -81,7 +81,7 @@ struct RangeTestConfig: View { setRangeTestValues() // Need to request a RangeTestModule Config from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.rangeTestConfig == nil { - print("empty range test module config") + logger.debug("empty range test module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestRangeTestModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/SerialConfig.swift b/Meshtastic/Views/Settings/Config/Module/SerialConfig.swift index 19b58c6f..ad8ac991 100644 --- a/Meshtastic/Views/Settings/Config/Module/SerialConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/SerialConfig.swift @@ -137,7 +137,7 @@ struct SerialConfig: View { setSerialValues() // Need to request a SerialModuleConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.serialConfig == nil { - print("empty serial module config") + logger.debug("empty serial module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestSerialModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/StoreForwardConfig.swift b/Meshtastic/Views/Settings/Config/Module/StoreForwardConfig.swift index 15cbabed..8dea5716 100644 --- a/Meshtastic/Views/Settings/Config/Module/StoreForwardConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/StoreForwardConfig.swift @@ -116,7 +116,7 @@ struct StoreForwardConfig: View { do { try context.save() } catch { - print("Failed to save isRouter") + logger.error("Failed to save isRouter: \(error.localizedDescription)") } } @@ -147,7 +147,7 @@ struct StoreForwardConfig: View { // Need to request a Detection Sensor Module Config from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.storeForwardConfig == nil { - print("empty store and forward module config") + logger.debug("empty store and forward module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestStoreAndForwardModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/Module/TelemetryConfig.swift b/Meshtastic/Views/Settings/Config/Module/TelemetryConfig.swift index f645fc51..fb433494 100644 --- a/Meshtastic/Views/Settings/Config/Module/TelemetryConfig.swift +++ b/Meshtastic/Views/Settings/Config/Module/TelemetryConfig.swift @@ -134,7 +134,7 @@ struct TelemetryConfig: View { setTelemetryValues() // Need to request a TelemetryModuleConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.telemetryConfig == nil { - print("empty telemetry module config") + logger.info("empty telemetry module config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestTelemetryModuleConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/NetworkConfig.swift b/Meshtastic/Views/Settings/Config/NetworkConfig.swift index 2527138b..05386683 100644 --- a/Meshtastic/Views/Settings/Config/NetworkConfig.swift +++ b/Meshtastic/Views/Settings/Config/NetworkConfig.swift @@ -119,7 +119,7 @@ struct NetworkConfig: View { setNetworkValues() // Need to request a NetworkConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.networkConfig == nil { - print("empty network config") + logger.info("empty network config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestNetworkConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Config/PositionConfig.swift b/Meshtastic/Views/Settings/Config/PositionConfig.swift index e92088ff..3ed23b2e 100644 --- a/Meshtastic/Views/Settings/Config/PositionConfig.swift +++ b/Meshtastic/Views/Settings/Config/PositionConfig.swift @@ -284,35 +284,35 @@ struct PositionConfig: View { if node?.positionConfig?.fixedPosition ?? false { Button("Remove", role: .destructive) { if !bleManager.removeFixedPosition(fromUser: node!.user!, channel: 0) { - print("Set Position Failed") + logger.error("Set Position Failed") } - print("Remove a fixed position here") + logger.debug("Remove a fixed position here") let mutablePositions = node?.positions?.mutableCopy() as? NSMutableOrderedSet mutablePositions?.removeAllObjects() node?.positions = mutablePositions node?.positionConfig?.fixedPosition = false do { try context.save() - print("💾 Updated Position Config with Fixed Position = false") + logger.info("💾 Updated Position Config with Fixed Position = false") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving Position Config Entity \(nsError)") + logger.error("Error Saving Position Config Entity \(nsError)") } } } else { Button("Set") { if !bleManager.setFixedPosition(fromUser: node!.user!, channel: 0) { - print("Set Position Failed") + logger.error("Set Position Failed") } node?.positionConfig?.fixedPosition = true do { try context.save() - print("💾 Updated Position Config with Fixed Position = true") + logger.info("💾 Updated Position Config with Fixed Position = true") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving Position Config Entity \(nsError)") + logger.error("Error Saving Position Config Entity \(nsError)") } } } @@ -375,7 +375,7 @@ struct PositionConfig: View { supportedVersion = bleManager.connectedVersion == "0.0.0" || self.minimumVersion.compare(bleManager.connectedVersion, options: .numeric) == .orderedAscending || minimumVersion.compare(bleManager.connectedVersion, options: .numeric) == .orderedSame // Need to request a PositionConfig from the remote node before allowing changes if bleManager.connectedPeripheral != nil && node?.positionConfig == nil { - print("empty position config") + logger.info("empty position config") let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral.num, context: context) if node != nil && connectedNode != nil { _ = bleManager.requestPositionConfig(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) diff --git a/Meshtastic/Views/Settings/Firmware.swift b/Meshtastic/Views/Settings/Firmware.swift index 2b77a9b1..748a7cd3 100644 --- a/Meshtastic/Views/Settings/Firmware.swift +++ b/Meshtastic/Views/Settings/Firmware.swift @@ -115,7 +115,7 @@ struct Firmware: View { bleManager.disconnectPeripheral(reconnect: false) } } else { - print("Enter DFU Failed") + logger.error("Enter DFU Failed") } } } label: { @@ -160,7 +160,7 @@ struct Firmware: View { let connectedNode = getNodeInfo(id: bleManager.connectedPeripheral?.num ?? 0, context: context) if connectedNode != nil { if !bleManager.sendRebootOta(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode!.myInfo!.adminIndex) { - print("Reboot Failed") + logger.error("Reboot Failed") } } } label: { diff --git a/Meshtastic/Views/Settings/FirmwareApi.swift b/Meshtastic/Views/Settings/FirmwareApi.swift index e9670f2c..ff9186ce 100644 --- a/Meshtastic/Views/Settings/FirmwareApi.swift +++ b/Meshtastic/Views/Settings/FirmwareApi.swift @@ -49,7 +49,7 @@ class Api: ObservableObject { /// List from https://api.meshtastic.org/resource/deviceHardware guard let url = Bundle.main.url(forResource: "DeviceHardware.json", withExtension: nil) else { - print("Couldn't find DeviceHardware.json in main bundle.") + logger.critical("Couldn't find DeviceHardware.json in main bundle.") return } @@ -60,8 +60,8 @@ class Api: ObservableObject { DispatchQueue.main.async { completion(deviceHardware) } - } catch let jsonError as NSError { - print("JSON decode failure: \(jsonError.localizedDescription)") + } catch { + logger.error("JSON decode failure: \(error.localizedDescription)") } return } @@ -70,7 +70,7 @@ class Api: ObservableObject { func loadFirmwareReleaseData(completion: @escaping (FirmwareReleases) -> Void) { guard let url = URL(string: "https://api.meshtastic.org/github/firmware/list") else { - print("Invalid url...") + logger.error("Invalid url...") return } URLSession.shared.dataTask(with: url) { data, _, _ in @@ -80,8 +80,8 @@ class Api: ObservableObject { DispatchQueue.main.async { completion(firmwareReleases) } - } catch let jsonError as NSError { - print("JSON decode failure: \(jsonError.localizedDescription)") + } catch { + logger.error("JSON decode failure: \(error.localizedDescription)") } return } diff --git a/Meshtastic/Views/Settings/MeshLog.swift b/Meshtastic/Views/Settings/MeshLog.swift index 4f0072ca..383c2e07 100644 --- a/Meshtastic/Views/Settings/MeshLog.swift +++ b/Meshtastic/Views/Settings/MeshLog.swift @@ -46,10 +46,11 @@ struct MeshLog: View { contentType: UTType.plainText, defaultFilename: "mesh-activity-log", onCompletion: { result in - if case .success = result { - print("Mesh activity log download: success.") - } else { - print("Mesh activity log download \(result).") + switch result { + case .success: + logger.info("Mesh activity log download: success") + case .failure(let error): + logger.error("Mesh activity log download: \(error.localizedDescription)") } } ) @@ -64,7 +65,7 @@ struct MeshLog: View { try text.write(to: logFile!, atomically: false, encoding: .utf8) logs.removeAll() } catch { - print(error) + logger.error("\(error.localizedDescription)") } } label: { Label("Clear", systemImage: "trash.fill") diff --git a/Meshtastic/Views/Settings/RouteRecorder.swift b/Meshtastic/Views/Settings/RouteRecorder.swift index d05cc2e3..df4a3c61 100644 --- a/Meshtastic/Views/Settings/RouteRecorder.swift +++ b/Meshtastic/Views/Settings/RouteRecorder.swift @@ -184,11 +184,11 @@ struct RouteRecorder: View { self.recording = newRoute do { try context.save() - print("💾 Saved a new route") + logger.info("💾 Saved a new route") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving RouteEntity from the Route Recorder \(nsError)") + logger.error("Error Saving RouteEntity from the Route Recorder \(nsError)") } } label: { Label("start", systemImage: "play") @@ -242,11 +242,11 @@ struct RouteRecorder: View { locationsHandler.recordingStarted = nil do { try context.save() - print("💾 Saved a route finish") + logger.info("💾 Saved a route finish") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving RouteEntity from the Route Recorder \(nsError)") + logger.error("Error Saving RouteEntity from the Route Recorder \(nsError)") } isShowingDetails = false } label: { @@ -297,12 +297,12 @@ struct RouteRecorder: View { locationEntity.longitudeI = Int32(loc.coordinate.longitude * 1e7) do { try context.save() - print("💾 Saved a new route location") - // print("💾 Updated Canned Messages Messages For: \(fetchedNode[0].num)") + logger.info("💾 Saved a new route location") + // logger.info("💾 Updated Canned Messages Messages For: \(fetchedNode[0].num)") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving LocationEntity from the Route Recorder \(nsError)") + logger.error("Error Saving LocationEntity from the Route Recorder \(nsError)") } } } diff --git a/Meshtastic/Views/Settings/Routes.swift b/Meshtastic/Views/Settings/Routes.swift index dc112ae1..d27c3e7f 100644 --- a/Meshtastic/Views/Settings/Routes.swift +++ b/Meshtastic/Views/Settings/Routes.swift @@ -64,7 +64,7 @@ struct Routes: View { var latIndex = -1 var longIndex = -1 for index in headers!.indices { - print("\(index): \( headers![index])") + logger.debug("\(index): \( headers![index])") if headers![index].trimmingCharacters(in: .whitespaces) == "Latitude" { latIndex = index } else if headers![index].trimmingCharacters(in: .whitespaces) == "Longitude" { @@ -88,14 +88,14 @@ struct Routes: View { loc.latitudeI = Int32((Double(latitude) ?? 0) * 1e7) loc.longitudeI = Int32((Double(longitude) ?? 0) * 1e7) newLocations.append(loc) - print("Longitude: \(longitude) Latitude: \(latitude)") + logger.debug("Longitude: \(longitude) Latitude: \(latitude)") } } newRoute.locations? = NSOrderedSet(array: newLocations) do { try context.save() } catch let error as NSError { - print("Error: \(error.localizedDescription)") + logger.error("\(error.localizedDescription)") isShowingBadFileAlert = true } } else { @@ -103,11 +103,12 @@ struct Routes: View { } } catch { - print("error: \(error)") // to do deal with errors + // TODO: deal with errors + logger.error("\(error.localizedDescription)") } } catch { - print("CSV Import Error") + logger.error("CSV Import Error: \(error.localizedDescription)") } } List(routes, id: \.self, selection: $selectedRoute) { route in @@ -151,7 +152,7 @@ struct Routes: View { do { try context.save() } catch let error as NSError { - print("Error: \(error.localizedDescription)") + logger.error("\(error.localizedDescription)") } } label: { Label("delete", systemImage: "trash") @@ -223,11 +224,11 @@ struct Routes: View { do { try context.save() selectedRoute = nil - print("💾 Saved a route") + logger.info("💾 Saved a route") } catch { context.rollback() let nsError = error as NSError - print("đŸ’Ĩ Error Saving RouteEntity from the Route Editor \(nsError)") + logger.error("Error Saving RouteEntity from the Route Editor \(nsError)") } } .buttonStyle(.bordered) @@ -295,11 +296,12 @@ struct Routes: View { contentType: .commaSeparatedText, defaultFilename: String("\(selectedRoute?.name ?? "Route") Log"), onCompletion: { result in - if case .success = result { - print("Route log download succeeded.") + switch result { + case .success: self.isExporting = false - } else { - print("Route log download failed: \(result).") + logger.info("Route log download succeeded.") + case .failure(let error): + logger.error("Route log download failed: \(error.localizedDescription).") } } ) diff --git a/Meshtastic/Views/Settings/Settings.swift b/Meshtastic/Views/Settings/Settings.swift index 187a4797..410337a2 100644 --- a/Meshtastic/Views/Settings/Settings.swift +++ b/Meshtastic/Views/Settings/Settings.swift @@ -142,7 +142,7 @@ struct Settings: View { if connectedNode != nil && connectedNode?.user != nil && connectedNode?.myInfo != nil && node?.user != nil && node?.metadata == nil { let adminMessageId = bleManager.requestDeviceMetadata(fromUser: connectedNode!.user!, toUser: node!.user!, adminIndex: connectedNode!.myInfo!.adminIndex, context: context) if adminMessageId > 0 { - print("Sent node metadata request from node details") + logger.info("Sent node metadata request from node details") } } } diff --git a/Meshtastic/Views/Settings/UserConfig.swift b/Meshtastic/Views/Settings/UserConfig.swift index 12f584d1..e58d4c83 100644 --- a/Meshtastic/Views/Settings/UserConfig.swift +++ b/Meshtastic/Views/Settings/UserConfig.swift @@ -167,7 +167,6 @@ struct UserConfig: View { ham.callSign = longName ham.txPower = Int32(txPower) ham.frequency = overrideFrequency - print(ham) let adminMessageId = bleManager.saveLicensedUser(ham: ham, fromUser: connectedUser, toUser: node!.user!, adminIndex: connectedNode?.myInfo?.adminIndex ?? 0) if adminMessageId > 0 { hasChanges = false