Skip to content

Commit

Permalink
Merge pull request #467 from ps2/track-frequency
Browse files Browse the repository at this point in the history
Track last valid pump frequency across RL reconnects
  • Loading branch information
ps2 authored Oct 1, 2018
2 parents ac0fa95 + a033a6b commit 483b228
Show file tree
Hide file tree
Showing 31 changed files with 153 additions and 155 deletions.
2 changes: 1 addition & 1 deletion Cartfile
Original file line number Diff line number Diff line change
@@ -1 +1 @@
github "LoopKit/LoopKit" == 2.1.3
github "LoopKit/LoopKit" == 2.1.5
2 changes: 1 addition & 1 deletion Cartfile.resolved
Original file line number Diff line number Diff line change
@@ -1 +1 @@
github "LoopKit/LoopKit" "v2.1.3"
github "LoopKit/LoopKit" "v2.1.5"
2 changes: 1 addition & 1 deletion Crypto/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.6</string>
<string>2.0.7</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
Expand Down
2 changes: 1 addition & 1 deletion MinimedKit/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.6</string>
<string>2.0.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
Expand Down
28 changes: 10 additions & 18 deletions MinimedKit/PumpManager/MinimedPumpManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -197,20 +197,13 @@ public class MinimedPumpManager: RileyLinkPumpManager, PumpManager {
// How long we should wait before we re-tune the RileyLink
let tuneTolerance = TimeInterval(minutes: 14)

let deviceState = deviceStates[device.peripheralIdentifier, default: DeviceState()]
let lastTuned = deviceState.lastTuned ?? .distantPast
let lastTuned = state.lastTuned ?? .distantPast

if lastTuned.timeIntervalSinceNow <= -tuneTolerance {
pumpOps.runSession(withName: "Tune pump", using: device) { (session) in
do {
let scanResult = try session.tuneRadio(current: deviceState.lastValidFrequency)
let scanResult = try session.tuneRadio()
self.log.error("Device %{public}@ auto-tuned to %{public}@ MHz", device.name ?? "", String(describing: scanResult.bestFrequency))
self.queue.async {
self.deviceStates[device.peripheralIdentifier] = DeviceState(
lastTuned: Date(),
lastValidFrequency: scanResult.bestFrequency
)
}
} catch let error {
self.log.error("Device %{public}@ auto-tune failed with error: %{public}@", device.name ?? "", String(describing: error))
self.rileyLinkDeviceProvider.deprioritize(device, completion: nil)
Expand Down Expand Up @@ -262,14 +255,13 @@ public class MinimedPumpManager: RileyLinkPumpManager, PumpManager {
device.getStatus { (deviceStatus) in
// Trigger device status upload, even if something is wrong with pumpStatus
self.queue.async {
let deviceState = self.deviceStates[device.peripheralIdentifier]

let pumpManagerStatus = PumpManagerStatus(
date: pumpDate,
timeZone: timeZone,
device: deviceStatus.device(pumpID: self.state.pumpID, pumpModel: self.state.pumpModel),
lastValidFrequency: deviceState?.lastValidFrequency,
lastTuned: deviceState?.lastTuned,
lastValidFrequency: self.state.lastValidFrequency,
lastTuned: self.state.lastTuned,
battery: PumpManagerStatus.BatteryStatus(percent: Double(status.batteryRemainingPercent) / 100),
isSuspended: nil,
isBolusing: nil,
Expand Down Expand Up @@ -454,13 +446,12 @@ public class MinimedPumpManager: RileyLinkPumpManager, PumpManager {

device.getStatus { (deviceStatus) in
self.queue.async {
let deviceState = self.deviceStates[device.peripheralIdentifier]
let pumpManagerStatus = PumpManagerStatus(
date: date,
timeZone: session.pump.timeZone,
device: deviceStatus.device(pumpID: self.state.pumpID, pumpModel: self.state.pumpModel),
lastValidFrequency: deviceState?.lastValidFrequency,
lastTuned: deviceState?.lastTuned,
lastValidFrequency: self.state.lastValidFrequency,
lastTuned: self.state.lastTuned,
battery: PumpManagerStatus.BatteryStatus(
voltage: status.batteryVolts,
state: {
Expand Down Expand Up @@ -598,14 +589,15 @@ public class MinimedPumpManager: RileyLinkPumpManager, PumpManager {
// MARK: - Configuration

// MARK: Pump

// TODO
public func getStateForDevice(_ device: RileyLinkDevice, completion: @escaping (_ deviceState: DeviceState, _ pumpOps: PumpOps) -> Void) {
public func getOpsForDevice(_ device: RileyLinkDevice, completion: @escaping (_ pumpOps: PumpOps) -> Void) {
queue.async {
completion(self.deviceStates[device.peripheralIdentifier, default: DeviceState()], self.pumpOps)
completion(self.pumpOps)
}
}


public private(set) var pumpOps: PumpOps!

/// The user's preferred method of fetching insulin data from the pump
Expand Down
27 changes: 25 additions & 2 deletions MinimedKit/PumpManager/MinimedPumpManagerState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
public var pumpID: String

public var pumpRegion: PumpRegion

public var lastValidFrequency: Measurement<UnitFrequency>?

public var lastTuned: Date?

public var pumpSettings: PumpSettings {
get {
Expand All @@ -42,12 +46,16 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
var state = PumpState()
state.pumpModel = pumpModel
state.timeZone = timeZone
state.lastValidFrequency = lastValidFrequency
state.lastTuned = lastTuned
return state
}
set {
if let model = newValue.pumpModel {
pumpModel = model
}
lastValidFrequency = newValue.lastValidFrequency
lastTuned = newValue.lastTuned
timeZone = newValue.timeZone
}
}
Expand All @@ -56,7 +64,7 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {

public var timeZone: TimeZone

public init(batteryChemistry: BatteryChemistryType = .alkaline, preferredInsulinDataSource: InsulinDataSource = .pumpHistory, pumpColor: PumpColor, pumpID: String, pumpModel: PumpModel, pumpRegion: PumpRegion, rileyLinkConnectionManagerState: RileyLinkConnectionManagerState?, timeZone: TimeZone) {
public init(batteryChemistry: BatteryChemistryType = .alkaline, preferredInsulinDataSource: InsulinDataSource = .pumpHistory, pumpColor: PumpColor, pumpID: String, pumpModel: PumpModel, pumpRegion: PumpRegion, rileyLinkConnectionManagerState: RileyLinkConnectionManagerState?, timeZone: TimeZone, lastValidFrequency: Measurement<UnitFrequency>? = nil) {
self.batteryChemistry = batteryChemistry
self.preferredInsulinDataSource = preferredInsulinDataSource
self.pumpColor = pumpColor
Expand All @@ -65,6 +73,7 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
self.pumpRegion = pumpRegion
self.rileyLinkConnectionManagerState = rileyLinkConnectionManagerState
self.timeZone = timeZone
self.lastValidFrequency = lastValidFrequency
}

public init?(rawValue: RawValue) {
Expand Down Expand Up @@ -104,6 +113,13 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
}
}

let lastValidFrequency: Measurement<UnitFrequency>?
if let frequencyRaw = rawValue["lastValidFrequency"] as? Double {
lastValidFrequency = Measurement<UnitFrequency>(value: frequencyRaw, unit: .megahertz)
} else {
lastValidFrequency = nil
}

self.init(
batteryChemistry: batteryChemistry,
preferredInsulinDataSource: insulinDataSource,
Expand All @@ -112,7 +128,8 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
pumpModel: pumpModel,
pumpRegion: pumpRegion,
rileyLinkConnectionManagerState: rileyLinkConnectionManagerState,
timeZone: timeZone
timeZone: timeZone,
lastValidFrequency: lastValidFrequency
)
}

Expand All @@ -132,6 +149,11 @@ public struct MinimedPumpManagerState: RawRepresentable, Equatable {
if let rileyLinkConnectionManagerState = rileyLinkConnectionManagerState {
value["rileyLinkConnectionManagerState"] = rileyLinkConnectionManagerState.rawValue
}

if let frequency = lastValidFrequency?.converted(to: .megahertz) {
value["lastValidFrequency"] = frequency.value
}

return value
}
}
Expand All @@ -152,6 +174,7 @@ extension MinimedPumpManagerState: CustomDebugStringConvertible {
"pumpID: ✔︎",
"pumpModel: \(pumpModel.rawValue)",
"pumpRegion: \(pumpRegion)",
"lastValidFrequency: \(String(describing: lastValidFrequency))",
"timeZone: \(timeZone)",
String(reflecting: rileyLinkConnectionManagerState),
].joined(separator: "\n")
Expand Down
15 changes: 14 additions & 1 deletion MinimedKit/PumpManager/PumpOps.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public class PumpOps {
}

private var configuredDevices: Set<RileyLinkDevice> = Set()

private var sessionDevice: RileyLinkDevice?

private let sessionQueue = DispatchQueue(label: "com.rileylink.RileyLinkKit.PumpOps", qos: .utility)

Expand Down Expand Up @@ -69,8 +71,10 @@ public class PumpOps {

device.runSession(withName: name) { (session) in
let session = PumpOpsSession(settings: self.pumpSettings, pumpState: self.pumpState, session: session, delegate: self)
self.sessionDevice = device
self.configureDevice(device, with: session)
block(session)
self.sessionDevice = nil
semaphore.signal()
}

Expand All @@ -85,7 +89,7 @@ public class PumpOps {
}

do {
_ = try session.configureRadio(for: pumpSettings.pumpRegion)
_ = try session.configureRadio(for: pumpSettings.pumpRegion, frequency: pumpState.lastValidFrequency)
} catch {
// Ignore the error and let the block run anyway
return
Expand Down Expand Up @@ -116,6 +120,15 @@ public class PumpOps {


extension PumpOps: PumpOpsSessionDelegate {

func pumpOpsSessionDidChangeRadioConfig(_ session: PumpOpsSession) {
sessionQueue.async {
if let sessionDevice = self.sessionDevice {
self.configuredDevices = [sessionDevice]
}
}
}

func pumpOpsSession(_ session: PumpOpsSession, didChange state: PumpState) {
self.pumpState = state
}
Expand Down
16 changes: 15 additions & 1 deletion MinimedKit/PumpManager/PumpState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ public struct PumpState: RawRepresentable, Equatable {

public var awakeUntil: Date?

public var lastValidFrequency: Measurement<UnitFrequency>?

public var lastTuned: Date?

var isAwake: Bool {
if let awakeUntil = awakeUntil {
return awakeUntil.timeIntervalSinceNow > 0
Expand All @@ -41,10 +45,14 @@ public struct PumpState: RawRepresentable, Equatable {
}

self.timeZone = timeZone

if let pumpModelNumber = rawValue["pumpModel"] as? PumpModel.RawValue {
pumpModel = PumpModel(rawValue: pumpModelNumber)
}

if let frequencyRaw = rawValue["lastValidFrequency"] as? Double {
lastValidFrequency = Measurement<UnitFrequency>(value: frequencyRaw, unit: .megahertz)
}
}

public var rawValue: RawValue {
Expand All @@ -55,6 +63,10 @@ public struct PumpState: RawRepresentable, Equatable {
if let pumpModel = pumpModel {
rawValue["pumpModel"] = pumpModel.rawValue
}

if let frequency = lastValidFrequency?.converted(to: .megahertz) {
rawValue["lastValidFrequency"] = frequency.value
}

return rawValue
}
Expand All @@ -69,6 +81,8 @@ extension PumpState: CustomDebugStringConvertible {
"timeZone: \(timeZone)",
"pumpModel: \(pumpModel?.rawValue ?? "")",
"awakeUntil: \(awakeUntil ?? .distantPast)",
"lastValidFrequency: \(String(describing: lastValidFrequency))",
"lastTuned: \(awakeUntil ?? .distantPast))",
"lastWakeAttempt: \(String(describing: lastWakeAttempt))"
].joined(separator: "\n")
}
Expand Down
2 changes: 1 addition & 1 deletion MinimedKitTests/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>2.0.6</string>
<string>2.0.7</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
Expand Down
5 changes: 5 additions & 0 deletions MinimedKitTests/PumpOpsSynchronousTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,11 @@ extension PumpMessageSenderStub: PumpOpsSessionDelegate {
func pumpOpsSession(_ session: PumpOpsSession, didChange state: PumpState) {

}

func pumpOpsSessionDidChangeRadioConfig(_ session: PumpOpsSession) {

}

}

func array(_ timestampedEvents: [TimestampedHistoryEvent], containsPumpEvent pumpEvent: PumpEvent) -> Bool {
Expand Down
15 changes: 2 additions & 13 deletions MinimedKitUI/CommandResponseViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -297,23 +297,12 @@ extension CommandResponseViewController {
}
}

static func tuneRadio(ops: PumpOps?, device: RileyLinkDevice, current: Measurement<UnitFrequency>?, measurementFormatter: MeasurementFormatter) -> T {
static func tuneRadio(ops: PumpOps?, device: RileyLinkDevice, measurementFormatter: MeasurementFormatter) -> T {
return T { (completionHandler) -> String in
ops?.runSession(withName: "Tune pump", using: device) { (session) in
let response: String
do {
let scanResult = try session.tuneRadio(current: nil)

NotificationCenter.default.post(
name: .DeviceStateDidChange,
object: device,
userInfo: [
RileyLinkDevice.notificationDeviceStateKey: DeviceState(
lastTuned: Date(),
lastValidFrequency: scanResult.bestFrequency
)
]
)
let scanResult = try session.tuneRadio()

var resultDict: [String: Any] = [:]

Expand Down
2 changes: 1 addition & 1 deletion MinimedKitUI/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.0.6</string>
<string>2.0.7</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
Expand Down
3 changes: 1 addition & 2 deletions MinimedKitUI/MinimedPumpSettingsViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,10 @@ class MinimedPumpSettingsViewController: RileyLinkSettingsViewController {
case .rileyLinks:
let device = devicesDataSource.devices[indexPath.row]

pumpManager.getStateForDevice(device) { (deviceState, pumpOps) in
pumpManager.getOpsForDevice(device) { (pumpOps) in
DispatchQueue.main.async {
let vc = RileyLinkMinimedDeviceTableViewController(
device: device,
deviceState: deviceState,
pumpOps: pumpOps
)

Expand Down
Loading

0 comments on commit 483b228

Please sign in to comment.