Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions LoopFollow/Application/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,13 @@ extension AppDelegate: UNUserNotificationCenterDelegate {
return
}

// Loop's and Trio's replies to remote commands stay in Notification Center to be read later.
// Alarms are handled on screen, and a listed alarm's snooze action would act on the current alarm.
if content.userInfo["command_status"] != nil {
completionHandler([.banner, .list, .sound, .badge])
return
}

completionHandler([.banner, .sound, .badge])
}
}
52 changes: 50 additions & 2 deletions LoopFollow/Controllers/Nightscout/Treatments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,52 @@ extension MainViewController {
return rawDate.flatMap(NightscoutUtils.parseDate)
}

/// The greatest 24-hex-digit `_id` among the entries. Nightscout `_id`s are Mongo ObjectIds, which sort by server insert time
/// (first 8 hex digits, seconds); ids dated more than 5 minutes after `now` are skipped.
static func knownThroughID(_ entries: [[String: AnyObject]], now: Date = Date()) -> String? {
let latest = now.addingTimeInterval(5 * 60).timeIntervalSince1970
return entries
.compactMap { $0["_id"] as? String }
.filter { $0.count == 24 && $0.allSatisfy { $0.isASCII && $0.isHexDigit } }
.filter { UInt32($0.prefix(8), radix: 16).map { TimeInterval($0) <= latest } ?? false }
.map { $0.lowercased() }
.max()
}

/// The Nightscout site and hub a treatments download reads from; the marker is cleared when any of them changes.
struct TreatmentsSite: Equatable {
let url: String
let token: String
let hubURL: String
var hubMode = false
var deviceKey = ""

static var current: TreatmentsSite {
TreatmentsSite(
url: Storage.shared.url.value,
token: Storage.shared.token.value,
hubURL: Storage.shared.hubURL.value,
hubMode: HubClient.shared.isHubMode,
deviceKey: HubClient.shared.deviceKey.value
)
}
}

/// Stores the marker of a download that started at `site`, provided the site is still `current` and treatments are still downloaded.
static func storeKnownThroughID(
_ entries: [[String: AnyObject]],
fetchedFrom site: TreatmentsSite,
current: TreatmentsSite = .current,
downloadsTreatments: Bool = Storage.shared.downloadTreatments.value,
now: Date = Date()
) {
guard site == current, downloadsTreatments else {
LogManager.shared.log(category: .nightscout, message: "Treatments marker skipped: the site or the treatment download changed during the download")
return
}
Observable.shared.treatmentsKnownThroughID.value = knownThroughID(entries, now: now)
}

// NS Treatments Web Call
// Downloads Basal, Bolus, Carbs, BG Check, Notes, Overrides
func WebLoadNSTreatments() {
Expand All @@ -50,12 +96,13 @@ extension MainViewController {
"find[created_at][$lte]": endTimeString,
"count": "\(estimatedCount)",
]
let site = TreatmentsSite.current
NightscoutUtils.executeDynamicRequest(eventType: .treatments, parameters: parameters, hubPart: .treatments) { (result: Result<Any, Error>) in
switch result {
case let .success(data):
if let entries = data as? [[String: AnyObject]] {
DispatchQueue.main.async {
self.updateTreatments(entries: entries)
self.updateTreatments(entries: entries, site: site)
}
} else {
LogManager.shared.log(category: .nightscout, message: "WebLoadNSTreatments, Unexpected data structure")
Expand All @@ -67,7 +114,8 @@ extension MainViewController {
}

// Process and split out treatments to individual tasks
func updateTreatments(entries: [[String: AnyObject]]) {
func updateTreatments(entries: [[String: AnyObject]], site: TreatmentsSite) {
Self.storeKnownThroughID(entries, fetchedFrom: site)
let uniqueEntries = Self.deduplicatedTreatmentEntries(entries)

var tempBasal: [[String: AnyObject]] = []
Expand Down
5 changes: 4 additions & 1 deletion LoopFollow/Remote/LoopAPNS/LoopAPNSBolusView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ struct LoopAPNSBolusView: View {
@State private var otpTimeRemaining: Int? = nil
@State private var showOldCalculationWarning = false
@State private var showTOTPWarning = false
/// The treatments marker as the user sees it on this screen.
@State private var origin = RemoteCommandOrigin.phoneScreenAppeared()
private let otpPeriod: TimeInterval = 30
private var otpTimer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

Expand Down Expand Up @@ -202,6 +204,7 @@ struct LoopAPNSBolusView: View {
.navigationBarTitleDisplayMode(.inline)
}

.remoteCommandOrigin($origin)
.onAppear {
// Validate APNS setup
let apnsService = LoopAPNSService()
Expand Down Expand Up @@ -400,7 +403,7 @@ struct LoopAPNSBolusView: View {
)

let apnsService = LoopAPNSService()
apnsService.sendBolusViaAPNS(payload: payload) { success, errorMessage in
apnsService.sendBolusViaAPNS(payload: payload, origin: origin) { success, errorMessage in
DispatchQueue.main.async {
self.isLoading = false
if success {
Expand Down
5 changes: 4 additions & 1 deletion LoopFollow/Remote/LoopAPNS/LoopAPNSCarbsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ struct LoopAPNSCarbsView: View {
@State private var alertType: AlertType = .success
@State private var otpTimeRemaining: Int? = nil
@State private var showTOTPWarning = false
/// The treatments marker as the user sees it on this screen.
@State private var origin = RemoteCommandOrigin.phoneScreenAppeared()
private let otpPeriod: TimeInterval = 30
private let timeAdjustmentStepMinutes = 5
private let maxPastHours = 12
Expand Down Expand Up @@ -405,6 +407,7 @@ struct LoopAPNSCarbsView: View {
normalizeAbsorptionTime()
}
}
.remoteCommandOrigin($origin)
.onAppear {
// Validate APNS setup
let apnsService = LoopAPNSService()
Expand Down Expand Up @@ -565,7 +568,7 @@ struct LoopAPNSCarbsView: View {
)

let apnsService = LoopAPNSService()
apnsService.sendCarbsViaAPNS(payload: payload) { success, errorMessage in
apnsService.sendCarbsViaAPNS(payload: payload, origin: origin) { success, errorMessage in
DispatchQueue.main.async {
self.isLoading = false
if success {
Expand Down
8 changes: 4 additions & 4 deletions LoopFollow/Remote/LoopAPNS/LoopAPNSService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ class LoopAPNSService {
/// - Parameters:
/// - payload: The carbs payload to send
/// - completion: Completion handler with success status and error message
func sendCarbsViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
var finalPayload = LoopAPNSCommands.carbsCommandPayload(payload)
func sendCarbsViaAPNS(payload: LoopAPNSPayload, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) {
var finalPayload = LoopAPNSCommands.carbsCommandPayload(payload, knownThroughID: origin.knownThroughID)
if let encryptedReturnInfo = encryptedReturnNotification(otp: payload.otp) {
finalPayload["encrypted_return_notification"] = encryptedReturnInfo
}
Expand All @@ -251,8 +251,8 @@ class LoopAPNSService {
/// - Parameters:
/// - payload: The bolus payload to send
/// - completion: Completion handler with success status and error message
func sendBolusViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
var finalPayload = LoopAPNSCommands.bolusCommandPayload(payload)
func sendBolusViaAPNS(payload: LoopAPNSPayload, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) {
var finalPayload = LoopAPNSCommands.bolusCommandPayload(payload, knownThroughID: origin.knownThroughID)
if let encryptedReturnInfo = encryptedReturnNotification(otp: payload.otp) {
finalPayload["encrypted_return_notification"] = encryptedReturnInfo
}
Expand Down
66 changes: 66 additions & 0 deletions LoopFollow/Remote/RemoteCommandOrigin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// LoopFollow
// RemoteCommandOrigin.swift

import Foundation
import SwiftUI
import UIKit

/// Where a bolus or carb command was entered.
enum RemoteCommandOrigin: Equatable {
/// Entered on a command screen of the phone; `screenOpenedWith` is the treatments marker when that screen appeared,
/// read from `site`.
case phone(screenOpenedWith: String?, site: MainViewController.TreatmentsSite)
/// Relayed from Apple Watch, which may show older data than the phone.
case watch

/// A phone command screen that is appearing now: it keeps the treatments marker the user sees while deciding.
static func phoneScreenAppeared() -> RemoteCommandOrigin {
.phone(screenOpenedWith: Observable.shared.treatmentsKnownThroughID.value, site: .current)
}

/// The treatments marker the command carries.
var knownThroughID: String? {
knownThroughID(current: Observable.shared.treatmentsKnownThroughID.value, currentSite: .current)
}

/// The older of the marker when the screen appeared and `current`, or whichever of them exists. The marker from
/// when the screen appeared counts only while its site is `currentSite`. Watch commands carry none.
func knownThroughID(current: String?, currentSite: MainViewController.TreatmentsSite) -> String? {
switch self {
case let .phone(screenOpenedWith, site):
let opened = site == currentSite ? screenOpenedWith : nil
return [opened, current].compactMap { $0 }.min()
case .watch:
return nil
}
}
}

extension View {
/// Keeps `origin` at the treatments marker the user sees on this phone command screen: the marker when the screen
/// appears, and after a return to the foreground the marker of the first treatments download that follows.
func remoteCommandOrigin(_ origin: Binding<RemoteCommandOrigin>) -> some View {
modifier(RemoteCommandOriginTracker(origin: origin))
}
}

private struct RemoteCommandOriginTracker: ViewModifier {
@Binding var origin: RemoteCommandOrigin
@State private var awaitsDownload = false

func body(content: Content) -> some View {
content
.onAppear {
origin = .phoneScreenAppeared()
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
origin = .phoneScreenAppeared()
awaitsDownload = true
}
.onReceive(Observable.shared.treatmentsKnownThroughID.$value.dropFirst()) { marker in
guard awaitsDownload, let marker else { return }
origin = .phone(screenOpenedWith: marker, site: .current)
awaitsDownload = false
}
}
}
5 changes: 4 additions & 1 deletion LoopFollow/Remote/TRC/BolusView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ struct BolusView: View {
@State private var alertMessage: String? = nil
@State private var isLoading = false
@State private var statusMessage: String? = nil
/// The treatments marker as the user sees it on this screen.
@State private var origin = RemoteCommandOrigin.phoneScreenAppeared()

private let pushNotificationManager = PushNotificationManager()

Expand Down Expand Up @@ -141,6 +143,7 @@ struct BolusView: View {
.navigationTitle("Bolus")
.navigationBarTitleDisplayMode(.inline)
}
.remoteCommandOrigin($origin)
.onAppear {
quickPickBoluses.refresh(
stepIncrement: stepU,
Expand Down Expand Up @@ -312,7 +315,7 @@ struct BolusView: View {

private func sendBolus() {
isLoading = true
pushNotificationManager.sendBolusPushNotification(bolusAmount: bolusAmount) { success, errorMessage in
pushNotificationManager.sendBolusPushNotification(bolusAmount: bolusAmount, origin: origin) { success, errorMessage in
DispatchQueue.main.async {
isLoading = false
if success {
Expand Down
6 changes: 5 additions & 1 deletion LoopFollow/Remote/TRC/MealView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ struct MealView: View {
@State private var selectedTime: Date? = nil
@State private var isScheduling: Bool = false
@State private var showFatProteinOrderBanner = false
/// The treatments marker as the user sees it on this screen.
@State private var origin = RemoteCommandOrigin.phoneScreenAppeared()

enum AlertType {
case confirmMeal
Expand Down Expand Up @@ -187,6 +189,7 @@ struct MealView: View {
.navigationTitle("Meal")
.navigationBarTitleDisplayMode(.inline)
}
.remoteCommandOrigin($origin)
.onAppear {
selectedTime = nil
isScheduling = false
Expand Down Expand Up @@ -318,7 +321,8 @@ struct MealView: View {
protein: protein,
fat: fat,
bolusAmount: bolusAmount,
scheduledTime: scheduledDate
scheduledTime: scheduledDate,
origin: origin
) { success, errorMessage in
DispatchQueue.main.async {
isLoading = false
Expand Down
61 changes: 54 additions & 7 deletions LoopFollow/Remote/TRC/PushNotificationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,12 @@ class PushNotificationManager {
sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following(.override, completion))
}

func sendBolusPushNotification(bolusAmount: HKQuantity, completion: @escaping (Bool, String?) -> Void) {
func sendBolusPushNotification(bolusAmount: HKQuantity, origin: RemoteCommandOrigin, completion: @escaping (Bool, String?) -> Void) {
let bolusAmountDecimal = Decimal(bolusAmount.doubleValue(for: .internationalUnit()))
let payload = CommandPayload(
let payload = Self.bolusPayload(
user: user,
commandType: .bolus,
timestamp: Date().timeIntervalSince1970,
bolusAmount: bolusAmountDecimal,
knownThroughID: origin.knownThroughID,
returnNotification: ReturnNotificationInfo.loopFollow()
)
sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following(.bolus(units: bolusAmount.doubleValue(for: .internationalUnit())), completion))
Expand Down Expand Up @@ -96,6 +95,7 @@ class PushNotificationManager {
fat: HKQuantity,
bolusAmount: HKQuantity,
scheduledTime: Date?,
origin: RemoteCommandOrigin,
completion: @escaping (Bool, String?) -> Void
) {
func convertToOptionalInt(_ quantity: HKQuantity) -> Int? {
Expand All @@ -116,15 +116,14 @@ class PushNotificationManager {
completion(false, "No nutrient data provided. At least one of carbs, fat, or protein must be greater than 0.")
return
}
let payload = CommandPayload(
let payload = Self.mealPayload(
user: user,
commandType: .meal,
timestamp: Date().timeIntervalSince1970,
bolusAmount: bolusAmountValue,
carbs: carbsValue,
protein: proteinValue,
fat: fatValue,
scheduledTime: scheduledTimeInterval,
knownThroughID: origin.knownThroughID,
returnNotification: ReturnNotificationInfo.loopFollow()
)
sendEncryptedCommand(payload: payload, completion: RemoteCommandRefresh.following(
Expand All @@ -133,6 +132,54 @@ class PushNotificationManager {
))
}

/// A bolus command with a command id of its own, so Trio enacts it at most once.
static func bolusPayload(
user: String,
bolusAmount: Decimal,
knownThroughID: String?,
returnNotification: ReturnNotificationInfo?,
now: Date = Date(),
commandID: String = UUID().uuidString
) -> CommandPayload {
CommandPayload(
user: user,
commandType: .bolus,
timestamp: now.timeIntervalSince1970,
bolusAmount: bolusAmount,
commandID: commandID,
knownThroughID: knownThroughID,
returnNotification: returnNotification
)
}

/// A meal command with a command id of its own, so Trio enacts it at most once.
static func mealPayload(
user: String,
bolusAmount: Decimal?,
carbs: Int?,
protein: Int?,
fat: Int?,
scheduledTime: TimeInterval?,
knownThroughID: String?,
returnNotification: ReturnNotificationInfo?,
now: Date = Date(),
commandID: String = UUID().uuidString
) -> CommandPayload {
CommandPayload(
user: user,
commandType: .meal,
timestamp: now.timeIntervalSince1970,
bolusAmount: bolusAmount,
carbs: carbs,
protein: protein,
fat: fat,
scheduledTime: scheduledTime,
commandID: commandID,
knownThroughID: knownThroughID,
returnNotification: returnNotification
)
}

/// Trio confirms edit/delete through a return notification, so LoopFollow's own APNs credentials are required.
func sendDeleteMealPushNotification(mealID: String, commandID: String, completion: @escaping (Bool, String?) -> Void) {
guard let returnNotification = ReturnNotificationInfo.loopFollow() else {
Expand Down
3 changes: 3 additions & 0 deletions LoopFollow/Storage/Observable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ class Observable {

var lastSentTOTP = ObservableValue<String?>(default: nil)

/// Greatest Nightscout `_id` in the latest treatments download; nil until one has loaded.
var treatmentsKnownThroughID = ObservableValue<String?>(default: nil)

var loopFollowDeviceToken = ObservableValue<String>(default: "")

/// Saved profiles from the latest Loop or Trio profile upload; nil until one is loaded.
Expand Down
Loading