Quellcode durchsuchen

Remove extra logic, extra comments, move to logging instead of print

Sam King vor 1 Jahr
Ursprung
Commit
ba63e18691

+ 0 - 4
FreeAPS.xcodeproj/project.pbxproj

@@ -255,7 +255,6 @@
 		3B5CD2CE2D4AECD500CE213C /* ProfileBasalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B5CD2C12D4AECD500CE213C /* ProfileBasalTests.swift */; };
 		3BCE75B32D4B38AE009E9453 /* InsulinSensitivities+Convert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BCE75B22D4B38A0009E9453 /* InsulinSensitivities+Convert.swift */; };
 		3BCE75B52D4B391F009E9453 /* Decimal+rounding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BCE75B42D4B3917009E9453 /* Decimal+rounding.swift */; };
-		3BCE75B72D4B3DCF009E9453 /* BGTargets+Convert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BCE75B62D4B3DC4009E9453 /* BGTargets+Convert.swift */; };
 		45252C95D220E796FDB3B022 /* ConfigEditorDataFlow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F8A87AA037BD079BA3528BA /* ConfigEditorDataFlow.swift */; };
 		45717281F743594AA9D87191 /* ConfigEditorRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 920DDB21E5D0EB813197500D /* ConfigEditorRootView.swift */; };
 		5075C1608E6249A51495C422 /* TargetsEditorProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BDEA2DC60EDE0A3CA54DC73 /* TargetsEditorProvider.swift */; };
@@ -981,7 +980,6 @@
 		3B5CD2C62D4AECD500CE213C /* ProfileTargetsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileTargetsTests.swift; sourceTree = "<group>"; };
 		3BCE75B22D4B38A0009E9453 /* InsulinSensitivities+Convert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InsulinSensitivities+Convert.swift"; sourceTree = "<group>"; };
 		3BCE75B42D4B3917009E9453 /* Decimal+rounding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Decimal+rounding.swift"; sourceTree = "<group>"; };
-		3BCE75B62D4B3DC4009E9453 /* BGTargets+Convert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BGTargets+Convert.swift"; sourceTree = "<group>"; };
 		3BDEA2DC60EDE0A3CA54DC73 /* TargetsEditorProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = TargetsEditorProvider.swift; sourceTree = "<group>"; };
 		3BF768BD6264FF7D71D66767 /* NightscoutConfigProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = NightscoutConfigProvider.swift; sourceTree = "<group>"; };
 		3F60E97100041040446F44E7 /* PumpConfigStateModel.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PumpConfigStateModel.swift; sourceTree = "<group>"; };
@@ -2374,7 +2372,6 @@
 		3B5CD2A42D4AEA5D00CE213C /* Extensions */ = {
 			isa = PBXGroup;
 			children = (
-				3BCE75B62D4B3DC4009E9453 /* BGTargets+Convert.swift */,
 				3B5CD2A32D4AEA5D00CE213C /* Date+MinutesFromMidnight.swift */,
 				3BCE75B42D4B3917009E9453 /* Decimal+rounding.swift */,
 				3BCE75B22D4B38A0009E9453 /* InsulinSensitivities+Convert.swift */,
@@ -3638,7 +3635,6 @@
 				58645BA32CA2D325008AFCE7 /* BatterySetup.swift in Sources */,
 				388E5A5C25B6F0770019842D /* JSON.swift in Sources */,
 				3811DF0225CA9FEA00A708ED /* Credentials.swift in Sources */,
-				3BCE75B72D4B3DCF009E9453 /* BGTargets+Convert.swift in Sources */,
 				5837A5302BD2E3C700A5DC04 /* CarbEntryStored+helper.swift in Sources */,
 				389A572026079BAA00BC102F /* Interpolation.swift in Sources */,
 				DD9ECB702CA9A0BA00AA7C45 /* RemoteControlConfigStateModel.swift in Sources */,

+ 12 - 1
FreeAPS.xcodeproj/xcshareddata/xcschemes/Trio.xcscheme

@@ -264,7 +264,18 @@
       buildConfiguration = "Debug"
       selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
       selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
-      shouldUseLaunchSchemeArgsEnv = "YES">
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      codeCoverageEnabled = "YES"
+      onlyGenerateCoverageForSpecifiedTargets = "YES">
+      <CodeCoverageTargets>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "388E595725AD948C0019842D"
+            BuildableName = "FreeAPS.app"
+            BlueprintName = "FreeAPS"
+            ReferencedContainer = "container:FreeAPS.xcodeproj">
+         </BuildableReference>
+      </CodeCoverageTargets>
       <Testables>
          <TestableReference
             skipped = "NO">

+ 0 - 14
FreeAPS/Sources/APS/OpenAPSSwift/Extensions/BGTargets+Convert.swift

@@ -1,14 +0,0 @@
-import Foundation
-
-extension BGTargets {
-    func inMgDl() -> BGTargets {
-        switch units {
-        case .mgdL:
-            return self
-        case .mmolL:
-            let targets = targets
-                .map { BGTargetEntry(low: $0.low * 18, high: $0.high * 18, start: $0.start, offset: $0.offset) }
-            return BGTargets(units: .mgdL, userPreferredUnits: userPreferredUnits, targets: targets)
-        }
-    }
-}

+ 0 - 15
FreeAPS/Sources/APS/OpenAPSSwift/Extensions/InsulinSensitivities+Convert.swift

@@ -6,19 +6,4 @@ extension InsulinSensitivities {
             .map { ComputedInsulinSensitivityEntry(sensitivity: $0.sensitivity, offset: $0.offset, start: $0.start) }
         return ComputedInsulinSensitivities(units: units, userPreferredUnits: userPreferredUnits, sensitivities: sensitivities)
     }
-
-    func inMgDl() -> InsulinSensitivities {
-        switch units {
-        case .mgdL:
-            return self
-        case .mmolL:
-            let sensitivities = self.sensitivities
-                .map { InsulinSensitivityEntry(sensitivity: $0.sensitivity * 18, offset: $0.offset, start: $0.start) }
-            return InsulinSensitivities(
-                units: .mgdL,
-                userPreferredUnits: userPreferredUnits,
-                sensitivities: sensitivities
-            )
-        }
-    }
 }

+ 1 - 1
FreeAPS/Sources/APS/OpenAPSSwift/Profile/Basal.swift

@@ -8,7 +8,7 @@ struct Basal {
         let basalProfileData = basalProfile
 
         guard let lastBasalRate = basalProfileData.last?.rate, lastBasalRate != 0 else {
-            print("ERROR: bad basal schedule \(basalProfile)")
+            warning(.openAPS, "Warning: bad basal schedule \(basalProfile)")
             return nil
         }
 

+ 1 - 1
FreeAPS/Sources/APS/OpenAPSSwift/Profile/Carbs.swift

@@ -20,7 +20,7 @@ struct Carbs {
 
         // Check for invalid values
         if currentRatio < 3 || currentRatio > 150 {
-            print("Error: carbRatio of \(currentRatio) out of bounds.")
+            warning(.openAPS, "Warning: carbRatio of \(currentRatio) out of bounds.")
             return nil
         }
 

+ 3 - 42
FreeAPS/Sources/APS/OpenAPSSwift/Profile/ProfileGenerator.swift

@@ -77,8 +77,6 @@ enum ProfileGenerator {
         autotune _: Autotune?,
         freeaps _: FreeAPSSettings
     ) throws -> Profile {
-        let bgTargets = bgTargets.inMgDl()
-        let isf = isf.inMgDl()
         let model = model.replacingOccurrences(of: "\"", with: "").trimmingCharacters(in: .whitespacesAndNewlines)
 
         guard !carbRatios.schedule.isEmpty else {
@@ -97,39 +95,9 @@ enum ProfileGenerator {
             preferences.insulinPeakTime = 55
         default:
             // don't do anything
-            print("don't modify insulin peak time")
+            debug(.openAPS, "don't modify insulin peak time")
         }
 
-        /* From Javascript
-         for (var pref in preferences) {
-           if (preferences.hasOwnProperty(pref)) {
-             inputs[pref] = preferences[pref];
-           }
-         }
-
-         inputs.max_iob = inputs.max_iob || 0;
-         */
-        // we don't need the JS logic above because it is handled by
-        // our update function
-
-        // in Trio it looks like autotune is always null
-        /*
-          var basalProfile = basalProfile
-          var carbRatios = carbRatios
-         if let autotune = autotune {
-             if let basal = autotune.basalProfile {
-                 basalProfile = basal
-             }
-             // onlyAutotuneBasals is not defined in Swift
-             if let isfProfile = autotune.isfProfile {
-                 // TODO: should we convert this to mg/dL as well?
-                 isf = isfProfile
-             }
-             if let carbRatio = autotune.carbRatio {
-                 carbRatios.schedule[0].ratio = carbRatio
-             }
-         }
-          */
         return try generate(
             pumpSettings: pumpSettings,
             bgTargets: bgTargets,
@@ -153,8 +121,7 @@ enum ProfileGenerator {
         tempTargets: [TempTarget],
         model: String
     ) throws -> Profile {
-        // var profile = opts && opts.type ? opts : defaults( );
-        var profile = Profile() // uses defaults
+        var profile = Profile() // start with the defaults
 
         // check if inputs has overrides for any of the default prefs
         // and apply if applicable. Note, this comes from the generate/profile.js
@@ -193,11 +160,8 @@ enum ProfileGenerator {
             throw ProfileError.invalidMaxBasal(value: profile.maxBasal)
         }
 
-        // var range = targets.bgTargetsLookup(inputs, profile);
         profile.outUnits = bgTargets.userPreferredUnits.rawValue
         let (updatedTargets, range) = try Targets.bgTargetsLookup(targets: bgTargets, tempTargets: tempTargets, profile: profile)
-        // profile.min_bg = Math.round(range.min_bg);
-        // profile.max_bg = Math.round(range.max_bg);
         profile.minBg = range.minBg?.rounded()
         profile.maxBg = range.maxBg?.rounded()
         // Note: we're using updatedTargets here because in Javascript the bgTargetsLookup
@@ -222,16 +186,13 @@ enum ProfileGenerator {
             targets: roundedTargets
         )
 
-        // delete profile.bg_targets.raw;
-        // Note: we don't need this in Swift as we don't have the raw property
-
         profile.temptargetSet = range.temptargetSet
         let (sens, isfUpdated) = try Isf.isfLookup(isfDataInput: isf)
         profile.sens = sens
         profile.isfProfile = isfUpdated
 
         guard let sens = profile.sens, sens >= 5 else {
-            print("ISF of \(String(describing: profile.sens)) is not supported")
+            debug(.openAPS, "ISF of \(String(describing: profile.sens)) is not supported")
             throw ProfileError.invalidISF(value: profile.sens)
         }
 

+ 4 - 10
FreeAPS/Sources/APS/OpenAPSSwift/Profile/Targets.swift

@@ -1,12 +1,9 @@
 import Foundation
 
 struct Targets {
-    ///  The Javascript implementation was hard to port. First, it mutates
-    ///  the inputs in a way that is visible in the Profile. Second, there
-    ///  is a line of code where it sets the high value to low but only if
-    ///  it's not a temp target. I'm going to port it as is for now, but this
-    ///  is worth revisiting after we're done with the port.
-    ///
+    // The Javascript implementation was hard to port because it
+    // mutates the inputs in a way that is visible in the Profile.
+    //
     //  TODO: See if we can get rid of the logic that mutates inputs in Javascript
     static func lookup(
         targets: BGTargets,
@@ -56,7 +53,7 @@ struct Targets {
                     break
                 }
             } else {
-                print("eventualBG target range invalid: \(target.targetBottom ?? -1)-\(target.targetTop ?? -1)")
+                warning(.openAPS, "eventualBG target range invalid: \(target.targetBottom ?? -1)-\(target.targetTop ?? -1)")
                 break
             }
         }
@@ -69,9 +66,6 @@ struct Targets {
 
     static func boundTargetRange(_ entry: ComputedBGTargetEntry) -> ComputedBGTargetEntry {
         var target = entry
-        // Convert from mmol/L to mg/dL if needed
-        if target.high < 20 { target.high *= 18 }
-        if target.low < 20 { target.low *= 18 }
 
         // hard-code lower bounds for min_bg and max_bg in case pump is set too low, or units are wrong
         var maxBg = max(80, target.high)

+ 3 - 3
FreeAPS/Sources/APS/OpenAPSSwift/Utils/JSONCompare.swift

@@ -63,12 +63,12 @@ public enum JSONCompare {
         javascriptRuntime: TimeInterval
     ) {
         guard let differences = try? differences(native: native, javascript: javascript) else {
-            print("Exception calculating differences")
+            warning(.openAPS, "Exception calculating differences")
             return
         }
 
         // TODO: For now we'll just print this out to the console but we'll add proper logging next
-        print("\(label) -> n: \(nativeRuntime)s, js: \(javascriptRuntime)s")
+        debug(.openAPS, "\(label) -> n: \(nativeRuntime)s, js: \(javascriptRuntime)s")
         prettyPrint(differences)
     }
 
@@ -79,7 +79,7 @@ public enum JSONCompare {
         if let data = try? encoder.encode(differences),
            let prettyString = String(data: data, encoding: .utf8)
         {
-            print(prettyString)
+            debug(.openAPS, prettyString)
         }
     }
 

+ 0 - 13
FreeAPSTests/OpenAPSSwiftTests/ProfileTargetsTests.swift

@@ -87,19 +87,6 @@ import Testing
         #expect(result.low == 100)
     }
 
-    @Test("should bound target range for mmol/L input") func boundMmolTargets() async throws {
-        let mmolTargets = BGTargets(
-            units: .mmolL,
-            userPreferredUnits: .mmolL,
-            targets: [
-                BGTargetEntry(low: 3, high: 4, start: "00:00:00", offset: 0)
-            ]
-        )
-        let (_, result) = try Targets.bgTargetsLookup(targets: mmolTargets, tempTargets: [], profile: profile)
-        #expect(result.maxBg == 80)
-        #expect(result.minBg == 80)
-    }
-
     @Test("should enforce hard limits on target range") func enforceHardLimits() async throws {
         let extremeTargets = BGTargets(
             units: .mgdL,

+ 6 - 3
oref_swift_port_notes.md

@@ -25,9 +25,12 @@ something different if people have strong opinions here.
 
 Our plan is:
 
-1. Port one function at a time. The functions are `iob`, `meal`,
-`autotunePrepare`, `autotuneRun`, `determineBasal`, `autosense`,
-`exportDefaultPreferences`, and `makeProfile`.
+1. Port one function at a time. The functions, in order, are:
+  - `makeProfile`
+  - `iob`
+  - `meal`
+  - `autosense`
+  - `determineBasal`
 
 2. For each function, the process will be:
   - Write the code in Swift