From d327ac0ed7bc25feba31212eb10de5ddecfa3f0b Mon Sep 17 00:00:00 2001 From: Garth Vander Houwen Date: Sat, 15 Oct 2022 10:14:08 -0700 Subject: [PATCH] Clean up logging --- Meshtastic/Helpers/BLEManager.swift | 197 +++++-------- Meshtastic/Helpers/MeshPackets.swift | 289 ++++++-------------- Meshtastic/Views/Messages/MessageList.swift | 7 - 3 files changed, 143 insertions(+), 350 deletions(-) diff --git a/Meshtastic/Helpers/BLEManager.swift b/Meshtastic/Helpers/BLEManager.swift index d483a710..eca59b9b 100644 --- a/Meshtastic/Helpers/BLEManager.swift +++ b/Meshtastic/Helpers/BLEManager.swift @@ -72,7 +72,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph var DFURESULT_characteristic: CBCharacteristic? var DFUREGION_characteristic: CBCharacteristic? - private var meshLoggingEnabled: Bool = true + //private var meshLoggingEnabled: Bool = true let meshLog = documentsFolder.appendingPathComponent("meshlog.txt") // MARK: init BLEManager @@ -133,13 +133,10 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let name: String = timerContext["name", default: "Unknown"] self.timeoutTimerCount += 1 - self.isConnecting = true self.lastConnectionError = "" if timeoutTimerCount == 10 { - if connectedPeripheral != nil { - self.centralManager?.cancelPeripheralConnection(connectedPeripheral.peripheral) } connectedPeripheral = nil @@ -149,17 +146,12 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph } self.isConnected = false self.isConnecting = false - self.lastConnectionError = "🚨 Connection failed after \(timeoutTimerCount) attempts to connect to \(name). You may need to forget your device under Settings > Bluetooth." - - if meshLoggingEnabled { MeshLogger.log("🚨 BLE Connection failed after making \(timeoutTimerCount) attempts to connect to \(name). You may need to forget your device under Settings > Bluetooth.") } - + MeshLogger.log(lastConnectionError) self.timeoutTimerCount = 0 self.startScanning() - } else { - - if meshLoggingEnabled { MeshLogger.log("🚨 BLE Connecting 2 Second Timeout Timer Fired \(timeoutTimerCount) Time(s): \(name)") } + MeshLogger.log("🚨 BLE Connecting 2 Second Timeout Timer Fired \(timeoutTimerCount) Time(s): \(name)") } } @@ -241,6 +233,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph } else if userSettings!.preferredPeripheralId == peripheral.identifier.uuidString { self.preferredPeripheral = true } else { + self.preferredPeripheral = false print("Trying to connect a non prefered peripheral") } // Invalidate and reset connection timer count, remove any connection errors @@ -330,7 +323,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if let e = error { - if meshLoggingEnabled { MeshLogger.log("🚫 BLE didDiscoverCharacteristicsFor error by \(peripheral.name ?? "Unknown") \(e)") } + MeshLogger.log("🚫 BLE didDiscoverCharacteristicsFor error by \(peripheral.name ?? "Unknown") \(e)") } guard let characteristics = service.characteristics else { return } @@ -340,50 +333,40 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph switch characteristic.uuid { case TORADIO_UUID: - - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover TORADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover TORADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") TORADIO_characteristic = characteristic case FROMRADIO_UUID: - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover FROMRADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover FROMRADIO characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") FROMRADIO_characteristic = characteristic peripheral.readValue(for: FROMRADIO_characteristic) case FROMNUM_UUID: - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover FROMNUM (Notify) characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover FROMNUM (Notify) characteristic for Meshtastic by \(peripheral.name ?? "Unknown")") FROMNUM_characteristic = characteristic peripheral.setNotifyValue(true, for: characteristic) case DFUSIZE_UUID: - - print("βœ… DFU Size characteristic OK") - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover DFU Size characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover DFU Size characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") DFUSIZE_characteristic = characteristic case DFUDATA_UUID: - - print("βœ… DFU Data characteristic OK") - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover DFU Data characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover DFU Data characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") DFUDATA_characteristic = characteristic case DFUCRC32_UUID: - - print("βœ… DFU CRC32 characteristic OK") - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover DFU CRC32 characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover DFU CRC32 characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") DFUCRC32_characteristic = characteristic - + case DFURESULT_UUID: - - print("βœ… DFU Result characteristic OK") - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover DFU Result characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") } + MeshLogger.log("βœ… BLE did discover DFU Result characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") DFURESULT_characteristic = characteristic - - case DFUREGION_UUID: - print("βœ… DFU Region characteristic OK") - if meshLoggingEnabled { MeshLogger.log("βœ… BLE did discover DFU Region characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") } + case DFUREGION_UUID: + + MeshLogger.log("βœ… BLE did discover DFU Region characteristic for Meshtastic DFU by \(peripheral.name ?? "Unknown")") DFUREGION_characteristic = characteristic default: @@ -432,7 +415,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if FROMRADIO_characteristic == nil { - if meshLoggingEnabled { MeshLogger.log("🚨 Unsupported Firmware Version Detected, unable to connect to device.") } + MeshLogger.log("🚨 Unsupported Firmware Version Detected, unable to connect to device.") invalidVersion = true return @@ -453,8 +436,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if let errorText = error?.localizedDescription { - - if meshLoggingEnabled { MeshLogger.log("🚫 didUpdateNotificationStateFor error: \(errorText)") } + MeshLogger.log("🚫 didUpdateNotificationStateFor error: \(errorText)") } } @@ -468,20 +450,16 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let errorCode = (e as NSError).code if errorCode == 5 { // CBATTErrorDomain Code=5 "Authentication is insufficient." - // BLE Pin connection error lastConnectionError = "🚫 BLE \(e.localizedDescription) Please try connecting again and check the PIN carefully." - if meshLoggingEnabled { MeshLogger.log("🚫 BLE \(e.localizedDescription) Please try connecting again and check the PIN carefully.") } + MeshLogger.log("🚫 BLE \(e.localizedDescription) Please try connecting again and check the PIN carefully.") self.centralManager?.cancelPeripheralConnection(peripheral) - } if errorCode == 15 { // CBATTErrorDomain Code=15 "Encryption is insufficient." - // BLE Pin connection error lastConnectionError = "🚫 BLE \(e.localizedDescription) Please try connecting again and check the PIN carefully." - if meshLoggingEnabled { MeshLogger.log("🚫 BLE \(e.localizedDescription) Please try connecting again. You may need to forget the device under Settings > General > Bluetooth.") } + MeshLogger.log("🚫 BLE \(e.localizedDescription) Please try connecting again. You may need to forget the device under Settings > General > Bluetooth.") self.centralManager?.cancelPeripheralConnection(peripheral) - } } @@ -531,7 +509,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph } else { - let myInfo = myInfoPacket(myInfo: decodedInfo.myInfo, peripheralId: self.connectedPeripheral.id, meshLogging: meshLoggingEnabled, context: context!) + let myInfo = myInfoPacket(myInfo: decodedInfo.myInfo, peripheralId: self.connectedPeripheral.id, context: context!) self.userSettings?.preferredNodeNum = myInfo?.myNodeNum ?? 0 @@ -552,7 +530,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if decodedInfo.nodeInfo.num != 0 && !invalidVersion { nowKnown = true - let nodeInfo = nodeInfoPacket(nodeInfo: decodedInfo.nodeInfo, meshLogging: meshLoggingEnabled, context: context!) + let nodeInfo = nodeInfoPacket(nodeInfo: decodedInfo.nodeInfo, context: context!) if nodeInfo != nil { @@ -572,53 +550,42 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph // Channels if decodedInfo.channel.isInitialized { nowKnown = true - channelPacket(channel: decodedInfo.channel, fromNum: connectedPeripheral.num, meshLogging: meshLoggingEnabled, context: context!) + channelPacket(channel: decodedInfo.channel, fromNum: connectedPeripheral.num, context: context!) } // Config if decodedInfo.config.isInitialized && !invalidVersion { nowKnown = true - localConfig(config: decodedInfo.config, meshlogging: meshLoggingEnabled, context: context!, nodeNum: self.connectedPeripheral.num, nodeLongName: self.connectedPeripheral.longName) + localConfig(config: decodedInfo.config, context: context!, nodeNum: self.connectedPeripheral.num, nodeLongName: self.connectedPeripheral.longName) } // Module Config if decodedInfo.moduleConfig.isInitialized && !invalidVersion { nowKnown = true - moduleConfig(config: decodedInfo.moduleConfig, meshlogging: meshLoggingEnabled, context: context!, nodeNum: self.connectedPeripheral.num, nodeLongName: self.connectedPeripheral.longName) + moduleConfig(config: decodedInfo.moduleConfig, context: context!, nodeNum: self.connectedPeripheral.num, nodeLongName: self.connectedPeripheral.longName) if decodedInfo.moduleConfig.payloadVariant == ModuleConfig.OneOf_PayloadVariant.cannedMessage(decodedInfo.moduleConfig.cannedMessage) { self.getCannedMessageModuleMessages(destNum: self.connectedPeripheral.num, wantResponse: true) } } // Log any other unknownApp calls - if !nowKnown { - - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Unknown App UNHANDLED \(try! decodedInfo.packet.jsonString())") } - } + if !nowKnown { MeshLogger.log("ℹ️ MESH PACKET received for Unknown App UNHANDLED \(try! decodedInfo.packet.jsonString())") } case .textMessageApp: - textMessageAppPacket(packet: decodedInfo.packet, connectedNode: (self.connectedPeripheral != nil ? connectedPeripheral.num : 0), meshLogging: meshLoggingEnabled, context: context!) + textMessageAppPacket(packet: decodedInfo.packet, connectedNode: (self.connectedPeripheral != nil ? connectedPeripheral.num : 0), context: context!) case .remoteHardwareApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Remote Hardware App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Remote Hardware App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .positionApp: - positionPacket(packet: decodedInfo.packet, meshLogging: meshLoggingEnabled, context: context!) + positionPacket(packet: decodedInfo.packet, context: context!) case .waypointApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Waypoint App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Waypoint App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .nodeinfoApp: - - if !invalidVersion { - - nodeInfoAppPacket(packet: decodedInfo.packet, meshLogging: meshLoggingEnabled, context: context!) - } + if !invalidVersion { nodeInfoAppPacket(packet: decodedInfo.packet, context: context!) } case .routingApp: - - if !invalidVersion { - - routingPacket(packet: decodedInfo.packet, meshLogging: meshLoggingEnabled, context: context!) - } + if !invalidVersion { routingPacket(packet: decodedInfo.packet, context: context!) } case .adminApp: - adminAppPacket(packet: decodedInfo.packet, meshLogging: meshLoggingEnabled, context: context!) + adminAppPacket(packet: decodedInfo.packet, context: context!) case .replyApp: MeshLogger.log("ℹ️ MESH PACKET received for Reply App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .ipTunnelApp: @@ -628,25 +595,21 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph case .storeForwardApp: MeshLogger.log("ℹ️ MESH PACKET received for Store Forward App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .rangeTestApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Range Test App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Range Test App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .telemetryApp: - - if !invalidVersion { - - telemetryPacket(packet: decodedInfo.packet, meshLogging: meshLoggingEnabled, context: context!) - } + if !invalidVersion { telemetryPacket(packet: decodedInfo.packet, context: context!) } case .textMessageCompressedApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Text Message Compressed App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Text Message Compressed App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .zpsApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for ZPS App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for ZPS App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .privateApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Private App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Private App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .atakForwarder: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for ATAK Forwarder App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for ATAK Forwarder App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .simulatorApp: - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Simulator App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Simulator App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .UNRECOGNIZED(_): - if meshLoggingEnabled { MeshLogger.log("ℹ️ MESH PACKET received for Other App UNHANDLED \(try! decodedInfo.packet.jsonString())") } + MeshLogger.log("ℹ️ MESH PACKET received for Other App UNHANDLED \(try! decodedInfo.packet.jsonString())") case .max: print("MAX PORT NUM OF 511") } @@ -669,7 +632,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph } } catch { - print("πŸ’₯ Error Saving the All - Broadcast User") + MeshLogger.log("πŸ’₯ Error Saving the All - Broadcast User") } // MARK: Share Location Position Update Timer @@ -687,7 +650,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if decodedInfo.configCompleteID != 0 && decodedInfo.configCompleteID == configNonce { invalidVersion = false lastConnectionError = "" - if meshLoggingEnabled { MeshLogger.log("🀜 BLE Config Complete Packet Id: \(decodedInfo.configCompleteID)") } + MeshLogger.log("🀜 BLE Config Complete Packet Id: \(decodedInfo.configCompleteID)") self.connectedPeripheral.subscribed = true peripherals.removeAll(where: { $0.peripheral.state == CBPeripheralState.disconnected }) // Config conplete returns so we don't read the characteristic again @@ -719,8 +682,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if preferredPeripheral != nil && preferredPeripheral?.peripheral != nil { connectTo(peripheral: preferredPeripheral!.peripheral) } - if meshLoggingEnabled { MeshLogger.log("🚫 Message Send Failed, not properly connected to \(preferredPeripheral?.name ?? "Unknown")") } - + MeshLogger.log("🚫 Message Send Failed, not properly connected to \(preferredPeripheral?.name ?? "Unknown")") success = false } else if message.count < 1 { @@ -796,16 +758,14 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph toRadio.packet = meshPacket let binaryData: Data = try! toRadio.serializedData() - - if meshLoggingEnabled { MeshLogger.log("πŸ“² New messageId \(newMessage.messageId) sent to \(newMessage.toUser?.longName! ?? "Unknown")") } - + + MeshLogger.log("πŸ“² New messageId \(newMessage.messageId) sent to \(newMessage.toUser?.longName! ?? "Unknown")") if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) do { try context!.save() - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ Saved a new sent message from \(connectedPeripheral.num) to \(toUserNum)") } + MeshLogger.log("πŸ’Ύ Saved a new sent message from \(connectedPeripheral.num) to \(toUserNum)") success = true } catch { @@ -813,7 +773,7 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph context!.rollback() let nsError = error as NSError - if meshLoggingEnabled { MeshLogger.log("πŸ’₯ Unresolved Core Data error in Send Message Function it is likely that your database is corrupted deleting and re-installing the app should clear the corrupted data. Error: \(nsError)") } + MeshLogger.log("πŸ’₯ Unresolved Core Data error in Send Message Function your database is corrupted running a node db reset should clean up the data. Error: \(nsError)") } } } @@ -869,15 +829,12 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph toRadio.packet = meshPacket let binaryData: Data = try! toRadio.serializedData() - if meshLoggingEnabled { MeshLogger.log("πŸ“ Sent a Location Packet from the Apple device GPS to node: \(fromNodeNum)") } + MeshLogger.log("πŸ“ Sent a Location Packet from the Apple device GPS to node: \(fromNodeNum)") if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) success = true - } - return success } @@ -980,24 +937,18 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { do { - try context!.save() - - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ Saved a Shutdown Admin Message for node: \(String(destNum))") } - + MeshLogger.log("πŸ’Ύ Saved a Shutdown Admin Message for node: \(String(destNum))") connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - return true } catch { - context!.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Inserting New Core Data MessageEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error Inserting New Core Data MessageEntity: \(nsError)") + print() } } - return false } @@ -1017,7 +968,6 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph var dataMessage = DataMessage() dataMessage.payload = try! adminPacket.serializedData() dataMessage.portnum = PortNum.adminApp - meshPacket.decoded = dataMessage var toRadio: ToRadio! @@ -1029,24 +979,16 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { do { - try context!.save() - - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ Saved a Reboot Admin Message for node: \(String(destNum))") } - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - + MeshLogger.log("πŸ’Ύ Saved a Reboot Admin Message for node: \(String(destNum))") return true - } catch { - context!.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Inserting New Core Data MessageEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error Inserting New Core Data MessageEntity: \(nsError)") } } - return false } @@ -1075,12 +1017,10 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let binaryData: Data = try! toRadio.serializedData() if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ Sent a Factory Reset for node: \(String(destNum))") } + MeshLogger.log("πŸ’Ύ Sent a Factory Reset for node: \(String(destNum))") return true } - return false } @@ -1109,16 +1049,10 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let binaryData: Data = try! toRadio.serializedData() if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { - - do { - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ Sent a NodeDB Reset for node: \(String(destNum))") } - return true - } catch { - print("πŸ’₯ Error Sending NodeDB Reset") - } + connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) + MeshLogger.log("πŸ’Ύ Sent a NodeDB Reset for node: \(String(destNum))") + return true } - return false } @@ -1439,11 +1373,9 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph let binaryData: Data = try! toRadio.serializedData() if connectedPeripheral!.peripheral.state == CBPeripheralState.connected { - - if meshLoggingEnabled { MeshLogger.log("✈️ Sent a Canned Messages Module Get Messages Request Admin Message for node: \(String(destNum))") } - - connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - return true + MeshLogger.log("✈️ Sent a Canned Messages Module Get Messages Request Admin Message for node: \(String(destNum))") + connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) + return true } return false @@ -1614,10 +1546,8 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph do { connectedPeripheral.peripheral.writeValue(binaryData, for: TORADIO_characteristic, type: .withResponse) - try context!.save() - - if meshLoggingEnabled { MeshLogger.log("πŸ’Ύ \(adminDescription)") } + MeshLogger.log("πŸ’Ύ \(adminDescription)") return true @@ -1626,9 +1556,8 @@ class BLEManager: NSObject, ObservableObject, CBCentralManagerDelegate, CBPeriph context!.rollback() let nsError = error as NSError - print("πŸ’₯ Error inserting new core data MessageEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error inserting new core data MessageEntity: \(nsError)") } - } return false } diff --git a/Meshtastic/Helpers/MeshPackets.swift b/Meshtastic/Helpers/MeshPackets.swift index 8114da96..4a39e5b9 100644 --- a/Meshtastic/Helpers/MeshPackets.swift +++ b/Meshtastic/Helpers/MeshPackets.swift @@ -9,12 +9,12 @@ import Foundation import CoreData import SwiftUI -func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectContext, nodeNum: Int64, nodeLongName: String) { +func localConfig (config: Config, context:NSManagedObjectContext, nodeNum: Int64, nodeLongName: String) { // We don't care about any of the Power settings, config is available for everyting else if config.payloadVariant == Config.OneOf_PayloadVariant.bluetooth(config.bluetooth) { - if meshlogging { MeshLogger.log("πŸ–₯️ Bluetooth config received: \(String(nodeNum))") } + MeshLogger.log("πŸ–₯️ Bluetooth config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -44,83 +44,66 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Bluetooth Config for node number: \(String(nodeNum))") } - + MeshLogger.log("πŸ’Ύ Updated Bluetooth Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Updating Core Data BluetoothConfigEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error Updating Core Data BluetoothConfigEntity: \(nsError)") } - } else { - - print("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save Bluetooth Config") + MeshLogger.log("πŸ’₯ 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)") + MeshLogger.log("πŸ’₯ Fetching node for core data BluetoothConfigEntity failed: \(nsError)") } } if config.payloadVariant == Config.OneOf_PayloadVariant.device(config.device) { - if meshlogging { MeshLogger.log("πŸ“Ÿ Device config received: \(String(nodeNum))") } - + MeshLogger.log("πŸ“Ÿ Device config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) do { let fetchedNode = try context.fetch(fetchNodeInfoRequest) as! [NodeInfoEntity] - // Found a node, save Device Config if !fetchedNode.isEmpty { if fetchedNode[0].deviceConfig == nil { let newDeviceConfig = DeviceConfigEntity(context: context) - newDeviceConfig.role = Int32(config.device.role.rawValue) newDeviceConfig.serialEnabled = config.device.serialEnabled newDeviceConfig.debugLogEnabled = config.device.debugLogEnabled - fetchedNode[0].deviceConfig = newDeviceConfig - } else { - fetchedNode[0].deviceConfig?.role = Int32(config.device.role.rawValue) fetchedNode[0].deviceConfig?.serialEnabled = config.device.serialEnabled fetchedNode[0].deviceConfig?.debugLogEnabled = config.device.debugLogEnabled } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Device Config for node number: \(String(nodeNum))") } - + MeshLogger.log("πŸ’Ύ Updated Device Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Updating Core Data DeviceConfigEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error Updating Core Data DeviceConfigEntity: \(nsError)") } } } catch { - + let nsError = error as NSError + MeshLogger.log("πŸ’₯ Fetching node for core data DeviceConfigEntity failed: \(nsError)") } } if config.payloadVariant == Config.OneOf_PayloadVariant.display(config.display) { - if meshlogging { MeshLogger.log("πŸ–₯️ Display config received: \(String(nodeNum))") } + MeshLogger.log("πŸ–₯️ Display config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -135,12 +118,10 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont if fetchedNode[0].displayConfig == nil { let newDisplayConfig = DisplayConfigEntity(context: context) - newDisplayConfig.gpsFormat = Int32(config.display.gpsFormat.rawValue) newDisplayConfig.screenOnSeconds = Int32(config.display.screenOnSecs) newDisplayConfig.screenCarouselInterval = Int32(config.display.autoScreenCarouselSecs) newDisplayConfig.compassNorthTop = config.display.compassNorthTop - fetchedNode[0].displayConfig = newDisplayConfig } else { @@ -154,7 +135,7 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont do { try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Display Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated Display Config for node number: \(String(nodeNum))") } catch { @@ -177,7 +158,7 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont if config.payloadVariant == Config.OneOf_PayloadVariant.lora(config.lora) { - if meshlogging { MeshLogger.log("πŸ“» LoRa config received: \(String(nodeNum))") } + MeshLogger.log("πŸ“» LoRa config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -222,24 +203,17 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated LoRa Config for node number: \(String(nodeNum))") } - + MeshLogger.log("πŸ’Ύ Updated LoRa Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError print("πŸ’₯ Error Updating Core Data LoRaConfigEntity: \(nsError)") } } else { - print("πŸ’₯ 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)") } @@ -247,7 +221,7 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont if config.payloadVariant == Config.OneOf_PayloadVariant.network(config.network) { - if meshlogging { MeshLogger.log("πŸ“Ά Network config received \(String(nodeNum))") } + MeshLogger.log("πŸ“Ά Network config received \(String(nodeNum))") print(try! config.network.jsonString()) let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") @@ -280,7 +254,7 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont do { try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated WiFi Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated WiFi Config for node number: \(String(nodeNum))") } catch { @@ -303,7 +277,7 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont if config.payloadVariant == Config.OneOf_PayloadVariant.position(config.position) { - if meshlogging { MeshLogger.log("πŸ—ΊοΈ Position config received: \(String(nodeNum))") } + MeshLogger.log("πŸ—ΊοΈ Position config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -341,36 +315,32 @@ func localConfig (config: Config, meshlogging: Bool, context:NSManagedObjectCont } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Position Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated Position Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Updating Core Data PositionConfigEntity: \(nsError)") + MeshLogger.log("πŸ’₯ Error Updating Core Data PositionConfigEntity: \(nsError)") } } else { - - print("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save Position Config") + MeshLogger.log("πŸ’₯ 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)") + MeshLogger.log("πŸ’₯ Fetching node for core data PositionConfigEntity failed: \(nsError)") } } } -func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObjectContext, nodeNum: Int64, nodeLongName: String) { +func moduleConfig (config: ModuleConfig, context:NSManagedObjectContext, nodeNum: Int64, nodeLongName: String) { if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.cannedMessage(config.cannedMessage) { - if meshlogging { MeshLogger.log("πŸ₯« Canned Message module config received: \(String(nodeNum))") } + MeshLogger.log("πŸ₯« Canned Message module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -414,33 +384,27 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Canned Message Module Config for node number: \(String(nodeNum))") } - + MeshLogger.log("πŸ’Ύ 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)") + MeshLogger.log("πŸ’₯ 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") + MeshLogger.log("πŸ’₯ 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)") + MeshLogger.log("πŸ’₯ Fetching node for core data CannedMessageConfigEntity failed: \(nsError)") } } if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.externalNotification(config.externalNotification) { - if meshlogging { MeshLogger.log("🚨 External Notifiation module config received: \(String(nodeNum))") } + MeshLogger.log("🚨 External Notifiation module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -448,25 +412,20 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj do { let fetchedNode = try context.fetch(fetchNodeInfoRequest) as! [NodeInfoEntity] - // Found a node, save External Notificaitone Config if !fetchedNode.isEmpty { if fetchedNode[0].externalNotificationConfig == nil { - let newExternalNotificationConfig = ExternalNotificationConfigEntity(context: context) - newExternalNotificationConfig.enabled = config.externalNotification.enabled newExternalNotificationConfig.alertBell = config.externalNotification.alertBell newExternalNotificationConfig.alertMessage = config.externalNotification.alertMessage newExternalNotificationConfig.active = config.externalNotification.active newExternalNotificationConfig.output = Int32(config.externalNotification.output) newExternalNotificationConfig.outputMilliseconds = Int32(config.externalNotification.outputMs) - fetchedNode[0].externalNotificationConfig = newExternalNotificationConfig } else { - fetchedNode[0].externalNotificationConfig?.enabled = config.externalNotification.enabled fetchedNode[0].externalNotificationConfig?.alertBell = config.externalNotification.alertBell fetchedNode[0].externalNotificationConfig?.alertMessage = config.externalNotification.alertMessage @@ -476,21 +435,17 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated External Notification Module Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ 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)") + MeshLogger.log("πŸ’₯ Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)") } } else { - - print("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save External Notifiation Module Config") + MeshLogger.log("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save External Notifiation Module Config") } } catch { @@ -502,7 +457,7 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.mqtt(config.mqtt) { - if meshlogging { MeshLogger.log("🌐 MQTT module config received: \(String(nodeNum))") } + MeshLogger.log("🌐 MQTT module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -540,31 +495,30 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj do { try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated MQTT Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated MQTT Config for node number: \(String(nodeNum))") } catch { context.rollback() let nsError = error as NSError - if meshlogging { MeshLogger.log("πŸ’₯ Error Updating Core Data MQTTConfigEntity: \(nsError)") } + MeshLogger.log("πŸ’₯ Error Updating Core Data MQTTConfigEntity: \(nsError)") } } else { - - if meshlogging { MeshLogger.log("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save MQTT Module Config") } + MeshLogger.log("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save MQTT Module Config") } } catch { let nsError = error as NSError - if meshlogging { MeshLogger.log("πŸ’₯ Fetching node for core data MQTTConfigEntity failed: \(nsError)") } + MeshLogger.log("πŸ’₯ Fetching node for core data MQTTConfigEntity failed: \(nsError)") } } if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.rangeTest(config.rangeTest) { - if meshlogging { MeshLogger.log("⛰️ Range Test module config received: \(String(nodeNum))") } + MeshLogger.log("⛰️ Range Test module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -574,53 +528,40 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj let fetchedNode = try context.fetch(fetchNodeInfoRequest) as! [NodeInfoEntity] // Found a node, save Device Config if !fetchedNode.isEmpty { - if fetchedNode[0].rangeTestConfig == nil { - let newRangeTestConfig = RangeTestConfigEntity(context: context) - newRangeTestConfig.sender = Int32(config.rangeTest.sender) newRangeTestConfig.enabled = config.rangeTest.enabled newRangeTestConfig.save = config.rangeTest.save - fetchedNode[0].rangeTestConfig = newRangeTestConfig - } else { - fetchedNode[0].rangeTestConfig?.sender = Int32(config.rangeTest.sender) fetchedNode[0].rangeTestConfig?.enabled = config.rangeTest.enabled fetchedNode[0].rangeTestConfig?.save = config.rangeTest.save } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Range Test Config for node number: \(String(nodeNum))") } - + MeshLogger.log("πŸ’Ύ Updated Range Test Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError - - if meshlogging { MeshLogger.log("πŸ’₯ Error Updating Core Data RangeTestConfigEntity: \(nsError)") } + MeshLogger.log("πŸ’₯ Error Updating Core Data RangeTestConfigEntity: \(nsError)") } } else { - - if meshlogging { MeshLogger.log("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save Range Test Module Config") } + MeshLogger.log("πŸ’₯ No Nodes found in local database matching node number \(nodeNum) unable to save Range Test Module Config") } } catch { - let nsError = error as NSError - if meshlogging { MeshLogger.log("πŸ’₯ Fetching node for core data RangeTestConfigEntity failed: \(nsError)") } + MeshLogger.log("πŸ’₯ Fetching node for core data RangeTestConfigEntity failed: \(nsError)") } } if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.serial(config.serial) { - if meshlogging { MeshLogger.log("πŸ€– Serial module config received: \(String(nodeNum))") } + MeshLogger.log("πŸ€– Serial module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -635,7 +576,6 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj if fetchedNode[0].serialConfig == nil { let newSerialConfig = SerialConfigEntity(context: context) - newSerialConfig.enabled = config.serial.enabled newSerialConfig.echo = config.serial.echo newSerialConfig.rxd = Int32(config.serial.rxd) @@ -643,11 +583,9 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj newSerialConfig.baudRate = Int32(config.serial.baud.rawValue) newSerialConfig.timeout = Int32(config.serial.timeout) newSerialConfig.mode = Int32(config.serial.mode.rawValue) - fetchedNode[0].serialConfig = newSerialConfig } else { - fetchedNode[0].serialConfig?.enabled = config.serial.enabled fetchedNode[0].serialConfig?.echo = config.serial.echo fetchedNode[0].serialConfig?.rxd = Int32(config.serial.rxd) @@ -655,13 +593,11 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj fetchedNode[0].serialConfig?.baudRate = Int32(config.serial.baud.rawValue) fetchedNode[0].serialConfig?.timeout = Int32(config.serial.timeout) fetchedNode[0].serialConfig?.mode = Int32(config.serial.mode.rawValue) - } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Serial Module Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated Serial Module Config for node number: \(String(nodeNum))") } catch { @@ -685,7 +621,7 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj if config.payloadVariant == ModuleConfig.OneOf_PayloadVariant.telemetry(config.telemetry) { - if meshlogging { MeshLogger.log("πŸ“ˆ Telemetry module config received: \(String(nodeNum))") } + MeshLogger.log("πŸ“ˆ Telemetry module config received: \(String(nodeNum))") let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum)) @@ -718,32 +654,27 @@ func moduleConfig (config: ModuleConfig, meshlogging: Bool, context:NSManagedObj } do { - try context.save() - if meshlogging { MeshLogger.log("πŸ’Ύ Updated Telemetry Module Config for node number: \(String(nodeNum))") } + MeshLogger.log("πŸ’Ύ Updated Telemetry Module Config for node number: \(String(nodeNum))") } catch { - context.rollback() - let nsError = error as NSError print("πŸ’₯ Error Updating Core Data TelemetryConfigEntity: \(nsError)") } } else { - print("πŸ’₯ 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)") } } } -func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, meshLogging: Bool, context: NSManagedObjectContext) -> MyInfoEntity? { +func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, context: NSManagedObjectContext) -> MyInfoEntity? { let fetchMyInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "MyInfoEntity") fetchMyInfoRequest.predicate = NSPredicate(format: "myNodeNum == %lld", Int64(myInfo.myNodeNum)) @@ -772,7 +703,7 @@ func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, meshLogging: Bool, do { try context.save() - if meshLogging { MeshLogger.log("πŸ’Ύ Saved a new myInfo for node number: \(String(myInfo.myNodeNum))") } + MeshLogger.log("πŸ’Ύ Saved a new myInfo for node number: \(String(myInfo.myNodeNum))") return myInfoEntity } catch { @@ -801,7 +732,7 @@ func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, meshLogging: Bool, do { try context.save() - if meshLogging { MeshLogger.log("πŸ’Ύ Updated myInfo for node number: \(String(myInfo.myNodeNum))") } + MeshLogger.log("πŸ’Ύ Updated myInfo for node number: \(String(myInfo.myNodeNum))") return fetchedMyInfo[0] } catch { @@ -820,7 +751,7 @@ func myInfoPacket (myInfo: MyNodeInfo, peripheralId: String, meshLogging: Bool, return nil } -func channelPacket (channel: Channel, fromNum: Int64, meshLogging: Bool, context: NSManagedObjectContext) { +func channelPacket (channel: Channel, fromNum: Int64, context: NSManagedObjectContext) { if channel.isInitialized && channel.hasSettings { @@ -851,12 +782,7 @@ func channelPacket (channel: Channel, fromNum: Int64, meshLogging: Bool, context } try context.save() - - if meshLogging { - - MeshLogger.log("πŸ’Ύ Updated MyInfo channel \(channel.index) from Channel App Packet For: \(fetchedMyInfo[0].myNodeNum)") - - } + MeshLogger.log("πŸ’Ύ Updated MyInfo channel \(channel.index) from Channel App Packet For: \(fetchedMyInfo[0].myNodeNum)") } catch { @@ -868,7 +794,7 @@ func channelPacket (channel: Channel, fromNum: Int64, meshLogging: Bool, context } } -func nodeInfoPacket (nodeInfo: NodeInfo, meshLogging: Bool, context: NSManagedObjectContext) -> NodeInfoEntity? { +func nodeInfoPacket (nodeInfo: NodeInfo, context: NSManagedObjectContext) -> NodeInfoEntity? { let fetchNodeInfoRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeInfo.num)) @@ -945,12 +871,9 @@ func nodeInfoPacket (nodeInfo: NodeInfo, meshLogging: Bool, context: NSManagedOb try context.save() if nodeInfo.hasUser { - - if meshLogging { MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.user.longName)") } - + MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.user.longName)") } else { - - if meshLogging { MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.num)") } + MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.num)") } return newNode @@ -1029,12 +952,10 @@ func nodeInfoPacket (nodeInfo: NodeInfo, meshLogging: Bool, context: NSManagedOb try context.save() if nodeInfo.hasUser { - - if meshLogging { MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.user.longName)") } + MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.user.longName)") } else { - - if meshLogging { MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.num)") } + MeshLogger.log("πŸ’Ύ BLE FROMRADIO received and nodeInfo inserted for \(nodeInfo.num)") } return fetchedNode[0] @@ -1061,7 +982,7 @@ func nodeInfoPacket (nodeInfo: NodeInfo, meshLogging: Bool, context: NSManagedOb } -func nodeInfoAppPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObjectContext) { +func nodeInfoAppPacket (packet: MeshPacket, context: NSManagedObjectContext) { let fetchNodeInfoAppRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodeInfoAppRequest.predicate = NSPredicate(format: "num == %lld", Int64(packet.from)) @@ -1104,32 +1025,24 @@ func nodeInfoAppPacket (packet: MeshPacket, meshLogging: Bool, context: NSManage } do { - try context.save() - - if meshLogging { MeshLogger.log("πŸ’Ύ Updated NodeInfo SNR \(packet.rxSnr) and Time from Node Info App Packet For: \(fetchedNode[0].num)")} - + MeshLogger.log("πŸ’Ύ 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)") - + MeshLogger.log("πŸ’₯ Error Saving NodeInfoEntity from NODEINFO_APP \(nsError)") } } catch { - - print("πŸ’₯ Error Fetching NodeInfoEntity for NODEINFO_APP") + MeshLogger.log("πŸ’₯ Error Fetching NodeInfoEntity for NODEINFO_APP") } } -func adminAppPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObjectContext) { - - print(try! packet.decoded.jsonString()) +func adminAppPacket (packet: MeshPacket, context: NSManagedObjectContext) { + print(try! packet.decoded.jsonString()) } -func positionPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObjectContext) { +func positionPacket (packet: MeshPacket, context: NSManagedObjectContext) { let fetchNodePositionRequest: NSFetchRequest = NSFetchRequest.init(entityName: "NodeInfoEntity") fetchNodePositionRequest.predicate = NSPredicate(format: "num == %lld", Int64(packet.from)) @@ -1170,13 +1083,8 @@ func positionPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedOb fetchedNode[0].positions = mutablePositions.copy() as? NSOrderedSet do { - try context.save() - - if meshLogging { - MeshLogger.log("πŸ’Ύ Updated Node Position Coordinates, SNR and Time from Position App Packet For: \(fetchedNode[0].num)") - } - + MeshLogger.log("πŸ’Ύ Updated Node Position Coordinates, SNR and Time from Position App Packet For: \(fetchedNode[0].num)") } catch { context.rollback() @@ -1203,7 +1111,7 @@ func positionPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedOb } } -func routingPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObjectContext) { +func routingPacket (packet: MeshPacket, context: NSManagedObjectContext) { print("Routing packet", packet) if let routingMessage = try? Routing(serializedData: packet.decoded.payload) { @@ -1239,18 +1147,13 @@ func routingPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObj default: () } - if meshLogging { MeshLogger.log("πŸ•ΈοΈ ROUTING PACKET received for RequestID: \(packet.decoded.requestID) Error: \(errorExplanation)") } - - + MeshLogger.log("πŸ•ΈοΈ ROUTING PACKET received for RequestID: \(packet.decoded.requestID) Error: \(errorExplanation)") let fetchMessageRequest: NSFetchRequest = NSFetchRequest.init(entityName: "MessageEntity") fetchMessageRequest.predicate = NSPredicate(format: "messageId == %lld", Int64(packet.decoded.requestID)) do { - let fetchedMessage = try context.fetch(fetchMessageRequest) as? [MessageEntity] - if fetchedMessage?.count ?? 0 > 0 { - fetchedMessage![0].ackError = Int32(routingMessage.errorReason.rawValue) if routingMessage.errorReason == Routing.Error.none { @@ -1264,27 +1167,19 @@ func routingPacket (packet: MeshPacket, meshLogging: Bool, context: NSManagedObj fetchedMessage![0].toUser?.objectWillChange.send() } else { - return } - try context.save() - - if meshLogging { - MeshLogger.log("πŸ’Ύ ACK Received and saved for MessageID \(packet.decoded.requestID)") - } - + MeshLogger.log("πŸ’Ύ ACK Received and saved for MessageID \(packet.decoded.requestID)") } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Saving ACK for message MessageID \(packet.id) Error: \(nsError)") + MeshLogger.log("πŸ’₯ Error Saving ACK for message MessageID \(packet.id) Error: \(nsError)") } } } -func telemetryPacket(packet: MeshPacket, meshLogging: Bool, context: NSManagedObjectContext) { +func telemetryPacket(packet: MeshPacket, context: NSManagedObjectContext) { if let telemetryMessage = try? Telemetry(serializedData: packet.decoded.payload) { @@ -1330,32 +1225,26 @@ func telemetryPacket(packet: MeshPacket, meshLogging: Bool, context: NSManagedOb } try context.save() - - if meshLogging { - MeshLogger.log("πŸ’Ύ Telemetry Saved for Node: \(packet.from)") - } + MeshLogger.log("πŸ’Ύ Telemetry Saved for Node: \(packet.from)") } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Error Saving Telemetry for Node \(packet.from) Error: \(nsError)") + MeshLogger.log("πŸ’₯ Error Saving Telemetry for Node \(packet.from) Error: \(nsError)") } } else { - + MeshLogger.log("πŸ’₯ Error Fetching NodeInfoEntity for Node \(packet.from)") } } -func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, meshLogging: Bool, context: NSManagedObjectContext) { +func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, context: NSManagedObjectContext) { let broadcastNodeNum: UInt32 = 4294967295 if let messageText = String(bytes: packet.decoded.payload, encoding: .utf8) { - if meshLogging { MeshLogger.log("πŸ’¬ Message received for text message app") } - + MeshLogger.log("πŸ’¬ Message received for text message app") let messageUsers: NSFetchRequest = NSFetchRequest.init(entityName: "UserEntity") messageUsers.predicate = NSPredicate(format: "num IN %@", [packet.to, packet.from]) @@ -1370,12 +1259,9 @@ func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, meshLogging: newMessage.isEmoji = packet.decoded.emoji == 1 if packet.decoded.replyID > 0 { - newMessage.replyID = Int64(packet.decoded.replyID) } - if packet.to == broadcastNodeNum && fetchedUsers.count == 1 { - // Save the broadcast user if it does not exist let bcu: UserEntity = UserEntity(context: context) bcu.shortName = "ALL" @@ -1386,10 +1272,8 @@ func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, meshLogging: newMessage.toUser = bcu } else { - newMessage.toUser = fetchedUsers.first(where: { $0.num == packet.to }) } - newMessage.fromUser = fetchedUsers.first(where: { $0.num == packet.from }) newMessage.messagePayload = messageText newMessage.fromUser?.objectWillChange.send() @@ -1400,19 +1284,13 @@ func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, meshLogging: do { try context.save() - - if meshLogging { MeshLogger.log("πŸ’Ύ Saved a new message for \(newMessage.messageId)") } - + MeshLogger.log("πŸ’Ύ Saved a new message for \(newMessage.messageId)") messageSaved = true - if messageSaved { //&& (newMessage.toUser != nil && newMessage.toUser!.num == broadcastNodeNum || connectedNode == newMessage.toUser!.num) { - - + if messageSaved { if newMessage.fromUser != nil { - // Create an iOS Notification for the received message and schedule it immediately let manager = LocalNotificationManager() - manager.notifications = [ Notification( id: ("notification.id.\(newMessage.messageId)"), @@ -1420,24 +1298,17 @@ func textMessageAppPacket(packet: MeshPacket, connectedNode: Int64, meshLogging: subtitle: "AKA \(newMessage.fromUser?.shortName ?? "???")", content: messageText) ] - manager.schedule() - - if meshLogging { MeshLogger.log("πŸ’¬ iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "Unknown")") } + MeshLogger.log("πŸ’¬ iOS Notification Scheduled for text message from \(newMessage.fromUser?.longName ?? "Unknown")") } } - } catch { - context.rollback() - let nsError = error as NSError - print("πŸ’₯ Failed to save new MessageEntity \(nsError)") + MeshLogger.log("πŸ’₯ Failed to save new MessageEntity \(nsError)") } - - } catch { - - print("πŸ’₯ Fetch Message To and From Users Error") + } catch { + MeshLogger.log("πŸ’₯ Fetch Message To and From Users Error") } } } diff --git a/Meshtastic/Views/Messages/MessageList.swift b/Meshtastic/Views/Messages/MessageList.swift index 117440a1..c31a9d17 100644 --- a/Meshtastic/Views/Messages/MessageList.swift +++ b/Meshtastic/Views/Messages/MessageList.swift @@ -371,27 +371,20 @@ struct MessageList: View { HStack(alignment: .top) { ZStack { - let kbType = UIKeyboardType(rawValue: UserDefaults.standard.object(forKey: "keyboardType") as? Int ?? 0) TextField("Message", text: $typingMessage, axis: .vertical) .onChange(of: typingMessage, perform: { value in - totalBytes = value.utf8.count - // Only mess with the value if it is too big if totalBytes > maxbytes { - let firstNBytes = Data(typingMessage.utf8.prefix(maxbytes)) - if let maxBytesString = String(data: firstNBytes, encoding: String.Encoding.utf8) { - // Set the message back to the last place where it was the right size typingMessage = maxBytesString } else { print("not a valid UTF-8 sequence") } } - }) .keyboardType(kbType!) .toolbar {