Skip to content
Merged
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
30 changes: 25 additions & 5 deletions G7SensorKit/G7CGMManager/G7CGMManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -529,10 +529,19 @@ public class G7CGMManager: CGMManager {
}

public func scanForNewSensor() {
forgetSensor(reason: .replaced)
}

private func forgetSensor(reason: G7SensorRecord.EndReason) {
cancelSuspectedSessionEndScan()
retractAllLifecycleAlerts()
if reason == .failed {
// The failure alert stays up until a new sensor is adopted.
G7LifecycleAlert.allCases.filter { $0 != .sensorFailed }.forEach(retractLifecycleAlert)
} else {
retractAllLifecycleAlerts()
}
recordSensorEndIfNeeded()
archiveCurrentSensor(reason: .replaced)
archiveCurrentSensor(reason: reason)

logDeviceCommunication("Forgetting existing sensor and starting scan for new sensor.", type: .connection)

Expand All @@ -547,7 +556,6 @@ public class G7CGMManager: CGMManager {
state.sharedKey = nil
state.peripheralIdentifier = nil
state.lifecycleAlertsScheduledFor = nil
state.sensorFailedAlertIssuedFor = nil
state.sensorEndRecordedFor = nil
state.pairedAt = nil
state.sensorFailureMessage = nil
Expand Down Expand Up @@ -819,8 +827,20 @@ extension G7CGMManager {

extension G7CGMManager: G7SensorDelegate {
public func sensor(_ sensor: G7Sensor, didDiscoverNewSensor name: String, activatedAt: Date, peripheralIdentifier: UUID) -> Bool {
// A failed or ended sensor keeps advertising, and the scan for its replacement finds it again.
if let previous = state.previousSensor, previous.endReason.isFinal, previous.sensorID == name,
let previousActivation = previous.activatedAt, abs(previousActivation.timeIntervalSince(activatedAt)) < .minutes(1) {
logDeviceCommunication("Ignoring \(name): its session already ended (\(previous.endReason.rawValue))", type: .connection)
return false
}

logDeviceCommunication("New sensor \(name) discovered, activated at \(activatedAt)", type: .connection)

if let failedSensor = state.sensorFailedAlertIssuedFor, failedSensor != name {
retractLifecycleAlert(.sensorFailed)
mutateState { $0.sensorFailedAlertIssuedFor = nil }
}

let shouldSwitchToNewSensor = true
// While eavesdropping, a held code was for another controller, and it belonged to the sensor
// just replaced: it goes, and the user is asked for the new one while it is in hand.
Expand Down Expand Up @@ -1261,12 +1281,12 @@ extension G7CGMManager: G7SensorDelegate {

if message.algorithmState.sensorFailed {
logDeviceCommunication("Detected failed sensor... scanning for new sensor.", type: .receive)
scanForNewSensor()
forgetSensor(reason: .failed)
}

if message.algorithmState == .known(.sessionEnded) {
logDeviceCommunication("Detected session ended... scanning for new sensor.", type: .receive)
scanForNewSensor()
forgetSensor(reason: .sessionEnded)
}


Expand Down
7 changes: 7 additions & 0 deletions G7SensorKit/G7CGMManager/G7SensorRecord.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ public struct G7SensorRecord: RawRepresentable, Equatable {
public enum EndReason: String {
case replaced
case deleted
case failed
case sessionEnded

/// The sensor can't be used again, so finding it in a later scan isn't a reason to adopt it.
public var isFinal: Bool {
self == .failed || self == .sessionEnded
}
}

public var model: G7SensorModel? {
Expand Down
63 changes: 63 additions & 0 deletions G7SensorKitTests/G7LifecycleAlertTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -363,4 +363,67 @@ class G7LifecycleAlertManagerTests: XCTestCase {

XCTAssertEqual(recorder.cgmEvents.map(\.type), [.sensorStart, .sensorEnd])
}

private func sensorFailedAlerts() -> Int {
recorder.issued.filter { $0.identifier.alertIdentifier == G7LifecycleAlert.sensorFailed.rawValue }.count
}

func testAFailedSensorFoundAgainIsNotAdopted() {
let manager = sensorIssueManager()
let activatedAt = manager.state.activatedAt!
manager.sensor(manager.sensor, didRead: reading(state: 25, minutes: 1))
settle()

XCTAssertEqual(sensorFailedAlerts(), 1)
XCTAssertFalse(recorder.retracted.contains { $0.alertIdentifier == G7LifecycleAlert.sensorFailed.rawValue },
"the failure alert stays up until a new sensor is adopted")
XCTAssertEqual(manager.state.previousSensor?.endReason, .failed)
XCTAssertNotNil(manager.state.previousSensor?.failureMessage)
let eventCount = recorder.cgmEvents.count

// The scan for a replacement finds the failed sensor again, every reading.
for _ in 0..<3 {
XCTAssertFalse(manager.sensor(manager.sensor, didDiscoverNewSensor: "DXCM99", activatedAt: activatedAt.addingTimeInterval(1), peripheralIdentifier: UUID()))
}
settle()

XCTAssertEqual(sensorFailedAlerts(), 1)
XCTAssertNil(manager.state.sensorID)
XCTAssertEqual(manager.state.previousSensor?.endReason, .failed)
XCTAssertEqual(recorder.cgmEvents.count, eventCount, "no sensor start or end for the failed sensor")
}

func testANewSensorRetractsTheFailureAlert() {
let manager = sensorIssueManager()
manager.sensor(manager.sensor, didRead: reading(state: 25, minutes: 1))
settle()

XCTAssertTrue(manager.sensor(manager.sensor, didDiscoverNewSensor: "DXCM98", activatedAt: Date(), peripheralIdentifier: UUID()))
settle()

XCTAssertTrue(recorder.retracted.contains { $0.alertIdentifier == G7LifecycleAlert.sensorFailed.rawValue })
XCTAssertEqual(manager.state.sensorID, "DXCM98")
XCTAssertNil(manager.state.sensorFailedAlertIssuedFor)
}

func testASensorWhoseSessionEndedIsNotAdoptedAgain() {
let manager = sensorIssueManager()
let activatedAt = manager.state.activatedAt!
manager.sensor(manager.sensor, didRead: reading(state: 26, minutes: 1))
settle()

XCTAssertEqual(manager.state.previousSensor?.endReason, .sessionEnded)
XCTAssertFalse(manager.sensor(manager.sensor, didDiscoverNewSensor: "DXCM99", activatedAt: activatedAt, peripheralIdentifier: UUID()))
XCTAssertNil(manager.state.sensorID)
}

func testAReplacedSensorCanBeAdoptedAgain() {
let manager = sensorIssueManager()
let activatedAt = manager.state.activatedAt!
manager.scanForNewSensor()
settle()

XCTAssertTrue(manager.sensor(manager.sensor, didDiscoverNewSensor: "DXCM99", activatedAt: activatedAt, peripheralIdentifier: UUID()))
XCTAssertEqual(manager.state.sensorID, "DXCM99")
}
}
4 changes: 4 additions & 0 deletions G7SensorKitUI/Views/G7PreviousSensorView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ struct G7PreviousSensorView: View {
return LocalizedString("Replaced", comment: "Row label for when the previous sensor was replaced")
case .deleted:
return LocalizedString("Removed", comment: "Row label for when the previous sensor's CGM was deleted")
case .failed:
return LocalizedString("Failed", comment: "Row label for when the previous sensor failed")
case .sessionEnded:
return LocalizedString("Session Ended", comment: "Row label for when the previous sensor's session ended")
}
}
}