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
2 changes: 1 addition & 1 deletion LoopFollow/Remote/Profiles/ProfileEditLimits.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ struct ProfileEditLimits: Decodable, Equatable {

/// The most segments a schedule may have: the published maximum, never more than one per segment slot.
var segmentLimit: Int {
min(maxSegments, 86400 / segmentSeconds)
segmentSeconds > 0 ? min(maxSegments, 86400 / segmentSeconds) : 0
}

/// The most segments a schedule of `kind` may have; basal also stays within the pump's entry limit.
Expand Down
9 changes: 7 additions & 2 deletions LoopFollow/Remote/Profiles/ProfileEditorSheet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,14 @@ struct ProfileEditorSheet: View {
?? ProfileValidation.nameProblem(name, existingNames: profileSet.profiles.map(\.name))
}

/// The schedules the draft changes; every schedule for a new profile.
private var changedSchedules: Set<ProfileScheduleKind> {
isNew ? Set(ProfileScheduleKind.allCases) : ProfileValidation.changedSchedules(from: source.values, to: draft.values, singleTarget: remote.hasSingleTarget)
}

private var problems: [String] {
guard let limits = editableLimits else { return [] }
return ProfileValidation.problems(draft.values, limits: limits)
return ProfileValidation.problems(draft.values, limits: limits, schedules: changedSchedules)
}

private var hasChanges: Bool {
Expand Down Expand Up @@ -150,7 +155,7 @@ struct ProfileEditorSheet: View {
}

ForEach(ProfileScheduleKind.allCases) { kind in
ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget)
ProfileValuesEditor(kind: kind, segments: Binding(get: { draft[kind] }, set: { draft[kind] = $0 }), units: draft.units, limits: editableLimits, singleTarget: remote.hasSingleTarget, isUnchanged: !changedSchedules.contains(kind), isActiveProfile: isEditingActive)
}

if !problems.isEmpty {
Expand Down
6 changes: 5 additions & 1 deletion LoopFollow/Remote/Profiles/ProfileReviewView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ struct ProfileReviewView: View {

private var problems: [String] {
guard let limits else { return ["Profiles can not be changed without the limits from \(remote.appName)."] }
return ProfileValidation.problems(for: command, limits: limits)
return ProfileValidation.problems(for: command, limits: limits, singleTarget: remote.hasSingleTarget)
}

private static func computePushSize(_ command: ProfileCommand, remote: ProfileRemote) -> Int? {
Expand Down Expand Up @@ -108,6 +108,10 @@ struct ProfileReviewView: View {
if appliesNow {
ActiveProfileWarning(remote: remote)
}
if !ProfileValidation.unchangedProblems(for: command, limits: limits, singleTarget: remote.hasSingleTarget).isEmpty {
Label("Schedules this change leaves alone stay outside the limits \(remote.appName) shared, so \(remote.appName) would refuse to activate this profile until they are changed too.", systemImage: "exclamationmark.triangle")
.foregroundColor(.orange)
}
if !increases.isEmpty {
MoreInsulinWarning(
increases: increases,
Expand Down
72 changes: 55 additions & 17 deletions LoopFollow/Remote/Profiles/ProfileValidation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,42 +128,80 @@ enum ProfileValidation {
return nil
}

/// Everything that keeps `values` from being sent within `limits`. Empty when the profile can be sent.
static func problems(_ values: TherapyProfileValues, limits: ProfileEditLimits) -> [String] {
/// Everything that keeps the `schedules` of `values` from being sent within `limits`. Empty when they can be sent.
static func problems(
_ values: TherapyProfileValues,
limits: ProfileEditLimits,
schedules: Set<ProfileScheduleKind> = Set(ProfileScheduleKind.allCases)
) -> [String] {
var problems: [String] = []
if values.units != limits.normalizedUnits {
problems.append("The profile is in \(values.units), but the limits are in \(limits.normalizedUnits).")
}
let schedules: [(ProfileScheduleKind, [Int])] = [
let starts: [(ProfileScheduleKind, [Int])] = [
(.correctionRange, values.target.map(\.seconds)),
(.carbRatio, values.carbRatio.map(\.seconds)),
(.basal, values.basal.map(\.seconds)),
(.sensitivity, values.sensitivity.map(\.seconds)),
]
for (kind, starts) in schedules {
for (kind, starts) in starts where schedules.contains(kind) {
problems += scheduleProblems(starts, kind: kind, limits: limits)
}
for (kind, items) in [(ProfileScheduleKind.carbRatio, values.carbRatio), (.basal, values.basal), (.sensitivity, values.sensitivity)] {
for (kind, items) in [(ProfileScheduleKind.carbRatio, values.carbRatio), (.basal, values.basal), (.sensitivity, values.sensitivity)] where schedules.contains(kind) {
if items.contains(where: { limits.status(of: $0.value, in: kind) == .notAllowed }) {
problems.append("\(kind.title): a value is outside what is allowed. \(limits.boundsText(for: kind))")
}
}
if values.target.contains(where: { limits.status(of: $0.low, in: .correctionRange) == .notAllowed || limits.status(of: $0.high, in: .correctionRange) == .notAllowed }) {
problems.append("Correction Range: a value is outside what is allowed. \(limits.boundsText(for: .correctionRange))")
}
if values.target.contains(where: { $0.low > $0.high + ProfileEditLimits.tolerance }) {
problems.append("Correction Range: the low value must not be above the high value.")
if schedules.contains(.correctionRange) {
if values.target.contains(where: { limits.status(of: $0.low, in: .correctionRange) == .notAllowed || limits.status(of: $0.high, in: .correctionRange) == .notAllowed }) {
problems.append("Correction Range: a value is outside what is allowed. \(limits.boundsText(for: .correctionRange))")
}
if values.target.contains(where: { $0.low > $0.high + ProfileEditLimits.tolerance }) {
problems.append("Correction Range: the low value must not be above the high value.")
}
}
return problems
}

/// Everything that keeps `command` from being sent within `limits`. A save that keeps the values of the
/// profile it updates (a pure rename) is not checked against the limits, which may have changed since the
/// values were stored.
static func problems(for command: ProfileCommand, limits: ProfileEditLimits) -> [String] {
/// The schedules of `values` that differ from `original`. With `singleTarget`, a correction range also counts as
/// unchanged when it matches `original` with each high value set to its low value, as the editor shows it.
static func changedSchedules(from original: TherapyProfileValues, to values: TherapyProfileValues, singleTarget: Bool = false) -> Set<ProfileScheduleKind> {
var changed = Set<ProfileScheduleKind>()
if values.basal != original.basal { changed.insert(.basal) }
if values.carbRatio != original.carbRatio { changed.insert(.carbRatio) }
if values.sensitivity != original.sensitivity { changed.insert(.sensitivity) }
let editorTarget = ProfileDraft(original, singleTarget: singleTarget).values.target
if values.target != original.target, values.target != editorTarget { changed.insert(.correctionRange) }
return changed
}

/// Everything that keeps `command` from being sent within `limits`. A save of an existing profile is checked only
/// in the schedules it changes, as Loop and Trio check it, so a schedule that no longer fits the limits does not
/// keep the others from being corrected. A pure rename is not checked against the limits.
static func problems(for command: ProfileCommand, limits: ProfileEditLimits, singleTarget: Bool = false) -> [String] {
guard case let .save(_, original, values) = command else { return [] }
if let original, original.values == values { return [] }
return problems(values, limits: limits)
guard let original else { return problems(values, limits: limits) }
let changed = changedSchedules(from: original.values, to: values, singleTarget: singleTarget)
if changed.isEmpty { return [] }
return problems(values, limits: limits, schedules: changed)
}

/// Why Loop or Trio would refuse to activate `profile` under `limits`, or empty when nothing in the limits stands in
/// the way. Empty when the limits are not usable, the profile could not be read completely, or the two are in
/// different units, since the profile can't be judged then.
static func activationProblems(_ profile: TherapyProfile, limits: ProfileEditLimits?) -> [String] {
guard let limits, limits.isUsable, profile.isWellFormed, profile.values.units == limits.normalizedUnits else { return [] }
return problems(profile.values, limits: limits)
}

/// The problems of the schedules a save of an existing profile leaves unchanged; they stay stored as they are.
static func unchangedProblems(for command: ProfileCommand, limits: ProfileEditLimits?, singleTarget: Bool = false) -> [String] {
guard case let .save(_, original?, values) = command, let limits, limits.isUsable, original.isWellFormed,
values.units == limits.normalizedUnits
else { return [] }
let unchanged = Set(ProfileScheduleKind.allCases).subtracting(changedSchedules(from: original.values, to: values, singleTarget: singleTarget))
if unchanged.isEmpty { return [] }
return problems(values, limits: limits, schedules: unchanged)
}

static func scheduleProblems(_ starts: [Int], kind: ProfileScheduleKind, limits: ProfileEditLimits) -> [String] {
Expand All @@ -173,7 +211,7 @@ enum ProfileValidation {
if zip(starts, starts.dropFirst()).contains(where: { $0 >= $1 }) {
problems.append("\(kind.title): each time must be later than the one before.")
}
if starts.contains(where: { $0 < 0 || $0 >= 86400 || $0 % limits.segmentSeconds != 0 }) {
if starts.contains(where: { $0 < 0 || $0 >= 86400 || limits.segmentSeconds <= 0 || $0 % limits.segmentSeconds != 0 }) {
problems.append("\(kind.title): times must be on the \(limits.segmentSeconds / 60)-minute grid.")
}
let segmentLimit = limits.segmentLimit(for: kind)
Expand Down
11 changes: 10 additions & 1 deletion LoopFollow/Remote/Profiles/ProfileValuesEditor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ struct ProfileValuesEditor: View {
let limits: ProfileEditLimits?
/// One target value per time, for Trio.
var singleTarget = false
/// True while the schedule keeps the values of the stored profile, which may be saved unchanged although they
/// no longer fit the limits.
var isUnchanged = false
/// True when the schedule belongs to the active profile.
var isActiveProfile = false

private var isRange: Bool { kind.isRange && !singleTarget }

Expand Down Expand Up @@ -121,7 +126,11 @@ struct ProfileValuesEditor: View {
}
switch status {
case .notAllowed:
Text("Outside what is allowed. Change this value before sending.")
Text(!isUnchanged
? "Outside what is allowed. Change this value before sending."
: isActiveProfile
? "Outside what is allowed now. Once another profile is activated, this one can't be activated again until this value is changed."
: "Outside what is allowed now. The profile can't be activated until this value is changed.")
.font(.caption)
.foregroundColor(.red)
case .outsideRecommended:
Expand Down
40 changes: 40 additions & 0 deletions LoopFollow/Remote/Profiles/TherapyProfilesView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ struct TherapyProfilesView: View {
HStack {
Text(profile.name)
Spacer()
if !ProfileValidation.activationProblems(profile, limits: profileSet.limits).isEmpty {
Text("Outside Limits")
.font(.caption)
.foregroundColor(.orange)
}
if profileSet.isActive(profile) {
Text("Active")
.font(.caption)
Expand Down Expand Up @@ -187,6 +192,26 @@ struct TherapyProfilePreviewView: View {
return increases.isEmpty ? nil : (active, increases)
}

/// Why the app would refuse to activate this profile under the limits it shared.
private var activationProblems: [String] {
guard let profile else { return [] }
return ProfileValidation.activationProblems(profile, limits: profileSet?.limits)
}

/// The note for the activation confirmation: the target is outside the limits, or the active profile itself no
/// longer fits them.
private var activationLimitsText: String? {
if !activationProblems.isEmpty {
return "This profile is outside the limits \(remote.appName) shared, so \(remote.appName) will likely refuse it."
}
guard !isActive, let active = profileSet?.activeProfile,
!ProfileValidation.activationProblems(active, limits: profileSet?.limits).isEmpty
else { return nil }
let blocked = ProfileEditing.blocker(for: active, limits: profileSet?.limits, remote: remote) != nil
return "\(active.name) no longer fits the limits \(remote.appName) shared, so \(remote.appName) would refuse to activate it again"
+ (blocked ? "." : " until it is edited.")
}

private var activateKey: String { remote.key(.activate, name: name) }
private var deleteKey: String { remote.key(.delete, name: name) }

Expand Down Expand Up @@ -241,6 +266,20 @@ struct TherapyProfilePreviewView: View {
List {
Section(footer: Text("\(remote.appName) writes the basal rates to the pump when the profile is activated.")) {
Text(isActive ? "This is the active profile. \(remote.appName) doses insulin with these values." : "Review the profile before activating it in \(remote.appName).")
if !activationProblems.isEmpty {
VStack(alignment: .leading, spacing: 4) {
Label(isActive
? "This profile no longer fits the limits \(remote.appName) shared. It stays active, but once another profile is activated, \(remote.appName) would refuse to activate it again" + (editBlocker == nil ? " until it is edited." : ".")
: "\(remote.appName) would refuse to activate this profile under the limits it shared." + (editBlocker == nil ? " Edit it to fit them first." : ""),
systemImage: "exclamationmark.triangle")
.foregroundColor(.orange)
ForEach(activationProblems, id: \.self) { problem in
Text(problem)
.font(.footnote)
.foregroundColor(.secondary)
}
}
}
if let activationIncreases {
MoreInsulinWarning(
increases: activationIncreases.increases,
Expand Down Expand Up @@ -336,6 +375,7 @@ struct TherapyProfilePreviewView: View {
title: Text("Activate \(name) in \(remote.appName)?"),
message: Text("\(remote.appName) replaces its correction range, carb ratios, basal rates and insulin sensitivities with these values and writes the basal rates to the pump. Dosing changes right away."
+ (profileSet.flatMap { ScheduledSwitches.holdText($0.scheduledSwitches) }.map { " " + $0 } ?? "")
+ (activationLimitsText.map { " " + $0 } ?? "")
+ MoreInsulinWarning.sentence(activationIncreases?.increases ?? [], comparedWith: activationIncreases?.active.name ?? "")),
primaryButton: .default(Text("Activate")) { send(.activate, fingerprint: fingerprint) },
secondaryButton: .cancel()
Expand Down
Loading
Loading