|
|
@@ -86,6 +86,63 @@ final class BaseGlucoseStorage: GlucoseStorage, Injectable {
|
|
|
} catch {
|
|
|
debugPrint("Glucose Storage: failed to save glucose to core data: \(error)")
|
|
|
}
|
|
|
+
|
|
|
+ debug(.deviceManager, "start storage cgmState")
|
|
|
+ self.storage.transaction { storage in
|
|
|
+ let file = OpenAPS.Monitor.cgmState
|
|
|
+ var treatments = storage.retrieve(file, as: [NigtscoutTreatment].self) ?? []
|
|
|
+ var updated = false
|
|
|
+ for x in glucose {
|
|
|
+ debug(.deviceManager, "storeGlucose \(x)")
|
|
|
+ guard let sessionStartDate = x.sessionStartDate else {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ if let lastTreatment = treatments.last,
|
|
|
+ let createdAt = lastTreatment.createdAt,
|
|
|
+ // When a new Dexcom sensor is started, it produces multiple consequetive
|
|
|
+ // startDates. Disambiguate them by only allowing a session start per minute.
|
|
|
+ abs(createdAt.timeIntervalSince(sessionStartDate)) < TimeInterval(60)
|
|
|
+ {
|
|
|
+ continue
|
|
|
+ }
|
|
|
+ var notes = ""
|
|
|
+ if let t = x.transmitterID {
|
|
|
+ notes = t
|
|
|
+ }
|
|
|
+ if let a = x.activationDate {
|
|
|
+ notes = "\(notes) activated on \(a)"
|
|
|
+ }
|
|
|
+ let treatment = NigtscoutTreatment(
|
|
|
+ duration: nil,
|
|
|
+ rawDuration: nil,
|
|
|
+ rawRate: nil,
|
|
|
+ absolute: nil,
|
|
|
+ rate: nil,
|
|
|
+ eventType: .nsSensorChange,
|
|
|
+ createdAt: sessionStartDate,
|
|
|
+ enteredBy: NigtscoutTreatment.local,
|
|
|
+ bolus: nil,
|
|
|
+ insulin: nil,
|
|
|
+ notes: notes,
|
|
|
+ carbs: nil,
|
|
|
+ fat: nil,
|
|
|
+ protein: nil,
|
|
|
+ targetTop: nil,
|
|
|
+ targetBottom: nil
|
|
|
+ )
|
|
|
+ debug(.deviceManager, "CGM sensor change \(treatment)")
|
|
|
+ treatments.append(treatment)
|
|
|
+ updated = true
|
|
|
+ }
|
|
|
+ if updated {
|
|
|
+ // We have to keep quite a bit of history as sensors start only every 10 days.
|
|
|
+ storage.save(
|
|
|
+ treatments.filter
|
|
|
+ { $0.createdAt != nil && $0.createdAt!.addingTimeInterval(30.days.timeInterval) > Date() },
|
|
|
+ as: file
|
|
|
+ )
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
}
|
|
|
}
|