PumpEnactResultImpl

This commit is contained in:
Milos Kozak 2022-11-06 20:55:48 +01:00
parent b30fb687db
commit e17ca2be0a
97 changed files with 1285 additions and 994 deletions

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.MainActivity
import info.nightscout.androidaps.R
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.OfflineEvent
@ -382,7 +382,7 @@ class LoopPlugin @Inject constructor(
if (resultAfterConstraints.isChangeRequested
&& !commandQueue.bolusInQueue()
) {
val waiting = PumpEnactResult(injector)
val waiting = PumpEnactResultImpl(injector)
waiting.queued = true
if (resultAfterConstraints.tempBasalRequested) lastRun.tbrSetByPump = waiting
if (resultAfterConstraints.bolusRequested()) lastRun.smbSetByPump = waiting
@ -533,18 +533,18 @@ class LoopPlugin @Inject constructor(
*/
private fun applyTBRRequest(request: APSResult, profile: Profile, callback: Callback?) {
if (!request.tempBasalRequested) {
callback?.result(PumpEnactResult(injector).enacted(false).success(true).comment(R.string.nochangerequested))?.run()
callback?.result(PumpEnactResultImpl(injector).enacted(false).success(true).comment(R.string.nochangerequested))?.run()
return
}
val pump = activePlugin.activePump
if (!pump.isInitialized()) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: " + rh.gs(R.string.pumpNotInitialized))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
return
}
if (pump.isSuspended()) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: " + rh.gs(R.string.pumpsuspended))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
return
}
aapsLogger.debug(LTag.APS, "applyAPSRequest: $request")
@ -558,7 +558,7 @@ class LoopPlugin @Inject constructor(
} else {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Basal set correctly")
callback?.result(
PumpEnactResult(injector).absolute(request.rate).duration(0)
PumpEnactResultImpl(injector).absolute(request.rate).duration(0)
.enacted(false).success(true).comment(R.string.basal_set_correctly)
)?.run()
}
@ -571,7 +571,7 @@ class LoopPlugin @Inject constructor(
} else {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Basal set correctly")
callback?.result(
PumpEnactResult(injector).percent(request.percent).duration(0)
PumpEnactResultImpl(injector).percent(request.percent).duration(0)
.enacted(false).success(true).comment(R.string.basal_set_correctly)
)?.run()
}
@ -582,7 +582,7 @@ class LoopPlugin @Inject constructor(
) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly")
callback?.result(
PumpEnactResult(injector).percent(request.percent)
PumpEnactResultImpl(injector).percent(request.percent)
.enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes)
.comment(R.string.let_temp_basal_run)
)?.run()
@ -605,7 +605,7 @@ class LoopPlugin @Inject constructor(
) {
aapsLogger.debug(LTag.APS, "applyAPSRequest: Temp basal set correctly")
callback?.result(
PumpEnactResult(injector).absolute(activeTemp.convertedToAbsolute(now, profile))
PumpEnactResultImpl(injector).absolute(activeTemp.convertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.plannedRemainingMinutes)
.comment(R.string.let_temp_basal_run)
)?.run()
@ -631,7 +631,7 @@ class LoopPlugin @Inject constructor(
if (lastBolusTime != 0L && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
aapsLogger.debug(LTag.APS, "SMB requested but still in 3 min interval")
callback?.result(
PumpEnactResult(injector)
PumpEnactResultImpl(injector)
.comment(R.string.smb_frequency_exceeded)
.enacted(false).success(false)
)?.run()
@ -639,12 +639,12 @@ class LoopPlugin @Inject constructor(
}
if (!pump.isInitialized()) {
aapsLogger.debug(LTag.APS, "applySMBRequest: " + rh.gs(R.string.pumpNotInitialized))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).comment(R.string.pumpNotInitialized).enacted(false).success(false))?.run()
return
}
if (pump.isSuspended()) {
aapsLogger.debug(LTag.APS, "applySMBRequest: " + rh.gs(R.string.pumpsuspended))
callback?.result(PumpEnactResult(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).comment(R.string.pumpsuspended).enacted(false).success(false))?.run()
return
}
aapsLogger.debug(LTag.APS, "applySMBRequest: $request")

View file

@ -7,6 +7,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.extensions.convertedToAbsolute
@ -132,7 +133,7 @@ open class VirtualPumpPlugin @Inject constructor(
var fakeDataDetected = false
override fun loadTDDs(): PumpEnactResult { //no result, could read DB in the future?
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
}
override fun isInitialized(): Boolean = true
@ -157,7 +158,7 @@ open class VirtualPumpPlugin @Inject constructor(
lastDataTime = System.currentTimeMillis()
rxBus.send(EventNewNotification(Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60)))
// Do nothing here. we are using database profile
return PumpEnactResult(injector).success(true).enacted(true)
return PumpEnactResultImpl(injector).success(true).enacted(true)
}
override fun isThisProfileSet(profile: Profile): Boolean = pumpSync.expectedPumpState().profile?.isEqual(profile) ?: false
@ -174,7 +175,7 @@ open class VirtualPumpPlugin @Inject constructor(
get() = batteryPercent
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
.success(true)
.bolusDelivered(detailedBolusInfo.insulin)
.carbsDelivered(detailedBolusInfo.carbs)
@ -190,7 +191,7 @@ open class VirtualPumpPlugin @Inject constructor(
rxBus.send(bolusingEvent)
delivering += 0.1
if (BolusProgressDialog.stopPressed)
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
.success(false)
.enacted(false)
.comment(rh.gs(R.string.stoppressed))
@ -225,7 +226,7 @@ open class VirtualPumpPlugin @Inject constructor(
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = true
result.enacted = true
result.isTempCancel = false
@ -242,14 +243,14 @@ open class VirtualPumpPlugin @Inject constructor(
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Setting temp basal absolute: $result")
aapsLogger.debug(LTag.PUMP, "Setting temp basal absolute: ${result.toText()}")
rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis()
return result
}
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = true
result.enacted = true
result.percent = percent
@ -267,7 +268,7 @@ open class VirtualPumpPlugin @Inject constructor(
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Settings temp basal percent: $result")
aapsLogger.debug(LTag.PUMP, "Settings temp basal percent: ${result.toText()}")
rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis()
return result
@ -291,14 +292,14 @@ open class VirtualPumpPlugin @Inject constructor(
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Setting extended bolus: $result")
aapsLogger.debug(LTag.PUMP, "Setting extended bolus: ${result.toText()}")
rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis()
return result
}
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = true
result.isTempCancel = true
result.comment = rh.gs(R.string.virtualpump_resultok)
@ -310,7 +311,7 @@ open class VirtualPumpPlugin @Inject constructor(
pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()
)
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: $result")
aapsLogger.debug(LTag.PUMP, "Canceling temp basal: ${result.toText()}")
rxBus.send(EventVirtualPumpUpdateGui())
}
lastDataTime = System.currentTimeMillis()
@ -318,7 +319,7 @@ open class VirtualPumpPlugin @Inject constructor(
}
override fun cancelExtendedBolus(): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (pumpSync.expectedPumpState().extendedBolus != null) {
pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = dateUtil.now(),
@ -331,7 +332,7 @@ open class VirtualPumpPlugin @Inject constructor(
result.enacted = true
result.isTempCancel = true
result.comment = rh.gs(R.string.virtualpump_resultok)
aapsLogger.debug(LTag.PUMP, "Canceling extended bolus: $result")
aapsLogger.debug(LTag.PUMP, "Canceling extended bolus: ${result.toText()}")
rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis()
return result

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,30 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -7,7 +7,7 @@ import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.insight.database.InsightDatabaseDao
import info.nightscout.androidaps.insight.database.InsightDbHelper
@ -84,7 +84,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
it.sp = sp
it.dateUtil = dateUtil
}
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}
@ -135,12 +135,100 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, rh, activePlugin, sp, config, dateUtil, uel)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, rh, profileFunction, sp, commandQueue, context, pumpSync, dateUtil, ruffyScripter)
danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync)
danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, rh, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil)
danaRSPlugin =
DanaRSPlugin(
injector,
aapsLogger,
aapsSchedulers,
rxBus,
context,
rh,
constraintChecker,
profileFunction,
sp,
commandQueue,
danaPump,
pumpSync,
detailedBolusInfoStorage,
temporaryBasalStorage,
fabricPrivacy,
dateUtil
)
insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, rh, sp, commandQueue, profileFunction, context, config, dateUtil, insightDbHelper, pumpSync)
openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider)
openAPSSMBDynamicISFPlugin = OpenAPSSMBDynamicISFPlugin(injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider, buildHelper)
openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, rh, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider)
safetyPlugin = SafetyPlugin(injector, aapsLogger, rh, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, openAPSSMBDynamicISFPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelperImpl(config, fileListProvider), iobCobCalculator, config, dateUtil)
openAPSSMBPlugin =
OpenAPSSMBPlugin(
injector,
aapsLogger,
rxBus,
constraintChecker,
rh,
profileFunction,
context,
activePlugin,
iobCobCalculator,
hardLimits,
profiler,
sp,
dateUtil,
repository,
glucoseStatusProvider
)
openAPSSMBDynamicISFPlugin =
OpenAPSSMBDynamicISFPlugin(
injector,
aapsLogger,
rxBus,
constraintChecker,
rh,
profileFunction,
context,
activePlugin,
iobCobCalculator,
hardLimits,
profiler,
sp,
dateUtil,
repository,
glucoseStatusProvider,
buildHelper
)
openAPSAMAPlugin =
OpenAPSAMAPlugin(
injector,
aapsLogger,
rxBus,
constraintChecker,
rh,
profileFunction,
context,
activePlugin,
iobCobCalculator,
hardLimits,
profiler,
fabricPrivacy,
dateUtil,
repository,
glucoseStatusProvider
)
safetyPlugin =
SafetyPlugin(
injector,
aapsLogger,
rh,
sp,
rxBus,
constraintChecker,
openAPSAMAPlugin,
openAPSSMBPlugin,
openAPSSMBDynamicISFPlugin,
sensitivityOref1Plugin,
activePlugin,
hardLimits,
BuildHelperImpl(config, fileListProvider),
iobCobCalculator,
config,
dateUtil
)
val constraintsPluginsList = ArrayList<PluginBase>()
constraintsPluginsList.add(safetyPlugin)
constraintsPluginsList.add(objectivesPlugin)

View file

@ -4,7 +4,7 @@ import android.content.Context
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.JsonHelper
@ -39,7 +39,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) {
timerUtil.scheduleReminder(10, text.value.takeIf { it.isNotBlank() }
?: rh.gs(R.string.app_name))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
}
override fun toJSON(): String {

View file

@ -2,7 +2,7 @@ package info.nightscout.automation.actions
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.interfaces.CommandQueue
@ -41,7 +41,7 @@ class ActionLoopDisable(injector: HasAndroidInjector) : Action(injector) {
}
})
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadydisabled)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.alreadydisabled)).run()
}
}

View file

@ -2,7 +2,7 @@ package info.nightscout.automation.actions
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.interfaces.ConfigBuilder
@ -33,9 +33,9 @@ class ActionLoopEnable(injector: HasAndroidInjector) : Action(injector) {
configBuilder.storeSettings("ActionLoopEnable")
rxBus.send(EventRefreshOverview("ActionLoopEnable"))
uel.log(UserEntry.Action.LOOP_ENABLED, Sources.Automation, title)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadyenabled)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.alreadyenabled)).run()
}
}

View file

@ -2,7 +2,7 @@ package info.nightscout.automation.actions
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
@ -45,9 +45,9 @@ class ActionLoopResume(injector: HasAndroidInjector) : Action(injector) {
})
rxBus.send(EventRefreshOverview("ActionLoopResume"))
uel.log(UserEntry.Action.RESUME, Sources.Automation, title)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.notsuspended)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.notsuspended)).run()
}
}

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
@ -40,9 +40,9 @@ class ActionLoopSuspend(injector: HasAndroidInjector) : Action(injector) {
UserEntry.Action.SUSPEND, Sources.Automation, title + ": " + rh.gs(R.string.suspendloopforXmin, minutes.getMinutes()),
ValueWithUnit.Minute(minutes.getMinutes())
)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
} else {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadysuspended)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.alreadysuspended)).run()
}
}

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
@ -39,7 +39,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
rxBus.send(EventNewNotification(notification))
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(text.value)).subscribe()
rxBus.send(EventRefreshOverview("ActionNotification"))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
}
override fun toJSON(): String {

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
@ -40,23 +40,23 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) {
//Check for uninitialized profileName
if (inputProfileName.value == "") {
aapsLogger.error(LTag.AUTOMATION, "Selected profile not initialized")
callback.result(PumpEnactResult(injector).success(false).comment(R.string.error_field_must_not_be_empty)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(R.string.error_field_must_not_be_empty)).run()
return
}
if (profileFunction.getProfile() == null) {
aapsLogger.error(LTag.AUTOMATION, "ProfileFunctions not initialized")
callback.result(PumpEnactResult(injector).success(false).comment(R.string.noprofile)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(R.string.noprofile)).run()
return
}
if (inputProfileName.value == activeProfileName) {
aapsLogger.debug(LTag.AUTOMATION, "Profile is already switched")
callback.result(PumpEnactResult(injector).success(true).comment(R.string.alreadyset)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.alreadyset)).run()
return
}
val profileStore = activePlugin.activeProfileSource.profile ?: return
if (profileStore.getSpecificProfile(inputProfileName.value) == null) {
aapsLogger.error(LTag.AUTOMATION, "Selected profile does not exist! - ${inputProfileName.value}")
callback.result(PumpEnactResult(injector).success(false).comment(R.string.notexists)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(R.string.notexists)).run()
return
}
uel.log(
@ -65,7 +65,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) {
ValueWithUnit.Percent(100)
)
val result = profileFunction.createProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, dateUtil.now())
callback.result(PumpEnactResult(injector).success(result).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(result).comment(R.string.ok)).run()
}
override fun generateDialog(root: LinearLayout) {

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
@ -51,10 +51,10 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector
ValueWithUnit.Percent(pct.value.toInt()),
ValueWithUnit.Minute(duration.value)
)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
} else {
aapsLogger.error(LTag.AUTOMATION, "Final profile not valid")
callback.result(PumpEnactResult(injector).success(false).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(R.string.ok)).run()
}
}

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Autotune
import info.nightscout.androidaps.interfaces.ProfileFunction
@ -49,11 +49,11 @@ class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) {
message = R.string.autotune_run_with_error
aapsLogger.error(LTag.AUTOMATION, "Error during Autotune Run")
}
callback.result(PumpEnactResult(injector).success(autotunePlugin.lastRunSuccess).comment(message)).run()
callback.result(PumpEnactResultImpl(injector).success(autotunePlugin.lastRunSuccess).comment(message)).run()
} else {
message = R.string.autotune_run_cancelled
aapsLogger.debug(LTag.AUTOMATION, "Autotune run detected, Autotune Run Cancelled")
callback.result(PumpEnactResult(injector).success(false).comment(message)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(message)).run()
}
}.start()
return

View file

@ -2,7 +2,7 @@ package info.nightscout.automation.actions
import android.widget.LinearLayout
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.SmsCommunicator
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
@ -25,7 +25,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) {
val result = smsCommunicator.sendNotificationToAllNumbers(text.value)
callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.error)).run()
callback.result(PumpEnactResultImpl(injector).success(result).comment(if (result) R.string.ok else R.string.error)).run()
}
override fun isValid(): Boolean = text.value.isNotEmpty()

View file

@ -4,7 +4,7 @@ import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.database.entities.UserEntry
@ -69,10 +69,10 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
ValueWithUnit.Mgdl(tt().highTarget).takeIf { tt().lowTarget != tt().highTarget },
ValueWithUnit.Minute(TimeUnit.MILLISECONDS.toMinutes(tt().duration).toInt())
)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
callback.result(PumpEnactResult(injector).success(false).comment(R.string.error)).run()
callback.result(PumpEnactResultImpl(injector).success(false).comment(R.string.error)).run()
})
}

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import androidx.annotation.DrawableRes
import com.google.gson.JsonObject
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.queue.Callback
import info.nightscout.automation.R
import org.json.JSONObject
@ -17,7 +17,7 @@ class ActionStopProcessing(injector: HasAndroidInjector) : Action(injector) {
override fun isValid(): Boolean = true
override fun doAction(callback: Callback) {
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
}
override fun toJSON(): String {

View file

@ -1,7 +1,7 @@
package info.nightscout.automation.actions
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Sources
@ -36,7 +36,7 @@ class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) {
}, {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
})
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok)).run()
callback.result(PumpEnactResultImpl(injector).success(true).comment(R.string.ok)).run()
}
override fun isValid(): Boolean = true

View file

@ -1,8 +1,8 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.ArgumentMatcher

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.Profile
@ -55,31 +56,31 @@ class TestPumpPlugin(
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResultImpl(
injector
).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResult(injector).success(true)
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
override fun specialEnableCondition(): Boolean = specialEnable

View file

@ -4,7 +4,7 @@ import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
@ -37,7 +37,7 @@ class ActionAlarmTest : TestBase() {
it.timerUtil = timerUtil
it.dateUtil = dateUtil
}
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}

View file

@ -3,7 +3,7 @@ package info.nightscout.automation.actions
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.database.transactions.Transaction
@ -35,7 +35,7 @@ class ActionNotificationTest : TestBase() {
it.rxBus = rxBus
it.repository = repository
}
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}

View file

@ -4,7 +4,7 @@ import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.TestPumpPlugin
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.entities.OfflineEvent
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
@ -157,7 +157,7 @@ ActionsTestBase : TestBaseWithProfile() {
if (it is ActionStopProcessing) {
it.rh = rh
}
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
if (it is Trigger) {

View file

@ -1,163 +1,40 @@
package info.nightscout.androidaps.data
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.interfaces.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
class PumpEnactResult(injector: HasAndroidInjector) {
interface PumpEnactResult {
@Inject lateinit var rh: ResourceHelper
init {
injector.androidInjector().inject(this)
}
var success = false // request was processed successfully (but possible no change was needed)
var enacted = false // request was processed successfully and change has been made
var comment = ""
var success: Boolean // request was processed successfully (but possible no change was needed)
var enacted: Boolean // request was processed successfully and change has been made
var comment: String
// Result of basal change
var duration = -1 // duration set [minutes]
var absolute = -1.0 // absolute rate [U/h] , isPercent = false
var percent = -1 // percent of current basal [%] (100% = current basal), isPercent = true
var isPercent = false // if true percent is used, otherwise absolute
var isTempCancel = false // if true we are canceling temp basal
var duration: Int // duration set [minutes]
var absolute: Double // absolute rate [U/h] , isPercent = false
var percent: Int // percent of current basal [%] (100% = current basal), isPercent = true
var isPercent: Boolean // if true percent is used, otherwise absolute
var isTempCancel: Boolean // if true we are canceling temp basal
// Result of treatment delivery
var bolusDelivered = 0.0 // real value of delivered insulin
var carbsDelivered = 0.0 // real value of delivered carbs
var queued = false
var bolusDelivered: Double // real value of delivered insulin
var carbsDelivered: Double // real value of delivered carbs
var queued: Boolean
fun success(success: Boolean): PumpEnactResult = this.also { this.success = success }
fun enacted(enacted: Boolean): PumpEnactResult = this.also { it.enacted = enacted }
fun comment(comment: String): PumpEnactResult = this.also { it.comment = comment }
fun comment(comment: Int): PumpEnactResult = this.also { it.comment = rh.gs(comment) }
fun duration(duration: Int): PumpEnactResult = this.also { it.duration = duration }
fun absolute(absolute: Double): PumpEnactResult = this.also { it.absolute = absolute }
fun percent(percent: Int): PumpEnactResult = this.also { it.percent = percent }
fun isPercent(isPercent: Boolean): PumpEnactResult = this.also { it.isPercent = isPercent }
fun isTempCancel(isTempCancel: Boolean): PumpEnactResult = this.also { it.isTempCancel = isTempCancel }
fun bolusDelivered(bolusDelivered: Double): PumpEnactResult = this.also { it.bolusDelivered = bolusDelivered }
fun carbsDelivered(carbsDelivered: Double): PumpEnactResult = this.also { it.carbsDelivered = carbsDelivered }
fun queued(queued: Boolean): PumpEnactResult = this.also { it.queued = queued }
fun success(success: Boolean): PumpEnactResult
fun enacted(enacted: Boolean): PumpEnactResult
fun comment(comment: String): PumpEnactResult
fun comment(comment: Int): PumpEnactResult
fun duration(duration: Int): PumpEnactResult
fun absolute(absolute: Double): PumpEnactResult
fun percent(percent: Int): PumpEnactResult
fun isPercent(isPercent: Boolean): PumpEnactResult
fun isTempCancel(isTempCancel: Boolean): PumpEnactResult
fun bolusDelivered(bolusDelivered: Double): PumpEnactResult
fun carbsDelivered(carbsDelivered: Double): PumpEnactResult
fun queued(queued: Boolean): PumpEnactResult
fun log(): String {
return "Success: " + success +
" Enacted: " + enacted +
" Comment: " + comment +
" Duration: " + duration +
" Absolute: " + absolute +
" Percent: " + percent +
" IsPercent: " + isPercent +
" IsTempCancel: " + isTempCancel +
" bolusDelivered: " + bolusDelivered +
" carbsDelivered: " + carbsDelivered +
" Queued: " + queued
}
override fun toString(): String {
var ret = rh.gs(R.string.success) + ": " + success
if (enacted) {
when {
bolusDelivered > 0 -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.configbuilder_insulin)}: $bolusDelivered ${rh.gs(R.string.insulin_unit_shortname)}"
}
isTempCancel -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.canceltemp)}"
}
isPercent -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.duration)}: $duration min"
ret += "\n${rh.gs(R.string.percent)}: $percent%"
}
else -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.duration)}: $duration min"
ret += "\n${rh.gs(R.string.absolute)}: $absolute U/h"
}
}
} else {
ret += "\n${rh.gs(R.string.comment)}: $comment"
}
return ret
}
fun toHtml(): String {
var ret = "<b>" + rh.gs(R.string.success) + "</b>: " + success
if (queued) {
ret = rh.gs(R.string.waitingforpumpresult)
} else if (enacted) {
when {
bolusDelivered > 0 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.smb_shortname) + "</b>: " + bolusDelivered + " " + rh.gs(R.string.insulin_unit_shortname)
}
isTempCancel -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment +
"<br>" + rh.gs(R.string.canceltemp)
}
isPercent && percent != -1 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.duration) + "</b>: " + duration + " min"
ret += "<br><b>" + rh.gs(R.string.percent) + "</b>: " + percent + "%"
}
absolute != -1.0 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.duration) + "</b>: " + duration + " min"
ret += "<br><b>" + rh.gs(R.string.absolute) + "</b>: " + DecimalFormatter.to2Decimal(absolute) + " U/h"
}
}
} else {
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
}
return ret
}
fun json(profile: Profile): JSONObject {
val result = JSONObject()
when {
bolusDelivered > 0 -> {
result.put("smb", bolusDelivered)
}
isTempCancel -> {
result.put("rate", 0)
result.put("duration", 0)
}
isPercent -> {
// Nightscout is expecting absolute value
val abs = Round.roundTo(profile.getBasal() * percent / 100, 0.01)
result.put("rate", abs)
result.put("duration", duration)
}
else -> {
result.put("rate", absolute)
result.put("duration", duration)
}
}
return result
}
fun log(): String
fun toHtml(): String
fun toText(): String
fun json(baseBasal: Double): JSONObject
}

View file

@ -0,0 +1,165 @@
package info.nightscout.androidaps.data
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.Round
import org.json.JSONObject
import java.lang.UnsupportedOperationException
import javax.inject.Inject
class PumpEnactResultImpl(injector: HasAndroidInjector) : PumpEnactResult {
@Inject lateinit var rh: ResourceHelper
init {
injector.androidInjector().inject(this)
}
override var success = false // request was processed successfully (but possible no change was needed)
override var enacted = false // request was processed successfully and change has been made
override var comment = ""
// Result of basal change
override var duration = -1 // duration set [minutes]
override var absolute = -1.0 // absolute rate [U/h] , isPercent = false
override var percent = -1 // percent of current basal [%] (100% = current basal), isPercent = true
override var isPercent = false // if true percent is used, otherwise absolute
override var isTempCancel = false // if true we are canceling temp basal
// Result of treatment delivery
override var bolusDelivered = 0.0 // real value of delivered insulin
override var carbsDelivered = 0.0 // real value of delivered carbs
override var queued = false
override fun success(success: Boolean): PumpEnactResultImpl = this.also { this.success = success }
override fun enacted(enacted: Boolean): PumpEnactResultImpl = this.also { it.enacted = enacted }
override fun comment(comment: String): PumpEnactResultImpl = this.also { it.comment = comment }
override fun comment(comment: Int): PumpEnactResultImpl = this.also { it.comment = rh.gs(comment) }
override fun duration(duration: Int): PumpEnactResultImpl = this.also { it.duration = duration }
override fun absolute(absolute: Double): PumpEnactResultImpl = this.also { it.absolute = absolute }
override fun percent(percent: Int): PumpEnactResultImpl = this.also { it.percent = percent }
override fun isPercent(isPercent: Boolean): PumpEnactResultImpl = this.also { it.isPercent = isPercent }
override fun isTempCancel(isTempCancel: Boolean): PumpEnactResultImpl = this.also { it.isTempCancel = isTempCancel }
override fun bolusDelivered(bolusDelivered: Double): PumpEnactResultImpl = this.also { it.bolusDelivered = bolusDelivered }
override fun carbsDelivered(carbsDelivered: Double): PumpEnactResultImpl = this.also { it.carbsDelivered = carbsDelivered }
override fun queued(queued: Boolean): PumpEnactResultImpl = this.also { it.queued = queued }
override fun log(): String {
return "Success: " + success +
" Enacted: " + enacted +
" Comment: " + comment +
" Duration: " + duration +
" Absolute: " + absolute +
" Percent: " + percent +
" IsPercent: " + isPercent +
" IsTempCancel: " + isTempCancel +
" bolusDelivered: " + bolusDelivered +
" carbsDelivered: " + carbsDelivered +
" Queued: " + queued
}
override fun toString(): String = toText()
override fun toText(): String {
var ret = rh.gs(R.string.success) + ": " + success
if (enacted) {
when {
bolusDelivered > 0 -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.configbuilder_insulin)}: $bolusDelivered ${rh.gs(R.string.insulin_unit_shortname)}"
}
isTempCancel -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.canceltemp)}"
}
isPercent -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.duration)}: $duration min"
ret += "\n${rh.gs(R.string.percent)}: $percent%"
}
else -> {
ret += "\n${rh.gs(R.string.enacted)}: $enacted"
if (comment.isNotEmpty()) ret += "\n${rh.gs(R.string.comment)}: $comment"
ret += "\n${rh.gs(R.string.duration)}: $duration min"
ret += "\n${rh.gs(R.string.absolute)}: $absolute U/h"
}
}
} else {
ret += "\n${rh.gs(R.string.comment)}: $comment"
}
return ret
}
override fun toHtml(): String {
var ret = "<b>" + rh.gs(R.string.success) + "</b>: " + success
if (queued) {
ret = rh.gs(R.string.waitingforpumpresult)
} else if (enacted) {
when {
bolusDelivered > 0 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.smb_shortname) + "</b>: " + bolusDelivered + " " + rh.gs(R.string.insulin_unit_shortname)
}
isTempCancel -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment +
"<br>" + rh.gs(R.string.canceltemp)
}
isPercent && percent != -1 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.duration) + "</b>: " + duration + " min"
ret += "<br><b>" + rh.gs(R.string.percent) + "</b>: " + percent + "%"
}
absolute != -1.0 -> {
ret += "<br><b>" + rh.gs(R.string.enacted) + "</b>: " + enacted
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
ret += "<br><b>" + rh.gs(R.string.duration) + "</b>: " + duration + " min"
ret += "<br><b>" + rh.gs(R.string.absolute) + "</b>: " + DecimalFormatter.to2Decimal(absolute) + " U/h"
}
}
} else {
if (comment.isNotEmpty()) ret += "<br><b>" + rh.gs(R.string.comment) + "</b>: " + comment
}
return ret
}
override fun json(baseBasal: Double): JSONObject {
val result = JSONObject()
when {
bolusDelivered > 0 -> {
result.put("smb", bolusDelivered)
}
isTempCancel -> {
result.put("rate", 0)
result.put("duration", 0)
}
isPercent -> {
// Nightscout is expecting absolute value
val abs = Round.roundTo(baseBasal * percent / 100, 0.01)
result.put("rate", abs)
result.put("duration", duration)
}
else -> {
result.put("rate", absolute)
result.put("duration", duration)
}
}
return result
}
}

View file

@ -1,42 +1,2 @@
package info.nightscout.androidaps.data
import android.telephony.SmsMessage
class Sms {
var phoneNumber: String
var text: String
var date: Long
var received = false
var sent = false
var processed = false
var ignored = false
constructor(message: SmsMessage) {
phoneNumber = message.originatingAddress ?: ""
text = message.messageBody
date = message.timestampMillis
received = true
}
constructor(phoneNumber: String, text: String) {
this.phoneNumber = phoneNumber
this.text = text
date = System.currentTimeMillis()
sent = true
}
constructor(other: Sms, number: String? = null) {
phoneNumber = number ?: other.phoneNumber
text = other.text
date = other.date
received = other.received
sent = other.sent
processed = other.processed
ignored = other.ignored
}
override fun toString(): String {
return "SMS from $phoneNumber: $text"
}
}

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.di
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData
@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData
@Suppress("unused")
abstract class CoreDataClassesModule {
@ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult
@ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResultImpl
@ContributesAndroidInjector abstract fun apsResultInjector(): APSResult
@ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData

View file

@ -54,8 +54,8 @@ fun buildDeviceStatus(
val requested = JSONObject()
if (lastRun.tbrSetByPump?.enacted == true) { // enacted
enacted = lastRun.request?.json()?.also {
it.put("rate", lastRun.tbrSetByPump!!.json(profile)["rate"])
it.put("duration", lastRun.tbrSetByPump!!.json(profile)["duration"])
it.put("rate", lastRun.tbrSetByPump!!.json(profile.getBasal())["rate"])
it.put("duration", lastRun.tbrSetByPump!!.json(profile.getBasal())["duration"])
it.put("received", true)
}
requested.put("duration", lastRun.request?.duration)

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.data.PumpEnactResult
interface Diaconn {
fun loadHistory(): PumpEnactResult // for history browser
fun setUserOptions(): PumpEnactResult // pump etc settings
}

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
interface SmsCommunicator {

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.rx.events.Event
class EventDismissBolusProgressIfRunning(val result: PumpEnactResult?, val id: Long?) : Event()

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.queue
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
abstract class Callback : Runnable {

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.queue.Callback
@ -48,7 +48,7 @@ abstract class Command(
abstract fun log(): String
fun cancel() {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = false
result.comment = rh.gs(R.string.connectiontimedout)
aapsLogger.debug(LTag.PUMPQUEUE, "Result cancel")

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,30 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -13,9 +13,9 @@ import org.skyscreamer.jsonassert.JSONAssert
class PumpEnactResultTest : TestBaseWithProfile() {
val injector = HasAndroidInjector {
private val injector = HasAndroidInjector {
AndroidInjector {
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}
@ -36,154 +36,167 @@ class PumpEnactResultTest : TestBaseWithProfile() {
}
@Test fun successTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.success(true)
Assert.assertEquals(true, per.success)
}
@Test fun enactedTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.enacted(true)
Assert.assertEquals(true, per.enacted)
}
@Test fun commentTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.comment("SomeComment")
Assert.assertEquals("SomeComment", per.comment)
}
@Test fun durationTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.duration(10)
Assert.assertEquals(10, per.duration.toLong())
}
@Test fun absoluteTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.absolute(11.0)
Assert.assertEquals(11.0, per.absolute, 0.01)
}
@Test fun percentTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.percent(10)
Assert.assertEquals(10, per.percent)
}
@Test fun isPercentTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.isPercent(true)
Assert.assertEquals(true, per.isPercent)
}
@Test fun isTempCancelTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.isTempCancel(true)
Assert.assertEquals(true, per.isTempCancel)
}
@Test fun bolusDeliveredTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.bolusDelivered(11.0)
Assert.assertEquals(11.0, per.bolusDelivered, 0.01)
}
@Test fun carbsDeliveredTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.carbsDelivered(11.0)
Assert.assertEquals(11.0, per.carbsDelivered, 0.01)
}
@Test fun queuedTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
per.queued(true)
Assert.assertEquals(true, per.queued)
}
@Test fun logTest() {
val per = PumpEnactResult(injector)
val per = PumpEnactResultImpl(injector)
Assert.assertEquals("Success: false Enacted: false Comment: Duration: -1 Absolute: -1.0 Percent: -1 IsPercent: false IsTempCancel: false bolusDelivered: 0.0 carbsDelivered: 0.0 Queued: false", per.log())
Assert.assertEquals(
"Success: false Enacted: false Comment: Duration: -1 Absolute: -1.0 Percent: -1 IsPercent: false IsTempCancel: false bolusDelivered: 0.0 carbsDelivered: 0.0 Queued: false",
per.log()
)
}
@Test fun toStringTest() {
var per = PumpEnactResult(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
Assert.assertEquals("""
var per = PumpEnactResultImpl(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
Assert.assertEquals(
"""
Success: false
Enacted: true
Comment: AAA
Insulin: 10.0 U
""".trimIndent(), per.toString())
per = PumpEnactResult(injector).enacted(true).isTempCancel(true).comment("AAA")
Assert.assertEquals("""
""".trimIndent(), per.toString()
)
per = PumpEnactResultImpl(injector).enacted(true).isTempCancel(true).comment("AAA")
Assert.assertEquals(
"""
Success: false
Enacted: true
Comment: AAA
Cancel temp basal
""".trimIndent(), per.toString())
per = PumpEnactResult(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
Assert.assertEquals("""
""".trimIndent(), per.toString()
)
per = PumpEnactResultImpl(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
Assert.assertEquals(
"""
Success: false
Enacted: true
Comment: AAA
Duration: 20 min
Percent: 90%
""".trimIndent(), per.toString())
per = PumpEnactResult(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
Assert.assertEquals("""
""".trimIndent(), per.toString()
)
per = PumpEnactResultImpl(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
Assert.assertEquals(
"""
Success: false
Enacted: true
Comment: AAA
Duration: 30 min
Absolute: 1.0 U/h
""".trimIndent(), per.toString())
per = PumpEnactResult(injector).enacted(false).comment("AAA")
Assert.assertEquals("""
""".trimIndent(), per.toString()
)
per = PumpEnactResultImpl(injector).enacted(false).comment("AAA")
Assert.assertEquals(
"""
Success: false
Comment: AAA
""".trimIndent(), per.toString())
""".trimIndent(), per.toString()
)
}
@Test fun toHtmlTest() {
var per: PumpEnactResult = PumpEnactResult(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
var per: PumpEnactResult = PumpEnactResultImpl(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
Assert.assertEquals("<b>Success</b>: false<br><b>Enacted</b>: true<br><b>Comment</b>: AAA<br><b>SMB</b>: 10.0 U", per.toHtml())
per = PumpEnactResult(injector).enacted(true).isTempCancel(true).comment("AAA")
per = PumpEnactResultImpl(injector).enacted(true).isTempCancel(true).comment("AAA")
Assert.assertEquals("<b>Success</b>: false<br><b>Enacted</b>: true<br><b>Comment</b>: AAA<br>Cancel temp basal", per.toHtml())
per = PumpEnactResult(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
per = PumpEnactResultImpl(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
Assert.assertEquals("<b>Success</b>: false<br><b>Enacted</b>: true<br><b>Comment</b>: AAA<br><b>Duration</b>: 20 min<br><b>Percent</b>: 90%", per.toHtml())
per = PumpEnactResult(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
per = PumpEnactResultImpl(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
Assert.assertEquals("<b>Success</b>: false<br><b>Enacted</b>: true<br><b>Comment</b>: AAA<br><b>Duration</b>: 30 min<br><b>Absolute</b>: 1.00 U/h", per.toHtml())
per = PumpEnactResult(injector).enacted(false).comment("AAA")
per = PumpEnactResultImpl(injector).enacted(false).comment("AAA")
Assert.assertEquals("<b>Success</b>: false<br><b>Comment</b>: AAA", per.toHtml())
}
@Test fun jsonTest() {
var o: JSONObject?
var per: PumpEnactResult = PumpEnactResult(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
o = per.json(validProfile)
var per: PumpEnactResult = PumpEnactResultImpl(injector).enacted(true).bolusDelivered(10.0).comment("AAA")
o = per.json(validProfile.getBasal())
JSONAssert.assertEquals("{\"smb\":10}", o, false)
per = PumpEnactResult(injector).enacted(true).isTempCancel(true).comment("AAA")
o = per.json(validProfile)
per = PumpEnactResultImpl(injector).enacted(true).isTempCancel(true).comment("AAA")
o = per.json(validProfile.getBasal())
JSONAssert.assertEquals("{\"rate\":0,\"duration\":0}", o, false)
per = PumpEnactResult(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
o = per.json(validProfile)
per = PumpEnactResultImpl(injector).enacted(true).isPercent(true).percent(90).duration(20).comment("AAA")
o = per.json(validProfile.getBasal())
JSONAssert.assertEquals("{\"rate\":0.9,\"duration\":20}", o, false)
per = PumpEnactResult(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
o = per.json(validProfile)
per = PumpEnactResultImpl(injector).enacted(true).isPercent(false).absolute(1.0).duration(30).comment("AAA")
o = per.json(validProfile.getBasal())
JSONAssert.assertEquals("{\"rate\":1,\"duration\":30}", o, false)
}
}

View file

@ -6,6 +6,7 @@ import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.interfaces.data.maintenance.PrefFormatError
import info.nightscout.interfaces.data.maintenance.PrefMetadata
import info.nightscout.interfaces.data.maintenance.Prefs
import info.nightscout.interfaces.data.maintenance.PrefsFormat
import info.nightscout.interfaces.data.maintenance.PrefsMetadataKey
import info.nightscout.interfaces.data.maintenance.PrefsStatus
import info.nightscout.shared.sharedPreferences.SP
@ -23,7 +24,6 @@ import java.io.File
class EncryptedPrefsFormatTest : TestBase() {
@Mock lateinit var rh: ResourceHelper
@Mock lateinit var sp: SP
@Mock lateinit var file: MockedFile
private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger)
@ -68,7 +68,7 @@ class EncryptedPrefsFormatTest : TestBase() {
Assert.assertEquals(prefs.values["keyB"], "2")
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, PrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.OK)
}
@ -82,7 +82,7 @@ class EncryptedPrefsFormatTest : TestBase() {
"keyB" to "2"
),
mapOf(
PrefsMetadataKey.ENCRYPTION to PrefMetadata(EncryptedPrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK)
PrefsMetadataKey.ENCRYPTION to PrefMetadata(PrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK)
)
)
encryptedFormat.savePreferences(getMockedFile(), prefs, "sikret")
@ -99,7 +99,7 @@ class EncryptedPrefsFormatTest : TestBase() {
"testpref2" to "another"
),
mapOf(
PrefsMetadataKey.ENCRYPTION to PrefMetadata(EncryptedPrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK)
PrefsMetadataKey.ENCRYPTION to PrefMetadata(PrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK)
)
)
encryptedFormat.savePreferences(getMockedFile(), prefsIn, "tajemnica")
@ -112,7 +112,7 @@ class EncryptedPrefsFormatTest : TestBase() {
Assert.assertEquals(prefsOut.values["testpref2"], "another")
Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, PrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefsOut.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.OK)
}
@ -137,7 +137,7 @@ class EncryptedPrefsFormatTest : TestBase() {
Assert.assertEquals(prefs.values.size, 0)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, PrefsStatus.OK)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, EncryptedPrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.value, PrefsFormat.FORMAT_KEY_ENC)
Assert.assertEquals(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, PrefsStatus.ERROR)
}

View file

@ -10,6 +10,7 @@ import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.ProfileSealed
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch
@ -20,9 +21,7 @@ import info.nightscout.androidaps.extensions.getCustomizedName
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ActivityNames
import info.nightscout.androidaps.interfaces.AndroidPermission
import info.nightscout.interfaces.BuildHelper
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.interfaces.Config
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.androidaps.interfaces.Profile
@ -58,6 +57,8 @@ import info.nightscout.implementation.queue.commands.CommandStartPump
import info.nightscout.implementation.queue.commands.CommandStopPump
import info.nightscout.implementation.queue.commands.CommandTempBasalAbsolute
import info.nightscout.implementation.queue.commands.CommandTempBasalPercent
import info.nightscout.interfaces.BuildHelper
import info.nightscout.interfaces.Config
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventMobileToWear
@ -145,7 +146,7 @@ class CommandQueueImplementation @Inject constructor(
}
private fun executingNowError(): PumpEnactResult =
PumpEnactResult(injector).success(false).enacted(false).comment(R.string.executing_right_now)
PumpEnactResultImpl(injector).success(false).enacted(false).comment(R.string.executing_right_now)
override fun isRunning(type: CommandType): Boolean = performing?.commandType == type
@ -268,12 +269,12 @@ class CommandQueueImplementation @Inject constructor(
.subscribeBy(
onSuccess = { result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") }
callback?.result(PumpEnactResult(injector).enacted(false).success(true))?.run()
callback?.result(PumpEnactResultImpl(injector).enacted(false).success(true))?.run()
},
onError = {
aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it)
callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).enacted(false).success(false))?.run()
}
)
}
@ -290,13 +291,13 @@ class CommandQueueImplementation @Inject constructor(
if (type == CommandType.SMB_BOLUS) {
if (bolusInQueue()) {
aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running")
callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).enacted(false).success(false))?.run()
return false
}
val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L
if (detailedBolusInfo.lastKnownBolusTime < lastBolusTime) {
aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time")
callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run()
callback?.result(PumpEnactResultImpl(injector).enacted(false).success(false))?.run()
return false
}
removeAll(CommandType.SMB_BOLUS)
@ -349,7 +350,7 @@ class CommandQueueImplementation @Inject constructor(
@Synchronized
override fun cancelAllBoluses(id: Long?) {
if (!isRunning(CommandType.BOLUS)) {
rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false), id))
rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResultImpl(injector).success(true).enacted(false), id))
}
removeAll(CommandType.BOLUS)
removeAll(CommandType.SMB_BOLUS)
@ -433,12 +434,12 @@ class CommandQueueImplementation @Inject constructor(
override fun setProfile(profile: Profile, hasNsId: Boolean, callback: Callback?): Boolean {
if (isRunning(CommandType.BASAL_PROFILE)) {
aapsLogger.debug(LTag.PUMPQUEUE, "Command is already executed")
callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run()
callback?.result(PumpEnactResultImpl(injector).success(true).enacted(false))?.run()
return false
}
if (isThisProfileSet(profile) && repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing) {
aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set")
callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run()
callback?.result(PumpEnactResultImpl(injector).success(true).enacted(false))?.run()
return false
}
// Compare with pump limits
@ -447,7 +448,7 @@ class CommandQueueImplementation @Inject constructor(
if (basalValue.value < activePlugin.activePump.pumpDescription.basalMinimumRate) {
val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, rh.gs(R.string.basal_value_below_minimum), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(R.string.basal_value_below_minimum))?.run()
callback?.result(PumpEnactResultImpl(injector).success(false).enacted(false).comment(R.string.basal_value_below_minimum))?.run()
return false
}
}

View file

@ -1,7 +1,7 @@
package info.nightscout.implementation.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.interfaces.LocalAlertUtils
import info.nightscout.androidaps.queue.Callback
@ -26,7 +26,7 @@ class CommandReadStatus(
localAlertUtils.notifyPumpStatusRead()
aapsLogger.debug(LTag.PUMPQUEUE, "CommandReadStatus executed. Reason: $reason")
val pump = activePlugin.activePump
val result = PumpEnactResult(injector).success(false)
val result = PumpEnactResultImpl(injector).success(false)
val lastConnection = pump.lastDataTime()
if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs()) result.success(true)
callback?.result(result)?.run()

View file

@ -3,6 +3,7 @@ package info.nightscout.implementation.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.queue.commands.Command
@ -28,11 +29,11 @@ class CommandSMBBolus(
aapsLogger.debug(LTag.PUMPQUEUE, "Last bolus: $lastBolusTime ${dateUtil.dateAndTimeAndSecondsString(lastBolusTime)}")
if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > dateUtil.now()) {
aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval")
r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval")
r = PumpEnactResultImpl(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval")
} else if (detailedBolusInfo.deliverAtTheLatest != 0L && detailedBolusInfo.deliverAtTheLatest + T.mins(1).msecs() > System.currentTimeMillis()) {
r = activePlugin.activePump.deliverTreatment(detailedBolusInfo)
} else {
r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB request too old")
r = PumpEnactResultImpl(injector).enacted(false).success(false).comment("SMB request too old")
aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + dateUtil.dateAndTimeString(detailedBolusInfo.deliverAtTheLatest))
}
aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}")

View file

@ -1,7 +1,7 @@
package info.nightscout.implementation.queue.commands
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
@ -33,7 +33,7 @@ class CommandSetProfile constructor(
override fun execute() {
if (commandQueue.isThisProfileSet(profile) && repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing) {
aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set. profile: $profile")
callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run()
callback?.result(PumpEnactResultImpl(injector).success(true).enacted(false))?.run()
return
}
val r = activePlugin.activePump.setNewBasalProfile(profile)

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,30 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -7,15 +7,13 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.TestPumpPlugin
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.ValueWrapper
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ActivityNames
import info.nightscout.androidaps.interfaces.AndroidPermission
import info.nightscout.interfaces.BuildHelper
import info.nightscout.interfaces.Config
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.androidaps.interfaces.ProfileFunction
@ -32,6 +30,8 @@ import info.nightscout.implementation.queue.commands.CommandCustomCommand
import info.nightscout.implementation.queue.commands.CommandExtendedBolus
import info.nightscout.implementation.queue.commands.CommandLoadHistory
import info.nightscout.implementation.queue.commands.CommandTempBasalPercent
import info.nightscout.interfaces.BuildHelper
import info.nightscout.interfaces.Config
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.logging.AAPSLogger
@ -105,7 +105,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() {
if (it is CommandLoadHistory) {
it.activePlugin = activePlugin
}
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}

View file

@ -31,33 +31,27 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.interfaces.Insight;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.rx.events.EventInitializationChanged;
import info.nightscout.rx.events.EventRefreshOverview;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.insight.R;
import info.nightscout.androidaps.insight.database.InsightBolusID;
import info.nightscout.androidaps.insight.database.InsightDbHelper;
import info.nightscout.androidaps.insight.database.InsightHistoryOffset;
import info.nightscout.androidaps.insight.database.InsightPumpID;
import info.nightscout.androidaps.insight.database.InsightPumpID.EventType;
import info.nightscout.androidaps.insight.R;
import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.interfaces.Config;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.Constraints;
import info.nightscout.androidaps.interfaces.Insight;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.Pump;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.interfaces.PumpSync.PumpState.TemporaryBasal;
import info.nightscout.rx.logging.AAPSLogger;
import info.nightscout.rx.logging.LTag
;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.androidaps.interfaces.ResourceHelper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -132,7 +126,13 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator
import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.interfaces.ResourceHelper;
import info.nightscout.interfaces.Config;
import info.nightscout.interfaces.PluginType;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventInitializationChanged;
import info.nightscout.rx.events.EventRefreshOverview;
import info.nightscout.rx.logging.AAPSLogger;
import info.nightscout.rx.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP;
@Singleton
@ -235,7 +235,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
pumpDescription = new PumpDescription();
pumpDescription.fillFor(PumpType.ACCU_CHEK_INSIGHT);
lastBolusTimestamp = sp.getLong(R.string.key_insight_last_bolus_timestamp,0L);
lastBolusTimestamp = sp.getLong(R.string.key_insight_last_bolus_timestamp, 0L);
lastBolusAmount = sp.getDouble(R.string.key_insight_last_bolus_amount, 0.0);
}
@ -475,7 +475,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
@NonNull @Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
List<BasalProfileBlock> profileBlocks = new ArrayList<>();
for (int i = 0; i < profile.getBasalValues().length; i++) {
@ -575,7 +575,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
if (detailedBolusInfo.insulin == 0 || detailedBolusInfo.carbs > 0) {
throw new IllegalArgumentException(detailedBolusInfo.toString(), new Exception());
}
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
double insulin = Math.round(detailedBolusInfo.insulin / 0.01) * 0.01;
if (insulin > 0) {
try {
@ -599,7 +599,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
int trials = 0;
long now = dateUtil.now();
String serial = serialNumber();
insightDbHelper.createOrUpdate( new InsightBolusID(
insightDbHelper.createOrUpdate(new InsightBolusID(
now,
serial,
bolusID,
@ -691,7 +691,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
@NonNull @Override
public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (activeBasalRate == null) return result;
if (activeBasalRate.getActiveBasalRate() == 0) return result;
double percent = 100D / activeBasalRate.getActiveBasalRate() * absoluteRate;
@ -741,7 +741,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
@NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
percent = (int) Math.round(((double) percent) / 10d) * 10;
if (percent == 100) return cancelTempBasal(true);
else if (percent > 250) percent = 250;
@ -797,7 +797,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes, boolean disableVibration) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
try {
DeliverBolusMessage bolusMessage = new DeliverBolusMessage();
bolusMessage.setBolusType(BolusType.EXTENDED);
@ -829,7 +829,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
@NonNull @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
PumpEnactResult cancelEBResult = null;
if (isFakingTempsByExtendedBoluses()) cancelEBResult = cancelExtendedBolusOnly();
PumpEnactResult cancelTBRResult = cancelTempBasalOnly();
@ -850,7 +850,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
private PumpEnactResult cancelTempBasalOnly() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
try {
alertService.ignore(AlertType.WARNING_36);
connectionService.requestMessage(new CancelTBRMessage()).await();
@ -893,7 +893,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
private PumpEnactResult cancelExtendedBolusOnly() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
try {
for (ActiveBolus activeBolus : activeBoluses) {
if (activeBolus.getBolusType() == BolusType.EXTENDED || activeBolus.getBolusType() == BolusType.MULTIWAVE) {
@ -1012,7 +1012,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
public PumpEnactResult stopPump() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
try {
SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage();
operatingModeMessage.setOperatingMode(OperatingMode.STOPPED);
@ -1034,7 +1034,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
public PumpEnactResult startPump() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
try {
SetOperatingModeMessage operatingModeMessage = new SetOperatingModeMessage();
operatingModeMessage.setOperatingMode(OperatingMode.STARTED);
@ -1056,7 +1056,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
}
public PumpEnactResult setTBROverNotification(boolean enabled) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
boolean valueBefore = tbrOverNotificationBlock.isEnabled();
tbrOverNotificationBlock.setEnabled(enabled);
try {
@ -1119,7 +1119,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
@NonNull @Override
public PumpEnactResult loadTDDs() {
return new PumpEnactResult(getInjector()).success(true);
return new PumpEnactResultImpl(getInjector()).success(true);
}
private void readHistory() {
@ -1213,12 +1213,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
for (TemporaryBasal temporaryBasal : temporaryBasals) {
if (temporaryBasal.getDuration() == 0L) { // for Stop TBR event duration = 0L
pumpSync.syncStopTemporaryBasalWithPumpId(
temporaryBasal.getTimestamp(),
temporaryBasal.getPumpId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
temporaryBasal.getTimestamp(),
temporaryBasal.getPumpId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
if (temporaryBasal.getRate() != 100.0){
if (temporaryBasal.getRate() != 100.0) {
pumpSync.syncTemporaryBasalWithPumpId(
temporaryBasal.getTimestamp(),
temporaryBasal.getRate(),
@ -1240,7 +1240,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
processCannulaFilledEvent(serial, (CannulaFilledEvent) event);
else if (event instanceof TotalDailyDoseEvent)
processTotalDailyDoseEvent(serial, (TotalDailyDoseEvent) event);
else if (event instanceof TubeFilledEvent) processTubeFilledEvent(serial, (TubeFilledEvent) event);
else if (event instanceof TubeFilledEvent)
processTubeFilledEvent(serial, (TubeFilledEvent) event);
else if (event instanceof SniffingDoneEvent)
processSniffingDoneEvent(serial, (SniffingDoneEvent) event);
else if (event instanceof PowerUpEvent) processPowerUpEvent(serial, (PowerUpEvent) event);
@ -1447,20 +1448,20 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight,
PumpType.ACCU_CHEK_INSIGHT,
serial);
lastBolusTimestamp = bolusID.getTimestamp();
sp.putLong(R.string.key_insight_last_bolus_timestamp,lastBolusTimestamp);
sp.putLong(R.string.key_insight_last_bolus_timestamp, lastBolusTimestamp);
lastBolusAmount = event.getImmediateAmount();
sp.putDouble(R.string.key_insight_last_bolus_amount, lastBolusAmount);
}
if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) {
if (event.getDuration() > 0 && profileFunction.getProfile(bolusID.getTimestamp()) != null)
pumpSync.syncExtendedBolusWithPumpId(
bolusID.getTimestamp(),
event.getExtendedAmount(),
timestamp - startTimestamp,
isFakingTempsByExtendedBoluses(),
bolusID.getId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
pumpSync.syncExtendedBolusWithPumpId(
bolusID.getTimestamp(),
event.getExtendedAmount(),
timestamp - startTimestamp,
isFakingTempsByExtendedBoluses(),
bolusID.getId(),
PumpType.ACCU_CHEK_INSIGHT,
serial);
}
}

View file

@ -0,0 +1,42 @@
package info.nightscout.interfaces.data.smsCommunicator
import android.telephony.SmsMessage
class Sms {
var phoneNumber: String
var text: String
var date: Long
var received = false
var sent = false
var processed = false
var ignored = false
constructor(message: SmsMessage) {
phoneNumber = message.originatingAddress ?: ""
text = message.messageBody
date = message.timestampMillis
received = true
}
constructor(phoneNumber: String, text: String) {
this.phoneNumber = phoneNumber
this.text = text
date = System.currentTimeMillis()
sent = true
}
constructor(other: Sms, number: String? = null) {
phoneNumber = number ?: other.phoneNumber
text = other.text
date = other.date
received = other.received
sent = other.sent
processed = other.processed
ignored = other.ignored
}
override fun toString(): String {
return "SMS from $phoneNumber: $text"
}
}

View file

@ -3,7 +3,7 @@ package info.nightscout.plugins.general.smsCommunicator
import android.os.SystemClock
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.interfaces.SmsCommunicator

View file

@ -5,7 +5,7 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
import info.nightscout.androidaps.interfaces.SmsCommunicator
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy

View file

@ -14,7 +14,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.annotations.OpenForTesting
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.OfflineEvent
import info.nightscout.androidaps.database.entities.TemporaryTarget

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,30 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -4,7 +4,7 @@ import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.interfaces.SmsCommunicator
import info.nightscout.plugins.general.smsCommunicator.otp.OneTimePassword

View file

@ -4,23 +4,26 @@ import android.telephony.SmsManager
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.plugins.R
import info.nightscout.androidaps.TestBaseWithProfile
import info.nightscout.androidaps.TestPumpPlugin
import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.Sms
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.transactions.CancelCurrentOfflineEventIfAnyTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction
import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.Transaction
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.androidaps.interfaces.GlucoseUnit
import info.nightscout.androidaps.interfaces.Loop
import info.nightscout.androidaps.interfaces.ProfileSource
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.XDripBroadcast
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider
@ -28,8 +31,11 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.XDripBroadcast
import info.nightscout.interfaces.PluginType
import info.nightscout.interfaces.data.smsCommunicator.Sms
import info.nightscout.plugins.R
import info.nightscout.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.rxjava3.core.Single
import org.junit.Assert
@ -40,8 +46,8 @@ import org.mockito.ArgumentMatchers.anyString
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyLong
import org.mockito.Mockito.`when`
import org.mockito.invocation.InvocationOnMock
@Suppress("SpellCheckingInspection")
@ -64,7 +70,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector {
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
if (it is AuthRequest) {
@ -98,50 +104,54 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
}))
val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtilMocked)
smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, rh, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue,
loop, iobCobCalculator, xDripBroadcast,
otp, config, dateUtilMocked, uel,
glucoseStatusProvider, repository)
smsCommunicatorPlugin = SmsCommunicatorPlugin(
injector, aapsLogger, rh, smsManager, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue,
loop, iobCobCalculator, xDripBroadcast,
otp, config, dateUtilMocked, uel,
glucoseStatusProvider, repository
)
smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true)
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(1)
callback.result = PumpEnactResult(injector).success(true)
callback.result = PumpEnactResultImpl(injector).success(true)
callback.run()
null
}.`when`(commandQueue).cancelTempBasal(ArgumentMatchers.anyBoolean(), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(0)
callback.result = PumpEnactResult(injector).success(true)
callback.result = PumpEnactResultImpl(injector).success(true)
callback.run()
null
}.`when`(commandQueue).cancelExtended(ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(1)
callback.result = PumpEnactResult(injector).success(true)
callback.result = PumpEnactResultImpl(injector).success(true)
callback.run()
null
}.`when`(commandQueue).readStatus(ArgumentMatchers.anyString(), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(1)
callback.result = PumpEnactResult(injector).success(true).bolusDelivered(1.0)
callback.result = PumpEnactResultImpl(injector).success(true).bolusDelivered(1.0)
callback.run()
null
}.`when`(commandQueue).bolus(anyObject(), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(5)
callback.result = PumpEnactResult(injector).success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.result = PumpEnactResultImpl(injector).success(true).isPercent(true).percent(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.run()
null
}.`when`(commandQueue).tempBasalPercent(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), anyObject(), ArgumentMatchers.any(Callback::class.java))
}.`when`(commandQueue)
.tempBasalPercent(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), anyObject(), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(5)
callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.result = PumpEnactResultImpl(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.run()
null
}.`when`(commandQueue).tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), anyObject(), ArgumentMatchers.any(Callback::class.java))
}.`when`(commandQueue)
.tempBasalAbsolute(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.anyBoolean(), anyObject(), anyObject(), ArgumentMatchers.any(Callback::class.java))
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(2)
callback.result = PumpEnactResult(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.result = PumpEnactResultImpl(injector).success(true).isPercent(false).absolute(invocation.getArgument(0)).duration(invocation.getArgument(1))
callback.run()
null
}.`when`(commandQueue).extendedBolus(ArgumentMatchers.anyDouble(), ArgumentMatchers.anyInt(), ArgumentMatchers.any(Callback::class.java))
@ -180,8 +190,10 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
`when`(rh.gs(R.string.loopisdisabled)).thenReturn("Loop is disabled")
`when`(rh.gs(R.string.smscommunicator_loopisenabled)).thenReturn("Loop is enabled")
`when`(rh.gs(R.string.wrong_format)).thenReturn("Wrong format")
`when`(rh.gs(eq(R.string.sms_wrong_tbr_duration), ArgumentMatchers.any())).thenAnswer { i: InvocationOnMock -> "TBR duration must be a multiple of " + i.arguments[1] + " minutes and greater than " +
"0." }
`when`(rh.gs(eq(R.string.sms_wrong_tbr_duration), ArgumentMatchers.any())).thenAnswer { i: InvocationOnMock ->
"TBR duration must be a multiple of " + i.arguments[1] + " minutes and greater than " +
"0."
}
`when`(rh.gs(R.string.smscommunicator_loophasbeendisabled)).thenReturn("Loop has been disabled")
`when`(rh.gs(R.string.smscommunicator_loophasbeenenabled)).thenReturn("Loop has been enabled")
`when`(rh.gs(R.string.smscommunicator_tempbasalcanceled)).thenReturn("Temp basal canceled")

View file

@ -2,7 +2,7 @@ package info.nightscout.plugins.general.smsCommunicator
import android.telephony.SmsMessage
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.Sms
import info.nightscout.interfaces.data.smsCommunicator.Sms
import org.junit.Assert
import org.junit.Test
import org.mockito.Mockito

View file

@ -24,12 +24,12 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.combo.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.extensions.PumpStateExtensionKt;
import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.Constraints;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.Pump;
@ -59,6 +59,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.InstanceId;
import info.nightscout.androidaps.utils.T;
import info.nightscout.interfaces.PluginType;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventInitializationChanged;
import info.nightscout.rx.events.EventRefreshOverview;
@ -180,7 +181,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
@Override protected void onStart() {
super.onStart();
OPERATION_NOT_SUPPORTED = new PumpEnactResult(getInjector())
OPERATION_NOT_SUPPORTED = new PumpEnactResultImpl(getInjector())
.success(false).enacted(false).comment(R.string.combo_pump_unsupported_operation);
}
@ -267,7 +268,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
getAapsLogger().error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, getRh().gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.pumpNotInitializedProfileNotSet);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(R.string.pumpNotInitializedProfileNotSet);
}
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
@ -275,12 +276,12 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
//dismiss previously "FAILED" overview notifications
rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
rxBus.send(new EventDismissNotification(Notification.FAILED_UPDATE_PROFILE));
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState);
if (stateResult.state.unsafeUsageDetected == PumpState.UNSUPPORTED_BASAL_RATE_PROFILE) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.combo_force_disabled_notification);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(R.string.combo_force_disabled_notification);
}
CommandResult setResult = runCommand(getRh().gs(R.string.combo_activity_setting_basal_profile), 2,
@ -288,7 +289,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UPDATE_PROFILE, getRh().gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(R.string.failedupdatebasalprofile);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(R.string.failedupdatebasalprofile);
}
pump.basalProfile = requestedBasalProfile;
@ -299,7 +300,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
//issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, getRh().gs(R.string.profile_set_ok), Notification.INFO, 60);
rxBus.send(new EventNewNotification(notification));
return new PumpEnactResult(getInjector()).success(true).enacted(true);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(true);
}
@Override
@ -512,16 +513,16 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
// check pump is ready and all pump bolus records are known
CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1));
if (!stateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_error_no_connection_no_bolus_delivered);
}
if (stateResult.reservoirLevel != -1 && stateResult.reservoirLevel - 0.5 < detailedBolusInfo.insulin) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_reservoir_level_insufficient_for_bolus);
}
// the commands above ensured a connection was made, which updated this field
if (pumpHistoryChanged) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_bolus_rejected_due_to_pump_history_change);
}
@ -534,7 +535,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01
&& previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) {
getAapsLogger().debug(LTag.PUMP, "Bolus request rejected, same bolus was successfully delivered very recently");
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.bolus_frequency_exceeded);
}
@ -547,10 +548,10 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
while (previousBolus.timestamp == timeCheckResult.state.pumpTime
&& maxWaitTimeout > System.currentTimeMillis()) {
if (cancelBolus) {
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
if (!timeCheckResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_error_no_connection_no_bolus_delivered);
}
getAapsLogger().debug(LTag.PUMP, "Waiting for pump clock to advance for the next unused bolus record timestamp");
@ -564,7 +565,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
}
if (cancelBolus) {
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
EventOverviewBolusProgress.Treatment treatment = new EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.getId());
@ -584,7 +585,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
// (reads 2 records to update `recentBoluses` further down)
CommandResult postBolusStateResult = runCommand(null, 3, () -> ruffyScripter.readQuickInfo(2));
if (!postBolusStateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_error_bolus_verification_failed);
}
Bolus lastPumpBolus = postBolusStateResult.history != null && !postBolusStateResult.history.bolusHistory.isEmpty()
@ -594,9 +595,9 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
// no bolus delivered?
if (lastPumpBolus == null || lastPumpBolus.equals(previousBolus)) {
if (cancelBolus) {
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
} else {
return new PumpEnactResult(getInjector())
return new PumpEnactResultImpl(getInjector())
.success(false)
.enacted(false)
.comment(R.string.combo_error_no_bolus_delivered);
@ -605,7 +606,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
// at least some insulin delivered, so add it to treatments
if (!addBolusToTreatments(detailedBolusInfo, lastPumpBolus))
return new PumpEnactResult(getInjector()).success(false).enacted(true)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(true)
.comment(R.string.combo_error_updating_treatment_record);
// check pump bolus record has a sane timestamp
@ -622,16 +623,16 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
// only a partial bolus was delivered
if (Math.abs(lastPumpBolus.amount - detailedBolusInfo.insulin) > 0.01) {
if (cancelBolus) {
return new PumpEnactResult(getInjector()).success(true).enacted(true);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(true);
}
return new PumpEnactResult(getInjector()).success(false).enacted(true)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(true)
.comment(getRh().gs(R.string.combo_error_partial_bolus_delivered,
lastPumpBolus.amount, detailedBolusInfo.insulin));
}
// full bolus was delivered successfully
incrementBolusCount();
return new PumpEnactResult(getInjector())
return new PumpEnactResultImpl(getInjector())
.success(true)
.enacted(lastPumpBolus.amount > 0)
.bolusDelivered(lastPumpBolus.amount)
@ -732,7 +733,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min");
if (pumpHistoryChanged && percent > 110) {
return new PumpEnactResult(getInjector()).success(false).enacted(false)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false)
.comment(R.string.combo_high_temp_rejected_due_to_pump_history_changes);
}
@ -758,7 +759,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
CommandResult commandResult = runCommand(getRh().gs(R.string.combo_pump_action_setting_tbr, percent, durationInMinutes),
3, () -> ruffyScripter.setTbr(finalAdjustedPercent, durationInMinutes));
if (!commandResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false);
}
PumpState state = commandResult.state;
@ -784,7 +785,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
}
incrementTbrCount();
return new PumpEnactResult(getInjector()).success(true).enacted(true).isPercent(true)
return new PumpEnactResultImpl(getInjector()).success(true).enacted(true).isPercent(true)
.percent(state.tbrPercent).duration(state.tbrRemainingDuration);
}
@ -808,15 +809,15 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
if (enforceNew) {
CommandResult stateResult = runCommand(getRh().gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
if (!stateResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false);
}
if (!stateResult.state.tbrActive) {
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: hard-cancelling TBR since force requested");
CommandResult cancelResult = runCommand(getRh().gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
if (!cancelResult.success) {
return new PumpEnactResult(getInjector()).success(false).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false);
}
if (!cancelResult.state.tbrActive) {
pumpSync.syncStopTemporaryBasalWithPumpId(
@ -826,19 +827,19 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
PumpType.ACCU_CHEK_COMBO,
serialNumber()
);
return new PumpEnactResult(getInjector()).isTempCancel(true).success(true).enacted(true);
return new PumpEnactResultImpl(getInjector()).isTempCancel(true).success(true).enacted(true);
} else {
return new PumpEnactResult(getInjector()).success(false).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false);
}
} else if (activeTemp == null) {
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
} else if ((activeTemp.getRate() >= 90 && activeTemp.getRate() <= 110)
&& PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) <= 15) {
// Let fake neutral temp keep run (see below)
// Note that since this runs on the queue a connection is opened regardless, but this
// case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR).
getAapsLogger().debug(LTag.PUMP, "cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.getRate() + "% and running for another " + PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) + " mins.");
return new PumpEnactResult(getInjector()).success(true).enacted(true)
return new PumpEnactResultImpl(getInjector()).success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.getRate() + "% and running for another "
+ PumpStateExtensionKt.getPlannedRemainingMinutes(activeTemp) + " mins.");
@ -1364,7 +1365,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints {
@NonNull @Override
public PumpEnactResult loadTDDs() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(readHistory(new PumpHistoryRequest().tddHistory(PumpHistoryRequest.FULL)));
if (result.getSuccess()) {
List<Tdd> tdds = pump.tddHistory;

View file

@ -5,8 +5,13 @@ import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.combo.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.RuffyScripter
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus
import info.nightscout.androidaps.utils.DateUtil
@ -33,7 +38,7 @@ class ComboPluginTest : TestBase() {
val injector = HasAndroidInjector {
AndroidInjector {
if (it is PumpEnactResult) {
if (it is PumpEnactResultImpl) {
it.rh = rh
}
}

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
@Suppress("SpellCheckingInspection")
open class TestBase {

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -12,12 +12,12 @@ import info.nightscout.androidaps.danar.AbstractDanaRPlugin
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.PumpSync.TemporaryBasalType
@ -27,6 +27,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.Round
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventAppExit
@ -69,14 +70,14 @@ class DanaRKoreanPlugin @Inject constructor(
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
if (isEnabled(PluginType.PUMP)) {
val previousValue = useExtendedBoluses
useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false)
if (useExtendedBoluses != previousValue && pumpSync.expectedPumpState().extendedBolus != null) {
sExecutionService.extendedBolusStop()
}
}
}, fabricPrivacy::logException)
if (isEnabled(PluginType.PUMP)) {
val previousValue = useExtendedBoluses
useExtendedBoluses = sp.getBoolean(R.string.key_danar_useextended, false)
if (useExtendedBoluses != previousValue && pumpSync.expectedPumpState().extendedBolus != null) {
sExecutionService.extendedBolusStop()
}
}
}, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
@ -130,9 +131,11 @@ class DanaRKoreanPlugin @Inject constructor(
val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.id)
var connectionOK = false
if (detailedBolusInfo.insulin > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, detailedBolusInfo.carbs.toInt(), detailedBolusInfo.carbsTimestamp
?: detailedBolusInfo.timestamp, t)
val result = PumpEnactResult(injector)
connectionOK = sExecutionService.bolus(
detailedBolusInfo.insulin, detailedBolusInfo.carbs.toInt(), detailedBolusInfo.carbsTimestamp
?: detailedBolusInfo.timestamp, t
)
val result = PumpEnactResultImpl(injector)
result.success(connectionOK && abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep)
.bolusDelivered(t.insulin)
if (!result.success) result.comment(rh.gs(R.string.boluserrorcode, detailedBolusInfo.insulin, t.insulin, danaPump.bolusStartErrorCode)) else result.comment(R.string.ok)
@ -149,7 +152,7 @@ class DanaRKoreanPlugin @Inject constructor(
)
result
} else {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success(false).bolusDelivered(0.0).carbsDelivered(0.0).comment(R.string.invalidinput)
aapsLogger.error("deliverTreatment: Invalid input")
result
@ -160,7 +163,6 @@ class DanaRKoreanPlugin @Inject constructor(
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult {
// Recheck pump status if older than 30 min
//This should not be needed while using queue because connection should be done before calling this
var result = PumpEnactResult(injector)
val absoluteRateAfterConstraint = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value()
var doTempOff = baseBasalRate - absoluteRateAfterConstraint == 0.0 && absoluteRateAfterConstraint >= 0.10
val doLowTemp = absoluteRateAfterConstraint < baseBasalRate || absoluteRateAfterConstraint < 0.10
@ -189,15 +191,14 @@ class DanaRKoreanPlugin @Inject constructor(
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)")
return cancelRealTempBasal()
}
result.success(true).enacted(false).percent(100).isPercent(true).isTempCancel(true)
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK")
return result
return PumpEnactResultImpl(injector).success(true).enacted(false).percent(100).isPercent(true).isTempCancel(true)
}
if (doLowTemp || doHighTemp) {
// If extended in progress
if (danaPump.isExtendedInProgress && useExtendedBoluses) {
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)")
result = cancelExtendedBolus()
val result = cancelExtendedBolus()
if (!result.success) {
aapsLogger.error("setTempBasalAbsolute: Failed to stop previous extended bolus (doLowTemp || doHighTemp)")
return result
@ -211,9 +212,8 @@ class DanaRKoreanPlugin @Inject constructor(
if (enforceNew) {
cancelTempBasal(true)
} else {
result.success(true).percent(percentRate).enacted(false).duration(danaPump.tempBasalRemainingMin).isPercent(true).isTempCancel(false)
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)")
return result
return PumpEnactResultImpl(injector).success(true).percent(percentRate).enacted(false).duration(danaPump.tempBasalRemainingMin).isPercent(true).isTempCancel(false)
}
}
}
@ -225,7 +225,7 @@ class DanaRKoreanPlugin @Inject constructor(
// Check if some temp is already in progress
if (danaPump.isTempBasalInProgress) {
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)")
result = cancelRealTempBasal()
val result = cancelRealTempBasal()
// Check for proper result
if (!result.success) {
aapsLogger.error("setTempBasalAbsolute: Failed to stop previous temp basal (doExtendedTemp)")
@ -242,21 +242,24 @@ class DanaRKoreanPlugin @Inject constructor(
extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2) // *2 because of half hours
// What is current rate of extended bolusing in u/h?
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Extended bolus in progress: " + danaPump.isExtendedInProgress + " rate: " + danaPump.extendedBolusAbsoluteRate + "U/h duration remaining: " + danaPump.extendedBolusRemainingMinutes + "min")
aapsLogger.debug(
LTag.PUMP,
"setTempBasalAbsolute: Extended bolus in progress: " + danaPump.isExtendedInProgress + " rate: " + danaPump.extendedBolusAbsoluteRate + "U/h duration remaining: " + danaPump.extendedBolusRemainingMinutes + "min"
)
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h")
// Compare with extended rate in progress
if (danaPump.isExtendedInProgress && abs(danaPump.extendedBolusAbsoluteRate - extendedRateToSet) < pumpDescription.extendedBolusStep) {
// correct extended already set
result.success(true).absolute(danaPump.extendedBolusAbsoluteRate).enacted(false).duration(danaPump.extendedBolusRemainingMinutes).isPercent(false).isTempCancel(false)
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Correct extended already set")
return result
return PumpEnactResultImpl(injector).success(true).absolute(danaPump.extendedBolusAbsoluteRate).enacted(false).duration(danaPump.extendedBolusRemainingMinutes).isPercent(false)
.isTempCancel(false)
}
// Now set new extended, no need to to stop previous (if running) because it's replaced
val extendedAmount = extendedRateToSet / 2 * durationInHalfHours
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Setting extended: " + extendedAmount + "U half hours: " + durationInHalfHours)
result = setExtendedBolus(extendedAmount, durationInMinutes)
val result = setExtendedBolus(extendedAmount, durationInMinutes)
if (!result.success) {
aapsLogger.error("setTempBasalAbsolute: Failed to set extended bolus")
return result
@ -267,8 +270,7 @@ class DanaRKoreanPlugin @Inject constructor(
}
// We should never end here
aapsLogger.error("setTempBasalAbsolute: Internal error")
result.success(false).comment("Internal error")
return result
return PumpEnactResultImpl(injector).success(false).comment("Internal error")
}
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
@ -276,7 +278,7 @@ class DanaRKoreanPlugin @Inject constructor(
if (danaPump.isExtendedInProgress && useExtendedBoluses) {
return cancelExtendedBolus()
}
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success(true).enacted(false).comment(R.string.ok).isTempCancel(true)
return result
}
@ -284,7 +286,7 @@ class DanaRKoreanPlugin @Inject constructor(
override fun model(): PumpType = PumpType.DANA_R_KOREAN
private fun cancelRealTempBasal(): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (danaPump.isTempBasalInProgress) {
sExecutionService.tempBasalStop()
if (!danaPump.isTempBasalInProgress) {
@ -303,6 +305,6 @@ class DanaRKoreanPlugin @Inject constructor(
return result
}
override fun loadEvents(): PumpEnactResult = PumpEnactResult(injector) // no history, not needed
override fun setUserOptions(): PumpEnactResult = PumpEnactResult(injector)
override fun loadEvents(): PumpEnactResult = PumpEnactResultImpl(injector) // no history, not needed
override fun setUserOptions(): PumpEnactResult = PumpEnactResultImpl(injector)
}

View file

@ -18,6 +18,7 @@ import info.nightscout.androidaps.danar.AbstractDanaRPlugin;
import info.nightscout.androidaps.danar.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.androidaps.interfaces.Constraint;
@ -189,7 +190,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
boolean connectionOK = false;
if (detailedBolusInfo.insulin > 0 || carbs > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) carbs, carbTimeStamp, t);
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(connectionOK && Math.abs(detailedBolusInfo.insulin - t.getInsulin()) < pumpDescription.getBolusStep())
.bolusDelivered(t.getInsulin())
.carbsDelivered(detailedBolusInfo.carbs);
@ -202,7 +203,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
// remove carbs because it's get from history separately
return result;
} else {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(false).bolusDelivered(0d).carbsDelivered(0d).comment(R.string.invalidinput);
aapsLogger.error("deliverTreatment: Invalid input");
return result;
@ -222,7 +223,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
@NonNull @Override
public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value();
@ -289,7 +290,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
@NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
DanaPump pump = danaPump;
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value();
if (percent < 0) {
result.isTempCancel(false).enacted(false).success(false).comment(R.string.invalidinput);
@ -323,7 +324,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
private PumpEnactResult setHighTempBasalPercent(Integer percent, int durationInMinutes) {
DanaPump pump = danaPump;
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
boolean connectionOK = sExecutionService.highTempBasal(percent, durationInMinutes);
if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) {
result.enacted(true).success(true).comment(R.string.ok).isTempCancel(false).duration(pump.getTempBasalRemainingMin()).percent(pump.getTempBasalPercent()).isPercent(true);
@ -337,7 +338,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
@NonNull @Override
public PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isTempBasalInProgress()) {
sExecutionService.tempBasalStop();
result.enacted(true).isTempCancel(true);
@ -356,7 +357,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
insulin = Round.INSTANCE.roundTo(insulin, getPumpDescription().getExtendedBolusStep());
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isExtendedInProgress() && Math.abs(danaPump.getExtendedBolusAmount() - insulin) < pumpDescription.getExtendedBolusStep()) {
result.enacted(false)
.success(true)
@ -389,7 +390,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
@NonNull @Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isExtendedInProgress()) {
sExecutionService.extendedBolusStop();
result.enacted(true).success(!danaPump.isExtendedInProgress()).isTempCancel(true);

View file

@ -50,6 +50,7 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePlugin;
@ -429,14 +430,14 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
public PumpEnactResult loadEvents() {
if (!danaRv2Plugin.isInitialized()) {
PumpEnactResult result = new PumpEnactResult(injector).success(false);
PumpEnactResult result = new PumpEnactResultImpl(injector).success(false);
result.comment("pump not initialized");
return result;
}
if (!isConnected())
return new PumpEnactResult(injector).success(false);
return new PumpEnactResultImpl(injector).success(false);
SystemClock.sleep(300);
MsgHistoryEventsV2 msg = new MsgHistoryEventsV2(injector, danaPump.lastHistoryFetched);
aapsLogger.debug(LTag.PUMP, "Loading event history from: " + dateUtil.dateAndTimeString(danaPump.lastHistoryFetched));
@ -451,7 +452,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
else
danaPump.lastHistoryFetched = 0;
danaPump.setLastConnection(System.currentTimeMillis());
return new PumpEnactResult(injector).success(true);
return new PumpEnactResultImpl(injector).success(true);
}
public boolean updateBasalsInPump(final Profile profile) {
@ -470,12 +471,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
public PumpEnactResult setUserOptions() {
if (!isConnected())
return new PumpEnactResult(injector).success(false);
return new PumpEnactResultImpl(injector).success(false);
SystemClock.sleep(300);
MsgSetUserOptions msg = new MsgSetUserOptions(injector);
mSerialIOThread.sendMessage(msg);
SystemClock.sleep(200);
return new PumpEnactResult(injector).success(!msg.getFailed());
return new PumpEnactResultImpl(injector).success(!msg.getFailed());
}
}

View file

@ -11,6 +11,7 @@ import info.nightscout.androidaps.dana.DanaPump;
import info.nightscout.androidaps.dana.comm.RecordTypes;
import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.extensions.PumpStateExtensionKt;
import info.nightscout.androidaps.interfaces.ActivePlugin;
@ -19,7 +20,6 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.Constraints;
import info.nightscout.androidaps.interfaces.Dana;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.Pump;
import info.nightscout.androidaps.interfaces.PumpDescription;
@ -33,6 +33,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.interfaces.PluginType;
import info.nightscout.rx.AapsSchedulers;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventConfigBuilderChange;
@ -135,7 +136,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
// Pump interface
@NonNull @Override
public PumpEnactResult setNewBasalProfile(@NonNull Profile profile) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (sExecutionService == null) {
getAapsLogger().error("setNewBasalProfile sExecutionService is null");
@ -215,7 +216,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
@NonNull @Override
public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value();
if (percent < 0) {
result.isTempCancel(false).enacted(false).success(false).comment(R.string.invalidinput);
@ -268,7 +269,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
insulin = Round.INSTANCE.roundTo(insulin, getPumpDescription().getExtendedBolusStep());
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isExtendedInProgress() && Math.abs(danaPump.getExtendedBolusAmount() - insulin) < getPumpDescription().getExtendedBolusStep()) {
result.enacted(false)
.success(true)
@ -319,7 +320,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump
@NonNull @Override
public PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isExtendedInProgress()) {
sExecutionService.extendedBolusStop();
if (!danaPump.isExtendedInProgress()) {

View file

@ -16,12 +16,12 @@ import info.nightscout.androidaps.dana.DanaPump;
import info.nightscout.androidaps.danar.services.DanaRExecutionService;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.Constraints;
import info.nightscout.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.interfaces.ResourceHelper;
@ -30,6 +30,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.interfaces.PluginType;
import info.nightscout.rx.AapsSchedulers;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventAppExit;
@ -165,7 +166,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
boolean connectionOK = false;
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.getCarbsTimestamp() != null ? detailedBolusInfo.getCarbsTimestamp() : detailedBolusInfo.timestamp, t);
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(connectionOK && Math.abs(detailedBolusInfo.insulin - t.getInsulin()) < pumpDescription.getBolusStep())
.bolusDelivered(t.getInsulin())
.carbsDelivered(detailedBolusInfo.carbs);
@ -193,7 +194,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
serialNumber());
return result;
} else {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(false).bolusDelivered(0d).carbsDelivered(0d).comment(R.string.invalidinput);
aapsLogger.error("deliverTreatment: Invalid input");
return result;
@ -205,7 +206,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) {
// Recheck pump status if older than 30 min
//This should not be needed while using queue because connection should be done before calling this
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
absoluteRate = constraints.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value();
@ -327,7 +328,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
if (danaPump.isExtendedInProgress() && useExtendedBoluses) {
return cancelExtendedBolus();
}
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
result.success(true).enacted(false).comment(R.string.ok).isTempCancel(true);
return result;
}
@ -338,7 +339,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
}
private PumpEnactResult cancelRealTempBasal() {
PumpEnactResult result = new PumpEnactResult(getInjector());
PumpEnactResult result = new PumpEnactResultImpl(getInjector());
if (danaPump.isTempBasalInProgress()) {
sExecutionService.tempBasalStop();
if (!danaPump.isTempBasalInProgress()) {
@ -360,7 +361,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
@NonNull @Override
public PumpEnactResult loadEvents() {
return new PumpEnactResult(getInjector()); // no history, not needed
return new PumpEnactResultImpl(getInjector()); // no history, not needed
}
@NonNull @Override

View file

@ -40,6 +40,7 @@ import info.nightscout.androidaps.danar.comm.MsgHistorySuspend;
import info.nightscout.androidaps.danar.comm.MsgPCCommStart;
import info.nightscout.androidaps.danar.comm.MsgPCCommStop;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.Profile;
@ -241,7 +242,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService {
}
public PumpEnactResult loadHistory(byte type) {
PumpEnactResult result = new PumpEnactResult(injector);
PumpEnactResult result = new PumpEnactResultImpl(injector);
if (!isConnected()) return result;
MessageBase msg = null;
switch (type) {

View file

@ -45,6 +45,7 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBasic;
import info.nightscout.androidaps.danar.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.CommandQueue;
@ -396,11 +397,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
public PumpEnactResult setUserOptions() {
if (!isConnected())
return new PumpEnactResult(injector).success(false);
return new PumpEnactResultImpl(injector).success(false);
SystemClock.sleep(300);
MsgSetUserOptions msg = new MsgSetUserOptions(injector);
mSerialIOThread.sendMessage(msg);
SystemClock.sleep(200);
return new PumpEnactResult(injector).success(!msg.getFailed());
return new PumpEnactResultImpl(injector).success(!msg.getFailed());
}
}

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
@Suppress("SpellCheckingInspection")
open class TestBase {

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,26 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.danars.events.EventDanaRSDeviceChange
import info.nightscout.androidaps.danars.services.DanaRSService
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.interfaces.CommandQueue
@ -22,7 +23,6 @@ import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.androidaps.interfaces.Dana
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.Pump
@ -44,6 +44,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventAppExit
@ -124,9 +125,9 @@ class DanaRSPlugin @Inject constructor(
.toObservable(EventDanaRSDeviceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
pumpSync.connectNewPump()
changePump()
}, fabricPrivacy::logException)
pumpSync.connectNewPump()
changePump()
}, fabricPrivacy::logException)
changePump() // load device name
}
@ -185,15 +186,15 @@ class DanaRSPlugin @Inject constructor(
// DanaR interface
override fun loadHistory(type: Byte): PumpEnactResult {
return danaRSService?.loadHistory(type) ?: PumpEnactResult(injector).success(false)
return danaRSService?.loadHistory(type) ?: PumpEnactResultImpl(injector).success(false)
}
override fun loadEvents(): PumpEnactResult {
return danaRSService?.loadEvents() ?: PumpEnactResult(injector).success(false)
return danaRSService?.loadEvents() ?: PumpEnactResultImpl(injector).success(false)
}
override fun setUserOptions(): PumpEnactResult {
return danaRSService?.setUserSettings() ?: PumpEnactResult(injector).success(false)
return danaRSService?.setUserSettings() ?: PumpEnactResultImpl(injector).success(false)
}
// Constraints interface
@ -228,7 +229,7 @@ class DanaRSPlugin @Inject constructor(
danaRSService?.isConnected ?: false || danaRSService?.isConnecting ?: false
override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (!isInitialized()) {
aapsLogger.error("setNewBasalProfile not initialized")
val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, rh.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT)
@ -304,7 +305,7 @@ class DanaRSPlugin @Inject constructor(
var connectionOK = false
if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = danaRSService?.bolus(detailedBolusInfo.insulin, carbs.toInt(), carbTimeStamp, t)
?: false
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = connectionOK && abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep
result.bolusDelivered = t.insulin
result.carbsDelivered = detailedBolusInfo.carbs
@ -321,7 +322,7 @@ class DanaRSPlugin @Inject constructor(
aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered)
result
} else {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = false
result.bolusDelivered = 0.0
result.carbsDelivered = 0.0
@ -338,7 +339,6 @@ class DanaRSPlugin @Inject constructor(
// This is called from APS
@Synchronized
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
var result = PumpEnactResult(injector)
val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value()
var doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0
val doLowTemp = absoluteAfterConstrain < baseBasalRate
@ -363,13 +363,13 @@ class DanaRSPlugin @Inject constructor(
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)")
return cancelTempBasal(false)
}
result.success = true
result.enacted = false
result.percent = 100
result.isPercent = true
result.isTempCancel = true
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK")
return result
return PumpEnactResultImpl(injector)
.success(true)
.enacted(false)
.percent(100)
.isPercent(true)
.isTempCancel(true)
}
if (doLowTemp || doHighTemp) {
// Check if some temp is already in progress
@ -378,21 +378,21 @@ class DanaRSPlugin @Inject constructor(
// Correct basal already set ?
if (danaPump.tempBasalPercent == percentRate && danaPump.tempBasalRemainingMin > 4) {
if (!enforceNew) {
result.success = true
result.percent = percentRate
result.enacted = false
result.duration = danaPump.tempBasalRemainingMin
result.isPercent = true
result.isTempCancel = false
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)")
return result
return PumpEnactResultImpl(injector)
.success(true)
.percent(percentRate)
.enacted(false)
.duration(danaPump.tempBasalRemainingMin)
.isPercent(true)
.isTempCancel(false)
}
}
}
temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil.now(), T.mins(durationInMinutes.toLong()).msecs(), percentRate.toDouble(), false, tbrType, 0L, 0L))
// Convert duration from minutes to hours
aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal $percentRate% for $durationInMinutes minutes (doLowTemp || doHighTemp)")
result = if (percentRate == 0 && durationInMinutes > 30) {
val result = if (percentRate == 0 && durationInMinutes > 30) {
setTempBasalPercent(percentRate, durationInMinutes, profile, enforceNew, tbrType)
} else {
// use special APS temp basal call ... 100+/15min .... 100-/30min
@ -407,14 +407,14 @@ class DanaRSPlugin @Inject constructor(
}
// We should never end here
aapsLogger.error("setTempBasalAbsolute: Internal error")
result.success = false
result.comment = "Internal error"
return result
return PumpEnactResultImpl(injector)
.success(false)
.comment("Internal error")
}
@Synchronized
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
var percentAfterConstraint = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value()
if (percentAfterConstraint < 0) {
result.isTempCancel = false
@ -463,7 +463,7 @@ class DanaRSPlugin @Inject constructor(
}
@Synchronized private fun setHighTempBasalPercent(percent: Int): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
val connectionOK = danaRSService?.highTempBasal(percent) ?: false
if (connectionOK && danaPump.isTempBasalInProgress && danaPump.tempBasalPercent == percent) {
result.enacted = true
@ -489,7 +489,7 @@ class DanaRSPlugin @Inject constructor(
// needs to be rounded
val durationInHalfHours = max(durationInMinutes / 30, 1)
insulinAfterConstraint = Round.roundTo(insulinAfterConstraint, pumpDescription.extendedBolusStep)
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (danaPump.isExtendedInProgress && abs(danaPump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) {
result.enacted = false
result.success = true
@ -524,7 +524,7 @@ class DanaRSPlugin @Inject constructor(
@Synchronized
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (danaPump.isTempBasalInProgress) {
danaRSService?.tempBasalStop()
result.success = !danaPump.isTempBasalInProgress
@ -541,7 +541,7 @@ class DanaRSPlugin @Inject constructor(
}
@Synchronized override fun cancelExtendedBolus(): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (danaPump.isExtendedInProgress) {
danaRSService?.extendedBolusStop()
result.success = !danaPump.isExtendedInProgress

View file

@ -56,6 +56,7 @@ import info.nightscout.androidaps.danars.comm.DanaRSPacketOptionSetPumpTime
import info.nightscout.androidaps.danars.comm.DanaRSPacketOptionSetPumpUTCAndTimeZone
import info.nightscout.androidaps.danars.comm.DanaRSPacketOptionSetUserOption
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePlugin
@ -260,7 +261,7 @@ class DanaRSService : DaggerService() {
fun loadEvents(): PumpEnactResult {
if (!danaRSPlugin.isInitialized()) {
val result = PumpEnactResult(injector).success(false)
val result = PumpEnactResultImpl(injector).success(false)
result.comment = "pump not initialized"
return result
}
@ -282,13 +283,13 @@ class DanaRSService : DaggerService() {
rxBus.send(EventPumpStatusChanged(rh.gs(R.string.gettingpumpstatus)))
sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector))
danaPump.lastConnection = System.currentTimeMillis()
return PumpEnactResult(injector).success(msg.success())
return PumpEnactResultImpl(injector).success(msg.success())
}
fun setUserSettings(): PumpEnactResult {
val message = DanaRSPacketOptionSetUserOption(injector)
sendMessage(message)
return PumpEnactResult(injector).success(message.success())
return PumpEnactResultImpl(injector).success(message.success())
}
fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean {
@ -498,7 +499,7 @@ class DanaRSService : DaggerService() {
}
fun loadHistory(type: Byte): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (!isConnected) return result
var msg: DanaRSPacketHistory? = null
when (type) {

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
@Suppress("SpellCheckingInspection")
open class TestBase {

View file

@ -11,6 +11,7 @@ import androidx.preference.PreferenceFragmentCompat
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.diaconn.events.EventDiaconnG8DeviceChange
import info.nightscout.androidaps.diaconn.service.DiaconnG8Service
import info.nightscout.androidaps.extensions.convertedToAbsolute
@ -20,7 +21,6 @@ import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.Constraints
import info.nightscout.androidaps.interfaces.Diaconn
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.Pump
@ -44,6 +44,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventAppExit
@ -77,14 +78,15 @@ class DiaconnG8Plugin @Inject constructor(
private val fabricPrivacy: FabricPrivacy,
private val dateUtil: DateUtil,
private val aapsSchedulers: AapsSchedulers
) : PumpPluginBase(PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(DiaconnG8Fragment::class.java.name)
.pluginIcon(R.drawable.ic_diaconn_g8)
.pluginName(R.string.diaconn_g8_pump)
.shortName(R.string.diaconn_g8_pump_shortname)
.preferencesId(R.xml.pref_diaconn)
.description(R.string.description_pump_diaconn_g8),
) : PumpPluginBase(
PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(DiaconnG8Fragment::class.java.name)
.pluginIcon(R.drawable.ic_diaconn_g8)
.pluginName(R.string.diaconn_g8_pump)
.shortName(R.string.diaconn_g8_pump_shortname)
.preferencesId(R.xml.pref_diaconn)
.description(R.string.description_pump_diaconn_g8),
injector, aapsLogger, rh, commandQueue
), Pump, Diaconn, Constraints {
@ -99,19 +101,19 @@ class DiaconnG8Plugin @Inject constructor(
val intent = Intent(context, DiaconnG8Service::class.java)
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
disposable.add(rxBus
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ context.unbindService(mConnection) }) { fabricPrivacy.logException(it) }
.toObservable(EventAppExit::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ context.unbindService(mConnection) }) { fabricPrivacy.logException(it) }
)
disposable.add(rxBus
.toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe { diaconnG8Pump.reset() }
.toObservable(EventConfigBuilderChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe { diaconnG8Pump.reset() }
)
disposable.add(rxBus
.toObservable(EventDiaconnG8DeviceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ changePump() }) { fabricPrivacy.logException(it) }
.toObservable(EventDiaconnG8DeviceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ changePump() }) { fabricPrivacy.logException(it) }
)
changePump() // load device name
}
@ -144,9 +146,9 @@ class DiaconnG8Plugin @Inject constructor(
override fun connect(reason: String) {
aapsLogger.debug(LTag.PUMP, "Diaconn G8 connect from: $reason")
if(diaconnG8Service != null && mDeviceAddress != "" && mDeviceName != "") {
if (diaconnG8Service != null && mDeviceAddress != "" && mDeviceName != "") {
val success = diaconnG8Service?.connect(reason, mDeviceAddress) ?: false
if(!success) ToastUtils.errorToast(context, R.string.ble_not_supported)
if (!success) ToastUtils.errorToast(context, R.string.ble_not_supported)
}
}
@ -172,11 +174,11 @@ class DiaconnG8Plugin @Inject constructor(
// Diaconn Pump Interface
override fun loadHistory(): PumpEnactResult {
return diaconnG8Service?.loadHistory() ?: PumpEnactResult(injector).success(false)
return diaconnG8Service?.loadHistory() ?: PumpEnactResultImpl(injector).success(false)
}
override fun setUserOptions(): PumpEnactResult {
return diaconnG8Service?.setUserSettings() ?: PumpEnactResult(injector).success(false)
return diaconnG8Service?.setUserSettings() ?: PumpEnactResultImpl(injector).success(false)
}
// Constraints interface
@ -201,7 +203,7 @@ class DiaconnG8Plugin @Inject constructor(
}
// Pump interface
override fun isInitialized(): Boolean =
override fun isInitialized(): Boolean =
diaconnG8Pump.lastConnection > 0 && diaconnG8Pump.maxBasal > 0
override fun isSuspended(): Boolean =
@ -211,7 +213,7 @@ class DiaconnG8Plugin @Inject constructor(
diaconnG8Service?.isConnected ?: false || diaconnG8Service?.isConnecting ?: false
override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (!isInitialized()) {
val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, rh.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
@ -241,7 +243,7 @@ class DiaconnG8Plugin @Inject constructor(
if (!isInitialized()) return true
if (diaconnG8Pump.pumpProfiles == null) return true
val basalValues = 24
val basalIncrement = 60 * 60
val basalIncrement = 60 * 60
for (h in 0 until basalValues) {
val pumpValue = diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][h]
val profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement)
@ -275,19 +277,19 @@ class DiaconnG8Plugin @Inject constructor(
var connectionOK = false
if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = diaconnG8Service?.bolus(detailedBolusInfo.insulin, carbs.toInt(), carbTimeStamp, t)
?: false
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = connectionOK
result.bolusDelivered = t.insulin
result.carbsDelivered = detailedBolusInfo.carbs
if(result.success) result.enacted = true
if (result.success) result.enacted = true
if (!result.success) {
setErrorMsg(diaconnG8Pump.resultErrorCode, result)
} else result.comment = rh.gs(R.string.ok)
aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered)
result
} else {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.success = false
result.bolusDelivered = 0.0
result.carbsDelivered = 0.0
@ -304,7 +306,7 @@ class DiaconnG8Plugin @Inject constructor(
// This is called from APS
@Synchronized
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value()
val doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0
val doLowTemp = absoluteAfterConstrain < baseBasalRate
@ -381,7 +383,10 @@ class DiaconnG8Plugin @Inject constructor(
} else {
var absoluteValue = profile.getBasal() * (percent / 100.0)
absoluteValue = pumpDescription.pumpType.determineCorrectBasalSize(absoluteValue)
aapsLogger.warn(LTag.PUMP, "setTempBasalPercent [DiaconnG8Plugin] - You are trying to use setTempBasalPercent with percent other then 0% ($percent). This will start setTempBasalAbsolute, with calculated value ($absoluteValue). Result might not be 100% correct.")
aapsLogger.warn(
LTag.PUMP,
"setTempBasalPercent [DiaconnG8Plugin] - You are trying to use setTempBasalPercent with percent other then 0% ($percent). This will start setTempBasalAbsolute, with calculated value ($absoluteValue). Result might not be 100% correct."
)
setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew, tbrType)
}
@ -392,7 +397,7 @@ class DiaconnG8Plugin @Inject constructor(
var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value()
// needs to be rounded
insulinAfterConstraint = Round.roundTo(insulinAfterConstraint, pumpDescription.extendedBolusStep)
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (diaconnG8Pump.isExtendedInProgress && abs(diaconnG8Pump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) {
result.enacted = false
@ -430,13 +435,13 @@ class DiaconnG8Plugin @Inject constructor(
@Synchronized
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (diaconnG8Pump.isTempBasalInProgress) {
diaconnG8Service?.tempBasalStop()
result.success = !diaconnG8Pump.isTempBasalInProgress
result.enacted = true
result.isTempCancel = true
if(!result.success) setErrorMsg(diaconnG8Pump.resultErrorCode, result)
if (!result.success) setErrorMsg(diaconnG8Pump.resultErrorCode, result)
} else {
result.success = true
result.enacted = false
@ -448,17 +453,17 @@ class DiaconnG8Plugin @Inject constructor(
}
@Synchronized override fun cancelExtendedBolus(): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
if (diaconnG8Pump.isExtendedInProgress) {
diaconnG8Service?.extendedBolusStop()
result.success = !diaconnG8Pump.isExtendedInProgress
result.enacted = true
if(!result.success) {
if (!result.success) {
setErrorMsg(diaconnG8Pump.resultErrorCode, result)
diaconnG8Service?.readPumpStatus()
}
} else {
} else {
result.success = true
result.enacted = false
result.comment = rh.gs(R.string.ok)
@ -549,42 +554,43 @@ class DiaconnG8Plugin @Inject constructor(
ret += "Batt: ${diaconnG8Pump.systemRemainBattery}"
return ret
}
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = loadHistory()
override fun getCustomActions(): List<CustomAction>? = null
override fun executeCustomAction(customActionType: CustomActionType) {}
override fun canHandleDST(): Boolean = false
override fun isBatteryChangeLoggingEnabled():Boolean {
override fun isBatteryChangeLoggingEnabled(): Boolean {
return sp.getBoolean(R.string.key_diaconn_g8_logbatterychange, false)
}
fun isInsulinChangeLoggingEnabled():Boolean {
fun isInsulinChangeLoggingEnabled(): Boolean {
return sp.getBoolean(R.string.key_diaconn_g8_loginsulinchange, false)
}
@Synchronized
fun setErrorMsg(errorCode: Int, result: PumpEnactResult) {
when (errorCode) {
1 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_1)
2 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_2)
3 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_3)
4 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_4)
6 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_6)
7 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_7)
8 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_8)
9 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_9)
10 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_10)
11 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_11)
12 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_12)
13 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_13)
14 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_14)
15 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_15)
32 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_32)
33 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_33)
34 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_34)
35 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_35)
36 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_36)
1 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_1)
2 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_2)
3 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_3)
4 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_4)
6 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_6)
7 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_7)
8 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_8)
9 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_9)
10 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_10)
11 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_11)
12 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_12)
13 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_13)
14 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_14)
15 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_15)
32 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_32)
33 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_33)
34 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_34)
35 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_35)
36 -> result.comment = rh.gs(R.string.diaconn_g8_errorcode_36)
else -> result.comment = "not defined Error code: $errorCode"
}
}

View file

@ -10,6 +10,7 @@ import dagger.android.DaggerService
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.diaconn.DiaconnG8Plugin
import info.nightscout.androidaps.diaconn.DiaconnG8Pump
import info.nightscout.androidaps.diaconn.R
@ -268,7 +269,7 @@ class DiaconnG8Service : DaggerService() {
fun loadHistory(): PumpEnactResult {
if (!diaconnG8Plugin.isInitialized()) {
val result = PumpEnactResult(injector).success(false)
val result = PumpEnactResultImpl(injector).success(false)
result.comment = "pump not initialized"
return result
}
@ -278,14 +279,14 @@ class DiaconnG8Service : DaggerService() {
sendMessage(IncarnationInquirePacket(injector))
}
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
var apsLastLogNum = 9999
var apsWrappingCount = -1
// get saved last loginfo
val diaconnHistoryRecord = diaconnHistoryRecordDao.getLastRecord(diaconnG8Pump.pumpUid)
aapsLogger.debug(LTag.PUMPCOMM, "diaconnHistoryRecord :: $diaconnHistoryRecord")
if(diaconnHistoryRecord != null) {
if (diaconnHistoryRecord != null) {
apsLastLogNum = diaconnHistoryRecord.lognum
apsWrappingCount = diaconnHistoryRecord.wrappingCount
}
@ -297,25 +298,24 @@ class DiaconnG8Service : DaggerService() {
// aps last log num
val pumpSerialNo = sp.getInt(rh.gs(R.string.pumpserialno), 0)
// if first install app
if (apsWrappingCount == -1 && apsLastLogNum == 9999 ) {
if (apsWrappingCount == -1 && apsLastLogNum == 9999) {
apsWrappingCount = pumpWrappingCount
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum -2
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum - 2
}
// if another pump
if (pumpSerialNo != diaconnG8Pump.serialNo) {
apsWrappingCount = pumpWrappingCount
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum -2
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum - 2
sp.putInt(rh.gs(R.string.pumpserialno), diaconnG8Pump.serialNo)
}
// if pump reset
if (apsIncarnationNum != diaconnG8Pump.pumpIncarnationNum) {
apsWrappingCount = pumpWrappingCount
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum -2
apsLastLogNum = if (pumpLastNum - 1 < 0) 0 else pumpLastNum - 2
sp.putInt(R.string.apsIncarnationNo, apsIncarnationNum)
}
aapsLogger.debug(LTag.PUMPCOMM, "apsWrappingCount : $apsWrappingCount, apsLastLogNum : $apsLastLogNum")
aapsLogger.debug(LTag.PUMPCOMM, "apsWrappingCount : $apsWrappingCount, apsLastLogNum : $apsLastLogNum")
// pump log loop size
val pumpLogPageSize = 11
@ -340,7 +340,7 @@ class DiaconnG8Service : DaggerService() {
val retrofit = diaconnLogUploader.getRetrofitInstance()
val api = retrofit?.create(DiaconnApiService::class.java)
val response = api?.getPumpLastNo(diaconnG8Pump.pumpUid, diaconnG8Pump.pumpVersion, diaconnG8Pump.pumpIncarnationNum)?.execute()
if(response?.body()?.ok == true) {
if (response?.body()?.ok == true) {
aapsLogger.debug(LTag.PUMPCOMM, "pumplog_no = ${response.body()?.info?.pumplog_no}")
val platformLastNo = response.body()?.info?.pumplog_no!!
val platformWrappingCount: Int = floor(platformLastNo / 10000.0).toInt()
@ -353,10 +353,10 @@ class DiaconnG8Service : DaggerService() {
// 페이지 사이즈로 처리할 때 루핑 횟수 계산
val (platformStart, platformEnd, platformLoopSize) = getCloudLogLoopCount(platformLastNo.toInt(), platformLogNo, platformWrappingCount, pumpLastNum, pumpWrappingCount)
if(platformLoopSize > 0) {
if (platformLoopSize > 0) {
diaconnG8Pump.isPlatformUploadStarted = true
for (i in 0 until platformLoopSize) {
if(diaconnG8Pump.isPumpLogUploadFailed) {
if (diaconnG8Pump.isPumpLogUploadFailed) {
break
}
rxBus.send(EventPumpStatusChanged("클라우드동기화 진행 중 : $i / $platformLoopSize"))
@ -370,7 +370,7 @@ class DiaconnG8Service : DaggerService() {
diaconnG8Pump.isPumpLogUploadFailed = false
}
}
} catch (e:Exception) {
} catch (e: Exception) {
aapsLogger.error("Unhandled exception", e)
}
}
@ -394,18 +394,21 @@ class DiaconnG8Service : DaggerService() {
return Triple(start, end, size)
}
private fun getCloudLogLoopCount(platformLastNo:Int, platformPumpLogNum: Int, wrappingCount: Int, pumpLastNum: Int, pumpWrappingCount: Int): Triple<Int, Int, Int> {
private fun getCloudLogLoopCount(platformLastNo: Int, platformPumpLogNum: Int, wrappingCount: Int, pumpLastNum: Int, pumpWrappingCount: Int): Triple<Int, Int, Int> {
val start: Int// log sync start number
val end: Int // log sync end number1311
aapsLogger.debug(LTag.PUMPCOMM, "platformLastNo: $platformLastNo, PlatformPumpLogNum : $platformPumpLogNum, wrappingCount : $wrappingCount , pumpLastNum: $pumpLastNum, pumpWrappingCount :$pumpWrappingCount")
aapsLogger.debug(
LTag.PUMPCOMM,
"platformLastNo: $platformLastNo, PlatformPumpLogNum : $platformPumpLogNum, wrappingCount : $wrappingCount , pumpLastNum: $pumpLastNum, pumpWrappingCount :$pumpWrappingCount"
)
if ((pumpWrappingCount * 10000 + pumpLastNum - platformLastNo > 10000 )) {
if ((pumpWrappingCount * 10000 + pumpLastNum - platformLastNo > 10000)) {
start = pumpLastNum
end = 10000
} else if (pumpWrappingCount > wrappingCount && platformPumpLogNum < 9999) {
start = (platformPumpLogNum + 1)
end = 10000
} else if (pumpWrappingCount > wrappingCount && platformPumpLogNum >= 9999 ) {
} else if (pumpWrappingCount > wrappingCount && platformPumpLogNum >= 9999) {
start = 0 // 처음부터 시작
end = pumpLastNum
} else {
@ -418,7 +421,7 @@ class DiaconnG8Service : DaggerService() {
}
fun setUserSettings(): PumpEnactResult {
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
val msg: DiaconnG8Packet = when (diaconnG8Pump.setUserOptionType) {
DiaconnG8Pump.ALARM -> SoundSettingPacket(injector, diaconnG8Pump.beepAndAlarm, diaconnG8Pump.alarmIntesity)
@ -501,7 +504,7 @@ class DiaconnG8Service : DaggerService() {
val bolusDurationInMSec = (insulin * speed * 1000).toLong()
val expectedEnd = bolusStart + bolusDurationInMSec + 3500L
val totalwaitTime = (expectedEnd - System.currentTimeMillis()) / 1000
if(diaconnG8Pump.isReadyToBolus) {
if (diaconnG8Pump.isReadyToBolus) {
while (!diaconnG8Pump.bolusDone) {
val waitTime = (expectedEnd - System.currentTimeMillis()) / 1000
bolusingEvent.status = String.format(rh.gs(R.string.waitingforestimatedbolusend), if (waitTime < 0) 0 else waitTime)
@ -739,7 +742,7 @@ class DiaconnG8Service : DaggerService() {
// pump confirm
var loopCnt = 0
// waiting 2 seconds for otp
while(loopCnt < 20) {
while (loopCnt < 20) {
if (diaconnG8Pump.otpNumber == 0) {
SystemClock.sleep(100)
aapsLogger.error(LTag.PUMPCOMM, "OTP waiting 100ms $loopCnt / 20")

View file

@ -4,10 +4,10 @@ import android.os.SystemClock
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
@ -33,6 +33,7 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.TimeChangeType
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventAppInitialized
@ -61,14 +62,15 @@ class EopatchPumpPlugin @Inject constructor(
private val patchManager: IPatchManager,
private val alarmManager: IAlarmManager,
private val preferenceManager: IPreferenceManager
):PumpPluginBase(PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(EopatchOverviewFragment::class.java.name)
.pluginIcon(R.drawable.ic_eopatch2_128)
.pluginName(R.string.eopatch)
.shortName(R.string.eopatch_shortname)
.preferencesId(R.xml.pref_eopatch)
.description(R.string.eopatch_pump_description), injector, aapsLogger, rh, commandQueue
) : PumpPluginBase(
PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(EopatchOverviewFragment::class.java.name)
.pluginIcon(R.drawable.ic_eopatch2_128)
.pluginName(R.string.eopatch)
.shortName(R.string.eopatch_shortname)
.preferencesId(R.xml.pref_eopatch)
.description(R.string.eopatch_pump_description), injector, aapsLogger, rh, commandQueue
), Pump {
private val mDisposables = CompositeDisposable()
@ -80,31 +82,31 @@ class EopatchPumpPlugin @Inject constructor(
override fun onStart() {
super.onStart()
mDisposables.add(rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange ->
if (event.isChanged(rh, SettingKeys.LOW_RESERVOIR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) {
patchManager.changeReminderSetting()
} else if (event.isChanged(rh, SettingKeys.BUZZER_REMINDERS)) {
patchManager.changeBuzzerSetting()
}
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
.toObservable(EventPreferenceChange::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({ event: EventPreferenceChange ->
if (event.isChanged(rh, SettingKeys.LOW_RESERVOIR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) {
patchManager.changeReminderSetting()
} else if (event.isChanged(rh, SettingKeys.BUZZER_REMINDERS)) {
patchManager.changeBuzzerSetting()
}
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
)
mDisposables.add(rxBus
.toObservable(EventAppInitialized::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
preferenceManager.init()
patchManager.init()
alarmManager.init()
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
.toObservable(EventAppInitialized::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
preferenceManager.init()
patchManager.init()
alarmManager.init()
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
)
}
override fun specialEnableCondition(): Boolean {
//BG -> FG, restart patch activation and trigger unhandled alarm
if(preferenceManager.isInitDone()) {
if (preferenceManager.isInitDone()) {
patchManager.checkActivationProcess()
alarmManager.restartAll()
}
@ -129,7 +131,7 @@ class EopatchPumpPlugin @Inject constructor(
}
override fun isConnected(): Boolean {
return if(patchManager.isDeactivated) true else patchManager.patchConnectionState.isConnected
return if (patchManager.isDeactivated) true else patchManager.patchConnectionState.isConnected
}
override fun isConnecting(): Boolean {
@ -144,12 +146,12 @@ class EopatchPumpPlugin @Inject constructor(
}
override fun connect(reason: String) {
aapsLogger.debug(LTag.PUMP,"EOPatch connect - reason:$reason")
aapsLogger.debug(LTag.PUMP, "EOPatch connect - reason:$reason")
mLastDataTime = System.currentTimeMillis()
}
override fun disconnect(reason: String) {
aapsLogger.debug(LTag.PUMP,"EOPatch disconnect - reason:$reason")
aapsLogger.debug(LTag.PUMP, "EOPatch disconnect - reason:$reason")
}
override fun stopConnecting() {
@ -159,23 +161,24 @@ class EopatchPumpPlugin @Inject constructor(
if (patchManager.isActivated) {
if ("SMS" == reason) {
aapsLogger.debug("Acknowledged AAPS getPumpStatus request it was requested through an SMS")
}else{
} else {
aapsLogger.debug("Acknowledged AAPS getPumpStatus request")
}
mDisposables.add(patchManager.updateConnection()
.subscribe(Consumer {
mLastDataTime = System.currentTimeMillis()
})
mDisposables.add(
patchManager.updateConnection()
.subscribe(Consumer {
mLastDataTime = System.currentTimeMillis()
})
)
}
}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
mLastDataTime = System.currentTimeMillis()
if(patchManager.isActivated){
if(patchManager.patchState.isTempBasalActive || patchManager.patchState.isBolusActive){
return PumpEnactResult(injector)
}else{
if (patchManager.isActivated) {
if (patchManager.patchState.isTempBasalActive || patchManager.patchState.isBolusActive) {
return PumpEnactResultImpl(injector)
} else {
var isSuccess: Boolean? = null
val result: BehaviorSubject<Boolean> = BehaviorSubject.create()
val disposable = result.hide()
@ -184,33 +187,34 @@ class EopatchPumpPlugin @Inject constructor(
}
val nb = preferenceManager.getNormalBasalManager().convertProfileToNormalBasal(profile)
mDisposables.add(patchManager.startBasal(nb)
.observeOn(aapsSchedulers.main)
.subscribe({ response ->
result.onNext(response.isSuccess)
}, {
result.onNext(false)
})
mDisposables.add(
patchManager.startBasal(nb)
.observeOn(aapsSchedulers.main)
.subscribe({ response ->
result.onNext(response.isSuccess)
}, {
result.onNext(false)
})
)
do{
do {
SystemClock.sleep(100)
}while(isSuccess == null)
} while (isSuccess == null)
disposable.dispose()
aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess?:false}")
if(isSuccess == true) {
aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess ?: false}")
if (isSuccess == true) {
rxBus.send(EventNewNotification(Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60)))
return PumpEnactResult(injector).success(true).enacted(true)
}else{
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector).success(true).enacted(true)
} else {
return PumpEnactResultImpl(injector)
}
}
}else{
} else {
preferenceManager.getNormalBasalManager().setNormalBasal(profile)
preferenceManager.flushNormalBasalManager()
rxBus.send(EventNewNotification(Notification(Notification.PROFILE_SET_OK, rh.gs(R.string.profile_set_ok), Notification.INFO, 60)))
return PumpEnactResult(injector).success(true).enacted(true)
return PumpEnactResultImpl(injector).success(true).enacted(true)
}
}
@ -229,39 +233,39 @@ class EopatchPumpPlugin @Inject constructor(
}
override val baseBasalRate: Double
get() {
if (!patchManager.isActivated || patchManager.patchState.isNormalBasalPaused) {
return 0.0
}
get() {
if (!patchManager.isActivated || patchManager.patchState.isNormalBasalPaused) {
return 0.0
}
return preferenceManager.getNormalBasalManager().normalBasal.getCurrentSegment()?.doseUnitPerHour?.toDouble()?:0.05
}
return preferenceManager.getNormalBasalManager().normalBasal.getCurrentSegment()?.doseUnitPerHour?.toDouble() ?: 0.05
}
override val reservoirLevel: Double
get() {
if (!patchManager.isActivated) {
return 0.0
}
get() {
if (!patchManager.isActivated) {
return 0.0
}
return patchManager.patchState.remainedInsulin.toDouble()
}
return patchManager.patchState.remainedInsulin.toDouble()
}
override val batteryLevel: Int
get() {
return if(patchManager.isActivated) {
patchManager.patchState.batteryLevel()
}else{
0
get() {
return if (patchManager.isActivated) {
patchManager.patchState.batteryLevel()
} else {
0
}
}
}
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult {
if (detailedBolusInfo.insulin == 0.0 && detailedBolusInfo.carbs == 0.0) {
// neither carbs nor bolus requested
aapsLogger.error("deliverTreatment: Invalid input: neither carbs nor insulin are set in treatment")
return PumpEnactResult(injector).success(false).enacted(false).bolusDelivered(0.0).carbsDelivered(0.0)
.comment(rh.gs(R.string.invalidinput))
return PumpEnactResultImpl(injector).success(false).enacted(false).bolusDelivered(0.0).carbsDelivered(0.0)
.comment(rh.gs(R.string.invalidinput))
} else if (detailedBolusInfo.insulin > 0.0) {
var isSuccess = true
val result = BehaviorSubject.createDefault(true)
@ -271,22 +275,22 @@ class EopatchPumpPlugin @Inject constructor(
}
mDisposables.add(patchManager.startCalculatorBolus(detailedBolusInfo)
.doOnSuccess {
mLastDataTime = System.currentTimeMillis()
}.subscribe({
result.onNext(it.isSuccess)
}, {
result.onNext(false)
})
.doOnSuccess {
mLastDataTime = System.currentTimeMillis()
}.subscribe({
result.onNext(it.isSuccess)
}, {
result.onNext(false)
})
)
val tr = detailedBolusInfo.let {
EventOverviewBolusProgress.Treatment(it.insulin, it.carbs.toInt(), it.bolusType === DetailedBolusInfo.BolusType.SMB, it.id)
}
do{
do {
SystemClock.sleep(100)
if(patchManager.patchConnectionState.isConnected) {
if (patchManager.patchConnectionState.isConnected) {
val delivering = patchManager.bolusCurrent.nowBolus.injected
rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivering, delivering)
@ -294,7 +298,7 @@ class EopatchPumpPlugin @Inject constructor(
t = tr
})
}
}while(!patchManager.bolusCurrent.nowBolus.endTimeSynced && isSuccess)
} while (!patchManager.bolusCurrent.nowBolus.endTimeSynced && isSuccess)
rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin)
@ -306,35 +310,35 @@ class EopatchPumpPlugin @Inject constructor(
disposable.dispose()
return if(isSuccess)
PumpEnactResult(injector).success(true)/*.enacted(true)*/.carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(detailedBolusInfo.insulin)
return if (isSuccess)
PumpEnactResultImpl(injector).success(true)/*.enacted(true)*/.carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(detailedBolusInfo.insulin)
else
PumpEnactResult(injector).success(false)/*.enacted(false)*/.carbsDelivered(0.0).bolusDelivered(detailedBolusInfo.insulin)
PumpEnactResultImpl(injector).success(false)/*.enacted(false)*/.carbsDelivered(0.0).bolusDelivered(detailedBolusInfo.insulin)
} else {
// no bolus required, carb only treatment
patchManager.addBolusToHistory(detailedBolusInfo)
return PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(0.0)
.carbsDelivered(detailedBolusInfo.carbs).comment(rh.gs(info.nightscout.androidaps.core.R.string.ok))
return PumpEnactResultImpl(injector).success(true).enacted(true).bolusDelivered(0.0)
.carbsDelivered(detailedBolusInfo.carbs).comment(rh.gs(info.nightscout.androidaps.core.R.string.ok))
}
}
override fun stopBolusDelivering() {
mDisposables.add(patchManager.stopNowBolus()
.subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)
.subscribe { it ->
rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivered, (it.injectedBolusAmount * 0.05f))
})
}
.subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)
.subscribe { it ->
rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivered, (it.injectedBolusAmount * 0.05f))
})
}
)
}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - absoluteRate: ${absoluteRate.toFloat()}, durationInMinutes: ${durationInMinutes.toLong()}, enforceNew: $enforceNew")
if(patchManager.patchState.isNormalBasalAct){
if (patchManager.patchState.isNormalBasalAct) {
mLastDataTime = System.currentTimeMillis()
val tb = TempBasal.createAbsolute(durationInMinutes.toLong(), absoluteRate.toFloat())
return patchManager.startTempBasal(tb)
@ -351,21 +355,23 @@ class EopatchPumpPlugin @Inject constructor(
pumpType = PumpType.EOFLOW_EOPATCH2,
pumpSerial = serialNumber()
)
aapsLogger.info(LTag.PUMP,"setTempBasalAbsolute - tbrCurrent:${readTBR()}")
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - tbrCurrent:${readTBR()}")
}
.map { PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).absolute(absoluteRate).isPercent(false).isTempCancel(false) }
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment("Internal error"))
.map { PumpEnactResultImpl(injector).success(true).enacted(true).duration(durationInMinutes).absolute(absoluteRate).isPercent(false).isTempCancel(false) }
.onErrorReturnItem(
PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Internal error")
)
.blockingGet()
}else{
aapsLogger.info(LTag.PUMP,"setTempBasalAbsolute - normal basal is not active")
return PumpEnactResult(injector).success(false).enacted(false)
} else {
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - normal basal is not active")
return PumpEnactResultImpl(injector).success(false).enacted(false)
}
}
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - percent: $percent, durationInMinutes: $durationInMinutes, enforceNew: $enforceNew")
if(patchManager.patchState.isNormalBasalAct && percent != 0){
aapsLogger.info(LTag.PUMP, "setTempBasalPercent - percent: $percent, durationInMinutes: $durationInMinutes, enforceNew: $enforceNew")
if (patchManager.patchState.isNormalBasalAct && percent != 0) {
mLastDataTime = System.currentTimeMillis()
val tb = TempBasal.createPercent(durationInMinutes.toLong(), percent)
return patchManager.startTempBasal(tb)
@ -382,20 +388,22 @@ class EopatchPumpPlugin @Inject constructor(
pumpType = PumpType.EOFLOW_EOPATCH2,
pumpSerial = serialNumber()
)
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - tbrCurrent:${readTBR()}")
aapsLogger.info(LTag.PUMP, "setTempBasalPercent - tbrCurrent:${readTBR()}")
}
.map { PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).percent(percent).isPercent(true).isTempCancel(false) }
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment("Internal error"))
.map { PumpEnactResultImpl(injector).success(true).enacted(true).duration(durationInMinutes).percent(percent).isPercent(true).isTempCancel(false) }
.onErrorReturnItem(
PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Internal error")
)
.blockingGet()
}else{
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - normal basal is not active")
return PumpEnactResult(injector).success(false).enacted(false)
} else {
aapsLogger.info(LTag.PUMP, "setTempBasalPercent - normal basal is not active")
return PumpEnactResultImpl(injector).success(false).enacted(false)
}
}
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
aapsLogger.info(LTag.PUMP,"setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes")
aapsLogger.info(LTag.PUMP, "setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes")
return patchManager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes))
.doOnSuccess {
@ -410,31 +418,33 @@ class EopatchPumpPlugin @Inject constructor(
pumpSerial = serialNumber()
)
}
.map { PumpEnactResult(injector).success(true).enacted(true)}
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false).bolusDelivered(0.0)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.map { PumpEnactResultImpl(injector).success(true).enacted(true) }
.onErrorReturnItem(
PumpEnactResultImpl(injector).success(false).enacted(false).bolusDelivered(0.0)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))
)
.blockingGet()
}
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult {
val tbrCurrent = readTBR()
if (tbrCurrent == null ) {
aapsLogger.debug(LTag.PUMP,"cancelTempBasal - TBR already false.")
return PumpEnactResult(injector).success(true).enacted(false)
}
if (tbrCurrent == null) {
aapsLogger.debug(LTag.PUMP, "cancelTempBasal - TBR already false.")
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
if (!patchManager.patchState.isTempBasalActive) {
return if (pumpSync.expectedPumpState().temporaryBasal != null) {
PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)
}else
PumpEnactResult(injector).success(true).isTempCancel(true)
if (!patchManager.patchState.isTempBasalActive) {
return if (pumpSync.expectedPumpState().temporaryBasal != null) {
PumpEnactResultImpl(injector).success(true).enacted(true).isTempCancel(true)
} else
PumpEnactResultImpl(injector).success(true).isTempCancel(true)
}
return patchManager.stopTempBasal()
.doOnSuccess {
mLastDataTime = System.currentTimeMillis()
aapsLogger.debug(LTag.PUMP,"cancelTempBasal - $it")
aapsLogger.debug(LTag.PUMP, "cancelTempBasal - $it")
pumpSync.syncStopTemporaryBasalWithPumpId(
timestamp = dateUtil.now(),
endPumpId = dateUtil.now(),
@ -442,20 +452,22 @@ class EopatchPumpPlugin @Inject constructor(
pumpSerial = serialNumber()
)
}
.doOnError{
aapsLogger.error(LTag.PUMP,"cancelTempBasal() - $it")
.doOnError {
aapsLogger.error(LTag.PUMP, "cancelTempBasal() - $it")
}
.map { PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.map { PumpEnactResultImpl(injector).success(true).enacted(true).isTempCancel(true) }
.onErrorReturnItem(
PumpEnactResultImpl(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))
)
.blockingGet()
}
override fun cancelExtendedBolus(): PumpEnactResult {
if(patchManager.patchState.isExtBolusActive){
if (patchManager.patchState.isExtBolusActive) {
return patchManager.stopExtBolus()
.doOnSuccess {
aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - success")
aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus - success")
mLastDataTime = System.currentTimeMillis()
pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = dateUtil.now(),
@ -464,12 +476,14 @@ class EopatchPumpPlugin @Inject constructor(
pumpSerial = serialNumber()
)
}
.map { PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.map { PumpEnactResultImpl(injector).success(true).enacted(true).isTempCancel(true) }
.onErrorReturnItem(
PumpEnactResultImpl(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))
)
.blockingGet()
}else{
aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - nothing stops")
} else {
aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus - nothing stops")
return if (pumpSync.expectedPumpState().extendedBolus != null) {
pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = dateUtil.now(),
@ -477,9 +491,9 @@ class EopatchPumpPlugin @Inject constructor(
pumpType = PumpType.EOFLOW_EOPATCH2,
pumpSerial = serialNumber()
)
PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)
}else
PumpEnactResult(injector)
PumpEnactResultImpl(injector).success(true).enacted(true).isTempCancel(true)
} else
PumpEnactResultImpl(injector)
}
}
@ -503,7 +517,7 @@ class EopatchPumpPlugin @Inject constructor(
get() = mPumpDescription
override fun shortStatus(veryShort: Boolean): String {
if(patchManager.isActivated) {
if (patchManager.isActivated) {
var ret = ""
val activeTemp = pumpSync.expectedPumpState().temporaryBasal
if (activeTemp != null)
@ -524,7 +538,7 @@ class EopatchPumpPlugin @Inject constructor(
ret += "Reservoir: $reservoirStr"
ret += "Battery: ${patchManager.patchState.batteryLevel()}"
return ret
}else{
} else {
return "EOPatch is not enabled."
}
}
@ -532,7 +546,7 @@ class EopatchPumpPlugin @Inject constructor(
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult {
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
}
override fun canHandleDST(): Boolean {
@ -551,7 +565,6 @@ class EopatchPumpPlugin @Inject constructor(
return null
}
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {
}

View file

@ -9,11 +9,11 @@ import androidx.preference.Preference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ActivityNames
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpSync
@ -66,6 +66,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Comp
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.TimeChangeType
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventRefreshOverview
@ -591,7 +592,7 @@ class MedtronicPumpPlugin @Inject constructor(
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared)
setRefreshButtonEnabled(false)
if (detailedBolusInfo.insulin > medtronicPumpStatus.reservoirRemainingUnits) {
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(false) //
.enacted(false) //
.comment(
@ -632,7 +633,7 @@ class MedtronicPumpPlugin @Inject constructor(
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Response: {}", response);
return if (response == null || !response) {
PumpEnactResult(injector) //
PumpEnactResultImpl(injector) //
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(R.string.medtronic_cmd_bolus_could_not_be_delivered)
@ -659,7 +660,7 @@ class MedtronicPumpPlugin @Inject constructor(
val time = now + bolusTime * 1000
busyTimestamps.add(time)
setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true)
PumpEnactResult(injector).success(true) //
PumpEnactResultImpl(injector).success(true) //
.enacted(true) //
.bolusDelivered(detailedBolusInfo.insulin) //
.carbsDelivered(detailedBolusInfo.carbs)
@ -676,8 +677,8 @@ class MedtronicPumpPlugin @Inject constructor(
private fun setNotReachable(isBolus: Boolean, success: Boolean): PumpEnactResult {
setRefreshButtonEnabled(true)
if (isBolus) bolusDeliveryType = BolusDeliveryType.Idle
return if (success) PumpEnactResult(injector).success(true).enacted(false)
else PumpEnactResult(injector).success(false).enacted(false).comment(R.string.medtronic_pump_status_pump_unreachable)
return if (success) PumpEnactResultImpl(injector).success(true).enacted(false)
else PumpEnactResultImpl(injector).success(false).enacted(false).comment(R.string.medtronic_pump_status_pump_unreachable)
}
override fun stopBolusDelivering() {
@ -700,7 +701,7 @@ class MedtronicPumpPlugin @Inject constructor(
setRefreshButtonEnabled(false)
if (isPumpNotReachable) {
setRefreshButtonEnabled(true)
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(false) //
.enacted(false) //
.comment(R.string.medtronic_pump_status_pump_unreachable)
@ -713,7 +714,7 @@ class MedtronicPumpPlugin @Inject constructor(
if (tbrCurrent == null) {
aapsLogger.warn(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Could not read current TBR, canceling operation.")
finishAction("TBR")
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment(R.string.medtronic_cmd_cant_read_tbr)
} else {
aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute: Current Basal: duration: " + tbrCurrent.durationMinutes + " min, rate=" + tbrCurrent.insulinRate)
@ -728,7 +729,7 @@ class MedtronicPumpPlugin @Inject constructor(
if (sameRate) {
aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - No enforceNew and same rate. Exiting.")
finishAction("TBR")
return PumpEnactResult(injector).success(true).enacted(false)
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
}
// if not the same rate, we cancel and start new
@ -744,7 +745,7 @@ class MedtronicPumpPlugin @Inject constructor(
if (response == null || !response) {
aapsLogger.error(logPrefix + "setTempBasalAbsolute - Cancel TBR failed.")
finishAction("TBR")
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment(R.string.medtronic_cmd_cant_cancel_tbr_stop_op)
} else {
//cancelTBRWithTemporaryId()
@ -761,7 +762,7 @@ class MedtronicPumpPlugin @Inject constructor(
aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - setTBR. Response: " + response)
return if (response == null || !response) {
finishAction("TBR")
PumpEnactResult(injector).success(false).enacted(false) //
PumpEnactResultImpl(injector).success(false).enacted(false) //
.comment(R.string.medtronic_cmd_tbr_could_not_be_delivered)
} else {
medtronicPumpStatus.tempBasalStart = System.currentTimeMillis()
@ -775,7 +776,7 @@ class MedtronicPumpPlugin @Inject constructor(
incrementStatistics(MedtronicConst.Statistics.TBRsSet)
finishAction("TBR")
PumpEnactResult(injector).success(true).enacted(true) //
PumpEnactResultImpl(injector).success(true).enacted(true) //
.absolute(absoluteRate).duration(durationInMinutes)
}
}
@ -1021,7 +1022,7 @@ class MedtronicPumpPlugin @Inject constructor(
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - started")
if (isPumpNotReachable) {
setRefreshButtonEnabled(true)
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(false) //
.enacted(false) //
.comment(R.string.medtronic_pump_status_pump_unreachable)
@ -1033,12 +1034,12 @@ class MedtronicPumpPlugin @Inject constructor(
if (tbrCurrent.insulinRate > 0.0f && tbrCurrent.durationMinutes == 0) {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - TBR already canceled.")
finishAction("TBR")
return PumpEnactResult(injector).success(true).enacted(false)
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
} else {
aapsLogger.warn(LTag.PUMP, logPrefix + "cancelTempBasal - Could not read current TBR, canceling operation.")
finishAction("TBR")
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment(R.string.medtronic_cmd_cant_read_tbr)
}
val responseTask2 = rileyLinkMedtronicService?.medtronicUIComm?.executeCommand(MedtronicCommandType.CancelTBR)
@ -1046,7 +1047,7 @@ class MedtronicPumpPlugin @Inject constructor(
finishAction("TBR")
return if (response == null || !response) {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR failed.")
PumpEnactResult(injector).success(false).enacted(false) //
PumpEnactResultImpl(injector).success(false).enacted(false) //
.comment(R.string.medtronic_cmd_cant_cancel_tbr)
} else {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.")
@ -1082,7 +1083,7 @@ class MedtronicPumpPlugin @Inject constructor(
//cancelTBRWithTemporaryId()
PumpEnactResult(injector).success(true).enacted(true) //
PumpEnactResultImpl(injector).success(true).enacted(true) //
.isTempCancel(true)
}
}
@ -1105,7 +1106,7 @@ class MedtronicPumpPlugin @Inject constructor(
// this shouldn't be needed, but let's do check if profile setting we are setting is same as current one
if (isProfileSame(profile)) {
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(true) //
.enacted(false) //
.comment(R.string.medtronic_cmd_basal_profile_not_set_is_same)
@ -1113,7 +1114,7 @@ class MedtronicPumpPlugin @Inject constructor(
setRefreshButtonEnabled(false)
if (isPumpNotReachable) {
setRefreshButtonEnabled(true)
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(false) //
.enacted(false) //
.comment(R.string.medtronic_pump_status_pump_unreachable)
@ -1123,7 +1124,7 @@ class MedtronicPumpPlugin @Inject constructor(
aapsLogger.debug("Basal Profile: $basalProfile")
val profileInvalid = isProfileValid(basalProfile)
if (profileInvalid != null) {
return PumpEnactResult(injector) //
return PumpEnactResultImpl(injector) //
.success(false) //
.enacted(false) //
.comment(rh.gs(R.string.medtronic_cmd_set_profile_pattern_overflow, profileInvalid))
@ -1135,10 +1136,10 @@ class MedtronicPumpPlugin @Inject constructor(
val response = responseTask?.result as Boolean?
aapsLogger.info(LTag.PUMP, logPrefix + "Basal Profile was set: " + response)
return if (response == null || !response) {
PumpEnactResult(injector).success(false).enacted(false) //
PumpEnactResultImpl(injector).success(false).enacted(false) //
.comment(R.string.medtronic_cmd_basal_profile_could_not_be_set)
} else {
PumpEnactResult(injector).success(true).enacted(true)
PumpEnactResultImpl(injector).success(true).enacted(true)
}
}

View file

@ -12,10 +12,10 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.Medtr
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import info.nightscout.shared.sharedPreferences.SP
import org.junit.Before
import org.junit.Rule
@ -24,7 +24,7 @@ import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -12,8 +12,8 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalProce
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.androidaps.utils.serialisation.SealedClassHelper.gson
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.bus.RxBus
import org.junit.Before
import org.junit.Test

View file

@ -4,6 +4,7 @@ import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.logging.AAPSLogger
import info.nightscout.rx.logging.LTag
@ -41,7 +42,7 @@ abstract class ActionViewModelBase(
logger.error(LTag.PUMP, "Caught exception in while executing action in ActionViewModelBase", throwable)
_isActionExecutingLiveData.postValue(false)
_actionResultLiveData.postValue(
PumpEnactResult(injector).success(false).comment(
PumpEnactResultImpl(injector).success(false).comment(
throwable.message ?: "Caught exception in while executing action in ActionViewModelBase"
)
)

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.Omnipod
import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase
import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordDao
import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import io.reactivex.rxjava3.schedulers.Schedulers
import org.junit.After
import org.junit.Before

View file

@ -7,6 +7,7 @@ import android.text.format.DateFormat
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
@ -14,7 +15,6 @@ import info.nightscout.androidaps.extensions.toStringFull
import info.nightscout.androidaps.interfaces.ActivityNames
import info.nightscout.androidaps.interfaces.CommandQueue
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.interfaces.PluginType
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.Pump
@ -68,6 +68,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.TimeChangeType
import info.nightscout.interfaces.PluginType
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.rx.events.EventProfileSwitchChanged
@ -394,7 +395,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
if (!podStateManager.isActivationCompleted) {
return PumpEnactResult(injector).success(true).enacted(true)
return PumpEnactResultImpl(injector).success(true).enacted(true)
}
aapsLogger.debug(LTag.PUMP, "setNewBasalProfile profile=$profile")
return setNewBasalProfile(profile, OmnipodCommandType.SET_BASAL_PROFILE)
@ -420,7 +421,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
command = omnipodManager.setBasalProgram(basalProgram, hasBasalBeepEnabled()).ignoreElements(),
post = failWhenUnconfirmed(deliverySuspended),
// mark as failed even if it worked OK and try again vs. mark ok and deny later
).toPumpEnactResult()
).toPumpEnactResultImpl()
}
private fun failWhenUnconfirmed(deliverySuspended: Boolean): Completable = Completable.defer {
@ -566,7 +567,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
detailedBolusInfo.insulin == 0.0
) {
// Accept only valid insulin requests
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
.success(false)
.enacted(false)
.bolusDelivered(0.0)
@ -574,7 +575,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
}
val requestedBolusAmount = detailedBolusInfo.insulin
if (requestedBolusAmount > reservoirLevel) {
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
.success(false)
.enacted(false)
.bolusDelivered(0.0)
@ -583,7 +584,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
if (podStateManager.deliveryStatus == DeliveryStatus.BOLUS_AND_BASAL_ACTIVE ||
podStateManager.deliveryStatus == DeliveryStatus.BOLUS_AND_TEMP_BASAL_ACTIVE
) {
return PumpEnactResult(injector)
return PumpEnactResultImpl(injector)
.success(false)
.enacted(false)
.bolusDelivered(0.0)
@ -652,10 +653,10 @@ class OmnipodDashPumpPlugin @Inject constructor(
}
}
}.toSingle {
PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(deliveredBolusAmount)
PumpEnactResultImpl(injector).success(true).enacted(true).bolusDelivered(deliveredBolusAmount)
}.onErrorReturnItem(
// success if canceled
PumpEnactResult(injector).success(bolusCanceled).enacted(false)
PumpEnactResultImpl(injector).success(bolusCanceled).enacted(false)
)
.blockingGet()
aapsLogger.info(
@ -864,7 +865,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
"it has been cancelled. Please manually refresh the Pod status from the Omnipod tab.",
R.raw.boluserror,
)
}.toPumpEnactResult()
}.toPumpEnactResultImpl()
if (ret.success && ret.enacted) {
ret.isPercent(false).absolute(absoluteRate).duration(durationInMinutes)
@ -939,13 +940,13 @@ class OmnipodDashPumpPlugin @Inject constructor(
tbrType: PumpSync.TemporaryBasalType
): PumpEnactResult {
// TODO i18n
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Omnipod Dash driver does not support percentage temp basals")
}
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
// TODO i18n
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Omnipod Dash driver does not support extended boluses")
}
@ -962,7 +963,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
pumpSync.expectedPumpState().temporaryBasal == null
) {
// nothing to cancel
return PumpEnactResult(injector).success(true).enacted(false)
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
return executeProgrammingCommand(
@ -974,7 +975,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
"Cancel temp basal result is uncertain", // TODO: i8n,
R.raw.boluserror, // TODO: add setting for this
)
}.toPumpEnactResult()
}.toPumpEnactResultImpl()
}
private fun notifyOnUnconfirmed(notificationId: Int, msg: String, sound: Int?) {
@ -984,18 +985,18 @@ class OmnipodDashPumpPlugin @Inject constructor(
}
}
private fun Completable.toPumpEnactResult(): PumpEnactResult {
return this.toSingleDefault(PumpEnactResult(injector).success(true).enacted(true))
private fun Completable.toPumpEnactResultImpl(): PumpEnactResult {
return this.toSingleDefault(PumpEnactResultImpl(injector).success(true).enacted(true))
.doOnError { throwable ->
aapsLogger.error(LTag.PUMP, "toPumpEnactResult, error executing command: $throwable")
}
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false))
.onErrorReturnItem(PumpEnactResultImpl(injector).success(false).enacted(false))
.blockingGet()
}
override fun cancelExtendedBolus(): PumpEnactResult {
// TODO i18n
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Omnipod Dash driver does not support extended boluses")
}
@ -1096,7 +1097,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
override fun loadTDDs(): PumpEnactResult {
// TODO i18n
return PumpEnactResult(injector).success(false).enacted(false)
return PumpEnactResultImpl(injector).success(false).enacted(false)
.comment("Omnipod Dash driver does not support TDD")
}
@ -1131,7 +1132,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
else -> {
aapsLogger.warn(LTag.PUMP, "Unsupported custom command: " + customCommand.javaClass.name)
PumpEnactResult(injector).success(false).enacted(false).comment(
PumpEnactResultImpl(injector).success(false).enacted(false).comment(
rh.gs(
R.string.omnipod_common_error_unsupported_custom_command,
customCommand.javaClass.name
@ -1147,8 +1148,8 @@ class OmnipodDashPumpPlugin @Inject constructor(
executeProgrammingCommand(
historyEntry = history.createRecord(commandType = OmnipodCommandType.ACKNOWLEDGE_ALERTS),
command = omnipodManager.silenceAlerts(it).ignoreElements(),
).toPumpEnactResult()
} ?: PumpEnactResult(injector).success(false).enacted(false).comment("No active alerts") // TODO i18n
).toPumpEnactResultImpl()
} ?: PumpEnactResultImpl(injector).success(false).enacted(false).comment("No active alerts") // TODO i18n
}
private fun disableSuspendAlerts(): PumpEnactResult {
@ -1168,7 +1169,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
val ret = executeProgrammingCommand(
historyEntry = history.createRecord(OmnipodCommandType.CONFIGURE_ALERTS),
command = omnipodManager.programAlerts(alerts).ignoreElements(),
).toPumpEnactResult()
).toPumpEnactResultImpl()
if (ret.success && ret.enacted) {
podStateManager.suspendAlertsEnabled = false
}
@ -1195,8 +1196,8 @@ class OmnipodDashPumpPlugin @Inject constructor(
"Unconfirmed resumeDelivery command. Please refresh pod status",
R.raw.boluserror
)
}.toPumpEnactResult()
} ?: PumpEnactResult(injector).success(false).enacted(false).comment("No profile active") // TODO i18n
}.toPumpEnactResultImpl()
} ?: PumpEnactResultImpl(injector).success(false).enacted(false).comment("No profile active") // TODO i18n
}
private fun deactivatePod(): PumpEnactResult {
@ -1212,7 +1213,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
podStateManager.reset()
rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_FAULT))
}
}.toPumpEnactResult()
}.toPumpEnactResultImpl()
if (!success) {
ret.success(false)
}
@ -1222,7 +1223,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
private fun handleTimeChange(): PumpEnactResult {
return profileFunction.getProfile()?.let {
setNewBasalProfile(it, OmnipodCommandType.SET_TIME)
} ?: PumpEnactResult(injector).success(false).enacted(false).comment("No profile active")
} ?: PumpEnactResultImpl(injector).success(false).enacted(false).comment("No profile active")
}
private fun updateAlertConfiguration(): PumpEnactResult {
@ -1240,12 +1241,12 @@ class OmnipodDashPumpPlugin @Inject constructor(
lowReservoirAlertUnits
) -> {
aapsLogger.debug(LTag.PUMP, "Ignoring updateAlertConfiguration because the settings did not change")
return PumpEnactResult(injector).success(true).enacted(false)
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
!podStateManager.isPodRunning -> {
aapsLogger.debug(LTag.PUMP, "Ignoring updateAlertConfiguration because there is no active pod")
return PumpEnactResult(injector).success(true).enacted(false)
return PumpEnactResultImpl(injector).success(true).enacted(false)
}
}
@ -1257,7 +1258,7 @@ class OmnipodDashPumpPlugin @Inject constructor(
"updateAlertConfiguration negative " +
"expiryAlertDuration=$expiryAlertDelay"
)
PumpEnactResult(injector).success(false).enacted(false)
PumpEnactResultImpl(injector).success(false).enacted(false)
}
val alerts = listOf(
AlertConfiguration(
@ -1293,14 +1294,14 @@ class OmnipodDashPumpPlugin @Inject constructor(
lowReservoirAlertUnits
)
)
).toPumpEnactResult()
).toPumpEnactResultImpl()
}
private fun playTestBeep(): PumpEnactResult {
return executeProgrammingCommand(
historyEntry = history.createRecord(OmnipodCommandType.PLAY_TEST_BEEP),
command = omnipodManager.playBeep(BeepType.LONG_SINGLE_BEEP).ignoreElements()
).toPumpEnactResult()
).toPumpEnactResultImpl()
}
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activatio
import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType
import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel
@ -66,14 +67,14 @@ class DashInitializePodViewModel @Inject constructor(
onError = { throwable ->
logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable)
source.onSuccess(
PumpEnactResult(injector)
PumpEnactResultImpl(injector)
.success(false)
.comment(I8n.textFromException(throwable, rh))
)
},
onComplete = {
logger.debug("Pod activation part 1 completed")
source.onSuccess(PumpEnactResult(injector).success(true))
source.onSuccess(PumpEnactResultImpl(injector).success(true))
}
)
}

View file

@ -4,6 +4,7 @@ import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.ResourceHelper
@ -90,7 +91,7 @@ class DashInsertCannulaViewModel @Inject constructor(
.subscribeBy(
onError = { throwable ->
logger.error(LTag.PUMP, "Error in Pod activation part 2", throwable)
source.onSuccess(PumpEnactResult(injector).success(false).comment(I8n.textFromException(throwable, rh)))
source.onSuccess(PumpEnactResultImpl(injector).success(false).comment(I8n.textFromException(throwable, rh)))
},
onComplete = {
logger.debug("Pod activation part 2 completed")
@ -120,7 +121,7 @@ class DashInsertCannulaViewModel @Inject constructor(
)
rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_NOT_ATTACHED))
fabricPrivacy.logCustom("OmnipodDashPodActivated")
source.onSuccess(PumpEnactResult(injector).success(true))
source.onSuccess(PumpEnactResultImpl(injector).success(true))
}
)
}

View file

@ -0,0 +1,40 @@
package info.nightscout.androidaps
import info.nightscout.rx.AapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
@Suppress("SpellCheckingInspection")
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
}

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.endecry
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Assert
import org.junit.Test
import org.spongycastle.util.encoders.Hex

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message
import com.google.crypto.tink.subtle.Hex
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Assert.assertEquals
import org.junit.Test

View file

@ -1,24 +1,29 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.RandomByteGenerator
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.X25519KeyGenerator
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.interfaces.Config
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.mock
import org.mockito.Mockito.spy
import org.spongycastle.util.encoders.Hex
class KeyExchangeTest {
class KeyExchangeTest : TestBase() {
val keyGenerator = X25519KeyGenerator()
val keyGeneratorSpy = spy(keyGenerator)
var randomByteGenerator: RandomByteGenerator = mock(RandomByteGenerator::class.java)
@Mock lateinit var config: Config
@Test fun testLTK() {
val aapsLogger = AAPSLoggerTest()
@ -31,6 +36,7 @@ class KeyExchangeTest {
val ke = KeyExchange(
aapsLogger,
config,
keyGeneratorSpy,
randomByteGenerator
)

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.session
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Assert
import org.junit.Test
import org.spongycastle.util.encoders.Hex

View file

@ -1,17 +1,23 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.session
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.extensions.toHex
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.interfaces.Config
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Assert
import org.junit.Test
import org.mockito.Mock
import org.spongycastle.util.encoders.Hex
class MilenageTest {
class MilenageTest : TestBase() {
@Mock lateinit var config: Config
@Test fun testMilenage() {
val aapsLogger = AAPSLoggerTest()
val m = Milenage(
aapsLogger = aapsLogger,
config = config,
k = Hex.decode("c0772899720972a314f557de66d571dd"),
sqn = byteArrayOf(0, 0, 0, 0, 0, 2),
randParam = Hex.decode("c2cd1248451103bd77a6c7ef88c441ba")
@ -25,6 +31,7 @@ class MilenageTest {
val aapsLogger = AAPSLoggerTest()
val m = Milenage(
aapsLogger = aapsLogger,
config = config,
k = Hex.decode("78411ccad0fd0fb6f381a47fb3335ecb"),
sqn = byteArrayOf(0, 0, 0, 0, 0, 2), // 1 + 1
randParam = Hex.decode("4fc01ac1a94376ae3e052339c07d9e1f")
@ -38,6 +45,7 @@ class MilenageTest {
val aapsLogger = AAPSLoggerTest()
val m = Milenage(
aapsLogger = aapsLogger,
config = config,
k = Hex.decode("c0772899720972a314f557de66d571dd"),
// byteArrayOf(0,0,0,0,0x01,0x5d), this is in logs. SQN has to be incremented.
sqn = byteArrayOf(0, 0, 0, 0, 0x01, 0x5e),
@ -52,6 +60,7 @@ class MilenageTest {
val aapsLogger = AAPSLoggerTest()
val m = Milenage(
aapsLogger = aapsLogger,
config = config,
k = Hex.decode("689b860fde3331dd7e1671ad39985e3b"),
sqn = byteArrayOf(0, 0, 0, 0, 0, 8), // 1 + 1
auts = Hex.decode("84ff173947a67567985de71e4890"),

View file

@ -36,12 +36,12 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.ActivityNames;
import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.Pump;
@ -104,6 +104,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.TimeChangeType;
import info.nightscout.interfaces.PluginType;
import info.nightscout.rx.AapsSchedulers;
import info.nightscout.rx.bus.RxBus;
import info.nightscout.rx.events.EventAppExit;
@ -601,7 +602,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
@Override
public PumpEnactResult setNewBasalProfile(@NonNull Profile profile) {
if (!podStateManager.hasPodState())
return new PumpEnactResult(getInjector()).enacted(false).success(false).comment("Null pod state");
return new PumpEnactResultImpl(getInjector()).enacted(false).success(false).comment("Null pod state");
PumpEnactResult result = executeCommand(OmnipodCommandType.SET_BASAL_PROFILE, () -> aapsOmnipodErosManager.setBasalProfile(profile, true));
aapsLogger.info(LTag.PUMP, "Basal Profile was set: " + result.getSuccess());
@ -659,7 +660,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
if (detailedBolusInfo.insulin == 0 && detailedBolusInfo.carbs == 0) {
// neither carbs nor bolus requested
aapsLogger.error("deliverTreatment: Invalid input: neither carbs nor insulin are set in treatment");
return new PumpEnactResult(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d)
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d)
.comment(R.string.invalidinput);
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
@ -677,7 +678,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
"[date=%d, carbs=%.2f, pumpSerial=%s] - Result: %b",
detailedBolusInfo.timestamp, detailedBolusInfo.carbs, serialNumber(), result));
return new PumpEnactResult(getInjector()).success(true).enacted(true).bolusDelivered(0d)
return new PumpEnactResultImpl(getInjector()).success(true).enacted(true).bolusDelivered(0d)
.carbsDelivered(detailedBolusInfo.carbs);
}
}
@ -695,7 +696,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute: rate: {}, duration={}", absoluteRate, durationInMinutes);
if (durationInMinutes <= 0 || durationInMinutes % BASAL_STEP_DURATION.getStandardMinutes() != 0) {
return new PumpEnactResult(getInjector()).success(false).comment(rh.gs(R.string.omnipod_eros_error_set_temp_basal_failed_validation, BASAL_STEP_DURATION.getStandardMinutes()));
return new PumpEnactResultImpl(getInjector()).success(false).comment(rh.gs(R.string.omnipod_eros_error_set_temp_basal_failed_validation, BASAL_STEP_DURATION.getStandardMinutes()));
}
// read current TBR
@ -709,7 +710,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
if (tbrCurrent != null && !enforceNew) {
if (Round.INSTANCE.isSame(tbrCurrent.getRate(), absoluteRate)) {
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - No enforceNew and same rate. Exiting.");
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
}
@ -731,7 +732,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
if (tbrCurrent == null) {
aapsLogger.info(LTag.PUMP, "cancelTempBasal - TBR already cancelled.");
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
return executeCommand(OmnipodCommandType.CANCEL_TEMPORARY_BASAL, aapsOmnipodErosManager::cancelTemporaryBasal);
@ -855,7 +856,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
@Override
public PumpEnactResult executeCustomCommand(@NonNull CustomCommand command) {
if (!podStateManager.hasPodState())
return new PumpEnactResult(getInjector()).enacted(false).success(false).comment("Null pod state");
return new PumpEnactResultImpl(getInjector()).enacted(false).success(false).comment("Null pod state");
if (command instanceof CommandSilenceAlerts) {
return executeCommand(OmnipodCommandType.ACKNOWLEDGE_ALERTS, aapsOmnipodErosManager::acknowledgeAlerts);
}
@ -885,7 +886,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
}
aapsLogger.warn(LTag.PUMP, "Unsupported custom command: " + command.getClass().getName());
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(rh.gs(R.string.omnipod_common_error_unsupported_custom_command, command.getClass().getName()));
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(rh.gs(R.string.omnipod_common_error_unsupported_custom_command, command.getClass().getName()));
}
private PumpEnactResult retrievePulseLog() {
@ -893,7 +894,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
try {
result = executeCommand(OmnipodCommandType.READ_POD_PULSE_LOG, aapsOmnipodErosManager::readPulseLog);
} catch (Exception ex) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(aapsOmnipodErosManager.translateException(ex));
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(aapsOmnipodErosManager.translateException(ex));
}
Intent i = new Intent(context, activityNames.getErrorHelperActivity());
@ -903,7 +904,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
i.putExtra("clipboardContent", result.toString());
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
return new PumpEnactResult(getInjector()).success(true).enacted(false);
return new PumpEnactResultImpl(getInjector()).success(true).enacted(false);
}
@NonNull private PumpEnactResult updateAlertConfiguration() {
@ -1168,7 +1169,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley
}
private PumpEnactResult getOperationNotSupportedWithCustomText(int resourceId) {
return new PumpEnactResult(getInjector()).success(false).enacted(false).comment(resourceId);
return new PumpEnactResultImpl(getInjector()).success(false).enacted(false).comment(resourceId);
}
}

View file

@ -16,6 +16,7 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.data.PumpEnactResultImpl;
import info.nightscout.androidaps.extensions.PumpStateExtensionKt;
import info.nightscout.androidaps.interfaces.ActivityNames;
import info.nightscout.androidaps.interfaces.Profile;
@ -168,7 +169,7 @@ public class AapsOmnipodErosManager {
}
public PumpEnactResult initializePod() {
PumpEnactResult result = new PumpEnactResult(injector);
PumpEnactResult result = new PumpEnactResultImpl(injector);
try {
Boolean res = executeCommand(delegate::pairAndPrime)
.blockingGet();
@ -190,10 +191,10 @@ public class AapsOmnipodErosManager {
public PumpEnactResult insertCannula(Profile profile) {
if (profile == null) {
String comment = getStringResource(R.string.omnipod_common_error_set_initial_basal_schedule_no_profile);
return new PumpEnactResult(injector).success(false).enacted(false).comment(comment);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(comment);
}
PumpEnactResult result = new PumpEnactResult(injector);
PumpEnactResult result = new PumpEnactResultImpl(injector);
try {
BasalSchedule basalSchedule = mapProfileToBasalSchedule(profile);
@ -231,11 +232,11 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.CONFIGURE_ALERTS, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.CONFIGURE_ALERTS, alertConfigurations);
return new PumpEnactResult(injector).success(true).enacted(false);
return new PumpEnactResultImpl(injector).success(true).enacted(false);
}
public PumpEnactResult playTestBeep(BeepConfigType beepType) {
@ -244,11 +245,11 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.PLAY_TEST_BEEP, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.PLAY_TEST_BEEP, beepType);
return new PumpEnactResult(injector).success(true).enacted(false);
return new PumpEnactResultImpl(injector).success(true).enacted(false);
}
@ -260,12 +261,12 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.GET_POD_STATUS, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.GET_POD_STATUS, statusResponse);
return new PumpEnactResult(injector).success(true).enacted(false);
return new PumpEnactResultImpl(injector).success(true).enacted(false);
}
public PumpEnactResult deactivatePod() {
@ -274,7 +275,7 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.DEACTIVATE_POD, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.DEACTIVATE_POD, null);
@ -282,7 +283,7 @@ public class AapsOmnipodErosManager {
dismissNotification(Notification.OMNIPOD_POD_FAULT);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PumpEnactResult setBasalProfile(Profile profile, boolean showNotifications) {
@ -291,7 +292,7 @@ public class AapsOmnipodErosManager {
if (showNotifications) {
showNotification(Notification.FAILED_UPDATE_PROFILE, note, Notification.URGENT, R.raw.boluserror);
}
return new PumpEnactResult(injector).success(false).enacted(false).comment(note);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(note);
}
// #1963 return synthetic success if pre-activation
@ -299,7 +300,7 @@ public class AapsOmnipodErosManager {
// otherwise a catch-22
if (!podStateManager.getActivationProgress().isCompleted()) {
// TODO: i18n string
return new PumpEnactResult(injector).success(true).enacted(false).comment("pre" +
return new PumpEnactResultImpl(injector).success(true).enacted(false).comment("pre" +
"-activation basal change moot");
}
@ -315,14 +316,14 @@ public class AapsOmnipodErosManager {
}
String errorMessage = translateException(ex.getCause());
addFailureToHistory(historyEntryType, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (PrecedingCommandFailedUncertainlyException ex) {
if (showNotifications) {
showNotification(Notification.FAILED_UPDATE_PROFILE, getStringResource(R.string.omnipod_eros_error_set_basal_failed_delivery_might_be_suspended), Notification.URGENT, R.raw.boluserror);
}
String errorMessage = translateException(ex.getCause());
addFailureToHistory(historyEntryType, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (Exception ex) {
if (showNotifications) {
String note;
@ -335,7 +336,7 @@ public class AapsOmnipodErosManager {
}
String errorMessage = translateException(ex);
addFailureToHistory(historyEntryType, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
@ -353,7 +354,7 @@ public class AapsOmnipodErosManager {
dismissNotification(Notification.OMNIPOD_POD_SUSPENDED);
dismissNotification(Notification.OMNIPOD_TIME_OUT_OF_SYNC);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PumpEnactResult discardPodState() {
@ -367,7 +368,7 @@ public class AapsOmnipodErosManager {
sendEvent(new EventOmnipodErosPumpValuesChanged());
sendEvent(new EventRefreshOverview("Omnipod command: " + OmnipodCommandType.DISCARD_POD, false));
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PumpEnactResult bolus(DetailedBolusInfo detailedBolusInfo) {
@ -391,7 +392,7 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(System.currentTimeMillis(), PodHistoryEntryType.SET_BOLUS, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
if (OmnipodManager.CommandDeliveryStatus.UNCERTAIN_FAILURE.equals(bolusCommandResult.getCommandDeliveryStatus())) {
@ -446,7 +447,7 @@ public class AapsOmnipodErosManager {
sp.remove(OmnipodErosStorageKeys.Preferences.ACTIVE_BOLUS);
return new PumpEnactResult(injector).success(true).enacted(true).carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(detailedBolusInfo.insulin);
return new PumpEnactResultImpl(injector).success(true).enacted(true).carbsDelivered(detailedBolusInfo.carbs).bolusDelivered(detailedBolusInfo.insulin);
}
public PumpEnactResult cancelBolus() {
@ -461,7 +462,7 @@ public class AapsOmnipodErosManager {
aapsLogger.debug(LTag.PUMP, "Not cancelling bolus: bolus command failed");
String comment = getStringResource(R.string.omnipod_common_error_bolus_did_not_succeed);
addFailureToHistory(System.currentTimeMillis(), PodHistoryEntryType.CANCEL_BOLUS, comment);
return new PumpEnactResult(injector).success(true).enacted(false).comment(comment);
return new PumpEnactResultImpl(injector).success(true).enacted(false).comment(comment);
}
}
@ -473,11 +474,11 @@ public class AapsOmnipodErosManager {
executeCommand(() -> delegate.cancelBolus(isBolusBeepsEnabled()));
aapsLogger.debug(LTag.PUMP, "Successfully cancelled bolus", i);
addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.CANCEL_BOLUS, null);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
} catch (PodFaultException ex) {
aapsLogger.debug(LTag.PUMP, "Successfully cancelled bolus (implicitly because of a Pod Fault)");
addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.CANCEL_BOLUS, null);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
} catch (Exception ex) {
aapsLogger.debug(LTag.PUMP, "Failed to cancel bolus", ex);
comment = translateException(ex);
@ -485,7 +486,7 @@ public class AapsOmnipodErosManager {
}
addFailureToHistory(System.currentTimeMillis(), PodHistoryEntryType.CANCEL_BOLUS, comment);
return new PumpEnactResult(injector).success(false).enacted(false).comment(comment);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(comment);
}
public PumpEnactResult setTemporaryBasal(TempBasalPair tempBasalPair) {
@ -495,7 +496,7 @@ public class AapsOmnipodErosManager {
} catch (CommandFailedAfterChangingDeliveryStatusException ex) {
String errorMessage = translateException(ex.getCause());
addFailureToHistory(PodHistoryEntryType.SET_TEMPORARY_BASAL, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (PrecedingCommandFailedUncertainlyException ex) {
String errorMessage = translateException(ex.getCause());
addFailureToHistory(PodHistoryEntryType.SET_TEMPORARY_BASAL, errorMessage);
@ -504,7 +505,7 @@ public class AapsOmnipodErosManager {
splitActiveTbr(); // Split any active TBR so when we recover from the uncertain TBR status,we only cancel the part after the cancellation
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (Exception ex) {
String errorMessage = translateException(ex);
long pumpId = addFailureToHistory(PodHistoryEntryType.SET_TEMPORARY_BASAL, errorMessage);
@ -522,7 +523,7 @@ public class AapsOmnipodErosManager {
addTempBasalTreatment(System.currentTimeMillis(), pumpId, tempBasalPair);
}
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
long pumpId = addSuccessToHistory(PodHistoryEntryType.SET_TEMPORARY_BASAL, tempBasalPair);
@ -531,7 +532,7 @@ public class AapsOmnipodErosManager {
sendEvent(new EventDismissNotification(Notification.OMNIPOD_TBR_ALERTS));
return new PumpEnactResult(injector)
return new PumpEnactResultImpl(injector)
.duration(tempBasalPair.getDurationMinutes())
.absolute(PumpType.OMNIPOD_EROS.determineCorrectBasalSize(tempBasalPair.getInsulinRate()))
.success(true).enacted(true);
@ -548,7 +549,7 @@ public class AapsOmnipodErosManager {
}
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.CANCEL_TEMPORARY_BASAL, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
long pumpId = addSuccessToHistory(PodHistoryEntryType.CANCEL_TEMPORARY_BASAL, null);
@ -562,7 +563,7 @@ public class AapsOmnipodErosManager {
sendEvent(new EventDismissNotification(Notification.OMNIPOD_TBR_ALERTS));
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PumpEnactResult acknowledgeAlerts() {
@ -571,11 +572,11 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.ACKNOWLEDGE_ALERTS, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.ACKNOWLEDGE_ALERTS, null);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PumpEnactResult suspendDelivery() {
@ -584,7 +585,7 @@ public class AapsOmnipodErosManager {
} catch (Exception ex) {
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.SUSPEND_DELIVERY, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.SUSPEND_DELIVERY, null);
@ -593,7 +594,7 @@ public class AapsOmnipodErosManager {
dismissNotification(Notification.FAILED_UPDATE_PROFILE);
dismissNotification(Notification.OMNIPOD_TIME_OUT_OF_SYNC);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
// Updates the pods current time based on the device timezone and the pod's time zone
@ -607,21 +608,21 @@ public class AapsOmnipodErosManager {
}
String errorMessage = translateException(ex.getCause());
addFailureToHistory(PodHistoryEntryType.SET_TIME, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (PrecedingCommandFailedUncertainlyException ex) {
if (showNotifications) {
showNotification(Notification.FAILED_UPDATE_PROFILE, getStringResource(R.string.omnipod_eros_error_set_time_failed_delivery_might_be_suspended), Notification.URGENT, R.raw.boluserror);
}
String errorMessage = translateException(ex.getCause());
addFailureToHistory(PodHistoryEntryType.SET_TIME, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
} catch (Exception ex) {
if (showNotifications) {
showNotification(Notification.FAILED_UPDATE_PROFILE, getStringResource(R.string.omnipod_eros_error_set_time_failed_delivery_might_be_suspended), Notification.URGENT, R.raw.boluserror);
}
String errorMessage = translateException(ex);
addFailureToHistory(PodHistoryEntryType.SET_TIME, errorMessage);
return new PumpEnactResult(injector).success(false).enacted(false).comment(errorMessage);
return new PumpEnactResultImpl(injector).success(false).enacted(false).comment(errorMessage);
}
addSuccessToHistory(PodHistoryEntryType.SET_TIME, null);
@ -630,7 +631,7 @@ public class AapsOmnipodErosManager {
dismissNotification(Notification.OMNIPOD_POD_SUSPENDED);
dismissNotification(Notification.OMNIPOD_TIME_OUT_OF_SYNC);
return new PumpEnactResult(injector).success(true).enacted(true);
return new PumpEnactResultImpl(injector).success(true).enacted(true);
}
public PodInfoRecentPulseLog readPulseLog() {

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ActivityNames
import info.nightscout.androidaps.interfaces.CommandQueue
@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.bus.RxBus
import org.joda.time.DateTimeZone
import org.joda.time.tz.UTCProvider
@ -74,7 +74,7 @@ class OmnipodErosPumpPluginTest : TestBase() {
)
).thenAnswer { invocation: InvocationOnMock ->
val pair = invocation.getArgument<TempBasalPair>(0)
val result = PumpEnactResult(injector)
val result = PumpEnactResultImpl(injector)
result.absolute(pair.insulinRate)
result.duration(pair.durationMinutes)
result

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.manager
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FirmwareVersion
import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.bus.RxBus
import info.nightscout.shared.sharedPreferences.SP
import org.joda.time.DateTime

View file

@ -8,6 +8,7 @@ import com.google.gson.GsonBuilder
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.extensions.toStringFull
@ -312,7 +313,7 @@ abstract class PumpPluginAbstract protected constructor(
if (detailedBolusInfo.insulin == 0.0 && detailedBolusInfo.carbs == 0.0) {
// neither carbs nor bolus requested
aapsLogger.error("deliverTreatment: Invalid input")
PumpEnactResult(injector).success(false).enacted(false).bolusDelivered(0.0).carbsDelivered(0.0)
PumpEnactResultImpl(injector).success(false).enacted(false).bolusDelivered(0.0).carbsDelivered(0.0)
.comment(R.string.invalidinput)
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
@ -328,7 +329,7 @@ abstract class PumpPluginAbstract protected constructor(
bolusingEvent.percent = 100
rxBus.send(bolusingEvent)
aapsLogger.debug(LTag.PUMP, "deliverTreatment: Carb only treatment.")
PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(0.0)
PumpEnactResultImpl(injector).success(true).enacted(true).bolusDelivered(0.0)
.carbsDelivered(detailedBolusInfo.carbs).comment(R.string.common_resultok)
}
} finally {
@ -349,7 +350,7 @@ abstract class PumpPluginAbstract protected constructor(
protected abstract fun triggerUIChange()
private fun getOperationNotSupportedWithCustomText(resourceId: Int): PumpEnactResult =
PumpEnactResult(injector).success(false).enacted(false).comment(resourceId)
PumpEnactResultImpl(injector).success(false).enacted(false).comment(resourceId)
init {
pumpDescription.fillFor(pumpType)

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -1,14 +1,14 @@
package info.nightscout.androidaps
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.rx.TestAapsSchedulers
import info.nightscout.rx.logging.AAPSLoggerTest
import org.junit.Before
import org.junit.Rule
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.data.PumpEnactResultImpl
import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.interfaces.Pump
import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
@ -43,26 +44,30 @@ class TestPumpPlugin(val injector: HasAndroidInjector) : Pump {
override fun waitForDisconnectionInSeconds(): Int = 0
override fun getPumpStatus(reason: String) {}
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResult(injector)
override fun setNewBasalProfile(profile: Profile): PumpEnactResult = PumpEnactResultImpl(injector)
override fun isThisProfileSet(profile: Profile): Boolean = isProfileSet
override fun lastDataTime(): Long = lastData
override val baseBasalRate: Double = baseBasal
override val reservoirLevel: Double = 0.0
override val batteryLevel: Int = 0
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun stopBolusDelivering() {}
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult =
PumpEnactResultImpl(injector).success(true)
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun cancelExtendedBolus(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject = JSONObject()
override fun manufacturer(): ManufacturerType = ManufacturerType.AAPS
override fun model(): PumpType = PumpType.GENERIC_AAPS
override fun serialNumber(): String = "1"
override fun shortStatus(veryShort: Boolean): String = ""
override val isFakingTempsByExtendedBoluses: Boolean = false
override fun loadTDDs(): PumpEnactResult = PumpEnactResult(injector).success(true)
override fun loadTDDs(): PumpEnactResult = PumpEnactResultImpl(injector).success(true)
override fun canHandleDST(): Boolean = true
override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) {}
}

View file

@ -7,7 +7,7 @@ import info.nightscout.androidaps.interaction.utils.WearUtil
import info.nightscout.androidaps.testing.mockers.WearUtilMocker
import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.rx.logging.AAPSLoggerTest
import info.nightscout.shared.sharedPreferences.SP
import org.junit.Before
import org.junit.Rule
@ -16,7 +16,7 @@ import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
import java.util.Locale
open class TestBase {