-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreMeal.patch
118 lines (112 loc) · 4.52 KB
/
preMeal.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
From 7e707f9ba0b19396c00be0d76af5992c8a59ab80 Mon Sep 17 00:00:00 2001
From: bjorkert <[email protected]>
Date: Sat, 25 Feb 2023 19:58:27 +0100
Subject: [PATCH] preMeal
---
Loop/Managers/LoopDataManager.swift | 81 +++++++++++++++++++++++++++++
1 file changed, 81 insertions(+)
diff --git a/Loop/Managers/LoopDataManager.swift b/Loop/Managers/LoopDataManager.swift
index 00b64996..bafe4052 100644
--- a/Loop/Managers/LoopDataManager.swift
+++ b/Loop/Managers/LoopDataManager.swift
@@ -12,6 +12,19 @@ import HealthKit
import LoopKit
import LoopCore
import WidgetKit
+import CommonCrypto
+
+extension String {
+ func sha1() -> String {
+ let data = Data(self.utf8)
+ var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
+ data.withUnsafeBytes {
+ _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest)
+ }
+ let hexBytes = digest.map { String(format: "%02hhx", $0) }
+ return hexBytes.joined()
+ }
+}
protocol PresetActivationObserver: AnyObject {
func presetActivated(context: TemporaryScheduleOverride.Context, duration: TemporaryScheduleOverride.Duration)
@@ -220,6 +233,73 @@ final class LoopDataManager {
lockedSettings.value
}
+ //Patch for updating nightscout with preMeal info
+ private func preMeal(preMealTargetRange: TemporaryScheduleOverride?) {
+ do { // Silence all errors and return
+ let now = Date()
+
+ let keychain = KeychainManager()
+ let credentials = try keychain.getInternetCredentials(account: "NightscoutAPI")
+
+ let formatter = ISO8601DateFormatter()
+ formatter.timeZone = TimeZone(abbreviation: "UTC")
+ let dateString = formatter.string(from: now)
+
+ let json: [String: Any]
+
+ if let targetRange = preMealTargetRange?.settings.targetRange {
+ json = [
+ "enteredBy": "Loop",
+ "created_at": dateString,
+ "eventType": "Temporary Target",
+ "duration" : 60,
+ "reason" : "Pre-Meal",
+ "targetTop" : targetRange.upperBound.doubleValue(for: .milligramsPerDeciliter),
+ "targetBottom" : targetRange.lowerBound.doubleValue(for: .milligramsPerDeciliter),
+ "secret": credentials.password.sha1()
+ ]
+ } else {
+ json = [
+ "enteredBy": "Loop",
+ "created_at": dateString,
+ "eventType": "Temporary Target",
+ "duration" : 0,
+ "secret": credentials.password.sha1()
+ ]
+ }
+
+ guard var urlComponents = URLComponents(url: credentials.url, resolvingAgainstBaseURL: false) else {return }
+ if urlComponents.path.hasSuffix("/") {
+ urlComponents.path = String(urlComponents.path.dropLast())
+ }
+ urlComponents.path += "/api/v1/treatments.json"
+
+ guard let apiURL = urlComponents.url else { return }
+
+ var request = URLRequest(url: apiURL)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try? JSONSerialization.data(withJSONObject: json)
+
+ let task = URLSession.shared.dataTask(with: request) { data, response, error in
+ if let error = error {
+ // Handle network error
+ print("Error: \(error)")
+ return
+ }
+
+ guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
+ // Handle server error
+ print("Error: Invalid response")
+ return
+ }
+ }
+ task.resume()
+ } catch {
+ return
+ }
+ }
+
func mutateSettings(_ changes: (_ settings: inout LoopSettings) -> Void) {
var oldValue: LoopSettings!
let newValue = lockedSettings.mutate { settings in
@@ -238,6 +318,7 @@ final class LoopDataManager {
if newValue.preMealOverride != oldValue.preMealOverride {
// The prediction isn't actually invalid, but a target range change requires recomputing recommended doses
predictedGlucose = nil
+ preMeal(preMealTargetRange: newValue.preMealOverride)
}
if newValue.scheduleOverride != oldValue.scheduleOverride {
--
2.38.1