Make OmnipodDashManager.connect() return an Observable of PodEvents

This commit is contained in:
Bart Sopers 2021-02-27 23:21:09 +01:00
parent f8ca7592ae
commit d08a979da3
16 changed files with 126 additions and 98 deletions

View file

@ -2,12 +2,18 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.SingleSubject
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import io.reactivex.Single
import javax.inject.Inject
abstract class ActionViewModelBase : ViewModelBase() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var logger: AAPSLogger
private val _isActionExecutingLiveData = MutableLiveData(false)
val isActionExecutingLiveData: LiveData<Boolean> = _isActionExecutingLiveData
@ -16,14 +22,15 @@ abstract class ActionViewModelBase : ViewModelBase() {
fun executeAction() {
_isActionExecutingLiveData.postValue(true)
SingleSubject.fromCallable(this::doExecuteAction)
.subscribeOn(Schedulers.io())
.doOnSuccess { result ->
_isActionExecutingLiveData.postValue(false)
_actionResultLiveData.postValue(result)
}
.subscribe()
val disposable = doExecuteAction().subscribe({ result ->
_isActionExecutingLiveData.postValue(false)
_actionResultLiveData.postValue(result)
}, { throwable ->
logger.error(LTag.PUMP, "Caught exception in while executing action in ActionViewModelBase", throwable)
_isActionExecutingLiveData.postValue(false)
_actionResultLiveData.postValue(PumpEnactResult(injector).success(false).comment(throwable.message))
})
}
protected abstract fun doExecuteAction(): PumpEnactResult
protected abstract fun doExecuteAction(): Single<PumpEnactResult>
}

View file

@ -11,6 +11,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@ -30,29 +32,17 @@ class OmnipodDashManagerImpl @Inject constructor(
return Observable.error(IllegalStateException("Pod is in an incorrect state"))
}
private val observeConnectToPod: Observable<PodEvent>
get() {
return Observable.defer {
bleManager.connect()
Observable.just(PodEvent.Connected(0)) // TODO should be returned in BleManager
}
}
override fun activatePodPart1(): Observable<PodEvent> {
val command = GetVersionCommand.Builder() //
.setSequenceNumber(podStateManager.messageSequenceNumber) //
.setUniqueId(DEFAULT_UNIQUE_ID) //
.build()
return Observable.concat(
observePodReadyForActivationPart1,
observeConnectToPod,
Observable.defer {
bleManager.sendCommand(command)
Observable.just(PodEvent.CommandSent(command)) // TODO should be returned in BleManager
}
bleManager.connect(),
bleManager.sendCommand(GetVersionCommand.Builder() //
.setSequenceNumber(podStateManager.messageSequenceNumber) //
.setUniqueId(DEFAULT_UNIQUE_ID) //
.build()) //
// ... Send more commands
)
).subscribeOn(Schedulers.io()) //
.observeOn(AndroidSchedulers.mainThread())
}
override fun activatePodPart2(): Observable<PodEvent> {

View file

@ -1,18 +1,17 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response
import io.reactivex.Observable
interface OmnipodDashBleManager {
fun sendCommand(cmd: Command): Response
fun sendCommand(cmd: Command): Observable<PodEvent>
fun getStatus(): ConnectionStatus
fun connect()
fun connect(): Observable<PodEvent>
fun disconnect()
fun getPodId(): Id
}

View file

@ -17,8 +17,10 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKE
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response
import io.reactivex.Observable
import org.apache.commons.lang3.NotImplementedException
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeoutException
@ -62,8 +64,9 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context
return bleIO
}
override fun sendCommand(cmd: Command): Response {
TODO("not implemented")
override fun sendCommand(cmd: Command): Observable<PodEvent> {
// TODO
return Observable.error(NotImplementedException("sendCommand is not yet implemented"))
}
override fun getStatus(): ConnectionStatus {
@ -71,30 +74,42 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context
}
@Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class)
override fun connect() {
// TODO: this is wrong and I know it
aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation")
val podScanner = PodScanner(aapsLogger, bluetoothAdapter)
val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address
// For tests: this.podAddress = "B8:27:EB:1D:7E:BB";
val bleIO = connect(podAddress)
val msgIO = MessageIO(aapsLogger, bleIO)
val ltkExchanger = LTKExchanger(aapsLogger, msgIO)
val ltk = ltkExchanger.negociateLTKAndNonce()
override fun connect(): Observable<PodEvent> = Observable.create { emitter ->
// TODO: when we are already connected,
// emit PodEvent.AlreadyConnected, complete the observable and return from this method
aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}")
try {
// TODO: this is wrong and I know it
aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation")
val podScanner = PodScanner(aapsLogger, bluetoothAdapter)
emitter.onNext(PodEvent.Scanning)
val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address
// For tests: this.podAddress = "B8:27:EB:1D:7E:BB";
emitter.onNext(PodEvent.BluetoothConnecting)
val bleIO = connect(podAddress)
emitter.onNext(PodEvent.BluetoothConnected(podAddress))
val msgIO = MessageIO(aapsLogger, bleIO)
val ltkExchanger = LTKExchanger(aapsLogger, msgIO)
emitter.onNext(PodEvent.NegotiatingLtkAndNoncePrefix)
val ltk = ltkExchanger.negotiateLTKAndNonce()
aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}")
emitter.onNext(PodEvent.Connected(PodScanner.POD_ID_NOT_ACTIVATED)) // TODO supply actual pod id
emitter.onComplete()
} catch (ex: Exception) {
emitter.onError(ex) // TODO is this necessary?
}
}
override fun disconnect() {
TODO("not implemented")
}
override fun getPodId(): Id {
// TODO: return something meaningful here
return Id.fromInt(4243);
}
companion object {
private const val CONNECT_TIMEOUT_MS = 5000

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions
open class ScanFailException : Exception {
constructor()
constructor(message: String) : super(message)
constructor(errorCode: Int) : super("errorCode$errorCode")
}

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.BleDiscoveredDevice
import java.util.*
class ScanFailFoundTooManyException(devices: List<BleDiscoveredDevice>) : ScanFailException() {
class ScanFailFoundTooManyException(devices: List<BleDiscoveredDevice>) : ScanFailException("Found more than one Pod") {
private val devices: List<BleDiscoveredDevice> = ArrayList(devices)
val discoveredDevices: List<BleDiscoveredDevice>

View file

@ -1,3 +1,3 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions
class ScanFailNotFoundException : ScanFailException()
class ScanFailNotFoundException : ScanFailException("No Pod found")

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.utils.extensions.hexStringToByteArray
internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) {
fun negociateLTKAndNonce(): LTK? {
fun negotiateLTKAndNonce(): LTK? {
// send SP1, SP2
// TODO: get this from somewhere(preferences?)
var seq: Byte = 1

View file

@ -34,7 +34,7 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S
for (result in found.values) {
try {
result.scanRecord?.let {
val device = BleDiscoveredDevice(result, result.scanRecord, podID)
val device = BleDiscoveredDevice(result, it, podID)
ret.add(device)
logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + podID)
}

View file

@ -5,10 +5,15 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.
sealed class PodEvent {
/* BT connection events */
class AlreadyConnected(val uniqueId: Long) : PodEvent()
object Scanning : PodEvent()
object Pairing : PodEvent()
object Connecting : PodEvent()
class Connected(val uniqueId: Int) : PodEvent()
object BluetoothConnecting : PodEvent()
class BluetoothConnected(val address: String) : PodEvent()
object NegotiatingLtkAndNoncePrefix : PodEvent()
class Connected(val uniqueId: Long) : PodEvent()
/* Message exchange events */
class CommandSending(val command: Command) : PodEvent()
class CommandSent(val command: Command) : PodEvent()
class ResponseReceived(val response: Response) : PodEvent()

View file

@ -1,18 +1,15 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action
import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel
import info.nightscout.androidaps.plugins.pump.omnipod.dash.R
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager
import io.reactivex.Single
import javax.inject.Inject
class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger,
private val injector: HasAndroidInjector,
private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() {
class DashInitializePodViewModel @Inject constructor(private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() {
override fun isPodInAlarm(): Boolean = false // TODO
@ -20,16 +17,20 @@ class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAP
override fun isPodDeactivatable(): Boolean = true // TODO
override fun doExecuteAction(): PumpEnactResult {
// TODO FIRST STEP OF ACTIVATION
val disposable = omnipodManager.activatePodPart1().subscribe(
{ podEvent -> aapsLogger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") },
{ throwable -> aapsLogger.error(LTag.PUMP, "Error in Pod activation part 1: $throwable") },
{ aapsLogger.debug("Pod activation part 1 completed") }
)
return PumpEnactResult(injector).success(false).comment("not implemented")
}
override fun doExecuteAction(): Single<PumpEnactResult> =
Single.create { source ->
val disposable = omnipodManager.activatePodPart1().subscribe(
{ podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") },
{ throwable ->
logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable)
source.onSuccess(PumpEnactResult(injector).success(false).comment(throwable.message))
},
{
logger.debug("Pod activation part 1 completed")
source.onSuccess(PumpEnactResult(injector).success(true))
}
)
}
@StringRes
override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action
import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel
import info.nightscout.androidaps.plugins.pump.omnipod.dash.R
import io.reactivex.Single
import javax.inject.Inject
class DashInsertCannulaViewModel @Inject constructor(private val injector: HasAndroidInjector, private val profileFunction: ProfileFunction) : InsertCannulaViewModel() {
class DashInsertCannulaViewModel @Inject constructor(private val profileFunction: ProfileFunction) : InsertCannulaViewModel() {
override fun isPodInAlarm(): Boolean = false // TODO
@ -16,7 +16,7 @@ class DashInsertCannulaViewModel @Inject constructor(private val injector: HasAn
override fun isPodDeactivatable(): Boolean = true // TODO
override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO
override fun doExecuteAction(): Single<PumpEnactResult> = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO
@StringRes
override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title

View file

@ -1,15 +1,15 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.action
import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.plugins.pump.omnipod.common.R
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel
import io.reactivex.Single
import javax.inject.Inject
class DashDeactivatePodViewModel @Inject constructor(private val injector: HasAndroidInjector) : DeactivatePodViewModel() {
class DashDeactivatePodViewModel @Inject constructor() : DeactivatePodViewModel() {
override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO
override fun doExecuteAction(): Single<PumpEnactResult> = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO
override fun discardPod() {
// TODO

View file

@ -7,9 +7,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.R
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager
import io.reactivex.Single
import javax.inject.Inject
class ErosInitializePodViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val podStateManager: AapsErosPodStateManager) : InitializePodViewModel() {
class ErosInitializePodViewModel @Inject constructor(
private val aapsOmnipodManager: AapsOmnipodErosManager,
private val podStateManager: AapsErosPodStateManager
) : InitializePodViewModel() {
override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted
@ -17,7 +21,7 @@ class ErosInitializePodViewModel @Inject constructor(private val aapsOmnipodMana
override fun isPodDeactivatable(): Boolean = podStateManager.activationProgress.isAtLeast(ActivationProgress.PAIRING_COMPLETED)
override fun doExecuteAction(): PumpEnactResult = aapsOmnipodManager.initializePod()
override fun doExecuteAction(): Single<PumpEnactResult> = Single.just(aapsOmnipodManager.initializePod())
@StringRes
override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title

View file

@ -8,9 +8,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.R
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager
import io.reactivex.Single
import javax.inject.Inject
class ErosInsertCannulaViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val podStateManager: AapsErosPodStateManager, private val profileFunction: ProfileFunction) : InsertCannulaViewModel() {
class ErosInsertCannulaViewModel @Inject constructor(
private val aapsOmnipodManager: AapsOmnipodErosManager,
private val podStateManager: AapsErosPodStateManager,
private val profileFunction: ProfileFunction
) : InsertCannulaViewModel() {
override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted
@ -18,7 +23,7 @@ class ErosInsertCannulaViewModel @Inject constructor(private val aapsOmnipodMana
override fun isPodDeactivatable(): Boolean = podStateManager.activationProgress.isAtLeast(ActivationProgress.PAIRING_COMPLETED)
override fun doExecuteAction(): PumpEnactResult = aapsOmnipodManager.insertCannula(profileFunction.getProfile())
override fun doExecuteAction(): Single<PumpEnactResult> = Single.just(aapsOmnipodManager.insertCannula(profileFunction.getProfile()))
@StringRes
override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title

View file

@ -8,20 +8,22 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.Comm
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager
import info.nightscout.androidaps.queue.Callback
import io.reactivex.subjects.SingleSubject
import io.reactivex.Single
import javax.inject.Inject
class ErosDeactivatePodViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val commandQueueProvider: CommandQueueProvider) : DeactivatePodViewModel() {
class ErosDeactivatePodViewModel @Inject constructor(
private val aapsOmnipodManager: AapsOmnipodErosManager,
private val commandQueueProvider: CommandQueueProvider
) : DeactivatePodViewModel() {
override fun doExecuteAction(): PumpEnactResult {
val singleSubject = SingleSubject.create<PumpEnactResult>()
commandQueueProvider.customCommand(CommandDeactivatePod(), object : Callback() {
override fun run() {
singleSubject.onSuccess(result)
}
})
return singleSubject.blockingGet()
}
override fun doExecuteAction(): Single<PumpEnactResult> =
Single.create { source ->
commandQueueProvider.customCommand(CommandDeactivatePod(), object : Callback() {
override fun run() {
source.onSuccess(result)
}
})
}
override fun discardPod() {
aapsOmnipodManager.discardPodState()