Kaynağa Gözat

Add missing function to handle userInfo updates from WCSession WIP

Deniz Cengiz 1 yıl önce
ebeveyn
işleme
919f6b2afb

+ 149 - 135
Trio Watch App Extension/WatchState.swift

@@ -269,177 +269,191 @@ import WatchConnectivity
         }
     }
 
-    // MARK: - WCSessionDelegate
-
-    /// Called when the session has completed activation
-    /// Updates the reachability status and logs the activation state
-    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
-        DispatchQueue.main.async {
-            if let error = error {
-                print("⌚️ Watch session activation failed: \(error.localizedDescription)")
-                return
+    private func processRawDataForWatchState(_ message: [String: Any]) {
+        if let acknowledged = message["acknowledged"] as? Bool,
+           let ackMessage = message["message"] as? String
+        {
+            switch ackMessage {
+            case "Saving carbs...":
+                isMealBolusCombo = true
+                mealBolusStep = .savingCarbs
+                showCommsAnimation = true
+                handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
+            case "Enacting bolus...":
+                isMealBolusCombo = true
+                mealBolusStep = .enactingBolus
+                showCommsAnimation = true
+                handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
+            case "Carbs and bolus logged successfully":
+                isMealBolusCombo = false
+                handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
+            default:
+                isMealBolusCombo = false
+                handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
             }
+        }
 
-            print("⌚️ Watch session activated with state: \(activationState.rawValue)")
-            self.isReachable = session.isReachable
-            print("⌚️ Watch isReachable after activation: \(session.isReachable)")
+        if let currentGlucose = message["currentGlucose"] as? String {
+            self.currentGlucose = currentGlucose
         }
-    }
 
-    /// Handles incoming messages from the paired iPhone
-    /// Updates local glucose data, trend, and delta information
-    func session(_: WCSession, didReceiveMessage message: [String: Any]) {
-        print("⌚️ Watch received message: \(message)")
-
-        DispatchQueue.main.async { [weak self] in
-            guard let self = self else { return }
-
-            if let acknowledged = message["acknowledged"] as? Bool,
-               let ackMessage = message["message"] as? String
-            {
-                switch ackMessage {
-                case "Saving carbs...":
-                    self.isMealBolusCombo = true
-                    self.mealBolusStep = .savingCarbs
-                    self.showCommsAnimation = true
-                    self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
-                case "Enacting bolus...":
-                    self.isMealBolusCombo = true
-                    self.mealBolusStep = .enactingBolus
-                    self.showCommsAnimation = true
-                    self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: false)
-                case "Carbs and bolus logged successfully":
-                    self.isMealBolusCombo = false
-                    self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
-                default:
-                    self.isMealBolusCombo = false
-                    self.handleAcknowledgment(success: acknowledged, message: ackMessage, isFinal: true)
-                }
-            }
+        if let currentGlucoseColorString = message["currentGlucoseColorString"] as? String {
+            self.currentGlucoseColorString = currentGlucoseColorString
+        }
 
-            if let currentGlucose = message["currentGlucose"] as? String {
-                self.currentGlucose = currentGlucose
-            }
+        if let trend = message["trend"] as? String {
+            self.trend = trend
+        }
 
-            if let currentGlucoseColorString = message["currentGlucoseColorString"] as? String {
-                self.currentGlucoseColorString = currentGlucoseColorString
-            }
+        if let delta = message["delta"] as? String {
+            self.delta = delta
+        }
 
-            if let trend = message["trend"] as? String {
-                self.trend = trend
-            }
+        if let iob = message["iob"] as? String {
+            self.iob = iob
+        }
 
-            if let delta = message["delta"] as? String {
-                self.delta = delta
-            }
+        if let cob = message["cob"] as? String {
+            self.cob = cob
+        }
 
-            if let iob = message["iob"] as? String {
-                self.iob = iob
-            }
+        if let lastLoopTime = message["lastLoopTime"] as? String {
+            self.lastLoopTime = lastLoopTime
+        }
 
-            if let cob = message["cob"] as? String {
-                self.cob = cob
+        if let glucoseData = message["glucoseValues"] as? [[String: Any]] {
+            glucoseValues = glucoseData.compactMap { data in
+                guard let glucose = data["glucose"] as? Double,
+                      let timestamp = data["date"] as? TimeInterval,
+                      let colorString = data["color"] as? String
+                else { return nil }
+
+                return (
+                    Date(timeIntervalSince1970: timestamp),
+                    glucose,
+                    colorString.toColor() // Convert colorString to Color
+                )
             }
+            .sorted { $0.date < $1.date }
+        }
 
-            if let lastLoopTime = message["lastLoopTime"] as? String {
-                self.lastLoopTime = lastLoopTime
+        if let overrideData = message["overridePresets"] as? [[String: Any]] {
+            overridePresets = overrideData.compactMap { data in
+                guard let name = data["name"] as? String,
+                      let isEnabled = data["isEnabled"] as? Bool
+                else { return nil }
+                return OverridePresetWatch(name: name, isEnabled: isEnabled)
             }
+        }
 
-            if let glucoseData = message["glucoseValues"] as? [[String: Any]] {
-                self.glucoseValues = glucoseData.compactMap { data in
-                    guard let glucose = data["glucose"] as? Double,
-                          let timestamp = data["date"] as? TimeInterval,
-                          let colorString = data["color"] as? String
-                    else { return nil }
-
-                    return (
-                        Date(timeIntervalSince1970: timestamp),
-                        glucose,
-                        colorString.toColor() // Convert colorString to Color
-                    )
-                }
-                .sorted { $0.date < $1.date }
+        if let tempTargetData = message["tempTargetPresets"] as? [[String: Any]] {
+            tempTargetPresets = tempTargetData.compactMap { data in
+                guard let name = data["name"] as? String,
+                      let isEnabled = data["isEnabled"] as? Bool
+                else { return nil }
+                return TempTargetPresetWatch(name: name, isEnabled: isEnabled)
             }
+        }
 
-            if let overrideData = message["overridePresets"] as? [[String: Any]] {
-                self.overridePresets = overrideData.compactMap { data in
-                    guard let name = data["name"] as? String,
-                          let isEnabled = data["isEnabled"] as? Bool
-                    else { return nil }
-                    return OverridePresetWatch(name: name, isEnabled: isEnabled)
-                }
+        if let bolusProgress = message["bolusProgress"] as? Double {
+            if !isBolusCanceled {
+                self.bolusProgress = bolusProgress
             }
+        }
 
-            if let tempTargetData = message["tempTargetPresets"] as? [[String: Any]] {
-                self.tempTargetPresets = tempTargetData.compactMap { data in
-                    guard let name = data["name"] as? String,
-                          let isEnabled = data["isEnabled"] as? Bool
-                    else { return nil }
-                    return TempTargetPresetWatch(name: name, isEnabled: isEnabled)
-                }
-            }
+        if let bolusWasCanceled = message["bolusCanceled"] as? Bool, bolusWasCanceled {
+            bolusProgress = 0
+            activeBolusAmount = 0
+            return
+        }
 
-            if let bolusProgress = message["bolusProgress"] as? Double {
-                if !self.isBolusCanceled {
-                    self.bolusProgress = bolusProgress
-                }
+        // Debug print für die Safety Limits
+        if let maxBolusValue = message["maxBolus"] {
+            print("⌚️ Received maxBolus: \(maxBolusValue) of type \(type(of: maxBolusValue))")
+            if let decimalValue = (maxBolusValue as? NSNumber)?.decimalValue {
+                maxBolus = decimalValue
+                print("⌚️ Converted maxBolus to: \(decimalValue)")
             }
+        }
 
-            if let bolusWasCanceled = message["bolusCanceled"] as? Bool, bolusWasCanceled {
-                self.bolusProgress = 0
-                self.activeBolusAmount = 0
-                return
+        if let maxCarbsValue = message["maxCarbs"] {
+            if let decimalValue = (maxCarbsValue as? NSNumber)?.decimalValue {
+                maxCarbs = decimalValue
             }
+        }
 
-            // Debug print für die Safety Limits
-            if let maxBolusValue = message["maxBolus"] {
-                print("⌚️ Received maxBolus: \(maxBolusValue) of type \(type(of: maxBolusValue))")
-                if let decimalValue = (maxBolusValue as? NSNumber)?.decimalValue {
-                    self.maxBolus = decimalValue
-                    print("⌚️ Converted maxBolus to: \(decimalValue)")
-                }
+        if let maxFatValue = message["maxFat"] {
+            if let decimalValue = (maxFatValue as? NSNumber)?.decimalValue {
+                maxFat = decimalValue
             }
+        }
 
-            if let maxCarbsValue = message["maxCarbs"] {
-                if let decimalValue = (maxCarbsValue as? NSNumber)?.decimalValue {
-                    self.maxCarbs = decimalValue
-                }
+        if let maxProteinValue = message["maxProtein"] {
+            if let decimalValue = (maxProteinValue as? NSNumber)?.decimalValue {
+                maxProtein = decimalValue
             }
+        }
 
-            if let maxFatValue = message["maxFat"] {
-                if let decimalValue = (maxFatValue as? NSNumber)?.decimalValue {
-                    self.maxFat = decimalValue
-                }
+        if let maxIOBValue = message["maxIOB"] {
+            if let decimalValue = (maxIOBValue as? NSNumber)?.decimalValue {
+                maxIOB = decimalValue
             }
+        }
 
-            if let maxProteinValue = message["maxProtein"] {
-                if let decimalValue = (maxProteinValue as? NSNumber)?.decimalValue {
-                    self.maxProtein = decimalValue
-                }
+        if let maxCOBValue = message["maxCOB"] {
+            if let decimalValue = (maxCOBValue as? NSNumber)?.decimalValue {
+                maxCOB = decimalValue
             }
+        }
 
-            if let maxIOBValue = message["maxIOB"] {
-                if let decimalValue = (maxIOBValue as? NSNumber)?.decimalValue {
-                    self.maxIOB = decimalValue
-                }
+        if let bolusIncrement = message["bolusIncrement"] {
+            if let decimalValue = (bolusIncrement as? NSNumber)?.decimalValue {
+                self.bolusIncrement = decimalValue
             }
+        }
 
-            if let maxCOBValue = message["maxCOB"] {
-                if let decimalValue = (maxCOBValue as? NSNumber)?.decimalValue {
-                    self.maxCOB = decimalValue
-                }
-            }
+        if let recommendedBolus = message["recommendedBolus"] as? NSNumber {
+            self.recommendedBolus = recommendedBolus.decimalValue
+            showBolusCalculationProgress = false
+        }
+    }
 
-            if let bolusIncrement = message["bolusIncrement"] {
-                if let decimalValue = (bolusIncrement as? NSNumber)?.decimalValue {
-                    self.bolusIncrement = decimalValue
-                }
-            }
+    // MARK: - WCSessionDelegate
 
-            if let recommendedBolus = message["recommendedBolus"] as? NSNumber {
-                self.recommendedBolus = recommendedBolus.decimalValue
-                showBolusCalculationProgress = false
+    /// Called when the session has completed activation
+    /// Updates the reachability status and logs the activation state
+    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
+        DispatchQueue.main.async {
+            if let error = error {
+                print("⌚️ Watch session activation failed: \(error.localizedDescription)")
+                return
             }
+
+            print("⌚️ Watch session activated with state: \(activationState.rawValue)")
+            self.isReachable = session.isReachable
+            print("⌚️ Watch isReachable after activation: \(session.isReachable)")
+        }
+    }
+
+    /// Handles incoming messages from the paired iPhone
+    /// Updates local glucose data, trend, and delta information
+    func session(_: WCSession, didReceiveMessage message: [String: Any]) {
+        print("⌚️ Watch received data from message: \(message)")
+
+        let dataFromMessage = message["watchState"] as! [String: Any]
+
+        DispatchQueue.main.async {
+            self.processRawDataForWatchState(dataFromMessage)
+        }
+    }
+
+    func session(_: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
+        print("⌚️ Watch received data from userInfo: \(userInfo)")
+
+        let dataFromUserInfo = userInfo["watchState"] as! [String: Any]
+
+        DispatchQueue.main.async {
+            self.processRawDataForWatchState(dataFromUserInfo)
         }
     }
 

+ 3 - 3
Trio/Sources/Services/WatchManager/AppleWatchManager.swift

@@ -384,11 +384,11 @@ final class BaseWatchManager: NSObject, WCSessionDelegate, Injectable, WatchMana
         // if session is reachable, it means watch App is in the foreground -> send watchState as message
         // if session is not reachable, it means it's in background -> send watchState as userInfo
         if session.isReachable {
-            session.sendMessage(message, replyHandler: nil, errorHandler: { (error) -> Void in
-                debug(.watchManager, "❌ Error sending watch state: \(error.localizedDescription)")
+            session.sendMessage(["watchState": message], replyHandler: nil, errorHandler: { (error) -> Void in
+                debug(.watchManager, "❌ Error sending watch state as message: \(error.localizedDescription)")
             })
         } else {
-            session.transferUserInfo(message)
+            session.transferUserInfo(["watchState": message])
         }
     }