Meshtastic-Apple/Meshtastic/Persistence/UpdateCoreData.swift

1387 lines
58 KiB
Swift
Raw Normal View History

//
// UpdateCoreData.swift
// Meshtastic
//
// Copyright(c) Garth Vander Houwen 10/3/22.
import CoreData
2024-06-03 02:17:55 -07:00
import OSLog
public func clearPax(destNum: Int64, context: NSManagedObjectContext) -> Bool {
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(destNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return false
}
let newPax = [PaxCounterLog]()
fetchedNode[0].pax? = NSOrderedSet(array: newPax)
do {
try context.save()
return true
} catch {
context.rollback()
return false
}
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetch NodeInfoEntity Error")
return false
}
}
public func clearPositions(destNum: Int64, context: NSManagedObjectContext) -> Bool {
2023-03-06 10:33:18 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(destNum))
2023-03-06 10:33:18 -08:00
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return false
}
let newPostions = [PositionEntity]()
fetchedNode[0].positions? = NSOrderedSet(array: newPostions)
do {
try context.save()
return true
2023-03-06 10:33:18 -08:00
} catch {
context.rollback()
return false
}
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetch NodeInfoEntity Error")
return false
}
}
public func clearTelemetry(destNum: Int64, metricsType: Int32, context: NSManagedObjectContext) -> Bool {
2023-03-06 10:33:18 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(destNum))
2023-03-06 10:33:18 -08:00
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return false
}
let emptyTelemetry = [TelemetryEntity]()
fetchedNode[0].telemetries? = NSOrderedSet(array: emptyTelemetry)
do {
try context.save()
return true
2023-03-06 10:33:18 -08:00
} catch {
context.rollback()
return false
}
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetch NodeInfoEntity Error")
return false
}
}
2022-12-17 23:53:06 -08:00
public func deleteChannelMessages(channel: ChannelEntity, context: NSManagedObjectContext) {
2022-11-24 23:25:44 -08:00
do {
let objects = channel.allPrivateMessages
2023-02-01 09:19:45 -08:00
for object in objects {
context.delete(object)
}
2022-11-24 23:25:44 -08:00
try context.save()
} catch let error as NSError {
2024-06-03 02:17:55 -07:00
Logger.data.error("\(error.localizedDescription)")
2022-11-24 23:25:44 -08:00
}
}
2022-11-25 00:22:51 -08:00
public func deleteUserMessages(user: UserEntity, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
2022-11-25 00:22:51 -08:00
do {
let objects = user.messageList
2023-02-01 09:19:45 -08:00
for object in objects {
context.delete(object)
}
2022-11-25 00:22:51 -08:00
try context.save()
} catch let error as NSError {
2024-06-03 02:17:55 -07:00
Logger.data.error("\(error.localizedDescription)")
2022-11-25 00:22:51 -08:00
}
}
public func clearCoreDataDatabase(context: NSManagedObjectContext, includeRoutes: Bool) {
2023-03-06 10:33:18 -08:00
let persistenceController = PersistenceController.shared.container
for i in 0...persistenceController.managedObjectModel.entities.count-1 {
let entity = persistenceController.managedObjectModel.entities[i]
let query = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
var deleteRequest = NSBatchDeleteRequest(fetchRequest: query)
let entityName = entity.name ?? "UNK"
if includeRoutes {
deleteRequest = NSBatchDeleteRequest(fetchRequest: query)
} else if !includeRoutes {
if !(entityName.contains("RouteEntity") || entityName.contains("LocationEntity")) {
deleteRequest = NSBatchDeleteRequest(fetchRequest: query)
}
}
2022-11-24 23:25:44 -08:00
do {
try context.executeAndMergeChanges(using: deleteRequest)
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("\(error.localizedDescription)")
2022-11-25 00:26:13 -08:00
}
}
}
2023-01-20 19:14:49 -08:00
func upsertNodeInfoPacket (packet: MeshPacket, context: NSManagedObjectContext) {
2023-03-14 12:44:10 -07:00
let logString = String.localizedStringWithFormat("mesh.log.nodeinfo.received %@".localized, String(packet.from))
MeshLogger.log("📟 \(logString)")
2023-03-14 12:44:10 -07:00
guard packet.from > 0 else { return }
2023-03-14 12:44:10 -07:00
let fetchNodeInfoAppRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoAppRequest.predicate = NSPredicate(format: "num == %lld", Int64(packet.from))
2023-03-14 12:44:10 -07:00
do {
2023-03-14 12:44:10 -07:00
let fetchedNode = try context.fetch(fetchNodeInfoAppRequest) as? [NodeInfoEntity] ?? []
if fetchedNode.count == 0 {
// Not Found Insert
let newNode = NodeInfoEntity(context: context)
newNode.id = Int64(packet.from)
newNode.num = Int64(packet.from)
2024-06-02 09:45:56 -07:00
newNode.firstHeard = Date(timeIntervalSince1970: TimeInterval(Int64(packet.rxTime)))
newNode.lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(packet.rxTime)))
newNode.snr = packet.rxSnr
2023-05-04 22:20:22 -07:00
newNode.rssi = packet.rxRssi
newNode.viaMqtt = packet.viaMqtt
if packet.to == 4294967295 || packet.to == UserDefaults.preferredPeripheralNum {
newNode.channel = Int32(packet.channel)
}
2023-04-02 15:00:15 -07:00
if let nodeInfoMessage = try? NodeInfo(serializedData: packet.decoded.payload) {
2024-03-23 09:01:44 -07:00
newNode.hopsAway = Int32(nodeInfoMessage.hopsAway)
2024-03-26 09:59:07 -07:00
newNode.favorite = nodeInfoMessage.isFavorite
2023-04-02 15:00:15 -07:00
}
if let newUserMessage = try? User(serializedData: packet.decoded.payload) {
if newUserMessage.id.isEmpty {
if packet.from > Int16.max {
let newUser = createUser(num: Int64(packet.from), context: context)
newNode.user = newUser
}
} else {
let newUser = UserEntity(context: context)
newUser.userId = newUserMessage.id
newUser.num = Int64(packet.from)
newUser.longName = newUserMessage.longName
newUser.shortName = newUserMessage.shortName
2023-12-20 10:24:01 -08:00
newUser.role = Int32(newUserMessage.role.rawValue)
newUser.hwModel = String(describing: newUserMessage.hwModel).uppercased()
newNode.user = newUser
if UserDefaults.newNodeNotifications {
let manager = LocalNotificationManager()
manager.notifications = [
Notification(
id: (UUID().uuidString),
title: "New Node",
subtitle: "\(newUser.longName ?? "unknown".localized)",
content: "New Node has been discovered",
target: "nodes",
path: "meshtastic://nodes?nodenum=\(newUser.num)"
)
]
manager.schedule()
}
}
} else {
if packet.from > Int16.max {
let newUser = createUser(num: Int64(packet.from), context: context)
fetchedNode[0].user = newUser
}
}
if newNode.user == nil && packet.from > Int16.max {
newNode.user = createUser(num: Int64(packet.from), context: context)
}
let myInfoEntity = MyInfoEntity(context: context)
myInfoEntity.myNodeNum = Int64(packet.from)
myInfoEntity.rebootCount = 0
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Saved a new myInfo for node number: \(String(packet.from))")
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Inserting New Core Data MyInfoEntity: \(nsError)")
}
newNode.myInfo = myInfoEntity
} else {
// Update an existing node
fetchedNode[0].id = Int64(packet.from)
fetchedNode[0].num = Int64(packet.from)
if packet.rxTime > 0 {
fetchedNode[0].lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(packet.rxTime)))
2024-06-02 09:45:56 -07:00
if fetchedNode[0].firstHeard == nil {
fetchedNode[0].lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(packet.rxTime)))
}
}
fetchedNode[0].snr = packet.rxSnr
2023-05-04 22:20:22 -07:00
fetchedNode[0].rssi = packet.rxRssi
fetchedNode[0].viaMqtt = packet.viaMqtt
if packet.to == 4294967295 || packet.to == UserDefaults.preferredPeripheralNum {
fetchedNode[0].channel = Int32(packet.channel)
}
2023-03-14 12:44:10 -07:00
if let nodeInfoMessage = try? NodeInfo(serializedData: packet.decoded.payload) {
2024-03-23 09:01:44 -07:00
fetchedNode[0].hopsAway = Int32(nodeInfoMessage.hopsAway)
2024-03-26 09:59:07 -07:00
fetchedNode[0].favorite = nodeInfoMessage.isFavorite
if nodeInfoMessage.hasDeviceMetrics {
let telemetry = TelemetryEntity(context: context)
telemetry.batteryLevel = Int32(nodeInfoMessage.deviceMetrics.batteryLevel)
telemetry.voltage = nodeInfoMessage.deviceMetrics.voltage
telemetry.channelUtilization = nodeInfoMessage.deviceMetrics.channelUtilization
telemetry.airUtilTx = nodeInfoMessage.deviceMetrics.airUtilTx
var newTelemetries = [TelemetryEntity]()
newTelemetries.append(telemetry)
fetchedNode[0].telemetries? = NSOrderedSet(array: newTelemetries)
}
if nodeInfoMessage.hasUser {
2023-09-25 19:30:21 -07:00
/// Seeing Some crashes here ?
fetchedNode[0].user!.userId = nodeInfoMessage.user.id
fetchedNode[0].user!.num = Int64(nodeInfoMessage.num)
fetchedNode[0].user!.longName = nodeInfoMessage.user.longName
fetchedNode[0].user!.shortName = nodeInfoMessage.user.shortName
2023-12-20 10:24:01 -08:00
fetchedNode[0].user!.role = Int32(nodeInfoMessage.user.role.rawValue)
fetchedNode[0].user!.hwModel = String(describing: nodeInfoMessage.user.hwModel).uppercased()
}
2024-03-23 09:01:44 -07:00
} else if packet.hopStart != 0 && packet.hopLimit <= packet.hopStart {
fetchedNode[0].hopsAway = Int32(packet.hopStart - packet.hopLimit)
}
if fetchedNode[0].user == nil {
let newUser = createUser(num: Int64(packet.from), context: context)
fetchedNode[0].user! = newUser
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated NodeInfo from Node Info App Packet For: \(fetchedNode[0].num)")
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Saving NodeInfoEntity from NODEINFO_APP \(nsError)")
}
}
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Fetching NodeInfoEntity for NODEINFO_APP")
}
}
func upsertPositionPacket (packet: MeshPacket, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.position.received %@".localized, String(packet.from))
MeshLogger.log("📍 \(logString)")
2023-03-06 10:33:18 -08:00
let fetchNodePositionRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodePositionRequest.predicate = NSPredicate(format: "num == %lld", Int64(packet.from))
2023-03-06 10:33:18 -08:00
do {
2023-03-06 10:33:18 -08:00
if let positionMessage = try? Position(serializedData: packet.decoded.payload) {
2023-03-06 10:33:18 -08:00
2023-10-03 16:47:36 -07:00
/// Don't save empty position packets from null island or apple park
if (positionMessage.longitudeI != 0 && positionMessage.latitudeI != 0) && (positionMessage.latitudeI != 373346000 && positionMessage.longitudeI != -1220090000) {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodePositionRequest) as? [NodeInfoEntity] else {
return
}
if fetchedNode.count == 1 {
2023-03-06 10:33:18 -08:00
// Unset the current latest position for this node
let fetchCurrentLatestPositionsRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "PositionEntity")
fetchCurrentLatestPositionsRequest.predicate = NSPredicate(format: "nodePosition.num == %lld && latest = true", Int64(packet.from))
2023-03-14 12:44:10 -07:00
2023-03-06 15:30:10 -08:00
guard let fetchedPositions = try context.fetch(fetchCurrentLatestPositionsRequest) as? [PositionEntity] else {
return
}
if fetchedPositions.count > 0 {
for position in fetchedPositions {
position.latest = false
}
}
let position = PositionEntity(context: context)
position.latest = true
position.snr = packet.rxSnr
2023-05-04 22:20:22 -07:00
position.rssi = packet.rxRssi
position.seqNo = Int32(positionMessage.seqNumber)
position.latitudeI = positionMessage.latitudeI
position.longitudeI = positionMessage.longitudeI
position.altitude = positionMessage.altitude
position.satsInView = Int32(positionMessage.satsInView)
position.speed = Int32(positionMessage.groundSpeed)
2024-05-29 12:52:35 -07:00
let heading = Int32(positionMessage.groundTrack)
// Throw out bad haeadings from the device
if heading >= 0 && heading <= 360 {
position.heading = Int32(positionMessage.groundTrack)
}
position.precisionBits = Int32(positionMessage.precisionBits)
if positionMessage.timestamp != 0 {
position.time = Date(timeIntervalSince1970: TimeInterval(Int64(positionMessage.timestamp)))
} else {
position.time = Date(timeIntervalSince1970: TimeInterval(Int64(positionMessage.time)))
}
2023-03-06 15:30:10 -08:00
guard let mutablePositions = fetchedNode[0].positions!.mutableCopy() as? NSMutableOrderedSet else {
return
}
/// Don't save nearly the same position over and over. If the next position is less than 10 meters from the new position, delete the previous position and save the new one.
2024-03-23 09:01:44 -07:00
if mutablePositions.count > 0 && (position.precisionBits == 32 || position.precisionBits == 0) {
if let mostRecent = mutablePositions.lastObject as? PositionEntity, mostRecent.coordinate.distance(from: position.coordinate) < 15.0 {
mutablePositions.remove(mostRecent)
}
} else if mutablePositions.count > 0 {
/// Don't store any history for reduced accuracy positions, we will just show a circle
mutablePositions.removeAllObjects()
}
mutablePositions.add(position)
fetchedNode[0].id = Int64(packet.from)
fetchedNode[0].num = Int64(packet.from)
if positionMessage.time > 0 {
fetchedNode[0].lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(positionMessage.time)))
} else if packet.rxTime > 0 {
fetchedNode[0].lastHeard = Date(timeIntervalSince1970: TimeInterval(Int64(packet.rxTime)))
}
fetchedNode[0].snr = packet.rxSnr
2023-05-04 22:20:22 -07:00
fetchedNode[0].rssi = packet.rxRssi
2024-02-05 23:48:23 -08:00
fetchedNode[0].viaMqtt = packet.viaMqtt
fetchedNode[0].channel = Int32(packet.channel)
fetchedNode[0].positions = mutablePositions.copy() as? NSOrderedSet
2023-03-06 10:33:18 -08:00
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Node Position Coordinates, SNR and Time from Position App Packet For: \(fetchedNode[0].num)")
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Saving NodeInfoEntity from POSITION_APP \(nsError)")
}
}
} else {
2023-03-14 12:44:10 -07:00
if (try? NodeInfo(serializedData: packet.decoded.payload)) != nil {
upsertNodeInfoPacket(packet: packet, context: context)
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("Empty POSITION_APP Packet: \((try? packet.jsonString()) ?? "JSON Decode Failure")")
2023-03-14 12:44:10 -07:00
}
}
}
} catch {
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Deserializing POSITION_APP packet.")
}
}
2023-01-31 22:08:03 -08:00
func upsertBluetoothConfigPacket(config: Meshtastic.Config.BluetoothConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.bluetooth.config %@".localized, String(nodeNum))
2023-01-23 17:56:04 -08:00
MeshLogger.log("📶 \(logString)")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-23 17:56:04 -08:00
// Found a node, save Device Config
if !fetchedNode.isEmpty {
if fetchedNode[0].bluetoothConfig == nil {
let newBluetoothConfig = BluetoothConfigEntity(context: context)
2023-01-31 22:08:03 -08:00
newBluetoothConfig.enabled = config.enabled
newBluetoothConfig.mode = Int32(config.mode.rawValue)
newBluetoothConfig.fixedPin = Int32(config.fixedPin)
2023-01-23 17:56:04 -08:00
fetchedNode[0].bluetoothConfig = newBluetoothConfig
} else {
2023-01-31 22:08:03 -08:00
fetchedNode[0].bluetoothConfig?.enabled = config.enabled
fetchedNode[0].bluetoothConfig?.mode = Int32(config.mode.rawValue)
fetchedNode[0].bluetoothConfig?.fixedPin = Int32(config.fixedPin)
2023-01-23 17:56:04 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Bluetooth Config for node number: \(String(nodeNum))")
2023-01-23 17:56:04 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data BluetoothConfigEntity: \(nsError)")
2023-01-23 17:56:04 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Bluetooth Config")
2023-01-23 17:56:04 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data BluetoothConfigEntity failed: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
2023-01-31 22:08:03 -08:00
func upsertDeviceConfigPacket(config: Meshtastic.Config.DeviceConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.device.config %@".localized, String(nodeNum))
2023-01-23 17:56:04 -08:00
MeshLogger.log("📟 \(logString)")
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-23 17:56:04 -08:00
// Found a node, save Device Config
if !fetchedNode.isEmpty {
if fetchedNode[0].deviceConfig == nil {
let newDeviceConfig = DeviceConfigEntity(context: context)
2023-01-31 22:08:03 -08:00
newDeviceConfig.role = Int32(config.role.rawValue)
newDeviceConfig.serialEnabled = config.serialEnabled
newDeviceConfig.debugLogEnabled = config.debugLogEnabled
newDeviceConfig.buttonGpio = Int32(config.buttonGpio)
newDeviceConfig.buzzerGpio = Int32(config.buzzerGpio)
newDeviceConfig.rebroadcastMode = Int32(config.rebroadcastMode.rawValue)
2024-02-07 15:42:20 -08:00
newDeviceConfig.nodeInfoBroadcastSecs = Int32(truncating: config.nodeInfoBroadcastSecs as NSNumber)
2023-04-09 23:04:11 -07:00
newDeviceConfig.doubleTapAsButtonPress = config.doubleTapAsButtonPress
2024-04-26 18:06:23 -07:00
newDeviceConfig.ledHeartbeatEnabled = !config.ledHeartbeatDisabled
2023-05-13 20:50:20 -07:00
newDeviceConfig.isManaged = config.isManaged
2024-04-08 11:41:54 -07:00
newDeviceConfig.tzdef = config.tzdef
2023-01-23 17:56:04 -08:00
fetchedNode[0].deviceConfig = newDeviceConfig
} else {
2023-01-31 22:08:03 -08:00
fetchedNode[0].deviceConfig?.role = Int32(config.role.rawValue)
fetchedNode[0].deviceConfig?.serialEnabled = config.serialEnabled
fetchedNode[0].deviceConfig?.debugLogEnabled = config.debugLogEnabled
fetchedNode[0].deviceConfig?.buttonGpio = Int32(config.buttonGpio)
fetchedNode[0].deviceConfig?.buzzerGpio = Int32(config.buzzerGpio)
fetchedNode[0].deviceConfig?.rebroadcastMode = Int32(config.rebroadcastMode.rawValue)
2024-02-07 15:42:20 -08:00
fetchedNode[0].deviceConfig?.nodeInfoBroadcastSecs = Int32(truncating: config.nodeInfoBroadcastSecs as NSNumber)
2023-05-13 20:50:20 -07:00
fetchedNode[0].deviceConfig?.doubleTapAsButtonPress = config.doubleTapAsButtonPress
2024-04-26 18:06:23 -07:00
fetchedNode[0].deviceConfig?.ledHeartbeatEnabled = !config.ledHeartbeatDisabled
2023-05-13 20:50:20 -07:00
fetchedNode[0].deviceConfig?.isManaged = config.isManaged
2024-04-08 11:41:54 -07:00
fetchedNode[0].deviceConfig?.tzdef = config.tzdef
2023-01-23 17:56:04 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Device Config for node number: \(String(nodeNum))")
2023-01-23 17:56:04 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data DeviceConfigEntity: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data DeviceConfigEntity failed: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
2023-01-31 22:08:03 -08:00
func upsertDisplayConfigPacket(config: Meshtastic.Config.DisplayConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.display.config %@".localized, String(nodeNum))
2023-01-23 17:56:04 -08:00
MeshLogger.log("🖥️ \(logString)")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-23 17:56:04 -08:00
// Found a node, save Device Config
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
if fetchedNode[0].displayConfig == nil {
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let newDisplayConfig = DisplayConfigEntity(context: context)
2023-01-31 22:08:03 -08:00
newDisplayConfig.gpsFormat = Int32(config.gpsFormat.rawValue)
newDisplayConfig.screenOnSeconds = Int32(config.screenOnSecs)
newDisplayConfig.screenCarouselInterval = Int32(config.autoScreenCarouselSecs)
newDisplayConfig.compassNorthTop = config.compassNorthTop
newDisplayConfig.flipScreen = config.flipScreen
newDisplayConfig.oledType = Int32(config.oled.rawValue)
newDisplayConfig.displayMode = Int32(config.displaymode.rawValue)
2023-11-26 12:54:45 -08:00
newDisplayConfig.units = Int32(config.units.rawValue)
newDisplayConfig.headingBold = config.headingBold
2023-01-23 17:56:04 -08:00
fetchedNode[0].displayConfig = newDisplayConfig
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
} else {
2023-03-06 10:33:18 -08:00
2023-01-31 22:08:03 -08:00
fetchedNode[0].displayConfig?.gpsFormat = Int32(config.gpsFormat.rawValue)
fetchedNode[0].displayConfig?.screenOnSeconds = Int32(config.screenOnSecs)
fetchedNode[0].displayConfig?.screenCarouselInterval = Int32(config.autoScreenCarouselSecs)
fetchedNode[0].displayConfig?.compassNorthTop = config.compassNorthTop
fetchedNode[0].displayConfig?.flipScreen = config.flipScreen
fetchedNode[0].displayConfig?.oledType = Int32(config.oled.rawValue)
fetchedNode[0].displayConfig?.displayMode = Int32(config.displaymode.rawValue)
2023-11-26 12:54:45 -08:00
fetchedNode[0].displayConfig?.units = Int32(config.units.rawValue)
fetchedNode[0].displayConfig?.headingBold = config.headingBold
2023-01-23 17:56:04 -08:00
}
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Display Config for node number: \(String(nodeNum))")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
} catch {
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
context.rollback()
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data DisplayConfigEntity: \(nsError)")
2023-01-23 17:56:04 -08:00
}
} else {
2023-03-06 10:33:18 -08:00
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Display Config")
2023-01-23 17:56:04 -08:00
}
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
} catch {
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data DisplayConfigEntity failed: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
2023-01-31 10:50:17 -08:00
func upsertLoRaConfigPacket(config: Meshtastic.Config.LoRaConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.lora.config %@".localized, String(nodeNum))
2023-01-20 19:14:49 -08:00
MeshLogger.log("📻 \(logString)")
2023-03-06 10:33:18 -08:00
2023-01-20 19:14:49 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", nodeNum)
do {
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-20 19:14:49 -08:00
// Found a node, save LoRa Config
2023-01-23 17:56:04 -08:00
if fetchedNode.count > 0 {
2023-01-20 19:14:49 -08:00
if fetchedNode[0].loRaConfig == nil {
2023-01-23 17:56:04 -08:00
// No lora config for node, save a new lora config
2023-01-20 19:14:49 -08:00
let newLoRaConfig = LoRaConfigEntity(context: context)
2023-01-31 10:50:17 -08:00
newLoRaConfig.regionCode = Int32(config.region.rawValue)
newLoRaConfig.usePreset = config.usePreset
newLoRaConfig.modemPreset = Int32(config.modemPreset.rawValue)
newLoRaConfig.bandwidth = Int32(config.bandwidth)
newLoRaConfig.spreadFactor = Int32(config.spreadFactor)
newLoRaConfig.codingRate = Int32(config.codingRate)
newLoRaConfig.frequencyOffset = config.frequencyOffset
2023-02-06 19:06:15 -08:00
newLoRaConfig.overrideFrequency = config.overrideFrequency
newLoRaConfig.overrideDutyCycle = config.overrideDutyCycle
2023-01-31 10:50:17 -08:00
newLoRaConfig.hopLimit = Int32(config.hopLimit)
newLoRaConfig.txPower = Int32(config.txPower)
newLoRaConfig.txEnabled = config.txEnabled
newLoRaConfig.channelNum = Int32(config.channelNum)
newLoRaConfig.sx126xRxBoostedGain = config.sx126XRxBoostedGain
newLoRaConfig.ignoreMqtt = config.ignoreMqtt
2023-01-20 19:14:49 -08:00
fetchedNode[0].loRaConfig = newLoRaConfig
} else {
2023-01-31 10:50:17 -08:00
fetchedNode[0].loRaConfig?.regionCode = Int32(config.region.rawValue)
fetchedNode[0].loRaConfig?.usePreset = config.usePreset
fetchedNode[0].loRaConfig?.modemPreset = Int32(config.modemPreset.rawValue)
fetchedNode[0].loRaConfig?.bandwidth = Int32(config.bandwidth)
fetchedNode[0].loRaConfig?.spreadFactor = Int32(config.spreadFactor)
fetchedNode[0].loRaConfig?.codingRate = Int32(config.codingRate)
fetchedNode[0].loRaConfig?.frequencyOffset = config.frequencyOffset
2023-02-06 19:06:15 -08:00
fetchedNode[0].loRaConfig?.overrideFrequency = config.overrideFrequency
fetchedNode[0].loRaConfig?.overrideDutyCycle = config.overrideDutyCycle
2023-01-31 10:50:17 -08:00
fetchedNode[0].loRaConfig?.hopLimit = Int32(config.hopLimit)
fetchedNode[0].loRaConfig?.txPower = Int32(config.txPower)
fetchedNode[0].loRaConfig?.txEnabled = config.txEnabled
fetchedNode[0].loRaConfig?.channelNum = Int32(config.channelNum)
fetchedNode[0].loRaConfig?.sx126xRxBoostedGain = config.sx126XRxBoostedGain
fetchedNode[0].loRaConfig?.ignoreMqtt = config.ignoreMqtt
fetchedNode[0].loRaConfig?.sx126xRxBoostedGain = config.sx126XRxBoostedGain
2023-01-20 19:14:49 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated LoRa Config for node number: \(String(nodeNum))")
2023-01-20 19:14:49 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data LoRaConfigEntity: \(nsError)")
2023-01-20 19:14:49 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Lora Config")
2023-01-20 19:14:49 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data LoRaConfigEntity failed: \(nsError)")
2023-01-20 19:14:49 -08:00
}
}
2023-01-23 17:56:04 -08:00
2023-01-31 22:20:16 -08:00
func upsertNetworkConfigPacket(config: Meshtastic.Config.NetworkConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.network.config %@".localized, String(nodeNum))
2023-01-23 17:56:04 -08:00
MeshLogger.log("🌐 \(logString)")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-23 17:56:04 -08:00
// Found a node, save WiFi Config
if !fetchedNode.isEmpty {
if fetchedNode[0].networkConfig == nil {
let newNetworkConfig = NetworkConfigEntity(context: context)
2023-01-31 22:20:16 -08:00
newNetworkConfig.wifiEnabled = config.wifiEnabled
newNetworkConfig.wifiSsid = config.wifiSsid
newNetworkConfig.wifiPsk = config.wifiPsk
newNetworkConfig.ethEnabled = config.ethEnabled
2023-01-23 17:56:04 -08:00
fetchedNode[0].networkConfig = newNetworkConfig
} else {
2023-01-31 22:20:16 -08:00
fetchedNode[0].networkConfig?.ethEnabled = config.ethEnabled
fetchedNode[0].networkConfig?.wifiEnabled = config.wifiEnabled
fetchedNode[0].networkConfig?.wifiSsid = config.wifiSsid
fetchedNode[0].networkConfig?.wifiPsk = config.wifiPsk
2023-01-23 17:56:04 -08:00
}
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Network Config for node number: \(String(nodeNum))")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data WiFiConfigEntity: \(nsError)")
2023-01-23 17:56:04 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Network Config")
2023-01-23 17:56:04 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data NetworkConfigEntity failed: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
2023-01-31 22:20:16 -08:00
func upsertPositionConfigPacket(config: Meshtastic.Config.PositionConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.position.config %@".localized, String(nodeNum))
2023-01-23 17:56:04 -08:00
MeshLogger.log("🗺️ \(logString)")
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-01-23 17:56:04 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-01-23 17:56:04 -08:00
// Found a node, save LoRa Config
if !fetchedNode.isEmpty {
if fetchedNode[0].positionConfig == nil {
let newPositionConfig = PositionConfigEntity(context: context)
2023-01-31 22:20:16 -08:00
newPositionConfig.smartPositionEnabled = config.positionBroadcastSmartEnabled
newPositionConfig.deviceGpsEnabled = config.gpsEnabled
2024-02-06 11:11:03 -08:00
newPositionConfig.gpsMode = Int32(config.gpsMode.rawValue)
2023-03-27 10:43:01 -07:00
newPositionConfig.rxGpio = Int32(config.rxGpio)
newPositionConfig.txGpio = Int32(config.txGpio)
2023-12-21 11:31:40 -08:00
newPositionConfig.gpsEnGpio = Int32(config.gpsEnGpio)
2023-01-31 22:20:16 -08:00
newPositionConfig.fixedPosition = config.fixedPosition
newPositionConfig.positionBroadcastSeconds = Int32(truncatingIfNeeded: config.positionBroadcastSecs)
2023-03-27 10:43:01 -07:00
newPositionConfig.broadcastSmartMinimumIntervalSecs = Int32(config.broadcastSmartMinimumIntervalSecs)
newPositionConfig.broadcastSmartMinimumDistance = Int32(config.broadcastSmartMinimumDistance)
2023-01-31 22:20:16 -08:00
newPositionConfig.positionFlags = Int32(config.positionFlags)
2023-12-22 19:08:32 -08:00
newPositionConfig.gpsAttemptTime = 900
2024-02-06 11:11:03 -08:00
newPositionConfig.gpsUpdateInterval = Int32(config.gpsUpdateInterval)
2023-01-23 17:56:04 -08:00
fetchedNode[0].positionConfig = newPositionConfig
} else {
2023-01-31 22:20:16 -08:00
fetchedNode[0].positionConfig?.smartPositionEnabled = config.positionBroadcastSmartEnabled
fetchedNode[0].positionConfig?.deviceGpsEnabled = config.gpsEnabled
2024-02-06 11:11:03 -08:00
fetchedNode[0].positionConfig?.gpsMode = Int32(config.gpsMode.rawValue)
2023-03-27 10:43:01 -07:00
fetchedNode[0].positionConfig?.rxGpio = Int32(config.rxGpio)
fetchedNode[0].positionConfig?.txGpio = Int32(config.txGpio)
2023-12-21 11:31:40 -08:00
fetchedNode[0].positionConfig?.gpsEnGpio = Int32(config.gpsEnGpio)
2023-01-31 22:20:16 -08:00
fetchedNode[0].positionConfig?.fixedPosition = config.fixedPosition
2024-02-07 15:42:20 -08:00
fetchedNode[0].positionConfig?.positionBroadcastSeconds = Int32(truncatingIfNeeded: config.positionBroadcastSecs)
2023-03-27 10:43:01 -07:00
fetchedNode[0].positionConfig?.broadcastSmartMinimumIntervalSecs = Int32(config.broadcastSmartMinimumIntervalSecs)
fetchedNode[0].positionConfig?.broadcastSmartMinimumDistance = Int32(config.broadcastSmartMinimumDistance)
2023-12-22 19:08:32 -08:00
fetchedNode[0].positionConfig?.gpsAttemptTime = 900
2024-02-06 11:11:03 -08:00
fetchedNode[0].positionConfig?.gpsUpdateInterval = Int32(config.gpsUpdateInterval)
2023-01-31 22:20:16 -08:00
fetchedNode[0].positionConfig?.positionFlags = Int32(config.positionFlags)
2023-01-23 17:56:04 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Position Config for node number: \(String(nodeNum))")
2023-01-23 17:56:04 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data PositionConfigEntity: \(nsError)")
2023-01-23 17:56:04 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Position Config")
2023-01-23 17:56:04 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data PositionConfigEntity failed: \(nsError)")
2023-01-23 17:56:04 -08:00
}
}
2023-02-01 09:19:45 -08:00
2024-02-19 21:30:19 -07:00
func upsertPowerConfigPacket(config: Meshtastic.Config.PowerConfig, nodeNum: Int64, context: NSManagedObjectContext) {
let logString = String.localizedStringWithFormat("mesh.log.power.config %@".localized, String(nodeNum))
MeshLogger.log("🗺️ \(logString)")
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
// Found a node, save Power Config
if !fetchedNode.isEmpty {
if fetchedNode[0].powerConfig == nil {
let newPowerConfig = PowerConfigEntity(context: context)
newPowerConfig.adcMultiplierOverride = config.adcMultiplierOverride
newPowerConfig.deviceBatteryInaAddress = Int32(config.deviceBatteryInaAddress)
newPowerConfig.isPowerSaving = config.isPowerSaving
newPowerConfig.lsSecs = Int32(config.lsSecs)
newPowerConfig.minWakeSecs = Int32(config.minWakeSecs)
newPowerConfig.onBatteryShutdownAfterSecs = Int32(config.onBatteryShutdownAfterSecs)
newPowerConfig.waitBluetoothSecs = Int32(config.waitBluetoothSecs)
fetchedNode[0].powerConfig = newPowerConfig
} else {
fetchedNode[0].powerConfig?.adcMultiplierOverride = config.adcMultiplierOverride
fetchedNode[0].powerConfig?.deviceBatteryInaAddress = Int32(config.deviceBatteryInaAddress)
fetchedNode[0].powerConfig?.isPowerSaving = config.isPowerSaving
fetchedNode[0].powerConfig?.lsSecs = Int32(config.lsSecs)
fetchedNode[0].powerConfig?.minWakeSecs = Int32(config.minWakeSecs)
fetchedNode[0].powerConfig?.onBatteryShutdownAfterSecs = Int32(config.onBatteryShutdownAfterSecs)
fetchedNode[0].powerConfig?.waitBluetoothSecs = Int32(config.waitBluetoothSecs)
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Power Config for node number: \(String(nodeNum))")
2024-02-19 21:30:19 -07:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data PowerConfigEntity: \(nsError)")
2024-02-19 21:30:19 -07:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Power Config")
2024-02-19 21:30:19 -07:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data PowerConfigEntity failed: \(nsError)")
2024-02-19 21:30:19 -07:00
}
}
func upsertAmbientLightingModuleConfigPacket(config: Meshtastic.ModuleConfig.AmbientLightingConfig, nodeNum: Int64, context: NSManagedObjectContext) {
let logString = String.localizedStringWithFormat("mesh.log.ambientlighting.config %@".localized, String(nodeNum))
MeshLogger.log("🏮 \(logString)")
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
// Found a node, save Ambient Lighting Config
if !fetchedNode.isEmpty {
if fetchedNode[0].cannedMessageConfig == nil {
let newAmbientLightingConfig = AmbientLightingConfigEntity(context: context)
newAmbientLightingConfig.ledState = config.ledState
newAmbientLightingConfig.current = Int32(config.current)
newAmbientLightingConfig.red = Int32(config.red)
newAmbientLightingConfig.green = Int32(config.green)
newAmbientLightingConfig.blue = Int32(config.blue)
fetchedNode[0].ambientLightingConfig = newAmbientLightingConfig
} else {
if fetchedNode[0].ambientLightingConfig == nil {
fetchedNode[0].ambientLightingConfig = AmbientLightingConfigEntity(context: context)
}
fetchedNode[0].ambientLightingConfig?.ledState = config.ledState
fetchedNode[0].ambientLightingConfig?.current = Int32(config.current)
fetchedNode[0].ambientLightingConfig?.red = Int32(config.red)
fetchedNode[0].ambientLightingConfig?.green = Int32(config.green)
fetchedNode[0].ambientLightingConfig?.blue = Int32(config.blue)
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Ambient Lighting Module Config for node number: \(String(nodeNum))")
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data AmbientLightingConfigEntity: \(nsError)")
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Ambient Lighting Module Config")
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data AmbientLightingConfigEntity failed: \(nsError)")
}
}
2023-02-01 09:19:45 -08:00
func upsertCannedMessagesModuleConfigPacket(config: Meshtastic.ModuleConfig.CannedMessageConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.cannedmessage.config %@".localized, String(nodeNum))
2023-02-01 09:19:45 -08:00
MeshLogger.log("🥫 \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-02-01 09:19:45 -08:00
// Found a node, save Canned Message Config
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
if fetchedNode[0].cannedMessageConfig == nil {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let newCannedMessageConfig = CannedMessageConfigEntity(context: context)
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
newCannedMessageConfig.enabled = config.enabled
newCannedMessageConfig.sendBell = config.sendBell
newCannedMessageConfig.rotary1Enabled = config.rotary1Enabled
newCannedMessageConfig.updown1Enabled = config.updown1Enabled
newCannedMessageConfig.inputbrokerPinA = Int32(config.inputbrokerPinA)
newCannedMessageConfig.inputbrokerPinB = Int32(config.inputbrokerPinB)
newCannedMessageConfig.inputbrokerPinPress = Int32(config.inputbrokerPinPress)
newCannedMessageConfig.inputbrokerEventCw = Int32(config.inputbrokerEventCw.rawValue)
newCannedMessageConfig.inputbrokerEventCcw = Int32(config.inputbrokerEventCcw.rawValue)
newCannedMessageConfig.inputbrokerEventPress = Int32(config.inputbrokerEventPress.rawValue)
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
fetchedNode[0].cannedMessageConfig = newCannedMessageConfig
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} else {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
fetchedNode[0].cannedMessageConfig?.enabled = config.enabled
fetchedNode[0].cannedMessageConfig?.sendBell = config.sendBell
fetchedNode[0].cannedMessageConfig?.rotary1Enabled = config.rotary1Enabled
fetchedNode[0].cannedMessageConfig?.updown1Enabled = config.updown1Enabled
fetchedNode[0].cannedMessageConfig?.inputbrokerPinA = Int32(config.inputbrokerPinA)
fetchedNode[0].cannedMessageConfig?.inputbrokerPinB = Int32(config.inputbrokerPinB)
fetchedNode[0].cannedMessageConfig?.inputbrokerPinPress = Int32(config.inputbrokerPinPress)
fetchedNode[0].cannedMessageConfig?.inputbrokerEventCw = Int32(config.inputbrokerEventCw.rawValue)
fetchedNode[0].cannedMessageConfig?.inputbrokerEventCcw = Int32(config.inputbrokerEventCcw.rawValue)
fetchedNode[0].cannedMessageConfig?.inputbrokerEventPress = Int32(config.inputbrokerEventPress.rawValue)
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Canned Message Module Config for node number: \(String(nodeNum))")
2023-02-01 09:19:45 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data CannedMessageConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Canned Message Module Config")
2023-02-01 09:19:45 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data CannedMessageConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
2023-08-26 20:45:15 -07:00
func upsertDetectionSensorModuleConfigPacket(config: Meshtastic.ModuleConfig.DetectionSensorConfig, nodeNum: Int64, context: NSManagedObjectContext) {
let logString = String.localizedStringWithFormat("mesh.log.detectionsensor.config %@".localized, String(nodeNum))
MeshLogger.log("🕵️ \(logString)")
2023-08-26 20:45:15 -07:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
// Found a node, save Detection Sensor Config
if !fetchedNode.isEmpty {
if fetchedNode[0].detectionSensorConfig == nil {
let newConfig = DetectionSensorConfigEntity(context: context)
newConfig.enabled = config.enabled
newConfig.sendBell = config.sendBell
newConfig.name = config.name
newConfig.monitorPin = Int32(config.monitorPin)
newConfig.detectionTriggeredHigh = config.detectionTriggeredHigh
newConfig.usePullup = config.usePullup
newConfig.minimumBroadcastSecs = Int32(config.minimumBroadcastSecs)
newConfig.stateBroadcastSecs = Int32(config.stateBroadcastSecs)
fetchedNode[0].detectionSensorConfig = newConfig
} else {
fetchedNode[0].detectionSensorConfig?.enabled = config.enabled
fetchedNode[0].detectionSensorConfig?.sendBell = config.sendBell
fetchedNode[0].detectionSensorConfig?.name = config.name
fetchedNode[0].detectionSensorConfig?.monitorPin = Int32(config.monitorPin)
fetchedNode[0].detectionSensorConfig?.usePullup = config.usePullup
fetchedNode[0].detectionSensorConfig?.detectionTriggeredHigh = config.detectionTriggeredHigh
fetchedNode[0].detectionSensorConfig?.minimumBroadcastSecs = Int32(config.minimumBroadcastSecs)
fetchedNode[0].detectionSensorConfig?.stateBroadcastSecs = Int32(config.stateBroadcastSecs)
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Detection Sensor Module Config for node number: \(String(nodeNum))")
2023-08-26 20:45:15 -07:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data DetectionSensorConfigEntity: \(nsError)")
2023-08-26 20:45:15 -07:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Detection Sensor Module Config")
2023-08-26 20:45:15 -07:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)")
2023-08-26 20:45:15 -07:00
}
}
2023-02-01 09:19:45 -08:00
func upsertExternalNotificationModuleConfigPacket(config: Meshtastic.ModuleConfig.ExternalNotificationConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.externalnotification.config %@".localized, String(nodeNum))
2023-02-01 09:19:45 -08:00
MeshLogger.log("📣 \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-02-01 09:19:45 -08:00
// Found a node, save External Notificaitone Config
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
if fetchedNode[0].externalNotificationConfig == nil {
let newExternalNotificationConfig = ExternalNotificationConfigEntity(context: context)
newExternalNotificationConfig.enabled = config.enabled
newExternalNotificationConfig.usePWM = config.usePwm
newExternalNotificationConfig.alertBell = config.alertBell
newExternalNotificationConfig.alertBellBuzzer = config.alertBellBuzzer
newExternalNotificationConfig.alertBellVibra = config.alertBellVibra
newExternalNotificationConfig.alertMessage = config.alertMessage
newExternalNotificationConfig.alertMessageBuzzer = config.alertMessageBuzzer
newExternalNotificationConfig.alertMessageVibra = config.alertMessageVibra
newExternalNotificationConfig.active = config.active
newExternalNotificationConfig.output = Int32(config.output)
newExternalNotificationConfig.outputBuzzer = Int32(config.outputBuzzer)
newExternalNotificationConfig.outputVibra = Int32(config.outputVibra)
newExternalNotificationConfig.outputMilliseconds = Int32(config.outputMs)
newExternalNotificationConfig.nagTimeout = Int32(config.nagTimeout)
2023-12-20 10:24:01 -08:00
newExternalNotificationConfig.useI2SAsBuzzer = config.useI2SAsBuzzer
2023-02-01 09:19:45 -08:00
fetchedNode[0].externalNotificationConfig = newExternalNotificationConfig
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} else {
fetchedNode[0].externalNotificationConfig?.enabled = config.enabled
fetchedNode[0].externalNotificationConfig?.usePWM = config.usePwm
fetchedNode[0].externalNotificationConfig?.alertBell = config.alertBell
fetchedNode[0].externalNotificationConfig?.alertBellBuzzer = config.alertBellBuzzer
fetchedNode[0].externalNotificationConfig?.alertBellVibra = config.alertBellVibra
fetchedNode[0].externalNotificationConfig?.alertMessage = config.alertMessage
fetchedNode[0].externalNotificationConfig?.alertMessageBuzzer = config.alertMessageBuzzer
fetchedNode[0].externalNotificationConfig?.alertMessageVibra = config.alertMessageVibra
fetchedNode[0].externalNotificationConfig?.active = config.active
fetchedNode[0].externalNotificationConfig?.output = Int32(config.output)
fetchedNode[0].externalNotificationConfig?.outputBuzzer = Int32(config.outputBuzzer)
fetchedNode[0].externalNotificationConfig?.outputVibra = Int32(config.outputVibra)
fetchedNode[0].externalNotificationConfig?.outputMilliseconds = Int32(config.outputMs)
fetchedNode[0].externalNotificationConfig?.nagTimeout = Int32(config.nagTimeout)
2023-12-20 10:24:01 -08:00
fetchedNode[0].externalNotificationConfig?.useI2SAsBuzzer = config.useI2SAsBuzzer
2023-02-01 09:19:45 -08:00
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated External Notification Module Config for node number: \(String(nodeNum))")
2023-02-01 09:19:45 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save External Notification Module Config")
2023-02-01 09:19:45 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data ExternalNotificationConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
2024-02-25 11:24:01 -08:00
func upsertPaxCounterModuleConfigPacket(config: Meshtastic.ModuleConfig.PaxcounterConfig, nodeNum: Int64, context: NSManagedObjectContext) {
let logString = String.localizedStringWithFormat("mesh.log.paxcounter.config %@".localized, String(nodeNum))
2024-02-27 12:24:50 -08:00
MeshLogger.log("🧑‍🤝‍🧑 \(logString)")
2024-02-25 11:24:01 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
// Found a node, save PAX Counter Config
if !fetchedNode.isEmpty {
if fetchedNode[0].paxCounterConfig == nil {
let newPaxCounterConfig = PaxCounterConfigEntity(context: context)
newPaxCounterConfig.enabled = config.enabled
2024-06-02 09:45:56 -07:00
newPaxCounterConfig.updateInterval = Int32(config.paxcounterUpdateInterval)
2024-02-25 11:24:01 -08:00
fetchedNode[0].paxCounterConfig = newPaxCounterConfig
} else {
fetchedNode[0].paxCounterConfig?.enabled = config.enabled
2024-06-02 09:45:56 -07:00
fetchedNode[0].paxCounterConfig?.updateInterval = Int32(config.paxcounterUpdateInterval)
2024-02-25 11:24:01 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated PAX Counter Module Config for node number: \(String(nodeNum))")
2024-02-25 11:24:01 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data ExternalNotificationConfigEntity: \(nsError)")
2024-02-25 11:24:01 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save PAX Counter Module Config")
2024-02-25 11:24:01 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data PaxCounterConfigEntity failed: \(nsError)")
2024-02-25 11:24:01 -08:00
}
}
2023-03-25 22:14:39 -07:00
func upsertRtttlConfigPacket(ringtone: String, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-25 14:30:18 -07:00
let logString = String.localizedStringWithFormat("mesh.log.ringtone.config %@".localized, String(nodeNum))
2023-03-25 14:30:18 -07:00
MeshLogger.log("⛰️ \(logString)")
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
// Found a node, save RTTTL Config
if !fetchedNode.isEmpty {
if fetchedNode[0].rtttlConfig == nil {
let newRtttlConfig = RTTTLConfigEntity(context: context)
2023-03-25 22:14:39 -07:00
newRtttlConfig.ringtone = ringtone
2023-03-25 14:30:18 -07:00
fetchedNode[0].rtttlConfig = newRtttlConfig
} else {
2023-03-25 22:14:39 -07:00
fetchedNode[0].rtttlConfig?.ringtone = ringtone
2023-03-25 14:30:18 -07:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated RTTTL Ringtone Config for node number: \(String(nodeNum))")
2023-03-25 14:30:18 -07:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data RtttlConfigEntity: \(nsError)")
2023-03-25 14:30:18 -07:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save RTTTL Ringtone Config")
2023-03-25 14:30:18 -07:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data RtttlConfigEntity failed: \(nsError)")
2023-03-25 14:30:18 -07:00
}
}
2023-02-01 09:19:45 -08:00
func upsertMqttModuleConfigPacket(config: Meshtastic.ModuleConfig.MQTTConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.mqtt.config %@".localized, String(nodeNum))
2023-02-01 09:19:45 -08:00
MeshLogger.log("🌉 \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-02-01 09:19:45 -08:00
// Found a node, save MQTT Config
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
if fetchedNode[0].mqttConfig == nil {
let newMQTTConfig = MQTTConfigEntity(context: context)
newMQTTConfig.enabled = config.enabled
2023-08-06 17:41:46 -07:00
newMQTTConfig.proxyToClientEnabled = config.proxyToClientEnabled
2023-02-01 09:19:45 -08:00
newMQTTConfig.address = config.address
newMQTTConfig.username = config.username
2023-02-01 09:19:45 -08:00
newMQTTConfig.password = config.password
2023-05-04 21:49:35 -07:00
newMQTTConfig.root = config.root
2023-02-01 09:19:45 -08:00
newMQTTConfig.encryptionEnabled = config.encryptionEnabled
newMQTTConfig.jsonEnabled = config.jsonEnabled
2023-05-04 21:49:35 -07:00
newMQTTConfig.tlsEnabled = config.tlsEnabled
2024-03-26 13:26:23 -07:00
newMQTTConfig.mapReportingEnabled = config.mapReportingEnabled
newMQTTConfig.mapPositionPrecision = Int32(config.mapReportSettings.positionPrecision)
newMQTTConfig.mapPublishIntervalSecs = Int32(config.mapReportSettings.publishIntervalSecs)
2023-02-01 09:19:45 -08:00
fetchedNode[0].mqttConfig = newMQTTConfig
} else {
fetchedNode[0].mqttConfig?.enabled = config.enabled
2023-08-06 17:41:46 -07:00
fetchedNode[0].mqttConfig?.proxyToClientEnabled = config.proxyToClientEnabled
2023-02-01 09:19:45 -08:00
fetchedNode[0].mqttConfig?.address = config.address
fetchedNode[0].mqttConfig?.username = config.username
2023-02-01 09:19:45 -08:00
fetchedNode[0].mqttConfig?.password = config.password
2023-05-04 21:49:35 -07:00
fetchedNode[0].mqttConfig?.root = config.root
2023-02-01 09:19:45 -08:00
fetchedNode[0].mqttConfig?.encryptionEnabled = config.encryptionEnabled
fetchedNode[0].mqttConfig?.jsonEnabled = config.jsonEnabled
2023-05-04 21:49:35 -07:00
fetchedNode[0].mqttConfig?.tlsEnabled = config.tlsEnabled
2024-03-26 13:26:23 -07:00
fetchedNode[0].mqttConfig?.mapReportingEnabled = config.mapReportingEnabled
fetchedNode[0].mqttConfig?.mapPositionPrecision = Int32(config.mapReportSettings.positionPrecision)
fetchedNode[0].mqttConfig?.mapPublishIntervalSecs = Int32(config.mapReportSettings.publishIntervalSecs)
2023-02-01 09:19:45 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated MQTT Config for node number: \(String(nodeNum))")
2023-02-01 09:19:45 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data MQTTConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save MQTT Module Config")
2023-02-01 09:19:45 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data MQTTConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
func upsertRangeTestModuleConfigPacket(config: Meshtastic.ModuleConfig.RangeTestConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.rangetest.config %@".localized, String(nodeNum))
2023-02-01 09:19:45 -08:00
MeshLogger.log("⛰️ \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-02-01 09:19:45 -08:00
// Found a node, save Device Config
if !fetchedNode.isEmpty {
if fetchedNode[0].rangeTestConfig == nil {
let newRangeTestConfig = RangeTestConfigEntity(context: context)
newRangeTestConfig.sender = Int32(config.sender)
newRangeTestConfig.enabled = config.enabled
newRangeTestConfig.save = config.save
fetchedNode[0].rangeTestConfig = newRangeTestConfig
} else {
fetchedNode[0].rangeTestConfig?.sender = Int32(config.sender)
fetchedNode[0].rangeTestConfig?.enabled = config.enabled
fetchedNode[0].rangeTestConfig?.save = config.save
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Range Test Config for node number: \(String(nodeNum))")
2023-02-01 09:19:45 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data RangeTestConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Range Test Module Config")
2023-02-01 09:19:45 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data RangeTestConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
func upsertSerialModuleConfigPacket(config: Meshtastic.ModuleConfig.SerialConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-03-06 10:33:18 -08:00
let logString = String.localizedStringWithFormat("mesh.log.serial.config %@".localized, String(nodeNum))
2023-02-01 09:19:45 -08:00
MeshLogger.log("🤖 \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
// Found a node, save Device Config
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
if fetchedNode[0].serialConfig == nil {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let newSerialConfig = SerialConfigEntity(context: context)
newSerialConfig.enabled = config.enabled
newSerialConfig.echo = config.echo
newSerialConfig.rxd = Int32(config.rxd)
newSerialConfig.txd = Int32(config.txd)
newSerialConfig.baudRate = Int32(config.baud.rawValue)
newSerialConfig.timeout = Int32(config.timeout)
newSerialConfig.mode = Int32(config.mode.rawValue)
fetchedNode[0].serialConfig = newSerialConfig
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} else {
fetchedNode[0].serialConfig?.enabled = config.enabled
fetchedNode[0].serialConfig?.echo = config.echo
fetchedNode[0].serialConfig?.rxd = Int32(config.rxd)
fetchedNode[0].serialConfig?.txd = Int32(config.txd)
fetchedNode[0].serialConfig?.baudRate = Int32(config.baud.rawValue)
fetchedNode[0].serialConfig?.timeout = Int32(config.timeout)
fetchedNode[0].serialConfig?.mode = Int32(config.mode.rawValue)
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Serial Module Config for node number: \(String(nodeNum))")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} catch {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
context.rollback()
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data SerialConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} else {
2023-03-06 10:33:18 -08:00
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Serial Module Config")
2023-02-01 09:19:45 -08:00
}
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} catch {
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data SerialConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
2023-08-26 20:45:15 -07:00
func upsertStoreForwardModuleConfigPacket(config: Meshtastic.ModuleConfig.StoreForwardConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-02-01 09:19:45 -08:00
2023-08-26 20:45:15 -07:00
let logString = String.localizedStringWithFormat("mesh.log.storeforward.config %@".localized, String(nodeNum))
MeshLogger.log("📬 \(logString)")
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
do {
2023-03-06 10:33:18 -08:00
2023-03-06 15:30:10 -08:00
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-08-26 20:45:15 -07:00
// Found a node, save Store & Forward Sensor Config
2023-02-01 09:19:45 -08:00
if !fetchedNode.isEmpty {
2023-03-06 10:33:18 -08:00
2023-08-26 20:45:15 -07:00
if fetchedNode[0].storeForwardConfig == nil {
2023-03-06 10:33:18 -08:00
2023-08-26 20:45:15 -07:00
let newConfig = StoreForwardConfigEntity(context: context)
newConfig.enabled = config.enabled
newConfig.heartbeat = config.heartbeat
newConfig.records = Int32(config.records)
newConfig.historyReturnMax = Int32(config.historyReturnMax)
newConfig.historyReturnWindow = Int32(config.historyReturnWindow)
fetchedNode[0].storeForwardConfig = newConfig
2023-03-06 10:33:18 -08:00
2023-02-01 09:19:45 -08:00
} else {
2023-08-26 20:45:15 -07:00
fetchedNode[0].storeForwardConfig?.enabled = config.enabled
fetchedNode[0].storeForwardConfig?.heartbeat = config.heartbeat
fetchedNode[0].storeForwardConfig?.records = Int32(config.records)
fetchedNode[0].storeForwardConfig?.historyReturnMax = Int32(config.historyReturnMax)
fetchedNode[0].storeForwardConfig?.historyReturnWindow = Int32(config.historyReturnWindow)
2023-02-01 09:19:45 -08:00
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Store & Forward Module Config for node number: \(String(nodeNum))")
2023-02-01 09:19:45 -08:00
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data StoreForwardConfigEntity: \(nsError)")
2023-02-01 09:19:45 -08:00
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Store & Forward Module Config")
2023-02-01 09:19:45 -08:00
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data DetectionSensorConfigEntity failed: \(nsError)")
2023-02-01 09:19:45 -08:00
}
}
2023-08-26 20:45:15 -07:00
func upsertTelemetryModuleConfigPacket(config: Meshtastic.ModuleConfig.TelemetryConfig, nodeNum: Int64, context: NSManagedObjectContext) {
2023-08-26 20:45:15 -07:00
let logString = String.localizedStringWithFormat("mesh.log.telemetry.config %@".localized, String(nodeNum))
MeshLogger.log("📈 \(logString)")
let fetchNodeInfoRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "NodeInfoEntity")
fetchNodeInfoRequest.predicate = NSPredicate(format: "num == %lld", Int64(nodeNum))
do {
guard let fetchedNode = try context.fetch(fetchNodeInfoRequest) as? [NodeInfoEntity] else {
return
}
2023-08-26 20:45:15 -07:00
// Found a node, save Telemetry Config
if !fetchedNode.isEmpty {
2023-08-26 20:45:15 -07:00
if fetchedNode[0].telemetryConfig == nil {
2023-08-26 20:45:15 -07:00
let newTelemetryConfig = TelemetryConfigEntity(context: context)
newTelemetryConfig.deviceUpdateInterval = Int32(config.deviceUpdateInterval)
newTelemetryConfig.environmentUpdateInterval = Int32(config.environmentUpdateInterval)
newTelemetryConfig.environmentMeasurementEnabled = config.environmentMeasurementEnabled
newTelemetryConfig.environmentScreenEnabled = config.environmentScreenEnabled
newTelemetryConfig.environmentDisplayFahrenheit = config.environmentDisplayFahrenheit
2024-03-14 00:04:35 -07:00
newTelemetryConfig.powerMeasurementEnabled = config.powerMeasurementEnabled
newTelemetryConfig.powerUpdateInterval = Int32(config.powerUpdateInterval)
newTelemetryConfig.powerScreenEnabled = config.powerScreenEnabled
2023-08-26 20:45:15 -07:00
fetchedNode[0].telemetryConfig = newTelemetryConfig
} else {
2023-08-26 20:45:15 -07:00
fetchedNode[0].telemetryConfig?.deviceUpdateInterval = Int32(config.deviceUpdateInterval)
fetchedNode[0].telemetryConfig?.environmentUpdateInterval = Int32(config.environmentUpdateInterval)
fetchedNode[0].telemetryConfig?.environmentMeasurementEnabled = config.environmentMeasurementEnabled
fetchedNode[0].telemetryConfig?.environmentScreenEnabled = config.environmentScreenEnabled
fetchedNode[0].telemetryConfig?.environmentDisplayFahrenheit = config.environmentDisplayFahrenheit
2024-03-14 00:04:35 -07:00
fetchedNode[0].telemetryConfig?.powerMeasurementEnabled = config.powerMeasurementEnabled
fetchedNode[0].telemetryConfig?.powerUpdateInterval = Int32(config.powerUpdateInterval)
fetchedNode[0].telemetryConfig?.powerScreenEnabled = config.powerScreenEnabled
}
do {
try context.save()
2024-06-03 02:17:55 -07:00
Logger.data.info("💾 Updated Telemetry Module Config for node number: \(String(nodeNum))")
} catch {
context.rollback()
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Error Updating Core Data TelemetryConfigEntity: \(nsError)")
}
} else {
2024-06-03 02:17:55 -07:00
Logger.data.error("No Nodes found in local database matching node number \(nodeNum) unable to save Telemetry Module Config")
}
} catch {
let nsError = error as NSError
2024-06-03 02:17:55 -07:00
Logger.data.error("Fetching node for core data TelemetryConfigEntity failed: \(nsError)")
}
}