Skip to content

Commit 055f81a

Browse files
committed
Merge branch 'scanning-fix' into update_for_pr34
2 parents 425a6b0 + b0d424d commit 055f81a

File tree

7 files changed

+74
-36
lines changed

7 files changed

+74
-36
lines changed

G7SensorKit/AlgorithmError.swift

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,14 @@ extension AlgorithmState {
3737
return LocalizedString("Sensor is OK", comment: "The description of sensor algorithm state when sensor is ok.")
3838
case .stopped:
3939
return LocalizedString("Sensor is stopped", comment: "The description of sensor algorithm state when sensor is stopped.")
40-
case .warmup, .questionMarks:
40+
case .warmup, .temporarySensorIssue:
4141
return LocalizedString("Sensor is warming up", comment: "The description of sensor algorithm state when sensor is warming up.")
4242
case .expired:
4343
return LocalizedString("Sensor expired", comment: "The description of sensor algorithm state when sensor is expired.")
4444
case .sensorFailed:
4545
return LocalizedString("Sensor failed", comment: "The description of sensor algorithm state when sensor failed.")
46+
default:
47+
return "Sensor state: \(String(describing: state))"
4648
}
4749
case .unknown(let rawValue):
4850
return String(format: LocalizedString("Sensor is in unknown state %1$d", comment: "The description of sensor algorithm state when raw value is unknown. (1: missing data details)"), rawValue)

G7SensorKit/AlgorithmState.swift

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,29 @@ public enum AlgorithmState: RawRepresentable {
1515
public enum State: RawValue {
1616
case stopped = 1
1717
case warmup = 2
18+
case excessNoise = 3
19+
case firstOfTwoBGsNeeded = 4
20+
case secondOfTwoBGsNeeded = 5
1821
case ok = 6
19-
case questionMarks = 18
22+
case needsCalibration = 7
23+
case calibrationError1 = 8
24+
case calibrationError2 = 9
25+
case calibrationLinearityFitFailure = 10
26+
case sensorFailedDuetoCountsAberration = 11
27+
case sensorFailedDuetoResidualAberration = 12
28+
case outOfCalibrationDueToOutlier = 13
29+
case outlierCalibrationRequest = 14
30+
case sessionExpired = 15
31+
case sessionFailedDueToUnrecoverableError = 16
32+
case sessionFailedDueToTransmitterError = 17
33+
case temporarySensorIssue = 18
34+
case sensorFailedDueToProgressiveSensorDecline = 19
35+
case sensorFailedDueToHighCountsAberration = 20
36+
case sensorFailedDueToLowCountsAberration = 21
37+
case sensorFailedDueToRestart = 22
2038
case expired = 24
2139
case sensorFailed = 25
40+
case sessionEnded = 26
2241
}
2342

2443
case known(State)
@@ -48,7 +67,7 @@ public enum AlgorithmState: RawRepresentable {
4867
}
4968

5069
switch state {
51-
case .sensorFailed:
70+
case .sensorFailed, .sensorFailedDuetoCountsAberration, .sensorFailedDuetoResidualAberration, .sessionFailedDueToTransmitterError, .sessionFailedDueToUnrecoverableError, .sensorFailedDueToProgressiveSensorDecline, .sensorFailedDueToHighCountsAberration, .sensorFailedDueToLowCountsAberration, .sensorFailedDueToRestart:
5271
return true
5372
default:
5473
return false
@@ -68,13 +87,13 @@ public enum AlgorithmState: RawRepresentable {
6887
}
6988
}
7089

71-
public var isInSensorError: Bool {
90+
public var hasTemporaryError: Bool {
7291
guard case .known(let state) = self else {
7392
return false
7493
}
7594

7695
switch state {
77-
case .questionMarks:
96+
case .temporarySensorIssue:
7897
return true
7998
default:
8099
return false
@@ -88,14 +107,10 @@ public enum AlgorithmState: RawRepresentable {
88107
}
89108

90109
switch state {
91-
case .stopped,
92-
.warmup,
93-
.questionMarks,
94-
.expired,
95-
.sensorFailed:
96-
return false
97110
case .ok:
98111
return true
112+
default:
113+
return false
99114
}
100115
}
101116
}

G7SensorKit/G7CGMManager/G7BluetoothManager.swift

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ class G7BluetoothManager: NSObject {
159159

160160
private func managerQueue_stopScanning() {
161161
if centralManager.isScanning {
162-
log.debug("Stopping scan")
162+
log.default("Stopping scan")
163163
centralManager.stopScan()
164164
delegate?.bluetoothManagerScanningStatusDidChange(self)
165165
}
@@ -170,7 +170,7 @@ class G7BluetoothManager: NSObject {
170170

171171
managerQueue.sync {
172172
if centralManager.isScanning {
173-
log.debug("Stopping scan on disconnect")
173+
log.default("Stopping scan on disconnect")
174174
centralManager.stopScan()
175175
delegate?.bluetoothManagerScanningStatusDidChange(self)
176176
}
@@ -180,24 +180,17 @@ class G7BluetoothManager: NSObject {
180180
}
181181
}
182182
}
183-
183+
184184
func centralManager(_ central: CBCentralManager, connectionEventDidOccur event: CBConnectionEvent, for peripheral: CBPeripheral) {
185-
186185
managerQueue.async {
187-
guard self.eventRegistrationActive else {
188-
self.centralManager.registerForConnectionEvents(options: nil)
189-
return
190-
}
191-
192-
self.managerQueue_establishActivePeripheral()
193-
194-
if !self.eventRegistrationActive {
195-
self.centralManager.registerForConnectionEvents(options: nil)
186+
if self.activePeripheralIdentifier == nil {
187+
self.log.default("Discovered peripheral from connectionEventDidOccur %{public}@", peripheral.identifier.uuidString)
188+
self.handleDiscoveredPeripheral(peripheral)
196189
}
197190
}
198191
}
199-
200-
private func managerQueue_establishActivePeripheral() {
192+
193+
private func managerQueue_scanForPeripheral() {
201194
dispatchPrecondition(condition: .onQueue(managerQueue))
202195

203196
guard centralManager.state == .poweredOn else {
@@ -211,13 +204,14 @@ class G7BluetoothManager: NSObject {
211204
}
212205

213206
if let peripheralID = activePeripheralIdentifier, let peripheral = centralManager.retrievePeripherals(withIdentifiers: [peripheralID]).first {
214-
log.debug("Retrieved peripheral %{public}@", peripheral.identifier.uuidString)
207+
log.default("Retrieved peripheral %{public}@", peripheral.identifier.uuidString)
215208
handleDiscoveredPeripheral(peripheral)
216209
} else {
217210
for peripheral in centralManager.retrieveConnectedPeripherals(withServices: [
218211
SensorServiceUUID.advertisement.cbUUID,
219212
SensorServiceUUID.cgmService.cbUUID
220213
]) {
214+
log.default("Found system-connected peripheral: %{public}@", peripheral.identifier.uuidString)
221215
handleDiscoveredPeripheral(peripheral)
222216
}
223217
}
@@ -233,7 +227,13 @@ class G7BluetoothManager: NSObject {
233227
managerQueue_establishActivePeripheral()
234228

235229
if activePeripheral == nil {
236-
log.debug("Scanning for peripherals")
230+
log.default("Scanning for peripherals and listening for connection events")
231+
232+
centralManager.registerForConnectionEvents(options: [CBConnectionEventMatchingOption.serviceUUIDs: [
233+
SensorServiceUUID.advertisement.cbUUID,
234+
SensorServiceUUID.cgmService.cbUUID
235+
]])
236+
237237
centralManager.scanForPeripherals(withServices: [
238238
SensorServiceUUID.advertisement.cbUUID
239239
],
@@ -295,7 +295,7 @@ class G7BluetoothManager: NSObject {
295295
if let delegate = delegate {
296296
switch delegate.bluetoothManager(self, shouldConnectPeripheral: peripheral) {
297297
case .makeActive:
298-
log.debug("Making peripheral active: %{public}@", peripheral.identifier.uuidString)
298+
log.default("Making peripheral active: %{public}@", peripheral.identifier.uuidString)
299299

300300
if let peripheralManager = activePeripheralManager {
301301
peripheralManager.peripheral = peripheral
@@ -311,7 +311,7 @@ class G7BluetoothManager: NSObject {
311311
self.centralManager.connect(peripheral)
312312

313313
case .connect:
314-
log.debug("Connecting to peripheral: %{public}@", peripheral.identifier.uuidString)
314+
log.default("Connecting to peripheral: %{public}@", peripheral.identifier.uuidString)
315315
self.centralManager.connect(peripheral)
316316
let peripheralManager = G7PeripheralManager(
317317
peripheral: peripheral,
@@ -349,7 +349,7 @@ extension G7BluetoothManager: CBCentralManagerDelegate {
349349
fallthrough
350350
@unknown default:
351351
if central.isScanning {
352-
log.debug("Stopping scan on central not powered on")
352+
log.default("Stopping scan on central not powered on")
353353
central.stopScan()
354354
delegate?.bluetoothManagerScanningStatusDidChange(self)
355355
}
@@ -370,7 +370,7 @@ extension G7BluetoothManager: CBCentralManagerDelegate {
370370
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
371371
dispatchPrecondition(condition: .onQueue(managerQueue))
372372

373-
log.info("%{public}@: %{public}@, data = %{public}@", #function, peripheral, String(describing: advertisementData))
373+
log.default("%{public}@: %{public}@, data = %{public}@", #function, peripheral, String(describing: advertisementData))
374374

375375
managerQueue.async {
376376
self.handleDiscoveredPeripheral(peripheral)

G7SensorKit/G7CGMManager/G7CGMManager.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,11 @@ extension G7CGMManager: G7SensorDelegate {
323323
}
324324
}
325325

326+
public func sensor(_ sensor: G7Sensor, logComms comms: String) {
327+
logDeviceCommunication("Sensor comms \(comms)", type: .receive)
328+
}
329+
330+
326331
public func sensor(_ sensor: G7Sensor, didError error: Error) {
327332
logDeviceCommunication("Sensor error \(error)", type: .error)
328333
}
@@ -335,6 +340,17 @@ extension G7CGMManager: G7SensorDelegate {
335340
return
336341
}
337342

343+
if message.algorithmState.sensorFailed {
344+
logDeviceCommunication("Detected failed sensor... scanning for new sensor.", type: .receive)
345+
scanForNewSensor()
346+
}
347+
348+
if message.algorithmState == .known(.sessionEnded) {
349+
logDeviceCommunication("Detected session ended... scanning for new sensor.", type: .receive)
350+
scanForNewSensor()
351+
}
352+
353+
338354
guard let activationDate = sensor.activationDate else {
339355
logDeviceCommunication("Unable to process sensor reading without activation date.", type: .error)
340356
return

G7SensorKit/G7CGMManager/G7Sensor.swift

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ public protocol G7SensorDelegate: AnyObject {
1919

2020
func sensor(_ sensor: G7Sensor, didError error: Error)
2121

22+
func sensor(_ sensor: G7Sensor, logComms comms: String)
23+
2224
func sensor(_ sensor: G7Sensor, didRead glucose: G7GlucoseMessage)
2325

2426
func sensor(_ sensor: G7Sensor, didReadBackfill backfill: [G7BackfillMessage])
@@ -198,7 +200,9 @@ public final class G7Sensor: G7BluetoothManagerDelegate {
198200
if let sensorID = sensorID, sensorID == peripheralManager.peripheral.name {
199201

200202
let suspectedEndOfSession: Bool
201-
if pendingAuth && wasRemoteDisconnect {
203+
204+
self.log.info("Sensor disconnected: wasRemoteDisconnect:%{public}@", String(describing: wasRemoteDisconnect))
205+
if pendingAuth, wasRemoteDisconnect {
202206
suspectedEndOfSession = true // Normal disconnect without auth is likely that G7 app stopped this session
203207
} else {
204208
suspectedEndOfSession = false
@@ -237,7 +241,7 @@ public final class G7Sensor: G7BluetoothManagerDelegate {
237241

238242
guard response.count > 0 else { return }
239243

240-
log.debug("Received control response: %{public}@", response.hexadecimalString)
244+
log.default("Received control response: %{public}@", response.hexadecimalString)
241245

242246
switch G7Opcode(rawValue: response[0]) {
243247
case .glucoseTx?:
@@ -256,7 +260,7 @@ public final class G7Sensor: G7BluetoothManagerDelegate {
256260
}
257261
}
258262
default:
259-
// We ignore all other known opcodes
263+
self.delegate?.sensor(self, logComms: response.hexadecimalString)
260264
break
261265
}
262266
}

G7SensorKit/Messages/G7Opcode.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import Foundation
1010

1111
enum G7Opcode: UInt8 {
1212
case authChallengeRx = 0x05
13+
case sessionStopTx = 0x28
1314
case glucoseTx = 0x4e
1415
case backfillFinished = 0x59
1516
}

G7SensorKitUI/G7CGMManager/G7CGMManager+UI.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ extension G7CGMManager: CGMManagerUI {
7474
state: .warning)
7575
}
7676

77-
if let latestReading = latestReading, latestReading.algorithmState.isInSensorError {
77+
if let latestReading = latestReading, latestReading.algorithmState.hasTemporaryError {
7878
return G7DeviceStatusHighlight(
7979
localizedMessage: LocalizedString("Sensor\nIssue", comment: "G7 Status highlight text for sensor error"),
8080
imageName: "exclamationmark.circle.fill",

0 commit comments

Comments
 (0)