diff --git a/app/build.gradle b/app/build.gradle index 928faf6625..f8b150939a 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -163,6 +163,10 @@ android { } useLibrary "org.apache.http.legacy" + + dataBinding { //Deleting it causes a binding error + enabled = true + } } allprojects { diff --git a/app/libs/eopatch_core.aar b/app/libs/eopatch_core.aar index 1a8aafe38f..837d402724 100644 Binary files a/app/libs/eopatch_core.aar and b/app/libs/eopatch_core.aar differ diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 0453fe87bb..2c80dd65f7 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -105,6 +105,7 @@ DanaRv2 DanaI Diaconn G8 + Eoflow Eopatch2 Medtronic 512/712 Medtronic 515/715 Medtronic 522/722 diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index 3c90148a1a..fd24cf070d 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -330,6 +330,7 @@ enum class PumpType { baseBasalStep = 0.05, baseBasalSpecialSteps = null, pumpCapability = PumpCapability.EopatchCapabilities, + isPatchPump = true, source = Sources.EOPatch2); val description: String diff --git a/eopatch/build.gradle b/eopatch/build.gradle index 2dd1ac5ed3..b60889cbcd 100644 --- a/eopatch/build.gradle +++ b/eopatch/build.gradle @@ -26,20 +26,12 @@ allprojects { dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation (name: 'eopatch_core', ext: 'aar') +// implementation (files("libs/eopatch_core.aar")) implementation project(':core') implementation project(':shared') implementation project(':database') - implementation 'androidx.core:core-ktx:1.6.0' - implementation 'androidx.appcompat:appcompat:1.3.1' - implementation 'androidx.legacy:legacy-support-v4:1.0.0' - - // RxJava - implementation "io.reactivex.rxjava2:rxjava:$rxjava_version" - implementation "io.reactivex.rxjava2:rxkotlin:$rxkotlin_version" - implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version" - //RxAndroidBle - implementation "com.polidea.rxandroidble2:rxandroidble:$rxandroidble_version" - implementation "com.jakewharton.rx2:replaying-share:$replayshare_version" + implementation "com.polidea.rxandroidble2:rxandroidble:1.12.1" + implementation "com.jakewharton.rx2:replaying-share:2.2.0" } \ No newline at end of file diff --git a/eopatch/libs/eopatch_core.aar b/eopatch/libs/eopatch_core.aar index 1a8aafe38f..837d402724 100644 Binary files a/eopatch/libs/eopatch_core.aar and b/eopatch/libs/eopatch_core.aar differ diff --git a/eopatch/src/main/AndroidManifest.xml b/eopatch/src/main/AndroidManifest.xml index bd032c2f01..b41d2247be 100644 --- a/eopatch/src/main/AndroidManifest.xml +++ b/eopatch/src/main/AndroidManifest.xml @@ -3,7 +3,6 @@ package="info.nightscout.androidaps.plugins.pump.eopatch"> - diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/AppConstant.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/AppConstant.kt index c12f177563..81087620ef 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/AppConstant.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/AppConstant.kt @@ -1,87 +1,29 @@ package info.nightscout.androidaps.plugins.pump.eopatch -import java.util.concurrent.TimeUnit - interface AppConstant { companion object { + const val BASAL_MIN_AMOUNT = 0.05f - val BASAL_MIN_AMOUNT = 0.05f - val CLICK_THROTTLE = 600L + const val INSULIN_UNIT_P = 0.05f - /** - * Bluetooth Connection State - */ - val BT_STATE_NOT_CONNECT = 1 - val BT_STATE_CONNECTED = 2 + const val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P + const val OFF = 0 + const val ON = 1 - val INSULIN_DECIMAL_PLACE_VAR = 100f // 10.f; 소수점자리수 계산상수 (100.f 는 두자리) + const val PUMP_DURATION_MILLI = 4 * 1000L - // 패치 1P = 1 cycle = 0.1U - const val INSULIN_UNIT_P = 0.05f // 최소 주입 단위 + const val BASAL_RATE_PER_HOUR_MIN = BASAL_MIN_AMOUNT - val INSULIN_UNIT_MIN_U = 0f - val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P + const val SEGMENT_MAX_SIZE_48 = 48 + const val SEGMENT_COUNT_MAX = SEGMENT_MAX_SIZE_48 - /** - * On/Off - */ - val OFF = 0 - val ON = 1 + const val BOLUS_ACTIVE_EXTENDED_WAIT = 0x2 - /** - * Pump Duration, Interval - */ - val PUMP_DURATION_MILLI = TimeUnit.SECONDS.toMillis(4) // 15; - val PUMP_RESOLUTION = INSULIN_UNIT_P - - /** - * Basal - */ - val BASAL_RATE_PER_HOUR_MIN = BASAL_MIN_AMOUNT - val BASAL_RATE_PER_HOUR_STEP = INSULIN_UNIT_STEP_U - val BASAL_RATE_PER_HOUR_MAX = 15.0f // 30.0f; 30.00U/hr - - val SEGMENT_MAX_SIZE_48 = 48 - val SEGMENT_MAX_SIZE = SEGMENT_MAX_SIZE_48 - - val SEGMENT_COUNT_MAX = SEGMENT_MAX_SIZE_48 - - /** - * Bolus - */ - val BOLUS_NORMAL_ID = 0x1 - val BOLUS_EXTENDED_ID = 0x2 - - val BOLUS_ACTIVE_OFF = OFF - val BOLUS_ACTIVE_NORMAL = 0x01 - val BOLUS_ACTIVE_EXTENDED_WAIT = 0x2 - val BOLUS_ACTIVE_EXTENDED = 0x04 - val BOLUS_ACTIVE_DISCONNECTED = 0x08 - - val BOLUS_UNIT_MIN = BASAL_MIN_AMOUNT - val BOLUS_UNIT_STEP = INSULIN_UNIT_STEP_U - val BOLUS_UNIT_MAX = 25.0f // 30.0f; - val BOLUS_DELIVER_MIN = 0.0f - - - - /* Wizard */ - val WIZARD_STEP_MAX = 24 - - val INFO_REMINDER_DEFAULT_VALUE = 1 - - - val DAY_START_MINUTE = 0 * 60 - val DAY_END_MINUTE = 24 * 60 - - - val SNOOZE_INTERVAL_STEP = 5 - - /* Insulin Duration */ - val INSULIN_DURATION_MIN = 2.0f - val INSULIN_DURATION_MAX = 8.0f - val INSULIN_DURATION_STEP = 0.5f + const val BOLUS_UNIT_STEP = INSULIN_UNIT_STEP_U + const val DAY_START_MINUTE = 0 * 60 + const val DAY_END_MINUTE = 24 * 60 + const val INSULIN_DURATION_MIN = 2.0f } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/CommonUtils.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/CommonUtils.kt index f2d9c2fb5b..2780825ed7 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/CommonUtils.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/CommonUtils.kt @@ -1,37 +1,23 @@ package info.nightscout.androidaps.plugins.pump.eopatch - -import android.content.Context -import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import io.reactivex.disposables.Disposable import java.util.* -import java.util.function.Function +import kotlin.math.abs +import kotlin.math.min object CommonUtils { - val TO_INT = Function { it.toInt() } - val TO_FLOAT = Function { it.toFloat() } - val TO_STRING = Function { it.toString() } - val TO_CLOCK = Function{ num -> String.format(Locale.US, "%d:%02d", num.toInt() / 60, num.toInt() % 60) } - - @JvmStatic fun dispose(vararg disposable: Disposable?) { + fun dispose(vararg disposable: Disposable?) { for (d in disposable){ d?.let { - if (!it.isDisposed()) { + if (!it.isDisposed) { it.dispose() } } } } - @JvmStatic fun nullSafe(ch: CharSequence?): String { - if (ch == null) - return "" - val str = ch.toString() - return str - } - - @JvmStatic fun hasText(str: CharSequence?): Boolean { - if (str == null || str.length == 0) { + fun hasText(str: CharSequence?): Boolean { + if (str == null || str.isEmpty()) { return false } val strLen = str.length @@ -43,12 +29,12 @@ object CommonUtils { return false } - @JvmStatic fun hasText(str: String?): Boolean { + fun hasText(str: String?): Boolean { return str?.let{hasText(it as CharSequence)}?:false } - @JvmStatic fun isStringEmpty(cs: CharSequence?): Boolean { - return cs == null || cs.length == 0 + fun isStringEmpty(cs: CharSequence?): Boolean { + return cs == null || cs.isEmpty() } @JvmStatic fun dateString(millis: Long): String { @@ -69,109 +55,42 @@ object CommonUtils { c.get(Calendar.SECOND)) } - fun getTimeString(millis: Long): String { - val c = Calendar.getInstance() - c.timeInMillis = millis - return getTimeString(c) - } - - fun getTimeString(c: Calendar): String { - return String.format(Locale.US, "%02d:%02d", - c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE)) - } - - fun bytesToStringArray(byteArray: ByteArray?): String { - if (byteArray == null || byteArray.size == 0) { - return "null" - } - - val sb = StringBuilder() - for (b in byteArray) { - if (sb.length > 0) { - sb.append(String.format(" %02x", b)) - } else { - sb.append(String.format("0x%02x", b)) - } - } - return sb.toString() - } - - fun insulinFormat(): String { - if (AppConstant.INSULIN_UNIT_STEP_U == 0.1f) { - return "%.1f" - } - return if (AppConstant.INSULIN_UNIT_STEP_U == 0.05f) { - "%.2f" - } else "%.2f 인슐린출력형식추가하셈" - - } - - fun convertInsulinFormat(context: Context, strResId: Int): String { - if (AppConstant.INSULIN_UNIT_STEP_U == 0.1f) { - return context.getString(strResId).replace(".2f", ".1f") - } - if (AppConstant.INSULIN_UNIT_STEP_U == 0.05f) { - return context.getString(strResId) - } - - return context.getString(strResId).replace(".2f", ".2f 인슐린출력형식추가하셈") - - } - fun getRemainHourMin(timeMillis: Long): Pair { val diffHours: Long var diffMinutes: Long if (timeMillis >= 0) { - diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60) + 1 + diffMinutes = abs(timeMillis / (60 * 1000) % 60) + 1 if (diffMinutes == 60L) { diffMinutes = 0 - diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) + 1 + diffHours = abs(timeMillis / (60 * 60 * 1000)) + 1 } else { - diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) + diffHours = abs(timeMillis / (60 * 60 * 1000)) } } else { - diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60) - diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) + diffMinutes = abs(timeMillis / (60 * 1000) % 60) + diffHours = abs(timeMillis / (60 * 60 * 1000)) } return Pair(diffHours, diffMinutes) } - fun getTimeString(minutes: Int): String { - return String.format("%d:%02d", minutes / 60, minutes % 60) - } - - fun getTimeString_hhmm(minutes: Int): String { - return String.format("%02d:%02d", minutes / 60, minutes % 60) - } - - @JvmStatic - fun generatePumpId(date: Long, typeCode: Long = 0): Long { - return DateTimeUtil.toATechDate(date) * 100L + typeCode - } - - @JvmStatic fun nearlyEqual(a: Float, b: Float, epsilon: Float): Boolean { - val absA = Math.abs(a) - val absB = Math.abs(b) - val diff = Math.abs(a - b) - return if (a == b) { // shortcut, handles infinities + val absA = abs(a) + val absB = abs(b) + val diff = abs(a - b) + return if (a == b) { true } else if (a == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) { - // a or b is zero or both are extremely close to it - // relative error is less meaningful here diff < epsilon * java.lang.Float.MIN_NORMAL - } else { // use relative error - diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon + } else { + diff / min(absA + absB, Float.MAX_VALUE) < epsilon } } - @JvmStatic fun nearlyNotEqual(a: Float, b: Float, epsilon: Float): Boolean { return !nearlyEqual(a, b, epsilon) } - @JvmStatic fun clone(src: T): T { return GsonHelper.sharedGson().fromJson(GsonHelper.sharedGson().toJson(src), src.javaClass) } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/EopatchPumpPlugin.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/EopatchPumpPlugin.kt index 630ed9e534..18852d29c1 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/EopatchPumpPlugin.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/EopatchPumpPlugin.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch -import android.content.Context import android.os.SystemClock import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat @@ -34,7 +33,6 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.TimeChangeType import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers -import info.nightscout.shared.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Consumer @@ -57,12 +55,12 @@ class EopatchPumpPlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val dateUtil: DateUtil, private val pumpSync: PumpSync, - private val patchmanager: IPatchManager, + private val patchManager: IPatchManager, private val alarmManager: IAlarmManager, private val preferenceManager: IPreferenceManager ):PumpPluginBase(PluginDescription() .mainType(PluginType.PUMP) - .fragmentClass(EopatchOverviewFragment::class.java.getName()) + .fragmentClass(EopatchOverviewFragment::class.java.name) .pluginIcon(R.drawable.ic_eopatch2_128) .pluginName(R.string.eopatch) .shortName(R.string.eopatch_shortname) @@ -72,8 +70,7 @@ class EopatchPumpPlugin @Inject constructor( private val mDisposables = CompositeDisposable() - var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2 - private set + private var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2 private var mLastDataTime: Long = 0 private val mPumpDescription = PumpDescription(mPumpType) @@ -83,10 +80,10 @@ class EopatchPumpPlugin @Inject constructor( .toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) .subscribe({ event: EventPreferenceChange -> - if (event.isChanged(rh, SettingKeys.LOW_RESERVIOR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) { - patchmanager.changeReminderSetting() + 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() + patchManager.changeBuzzerSetting() } }) { throwable: Throwable -> fabricPrivacy.logException(throwable) } ) @@ -94,10 +91,10 @@ class EopatchPumpPlugin @Inject constructor( mDisposables.add(rxBus .toObservable(EventAppInitialized::class.java) .observeOn(Schedulers.io()) - .subscribe({ event: EventAppInitialized? -> + .subscribe({ aapsLogger.debug(LTag.PUMP,"EventAppInitialized") preferenceManager.init() - patchmanager.init() + patchManager.init() alarmManager.init() }) { throwable: Throwable -> fabricPrivacy.logException(throwable) } ) @@ -106,7 +103,7 @@ class EopatchPumpPlugin @Inject constructor( override fun specialEnableCondition(): Boolean { //BG -> FG 시 패치 활성화 재진행 및 미처리 알람 발생 if(preferenceManager.isInitDone()) { - patchmanager.checkActivationProcess() + patchManager.checkActivationProcess() alarmManager.restartAll() } return super.specialEnableCondition() @@ -142,12 +139,11 @@ class EopatchPumpPlugin @Inject constructor( } override fun isInitialized(): Boolean { - val isInit = isConnected() && patchmanager.isActivated() - return isInit + return isConnected() && patchManager.isActivated } override fun isSuspended(): Boolean { - return patchmanager.patchState.isNormalBasalPaused + return patchManager.patchState.isNormalBasalPaused } override fun isBusy(): Boolean { @@ -155,11 +151,11 @@ class EopatchPumpPlugin @Inject constructor( } override fun isConnected(): Boolean { - return patchmanager.patchConnectionState.isConnected + return patchManager.patchConnectionState.isConnected } override fun isConnecting(): Boolean { - return patchmanager.patchConnectionState.isConnecting + return patchManager.patchConnectionState.isConnecting } override fun isHandshakeInProgress(): Boolean { @@ -182,22 +178,24 @@ class EopatchPumpPlugin @Inject constructor( } override fun getPumpStatus(reason: String) { - if (patchmanager.isActivated()) { + if (patchManager.isActivated) { if ("SMS" == reason) { aapsLogger.debug("Acknowledged AAPS getPumpStatus request it was requested through an SMS") }else{ aapsLogger.debug("Acknowledged AAPS getPumpStatus request") } - 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){ + if(patchManager.isActivated){ + if(patchManager.patchState.isTempBasalActive || patchManager.patchState.isBolusActive){ return PumpEnactResult(injector) }else{ var isSuccess: Boolean? = null @@ -208,24 +206,21 @@ class EopatchPumpPlugin @Inject constructor( } val nb = preferenceManager.getNormalBasalManager().convertProfileToNormalBasal(profile) - patchmanager.startBasal(nb) + mDisposables.add(patchManager.startBasal(nb) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> - if (response.isSuccess) { - preferenceManager.getNormalBasalManager().normalBasal = nb - preferenceManager.flushNormalBasalManager() - } result.onNext(response.isSuccess) - }, { throwable -> + }, { result.onNext(false) }) + ) do{ SystemClock.sleep(100) }while(isSuccess == null) disposable.dispose() - aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess?:false}"); + aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess?:false}") return PumpEnactResult(injector).apply{ success = isSuccess?:false } } }else{ @@ -236,12 +231,12 @@ class EopatchPumpPlugin @Inject constructor( } override fun isThisProfileSet(profile: Profile): Boolean { - if (!patchmanager.isActivated()) { + if (!patchManager.isActivated) { return true } val ret = preferenceManager.getNormalBasalManager().isEqual(profile) - aapsLogger.info(LTag.PUMP, "Is this profile set? ${ret}"); + aapsLogger.info(LTag.PUMP, "Is this profile set? $ret") return ret } @@ -251,7 +246,7 @@ class EopatchPumpPlugin @Inject constructor( override val baseBasalRate: Double get() { - if (!patchmanager.isActivated || patchmanager.patchState.isNormalBasalPaused) { + if (!patchManager.isActivated || patchManager.patchState.isNormalBasalPaused) { return 0.0 } @@ -260,20 +255,20 @@ class EopatchPumpPlugin @Inject constructor( override val reservoirLevel: Double get() { - if (!patchmanager.isActivated) { + if (!patchManager.isActivated) { return 0.0 } - val reserviorLevel = patchmanager.patchState.remainedInsulin.toDouble() + val reservoirLevel = patchManager.patchState.remainedInsulin.toDouble() - return (reserviorLevel > 50.0).takeOne(50.0, reserviorLevel) + return (reservoirLevel > 50.0).takeOne(50.0, reservoirLevel) } override val batteryLevel: Int get() { - if(patchmanager.isActivated) { - return patchmanager.patchState.batteryLevel() + return if(patchManager.isActivated) { + patchManager.patchState.batteryLevel() }else{ - return 0 + 0 } } @@ -292,7 +287,7 @@ class EopatchPumpPlugin @Inject constructor( isSuccess = it } - patchmanager.startCalculatorBolus(detailedBolusInfo) + mDisposables.add(patchManager.startCalculatorBolus(detailedBolusInfo) .doOnSuccess { mLastDataTime = System.currentTimeMillis() }.subscribe({ @@ -300,25 +295,26 @@ class EopatchPumpPlugin @Inject constructor( }, { result.onNext(false) }) + ) do{ SystemClock.sleep(100) - if(patchmanager.patchConnectionState.isConnected) { - var delivering = patchmanager.bolusCurrent.nowBolus.injected + if(patchManager.patchConnectionState.isConnected) { + val delivering = patchManager.bolusCurrent.nowBolus.injected rxBus.send(EventOverviewBolusProgress.apply { status = rh.gs(R.string.bolusdelivering, delivering) percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) }) } - }while(!patchmanager.bolusCurrent.nowBolus.endTimeSynced && isSuccess) + }while(!patchManager.bolusCurrent.nowBolus.endTimeSynced && isSuccess) rxBus.send(EventOverviewBolusProgress.apply { status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) percent = 100 }) - detailedBolusInfo.insulin = patchmanager.bolusCurrent.nowBolus.injected.toDouble() - patchmanager.addBolusToHistory(detailedBolusInfo) + detailedBolusInfo.insulin = patchManager.bolusCurrent.nowBolus.injected.toDouble() + patchManager.addBolusToHistory(detailedBolusInfo) disposable.dispose() @@ -329,37 +325,34 @@ class EopatchPumpPlugin @Inject constructor( } else { // no bolus required, carb only treatment - patchmanager.addBolusToHistory(detailedBolusInfo); + 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)); + .carbsDelivered(detailedBolusInfo.carbs).comment(rh.gs(info.nightscout.androidaps.core.R.string.ok)) } } override fun stopBolusDelivering() { - patchmanager.stopNowBolus() - .subscribeOn(aapsSchedulers.io) - .observeOn(aapsSchedulers.main) + 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)) //todo stoped 메세지로 변경 필요 + 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) + return patchManager.startTempBasal(tb) .subscribeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.main) .doOnSuccess { - preferenceManager.getTempBasalManager().startedBasal = tb - preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis() pumpSync.syncTemporaryBasalWithPumpId( timestamp = dateUtil.now(), rate = absoluteRate, @@ -372,7 +365,7 @@ class EopatchPumpPlugin @Inject constructor( ) aapsLogger.info(LTag.PUMP,"setTempBasalAbsolute - tbrCurrent:${readTBR()}") } - .map { it -> PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).absolute(absoluteRate).isPercent(false).isTempCancel(false) } + .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")) .blockingGet() @@ -384,15 +377,13 @@ class EopatchPumpPlugin @Inject constructor( 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){ + if(patchManager.patchState.isNormalBasalAct && percent != 0){ mLastDataTime = System.currentTimeMillis() val tb = TempBasal.createPercent(durationInMinutes.toLong(), percent) - return patchmanager.startTempBasal(tb) + return patchManager.startTempBasal(tb) .subscribeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.main) .doOnSuccess { - preferenceManager.getTempBasalManager().startedBasal = tb - preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis() pumpSync.syncTemporaryBasalWithPumpId( timestamp = dateUtil.now(), rate = percent.toDouble(), @@ -405,7 +396,7 @@ class EopatchPumpPlugin @Inject constructor( ) aapsLogger.info(LTag.PUMP,"setTempBasalPercent - tbrCurrent:${readTBR()}") } - .map { it -> PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).percent(percent).isPercent(true).isTempCancel(false) } + .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")) .blockingGet() @@ -418,7 +409,7 @@ class EopatchPumpPlugin @Inject constructor( override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { aapsLogger.info(LTag.PUMP,"setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes") - return patchmanager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes)) + return patchManager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes)) .doOnSuccess { mLastDataTime = System.currentTimeMillis() pumpSync.syncExtendedBolusWithPumpId( @@ -431,7 +422,7 @@ class EopatchPumpPlugin @Inject constructor( pumpSerial = serialNumber() ) } - .map { it -> PumpEnactResult(injector).success(true).enacted(true)} + .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))) .blockingGet() @@ -445,14 +436,14 @@ class EopatchPumpPlugin @Inject constructor( return PumpEnactResult(injector).success(true).enacted(false) } - if (!patchmanager.patchState.isTempBasalActive) { + 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) } - return patchmanager.stopTempBasal() + return patchManager.stopTempBasal() .doOnSuccess { mLastDataTime = System.currentTimeMillis() aapsLogger.debug(LTag.PUMP,"cancelTempBasal - $it") @@ -466,15 +457,15 @@ class EopatchPumpPlugin @Inject constructor( .doOnError{ aapsLogger.error(LTag.PUMP,"cancelTempBasal() - $it") } - .map { it -> PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)} + .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))) .blockingGet() } override fun cancelExtendedBolus(): PumpEnactResult { - if(patchmanager.patchState.isExtBolusActive){ - return patchmanager.stopExtBolus() + if(patchManager.patchState.isExtBolusActive){ + return patchManager.stopExtBolus() .doOnSuccess { aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - success") mLastDataTime = System.currentTimeMillis() @@ -485,7 +476,7 @@ class EopatchPumpPlugin @Inject constructor( pumpSerial = serialNumber() ) } - .map { it -> PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)} + .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))) .blockingGet() @@ -517,14 +508,14 @@ class EopatchPumpPlugin @Inject constructor( } override fun serialNumber(): String { - return patchmanager.patchConfig.patchSerialNumber + return patchManager.patchConfig.patchSerialNumber } override val pumpDescription: PumpDescription get() = mPumpDescription override fun shortStatus(veryShort: Boolean): String { - if(patchmanager.isActivated) { + if(patchManager.isActivated) { var ret = "" val activeTemp = pumpSync.expectedPumpState().temporaryBasal if (activeTemp != null) @@ -534,7 +525,7 @@ class EopatchPumpPlugin @Inject constructor( if (activeExtendedBolus != null) ret += "Extended: ${activeExtendedBolus.amount} U\n" - val reservoirStr = patchmanager.patchState.remainedInsulin.let { + val reservoirStr = patchManager.patchState.remainedInsulin.let { when { it > 50f -> "50+ U" it < 1f -> "0 U" @@ -543,7 +534,7 @@ class EopatchPumpPlugin @Inject constructor( } ret += "Reservoir: $reservoirStr" - ret += "Batt: ${patchmanager.patchState.batteryLevel()}" + ret += "Battery: ${patchManager.patchState.batteryLevel()}" return ret }else{ return "EOPatch is not enabled." diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/FloatFormatters.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/FloatFormatters.kt index badd141124..f90514ab22 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/FloatFormatters.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/FloatFormatters.kt @@ -4,7 +4,7 @@ import java.util.* import java.util.function.Function object FloatFormatters { - val INSULIN = Function{ value -> String.format(Locale.US, CommonUtils.insulinFormat(), value.toFloat()) } + val INSULIN = Function{ value -> String.format(Locale.US, "%.2f", value.toFloat()) } val FAT = Function{ value -> String.format(Locale.US, "%.1f", value.toFloat()) } val DURATION = Function{ value -> String.format(Locale.US, "%.1f", value.toFloat()) } @@ -16,19 +16,7 @@ object FloatFormatters { return if (CommonUtils.isStringEmpty(suffix)) { INSULIN.apply(value) } else { - INSULIN.apply(value).toString() +" "+ suffix!! - } - } - - fun fat(value: Float): String { - return FAT.apply(value) - } - - fun fat(value: Float, suffix: String?): String { - return if (CommonUtils.isStringEmpty(suffix)) { - FAT.apply(value) - } else { - FAT.apply(value).toString() + suffix!! + INSULIN.apply(value) +" "+ suffix!! } } @@ -40,7 +28,7 @@ object FloatFormatters { return if (CommonUtils.isStringEmpty(suffix)) { DURATION.apply(value) } else { - DURATION.apply(value).toString() +" " + suffix!! + DURATION.apply(value) +" " + suffix!! } } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/OsAlarmService.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/OsAlarmService.java index 141031e8cf..a1671f619a 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/OsAlarmService.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/OsAlarmService.java @@ -51,10 +51,6 @@ public class OsAlarmService extends Service { public synchronized void startForeground() { if (!foreground) { -//// CommonUtils.dispose(mNotificationDisposable); -// Notification builder = getNotification(this); -// startForeground(FOREGROUND_NOTIFICATION_ID, builder); -// startExerciseOrSleepMode(this); foreground = true; } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/RxAction.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/RxAction.kt index 4a4784eb78..2565d41e64 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/RxAction.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/RxAction.kt @@ -6,8 +6,6 @@ import android.os.SystemClock import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import io.reactivex.* -import io.reactivex.disposables.Disposable -import org.reactivestreams.Subscription import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton @@ -17,21 +15,10 @@ class RxAction @Inject constructor( private val aapsSchedulers: AapsSchedulers, private val aapsLogger: AAPSLogger ) { - enum class RxVoid { INSTANCE } - class SilentObserver(private val aapsLogger: AAPSLogger) : MaybeObserver, SingleObserver, Observer, FlowableSubscriber { - - override fun onSubscribe(d: Disposable) {} - override fun onSuccess(t: T) {} - override fun onError(e: Throwable) = aapsLogger.error("SilentObserver.onError() ignore", e) - override fun onComplete() {} - override fun onNext(t: T) {} - override fun onSubscribe(s: Subscription) {} - } - private fun sleep(millis: Long) { if (millis <= 0) return @@ -56,63 +43,14 @@ class RxAction @Inject constructor( } } - private fun safeSingle(action: Runnable, delayMs: Long, scheduler: Scheduler): Single<*> { - return single(action, delayMs, scheduler) - } - - @JvmOverloads - fun runOnComputationThread(action: Runnable, delayMs: Long = 0) { - single(action, delayMs, aapsSchedulers.cpu).subscribe(SilentObserver(aapsLogger)) - } - - @JvmOverloads - fun runOnIoThread(action: Runnable, delayMs: Long = 0) { - single(action, delayMs, aapsSchedulers.io).subscribe(SilentObserver(aapsLogger)) - } - - @JvmOverloads - fun runOnNewThread(action: Runnable, delayMs: Long = 0) { - single(action, delayMs, aapsSchedulers.newThread).subscribe(SilentObserver(aapsLogger)) - } - @JvmOverloads fun runOnMainThread(action: Runnable, delayMs: Long = 0) { - single(action, delayMs, aapsSchedulers.main).subscribe(SilentObserver(aapsLogger)) - } + single(action, delayMs, aapsSchedulers.main) + .subscribe({ - @JvmOverloads - fun safeRunOnComputationThread(action: Runnable, delayMs: Long = 0) { - safeSingle(action, delayMs, aapsSchedulers.cpu).subscribe(SilentObserver(aapsLogger)) - } - - @JvmOverloads - fun safeRunOnIoThread(action: Runnable, delayMs: Long = 0) { - safeSingle(action, delayMs, aapsSchedulers.io).subscribe(SilentObserver(aapsLogger)) - } - - @JvmOverloads - fun safeRunOnNewThread(action: Runnable, delayMs: Long = 0) { - safeSingle(action, delayMs, aapsSchedulers.newThread).subscribe(SilentObserver(aapsLogger)) - } - - @JvmOverloads - fun safeRunOnMainThread(action: Runnable, delayMs: Long = 0) { - safeSingle(action, delayMs, aapsSchedulers.main).subscribe(SilentObserver(aapsLogger)) - } - - fun singleOnMainThread(action: Runnable, delayMs: Long): Single<*> { - return single(action, delayMs, aapsSchedulers.main) - } - - fun singleOnComputationThread(action: Runnable, delayMs: Long): Single<*> { - return single(action, delayMs, aapsSchedulers.cpu) - } - - fun singleOnIoThread(action: Runnable, delayMs: Long): Single<*> { - return single(action, delayMs, aapsSchedulers.io) - } - - fun singleOnNewThread(action: Runnable, delayMs: Long): Single<*> { - return single(action, delayMs, aapsSchedulers.newThread) + }, + { e -> + aapsLogger.error("SilentObserver.onError() ignore", e) + }) } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmCode.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmCode.kt index cb410327bd..1fc2754f06 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmCode.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmCode.kt @@ -9,45 +9,47 @@ import java.util.function.Function import java.util.stream.Collectors import java.util.stream.Stream -enum class AlarmCode(defaultName: String, messageResId: Int) { - A002("Empty reservoir", R.string.string_a002), - A003("Patch expired", R.string.string_a003), - A004("Occlusion", R.string.string_a004), - A005("Power on self test failure", R.string.string_a005), - A007("Inappropriate temperature", R.string.string_a007), - A016("Needle insertion Error", R.string.string_a016), - A018("Patch battery Error", R.string.string_a018), - A019("Patch battery Error", R.string.string_a019), - A020("Patch activation Error", R.string.string_a020), - A022("Patch Error", R.string.string_a022), - A023("Patch Error", R.string.string_a023), - A034("Patch Error", R.string.string_a034), - A041("Patch Error", R.string.string_a041), - A042("Patch Error", R.string.string_a042), - A043("Patch Error", R.string.string_a043), - A044("Patch Error", R.string.string_a044), - A106("Patch Error", R.string.string_a106), - A107("Patch Error", R.string.string_a107), - A108("Patch Error", R.string.string_a108), - A116("Patch Error", R.string.string_a116), - A117("Patch Error", R.string.string_a117), - A118("Patch Error", R.string.string_a118), - B001("End of insulin suspend", R.string.string_b001), - B003("Low reservoir", R.string.string_b003), - B005("Patch operating life expired", R.string.string_b005), - B006("Patch will expire soon", R.string.string_b006), - B012("Incomplete Patch activation", R.string.string_b012), - B018("Patch battery low", R.string.string_b018); +enum class AlarmCode(messageResId: Int) { + A002(R.string.string_a002), //"Empty reservoir" + A003(R.string.string_a003), //"Patch expired" + A004(R.string.string_a004), //"Occlusion" + A005(R.string.string_a005), //"Power on self test failure" + A007(R.string.string_a007), //"Inappropriate temperature" + A016(R.string.string_a016), //"Needle insertion Error" + A018(R.string.string_a018), //"Patch battery Error" + A019(R.string.string_a019), //"Patch battery Error" + A020(R.string.string_a020), //"Patch activation Error" + A022(R.string.string_a022), //"Patch Error" + A023(R.string.string_a023), //"Patch Error" + A034(R.string.string_a034), //"Patch Error" + A041(R.string.string_a041), //"Patch Error" + A042(R.string.string_a042), //"Patch Error" + A043(R.string.string_a043), //"Patch Error" + A044(R.string.string_a044), //"Patch Error" + A106(R.string.string_a106), //"Patch Error" + A107(R.string.string_a107), //"Patch Error" + A108(R.string.string_a108), //"Patch Error" + A116(R.string.string_a116), //"Patch Error" + A117(R.string.string_a117), //"Patch Error" + A118(R.string.string_a118), //"Patch Error" + B001(R.string.string_b001), //"End of insulin suspend" + B003(R.string.string_b003), //"Low reservoir" + B005(R.string.string_b005), //"Patch operating life expired" + B006(R.string.string_b006), //"Patch will expire soon" + B012(R.string.string_b012), //"Incomplete Patch activation" + B018(R.string.string_b018); //"Patch battery low" + + val type: Char = name[0] + val code: Int = name.substring(1).toInt() + val resId: Int = messageResId - val type: Char - val code: Int - val resId: Int val alarmCategory: AlarmCategory get() = when (type) { TYPE_ALARM -> AlarmCategory.ALARM TYPE_ALERT -> AlarmCategory.ALERT else -> AlarmCategory.NONE } + val aeCode: Int get() { when (type) { @@ -57,13 +59,6 @@ enum class AlarmCode(defaultName: String, messageResId: Int) { return -1 } - val osAlarmId: Int - get() = (when (type) { - TYPE_ALARM -> 10000 - TYPE_ALERT -> 20000 - else -> 0 - } + code ) * 1000 + 1 - val isPatchOccurrenceAlert: Boolean get() = this == B003 || this == B005 || this == B006 || this == B018 @@ -72,12 +67,6 @@ enum class AlarmCode(defaultName: String, messageResId: Int) { || this == A023 || this == A034 || this == A041 || this == A042 || this == A043 || this == A044 || this == A106 || this == A107 || this == A108 || this == A116 || this == A117 || this == A118 - init { - type = name[0] - this.code = name.substring(1).toInt() - resId = messageResId - } - companion object { const val TYPE_ALARM = 'A' const val TYPE_ALERT = 'B' @@ -103,10 +92,10 @@ enum class AlarmCode(defaultName: String, messageResId: Int) { fun getUri(alarmCode: AlarmCode): Uri { return Uri.Builder() .scheme(SCHEME) - .authority("com.eoflow.eomapp") + .authority("info.nightscout.androidaps") .path(ALARM_KEY_PATH) .appendQueryParameter(QUERY_CODE, alarmCode.name) - .build(); + .build() } @JvmStatic diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmManager.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmManager.kt index 3929625d1c..b00b8067d4 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmManager.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmManager.kt @@ -26,10 +26,12 @@ import io.reactivex.Observable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable +import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton +import kotlin.math.max interface IAlarmManager { fun init() @@ -54,6 +56,7 @@ class AlarmManager @Inject constructor() : IAlarmManager { private lateinit var mAlarmProcess: AlarmProcess private var compositeDisposable: CompositeDisposable = CompositeDisposable() + private var alarmDisposable: Disposable? = null @Inject fun onInit() { @@ -61,27 +64,27 @@ class AlarmManager @Inject constructor() : IAlarmManager { } override fun init(){ - EoPatchRxBus.listen(EventEoPatchAlarm::class.java) - .map { it -> it.alarmCodes } + alarmDisposable = EoPatchRxBus.listen(EventEoPatchAlarm::class.java) + .map { it.alarmCodes } .doOnNext { aapsLogger.info(LTag.PUMP,"EventEoPatchAlarm Received") } .concatMap { Observable.fromArray(it) .observeOn(Schedulers.io()) .subscribeOn(AndroidSchedulers.mainThread()) .doOnNext { alarmCodes -> - alarmCodes.forEach { - aapsLogger.info(LTag.PUMP,"alarmCode: ${it.name}") - val valid = isValid(it) + alarmCodes.forEach { alarmCode -> + aapsLogger.info(LTag.PUMP,"alarmCode: ${alarmCode.name}") + val valid = isValid(alarmCode) if (valid) { - if (it.alarmCategory == AlarmCategory.ALARM || it == B012) { - showAlarmDialog(it) + if (alarmCode.alarmCategory == AlarmCategory.ALARM || alarmCode == B012) { + showAlarmDialog(alarmCode) } else { - showNotification(it) + showNotification(alarmCode) } - updateState(it, AlarmState.FIRED) + updateState(alarmCode, AlarmState.FIRED) }else{ - updateState(it, AlarmState.HANDLE) + updateState(alarmCode, AlarmState.HANDLE) } } } @@ -92,17 +95,19 @@ class AlarmManager @Inject constructor() : IAlarmManager { override fun restartAll() { val now = System.currentTimeMillis() - val occuredAlarm = pm.getAlarms().occured.clone() as HashMap + @Suppress("UNCHECKED_CAST") + val occurredAlarm= pm.getAlarms().occurred.clone() as HashMap + @Suppress("UNCHECKED_CAST") val registeredAlarm = pm.getAlarms().registered.clone() as HashMap compositeDisposable.clear() - if(occuredAlarm.isNotEmpty()){ - EoPatchRxBus.publish(EventEoPatchAlarm(occuredAlarm.keys)) + if(occurredAlarm.isNotEmpty()){ + EoPatchRxBus.publish(EventEoPatchAlarm(occurredAlarm.keys)) } if(registeredAlarm.isNotEmpty()){ registeredAlarm.forEach { raEntry -> compositeDisposable.add( - mAlarmRegistry.add(raEntry.key, Math.max(OS_REGISTER_GAP, raEntry.value.triggerTimeMilli - now)) + mAlarmRegistry.add(raEntry.key, max(OS_REGISTER_GAP, raEntry.value.triggerTimeMilli - now)) .subscribe() ) } @@ -112,11 +117,11 @@ class AlarmManager @Inject constructor() : IAlarmManager { private fun isValid(code: AlarmCode): Boolean{ return when(code){ A005, A016, A020, B012 -> { - aapsLogger.info(LTag.PUMP,"Is ${code} valid? ${pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning}") + aapsLogger.info(LTag.PUMP,"Is $code valid? ${pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning}") pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning } else -> { - aapsLogger.info(LTag.PUMP,"Is ${code} valid? ${pm.getPatchConfig().isActivated}") + aapsLogger.info(LTag.PUMP,"Is $code valid? ${pm.getPatchConfig().isActivated}") pm.getPatchConfig().isActivated } } @@ -133,11 +138,11 @@ class AlarmManager @Inject constructor() : IAlarmManager { } private fun showNotification(alarmCode: AlarmCode, timeOffset: Long = 0L){ - var occurredTimestamp: Long = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.SECONDS.toMillis(timeOffset) val notification = EONotification(Notification.EOELOW_PATCH_ALERTS + (alarmCode.aeCode + 10000), resourceHelper.gs(alarmCode.resId), Notification.URGENT) notification.action(R.string.confirm) { - Single.just(isValid(alarmCode)) + compositeDisposable.add( + Single.just(isValid(alarmCode)) .flatMap { isValid -> return@flatMap if(isValid) mAlarmProcess.doAction(context, alarmCode) else Single.just(IAlarmProcess.ALARM_HANDLED) @@ -148,17 +153,17 @@ class AlarmManager @Inject constructor() : IAlarmManager { }else{ rxBus.send(EventNewNotification(notification)) } - } + }) } notification.soundId = R.raw.error - notification.date = occurredTimestamp + notification.date = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.SECONDS.toMillis(timeOffset) rxBus.send(EventNewNotification(notification)) } private fun updateState(alarmCode: AlarmCode, state: AlarmState){ when(state){ AlarmState.REGISTER -> pm.getAlarms().register(alarmCode, 0) - AlarmState.FIRED -> pm.getAlarms().occured(alarmCode) + AlarmState.FIRED -> pm.getAlarms().occurred(alarmCode) AlarmState.HANDLE -> pm.getAlarms().handle(alarmCode) } pm.flushAlarms() diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmProcess.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmProcess.kt index 7f440d6527..cc686f9540 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmProcess.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmProcess.kt @@ -4,8 +4,7 @@ import android.content.Context import android.content.DialogInterface import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCheckConnection import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForDiscarded -import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForChangePatch -import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCanularInsertionError +import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCannulaInsertionError import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode.* import android.content.Intent @@ -13,7 +12,6 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.eopatch.R import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse -import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus import info.nightscout.androidaps.plugins.pump.eopatch.core.response.TemperatureResponse import info.nightscout.androidaps.plugins.pump.eopatch.event.EventDialog import info.nightscout.androidaps.plugins.pump.eopatch.event.EventProgressDialog @@ -40,13 +38,12 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr A002, A003, A004, A005, A018, A019, A020, A022, A023, A034, A041, A042, A043, A044, A106, A107, A108, A116, - A117, A118 -> patchDeactivationAction(context, true) + A117, A118 -> patchDeactivationAction(context) A007 -> inappropriateTemperatureAction(context) A016 -> needleInsertionErrorAction(context) B003, B018 -> Single.just(IAlarmProcess.ALARM_HANDLED) B005, B006 -> Single.just(IAlarmProcess.ALARM_HANDLED) B012 -> Single.just(IAlarmProcess.ALARM_HANDLED) - else -> Single.just(IAlarmProcess.ALARM_HANDLED) } } @@ -56,11 +53,11 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr } private fun showCommunicationFailedDialog(onConfirmed: Runnable) { - var dialog = CommonDialog().apply { + val dialog = CommonDialog().apply { title = R.string.patch_communication_failed message = R.string.patch_communication_check_helper_1 positiveBtn = R.string.string_communication_check - positiveListener = DialogInterface.OnClickListener { dialog, which -> + positiveListener = DialogInterface.OnClickListener { _, _ -> onConfirmed.run() dismiss() } @@ -80,7 +77,7 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr Single.fromCallable { showCommunicationFailedDialog { startActivityWithSingleTop(context, - createIntentForCheckConnection(context, true, true)) + createIntentForCheckConnection(context, goHomeAfterDiscard = true, forceDiscard = true)) } IAlarmProcess.ALARM_PAUSE } @@ -95,28 +92,21 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr } } - private fun patchDeactivationAction(context: Context, goHome: Boolean): Single { + private fun patchDeactivationAction(context: Context): Single { return actionWithPatchCheckConnection(context) { rxBus.send(EventProgressDialog(true, R.string.string_in_progress)) patchManager.deactivate(6000, true) .doFinally { rxBus.send(EventProgressDialog(false, R.string.string_in_progress)) - startActivityWithSingleTop(context, createIntentForDiscarded(context, goHome)) + startActivityWithSingleTop(context, createIntentForDiscarded(context)) } - .flatMap { ok: DeactivationStatus? -> Single.just(IAlarmProcess.ALARM_HANDLED) } - } - } - - private fun changPatchAction(context: Context): Single { - return Single.fromCallable { - startActivityWithSingleTop(context, createIntentForChangePatch(context)) - IAlarmProcess.ALARM_HANDLED + .flatMap { Single.just(IAlarmProcess.ALARM_HANDLED) } } } private fun needleInsertionErrorAction(context: Context): Single { return Single.fromCallable { - startActivityWithSingleTop(context, createIntentForCanularInsertionError(context)) + startActivityWithSingleTop(context, createIntentForCannulaInsertionError(context)) IAlarmProcess.ALARM_HANDLED } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt index 7d8c6ad1a6..157fea2d95 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt @@ -29,7 +29,7 @@ import javax.inject.Singleton interface IAlarmRegistry { fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean = false): Maybe fun add(patchAeCodes: Set) - fun remove(alarmKey: AlarmCode): Maybe + fun remove(alarmCode: AlarmCode): Maybe } @Singleton @@ -60,29 +60,30 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { PatchLifecycle.SHUTDOWN -> { val sources = ArrayList>() sources.add(Maybe.just(true)) - pm.getAlarms().occured.let{ - if(it.isNotEmpty()){ - it.keys.forEach { + pm.getAlarms().occurred.let{ occurredAlarms -> + if(occurredAlarms.isNotEmpty()){ + occurredAlarms.keys.forEach { alarmCode -> sources.add( - Maybe.just(it) + Maybe.just(alarmCode) .observeOn(aapsSchedulers.main) - .doOnSuccess { rxBus.send(EventDismissNotification(Notification.EOELOW_PATCH_ALERTS + (it.aeCode + 10000))) } + .doOnSuccess { rxBus.send(EventDismissNotification(Notification.EOELOW_PATCH_ALERTS + (alarmCode.aeCode + 10000))) } ) } } } - pm.getAlarms().registered.let{ - if(it.isNotEmpty()){ - it.keys.forEach { - sources.add(remove(it)) + pm.getAlarms().registered.let{ registeredAlarms -> + if(registeredAlarms.isNotEmpty()){ + registeredAlarms.keys.forEach { alarmCode -> + sources.add(remove(alarmCode)) } } } - Maybe.concat(sources) + compositeDisposable.add(Maybe.concat(sources) .subscribe { pm.getAlarms().clear() pm.flushAlarms() } + ) } else -> Unit @@ -91,7 +92,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { } override fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean): Maybe { - if(pm.getAlarms().occured.containsKey(alarmCode)){ + if(pm.getAlarms().occurred.containsKey(alarmCode)){ return Maybe.just(alarmCode) }else { val triggerTimeMilli = System.currentTimeMillis() + triggerAfter @@ -110,7 +111,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { Observable.fromIterable(patchAeCodes) .filter{patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.getAeValue()) != null} .observeOn(AndroidSchedulers.mainThread()) - .filter { patchAeCodes -> AlarmCode.findByPatchAeCode(patchAeCodes.getAeValue()) != null } + .filter { aeCodes -> AlarmCode.findByPatchAeCode(aeCodes.getAeValue()) != null } .flatMapMaybe{aeCodeResponse -> add(AlarmCode.findByPatchAeCode(aeCodeResponse.getAeValue())!!,0L, true)} .subscribe() ) @@ -120,22 +121,21 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { return Maybe.fromCallable { cancelOsAlarmInternal(alarmCode) val pendingIntent = createPendingIntent(alarmCode, 0) - val now = System.currentTimeMillis() mOsAlarmManager.setAlarmClock(AlarmClockInfo(triggerTime, pendingIntent), pendingIntent) alarmCode } } override fun remove(alarmCode: AlarmCode): Maybe { - if(pm.getAlarms().registered.containsKey(alarmCode)) { - return cancelOsAlarms(alarmCode) + return if(pm.getAlarms().registered.containsKey(alarmCode)) { + cancelOsAlarms(alarmCode) .doOnSuccess { pm.getAlarms().unregister(alarmCode) pm.flushAlarms() } - .map { integer: Int? -> alarmCode } + .map { alarmCode } }else{ - return Maybe.just(alarmCode) + Maybe.just(alarmCode) } } @@ -158,8 +158,8 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { } } - private fun createPendingIntent(alarmCode: AlarmCode, flag: Int): PendingIntent { + private fun createPendingIntent(alarmCode: AlarmCode, flag: Int): PendingIntent? { val intent = Intent(mContext, OsAlarmReceiver::class.java).setData(getUri(alarmCode)) - return PendingIntent.getBroadcast(mContext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT) + return PendingIntent.getBroadcast(mContext, 1, intent, flag) } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/bindingadapters/OnSafeClickListener.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/bindingadapters/OnSafeClickListener.kt index 236f5a5d65..c157f6fc2f 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/bindingadapters/OnSafeClickListener.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/bindingadapters/OnSafeClickListener.kt @@ -21,6 +21,6 @@ class OnSafeClickListener( } companion object { // 중복 클릭 방지 시간 설정 - private val MIN_CLICK_INTERVAL: Long = 1000 + private const val MIN_CLICK_INTERVAL: Long = 1000 } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/IPatchManager.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/IPatchManager.java index 7a6ead66b7..26f1f800b1 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/IPatchManager.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/IPatchManager.java @@ -27,13 +27,6 @@ import io.reactivex.Observable; import io.reactivex.Single; public interface IPatchManager { - - /* - @Deprecated - static IPatchManager shared() { - return BaseApplication.instance.getDataComponent().getPatchManager(); - } - */ void init(); IPreferenceManager getPreferenceManager(); @@ -74,8 +67,7 @@ public interface IPatchManager { Single stopComboBolus(); - Single startQuickBolus(float nowDoseU, float exDoseU, - BolusExDuration exDuration); + Single startQuickBolus(float nowDoseU, float exDoseU, BolusExDuration exDuration); Single startCalculatorBolus(DetailedBolusInfo detailedBolusInfo); @@ -116,8 +108,6 @@ public interface IPatchManager { Single getTemperature(); - void initBasalSchedule(); - void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo); void changeBuzzerSetting(); diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManager.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManager.java index e782da471f..4922551756 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManager.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManager.java @@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble; import android.content.Context; import android.content.Intent; -import com.polidea.rxandroidble2.exceptions.BleException; - import java.util.concurrent.TimeUnit; import javax.inject.Inject; @@ -51,16 +49,12 @@ import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; -import io.reactivex.exceptions.OnErrorNotImplementedException; -import io.reactivex.exceptions.UndeliverableException; -import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; @Singleton @@ -81,29 +75,11 @@ public class PatchManager implements IPatchManager { @Inject RxAction rxAction; private IPatchScanner patchScanner; - private CompositeDisposable mCompositeDisposable = new CompositeDisposable(); + private final CompositeDisposable mCompositeDisposable = new CompositeDisposable(); private Disposable mConnectingDisposable = null; @Inject - public PatchManager() { - setupRxAndroidBle(); - } - - private void setupRxAndroidBle() { - RxJavaPlugins.setErrorHandler(throwable -> { - if (throwable instanceof UndeliverableException) { - if (throwable.getCause() instanceof BleException) { - return; - } - aapsLogger.error(LTag.PUMPBTCOMM, "rx UndeliverableException Error Handler"); - return; - } else if (throwable instanceof OnErrorNotImplementedException) { - aapsLogger.error(LTag.PUMPBTCOMM, "rx exception Error Handler"); - return; - } - throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable); - }); - } + public PatchManager() {} @Inject void onInit() { @@ -155,7 +131,6 @@ public class PatchManager implements IPatchManager { @Override public void init() { - initBasalSchedule(); setConnection(); } @@ -272,7 +247,27 @@ public class PatchManager implements IPatchManager { } public Single patchActivation(long timeout) { - return patchManager.patchActivation(timeout); + return patchManager.patchActivation(timeout) + .doOnSuccess(success -> { + if (success) { + pumpSync.insertTherapyEventIfNewWithTimestamp( + getPatchConfig().getPatchWakeupTimestamp(), + DetailedBolusInfo.EventType.CANNULA_CHANGE, + null, + null, + PumpType.EOFLOW_EOPATCH2, + getPatchConfig().getPatchSerialNumber() + ); + pumpSync.insertTherapyEventIfNewWithTimestamp( + getPatchConfig().getPatchWakeupTimestamp(), + DetailedBolusInfo.EventType.INSULIN_CHANGE, + null, + null, + PumpType.EOFLOW_EOPATCH2, + getPatchConfig().getPatchSerialNumber() + ); + } + }); } public Single startBasal(NormalBasal basal) { @@ -305,8 +300,8 @@ public class PatchManager implements IPatchManager { } - public Single startQuickBolus(float nowDoseU, - float exDoseU, BolusExDuration exDuration) { + public Single startQuickBolus(float nowDoseU, float exDoseU, + BolusExDuration exDuration) { return patchManager.startQuickBolus(nowDoseU, exDoseU, exDuration); } @@ -334,10 +329,6 @@ public class PatchManager implements IPatchManager { return patchManager.deactivate(timeout, force); } - public Single stopBuzz() { - return patchManager.stopBuzz(); - } - public Single infoReminderSet(boolean infoReminder) { return patchManager.infoReminderSet(infoReminder); } @@ -361,14 +352,6 @@ public class PatchManager implements IPatchManager { return patchScanner.scan(timeout); } - @Override - public void initBasalSchedule() { - if(pm.getNormalBasalManager().getNormalBasal() == null){ - pm.getNormalBasalManager().setNormalBasal(profileFunction.getProfile()); - pm.flushNormalBasalManager(); - } - } - @Override public void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo) { DetailedBolusInfo detailedBolusInfo = originalDetailedBolusInfo.copy(); @@ -399,12 +382,12 @@ public class PatchManager implements IPatchManager { boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false); if(pm.getPatchConfig().getInfoReminder() != buzzer) { if (isActivated()) { - infoReminderSet(buzzer) + mCompositeDisposable.add(infoReminderSet(buzzer) .observeOn(AndroidSchedulers.mainThread()) .subscribe(patchBooleanResponse -> { pm.getPatchConfig().setInfoReminder(buzzer); pm.flushPatchConfig(); - }); + })); } else { pm.getPatchConfig().setInfoReminder(buzzer); pm.flushPatchConfig(); @@ -414,18 +397,18 @@ public class PatchManager implements IPatchManager { @Override public void changeReminderSetting() { - int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVIOR_REMINDERS(), 0); + int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVOIR_REMINDERS(), 0); int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0); PatchConfig pc = pm.getPatchConfig(); if(pc.getLowReservoirAlertAmount() != doseUnit || pc.getPatchExpireAlertTime() != hours) { if (isActivated()) { - setLowReservoir(doseUnit, hours) + mCompositeDisposable.add(setLowReservoir(doseUnit, hours) .observeOn(AndroidSchedulers.mainThread()) .subscribe(patchBooleanResponse -> { pc.setLowReservoirAlertAmount(doseUnit); pc.setPatchExpireAlertTime(hours); pm.flushPatchConfig(); - }); + })); } else { pc.setLowReservoirAlertAmount(doseUnit); pc.setPatchExpireAlertTime(hours); @@ -437,11 +420,9 @@ public class PatchManager implements IPatchManager { @Override public void checkActivationProcess(){ if(getPatchConfig().getLifecycleEvent().isSubStepRunning() - && !pm.getAlarms().isOccuring(AlarmCode.A005) - && !pm.getAlarms().isOccuring(AlarmCode.A020)) { - rxAction.runOnMainThread(() -> { - rxBus.send(new EventPatchActivationNotComplete()); - }); + && !pm.getAlarms().isOccurring(AlarmCode.A005) + && !pm.getAlarms().isOccurring(AlarmCode.A020)) { + rxAction.runOnMainThread(() -> rxBus.send(new EventPatchActivationNotComplete())); } } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManagerImpl.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManagerImpl.java index f77da843b8..c308950433 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManagerImpl.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchManagerImpl.java @@ -42,7 +42,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.BleConnectionSt import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.IBleDevice; import info.nightscout.androidaps.plugins.pump.eopatch.core.Patch; import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.PatchSelfTestResult; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalStop; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BuzzerStop; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetTemperature; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.PublicKeySend; @@ -59,7 +58,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus; import java.math.BigInteger; import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; @@ -74,17 +72,13 @@ import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidParameterSpecException; -import java.sql.SQLException; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import java.util.concurrent.TimeUnit; import javax.crypto.KeyAgreement; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.plugins.pump.eopatch.core.util.HexString; import info.nightscout.androidaps.plugins.pump.eopatch.code.SettingKeys; import info.nightscout.androidaps.plugins.pump.eopatch.event.EventEoPatchAlarm; import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver; @@ -102,7 +96,7 @@ import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; @Singleton -public class PatchManagerImpl/* implements IPatchConstant*/ { +public class PatchManagerImpl{ @Inject IPreferenceManager pm; @Inject Context context; @Inject SP sp; @@ -115,29 +109,23 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { @Inject NeedleSensingTask START_NEEDLE_CHECK; IBleDevice patch; - HexString hexString; - private CompositeDisposable compositeDisposable; - - private Observable dateTimeChanged; + private final CompositeDisposable compositeDisposable; private static final long DEFAULT_API_TIME_OUT = 10; // SECONDS - private BuzzerStop BUZZER_STOP; - private GetTemperature TEMPERATURE_GET; - private BasalStop BASAL_STOP; - private StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP; - private PublicKeySend PUBLIC_KEY_SET; - private SequenceGet SEQUENCE_GET; + private final BuzzerStop BUZZER_STOP; + private final GetTemperature TEMPERATURE_GET; + private final StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP; + private final PublicKeySend PUBLIC_KEY_SET; + private final SequenceGet SEQUENCE_GET; @Inject public PatchManagerImpl() { compositeDisposable = new CompositeDisposable(); - hexString = new HexString(); BUZZER_STOP = new BuzzerStop(); TEMPERATURE_GET = new GetTemperature(); - BASAL_STOP = new BasalStop(); ALARM_ALERT_ERROR_BEEP_STOP = new StopAeBeep(); PUBLIC_KEY_SET = new PublicKeySend(); SEQUENCE_GET = new SequenceGet(); @@ -153,7 +141,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { filter.addAction(ACTION_DATE_CHANGED); filter.addAction(ACTION_TIMEZONE_CHANGED); - dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter); + Observable dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter); compositeDisposable.add( Observable.combineLatest(patch.observeConnected(), pm.observePatchLifeCycle(), @@ -178,7 +166,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { compositeDisposable.add( patch.observeConnected() - .doOnNext(it -> onPatchConnected(it)) + .doOnNext(this::onPatchConnected) .subscribe()); compositeDisposable.add( @@ -190,22 +178,22 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { compositeDisposable.add( EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class) - .filter(it -> it.isFirst()) + .filter(EventEoPatchAlarm::isFirst) .filter(it -> !pm.getPatchConfig().isDeactivated()) .filter(it -> patch.getConnectionState().isConnected()) - .concatMapIterable(it -> it.getAlarmCodes()) - .filter(it -> it.isPatchOccurrenceAlert()) + .concatMapIterable(EventEoPatchAlarm::getAlarmCodes) + .filter(AlarmCode::isPatchOccurrenceAlert) .flatMap(it -> stopAeBeep(it.getAeCode()).toObservable()) .subscribe() ); compositeDisposable.add( EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class) - .filter(it -> it.isFirst()) + .filter(EventEoPatchAlarm::isFirst) .filter(it -> !pm.getPatchConfig().isDeactivated()) .filter(it -> patch.getConnectionState().isConnected()) - .concatMapIterable(it -> it.getAlarmCodes()) - .filter(it -> it.isPatchOccurrenceAlarm()) + .concatMapIterable(EventEoPatchAlarm::getAlarmCodes) + .filter(AlarmCode::isPatchOccurrenceAlarm) .flatMap(it -> pauseBasalImpl(0.0f, System.currentTimeMillis(), it).toObservable()) .subscribe() ); @@ -218,7 +206,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { private void onPatchConnected(boolean connected) { boolean activated = pm.getPatchConfig().isActivated(); boolean useEncryption = pm.getPatchConfig().getSharedKey() != null; - int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVIOR_REMINDERS(), 0); + int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVOIR_REMINDERS(), 0); int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0); boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false); PatchConfig pc = pm.getPatchConfig(); @@ -256,7 +244,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { .subscribe()); } - if(connected == false && activated == true){ + if(!connected && activated){ pm.getPatchConfig().updatetDisconnectedTime(); } } @@ -266,13 +254,15 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { patch.observeAlarmNotification() .subscribe( this::onAlarmNotification, - throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage()) + throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage() != null ? + throwable.getMessage() : "AlarmNotification observation error") ), patch.observeInfoNotification() .filter(state -> pm.getPatchConfig().isActivated()) .subscribe( this::onInfoNotification, - throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage()) + throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage() != null ? + throwable.getMessage() : "InfoNotification observation error") ) ); } @@ -294,8 +284,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { consumer.accept(pm.getPatchConfig()); if (needSave) { pm.flushPatchConfig(); - } else { - pm.flushPatchConfig(); } } } @@ -304,11 +292,8 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal(); - if (normalBasal != null) { - // 아래 코드를 실행하면 isDoseUChanged 가 false 가 된다. - if(normalBasal.updateNormalBasalIndex()) { - pm.flushNormalBasalManager(); - } + if(normalBasal.updateNormalBasalIndex()) { + pm.flushNormalBasalManager(); } } @@ -363,7 +348,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { * Activation Process task #4 NEEDLE SENSING * Fragment: fragment_patch_rotate_knob */ - public Single checkNeedleSensing(long timeout) { //TODO: Timeout 추가? + public Single checkNeedleSensing(long timeout) { return START_NEEDLE_CHECK.start() .timeout(timeout, TimeUnit.MILLISECONDS); } @@ -398,7 +383,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { public Single startBasal(NormalBasal basal) { - return startNormalBasalTask.start(basal, false) + return startNormalBasalTask.start(basal) .timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS); } @@ -427,22 +412,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { return pauseBasalTask.pause(pauseDurationHour, alarmOccurredTime, alarmCode); } - private Single stopBasal() { - return BASAL_STOP.stop(); - } - - private void insertBasalStart() throws SQLException { - insertBasalStart(System.currentTimeMillis()); - } - - private void insertBasalStart(long timestamp) throws SQLException { - NormalBasal startedBasal = pm.getNormalBasalManager().getNormalBasal(); - if (startedBasal != null) { - startedBasal.updateNormalBasalIndex(); - pm.flushNormalBasalManager(); - } - } - //============================================================================================== // IPatchManager interface [TEMP BASAL] //============================================================================================== @@ -504,34 +473,34 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { return stopComboBolusTask.stop().timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS); } - private Single stopNowAndExtBolus() { - - boolean nowActive = pm.getPatchState().isNowBolusActive(); - boolean extActive = pm.getPatchState().isExtBolusActive(); - - if (nowActive && extActive) { - return stopComboBolus(); - } else if (nowActive) { - return stopNowBolus(); - } else if (extActive) { - return stopExtBolus(); - } - - return Single.just(new PatchBooleanResponse(true)); - } +// private Single stopNowAndExtBolus() { +// +// boolean nowActive = pm.getPatchState().isNowBolusActive(); +// boolean extActive = pm.getPatchState().isExtBolusActive(); +// +// if (nowActive && extActive) { +// return stopComboBolus(); +// } else if (nowActive) { +// return stopNowBolus(); +// } else if (extActive) { +// return stopExtBolus(); +// } +// +// return Single.just(new PatchBooleanResponse(true)); +// } //============================================================================================== // IPatchManager implementation [BOLUS] //============================================================================================== - public void readBolusStatusFromNotification(InfoNotification noti) { - if (noti.isBolusRegAct()) { + public void readBolusStatusFromNotification(InfoNotification infoNotification) { + if (infoNotification.isBolusRegAct()) { BolusCurrent bolusCurrent = pm.getBolusCurrent(); Arrays.asList(BolusType.NOW, BolusType.EXT).forEach(type -> { - if (noti.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요. - int injectedPumpCount = noti.getInjected(type); - int remainPumpCount = noti.getRemain(type); + if (infoNotification.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요. + int injectedPumpCount = infoNotification.getInjected(type); + int remainPumpCount = infoNotification.getRemain(type); bolusCurrent.updateBolusFromPatch(type, injectedPumpCount, remainPumpCount); } }); @@ -547,29 +516,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { return deactivateTask.run(force, timeout); } - public Single stopAll(){ - List> sources = new ArrayList<>(); - - // 노멀볼루스 또는 확장볼루스가 동작중이면 정지 - - if (pm.getPatchState().isNowBolusActive() || pm.getPatchState().isExtBolusActive()) { - sources.add(stopNowAndExtBolus()); - } - - // 템프베이젤이 동작중이면 중지 - if (pm.getPatchState().isTempBasalActive()) { - sources.add(stopTempBasal()); - } - - sources.add(stopBasal()); - - return Single.concat(sources).lastOrError(); - } - - public Single stopBuzz() { - return BUZZER_STOP.stop(); - } - @Inject InfoReminderTask infoReminderTask; @@ -677,8 +623,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { ECGenParameterSpec ecSpec_named = new ECGenParameterSpec(SECP256R1); KeyPairGenerator kpg = KeyPairGenerator.getInstance(EC); kpg.initialize(ecSpec_named); - KeyPair pair = kpg.generateKeyPair(); - return pair; + return kpg.generateKeyPair(); }); } @@ -729,8 +674,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { } public static ECPublicKey rawToEncodedECPublicKey(String curveName, byte[] rawBytes) throws - NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException, - InvalidAlgorithmParameterException { + NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException { KeyFactory kf = KeyFactory.getInstance(EC); int mid = rawBytes.length / 2; byte[] x = Arrays.copyOfRange(rawBytes, 0, mid); @@ -740,7 +684,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { } public static ECParameterSpec ecParameterSpecForCurve(String curveName) throws - NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException { + NoSuchAlgorithmException, InvalidParameterSpecException { AlgorithmParameters params = AlgorithmParameters.getInstance(EC); params.init(new ECGenParameterSpec(curveName)); return params.getParameterSpec(ECParameterSpec.class); @@ -755,7 +699,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { return keyAgreement.generateSecret(); } catch (InvalidKeyException | NoSuchAlgorithmException e) { - // TODO Auto-generated catch block e.printStackTrace(); return null; } @@ -768,8 +711,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { private static final Scheduler SS = Schedulers.single(); public BleConnectionState getPatchConnectionState() { - BleConnectionState result = patch.getConnectionState(); - return result; + return patch.getConnectionState(); } public Observable observePatchConnectionState() { @@ -780,14 +722,3 @@ public class PatchManagerImpl/* implements IPatchConstant*/ { patch.updateMacAddress(mac, b); } } - -class AlarmFiredEventInfo -{ - public AlarmCode code; - public long createTimestamp; - - public AlarmFiredEventInfo(AlarmCode code, long createTimestamp) { - this.code = code; - this.createTimestamp = createTimestamp; - } -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchStateManager.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchStateManager.java index 0efaa50521..974c7ac061 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchStateManager.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PatchStateManager.java @@ -52,7 +52,7 @@ public class PatchStateManager { final PatchState oldState = pm.getPatchState(); int diff = newState.currentTime() - oldState.currentTime(); - if (0 <= diff && diff < 10) { // TODO 상수로 변경. + if (0 <= diff && diff < 10) { /* 10초 안에 같은 PatchState update 시 skip */ if (oldState.equalState(newState)) { return; @@ -267,8 +267,7 @@ public class PatchStateManager { public synchronized void onBasalStarted(NormalBasal basal, long timestamp) { if (basal != null) { pm.getNormalBasalManager().updateBasalStarted(); - - basal.updateNormalBasalIndex(); //normal basal index를 업데이트하여 basal change 이력이 또 발생하는것을 방지(df_356) + basal.updateNormalBasalIndex(); } pm.getPatchConfig().updateNormalBasalStarted(); // updateNormalBasalStarted 도 동일함... diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PreferenceManager.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PreferenceManager.kt index 97164f6c81..244814a109 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PreferenceManager.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/PreferenceManager.kt @@ -148,12 +148,12 @@ class PreferenceManager @Inject constructor(): IPreferenceManager { aapsLogger.error(LTag.PUMP, ex.message?:"Alarms load error") } - aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: ${mPatchConfig}") - aapsLogger.info(LTag.PUMP,"Load from PatchState preference: ${mPatchState}") - aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: ${mBolusCurrent}") - aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: ${mNormalBasalMgr}") - aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: ${mTempBasalMgr}") - aapsLogger.info(LTag.PUMP,"Load from Alarms preference: ${mAlarms}") + aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: $mPatchConfig") + aapsLogger.info(LTag.PUMP,"Load from PatchState preference: $mPatchState") + aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: $mBolusCurrent") + aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: $mNormalBasalMgr") + aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: $mTempBasalMgr") + aapsLogger.info(LTag.PUMP,"Load from Alarms preference: $mAlarms") initialized = true } @@ -179,9 +179,8 @@ class PreferenceManager @Inject constructor(): IPreferenceManager { flushBolusCurrent() mTempBasalMgr.clear() flushTempBasalManager() - // mAlarms.clear() - // flushAlarms() } + else -> Unit } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ActivateTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ActivateTask.java index 8e2c3710f1..888444e186 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ActivateTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ActivateTask.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; import info.nightscout.shared.logging.LTag; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalScheduleSetBig; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.SetKey; import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse; @@ -17,15 +16,11 @@ import io.reactivex.schedulers.Schedulers; public class ActivateTask extends TaskBase { @Inject StartNormalBasalTask startBasalTask; - private SetKey SET_KEY; - private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG; - + private final SetKey SET_KEY = new SetKey(); @Inject public ActivateTask() { super(TaskFunc.ACTIVATE); - SET_KEY = new SetKey(); - BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig(); } public Single start() { @@ -35,9 +30,9 @@ public class ActivateTask extends TaskBase { .doOnNext(this::checkResponse) .firstOrError() .observeOn(Schedulers.io()).doOnSuccess(this::onActivated) - .flatMap(v -> startBasalTask.start(enabled, false)) + .flatMap(v -> startBasalTask.start(enabled)) .map(BaseResponse::isSuccess) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ActivateTask error")); } private void onActivated(BaseResponse response) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/BolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/BolusTask.java index 016ea308a6..2896e250aa 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/BolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/BolusTask.java @@ -4,6 +4,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.BolusExDuration; import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant; import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType; +import info.nightscout.androidaps.plugins.pump.eopatch.core.util.FloatAdjusters; import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent; abstract class BolusTask extends TaskBase { @@ -16,17 +17,17 @@ abstract class BolusTask extends TaskBase { boolean now = (nowDoseU > 0); boolean ext = (exDoseU > 0); - long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720 + long startTimestamp = now ? System.currentTimeMillis() : 0; long endTimestamp = startTimestamp + getPumpDuration(nowDoseU); long nowHistoryID = 1L; //record no - long exStartTimestamp = 0; + long exStartTimestamp; if (now) { pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp); } if (ext) { - long estimatedExStartTimestamp = 0; + long estimatedExStartTimestamp; if (now) { exStartTimestamp = 0; @@ -46,12 +47,8 @@ abstract class BolusTask extends TaskBase { } - public void onCalcBolusStarted(float nowDoseU, float correctionBolus, float exDoseU, - BolusExDuration exDuration) { - + public void onCalcBolusStarted(float nowDoseU) { boolean now = (nowDoseU > 0); - boolean ext = (exDoseU > 0); - long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720 long endTimestamp = startTimestamp + getPumpDuration(nowDoseU); @@ -62,24 +59,6 @@ abstract class BolusTask extends TaskBase { pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp); } - long exStartTimestamp = 0; - - if (ext) { - long estimatedExStartTimestamp = 0; - - if (now) { - exStartTimestamp = 0; - } - else { - estimatedExStartTimestamp = System.currentTimeMillis(); - exStartTimestamp = estimatedExStartTimestamp; - } - long exEndTimestamp = exStartTimestamp + exDuration.milli(); - long extHistoryID = 2L; //record no - pm.getBolusCurrent().startExtBolus(extHistoryID, exDoseU, exStartTimestamp, - exEndTimestamp, exDuration.milli()); - } - pm.flushBolusCurrent(); } @@ -88,12 +67,13 @@ abstract class BolusTask extends TaskBase { } public void updateNowBolusStopped(int injected, long suspendedTimestamp) { - BolusCurrent bolusCurrent = pm.getBolusCurrent(); long nowID = bolusCurrent.historyId(BolusType.NOW); if (nowID > 0 && !bolusCurrent.endTimeSynced(BolusType.NOW)) { -// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); -// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P); + long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); + float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P); + bolusCurrent.getNowBolus().setInjected(injectedDoseU); + bolusCurrent.getNowBolus().setEndTimestamp(stopTime); bolusCurrent.setEndTimeSynced(BolusType.NOW, true); pm.flushBolusCurrent(); } @@ -107,8 +87,10 @@ abstract class BolusTask extends TaskBase { BolusCurrent bolusCurrent = pm.getBolusCurrent(); long extID = bolusCurrent.historyId(BolusType.EXT); if (extID > 0 && !bolusCurrent.endTimeSynced(BolusType.EXT)) { -// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); -// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P); + long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); + float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P); + bolusCurrent.getExtBolus().setInjected(injectedDoseU); + bolusCurrent.getExtBolus().setEndTimestamp(stopTime); bolusCurrent.setEndTimeSynced(BolusType.EXT, true); pm.flushBolusCurrent(); } @@ -116,8 +98,8 @@ abstract class BolusTask extends TaskBase { private long getPumpDuration(float doseU) { if (doseU > 0) { - long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli(); //todo - return (long) ((doseU / AppConstant.Companion.getBOLUS_UNIT_STEP()) * pumpDuration); + long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli(); + return (long) ((doseU / AppConstant.BOLUS_UNIT_STEP) * pumpDuration); } return 0L; } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/DeactivateTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/DeactivateTask.java index 1299a99a6b..3a403a4fe2 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/DeactivateTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/DeactivateTask.java @@ -5,7 +5,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager; import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType; import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus; -import java.sql.SQLException; import java.util.concurrent.TimeUnit; import javax.inject.Inject; @@ -14,7 +13,6 @@ import javax.inject.Singleton; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.DeActivation; import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent; import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchLifecycleEvent; -import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState; import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal; import io.reactivex.Observable; import io.reactivex.Single; @@ -22,14 +20,10 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class DeactivateTask extends TaskBase { + @Inject StopBasalTask stopBasalTask; + @Inject IPreferenceManager pm; - @Inject - StopBasalTask stopBasalTask; - - @Inject - IPreferenceManager pm; - - private DeActivation DEACTIVATION; + private final DeActivation DEACTIVATION; @Inject public DeactivateTask() { @@ -44,16 +38,16 @@ public class DeactivateTask extends TaskBase { DEACTIVATION.start() .doOnSuccess(this::checkResponse) .observeOn(Schedulers.io()) - .doOnSuccess(response -> onDeactivated(false))) + .doOnSuccess(response -> onDeactivated())) .map(response -> DeactivationStatus.of(response.isSuccess(), forced)) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())) + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "DeactivateTask error")) .onErrorResumeNext(e -> { if (forced) { try { - onDeactivated(true); + onDeactivated(); } catch (Exception t) { - aapsLogger.error(LTag.PUMPCOMM, e.getMessage()); + aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "DeactivateTask error"); } } @@ -73,31 +67,27 @@ public class DeactivateTask extends TaskBase { return isReady(); } - /* Schedulers.io() */ - private void onDeactivated(boolean forced) throws SQLException { + private void onDeactivated() { synchronized (lock) { patch.updateMacAddress(null, false); if (pm.getPatchConfig().getLifecycleEvent().isShutdown()) { return; } - cleanUpRepository(); - pm.getNormalBasalManager().updateForDeactivation(); - pm.updatePatchLifeCycle(PatchLifecycleEvent.createShutdown()); } } - private void cleanUpRepository() throws SQLException { + private void cleanUpRepository() { updateNowBolusStopped(); updateExtBolusStopped(); updateTempBasalStopped(); } - private void updateTempBasalStopped() throws SQLException { + private void updateTempBasalStopped() { TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal(); if (tempBasal != null) { @@ -106,7 +96,6 @@ public class DeactivateTask extends TaskBase { } } - /* copied from BolusTask. */ private void updateNowBolusStopped() { BolusCurrent bolusCurrent = pm.getBolusCurrent(); long nowID = bolusCurrent.historyId(BolusType.NOW); @@ -117,7 +106,6 @@ public class DeactivateTask extends TaskBase { } } - /* copied from BolusTask. */ private void updateExtBolusStopped() { BolusCurrent bolusCurrent = pm.getBolusCurrent(); long extID = bolusCurrent.historyId(BolusType.EXT); diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/FetchAlarmTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/FetchAlarmTask.java index 13a9326480..84276d013e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/FetchAlarmTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/FetchAlarmTask.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; import info.nightscout.shared.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode; import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetErrorCodes; @@ -13,18 +12,13 @@ import javax.inject.Singleton; import info.nightscout.androidaps.plugins.pump.eopatch.core.response.AeCodeResponse; import io.reactivex.Single; -import io.reactivex.android.schedulers.AndroidSchedulers; @Singleton public class FetchAlarmTask extends TaskBase { + @Inject RxBus rxBus; + @Inject IAlarmRegistry alarmRegistry; - @Inject - RxBus rxBus; - - @Inject - IAlarmRegistry alarmRegistry; - - private GetErrorCodes ALARM_ALERT_ERROR_CODE_GET; + private final GetErrorCodes ALARM_ALERT_ERROR_CODE_GET; @Inject public FetchAlarmTask() { @@ -38,7 +32,7 @@ public class FetchAlarmTask extends TaskBase { .doOnNext(this::checkResponse) .firstOrError() .doOnSuccess(aeCodeResponse -> alarmRegistry.add(aeCodeResponse.getAlarmCodes())) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "FetchAlarmTask error")); } public synchronized void enqueue() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/GetPatchInfoTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/GetPatchInfoTask.java index e84f9d649f..d297086148 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/GetPatchInfoTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/GetPatchInfoTask.java @@ -26,17 +26,15 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class GetPatchInfoTask extends TaskBase { + @Inject UpdateConnectionTask updateConnectionTask; - @Inject - UpdateConnectionTask updateConnectionTask; - - private SetGlobalTime SET_GLOBAL_TIME; - private GetSerialNumber SERIAL_NUMBER_GET; - private GetLOT LOT_NUMBER_GET; - private GetFirmwareVersion FIRMWARE_VERSION_GET; - private GetWakeUpTime WAKE_UP_TIME_GET; - private GetPumpDuration PUMP_DURATION_GET; - private GetModelName GET_MODEL_NAME; + private final SetGlobalTime SET_GLOBAL_TIME; + private final GetSerialNumber SERIAL_NUMBER_GET; + private final GetLOT LOT_NUMBER_GET; + private final GetFirmwareVersion FIRMWARE_VERSION_GET; + private final GetWakeUpTime WAKE_UP_TIME_GET; + private final GetPumpDuration PUMP_DURATION_GET; + private final GetModelName GET_MODEL_NAME; @Inject public GetPatchInfoTask() { @@ -61,17 +59,16 @@ public class GetPatchInfoTask extends TaskBase { PUMP_DURATION_GET.get().doOnSuccess(this::onPumpDurationResponse), GET_MODEL_NAME.get().doOnSuccess(this::onModelNameResponse))) .map(BaseResponse::isSuccess) - .filter(v -> !v) // fail 시 false 가 아래로 내려간다. + .filter(v -> !v) .first(true); return isReady() .concatMapSingle(it -> tasks) .firstOrError() -// .flatMap(v -> updateConnectionTask.update()).map(v -> true) .observeOn(Schedulers.io()) .doOnSuccess(this::onPatchWakeupSuccess) .doOnError(this::onPatchWakeupFailed) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "GetPatchInfoTask error")); } private void onSerialNumberResponse(SerialNumberResponse v) { @@ -91,23 +88,21 @@ public class GetPatchInfoTask extends TaskBase { } private void onPumpDurationResponse(PumpDurationResponse v) { - pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100); // 0.1 초 단위 - pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100); - pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100); + pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100L); + pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100L); + pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100L); } private void onModelNameResponse(ModelNameResponse modelNameResponse) { pm.getPatchConfig().setPatchModelName(modelNameResponse.getModelName()); } - /* Schedulers.io() */ private void onPatchWakeupSuccess(Boolean result) { synchronized (lock) { pm.flushPatchConfig(); } } - /* Schedulers.io() */ private void onPatchWakeupFailed(Throwable e) { patch.setSeq(-1); pm.getPatchConfig().updateDeactivated(); diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InfoReminderTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InfoReminderTask.java index f2a32536e8..367016ffb1 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InfoReminderTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InfoReminderTask.java @@ -14,11 +14,9 @@ import io.reactivex.Single; @Singleton public class InfoReminderTask extends TaskBase { + @Inject IPreferenceManager pm; - @Inject - IPreferenceManager pm; - - private InfoReminderSet INFO_REMINDER_SET; + private final InfoReminderSet INFO_REMINDER_SET; @Inject public InfoReminderTask() { @@ -32,7 +30,7 @@ public class InfoReminderTask extends TaskBase { .concatMapSingle(v -> INFO_REMINDER_SET.set(infoReminder)) .doOnNext(this::checkResponse) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "InfoReminderTask error")); } public synchronized void enqueue() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InternalSuspendedTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InternalSuspendedTask.java index 9e73ead46e..facd2c38c8 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InternalSuspendedTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/InternalSuspendedTask.java @@ -6,8 +6,6 @@ import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.UserEntryLogger; import info.nightscout.androidaps.utils.userEntry.UserEntryMapper; import info.nightscout.shared.logging.LTag; -import info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatchConstant; - import java.util.concurrent.TimeUnit; import javax.inject.Inject; @@ -15,11 +13,8 @@ import javax.inject.Singleton; import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStop; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetInternalSuspendTime; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStop; import info.nightscout.androidaps.plugins.pump.eopatch.core.response.PatchInternalSuspendTimeResponse; -import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; @@ -29,47 +24,44 @@ import io.reactivex.subjects.BehaviorSubject; @Singleton public class InternalSuspendedTask extends BolusTask { - @Inject CommandQueue commandQueue; @Inject AAPSLogger aapsLogger; @Inject PumpSync pumpSync; @Inject UserEntryLogger uel; - private GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET; - private BolusStop BOLUS_STOP; - private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP; - private BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject exbolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject basalCheckSubject = BehaviorSubject.create(); + private final GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET; + private final BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject extendedBolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject basalCheckSubject = BehaviorSubject.create(); @Inject public InternalSuspendedTask() { super(TaskFunc.INTERNAL_SUSPEND); INTERNAL_SUSPEND_TIME_GET = new GetInternalSuspendTime(); - BOLUS_STOP = new BolusStop(); - TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop(); } - private Observable getBolusSebject(){ + private Observable getBolusSubject(){ return bolusCheckSubject.hide(); } - private Observable getExbolusSebject(){ - return exbolusCheckSubject.hide(); + private Observable getExtendedBolusSubject(){ + return extendedBolusCheckSubject.hide(); } - private Observable getBasalSebject(){ + private Observable getBasalSubject(){ return basalCheckSubject.hide(); } public Single start(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) { - PatchState patchState = pm.getPatchState(); - if (isNowBolusActive || isExtBolusActive) { enqueue(TaskFunc.READ_BOLUS_FINISH_TIME); } + if (isTempBasalActive) { + enqueue(TaskFunc.READ_TEMP_BASAL_FINISH_TIME); + } + if (commandQueue.isRunning(Command.CommandType.BOLUS)) { uel.log(UserEntryMapper.Action.CANCEL_BOLUS, UserEntryMapper.Sources.EOPatch2); commandQueue.cancelAllBoluses(); @@ -82,11 +74,11 @@ public class InternalSuspendedTask extends BolusTask { commandQueue.cancelExtended(new Callback() { @Override public void run() { - exbolusCheckSubject.onNext(true); + extendedBolusCheckSubject.onNext(true); } }); }else{ - exbolusCheckSubject.onNext(true); + extendedBolusCheckSubject.onNext(true); } if (pumpSync.expectedPumpState().getTemporaryBasal() != null) { @@ -101,14 +93,13 @@ public class InternalSuspendedTask extends BolusTask { basalCheckSubject.onNext(true); } - return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { - return (bolusReady && exbolusReady && basalReady); - }) + return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(), + (bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady)) .filter(ready -> ready) .flatMap(v -> isReady()) .concatMapSingle(v -> getInternalSuspendTime()) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "InternalSuspendedTask error")); } private Single getInternalSuspendTime() { @@ -117,56 +108,6 @@ public class InternalSuspendedTask extends BolusTask { .map(PatchInternalSuspendTimeResponse::getTotalSeconds); } - private Single stopNowBolus(long suspendTime, boolean isNowBolusActive) { - if (isNowBolusActive) { - long suspendedTimestamp = pm.getPatchConfig().getPatchWakeupTimestamp() + suspendTime; - - return BOLUS_STOP.stop(IPatchConstant.NOW_BOLUS_ID) - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onNowBolusStopped(v.getInjectedBolusAmount(), suspendedTimestamp)) - .map(v -> suspendTime); - } - - return Single.just(suspendTime); - } - - private Single stopExtBolus(long suspendTime, boolean isExtBolusActive) { - if (isExtBolusActive) { - long suspendedTimestamp = pm.getPatchConfig().getPatchWakeupTimestamp() + suspendTime; - - return BOLUS_STOP.stop(IPatchConstant.EXT_BOLUS_ID) - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onExtBolusStopped(v.getInjectedBolusAmount(), suspendedTimestamp)) - .map(v -> suspendTime); - } - - return Single.just(suspendTime); - } - - private Single stopTempBasal(long suspendTime, boolean isTempBasalActive) { - if (isTempBasalActive) { - return TEMP_BASAL_SCHEDULE_STOP.stop() - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onTempBasalCanceled()) - .map(v -> suspendTime); - } - - return Single.just(suspendTime); - } - - private void onNowBolusStopped(int injectedBolusAmount, long suspendedTimestamp) { - updateNowBolusStopped(injectedBolusAmount, suspendedTimestamp); - } - - private void onExtBolusStopped(int injectedBolusAmount, long suspendedTimestamp) { - updateExtBolusStopped(injectedBolusAmount, suspendedTimestamp); - } - - private void onTempBasalCanceled() { - pm.getTempBasalManager().updateBasalStopped(); - pm.flushTempBasalManager(); - } - public synchronized void enqueue(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) { boolean ready = (disposable == null || disposable.isDisposed()); @@ -175,7 +116,7 @@ public class InternalSuspendedTask extends BolusTask { .timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS) .subscribe(v -> { bolusCheckSubject.onNext(false); - exbolusCheckSubject.onNext(false); + extendedBolusCheckSubject.onNext(false); basalCheckSubject.onNext(false); }); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/NeedleSensingTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/NeedleSensingTask.java index d924bc3659..c39f8d740b 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/NeedleSensingTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/NeedleSensingTask.java @@ -13,9 +13,7 @@ import io.reactivex.Single; @Singleton public class NeedleSensingTask extends TaskBase { - - @Inject - IAlarmRegistry alarmRegistry; + @Inject IAlarmRegistry alarmRegistry; StartNeedleCheck START_NEEDLE_CHECK; UpdateConnection UPDATE_CONNECTION; @@ -38,7 +36,7 @@ public class NeedleSensingTask extends TaskBase { .doOnNext(this::onResponse) .map(patchState -> !patchState.isNeedNeedleSensing()) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "NeedleSensingTask error")); } private void onResponse(PatchState v) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PauseBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PauseBasalTask.java index ebd32d3aec..9b0dca6015 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PauseBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PauseBasalTask.java @@ -18,13 +18,9 @@ import info.nightscout.shared.logging.LTag; import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode; import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry; import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager; -import info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatchConstant; import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalPause; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStop; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStop; import info.nightscout.androidaps.plugins.pump.eopatch.core.response.PatchBooleanResponse; -import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import io.reactivex.Observable; @@ -40,33 +36,28 @@ public class PauseBasalTask extends BolusTask { @Inject PumpSync pumpSync; @Inject UserEntryLogger uel; - private BasalPause BASAL_PAUSE; - private BolusStop BOLUS_STOP; - private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP; - - private BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject exbolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject basalCheckSubject = BehaviorSubject.create(); + private final BasalPause BASAL_PAUSE; + private final BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject extendedBolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject basalCheckSubject = BehaviorSubject.create(); @Inject public PauseBasalTask() { super(TaskFunc.PAUSE_BASAL); BASAL_PAUSE = new BasalPause(); - BOLUS_STOP = new BolusStop(); - TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop(); } - private Observable getBolusSebject(){ + private Observable getBolusSubject(){ return bolusCheckSubject.hide(); } - private Observable getExbolusSebject(){ - return exbolusCheckSubject.hide(); + private Observable getExtendedBolusSubject(){ + return extendedBolusCheckSubject.hide(); } - private Observable getBasalSebject(){ + private Observable getBasalSubject(){ return basalCheckSubject.hide(); } @@ -90,11 +81,11 @@ public class PauseBasalTask extends BolusTask { commandQueue.cancelExtended(new Callback() { @Override public void run() { - exbolusCheckSubject.onNext(true); + extendedBolusCheckSubject.onNext(true); } }); }else{ - exbolusCheckSubject.onNext(true); + extendedBolusCheckSubject.onNext(true); } if (pumpSync.expectedPumpState().getTemporaryBasal() != null) { @@ -109,71 +100,35 @@ public class PauseBasalTask extends BolusTask { basalCheckSubject.onNext(true); } - return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { - return (bolusReady && exbolusReady && basalReady); - }) + return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(), + (bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady)) .filter(ready -> ready) .flatMap(v -> isReady()) - .concatMapSingle(v -> getSuspendedTime(pausedTimestamp, alarmCode)) - .concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, suspendedTimestamp, alarmCode)) + .concatMapSingle(v -> getSuspendedTime(pausedTimestamp)) + .concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, alarmCode)) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "PauseBasalTask error")); } - private Single getSuspendedTime(long pausedTimestamp, @Nullable AlarmCode alarmCode) { + private Single getSuspendedTime(long pausedTimestamp) { return Single.just(pausedTimestamp); } - private Single stopNowBolus(long pausedTimestamp, boolean isNowBolusActive) { - if (isNowBolusActive) { - return BOLUS_STOP.stop(IPatchConstant.NOW_BOLUS_ID) - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onNowBolusStopped(v.getInjectedBolusAmount(), pausedTimestamp)) - .map(v -> pausedTimestamp); - } - - return Single.just(pausedTimestamp); - } - - private Single stopExtBolus(long pausedTimestamp, boolean isExtBolusActive) { - if (isExtBolusActive) { - return BOLUS_STOP.stop(IPatchConstant.EXT_BOLUS_ID) - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onExtBolusStopped(v.getInjectedBolusAmount(), pausedTimestamp)) - .map(v -> pausedTimestamp); - } - - return Single.just(pausedTimestamp); - } - - private Single stopTempBasal(long pausedTimestamp, boolean isTempBasalActive) { - if (isTempBasalActive) { - return TEMP_BASAL_SCHEDULE_STOP.stop() - .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onTempBasalCanceled(pausedTimestamp)) - .map(v -> pausedTimestamp); - } - - return Single.just(pausedTimestamp); - } - - private Single pauseBasal(float pauseDurationHour, long suspendedTimestamp, @Nullable AlarmCode alarmCode) { + private Single pauseBasal(float pauseDurationHour, @Nullable AlarmCode alarmCode) { if(alarmCode == null) { return BASAL_PAUSE.pause(pauseDurationHour) .doOnSuccess(this::checkResponse) - .doOnSuccess(v -> onBasalPaused(pauseDurationHour, suspendedTimestamp, null)); + .doOnSuccess(v -> onBasalPaused(pauseDurationHour, null)); } // 정지 알람 발생 시 basal pause 커맨드 전달하지 않음 - 주입 정지 이력만 생성 - onBasalPaused(pauseDurationHour, suspendedTimestamp, alarmCode); + onBasalPaused(pauseDurationHour, alarmCode); return Single.just(new PatchBooleanResponse(true)); } - private void onBasalPaused(float pauseDurationHour, long suspendedTimestamp, @Nullable AlarmCode alarmCode) { + private void onBasalPaused(float pauseDurationHour, @Nullable AlarmCode alarmCode) { if (!pm.getNormalBasalManager().isSuspended()) { - String strCode = (alarmCode != null) ? alarmCode.name() : null; - if (alarmCode != null) { pm.getPatchConfig().updateNormalBasalPausedSilently(); } @@ -192,23 +147,6 @@ public class PauseBasalTask extends BolusTask { enqueue(TaskFunc.UPDATE_CONNECTION); } - private void onNowBolusStopped(int injectedBolusAmount, long suspendedTimestamp) { - updateNowBolusStopped(injectedBolusAmount, suspendedTimestamp); - } - - private void onExtBolusStopped(int injectedBolusAmount, long suspendedTimestamp) { - updateExtBolusStopped(injectedBolusAmount, suspendedTimestamp); - } - - private void onTempBasalCanceled(long suspendedTimestamp) { - TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal(); - - if (tempBasal != null) { - pm.getTempBasalManager().updateBasalStopped(); - pm.flushTempBasalManager(); - } - } - public synchronized void enqueue(float pauseDurationHour, long pausedTime, @Nullable AlarmCode alarmCode) { boolean ready = (disposable == null || disposable.isDisposed()); @@ -217,7 +155,7 @@ public class PauseBasalTask extends BolusTask { .timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS) .subscribe(v -> { bolusCheckSubject.onNext(false); - exbolusCheckSubject.onNext(false); + extendedBolusCheckSubject.onNext(false); basalCheckSubject.onNext(false); }); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PrimingTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PrimingTask.java index 57d318ac67..ed65a8430e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PrimingTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/PrimingTask.java @@ -14,9 +14,8 @@ import io.reactivex.Observable; @Singleton public class PrimingTask extends TaskBase { - - private UpdateConnection UPDATE_CONNECTION; - private StartPriming START_PRIMING; + private final UpdateConnection UPDATE_CONNECTION; + private final StartPriming START_PRIMING; @Inject public PrimingTask() { @@ -31,25 +30,25 @@ public class PrimingTask extends TaskBase { .doOnNext(this::checkResponse) .flatMap(v -> observePrimingSuccess(count)) .takeUntil(value -> (value == count)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "PrimingTask error")); } private Observable observePrimingSuccess(long count) { return Observable.merge( Observable.interval(1, TimeUnit.SECONDS).take(count + 10) - .map(v -> v * 3) // 현재 20초 니깐 60 정도에서 꽉 채워짐. *4 도 괜찮을 듯. + .map(v -> v * 3) .doOnNext(v -> { if (v >= count) { throw new Exception("Priming failed"); } - }), // 프로그래스바 용. + }), Observable.interval(3, TimeUnit.SECONDS) .concatMapSingle(v -> UPDATE_CONNECTION.get()) .map(response -> PatchState.Companion.create(response.getPatchState(), System.currentTimeMillis())) - .filter(patchState -> patchState.isPrimingSuccess()) - .map(result -> count) // 프라이밍 체크 용 성공시 count 값 리턴 + .filter(PatchState::isPrimingSuccess) + .map(result -> count) ); } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadBolusFinishTimeTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadBolusFinishTimeTask.java index 6f9d1a212a..971d8cd0be 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadBolusFinishTimeTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadBolusFinishTimeTask.java @@ -15,8 +15,7 @@ import io.reactivex.Single; @Singleton public class ReadBolusFinishTimeTask extends BolusTask { - - private BolusFinishTimeGet BOLUS_FINISH_TIME_GET; + private final BolusFinishTimeGet BOLUS_FINISH_TIME_GET; @Inject public ReadBolusFinishTimeTask() { @@ -30,7 +29,7 @@ public class ReadBolusFinishTimeTask extends BolusTask { .firstOrError() .doOnSuccess(this::checkResponse) .doOnSuccess(this::onResponse) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ReadBolusFinishTimeTask error")); } void onResponse(BolusFinishTimeResponse response) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadTempBasalFinishTimeTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadTempBasalFinishTimeTask.java index 0d42506fa0..3b858a3e0b 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadTempBasalFinishTimeTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ReadTempBasalFinishTimeTask.java @@ -13,8 +13,7 @@ import io.reactivex.Single; @Singleton public class ReadTempBasalFinishTimeTask extends TaskBase { - - private TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET; + private final TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET; @Inject public ReadTempBasalFinishTimeTask() { @@ -28,7 +27,7 @@ public class ReadTempBasalFinishTimeTask extends TaskBase { .firstOrError() .doOnSuccess(this::checkResponse) .doOnSuccess(this::onResponse) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ReadTempBasalFinishTimeTask error")); } private void onResponse(TempBasalFinishTimeResponse response) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ResumeBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ResumeBasalTask.java index a25febb404..2927b4665a 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ResumeBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/ResumeBasalTask.java @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; -import info.nightscout.shared.logging.AAPSLogger; +import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode; +import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry; import info.nightscout.shared.logging.LTag; import info.nightscout.androidaps.plugins.pump.eopatch.ble.PatchStateManager; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalResume; @@ -17,13 +18,11 @@ import io.reactivex.Single; @Singleton public class ResumeBasalTask extends TaskBase { - @Inject - StartNormalBasalTask startNormalBasalTask; + @Inject IAlarmRegistry alarmRegistry; + @Inject StartNormalBasalTask startNormalBasalTask; + @Inject PatchStateManager patchStateManager; - @Inject - PatchStateManager patchStateManager; - - private BasalResume BASAL_RESUME; + private final BasalResume BASAL_RESUME; @Inject public ResumeBasalTask() { @@ -32,25 +31,21 @@ public class ResumeBasalTask extends TaskBase { } public synchronized Single resume() { - if (pm.getPatchConfig().getNeedSetBasalSchedule()) { - NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal(); - - if (normalBasal != null) { - return startNormalBasalTask.start(normalBasal, true); - } + return startNormalBasalTask.start(pm.getNormalBasalManager().getNormalBasal()); } return isReady().concatMapSingle(v -> BASAL_RESUME.resume()) .doOnNext(this::checkResponse) .firstOrError() .doOnSuccess(v -> onResumeResponse(v)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ResumeBasalTask error")); } - private void onResumeResponse(PatchBooleanResponse v) throws SQLException { + private void onResumeResponse(PatchBooleanResponse v) { if (v.isSuccess()) { patchStateManager.onBasalResumed(v.getTimestamp() + 1000); + alarmRegistry.remove(AlarmCode.B001).subscribe(); } enqueue(TaskFunc.UPDATE_CONNECTION); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SelfTestTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SelfTestTask.java index cafe9e1911..c39e89b256 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SelfTestTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SelfTestTask.java @@ -18,10 +18,9 @@ import io.reactivex.Single; @Singleton public class SelfTestTask extends TaskBase { - - private GetTemperature TEMPERATURE_GET; - private GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING; - private GetGlobalTime GET_GLOBAL_TIME; + private final GetTemperature TEMPERATURE_GET; + private final GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING; + private final GetGlobalTime GET_GLOBAL_TIME; @Inject public SelfTestTask() { @@ -35,33 +34,17 @@ public class SelfTestTask extends TaskBase { public Single start() { Single tasks = Single.concat(Arrays.asList( TEMPERATURE_GET.get() - .map(TemperatureResponse::getResult) - .doOnSuccess(this::onTemperatureResult), + .map(TemperatureResponse::getResult), BATTERY_LEVEL_GET_BEFORE_PRIMING.get() - .map(BatteryVoltageLevelPairingResponse::getResult) - .doOnSuccess(this::onBatteryResult), + .map(BatteryVoltageLevelPairingResponse::getResult), GET_GLOBAL_TIME.get(false) - .map(GlobalTimeResponse::getResult) - .doOnSuccess(this::onTimeResult))) + .map(GlobalTimeResponse::getResult))) .filter(result -> result != PatchSelfTestResult.TEST_SUCCESS) .first(PatchSelfTestResult.TEST_SUCCESS); return isReady() .concatMapSingle(v -> tasks) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); - } - - private void onTemperatureResult(PatchSelfTestResult patchSelfTestResult) { - if (patchSelfTestResult != PatchSelfTestResult.TEST_SUCCESS) { - } - } - - private void onBatteryResult(PatchSelfTestResult patchSelfTestResult) { - if (patchSelfTestResult != PatchSelfTestResult.TEST_SUCCESS) { - } - } - - private void onTimeResult(PatchSelfTestResult patchSelfTestResult) { + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SelfTestTask error")); } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetGlobalTimeTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetGlobalTimeTask.java index 0626764c8c..3fb3da115e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetGlobalTimeTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetGlobalTimeTask.java @@ -16,9 +16,8 @@ import io.reactivex.Single; @Singleton public class SetGlobalTimeTask extends TaskBase { - - private SetGlobalTime SET_GLOBAL_TIME; - private GetGlobalTime GET_GLOBAL_TIME; + private final SetGlobalTime SET_GLOBAL_TIME; + private final GetGlobalTime GET_GLOBAL_TIME; @Inject public SetGlobalTimeTask() { @@ -37,24 +36,23 @@ public class SetGlobalTimeTask extends TaskBase { .doOnNext(this::checkResponse) .firstOrError() .doOnSuccess(v -> onSuccess()) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SetGlobalTimeTask error")); } - private boolean checkPatchTime(GlobalTimeResponse response) throws Exception { + private void checkPatchTime(GlobalTimeResponse response) throws Exception { long newMilli = System.currentTimeMillis(); long oldMilli = response.getGlobalTimeInMilli(); long oldOffset = response.getTimeZoneOffset(); int offset = TimeZone.getDefault().getOffset(newMilli); int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(offset); - // TimeZoneOffset (8bit / signed): 타임존 offset 15분 단위을 1로 환산, Korea 의 경우 36값(+9:00) int newOffset = minutes / 15; long diff = Math.abs(oldMilli - newMilli); if (diff > 60000 || oldOffset != newOffset) { aapsLogger.debug(LTag.PUMPCOMM, String.format("checkPatchTime %s %s %s", diff, oldOffset, newOffset)); - return true; + return; } throw new Exception("No time set required"); diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetLowReservoirTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetLowReservoirTask.java index 14fd2510bb..fbb5a41ad3 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetLowReservoirTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SetLowReservoirTask.java @@ -14,11 +14,9 @@ import io.reactivex.Single; @Singleton public class SetLowReservoirTask extends TaskBase { + @Inject IPreferenceManager pm; - @Inject - IPreferenceManager pm; - - private SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT; + private final SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT; @Inject public SetLowReservoirTask() { @@ -33,7 +31,7 @@ public class SetLowReservoirTask extends TaskBase { hours)) .doOnNext(this::checkResponse) .firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SetLowReservoirTask error")); } public synchronized void enqueue() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartBondTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartBondTask.java index 4b4e9e02ef..d3a6d43066 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartBondTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartBondTask.java @@ -14,12 +14,9 @@ import io.reactivex.Single; import static info.nightscout.androidaps.plugins.pump.eopatch.core.api.StartBonding.OPTION_NUMERIC; -/** - * (주의) API 호출 후 본딩을 위해서 밑단 연결이 끊어짐. - */ @Singleton public class StartBondTask extends TaskBase { - private StartBonding START_BOND; + private final StartBonding START_BOND; @Inject public StartBondTask() { @@ -44,7 +41,7 @@ public class StartBondTask extends TaskBase { .doOnNext(v -> prefSetMacAddress(mac)) .doOnError(e -> { prefSetMacAddress(""); - aapsLogger.error(LTag.PUMPCOMM, e.getMessage()); + aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartBondTask error"); }) .firstOrError(); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartCalcBolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartCalcBolusTask.java index 6cdbb99329..de0a3e7920 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartCalcBolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartCalcBolusTask.java @@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.shared.logging.LTag; -import info.nightscout.androidaps.plugins.pump.eopatch.code.BolusExDuration; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStart; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.ComboBolusStart; -import info.nightscout.androidaps.plugins.pump.eopatch.core.api.ExtBolusStart; import javax.inject.Inject; import javax.inject.Singleton; @@ -16,47 +13,34 @@ import io.reactivex.Single; @Singleton public class StartCalcBolusTask extends BolusTask { - - private BolusStart NOW_BOLUS_START; - private ExtBolusStart EXT_BOLUS_START; - private ComboBolusStart COMBO_BOLUS_START; + private final BolusStart NOW_BOLUS_START; @Inject public StartCalcBolusTask() { super(TaskFunc.START_CALC_BOLUS); NOW_BOLUS_START = new BolusStart(); - EXT_BOLUS_START = new ExtBolusStart(); - COMBO_BOLUS_START = new ComboBolusStart(); } public Single start(DetailedBolusInfo detailedBolusInfo) { - return isReady().concatMapSingle(v -> startBolusImpl((float)detailedBolusInfo.insulin, 0f, BolusExDuration.OFF)) + return isReady().concatMapSingle(v -> startBolusImpl((float)detailedBolusInfo.insulin)) .doOnNext(this::checkResponse) .firstOrError() - .doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin, (float)detailedBolusInfo.insulin, 0f, BolusExDuration.OFF)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin)) + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartCalcBolusTask error")); } - private Single startBolusImpl(float nowDoseU, float exDoseU, - BolusExDuration exDuration) { - if (nowDoseU > 0 && exDoseU > 0) { - return COMBO_BOLUS_START.start(nowDoseU, exDoseU, exDuration.getMinute()); - } else if (exDoseU > 0) { - return EXT_BOLUS_START.start(exDoseU, exDuration.getMinute()); - } else { - return NOW_BOLUS_START.start(nowDoseU); - } + private Single startBolusImpl(float nowDoseU) { + return NOW_BOLUS_START.start(nowDoseU); } - private void onSuccess(float nowDoseU, float correctionBolus, float exDoseU, BolusExDuration exDuration) { - onCalcBolusStarted(nowDoseU, correctionBolus, exDoseU, exDuration); + private void onSuccess(float nowDoseU) { + onCalcBolusStarted(nowDoseU); enqueue(TaskFunc.UPDATE_CONNECTION); } @Override protected void preCondition() throws Exception { - //checkPatchActivated(); checkPatchConnected(); } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartNormalBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartNormalBasalTask.java index d7a232e14b..8f170eb4ab 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartNormalBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartNormalBasalTask.java @@ -16,8 +16,7 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class StartNormalBasalTask extends TaskBase { - - private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG; + private final BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG; @Inject PatchStateManager patchStateManager; @@ -28,23 +27,25 @@ public class StartNormalBasalTask extends TaskBase { BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig(); } - public Single start(NormalBasal basal, boolean resume) { - return isReady().concatMapSingle(v -> startJob(basal, resume)).firstOrError(); + public Single start(NormalBasal basal) { + return isReady().concatMapSingle(v -> startJob(basal)).firstOrError(); } - public Single startJob(NormalBasal basal, boolean resume) { + public Single startJob(NormalBasal basal) { return BASAL_SCHEDULE_SET_BIG.set(basal.getDoseUnitPerSegmentArray()) .doOnSuccess(this::checkResponse) .observeOn(Schedulers.io()) - .doOnSuccess(v -> onStartNormalBasalResponse(v, basal, resume)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnSuccess(v -> onStartNormalBasalResponse(v, basal)) + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartNormalBasalTask error")); } - private void onStartNormalBasalResponse(BasalScheduleSetResponse response, - NormalBasal basal, boolean resume) throws SQLException { + private void onStartNormalBasalResponse(BasalScheduleSetResponse response, NormalBasal basal) { long timeStamp = response.getTimestamp(); patchStateManager.onBasalStarted(basal, timeStamp+1000); + + pm.getNormalBasalManager().setNormalBasal(basal); + pm.flushNormalBasalManager(); enqueue(TaskFunc.UPDATE_CONNECTION); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartQuickBolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartQuickBolusTask.java index 87967f8da2..483f510c71 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartQuickBolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartQuickBolusTask.java @@ -15,10 +15,9 @@ import io.reactivex.Single; @Singleton public class StartQuickBolusTask extends BolusTask { - - private BolusStart NOW_BOLUS_START; - private ExtBolusStart EXT_BOLUS_START; - private ComboBolusStart COMBO_BOLUS_START; + private final BolusStart NOW_BOLUS_START; + private final ExtBolusStart EXT_BOLUS_START; + private final ComboBolusStart COMBO_BOLUS_START; @Inject public StartQuickBolusTask() { @@ -35,7 +34,7 @@ public class StartQuickBolusTask extends BolusTask { .doOnNext(this::checkResponse) .firstOrError() .doOnSuccess(v -> onSuccess(nowDoseU, exDoseU, exDuration)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartQuickBolusTask error")); } private Single startBolusImpl(float nowDoseU, float exDoseU, diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartTempBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartTempBasalTask.java index e3d6a4fb72..c3476f7df7 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartTempBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StartTempBasalTask.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; +import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager; import info.nightscout.shared.logging.LTag; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStart; @@ -13,8 +14,8 @@ import io.reactivex.schedulers.Schedulers; @Singleton public class StartTempBasalTask extends TaskBase { - - private TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START; + @Inject IPreferenceManager pm; + private final TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START; @Inject public StartTempBasalTask() { @@ -30,10 +31,12 @@ public class StartTempBasalTask extends TaskBase { .firstOrError() .observeOn(Schedulers.io()) .doOnSuccess(v -> onTempBasalStarted(tempBasal)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartTempBasalTask error")); } private void onTempBasalStarted(TempBasal tempBasal) { + pm.getTempBasalManager().updateBasalRunning(tempBasal); + pm.flushTempBasalManager(); enqueue(TaskFunc.UPDATE_CONNECTION); } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopBasalTask.java index ff8fa8996f..77c5544349 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopBasalTask.java @@ -25,17 +25,16 @@ import io.reactivex.subjects.BehaviorSubject; @Singleton public class StopBasalTask extends TaskBase { - @Inject IPreferenceManager pm; @Inject CommandQueue commandQueue; @Inject AAPSLogger aapsLogger; @Inject PumpSync pumpSync; @Inject UserEntryLogger uel; - private BasalStop BASAL_STOP; - private BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject exbolusCheckSubject = BehaviorSubject.create(); - private BehaviorSubject basalCheckSubject = BehaviorSubject.create(); + private final BasalStop BASAL_STOP; + private final BehaviorSubject bolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject exbolusCheckSubject = BehaviorSubject.create(); + private final BehaviorSubject basalCheckSubject = BehaviorSubject.create(); @Inject public StopBasalTask() { @@ -89,16 +88,15 @@ public class StopBasalTask extends TaskBase { basalCheckSubject.onNext(true); } - return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { - return (bolusReady && exbolusReady && basalReady); - }) + return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) + -> (bolusReady && exbolusReady && basalReady)) .filter(ready -> ready) .flatMap(v -> isReady()) .concatMapSingle(v -> BASAL_STOP.stop()) .doOnNext(this::checkResponse) .firstOrError() .doOnSuccess(this::onBasalStopped) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopBasalTask error")); } private void onBasalStopped(BasalStopResponse response) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopComboBolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopComboBolusTask.java index fec4f7ba8c..0746ae5e18 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopComboBolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopComboBolusTask.java @@ -16,8 +16,7 @@ import io.reactivex.Single; @Singleton public class StopComboBolusTask extends BolusTask { - - private BolusStop BOLUS_STOP; + private final BolusStop BOLUS_STOP; @Inject public StopComboBolusTask() { @@ -31,7 +30,7 @@ public class StopComboBolusTask extends BolusTask { .firstOrError() .doOnSuccess(this::checkResponse) .doOnSuccess(this::onComboBolusStopped) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopComboBolusTask error")); } public Single stopJob() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopExtBolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopExtBolusTask.java index f7a44ed3d8..b0ecf5265a 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopExtBolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopExtBolusTask.java @@ -14,19 +14,17 @@ import io.reactivex.Single; @Singleton public class StopExtBolusTask extends BolusTask { - - private BolusStop BOLUS_STOP; + private final BolusStop BOLUS_STOP; @Inject public StopExtBolusTask() { super(TaskFunc.STOP_EXT_BOLUS); - BOLUS_STOP = new BolusStop(); } public Single stop() { return isReady().concatMapSingle(v -> stopJob()).firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopExtBolusTask error")); } public Single stopJob() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopNowBolusTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopNowBolusTask.java index 28c7e5ad95..b66244b9e6 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopNowBolusTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopNowBolusTask.java @@ -15,13 +15,11 @@ import io.reactivex.android.schedulers.AndroidSchedulers; @Singleton public class StopNowBolusTask extends BolusTask { - - private BolusStop BOLUS_STOP; + private final BolusStop BOLUS_STOP; @Inject public StopNowBolusTask() { super(TaskFunc.STOP_NOW_BOLUS); - BOLUS_STOP = new BolusStop(); } @@ -29,7 +27,7 @@ public class StopNowBolusTask extends BolusTask { return isReady() .observeOn(AndroidSchedulers.mainThread()) .concatMapSingle(v -> stopJob()).firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopNowBolusTask error")); } public Single stopJob() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopTempBasalTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopTempBasalTask.java index 691c7f27c1..8ee052c05e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopTempBasalTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/StopTempBasalTask.java @@ -13,8 +13,7 @@ import io.reactivex.Single; @Singleton public class StopTempBasalTask extends TaskBase { - - private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP; + private final TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP; @Inject public StopTempBasalTask() { @@ -25,7 +24,7 @@ public class StopTempBasalTask extends TaskBase { public Single stop() { return isReady().concatMapSingle(v -> stopJob()).firstOrError() - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopTempBasalTask error")); } public Single stopJob() { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SyncBasalHistoryTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SyncBasalHistoryTask.java index d66ea87d82..966b913b6f 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SyncBasalHistoryTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/SyncBasalHistoryTask.java @@ -5,7 +5,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalHistoryGetE import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalHistoryIndexGet; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalHistoryGetExBig; -import java.sql.SQLException; import java.util.concurrent.TimeUnit; import javax.inject.Inject; @@ -19,13 +18,11 @@ import static info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatch @Singleton public class SyncBasalHistoryTask extends TaskBase { + @Inject IPreferenceManager pm; - @Inject - IPreferenceManager pm; - - private BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET; - private BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG; - private TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG; + private final BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET; + private final BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG; + private final TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG; @Inject public SyncBasalHistoryTask() { @@ -38,19 +35,10 @@ public class SyncBasalHistoryTask extends TaskBase { public Single sync(int end) { return Single.just(1); // 베이젤 싱크 사용 안함 -// return isReady() -// .concatMapSingle(v -> syncBoth(pm.getPatchConfig().getLastIndex(), end)) -// .firstOrError() -// .doOnSuccess(this::updatePatchLastIndex); } public Single sync() { return Single.just(1); // 베이젤 싱크 사용 안함 -// return isReady() -// .concatMapSingle(v -> getLastIndex()) -// .concatMapSingle(end -> syncBoth(pm.getPatchConfig().getLastIndex(), end)) -// .firstOrError() -// .doOnSuccess(this::updatePatchLastIndex); } private Single getLastIndex() { @@ -94,7 +82,7 @@ public class SyncBasalHistoryTask extends TaskBase { } private int onBasalHistoryResponse(BasalHistoryResponse n, BasalHistoryResponse t, - int startRequested, int end) throws SQLException { + int startRequested, int end) { if (!n.isSuccess() || !t.isSuccess() || n.getSeq() != t.getSeq()) { return -1; @@ -112,7 +100,7 @@ public class SyncBasalHistoryTask extends TaskBase { return updateInjected(normal, temp, start, end); } - public synchronized int updateInjected(float[] normal, float[] temp, int start, int end) throws SQLException { + public synchronized int updateInjected(float[] normal, float[] temp, int start, int end) { if (pm.getPatchState().isPatchInternalSuspended() && pm.getPatchConfig().isInBasalPausedTime() == false) { return -1; } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/TaskQueue.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/TaskQueue.java index 8b9ef9e8ab..88895ff90c 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/TaskQueue.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/TaskQueue.java @@ -33,11 +33,9 @@ public class TaskQueue { protected synchronized Observable isReady(final TaskFunc function) { return Observable.fromCallable(() -> publishTicket(function)) - .concatMap(v -> { - return ticketSubject - .takeUntil(it -> it.number > v) - .filter(it -> it.number == v); - }) + .concatMap(v -> ticketSubject + .takeUntil(it -> it.number > v) + .filter(it -> it.number == v)) .doOnNext(v -> aapsLogger.debug(LTag.PUMPCOMM, String.format("Task #:%s started func:%s", v.number, v.func.name()))) .observeOn(Schedulers.io()) .map(it -> it.func) @@ -86,13 +84,13 @@ public class TaskQueue { public synchronized boolean has(TaskFunc func) { if (queue.size() > 1) { - Iterator itor = queue.iterator(); + Iterator iterator = queue.iterator(); /* remove 1st queue */ - itor.next(); + iterator.next(); - while (itor.hasNext()) { - PatchTask item = itor.next(); + while (iterator.hasNext()) { + PatchTask item = iterator.next(); if (item.func == func) { return true; } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/UpdateConnectionTask.java b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/UpdateConnectionTask.java index 729bbb4651..cc80416365 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/UpdateConnectionTask.java +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ble/task/UpdateConnectionTask.java @@ -15,9 +15,7 @@ import io.reactivex.Single; @Singleton public class UpdateConnectionTask extends TaskBase { - - @Inject - PatchStateManager patchStateManager; + @Inject PatchStateManager patchStateManager; private UpdateConnection UPDATE_CONNECTION; @@ -38,7 +36,7 @@ public class UpdateConnectionTask extends TaskBase { .map(UpdateConnectionResponse::getPatchState) .map(bytes -> PatchState.Companion.create(bytes, System.currentTimeMillis())) .doOnSuccess(state -> onUpdateConnection(state)) - .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); + .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "UpdateConnectionTask error")); } private void onUpdateConnection(PatchState patchState) { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmCategory.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmCategory.kt index 10d3115a01..93f00b95ee 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmCategory.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmCategory.kt @@ -1,46 +1,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -import com.google.android.gms.common.internal.Preconditions - -enum class AlarmCategory private constructor(val rawValue: Int) { - NONE(0), - ALARM(1), - ALERT(2); - - companion object { - - - /** - * rawValue로 값을 찾기, 못찾으면 null을 리턴 - */ - fun ofRaw(rawValue: Int?): AlarmCategory? { - if (rawValue == null) { - return null - } - - for (t in AlarmCategory.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return null - } - - /** - * rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴 - */ - fun ofRaw(rawValue: Int?, defaultValue: AlarmCategory): AlarmCategory { - Preconditions.checkNotNull(defaultValue) - if (rawValue == null) { - return defaultValue - } - - for (t in AlarmCategory.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return defaultValue - } - } +enum class AlarmCategory{ + NONE, + ALARM, + ALERT; } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmSource.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmSource.kt deleted file mode 100644 index c433488b7b..0000000000 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/AlarmSource.kt +++ /dev/null @@ -1,66 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.eopatch.code - - -import com.google.android.gms.common.internal.Preconditions -import com.google.gson.annotations.SerializedName - -enum class AlarmSource private constructor(val rawValue: Int) { - @SerializedName("0") - NONE(0), - @SerializedName("1") - PATCH(1), - @SerializedName("2") - ADM(2), - @SerializedName("3") - CGM(3), - @SerializedName("9") - TEST(9); - - val isTest: Boolean - get() = this == TEST - - val isCgm: Boolean - get() = this == CGM - - companion object { - - /** - * rawValue로 값을 찾기, 못찾으면 null을 리턴 - */ - @JvmStatic - fun ofRaw(rawValue: Int?): AlarmSource { - if (rawValue == null) { - return NONE - } - - for (t in AlarmSource.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return NONE - } - - @JvmStatic - fun toRaw(source: AlarmSource?): Int { - return if (source != null) source.rawValue else NONE.rawValue - } - - /** - * rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴 - */ - fun ofRaw(rawValue: Int?, defaultValue: AlarmSource): AlarmSource { - Preconditions.checkNotNull(defaultValue) - if (rawValue == null) { - return defaultValue - } - - for (t in AlarmSource.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return defaultValue - } - } -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BasalStatus.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BasalStatus.kt index 4225e0e523..6758b29836 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BasalStatus.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BasalStatus.kt @@ -10,21 +10,12 @@ enum class BasalStatus constructor(val rawValue: Int) { val isStarted: Boolean get() = this == STARTED - val isPaused: Boolean - get() = this == PAUSED - val isSuspended: Boolean get() = this == SUSPENDED val isStopped: Boolean get() = this == STOPPED - val isSelected: Boolean - get() = this == SELECTED - - val isSelectedGroup: Boolean - get() = isStarted || isPaused || isSuspended || isSelected - companion object { @JvmStatic fun ofRaw(rawValue: Int?): BasalStatus { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BgUnit.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BgUnit.kt deleted file mode 100644 index b1bd632d51..0000000000 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BgUnit.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.eopatch.code - -enum class BgUnit private constructor(val rawValue: Int, val unitStr: String) { - GRAM(1, "mg/dL"), - MMOL(2, "mmol/L"); - - fun isGram() = GRAM == this - fun isMmol() = MMOL == this - - fun getUnit() = unitStr - - companion object { - /** - * rawValue로 값을 찾기, 못찾으면 null을 리턴 - */ - fun ofRaw(rawValue: Int?): BgUnit { - for (t in BgUnit.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return GRAM - } - - /** - * rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴 - */ - fun ofRaw(rawValue: Int, defaultValue: BgUnit): BgUnit { - for (t in BgUnit.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return defaultValue - } - } -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BolusExDuration.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BolusExDuration.kt index 30c0ae7116..fbb1a87e37 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BolusExDuration.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/BolusExDuration.kt @@ -1,10 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -import android.content.Context -import androidx.collection.SparseArrayCompat -import info.nightscout.androidaps.plugins.pump.eopatch.CommonUtils -import info.nightscout.androidaps.plugins.pump.eopatch.R -import java.util.* import java.util.concurrent.TimeUnit enum class BolusExDuration constructor(val index: Int, val minute: Int, val hour: Float) { @@ -26,34 +21,14 @@ enum class BolusExDuration constructor(val index: Int, val minute: Int, val hour MINUTE_450(15, 450, 7.5f), MINUTE_480(16, 480, 8.0f); - val isOff: Boolean - get() = this == OFF - - val isNotOff: Boolean - get() = this != OFF - fun milli(): Long { return TimeUnit.MINUTES.toMillis(this.minute.toLong()) } companion object { - @JvmStatic - fun getItemFromIndex(index: Int): BolusExDuration { - var reverseIndices = SparseArrayCompat() - for (duration in values()) { - reverseIndices.put(duration.index, duration) - } - val result = reverseIndices.get(index) - return result ?: OFF - } - @JvmStatic fun ofRaw(rawValue: Int): BolusExDuration { - if (rawValue == null) { - return OFF - } - - for (t in BolusExDuration.values()) { + for (t in values()) { if (t.minute == rawValue) { return t } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/DeactivationStatus.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/DeactivationStatus.kt index 8373e828df..829b865865 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/DeactivationStatus.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/DeactivationStatus.kt @@ -1,20 +1,14 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -enum class DeactivationStatus constructor(val rawValue: Int) { - DEACTIVATION_FAILED(0), - NORMAL_DEACTIVATED(1), - FORCE_DEACTIVATED(2); +enum class DeactivationStatus { + DEACTIVATION_FAILED, + NORMAL_DEACTIVATED, + FORCE_DEACTIVATED; val isDeactivated: Boolean get() = this == NORMAL_DEACTIVATED || this == FORCE_DEACTIVATED - val isNormalSuccess: Boolean - get() = this == NORMAL_DEACTIVATED - - val isNormalFailed: Boolean - get() = this == DEACTIVATION_FAILED || this == FORCE_DEACTIVATED - companion object { @JvmStatic fun of(isSuccess: Boolean, forced: Boolean): DeactivationStatus { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/Dummy.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/Dummy.kt deleted file mode 100644 index f81dff583e..0000000000 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/Dummy.kt +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.eopatch.code - -enum class Dummy { - INSTANCE -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/EventType.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/EventType.kt index be02c5fd07..efc8207243 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/EventType.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/EventType.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code enum class EventType { - ACTIVTION_CLICKED, - DEACTIVTION_CLICKED, + ACTIVATION_CLICKED, + DEACTIVATION_CLICKED, SUSPEND_CLICKED, RESUME_CLICKED, INVALID_BASAL_RATE, @@ -12,14 +12,9 @@ enum class EventType { SHOW_PATCH_COMM_ERROR_DIALOG, SHOW_BONDED_DIALOG, SHOW_CHANGE_PATCH_DIALOG, - SHOW_PROGRESS_DIALOG, - DISMISS_PROGRESS_DIALOG, FINISH_ACTIVITY, SHOW_DISCARD_DIALOG, PAUSE_BASAL_FAILED, - RESUME_BASAL_FAILED, - CALCULATED_BOLUS_CLICKED, - EXTENDED_BOLUS_SETTINGS_CLICKED, - SAVE_CLICKED + RESUME_BASAL_FAILED ; } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchExpireAlertTime.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchExpireAlertTime.kt index 9c3a685294..d34c568c04 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchExpireAlertTime.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchExpireAlertTime.kt @@ -1,9 +1,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -import android.content.Context -import info.nightscout.androidaps.plugins.pump.eopatch.R - -enum class PatchExpireAlertTime private constructor(val index: Int, val hour: Int) { +enum class PatchExpireAlertTime constructor(val index: Int, val hour: Int) { HOUR_1(0, 1), HOUR_2(1, 2), HOUR_3(2, 3), @@ -28,25 +25,4 @@ enum class PatchExpireAlertTime private constructor(val index: Int, val hour: In HOUR_22(21, 22), HOUR_23(22, 23), HOUR_24(23, 24); - - companion object { - - fun atIndex(index: Int): PatchExpireAlertTime { - for (i in values()) { - if (i.index == index) { - return i - } - } - return HOUR_1 - } - - fun atHour(hour: Int): PatchExpireAlertTime { - for (i in values()) { - if (i.hour == hour) { - return i - } - } - return HOUR_1 - } - } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchLifecycle.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchLifecycle.kt index 99c8d287c0..db153c6130 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchLifecycle.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchLifecycle.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -enum class PatchLifecycle private constructor(val rawValue: Int) { +enum class PatchLifecycle constructor(val rawValue: Int) { SHUTDOWN(1), BONDED(2), SAFETY_CHECK(3), @@ -16,15 +16,4 @@ enum class PatchLifecycle private constructor(val rawValue: Int) { val isActivated: Boolean get() = this == ACTIVATED - companion object { - @JvmStatic - fun ofRaw(rawValue: Int): PatchLifecycle { - for (type in values()) { - if (type.rawValue == rawValue) { - return type - } - } - return SHUTDOWN - } - } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchStep.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchStep.kt index eed465a75a..02ca419279 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchStep.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/PatchStep.kt @@ -21,9 +21,6 @@ enum class PatchStep { BACK_TO_HOME, FINISH; - val isConnectNew: Boolean - get() = this == CONNECT_NEW - val isSafeDeactivation: Boolean get() = this == SAFE_DEACTIVATION diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/SettingKeys.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/SettingKeys.kt index 13f6a5474f..23eb459cb8 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/SettingKeys.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/SettingKeys.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.R class SettingKeys { companion object{ - val LOW_RESERVIOR_REMINDERS: Int = R.string.key_eopatch_low_reservior_reminders + val LOW_RESERVOIR_REMINDERS: Int = R.string.key_eopatch_low_reservoir_reminders val EXPIRATION_REMINDERS: Int = R.string.key_eopatch_expiration_reminders val BUZZER_REMINDERS: Int = R.string.key_eopatch_patch_buzzer_reminders diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/UnitOrPercent.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/UnitOrPercent.kt index 56e27148bb..1c7aa5795d 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/UnitOrPercent.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/code/UnitOrPercent.kt @@ -1,52 +1,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.code -import com.google.android.gms.common.internal.Preconditions - -enum class UnitOrPercent private constructor(val rawValue: Int, val symbol: String) { - P(0, "%"), - U(1, "U"); - +enum class UnitOrPercent { + P, + U; fun isPercentage() = this == P - fun isU() = this == U - - companion object { - - val U_PER_HOUR = "U/hr" - val U_PER_DAY = "U/day" - - - /** - * rawValue로 값을 찾기, 못찾으면 null을 리턴 - */ - fun ofRaw(rawValue: Int?): UnitOrPercent? { - if (rawValue == null) { - return null - } - - for (t in UnitOrPercent.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return null - } - - /** - * rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴 - */ - fun ofRaw(rawValue: Int?, defaultValue: UnitOrPercent): UnitOrPercent { - Preconditions.checkNotNull(defaultValue) - if (rawValue == null) { - return defaultValue - } - - for (t in UnitOrPercent.values()) { - if (t.rawValue == rawValue) { - return t - } - } - return defaultValue - } - } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchInjectHelpers.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchInjectHelpers.kt index ca9592d836..d749761e66 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchInjectHelpers.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchInjectHelpers.kt @@ -6,11 +6,6 @@ import javax.inject.Scope @Qualifier annotation class EopatchPluginQualifier -@MustBeDocumented -@Scope -@Retention(AnnotationRetention.RUNTIME) -annotation class ActivityScope - @MustBeDocumented @Scope @Retention(AnnotationRetention.RUNTIME) diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchModule.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchModule.kt index e971078b5d..e148cf76ae 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchModule.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchModule.kt @@ -39,7 +39,6 @@ abstract class EopatchModule { } - @Binds @Singleton abstract fun bindPatchManager(patchManager: PatchManager): IPatchManager diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchPrefModule.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchPrefModule.kt index 94b63103d4..03cd624009 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchPrefModule.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/dagger/EopatchPrefModule.kt @@ -1,17 +1,11 @@ package info.nightscout.androidaps.plugins.pump.eopatch.dagger -import android.app.Application -import android.content.Context -import dagger.Binds import dagger.Module import dagger.Provides -import info.nightscout.androidaps.plugins.pump.eopatch.ble.* import info.nightscout.androidaps.plugins.pump.eopatch.vo.Alarms import info.nightscout.androidaps.plugins.pump.eopatch.vo.NormalBasalManager import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchConfig -import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasalManager -import info.nightscout.shared.sharedPreferences.SP import javax.inject.Singleton @Module @@ -24,13 +18,13 @@ class EopatchPrefModule { @Provides @Singleton - internal fun provideNormalBasalManager(sp: SP): NormalBasalManager { + internal fun provideNormalBasalManager(): NormalBasalManager { return NormalBasalManager() } @Provides @Singleton - internal fun provideTempBasalManager(sp: SP): TempBasalManager { + internal fun provideTempBasalManager(): TempBasalManager { return TempBasalManager() } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/event/EoPatchEvents.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/event/EoPatchEvents.kt index cd8656fc77..409a4e6561 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/event/EoPatchEvents.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/event/EoPatchEvents.kt @@ -8,4 +8,4 @@ import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode class EventEoPatchAlarm(var alarmCodes: Set, var isFirst: Boolean = false) : Event() class EventDialog(val dialog: DialogFragment, val show: Boolean) : Event() class EventProgressDialog(val show: Boolean, @StringRes val resId: Int = 0) : Event() -class EventPatchActivationNotComplete() : Event() \ No newline at end of file +class EventPatchActivationNotComplete : Event() \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/AppCompatActivityExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/AppCompatActivityExtension.kt index 46cb3c2cd5..e6ad855b07 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/AppCompatActivityExtension.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/AppCompatActivityExtension.kt @@ -1,13 +1,9 @@ package info.nightscout.androidaps.plugins.pump.eopatch.extension -import android.content.Intent -import android.os.Bundle -import android.os.Parcelable import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction -import java.io.Serializable fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int, addToBackStack: Boolean = false) { supportFragmentManager.transact { @@ -20,43 +16,4 @@ private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Un beginTransaction().apply { action() }.commit() -} - -fun Intent.fillExtras(params: Array>){ - fillIntentArguments(this, params) -} - -private fun fillIntentArguments(intent: Intent, params: Array>) { - params.forEach { - when (val value = it.second) { - null -> intent.putExtra(it.first, null as Serializable?) - is Int -> intent.putExtra(it.first, value) - is Long -> intent.putExtra(it.first, value) - is CharSequence -> intent.putExtra(it.first, value) - is String -> intent.putExtra(it.first, value) - is Float -> intent.putExtra(it.first, value) - is Double -> intent.putExtra(it.first, value) - is Char -> intent.putExtra(it.first, value) - is Short -> intent.putExtra(it.first, value) - is Boolean -> intent.putExtra(it.first, value) - is Serializable -> intent.putExtra(it.first, value) - is Bundle -> intent.putExtra(it.first, value) - is Parcelable -> intent.putExtra(it.first, value) - is Array<*> -> when { - value.isArrayOf() -> intent.putExtra(it.first, value) - value.isArrayOf() -> intent.putExtra(it.first, value) - value.isArrayOf() -> intent.putExtra(it.first, value) - else -> throw Exception("Intent extra ${it.first} has wrong type ${value.javaClass.name}") - } - is IntArray -> intent.putExtra(it.first, value) - is LongArray -> intent.putExtra(it.first, value) - is FloatArray -> intent.putExtra(it.first, value) - is DoubleArray -> intent.putExtra(it.first, value) - is CharArray -> intent.putExtra(it.first, value) - is ShortArray -> intent.putExtra(it.first, value) - is BooleanArray -> intent.putExtra(it.first, value) - else -> throw Exception("Intent extra ${it.first} has wrong type ${value.javaClass.name}") - } - return@forEach - } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/FloatExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/FloatExtension.kt index e8341c7273..08692f540a 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/FloatExtension.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/FloatExtension.kt @@ -1,15 +1,17 @@ package info.nightscout.androidaps.plugins.pump.eopatch.extension +import kotlin.math.abs + fun Float.nearlyEqual(b: Float, epsilon: Float): Boolean { - val absA = Math.abs(this) - val absB = Math.abs(b) - val diff = Math.abs(this - b) + val absA = abs(this) + val absB = abs(b) + val diff = abs(this - b) return if (this == b) { true } else if (this == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) { diff < epsilon * java.lang.Float.MIN_NORMAL } else { - diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon + diff / (absA + absB).coerceAtMost(Float.MAX_VALUE) < epsilon } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/LongExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/LongExtension.kt index c3de482c8c..7fef444e07 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/LongExtension.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/LongExtension.kt @@ -6,29 +6,6 @@ import java.util.concurrent.TimeUnit internal val Long.date: Date get() = Calendar.getInstance().also { it.timeInMillis = this }.time -fun Long.getDiffTime(isRelative: Boolean = false): Triple { - val inputTimeMillis = this - val currentTimeMillis = System.currentTimeMillis() - val diffTimeMillis = if (inputTimeMillis > currentTimeMillis) inputTimeMillis - currentTimeMillis else isRelative.takeOne(currentTimeMillis - inputTimeMillis, 0) - - val hours = TimeUnit.MILLISECONDS.toHours(diffTimeMillis) - val minutes = TimeUnit.MILLISECONDS.toMinutes(diffTimeMillis - TimeUnit.HOURS.toMillis(hours)) - val seconds = TimeUnit.MILLISECONDS.toSeconds(diffTimeMillis - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes)) - - return Triple(hours, minutes, seconds) -} - -fun Long.getDiffTime(startTimeMillis: Long): Triple { - val inputTimeMillis = this - val diffTimeMillis = if (inputTimeMillis > startTimeMillis) inputTimeMillis - startTimeMillis else 0 - - val hours = TimeUnit.MILLISECONDS.toHours(diffTimeMillis) - val minutes = TimeUnit.MILLISECONDS.toMinutes(diffTimeMillis - TimeUnit.HOURS.toMillis(hours)) - val seconds = TimeUnit.MILLISECONDS.toSeconds(diffTimeMillis - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes)) - - return Triple(hours, minutes, seconds) -} - fun Long.getDiffDays(isRelative: Boolean = false): Long { val inputTimeMillis = this val currentTimeMillis = System.currentTimeMillis() @@ -36,7 +13,3 @@ fun Long.getDiffDays(isRelative: Boolean = false): Long { return TimeUnit.MILLISECONDS.toDays(diffTimeMillis) } - -fun Long.getSeconds() : Long { - return (this/1000)*1000 -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/SingleExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/SingleExtension.kt index ba453140f2..cd89deeb51 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/SingleExtension.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/SingleExtension.kt @@ -7,8 +7,6 @@ import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers -fun Single.observeOnMainThread(): Single = observeOn(AndroidSchedulers.mainThread()) - fun Single.subscribeDefault(aapsLogger: AAPSLogger, onSuccess: (T) -> Unit): Disposable = subscribe(onSuccess, { aapsLogger.error(LTag.PUMP, "onError", it) }) diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/StringExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/StringExtension.kt index ad8a1b9b07..55fc573532 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/StringExtension.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/StringExtension.kt @@ -20,29 +20,3 @@ fun String.fromHtml(): CharSequence = Html.fromHtml(this, Html.FROM_HTML_MODE_CO fun String.isEmpty(): Boolean{ return this.length == 0 } - -fun String.getSeparatorForLog(): String { - return StringBuilder().let { - for (i in 0 until length) { - it.append("=") - } - it.toString() - } -} - -fun String.convertUtcToLocalDate(): Date { - val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()) - val convertDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) - val timeZone = TimeZone.getDefault() - - var parseDate = format.parse(this) - - val convertedDate = convertDateFormat.format(parseDate) - parseDate = convertDateFormat.parse(convertedDate) - - val locTime = convertDateFormat.format(parseDate.time + timeZone.getOffset(parseDate.time)).replace("+0000", "") - - val retDate = convertDateFormat.parse(locTime) - - return retDate -} \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/TextViewExtension.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/TextViewExtension.kt deleted file mode 100644 index 1292fe116e..0000000000 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/extension/TextViewExtension.kt +++ /dev/null @@ -1,20 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.eopatch.extension - -import android.text.InputFilter -import android.widget.EditText - -internal fun EditText.setRange(min: Int, max: Int) { - filters = arrayOf(InputFilter { source, _, _, dest, _, _ -> - try { - val input = Integer.parseInt(dest.toString() + source.toString()) - - if (input in min..max) { - return@InputFilter null - } - } catch (e: NumberFormatException) { - e.printStackTrace() - } - - return@InputFilter "" - }) -} diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/AlarmHelperActivity.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/AlarmHelperActivity.kt index d166a3d6e5..47706da849 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/AlarmHelperActivity.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/AlarmHelperActivity.kt @@ -1,8 +1,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui -import android.app.AlertDialog -import android.app.ProgressDialog import android.os.Bundle +import androidx.appcompat.app.AlertDialog import info.nightscout.androidaps.activities.DialogAppCompatActivity import info.nightscout.androidaps.core.R import info.nightscout.androidaps.plugins.bus.RxBus @@ -10,6 +9,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode import info.nightscout.androidaps.plugins.pump.eopatch.event.EventDialog import info.nightscout.androidaps.plugins.pump.eopatch.event.EventProgressDialog import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.AlarmDialog +import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.ProgressDialogHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable @@ -20,7 +20,7 @@ class AlarmHelperActivity : DialogAppCompatActivity() { @Inject lateinit var rxBus: RxBus private var disposable: CompositeDisposable = CompositeDisposable() - private var mProgressDialog: ProgressDialog? = null + private var mProgressDialog: AlertDialog? = null @Override override fun onCreate(savedInstanceState: Bundle?) { @@ -64,10 +64,8 @@ class AlarmHelperActivity : DialogAppCompatActivity() { private fun showProgressDialog(resId: Int){ if (mProgressDialog == null && resId != 0) { - mProgressDialog = ProgressDialog(this).apply { - setMessage(getString(resId)) + mProgressDialog = ProgressDialogHelper.get(this, getString(resId)).apply { setCancelable(false) - setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal) } mProgressDialog?.show() } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/DialogHelperActivity.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/DialogHelperActivity.kt index cc30cfd3b4..5751066837 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/DialogHelperActivity.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/DialogHelperActivity.kt @@ -18,8 +18,4 @@ class DialogHelperActivity : DialogAppCompatActivity() { dialog.message = intent.getStringExtra("message")?:"" dialog.show(supportFragmentManager, "Dialog") } - - override fun onDestroy() { - super.onDestroy() - } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseActivity.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseActivity.kt index 5c4ddd609b..b3dafab128 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseActivity.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseActivity.kt @@ -1,23 +1,17 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui -import android.content.Context import android.content.Intent import android.os.Bundle -import android.view.View import android.widget.Toast +import androidx.activity.result.ActivityResultLauncher import androidx.annotation.LayoutRes import androidx.annotation.StringRes -import androidx.appcompat.app.AppCompatDelegate import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.ViewModelProvider import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.plugins.pump.eopatch.EoPatchRxBus import info.nightscout.androidaps.plugins.pump.eopatch.dagger.EopatchPluginQualifier -import info.nightscout.androidaps.plugins.pump.eopatch.extension.fillExtras -import info.nightscout.androidaps.plugins.pump.eopatch.extension.subscribeDefault -import info.nightscout.androidaps.plugins.pump.eopatch.vo.ActivityResultEvent import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable @@ -35,6 +29,8 @@ abstract class EoBaseActivity : NoSplashAppCompatActivity() private val compositeDisposable = CompositeDisposable() + protected lateinit var getResult: ActivityResultLauncher + @LayoutRes abstract fun getLayoutId(): Int @@ -47,18 +43,6 @@ abstract class EoBaseActivity : NoSplashAppCompatActivity() } - override fun onStart() { - super.onStart() - window.decorView.systemUiVisibility = if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_NO) - View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR - else - View.SYSTEM_UI_FLAG_VISIBLE - } - - override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { - super.onActivityResult(requestCode, resultCode, data) - } - override fun toast(message: String) { Toast.makeText(this@EoBaseActivity, message, Toast.LENGTH_SHORT).show() } @@ -83,26 +67,5 @@ abstract class EoBaseActivity : NoSplashAppCompatActivity() } } - override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair) { - val intent = action(this) - if(params.isNotEmpty()) intent.fillExtras(params) - startActivityForResult(intent, requestCode) - } - - override fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)?, onDiscard: (() -> Unit)?, goHomeAfterDiscard: Boolean) { - EoPatchRxBus.listen(ActivityResultEvent::class.java) - .doOnSubscribe { startActivityForResult({ EopatchActivity.createIntentForCheckConnection(this, goHomeAfterDiscard) }, 10001) } - .observeOn(aapsSchedulers.main) - .subscribeDefault(aapsLogger) { - if (it.requestCode == 10001) { - when (it.resultCode) { - RESULT_OK -> onSuccess.invoke() - RESULT_CANCELED -> onCancel?.invoke() - EopatchActivity.RESULT_DISCARDED -> onDiscard?.invoke() - } - } - }.addTo() - } - fun Disposable.addTo() = addTo(compositeDisposable) } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseFragment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseFragment.kt index 14887253fc..bba0632a3e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseFragment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseFragment.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui import android.content.Context -import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View @@ -74,13 +73,6 @@ abstract class EoBaseFragment : DaggerFragment(), EoBaseNav override fun finish(finishAffinity: Boolean) { baseActivity?.finish(finishAffinity) } - override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair) { - baseActivity?.startActivityForResult(action, requestCode, *params) - } - - override fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)?, onDiscard: (() -> Unit)?, goHomeAfterDiscard: Boolean) { - baseActivity?.checkCommunication(onSuccess, onCancel, onDiscard, goHomeAfterDiscard) - } fun Disposable.addTo() = addTo(compositeDisposable) diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseNavigator.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseNavigator.kt index 33e85f15e4..2f98ff9cfb 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseNavigator.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EoBaseNavigator.kt @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui -import android.app.Activity -import android.content.Context -import android.content.Intent import androidx.annotation.StringRes interface EoBaseNavigator { @@ -13,8 +10,4 @@ interface EoBaseNavigator { fun back() fun finish(finishAffinity: Boolean = false) - - fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair) - - fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)? = null, onDiscard: (() -> Unit)? = null, goHomeAfterDiscard: Boolean = true) } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchActivity.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchActivity.kt index da62afe986..933bf5f645 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchActivity.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchActivity.kt @@ -1,14 +1,13 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui import android.app.Dialog -import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.media.MediaPlayer import android.media.RingtoneManager import android.os.Bundle import android.view.MotionEvent -import androidx.lifecycle.Observer +import androidx.appcompat.app.AlertDialog import androidx.lifecycle.ViewModelProvider import info.nightscout.androidaps.plugins.pump.eopatch.R import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchLifecycle @@ -17,6 +16,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.EventType import info.nightscout.androidaps.plugins.pump.eopatch.databinding.ActivityEopatchBinding import info.nightscout.androidaps.plugins.pump.eopatch.extension.replaceFragmentInActivity import info.nightscout.androidaps.plugins.pump.eopatch.extension.takeOne +import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.ProgressDialogHelper import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchViewModel import info.nightscout.androidaps.utils.alertDialogs.AlertDialogHelper @@ -24,7 +24,7 @@ class EopatchActivity : EoBaseActivity() { private var mediaPlayer: MediaPlayer? = null private var mPatchCommCheckDialog: Dialog? = null - private var mProgressDialog: ProgressDialog? = null + private var mProgressDialog: AlertDialog? = null override fun getLayoutId(): Int = R.layout.activity_eopatch @@ -44,59 +44,65 @@ class EopatchActivity : EoBaseActivity() { viewModel?.apply { processIntent(intent) - patchStep.observe(this@EopatchActivity, { + patchStep.observe(this@EopatchActivity) { when (it) { - PatchStep.SAFE_DEACTIVATION -> { - if(isActivated.value?:false){ + PatchStep.SAFE_DEACTIVATION -> { + if (isActivated.value == true) { setupViewFragment(EopatchSafeDeactivationFragment.newInstance()) - }else{ + } else { this@EopatchActivity.finish() } } + PatchStep.MANUALLY_TURNING_OFF_ALARM -> setupViewFragment(EopatchTurningOffAlarmFragment.newInstance()) PatchStep.DISCARDED_FOR_CHANGE, PatchStep.DISCARDED_FROM_ALARM, - PatchStep.DISCARDED -> setupViewFragment(EopatchRemoveFragment.newInstance()) - PatchStep.WAKE_UP -> setupViewFragment(EopatchWakeUpFragment.newInstance()) - PatchStep.CONNECT_NEW -> setupViewFragment(EopatchConnectNewFragment.newInstance()) - PatchStep.REMOVE_NEEDLE_CAP -> setupViewFragment(EopatchRemoveNeedleCapFragment.newInstance()) - PatchStep.REMOVE_PROTECTION_TAPE -> setupViewFragment(EopatchRemoveProtectionTapeFragment.newInstance()) - PatchStep.SAFETY_CHECK -> setupViewFragment(EopatchSafetyCheckFragment.newInstance()) + PatchStep.DISCARDED -> setupViewFragment(EopatchRemoveFragment.newInstance()) + PatchStep.WAKE_UP -> setupViewFragment(EopatchWakeUpFragment.newInstance()) + PatchStep.CONNECT_NEW -> setupViewFragment(EopatchConnectNewFragment.newInstance()) + PatchStep.REMOVE_NEEDLE_CAP -> setupViewFragment(EopatchRemoveNeedleCapFragment.newInstance()) + PatchStep.REMOVE_PROTECTION_TAPE -> setupViewFragment(EopatchRemoveProtectionTapeFragment.newInstance()) + PatchStep.SAFETY_CHECK -> setupViewFragment(EopatchSafetyCheckFragment.newInstance()) PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR, - PatchStep.ROTATE_KNOB -> setupViewFragment(EopatchRotateKnobFragment.newInstance()) - PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance()) + PatchStep.ROTATE_KNOB -> setupViewFragment(EopatchRotateKnobFragment.newInstance()) + PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance()) // PatchStep.SETTING_REMINDER_TIME -> setupViewFragment(PatchExpirationReminderSettingFragment.newInstance()) - PatchStep.CHECK_CONNECTION -> { - checkCommunication({ - setResult(RESULT_OK) - this@EopatchActivity.finish() - }, { - setResult(RESULT_CANCELED) - this@EopatchActivity.finish() - }, { - setResult(RESULT_DISCARDED) + PatchStep.CHECK_CONNECTION -> { + checkCommunication( + { + setResult(RESULT_OK) + this@EopatchActivity.finish() + }, { + setResult(RESULT_CANCELED) + this@EopatchActivity.finish() + }, { + setResult(RESULT_DISCARDED) - if (intent.getBooleanExtra(EXTRA_GO_HOME, true)) { - backToHome(false) - } else { - this@EopatchActivity.finish() - } - }, doIntercept = true) + if (intent.getBooleanExtra(EXTRA_GO_HOME, true)) { + backToHome(false) + } else { + this@EopatchActivity.finish() + } + }) } - PatchStep.COMPLETE -> backToHome(true) - PatchStep.FINISH -> { + + PatchStep.COMPLETE -> backToHome(true) + + PatchStep.FINISH -> { if (!intent.getBooleanExtra(EXTRA_START_FROM_MENU, false) - || intent.getBooleanExtra(EXTRA_GO_HOME, true)) { + || intent.getBooleanExtra(EXTRA_GO_HOME, true) + ) { backToHome(false) } else { this@EopatchActivity.finish() } } - PatchStep.BACK_TO_HOME -> backToHome(false) - PatchStep.CANCEL -> this@EopatchActivity.finish() - else -> Unit + + PatchStep.BACK_TO_HOME -> backToHome(false) + PatchStep.CANCEL -> this@EopatchActivity.finish() + else -> Unit } - }) + } } } } @@ -129,14 +135,12 @@ class EopatchActivity : EoBaseActivity() { } } - UIEventTypeHandler.observe(this@EopatchActivity, Observer { evt -> + eventHandler.observe(this@EopatchActivity) { evt -> when (evt.peekContent()) { EventType.SHOW_PATCH_COMM_DIALOG -> { if (mProgressDialog == null) { - mProgressDialog = ProgressDialog(this@EopatchActivity).apply { - setMessage(getString(evt.value as Int)) + mProgressDialog = ProgressDialogHelper.get(this@EopatchActivity, getString(evt.value as Int)).apply { setCancelable(false) - setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal) } mProgressDialog?.show() } @@ -149,33 +153,33 @@ class EopatchActivity : EoBaseActivity() { EventType.SHOW_PATCH_COMM_ERROR_DIALOG -> { dismissRetryDialog() - if (patchStep.value?.isSafeDeactivation?:false || connectionTryCnt >= 2) { - val cancelLabel = commCheckCancelLabel.value?:getString(R.string.cancel) + if (patchStep.value?.isSafeDeactivation == true || connectionTryCnt >= 2) { + val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel) val message = "${getString(R.string.patch_comm_error_during_discard_desc_2)}\n${getString(R.string.patch_communication_check_helper_2)}" mPatchCommCheckDialog = AlertDialogHelper.Builder(this@EopatchActivity) .setTitle(R.string.patch_communication_failed) .setMessage(message) .setCancelable(false) - .setPositiveButton(R.string.discard, { dialog, which -> + .setPositiveButton(R.string.discard) { _, _ -> discardPatch() - }) - .setNegativeButton(cancelLabel, { dialog, which -> + } + .setNegativeButton(cancelLabel) { _, _ -> cancelPatchCommCheck() - }) + } .show() - }else{ - val cancelLabel = commCheckCancelLabel.value?:getString(R.string.cancel) + } else { + val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel) val message = "${getString(R.string.patch_communication_check_helper_1)}\n${getString(R.string.patch_communication_check_helper_2)}" mPatchCommCheckDialog = AlertDialogHelper.Builder(this@EopatchActivity) .setTitle(R.string.patch_communication_failed) .setMessage(message) .setCancelable(false) - .setPositiveButton(R.string.retry, { dialog, which -> + .setPositiveButton(R.string.retry) { _, _ -> retryCheckCommunication() - }) - .setNegativeButton(cancelLabel, { dialog, which -> + } + .setNegativeButton(cancelLabel) { _, _ -> cancelPatchCommCheck() - }) + } .show() } } @@ -185,31 +189,34 @@ class EopatchActivity : EoBaseActivity() { AlertDialogHelper.Builder(this@EopatchActivity) .setTitle(R.string.patch_communication_succeed) .setMessage(R.string.patch_communication_succeed_message) - .setPositiveButton(R.string.confirm, { dialog, which -> + .setPositiveButton(R.string.confirm) { _, _ -> dismissPatchCommCheckDialogInternal(true) - }).show() + }.show() } EventType.SHOW_CHANGE_PATCH_DIALOG -> { AlertDialogHelper.Builder(this@EopatchActivity).apply { setTitle(R.string.string_discard_patch) - setMessage(when { - patchState.isBolusActive && patchState.isTempBasalActive -> { - R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc - } - patchState.isBolusActive -> R.string.patch_change_confirm_bolus_is_active_desc - patchState.isTempBasalActive -> R.string.patch_change_confirm_temp_basal_is_active_desc - else -> R.string.patch_change_confirm_desc - }) - setPositiveButton(R.string.string_discard_patch, { dialog, which -> - deactivatePatch() - }) - setNegativeButton(R.string.cancel, { dialog, which -> + setMessage( + when { + patchState.isBolusActive && patchState.isTempBasalActive -> { + R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc + } - }) + patchState.isBolusActive -> R.string.patch_change_confirm_bolus_is_active_desc + patchState.isTempBasalActive -> R.string.patch_change_confirm_temp_basal_is_active_desc + else -> R.string.patch_change_confirm_desc + } + ) + setPositiveButton(R.string.string_discard_patch) { _, _ -> + deactivatePatch() + } + setNegativeButton(R.string.cancel) { _, _ -> + + } }.show() } - EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish() + // EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish() EventType.SHOW_DISCARD_DIALOG -> { AlertDialogHelper.Builder(this@EopatchActivity).apply { setTitle(R.string.string_discard_patch) @@ -218,7 +225,7 @@ class EopatchActivity : EoBaseActivity() { } else { setMessage(R.string.string_are_you_sure_to_discard_current_patch) } - setPositiveButton(R.string.discard, { dialog, which -> + setPositiveButton(R.string.discard) { _, _ -> deactivate(true) { dismissPatchCommCheckDialogInternal() @@ -228,17 +235,18 @@ class EopatchActivity : EoBaseActivity() { this@EopatchActivity.finish() } } - }) - setNegativeButton(R.string.cancel, { dialog, which -> + } + setNegativeButton(R.string.cancel) { _, _ -> dismissProgressDialog() updateIncompletePatchActivationReminder() - }) + } }.show() } - else -> Unit + + else -> Unit } - }) + } } } @@ -302,9 +310,8 @@ class EopatchActivity : EoBaseActivity() { const val EXTRA_START_WITH_COMM_CHECK = "EXTRA_START_WITH_COMM_CHECK" const val EXTRA_GO_HOME = "EXTRA_GO_HOME" const val EXTRA_FORCE_DISCARD = "EXTRA_FORCE_DISCARD" - @JvmField val PATCH_INITIAL_VOLTAGE_MIN = 2700 - @JvmField val NORMAL_TEMPERATURE_MIN = 4 - @JvmField val NORMAL_TEMPERATURE_MAX = 45 + const val NORMAL_TEMPERATURE_MIN = 4 + const val NORMAL_TEMPERATURE_MAX = 45 @JvmStatic @JvmOverloads @@ -316,11 +323,6 @@ class EopatchActivity : EoBaseActivity() { } } - @JvmStatic - fun createIntentForActivatePatch(context: Context): Intent { - return createIntent(context, PatchStep.WAKE_UP, false) - } - @JvmStatic fun createIntentForChangePatch(context: Context): Intent { return createIntent(context, PatchStep.SAFE_DEACTIVATION, false) @@ -335,7 +337,7 @@ class EopatchActivity : EoBaseActivity() { } @JvmStatic - fun createIntentForCanularInsertionError(context: Context): Intent { + fun createIntentForCannulaInsertionError(context: Context): Intent { return createIntent(context, PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR, false) } @@ -383,7 +385,7 @@ class EopatchActivity : EoBaseActivity() { } } - fun setupViewFragment(baseFragment: EoBaseFragment<*>) { + private fun setupViewFragment(baseFragment: EoBaseFragment<*>) { replaceFragmentInActivity(baseFragment, R.id.framelayout_fragment, false) } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchConnectNewFragment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchConnectNewFragment.kt index 42c58e22ee..35115640d5 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchConnectNewFragment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchConnectNewFragment.kt @@ -23,16 +23,16 @@ class EopatchConnectNewFragment : EoBaseFragment checkCommunication ({ retryScan() }, { moveStep(PatchStep.WAKE_UP) }) - GET_PATCH_INFO_FAILED -> checkCommunication ({ getPatchInfo() }, { moveStep(PatchStep.WAKE_UP) }) - SELF_TEST_FAILED -> checkCommunication ({ selfTest() }, { moveStep(PatchStep.WAKE_UP) }) - ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show() - else -> Unit + BONDING_FAILED -> checkCommunication({ retryScan() }, { moveStep(PatchStep.WAKE_UP) }) + GET_PATCH_INFO_FAILED -> checkCommunication({ getPatchInfo() }, { moveStep(PatchStep.WAKE_UP) }) + SELF_TEST_FAILED -> checkCommunication({ selfTest() }, { moveStep(PatchStep.WAKE_UP) }) + ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show() + else -> Unit } - }) + } startScan() } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchOverviewFragment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchOverviewFragment.kt index 6ce1ba6f71..2346f206be 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchOverviewFragment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchOverviewFragment.kt @@ -1,28 +1,23 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui import android.app.AlertDialog -import android.app.ProgressDialog -import android.content.Context -import android.content.DialogInterface import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast -import androidx.lifecycle.Observer +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.StringRes import androidx.lifecycle.ViewModelProvider import dagger.android.support.DaggerAppCompatActivity import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.eopatch.R -import info.nightscout.androidaps.plugins.pump.eopatch.EoPatchRxBus import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchStep import info.nightscout.androidaps.plugins.pump.eopatch.code.EventType import info.nightscout.androidaps.plugins.pump.eopatch.databinding.FragmentEopatchOverviewBinding -import info.nightscout.androidaps.plugins.pump.eopatch.extension.fillExtras -import info.nightscout.androidaps.plugins.pump.eopatch.extension.subscribeDefault import info.nightscout.androidaps.plugins.pump.eopatch.extension.takeOne import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchOverviewViewModel -import info.nightscout.androidaps.plugins.pump.eopatch.vo.ActivityResultEvent import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import io.reactivex.disposables.CompositeDisposable @@ -32,8 +27,11 @@ class EopatchOverviewFragment: EoBaseFragment() @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsLogger: AAPSLogger + private lateinit var resultLauncherForResume: ActivityResultLauncher + private lateinit var resultLauncherForPause: ActivityResultLauncher private var disposable: CompositeDisposable = CompositeDisposable() + private var pauseDuration = 0.5f override fun getLayoutId(): Int = R.layout.fragment_eopatch_overview @@ -48,21 +46,42 @@ class EopatchOverviewFragment: EoBaseFragment() binding.apply { viewmodel = ViewModelProvider(this@EopatchOverviewFragment, viewModelFactory).get(EopatchOverviewViewModel::class.java) viewmodel?.apply { - UIEventTypeHandler.observe(viewLifecycleOwner, Observer { evt -> - when(evt.peekContent()){ - EventType.ACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentFromMenu(it, PatchStep.WAKE_UP)) } - EventType.DEACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentForChangePatch(it)) } - EventType.SUSPEND_CLICKED -> suspend() + eventHandler.observe(viewLifecycleOwner) { evt -> + when (evt.peekContent()) { + EventType.ACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentFromMenu(this, PatchStep.WAKE_UP)) } + EventType.DEACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentForChangePatch(this)) } + EventType.SUSPEND_CLICKED -> suspend() EventType.RESUME_CLICKED -> resume() - EventType.INVALID_BASAL_RATE -> Toast.makeText(activity, R.string.unsupported_basal_rate, Toast.LENGTH_SHORT).show() - EventType.PROFILE_NOT_SET -> Toast.makeText(activity, R.string.no_profile_selected, Toast.LENGTH_SHORT).show() + EventType.INVALID_BASAL_RATE -> showToast(R.string.unsupported_basal_rate) + EventType.PROFILE_NOT_SET -> showToast(R.string.no_profile_selected) + EventType.PAUSE_BASAL_FAILED -> showToast(R.string.string_pause_failed) + EventType.RESUME_BASAL_FAILED -> showToast(R.string.string_resume_failed) else -> Unit } - }) + } + + resultLauncherForResume = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ + when (it.resultCode) { + DaggerAppCompatActivity.RESULT_OK -> resumeBasal() + DaggerAppCompatActivity.RESULT_CANCELED -> showToast(R.string.string_resume_failed) + } + } + + resultLauncherForPause = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ + when (it.resultCode) { + DaggerAppCompatActivity.RESULT_OK -> { + pauseBasal(pauseDuration) + pauseDuration = 0.5f + } + DaggerAppCompatActivity.RESULT_CANCELED -> showToast(R.string.string_pause_failed) + } + } } } + } - + private fun showToast(@StringRes strId: Int){ + Toast.makeText(requireContext(), strId, Toast.LENGTH_SHORT).show() } private fun suspend() { @@ -73,12 +92,12 @@ class EopatchOverviewFragment: EoBaseFragment() val dialog = builder.setTitle(R.string.string_suspend) .setMessage(msg) - .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> + .setPositiveButton(R.string.confirm) { _, _ -> openPauseTimePicker() - }) - .setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which -> + } + .setNegativeButton(R.string.cancel) { _, _ -> - }).create() + }.create() dialog.show() } } @@ -90,18 +109,16 @@ class EopatchOverviewFragment: EoBaseFragment() val builder = AlertDialog.Builder(it) val dialog = builder.setTitle(R.string.string_resume_insulin_delivery_title) .setMessage(R.string.string_resume_insulin_delivery_message) - .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> - if(isPatchConnected) { + .setPositiveButton(R.string.confirm) { _, _ -> + if (isPatchConnected) { resumeBasal() - }else{ - checkCommunication({ - resumeBasal() - }) + } else { + resultLauncherForResume.launch(EopatchActivity.createIntentForCheckConnection(requireContext(), true)) } - }) - .setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which -> + } + .setNegativeButton(R.string.cancel) { _, _ -> - }).create() + }.create() dialog.show() } } @@ -114,21 +131,20 @@ class EopatchOverviewFragment: EoBaseFragment() val listArr = requireContext().resources.getStringArray(R.array.suspend_duration_array) var select = 0 val dialog = builder.setTitle(R.string.string_suspend_time_insulin_delivery_title) - .setSingleChoiceItems(listArr, 0, DialogInterface.OnClickListener { dialog, which -> + .setSingleChoiceItems(listArr, 0) { _, which -> select = which - }) - .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> + } + .setPositiveButton(R.string.confirm) { _, _ -> if (isPatchConnected) { pauseBasal((select + 1) * 0.5f) } else { - checkCommunication({ - pauseBasal((select + 1) * 0.5f) - }) + pauseDuration = (select + 1) * 0.5f + resultLauncherForPause.launch(EopatchActivity.createIntentForCheckConnection(requireContext(), true)) } - }) - .setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which -> + } + .setNegativeButton(R.string.cancel) { _, _ -> - }).create() + }.create() dialog.show() } } @@ -158,26 +174,4 @@ class EopatchOverviewFragment: EoBaseFragment() } return "" } - - override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair) { - val intent = action(requireContext()) - if(params.isNotEmpty()) intent.fillExtras(params) - startActivityForResult(intent, requestCode) - } - - override fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)?, onDiscard: (() -> Unit)?, goHomeAfterDiscard: Boolean) { - EoPatchRxBus.listen(ActivityResultEvent::class.java) - .doOnSubscribe { startActivityForResult({ EopatchActivity.createIntentForCheckConnection(this, goHomeAfterDiscard) }, 10001) } - .observeOn(aapsSchedulers.main) - .subscribeDefault(aapsLogger) { - if (it.requestCode == 10001) { - when (it.resultCode) { - DaggerAppCompatActivity.RESULT_OK -> onSuccess.invoke() - DaggerAppCompatActivity.RESULT_CANCELED -> onCancel?.invoke() - EopatchActivity.RESULT_DISCARDED -> onDiscard?.invoke() - } - } - }.addTo() - } - } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchRotateKnobFragment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchRotateKnobFragment.kt index cbeb1bc935..e1e4d7ee21 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchRotateKnobFragment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchRotateKnobFragment.kt @@ -39,14 +39,14 @@ class EopatchRotateKnobFragment : EoBaseFragment { checkCommunication({ startNeedleSensing() }) } - else -> Unit + else -> Unit } - }) + } } } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchSafetyCheckFragment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchSafetyCheckFragment.kt index c4858f90af..6ac1d9246e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchSafetyCheckFragment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/EopatchSafetyCheckFragment.kt @@ -24,12 +24,12 @@ class EopatchSafetyCheckFragment : EoBaseFragment checkCommunication ({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) }) - else -> Unit + SAFETY_CHECK_FAILED -> checkCommunication({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) }) + else -> Unit } - }) + } startSafetyCheck() } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ActivationNotCompleteDialog.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ActivationNotCompleteDialog.kt index e0c4bd0223..78b70ccd4c 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ActivationNotCompleteDialog.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ActivationNotCompleteDialog.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager import info.nightscout.androidaps.plugins.pump.eopatch.databinding.DialogCommonBinding import info.nightscout.androidaps.plugins.pump.eopatch.ui.DialogHelperActivity import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity -import io.reactivex.disposables.Disposable import javax.inject.Inject class ActivationNotCompleteDialog : DaggerDialogFragment() { @@ -24,7 +23,6 @@ class ActivationNotCompleteDialog : DaggerDialogFragment() { var title: String = "" private var _binding: DialogCommonBinding? = null - private var disposable: Disposable? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/AlarmDialog.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/AlarmDialog.kt index 3507ed48b6..23e431fd5e 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/AlarmDialog.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/AlarmDialog.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs import android.os.Build import android.os.Bundle import android.os.Handler +import android.os.HandlerThread import android.view.* import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.core.R @@ -32,13 +33,13 @@ class AlarmDialog : DaggerDialogFragment() { var helperActivity: AlarmHelperActivity? = null var alarmCode: AlarmCode? = null - var code: String = "" + var code: String? = null var status: String = "" var title: String = "" var sound: Int = 0 private lateinit var mAlarmProcess: IAlarmProcess - private var loopHandler = Handler() + private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) private var _binding: DialogAlarmBinding? = null private var disposable: Disposable? = null @@ -107,7 +108,7 @@ class AlarmDialog : DaggerDialogFragment() { aapsLogger.debug("USER ENTRY: Error dialog mute 5 min button pressed") stopAlarm() isMute = true - loopHandler.postDelayed(this::startAlarm, T.mins(5).msecs()) + handler.postDelayed(this::startAlarm, T.mins(5).msecs()) } startAlarm() @@ -150,7 +151,7 @@ class AlarmDialog : DaggerDialogFragment() { override fun dismiss() { super.dismissAllowingStateLoss() - loopHandler.removeCallbacksAndMessages(null) + handler.removeCallbacksAndMessages(null) helperActivity?.finish() } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/CommonDialog.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/CommonDialog.kt index 5becbcf5f2..5e0ab3d1d2 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/CommonDialog.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/CommonDialog.kt @@ -28,12 +28,12 @@ class CommonDialog : DaggerDialogFragment() { if(title != 0) setTitle(title) if(message != 0) setMessage(message) setPositiveButton(positiveBtn, - positiveListener?:DialogInterface.OnClickListener { dialog, which -> + positiveListener?:DialogInterface.OnClickListener { _, _ -> dismiss() }) if(negativeBtn != 0) { setNegativeButton(negativeBtn, - negativeListener ?: DialogInterface.OnClickListener { dialog, which -> + negativeListener ?: DialogInterface.OnClickListener { _, _ -> dismiss() }) } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ProgressDialogHelper.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ProgressDialogHelper.kt new file mode 100644 index 0000000000..c79d450a0b --- /dev/null +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/dialogs/ProgressDialogHelper.kt @@ -0,0 +1,61 @@ +package info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs + +import android.content.Context +import android.graphics.Color +import android.view.Gravity +import android.view.ViewGroup +import android.view.WindowManager +import android.widget.LinearLayout +import android.widget.ProgressBar +import android.widget.TextView +import androidx.appcompat.app.AlertDialog + +class ProgressDialogHelper { + companion object { + fun get(context:Context, message:String): AlertDialog { + val llPadding = 30 + val linearLayout = LinearLayout(context) + linearLayout.orientation = LinearLayout.HORIZONTAL + linearLayout.setPadding(llPadding, llPadding, llPadding, llPadding) + linearLayout.gravity = Gravity.CENTER + var llParam = LinearLayout.LayoutParams( + LinearLayout.LayoutParams.WRAP_CONTENT, + LinearLayout.LayoutParams.WRAP_CONTENT) + llParam.gravity = Gravity.CENTER + linearLayout.layoutParams = llParam + + val progressBar = ProgressBar(context) + progressBar.isIndeterminate = true + progressBar.setPadding(0, 0, llPadding, 0) + progressBar.layoutParams = llParam + + llParam = LinearLayout.LayoutParams( + ViewGroup.LayoutParams.WRAP_CONTENT, + ViewGroup.LayoutParams.WRAP_CONTENT) + llParam.gravity = Gravity.CENTER + val tvText = TextView(context) + tvText.text = message + // tvText.setTextColor(Color.parseColor("#000000")) + tvText.textSize = 20.toFloat() + tvText.layoutParams = llParam + + linearLayout.addView(progressBar) + linearLayout.addView(tvText) + + val builder = AlertDialog.Builder(context) + builder.setCancelable(true) + builder.setView(linearLayout) + + val dialog = builder.create() + val window = dialog.window + if (window != null) { + val layoutParams = WindowManager.LayoutParams() + layoutParams.copyFrom(dialog.window?.attributes) + layoutParams.width = LinearLayout.LayoutParams.WRAP_CONTENT + layoutParams.height = LinearLayout.LayoutParams.WRAP_CONTENT + dialog.window?.attributes = layoutParams + } + return dialog + } + } +} \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/event/SingleLiveEvent.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/event/SingleLiveEvent.kt index 17a1d965f3..499cc34305 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/event/SingleLiveEvent.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/event/SingleLiveEvent.kt @@ -4,17 +4,16 @@ import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import androidx.annotation.MainThread -import android.util.Log import java.util.concurrent.atomic.AtomicBoolean open class SingleLiveEvent : MutableLiveData() { private val mPending = AtomicBoolean(false) override fun observe(owner: LifecycleOwner, observer: Observer) { - super.observe(owner, Observer { t -> + super.observe(owner) { t -> if (mPending.compareAndSet(true, false)) { observer.onChanged(t) } - }) + } } @MainThread diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/receiver/RxBroadcastReceiver.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/receiver/RxBroadcastReceiver.kt index 5b6733ed4c..680e1c0483 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/receiver/RxBroadcastReceiver.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/receiver/RxBroadcastReceiver.kt @@ -6,10 +6,8 @@ import android.content.Intent import android.content.IntentFilter import androidx.annotation.CheckResult import io.reactivex.android.MainThreadDisposable -import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver.BroadcastReceiverObservable import io.reactivex.Observable import io.reactivex.Observer -import java.lang.AssertionError class RxBroadcastReceiver private constructor() { internal class BroadcastReceiverObservable : Observable { @@ -31,7 +29,7 @@ class RxBroadcastReceiver private constructor() { } override fun subscribeActual(observer: Observer) { - val listener: Listener = Listener(context, observer) + val listener = Listener(context, observer) observer.onSubscribe(listener) context.registerReceiver(listener.receiver, intentFilter) } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EoBaseViewModel.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EoBaseViewModel.kt index ff417e8b02..223e9ebbe5 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EoBaseViewModel.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EoBaseViewModel.kt @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel -import android.view.MotionEvent -import android.view.View -import androidx.annotation.Keep import androidx.lifecycle.ViewModel import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator import io.reactivex.disposables.CompositeDisposable @@ -26,10 +23,6 @@ abstract class EoBaseViewModel : ViewModel() { super.onCleared() } - fun blockTouchEvent(view: View, motionEvent: MotionEvent): Boolean { - return true - } - fun back() = navigator?.back() fun finish() = navigator?.finish() diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchOverviewViewModel.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchOverviewViewModel.kt index 7dd6d2be6a..c7252158fb 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchOverviewViewModel.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchOverviewViewModel.kt @@ -21,6 +21,7 @@ import io.reactivex.Observable import io.reactivex.disposables.Disposable import java.util.concurrent.TimeUnit import javax.inject.Inject +import kotlin.math.max import kotlin.math.roundToInt class EopatchOverviewViewModel @Inject constructor( @@ -31,7 +32,7 @@ class EopatchOverviewViewModel @Inject constructor( private val aapsSchedulers: AapsSchedulers ) : EoBaseViewModel() { private val _eventHandler = SingleLiveEvent>() - val UIEventTypeHandler : LiveData> + val eventHandler : LiveData> get() = _eventHandler private val _patchConfig = SingleLiveEvent() @@ -58,6 +59,10 @@ class EopatchOverviewViewModel @Inject constructor( val status : LiveData get() = _status + private val _pauseBtnStr = SingleLiveEvent() + val pauseBtnStr : LiveData + get() = _pauseBtnStr + private val _alarms = SingleLiveEvent() val alarms : LiveData get() = _alarms @@ -128,18 +133,18 @@ class EopatchOverviewViewModel @Inject constructor( private fun updatePatchStatus(){ if(patchManager.isActivated){ - var finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis() - var remainTimeMillis = Math.max(finishTimeMillis - System.currentTimeMillis(), 0L) + val finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis() + val remainTimeMillis = max(finishTimeMillis - System.currentTimeMillis(), 0L) val h = TimeUnit.MILLISECONDS.toHours(remainTimeMillis) val m = TimeUnit.MILLISECONDS.toMinutes(remainTimeMillis - TimeUnit.HOURS.toMillis(h)) _status.value = if(patchManager.patchState.isNormalBasalPaused) - "${rh.gs(R.string.string_suspended)}\n" + - "${rh.gs(R.string.string_temp_basal_remained_hhmm, h.toString(), m.toString())}" + "${rh.gs(R.string.string_suspended)}\n${rh.gs(R.string.string_temp_basal_remained_hhmm, h.toString(), m.toString())}" else rh.gs(R.string.string_running) }else{ _status.value = "" } + _pauseBtnStr.value = if(patchManager.patchState.isNormalBasalPaused) rh.gs(R.string.string_resume) else rh.gs(R.string.string_suspend) } private fun updateBasalInfo(){ @@ -166,7 +171,7 @@ class EopatchOverviewViewModel @Inject constructor( patchManager.preferenceManager.getNormalBasalManager().setNormalBasal(profile) patchManager.preferenceManager.flushNormalBasalManager() - _eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED)) + _eventHandler.postValue(UIEvent(EventType.ACTIVATION_CLICKED)) }else if(profile != null && profile.getBasal() < 0.05){ _eventHandler.postValue(UIEvent(EventType.INVALID_BASAL_RATE)) }else{ @@ -175,7 +180,7 @@ class EopatchOverviewViewModel @Inject constructor( } fun onClickDeactivation(){ - _eventHandler.postValue(UIEvent(EventType.DEACTIVTION_CLICKED)) + _eventHandler.postValue(UIEvent(EventType.DEACTIVATION_CLICKED)) } fun onClickSuspendOrResume(){ @@ -190,8 +195,8 @@ class EopatchOverviewViewModel @Inject constructor( patchManager.pauseBasal(pauseDurationHour) .subscribeOn(aapsSchedulers.io) .observeOn(aapsSchedulers.main) - .subscribe({ - if (it.isSuccess) { + .subscribe({ response -> + if (response.isSuccess) { navigator?.toast(R.string.string_suspended_insulin_delivery_message) startPeriodicallyUpdate() } else { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchViewModel.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchViewModel.kt index fc49c90f6a..fb70d95f57 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchViewModel.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/EopatchViewModel.kt @@ -25,7 +25,9 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator import info.nightscout.androidaps.plugins.pump.eopatch.ui.event.SingleLiveEvent import info.nightscout.androidaps.plugins.pump.eopatch.ui.event.UIEvent import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchViewModel.SetupStep.* +import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchConfig import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchLifecycleEvent +import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger @@ -55,24 +57,19 @@ class EopatchViewModel @Inject constructor( var forceDiscard = false var connectionTryCnt = 0 - val patchConfig = patchManager.patchConfig - - val patchState = patchManager.patchState + val patchConfig: PatchConfig = patchManager.patchConfig + val patchState: PatchState = patchManager.patchState private val _isActivated = MutableLiveData(patchConfig.isActivated) private val _eventHandler = SingleLiveEvent>() - val UIEventTypeHandler : LiveData> + val eventHandler : LiveData> get() = _eventHandler - fun onClickActivation(){ - _eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED)) - } - val patchStep = MutableLiveData() - val isActivated = MutableLiveData(patchManager.isActivated) - val isBolusActive = patchManager.getPatchState().isBolusActive + val isActivated = MutableLiveData(patchManager.isActivated) + val isBolusActive = patchManager.patchState.isBolusActive val isConnected = patchManager.patchConnectionState.isConnected val patchRemainedInsulin: LiveData @@ -86,7 +83,7 @@ class EopatchViewModel @Inject constructor( }, 0) } - private val _patchExpirationTimestamp = MutableLiveData(patchManager.patchExpiredTime) + private val _patchExpirationTimestamp = MutableLiveData(patchManager.patchExpiredTime) val patchRemainedDays: LiveData get() = Transformations.map(_patchExpirationTimestamp) { @@ -106,19 +103,11 @@ class EopatchViewModel @Inject constructor( val safetyCheckProgress: LiveData get() = _safetyCheckProgress - private val _patchExpirationReminderTime = MutableLiveData() - val patchExpirationReminderTime: LiveData - get() = _patchExpirationReminderTime - - private val _patchExpirationTime = MutableLiveData() - val patchExpirationTime: LiveData - get() = _patchExpirationTime - private val _isCommCheckFailed = MutableLiveData(false) - val isCommCheckFailed: LiveData + private val isCommCheckFailed: LiveData get() = _isCommCheckFailed - val isBonded: Boolean + private val isBonded: Boolean get() = !patchConfig.lifecycleEvent.isShutdown val commCheckCancelLabel: LiveData @@ -129,15 +118,11 @@ class EopatchViewModel @Inject constructor( } PatchStep.SAFE_DEACTIVATION -> R.string.patch_forced_discard else -> R.string.cancel - }) ?: "" + }) } val programEnabledMessage: String - // get() = """'기초1' program has been enabled.""" - get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1") ?: "" - - val patchStepIsSafeDeactivation: Boolean - get() = patchStep.value?.isSafeDeactivation ?: false + get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1") private val _isDiscardedWithNotConn = MutableLiveData(false) val isDiscardedWithNotConn: LiveData @@ -152,8 +137,6 @@ class EopatchViewModel @Inject constructor( private val initPatchStepIsCheckConnection: Boolean get() = mInitPatchStep?.isCheckConnection ?: false - // private var mProgressDialog: PatchProgressDialog? = null - private var mCommCheckDisposable: Disposable? = null private var mOnCommCheckSuccessListener: (() -> Unit)? = null @@ -174,8 +157,6 @@ class EopatchViewModel @Inject constructor( private val mB012UpdateSubject = PublishSubject.create() - // private var mCurrentTextDialog: TextDialog? = null - init { mB012UpdateDisposable = mB012UpdateSubject.hide() .throttleFirst(500, TimeUnit.MILLISECONDS) @@ -222,20 +203,7 @@ class EopatchViewModel @Inject constructor( @Synchronized fun checkCommunication(onSuccessListener: () -> Unit, onCancelListener: (() -> Unit)? = null, - onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false, doIntercept: Boolean = false) { - // mPatchCommCheckDialog?.let { - // if (doIntercept) { - // mOnCommCheckSuccessListener = onSuccessListener - // mOnCommCheckCancelListener = onCancelListener - // mOnCommCheckDiscardListener = onDiscardListener - // - // if (_isCommCheckFailed.value == true) { - // retryCheckCommunication() - // } - // } - // - // } - + onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false) { if (doPreCheck && patchManager.patchConnectionState.isConnected) { onSuccessListener.invoke() return @@ -286,7 +254,7 @@ class EopatchViewModel @Inject constructor( } } - fun showPatchCommCheckDialog(defaultFailedCondition: Boolean = false, @StringRes title: Int = R.string.string_connecting) { + private fun showPatchCommCheckDialog(defaultFailedCondition: Boolean = false, @StringRes title: Int = R.string.string_connecting) { _isCommCheckFailed.postValue(defaultFailedCondition) _eventHandler.postValue(UIEvent(EventType.SHOW_PATCH_COMM_DIALOG).apply { value = title @@ -307,7 +275,7 @@ class EopatchViewModel @Inject constructor( } private fun dismissPatchCommCheckDialog() { - if (_isCommCheckFailed.value == false) { + if (isCommCheckFailed.value == false) { if (isBonded) { _eventHandler.postValue(UIEvent(EventType.SHOW_BONDED_DIALOG)) } else { @@ -554,7 +522,7 @@ class EopatchViewModel @Inject constructor( } } - fun convertToPatchStep(lifecycle: PatchLifecycle) = when (lifecycle) { + private fun convertToPatchStep(lifecycle: PatchLifecycle) = when (lifecycle) { PatchLifecycle.SHUTDOWN -> patchConfig.isDeactivated.takeOne( PatchStep.WAKE_UP, PatchStep.SAFE_DEACTIVATION) PatchLifecycle.BONDED -> PatchStep.CONNECT_NEW @@ -567,13 +535,6 @@ class EopatchViewModel @Inject constructor( } private fun onClear() { - // _patchExpirationTime.value = null - // _rotateKnobRawRes.value = null - // _patchExpirationReminderTime.value = null - // _title.value = null - // mProgressDialog = null - // mPatchCommCheckDialog = null - // mCurrentTextDialog = null mOnCommCheckSuccessListener = null mOnCommCheckCancelListener = null mOnCommCheckDiscardListener = null @@ -691,7 +652,7 @@ class EopatchViewModel @Inject constructor( .doOnSubscribe { updateSetupStep(BONDING_STARTED) } .filter { result -> result } .toSingle() // 실패시 에러 반환. - .doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createbonded()) } + .doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createBonded()) } .doOnError { if (it is TimeoutException) { moveStep(PatchStep.WAKE_UP) diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/ViewModelFactory.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/ViewModelFactory.kt index eb155e423a..0a351591e1 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/ViewModelFactory.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/ui/viewmodel/ViewModelFactory.kt @@ -30,6 +30,7 @@ class ViewModelFactory @Inject constructor(private val creators: Map { +class Alarms: IPreference { @Transient private val subject: BehaviorSubject = BehaviorSubject.create() @@ -24,7 +24,7 @@ class Alarms(): IPreference { var registered = HashMap() - var occured = HashMap() + var occurred = HashMap() init { initObject() @@ -35,52 +35,52 @@ class Alarms(): IPreference { fun clear(){ registered.clear() - occured.clear() + occurred.clear() } fun update(other: Alarms) { registered = other.registered - occured = other.occured + occurred = other.occurred } - fun register(alarmcode: AlarmCode, triggerAfter: Long) { + fun register(alarmCode: AlarmCode, triggerAfter: Long) { val item = AlarmItem().apply { - alarmCode = alarmcode + this.alarmCode = alarmCode createTimestamp = System.currentTimeMillis() triggerTimeMilli = createTimestamp + triggerAfter } - if (isRegistered(alarmcode)){ - registered.remove(alarmcode) + if (isRegistered(alarmCode)){ + registered.remove(alarmCode) } - registered.put(alarmcode, item) + registered.put(alarmCode, item) } - fun unregister(alarmcode: AlarmCode) { - if (isRegistered(alarmcode)){ - registered.remove(alarmcode) + fun unregister(alarmCode: AlarmCode) { + if (isRegistered(alarmCode)){ + registered.remove(alarmCode) } } - fun occured(alarmcode: AlarmCode) { - val item: AlarmItem? = registered.get(alarmcode) - if (!isOccuring(alarmcode) && item != null) - occured.put(alarmcode, item) - if (isRegistered(alarmcode)) - registered.remove(alarmcode) + fun occurred(alarmCode: AlarmCode) { + val item: AlarmItem? = registered.get(alarmCode) + if (!isOccurring(alarmCode) && item != null) + occurred.put(alarmCode, item) + if (isRegistered(alarmCode)) + registered.remove(alarmCode) } - fun handle(alarmcode: AlarmCode) { - if (isOccuring(alarmcode)) - occured.remove(alarmcode) + fun handle(alarmCode: AlarmCode) { + if (isOccurring(alarmCode)) + occurred.remove(alarmCode) } - fun isRegistered(alarmcode: AlarmCode): Boolean{ - return registered.containsKey(alarmcode) + private fun isRegistered(alarmCode: AlarmCode): Boolean{ + return registered.containsKey(alarmCode) } - fun isOccuring(alarmcode: AlarmCode): Boolean{ - return occured.containsKey(alarmcode) + fun isOccurring(alarmCode: AlarmCode): Boolean{ + return occurred.containsKey(alarmCode) } override fun observe(): Observable { @@ -94,15 +94,6 @@ class Alarms(): IPreference { } override fun toString(): String { - return "Alarms(subject=$subject, registered=${registered.keys}, occured=${occured.keys}" + return "Alarms(subject=$subject, registered=${registered.keys}, occurred=${occurred.keys}" } - - companion object { - const val NAME = "ALARMS" - @JvmStatic - fun createEmpty(): Alarms { - return Alarms() - } - } - } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BasalSegment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BasalSegment.kt index e0571ecc7a..b7125d06af 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BasalSegment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BasalSegment.kt @@ -17,11 +17,11 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl this.endMinute = end } - internal override fun duplicate(startMinute: Long, endMinute: Long): BasalSegment { + override fun duplicate(startMinute: Long, endMinute: Long): BasalSegment { return BasalSegment(startMinute, endMinute, doseUnitPerHour) } - internal override fun deep(): BasalSegment { + override fun deep(): BasalSegment { return BasalSegment(startMinute, endMinute, doseUnitPerHour) } @@ -29,8 +29,8 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl segment.doseUnitPerHour = doseUnitPerHour } - internal override fun equalValue(segment: BasalSegment): Boolean { - return segment != null && doseUnitPerHour == segment.doseUnitPerHour + override fun equalValue(segment: BasalSegment): Boolean { + return doseUnitPerHour == segment.doseUnitPerHour } companion object { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BolusCurrent.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BolusCurrent.kt index 3ddb1b66f3..905673835a 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BolusCurrent.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/BolusCurrent.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch.vo -import android.content.Context import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant import info.nightscout.androidaps.plugins.pump.eopatch.GsonHelper import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType @@ -179,16 +178,4 @@ class BolusCurrent(): IPreference { override fun toString(): String { return "BolusCurrent(nowBolus=$nowBolus, extBolus=$extBolus)" } - - companion object { - - const val NAME = "BOLUS_CURRENT" - - @JvmStatic - fun createEmpty(): BolusCurrent { - return BolusCurrent() - } - - } - } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/IPreference.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/IPreference.kt index 225da1a390..e92fc7e5c6 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/IPreference.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/IPreference.kt @@ -4,6 +4,6 @@ import info.nightscout.shared.sharedPreferences.SP import io.reactivex.Observable interface IPreference{ - open fun flush(sp: SP) - open fun observe(): Observable + fun flush(sp: SP) + fun observe(): Observable } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasal.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasal.kt index 016e98776c..17a8f9d426 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasal.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasal.kt @@ -1,12 +1,11 @@ package info.nightscout.androidaps.plugins.pump.eopatch.vo -import android.util.MutableFloat import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant import info.nightscout.androidaps.plugins.pump.eopatch.core.util.FloatAdjusters import info.nightscout.androidaps.plugins.pump.eopatch.code.BasalStatus import java.util.* import java.util.concurrent.TimeUnit -import java.util.function.BiFunction +import kotlin.math.max class NormalBasal : SegmentsEntity() { var status: BasalStatus = BasalStatus.SELECTED @@ -18,11 +17,11 @@ class NormalBasal : SegmentsEntity() { } } - var segmentIndex = SEGMENT_INDEX_DEFAULT + private var segmentIndex = SEGMENT_INDEX_DEFAULT val maxDoseUnitPerHour: Float get() { - val max = list.stream().map({ it.doseUnitPerHour }).mapToDouble({ it.toDouble() }).max().orElse(0.0).toFloat() + val max = list.stream().map { it.doseUnitPerHour }.mapToDouble { it.toDouble() }.max().orElse(0.0).toFloat() return FloatAdjusters.ROUND2_INSULIN.apply(max) } @@ -30,7 +29,7 @@ class NormalBasal : SegmentsEntity() { get() { val doseArray = FloatArray(AppConstant.SEGMENT_COUNT_MAX) - eachSegmentItem(BiFunction { index, segment -> + eachSegmentItem { index, segment -> val dose = segment.doseUnitPerHour / 2 if (index % 2 == 0) { doseArray[index] = FloatAdjusters.CEIL2_BASAL_RATE.apply(dose) @@ -38,43 +37,40 @@ class NormalBasal : SegmentsEntity() { doseArray[index] = FloatAdjusters.FLOOR2_BASAL_RATE.apply(dose) } true - }) + } return doseArray } - val doseUnitPerSegmentArrayForGraph: FloatArray + private val doseUnitPerSegmentArrayForGraph: FloatArray get() { val doseArray = FloatArray(AppConstant.SEGMENT_COUNT_MAX) - eachSegmentItem(BiFunction { index, segment -> + eachSegmentItem { index, segment -> doseArray[index] = FloatAdjusters.CEIL2_BASAL_RATE.apply(segment.doseUnitPerHour) true - }) + } return doseArray } val doseUnitPerDay: Float get() { - val total = MutableFloat(0f) - eachSegmentItem(BiFunction { index, segment -> + var total = 0f + eachSegmentItem { index, segment -> val dose = segment.doseUnitPerHour / 2 - if (index % 2 == 0) { - total.value += FloatAdjusters.CEIL2_BASAL_RATE.apply(dose) + total += if (index % 2 == 0) { + FloatAdjusters.CEIL2_BASAL_RATE.apply(dose) } else { - total.value += FloatAdjusters.FLOOR2_BASAL_RATE.apply(dose) + FloatAdjusters.FLOOR2_BASAL_RATE.apply(dose) } true - }) - return total.value + } + return total } val currentSegmentDoseUnitPerHour: Float get() = FloatAdjusters.ROUND2_INSULIN.apply(getSegmentDoseUnitPerHourByIndex(currentSegmentIndex)) - val firstSegmentDoseUnitPerHour: Float - get() = FloatAdjusters.ROUND2_INSULIN.apply(getSegmentDoseUnitPerHourByIndex(0)) - - val currentSegmentIndex: Int + private val currentSegmentIndex: Int get() { val cal = Calendar.getInstance() var idx = cal.get(Calendar.HOUR_OF_DAY) * 2 @@ -84,19 +80,6 @@ class NormalBasal : SegmentsEntity() { return idx } - val isDoseUChanged: Boolean - get() { - val currentSegmentIndex = currentSegmentIndex - if (segmentIndex != SEGMENT_INDEX_DEFAULT && segmentIndex != currentSegmentIndex) { - val beforeDoesU = getSegmentDoseUnitPerHourByIndex(segmentIndex) - val currentDoseU = getSegmentDoseUnitPerHourByIndex(currentSegmentIndex) - if (beforeDoesU != currentDoseU) { - return true - } - } - return false - } - val startTime: Long get() = getStartTime(currentSegmentIndex) @@ -113,7 +96,7 @@ class NormalBasal : SegmentsEntity() { return FloatAdjusters.ROUND2_INSULIN.apply(getSegmentDoseUnitPerHourByIndex(getSegmentIndex(time))) } - fun getSegmentDoseUnitPerHourByIndex(idx: Int): Float { + private fun getSegmentDoseUnitPerHourByIndex(idx: Int): Float { val defaultValue = 0f for (seg in list) { val startIndex = seg.startIndex @@ -142,31 +125,27 @@ class NormalBasal : SegmentsEntity() { var minutes = calendar.get(Calendar.MINUTE) var startIndex = hours * 2 + minutes / 30 - startIndex = startIndex % AppConstant.SEGMENT_COUNT_MAX + startIndex %= AppConstant.SEGMENT_COUNT_MAX hours = (hours + durationMinutes / 60).toInt() minutes = (minutes + durationMinutes % 60).toInt() var endIndex = hours * 2 + minutes / 30 - endIndex = endIndex % AppConstant.SEGMENT_COUNT_MAX + endIndex %= AppConstant.SEGMENT_COUNT_MAX val segments = doseUnitPerSegmentArrayForGraph var maxBasal = segments[startIndex] var i = startIndex while (i != endIndex + 1) { if (i >= AppConstant.SEGMENT_COUNT_MAX) { - i = i % AppConstant.SEGMENT_COUNT_MAX + i %= AppConstant.SEGMENT_COUNT_MAX } - maxBasal = Math.max(maxBasal, segments[i]) + maxBasal = max(maxBasal, segments[i]) i++ } return maxBasal } - fun isIndexChanged(): Boolean { - return (segmentIndex != SEGMENT_INDEX_DEFAULT && segmentIndex != currentSegmentIndex) - } - @Synchronized fun updateNormalBasalIndex(): Boolean { val currentSegmentIndex = currentSegmentIndex @@ -182,7 +161,7 @@ class NormalBasal : SegmentsEntity() { return false } - fun getStartTime(segmentIndex: Int): Long { + private fun getStartTime(segmentIndex: Int): Long { val curIndexTime: Long val calendar = Calendar.getInstance() calendar.set(Calendar.HOUR_OF_DAY, 0) @@ -199,9 +178,7 @@ class NormalBasal : SegmentsEntity() { } companion object { - - private val HALF_HOUR = 0.5f - private val SEGMENT_INDEX_DEFAULT = -1 + private const val SEGMENT_INDEX_DEFAULT = -1 fun create(firstSegmentDoseUnitPerHour: Float): NormalBasal { val b = NormalBasal() diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasalManager.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasalManager.kt index a562e50d38..6f52a70436 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasalManager.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/NormalBasalManager.kt @@ -10,7 +10,7 @@ import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject import java.util.concurrent.TimeUnit -class NormalBasalManager() : IPreference { +class NormalBasalManager : IPreference { @Transient private val subject: BehaviorSubject = BehaviorSubject.create() @@ -29,16 +29,15 @@ class NormalBasalManager() : IPreference { } fun isEqual(profile: Profile?): Boolean{ - if(profile == null) false + return profile?.let{ + if(it.getBasalValues().size != normalBasal.list.size) + return false - if(profile?.getBasalValues()?.size?:0 != normalBasal.list.size) false - - return profile?.let{prof -> - for(i in prof.getBasalValues().indices){ - if(TimeUnit.SECONDS.toMinutes(prof.getBasalValues()[i].timeAsSeconds.toLong()) != normalBasal.list.get(i).start){ + for(i in it.getBasalValues().indices){ + if(TimeUnit.SECONDS.toMinutes(it.getBasalValues()[i].timeAsSeconds.toLong()) != normalBasal.list.get(i).start){ return false } - if(CommonUtils.nearlyNotEqual(prof.getBasalValues()[i].value.toFloat(), normalBasal.list.get(i).doseUnitPerHour, 0.0000001f)){ + if(CommonUtils.nearlyNotEqual(it.getBasalValues()[i].value.toFloat(), normalBasal.list.get(i).doseUnitPerHour, 0.0000001f)){ return false } } @@ -52,11 +51,11 @@ class NormalBasalManager() : IPreference { val size = profile.getBasalValues().size for(idx in profile.getBasalValues().indices){ - val next_idx = if(idx == (size - 1)) 0 else idx + 1 - val st_mins = TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[idx].timeAsSeconds.toLong()) - val et_mins = if(next_idx == 0) 1440 else TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[next_idx].timeAsSeconds.toLong()) + val nextIdx = if(idx == (size - 1)) 0 else idx + 1 + val startTimeMinutes = TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[idx].timeAsSeconds.toLong()) + val endTimeMinutes = if(nextIdx == 0) 1440 else TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[nextIdx].timeAsSeconds.toLong()) - tmpNormalBasal.list.add(BasalSegment(st_mins, et_mins, profile.getBasalValues()[idx].value.toFloat())) + tmpNormalBasal.list.add(BasalSegment(startTimeMinutes, endTimeMinutes, profile.getBasalValues()[idx].value.toFloat())) } return tmpNormalBasal @@ -67,11 +66,11 @@ class NormalBasalManager() : IPreference { val size = profile.getBasalValues().size for(idx in profile.getBasalValues().indices){ - val next_idx = if(idx == (size - 1)) 0 else idx + 1 - val st_mins = TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[idx].timeAsSeconds.toLong()) - val et_mins = if(next_idx == 0) 1440 else TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[next_idx].timeAsSeconds.toLong()) + val nextIdx = if(idx == (size - 1)) 0 else idx + 1 + val startTimeMinutes = TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[idx].timeAsSeconds.toLong()) + val endTimeMinutes = if(nextIdx == 0) 1440 else TimeUnit.SECONDS.toMinutes(profile.getBasalValues()[nextIdx].timeAsSeconds.toLong()) - normalBasal.list.add(BasalSegment(st_mins, et_mins, profile.getBasalValues()[idx].value.toFloat())) + normalBasal.list.add(BasalSegment(startTimeMinutes, endTimeMinutes, profile.getBasalValues()[idx].value.toFloat())) } } @@ -96,18 +95,13 @@ class NormalBasalManager() : IPreference { } @Synchronized - fun updateBasalSelecteded(index: Int) { - normalBasal.status = BasalStatus.SELECTED - } - - @Synchronized - fun updateBasalSelecteded() { + fun updateBasalSelected() { normalBasal.status = BasalStatus.SELECTED } fun updateForDeactivation() { // deactivation 할때는 SELECTED 상태로 변경 - updateBasalSelecteded() + updateBasalSelected() } fun update(other: NormalBasalManager){ diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchConfig.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchConfig.kt index c9389e7273..27efffe120 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchConfig.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchConfig.kt @@ -54,7 +54,7 @@ class PatchConfig: IPreference { /* 패치와 API 통신으로 업데이트 값을 여기에 기록 중복 API 호출이 생기면 안되는 경우 여기에 */ // SET_LOW_RESERVOIR_TASK - var LowReservoirAlertAmount = 10 + var lowReservoirAlertAmount = 10 var patchExpireAlertTime = 4 var infoReminder = false @@ -93,7 +93,7 @@ class PatchConfig: IPreference { get() = this.lifecycleEvent.isBasalSetting val isDeactivated: Boolean - get() = hasMacAddress() == false + get() = !hasMacAddress() val isInBasalPausedTime: Boolean get() = this.basalPauseFinishTimestamp > 0 && basalPauseFinishTimestamp > System.currentTimeMillis() @@ -144,7 +144,7 @@ class PatchConfig: IPreference { this.standardBolusInjectCount = 0 this.extendedBolusInjectCount = 0 this.basalInjectCount = 0 - this.LowReservoirAlertAmount = 10 + this.lowReservoirAlertAmount = 10 this.patchExpireAlertTime = 4 this.remainedInsulin = 0f } @@ -152,7 +152,7 @@ class PatchConfig: IPreference { fun patchFirmwareVersionString(): String? { patchFirmwareVersion?.let { var count = 0 - var i: Int = 0 + var i = 0 while (i < it.length) { if (it[i] == '.') { count++ @@ -225,8 +225,6 @@ class PatchConfig: IPreference { this.lastIndex = 0 this.needSetBasalSchedule = false } - else -> { - } } } @@ -293,7 +291,7 @@ class PatchConfig: IPreference { standardBolusInjectCount = other.standardBolusInjectCount extendedBolusInjectCount = other.extendedBolusInjectCount basalInjectCount = other.basalInjectCount - LowReservoirAlertAmount = other.LowReservoirAlertAmount + lowReservoirAlertAmount = other.lowReservoirAlertAmount patchExpireAlertTime = other.patchExpireAlertTime remainedInsulin = other.remainedInsulin @@ -313,7 +311,7 @@ class PatchConfig: IPreference { override fun toString(): String { - return "PatchConfig(securityValue=${securityValue.contentToString()}, macAddress=$macAddress, lifecycleEvent=$lifecycleEvent, bolusNormalStartTimestamp=$bolusNormalStartTimestamp, bolusNormalEndTimestamp=$bolusNormalEndTimestamp, bolusNormalDoseU=$bolusNormalDoseU, bolusExStartTimestamp=$bolusExStartTimestamp, bolusExEndTimestamp=$bolusExEndTimestamp, bolusExDoseU=$bolusExDoseU, injectCount=$injectCount, bgReminderMinute=$bgReminderMinute, lastIndex=$lastIndex, lastDisconnectedTimestamp=$lastDisconnectedTimestamp, standardBolusInjectCount=$standardBolusInjectCount, extendedBolusInjectCount=$extendedBolusInjectCount, basalInjectCount=$basalInjectCount, patchFirmwareVersion=$patchFirmwareVersion, patchSerialNumber='$patchSerialNumber', patchLotNumber=$patchLotNumber, patchModelName=$patchModelName, patchWakeupTimestamp=$patchWakeupTimestamp, activatedTimestamp=$activatedTimestamp, expireDurationMilli=$expireDurationMilli, basalPauseFinishTimestamp=$basalPauseFinishTimestamp, needleInsertionTryCount=$needleInsertionTryCount, LowReservoirAlertAmount=$LowReservoirAlertAmount, patchExpireAlertTime=$patchExpireAlertTime, isEnterPrimaryScreen=$isEnterPrimaryScreen, needSetBasalSchedule=$needSetBasalSchedule, sharedKey=${sharedKey?.contentToString()}, seq15=$seq15, rotateKnobNeedleSensingError=$rotateKnobNeedleSensingError, remainedInsulin=$remainedInsulin)" + return "PatchConfig(securityValue=${securityValue.contentToString()}, macAddress=$macAddress, lifecycleEvent=$lifecycleEvent, bolusNormalStartTimestamp=$bolusNormalStartTimestamp, bolusNormalEndTimestamp=$bolusNormalEndTimestamp, bolusNormalDoseU=$bolusNormalDoseU, bolusExStartTimestamp=$bolusExStartTimestamp, bolusExEndTimestamp=$bolusExEndTimestamp, bolusExDoseU=$bolusExDoseU, injectCount=$injectCount, bgReminderMinute=$bgReminderMinute, lastIndex=$lastIndex, lastDisconnectedTimestamp=$lastDisconnectedTimestamp, standardBolusInjectCount=$standardBolusInjectCount, extendedBolusInjectCount=$extendedBolusInjectCount, basalInjectCount=$basalInjectCount, patchFirmwareVersion=$patchFirmwareVersion, patchSerialNumber='$patchSerialNumber', patchLotNumber=$patchLotNumber, patchModelName=$patchModelName, patchWakeupTimestamp=$patchWakeupTimestamp, activatedTimestamp=$activatedTimestamp, expireDurationMilli=$expireDurationMilli, basalPauseFinishTimestamp=$basalPauseFinishTimestamp, needleInsertionTryCount=$needleInsertionTryCount, LowReservoirAlertAmount=$lowReservoirAlertAmount, patchExpireAlertTime=$patchExpireAlertTime, isEnterPrimaryScreen=$isEnterPrimaryScreen, needSetBasalSchedule=$needSetBasalSchedule, sharedKey=${sharedKey?.contentToString()}, seq15=$seq15, rotateKnobNeedleSensingError=$rotateKnobNeedleSensingError, remainedInsulin=$remainedInsulin)" } override fun equals(other: Any?): Boolean { @@ -347,7 +345,7 @@ class PatchConfig: IPreference { if (expireDurationMilli != other.expireDurationMilli) return false if (basalPauseFinishTimestamp != other.basalPauseFinishTimestamp) return false if (needleInsertionTryCount != other.needleInsertionTryCount) return false - if (LowReservoirAlertAmount != other.LowReservoirAlertAmount) return false + if (lowReservoirAlertAmount != other.lowReservoirAlertAmount) return false if (patchExpireAlertTime != other.patchExpireAlertTime) return false if (isEnterPrimaryScreen != other.isEnterPrimaryScreen) return false if (needSetBasalSchedule != other.needSetBasalSchedule) return false @@ -388,7 +386,7 @@ class PatchConfig: IPreference { result = 31 * result + expireDurationMilli.hashCode() result = 31 * result + basalPauseFinishTimestamp.hashCode() result = 31 * result + needleInsertionTryCount - result = 31 * result + LowReservoirAlertAmount + result = 31 * result + lowReservoirAlertAmount result = 31 * result + patchExpireAlertTime result = 31 * result + isEnterPrimaryScreen.hashCode() result = 31 * result + needSetBasalSchedule.hashCode() diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchLifecycleEvent.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchLifecycleEvent.kt index ad095fcc61..eb0f0be6eb 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchLifecycleEvent.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchLifecycleEvent.kt @@ -1,13 +1,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.vo -import android.os.Parcel -import android.os.Parcelable import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchLifecycle import com.google.android.gms.common.internal.Preconditions -/** - * 이 객체는 Immutable객체로 사용할 것 - */ class PatchLifecycleEvent { var lifeCycle: PatchLifecycle = PatchLifecycle.SHUTDOWN @@ -64,7 +59,7 @@ class PatchLifecycleEvent { } @JvmStatic - fun createbonded(): PatchLifecycleEvent { + fun createBonded(): PatchLifecycleEvent { return PatchLifecycleEvent(PatchLifecycle.BONDED) } @@ -97,12 +92,5 @@ class PatchLifecycleEvent { fun createActivated(): PatchLifecycleEvent { return PatchLifecycleEvent(PatchLifecycle.ACTIVATED) } - - // @JvmField val CREATOR: Parcelable.Creator = object : Parcelable.Creator { - // override fun createFromParcel(source: Parcel) = TREntityUtils.createFromBundle(source.readBundle(javaClass.classLoader), PatchLifecycleEvent::class.java) - // override fun newArray(size: Int): Array = arrayOfNulls(size) - // } } - - } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchState.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchState.kt index e80dfb4f3d..b1789cdd3c 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchState.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/PatchState.kt @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.pump.eopatch.vo -import android.os.Build -import android.util.Base64 -import com.google.gson.stream.JsonWriter import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant import info.nightscout.androidaps.plugins.pump.eopatch.GsonHelper import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType @@ -11,7 +8,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.SettingKeys import info.nightscout.shared.sharedPreferences.SP import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject -import java.io.IOException import java.io.Serializable import java.text.SimpleDateFormat import java.util.* @@ -24,7 +20,7 @@ class PatchState: IPreference { @Transient private val subject: BehaviorSubject = BehaviorSubject.create() - val stateBytes: ByteArray + private val stateBytes: ByteArray var updatedTimestamp: Long = 0 constructor(): this(ByteArray(SIZE), 0) { @@ -76,32 +72,15 @@ class PatchState: IPreference { return bitwiseAnd(stateBytes[index], bit) != 0 } - /** - * 참고표 - * 0 = 0x01 - * 1 = 0x02 - * 2 = 0x04 - * 3 = 0x08 - * 4 = 0x10 - * 5 = 0x20 - * 6 = 0x40 - * 7 = 0x80 - */ private fun bitwiseAnd(value: Byte, bit: Int): Int { return value.toInt() and (1 shl bit) } - val isNeedSyncTime: Boolean - get() = getBoolean(D3, 0) val isNeedPriming: Boolean get() = getBoolean(D3, 1) val isNeedNeedleSensing: Boolean get() = getBoolean(D3, 2) - fun useEncryption(): Boolean { - return getBoolean(D3, 3) - } - val isPrimingSuccess: Boolean get() = getBoolean(D3, 6) @@ -122,7 +101,7 @@ class PatchState: IPreference { val isTempBasalAct: Boolean get() = getBoolean(D4, 5) - fun _isExtBolusInjecting(): Boolean { + fun isExtBolusInjecting(): Boolean { return getBoolean(D4, 6) } @@ -155,14 +134,6 @@ class PatchState: IPreference { return ((get(D7) + 145 - 210) * 100.0 / 90).roundToInt() } - fun bootCount(): Int { - return get(D8) - } - - fun aeCount(): Int { - return get(D11) - } - //============================================================================================== // PUMP COUNT //============================================================================================== @@ -210,21 +181,12 @@ class PatchState: IPreference { val isNormalBasalRunning: Boolean get() = isNormalBasalReg && isNormalBasalAct - /* - 템프베이젤 Active(동작) 상태 - - tempBasalReg:1, tempBasalAct:1, tempBasalDone:0 - 템프베이젤 No Active (정지) 상태 - - tempBasalReg:0, tempBasalAct:0, tempBasalDone:0 - - tempBasalReg:1, tempBasalAct:0, tempBasalDone:1 - */ val isTempBasalActive: Boolean get() = isTempBasalReg && isTempBasalAct && !isTempBasalDone /* Bolus */ - private val isRecentPatchState: Boolean - private get() = System.currentTimeMillis() - updatedTimestamp < UPDATE_CONNECTION_INTERVAL_MILLI val isBolusActive: Boolean get() = isNowBolusActive || isExtBolusActive val isNowBolusActive: Boolean @@ -254,24 +216,10 @@ class PatchState: IPreference { } } - val isExtBolusInjectionWaiting: Boolean - get() = isExtBolusActive && !_isExtBolusInjecting() - val isExtBolusInjecting: Boolean - get() = isExtBolusActive && _isExtBolusInjecting() - val isBolusNotActive: Boolean - get() = !isBolusActive - - // 0 이면 reset - val isResetAutoOffTime: Boolean - get() = stateBytes[D3].toInt() and 0x80 == 0 - private fun b(value: Boolean): String { return if (value) ON else " " } - /** - * toString 심플 버전. - */ fun t(): String { return "PatchState{" + convertHumanTimeWithStandard(currentTime()) + "}" } @@ -290,98 +238,32 @@ class PatchState: IPreference { IntStream.of(D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, D18) .forEach { i: Int -> sb.append(String.format(" %02X ", stateBytes[i])) } if (isPatchInternalSuspended) { - Arrays.asList(indent, "isPatchInternalSuspended:", ON).forEach(Consumer { str: String? -> sb.append(str) }) + listOf(indent, "isPatchInternalSuspended:", ON).forEach(Consumer { str: String? -> sb.append(str) }) } if (isNeedPriming) { - Arrays.asList(indent, "NeedPriming:", ON).forEach(Consumer { str: String? -> sb.append(str) }) + listOf(indent, "NeedPriming:", ON).forEach(Consumer { str: String? -> sb.append(str) }) } if (isNeedNeedleSensing) { - Arrays.asList(indent, "NeedNeedleSensing:", ON).forEach(Consumer { str: String? -> sb.append(str) }) + listOf(indent, "NeedNeedleSensing:", ON).forEach(Consumer { str: String? -> sb.append(str) }) } if (isNowBolusRegAct || isNowBolusDone) { - Arrays.asList( - indent, "[NowBolus] RegAct:", b(isNowBolusRegAct), " Done:", b(isNowBolusDone)) + listOf(indent, "[NowBolus] RegAct:", b(isNowBolusRegAct), " Done:", b(isNowBolusDone)) .forEach(Consumer { str: String? -> sb.append(str) }) } - if (isExtBolusRegAct || isExtBolusDone || isExtBolusTime || _isExtBolusInjecting()) { - Arrays.asList( - indent, "[ExtBolus] RegAct:", b(isExtBolusRegAct), " Done:", b(isExtBolusDone), " Time:", b(isExtBolusTime), " Injecting:", b(_isExtBolusInjecting())) + if (isExtBolusRegAct || isExtBolusDone || isExtBolusTime || isExtBolusInjecting()) { + listOf(indent, "[ExtBolus] RegAct:", b(isExtBolusRegAct), " Done:", b(isExtBolusDone), " Time:", b(isExtBolusTime), " Injecting:", b(isExtBolusInjecting())) .forEach(Consumer { str: String? -> sb.append(str) }) } if (isTempBasalReg || isTempBasalAct || isTempBasalDone) { - Arrays.asList( - indent, "[TempBasal] Reg:", b(isTempBasalReg), " Act:", b(isTempBasalAct), " Done:", b(isTempBasalDone)) + listOf(indent, "[TempBasal] Reg:", b(isTempBasalReg), " Act:", b(isTempBasalAct), " Done:", b(isTempBasalDone)) .forEach(Consumer { str: String? -> sb.append(str) }) } - Arrays.asList( - indent, "[NormalBasal] Reg:", b(isNormalBasalReg), " Act:", b(isNormalBasalAct), " Paused:", b(isNormalBasalPaused), + listOf(indent, "[NormalBasal] Reg:", b(isNormalBasalReg), " Act:", b(isNormalBasalAct), " Paused:", b(isNormalBasalPaused), indent, "remainedInsulin:", remainedInsulin(), " remainedPumpCycle:", remainedPumpCycle(), "(", remainedInsulin, ")", " battery:", battery()) .forEach(Consumer { obj: Serializable? -> sb.append(obj) }) return sb.toString() } - fun info(): String { - val sb = StringBuilder() - val format = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") - sb.append("\n업데이트 된 시간\n(패치 시간 아니에요)") - sb.append(""" - - ${format.format(updatedTimestamp)} - - """.trimIndent()) - if (isCriticalAlarm || isNewAlertAlarm) { - sb.append(String.format("%nAlarm: %s %s", - if (isCriticalAlarm) "Critical" else "", - if (isNewAlertAlarm) "Alert" else "")) - } - sb.append(""" - - GlobalTime: ${convertHumanTimeWithStandard(currentTime())} - """.trimIndent()) - sb.append("\nNeedPriming: $isNeedPriming") - sb.append("\nNeedNeedleSensing: $isNeedNeedleSensing") - sb.append("\nPrimingSuccess: $isPrimingSuccess") - sb.append("\nBasalReg: $isNormalBasalReg") - sb.append("\nTempBasalReg: $isTempBasalReg") - sb.append("\nBasalAct: $isNormalBasalAct") - sb.append("\nisNowBolusRegAct: $isNowBolusRegAct") - sb.append("\nisNowBolusDone: $isNowBolusDone") - sb.append("\nisExtBolusRegAct: $isExtBolusRegAct") - sb.append("\nisExtBolusDone: $isExtBolusDone") - sb.append("\nisNormalBasalReg: $isNormalBasalReg") - sb.append("\nisNormalBasalAct: $isNormalBasalAct") - sb.append("\nisNormalBasalPaused: $isNormalBasalPaused") - sb.append("\nisTempBasalReg: $isTempBasalReg") - sb.append("\nisTempBasalAct: $isTempBasalAct") - sb.append("\nisTempBasalDone: $isTempBasalDone") - sb.append("\nExBolusTime: $isExtBolusTime") - sb.append("\nPumpAct: $isPumpAct") - sb.append(""" - - remainedInsulin: ${remainedInsulin()} - """.trimIndent()) - sb.append(""" - - remainedPumpCycle:${remainedPumpCycle()}($remainedInsulin) - """.trimIndent()) - sb.append(""" - - boot count :${bootCount()} - """.trimIndent()) - sb.append(""" - - aeCount : ${aeCount()} - """.trimIndent()) - sb.append(""" - - runningTime : ${runningTime()}hr - """.trimIndent()) - sb.append("\nisPumpInternalSuspended : $isPatchInternalSuspended") - sb.append("\nisResetAutoOffTime : $isResetAutoOffTime") - sb.append("\n\n\n") - return sb.toString() - } - fun convertHumanTimeWithStandard(timeSec: Int): String { val calendar = Calendar.getInstance() val dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") @@ -389,26 +271,20 @@ class PatchState: IPreference { return dateFormat.format(calendar.time) } - /** - * 다른 PatchState 와 비교해서 같은 값인지 확인. - * API 키[0-1], FUNC[2], 시간[14-17] 은 비교하지 않음. - * @param other 비교할 PatchState - * @return 같으면 true 다르면 false. - */ fun equalState(other: PatchState): Boolean { return IntStream.of(D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, D18, D19) .allMatch { i: Int -> other.stateBytes[i] == stateBytes[i] } } - override fun equals(o: Any?): Boolean { - if (this === o) { + override fun equals(other: Any?): Boolean { + if (this === other) { return true } - if (o == null || javaClass != o.javaClass) { + if (other == null || javaClass != other.javaClass) { return false } - val that = o as PatchState - return Arrays.equals(stateBytes, that.stateBytes) + val that = other as PatchState + return stateBytes.contentEquals(that.stateBytes) } override fun observe(): Observable { @@ -422,28 +298,10 @@ class PatchState: IPreference { } override fun hashCode(): Int { - return Arrays.hashCode(stateBytes) - } - - @Throws(IOException::class) fun writeJson(out: JsonWriter) { - out.beginObject() - out.name(NAME) - out.beginObject() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - out.name("stateBytes").value(java.util.Base64.getEncoder().encodeToString(stateBytes)) - } else { - out.name("stateBytes").value(Arrays.toString(Base64.encode(stateBytes, - Base64.DEFAULT))) - } - out.name("updateTimestamp").value(updatedTimestamp) - out.endObject() - out.endObject() + return stateBytes.contentHashCode() } companion object { - - val UPDATE_CONNECTION_INTERVAL_MILLI = TimeUnit.SECONDS.toMillis(10) - const val NAME = "PATCH_STATE" const val SIZE = 20 @JvmStatic fun create(bytes: ByteArray?, updatedTimestamp: Long): PatchState { var stateBytes = bytes @@ -462,22 +320,22 @@ class PatchState: IPreference { return bs[startPos + 0].toInt() and 0xFF shl 24 or (bs[startPos + 1].toInt() and 0xFF shl 16) or (bs[startPos + 2].toInt() and 0xFF shl 8) or (bs[startPos + 3].toInt() and 0xFF) } - private const val D0 = 0 // DUMMY - private const val D1 = 1 // DUMMY - private const val D2 = 2 // FUNCTION CODE 0x22 - private const val D3 = 3 // SETUP - private const val D4 = D3 + 1 // BOLUS - private const val D5 = D3 + 2 // ALERT - private const val D6 = D3 + 3 // INSULIN - private const val D7 = D3 + 4 // BATTERY - private const val D8 = D3 + 5 // BOOT - private const val D9 = D3 + 6 // APS - private const val D10 = D3 + 7 // APS - private const val D11 = D3 + 8 // New Alarm Count - private const val D12 = D3 + 9 // Remain Pump Count - private const val D13 = D3 + 10 // Remain Pump Count - private const val D14 = D3 + 11 // Current Time - private const val D18 = D3 + 15 // Remained Insulin - private const val D19 = D3 + 16 // Running Time + private const val D0 = 0 + private const val D1 = 1 + private const val D2 = 2 + private const val D3 = 3 + private const val D4 = D3 + 1 + private const val D5 = D3 + 2 + private const val D6 = D3 + 3 + private const val D7 = D3 + 4 + private const val D8 = D3 + 5 + private const val D9 = D3 + 6 + private const val D10 = D3 + 7 + private const val D11 = D3 + 8 + private const val D12 = D3 + 9 + private const val D13 = D3 + 10 + private const val D14 = D3 + 11 + private const val D18 = D3 + 15 + private const val D19 = D3 + 16 } } \ No newline at end of file diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/Segment.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/Segment.kt index 0db5e513d3..804f3266f1 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/Segment.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/Segment.kt @@ -16,33 +16,3 @@ internal class JoinedSegment(var index: Int) { endMinute = startMinute + SegmentEntity.TIME_BASE } } - -internal class JoinedSegments { - var activeBasal: String - var mList: Array - - init { - activeBasal = "" - mList = Array(DEF_COUNT, { i -> JoinedSegment(i)}) - } - - - fun apply(segments: SegmentsEntity>) { - var i = 0 - var no = 0 - - for (item in segments.list) { - while (i < DEF_COUNT && item.includes(mList[i])) { // i> { - var startMinute = 0L var endMinute = 0L @@ -16,9 +15,7 @@ abstract class SegmentEntity> { fun getDuration(): Long { return endMinute - startMinute } - /** - * Empty Segment 여부 돌려주기 - */ + internal abstract val isEmpty: Boolean internal fun isMinuteIncluding(minute: Long): Boolean { @@ -33,42 +30,23 @@ abstract class SegmentEntity> { return startMinute == target.startMinute || target.endMinute == endMinute } - /** - * 타겟을 완전히 포함? - */ internal fun canCover(target: SegmentEntity<*>): Boolean { return startMinute <= target.startMinute && target.endMinute <= endMinute } - /** - * 타겟에 완전히 덮임. - */ internal fun isCoveredBy(target: SegmentEntity<*>): Boolean { return target.canCover(this) } - /** - * 타겟과 걸침? 주의 canCover 또는 isCoveredBy 이 true 이면 이것도 true 임. - * 즉 canCover 와 isCoveredBy 가 미리 확인된 이후에 호출 할 것. - */ internal fun isOverlapped(target: SegmentEntity<*>): Boolean { return startMinute < target.endMinute && target.startMinute < endMinute } - /** - * 타겟을 완전히 포함하고 있지 않고 걸침. - */ internal fun isPartiallyNotFullyIncluding(target: SegmentEntity<*>): Boolean { return isOverlapped(target) && !canCover(target) && !isCoveredBy(target) } - /** - * target segment 를 뺸다. target 은 한방향으로만 걸쳐야 함. - * 즉 isPartiallyNotFullyIncluding(target) 이 false 여야 한다. - * 양 끝단 중 한 쪽이 같은 경우가 발생하는데 그 경우는 splitBy 에서 한쪽만 생성되므로 OK! - */ internal fun subtract(target: SegmentEntity<*>, validCheck: Boolean) { - if (validCheck) { if (!isPartiallyNotFullyIncluding(target)) { return @@ -82,11 +60,7 @@ abstract class SegmentEntity> { } } - /** - * target segment 에 의해서 쪼개져서 생성되는 segment list 를 돌려준다. - */ internal fun splitBy(target: T, validCheck: Boolean): List? { - if (validCheck) { if (!canCover(target)) { return null @@ -102,39 +76,19 @@ abstract class SegmentEntity> { if (target.endMinute < endMinute) { result.add(duplicate(target.endMinute, endMinute)) } - return result } - /** - * JoinedSegment 를 포함하는가? - */ internal fun includes(segment: JoinedSegment): Boolean { return startMinute <= segment.startMinute && segment.endMinute <= endMinute } - /** - * 같은 값을 가지는 주어진 시간으로 새로운 세그먼트 생성. - */ internal abstract fun duplicate(startMinute: Long, endMinute: Long): T - - /** - * copy constructor - */ internal abstract fun deep(): T - - /** - * 값이 같은가? - */ internal abstract fun equalValue(segment: T): Boolean - - /** - * 이 세그먼트의 값을 JoinedSegment 에 적용한다. - */ internal abstract fun apply(segment: JoinedSegment) companion object { - - internal val TIME_BASE = 30 + const val TIME_BASE = 30 } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/SegmentsEntity.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/SegmentsEntity.kt index 26ff1b5393..64775d316f 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/SegmentsEntity.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/SegmentsEntity.kt @@ -5,21 +5,14 @@ import java.util.* import java.util.function.BiFunction abstract class SegmentsEntity> { - - var list: ArrayList + var list: ArrayList = ArrayList() val segmentCount: Int get() = list.size - /** - * shallow copied list - */ val copiedSegmentList: ArrayList get() = ArrayList(list) - /** - * deep copied list - */ val deepCopiedSegmentList: ArrayList get() { val copied = ArrayList() @@ -42,10 +35,6 @@ abstract class SegmentsEntity> { return (segmentIndex * 30).toLong() } - init { - list = ArrayList() - } - fun hasSegments(): Boolean { return list.isNotEmpty() } @@ -70,59 +59,15 @@ abstract class SegmentsEntity> { } } - // 중복은 체크할 필요 없음, 세그먼트 추가할 때 중복체크함 -// var lastIndex = -1 for (seg in list) { if (seg.isEmpty) { return false } - -// val startIndex = seg.startIndex -// val endIndex = seg.endIndex -//// lastIndex += 1 -// if (lastIndex != startIndex) { -// return false -// } -// lastIndex = endIndex } return true } - private fun isTimeOverlapped(target: T): Boolean { - for (seg in list) { - if (seg.isOverlapped(target)) { - return true - } - } - return false - } - - // private fun millsToLocalDateTime(millis: Long): LocalDateTime { - // val instant = Instant.ofEpochMilli(millis) - // return instant.atZone(ZoneId.systemDefault()).toLocalDateTime() - // } - - // fun getCurrentSegmentRemainMinute(timeStamp: Long): Long { - // val localDateTime = millsToLocalDateTime(timeStamp) - // val minute = localDateTime.minute - // - // getSegment(minute.toLong())?.let { - // val hourMinutes = TimeUnit.HOURS.toMinutes(localDateTime.hour.toLong()) - // val totalMinutes = hourMinutes + minute - // val remain = it.endMinute - totalMinutes - // - // return it.endMinute - totalMinutes - // } - // - // return 0 - // } - - // fun getSegmentByTimeStamp(timeStamp: Long): T? { - // val minute = millsToLocalDateTime(timeStamp).minute.toLong() - // return getSegment(minute) - // } - - fun getSegment(minute: Long): T? { + private fun getSegment(minute: Long): T? { for (seg in list) { if (seg.isMinuteIncluding(minute)) { return seg @@ -136,127 +81,9 @@ abstract class SegmentsEntity> { return getSegment(timeMinute) } - fun addSegment(seg: T) { - if (isTimeOverlapped(seg)) { - throw Exception() - } - list.add(seg) - Collections.sort(list) { t1, t2 -> java.lang.Long.compare(t1.startMinute, t2.startMinute) } - } - - - /** - * 세그먼트가 한개인 경우 삭제 불가, 첫 번째 세그먼트는 삭제 불가이므로 - * 항상 mSegmentList.size() >= 2이고 idx는 0이 될 수 없음 - * @param segment - */ - fun removeSegment(segment: T): Int { - return _remove(segment, list) - } - - /** - * 기존 세그먼트 리스트에 덮으면서 추가함. 호환성을 위한 wrapper 함수. - * @param segment - */ - - fun addSegmentWithTimeOverlapped(segment: T) { - _union(segment, list) - } - - fun addSegmentWithTimeOverlapped(segment: T, oldSegment: T?) { - if(oldSegment != null) { // 편집인 경우는 기존 세그먼트 제거 - list.remove(oldSegment) - } - _union(segment, list) - } - - /** - * 삭제 - * @param target - */ - @Synchronized - private fun _remove(target: T, list: ArrayList): Int { - val idx = list.indexOf(target) - - // idx는 최소 1 - if (idx > 0) { -// list[idx - 1].endMinute = target.endMinute - list.remove(target) - _arrange(list) - return idx - } else { - return -1 - } - } - - /** - * 기존 세그먼트 리스트에 덮으면서 추가함. - * @param target - */ - @Synchronized - private fun _union(target: T, list: ArrayList) { - - val toBeAdded = ArrayList() - - val iterator = list.iterator() - - while (iterator.hasNext()) { - val item = iterator.next() - - if (target.canCover(item)) { - iterator.remove() - } else if (target.isCoveredBy(item)) { - toBeAdded.addAll(item.splitBy(target, false)!!) - iterator.remove() - } else if (target.isOverlapped(item)) { - item.subtract(target, false) - } - } - - list.addAll(toBeAdded) - list.add(target) - - _arrange(list) - } - - /** - * 동일 세그먼트 합치기 - */ - - @Synchronized - private fun _arrange(list: ArrayList) { - val size = list.size - - if (size < 2) { - return - } - - val resultList = ArrayList() - - Collections.sort(list) { t1, t2 -> java.lang.Long.compare(t1.startMinute, t2.startMinute) } - - // ADM df_385. 연속된 세그먼트에 동일한 값 설정 가능하도록 합치는 작업 하지 않음 - EOMAPP은 합친다 - var left = list[0] - - for (i in 1 until size) { - val right = list[i] - if((left.endMinute == right.startMinute) && left.equalValue(right)) { - left.endMinute = right.endMinute - }else { - resultList.add(left) - left = right - } - } - - resultList.add(left) - - list.clear() - list.addAll(resultList) - } - fun isFullSegment(): Boolean { var start = 0L - var end = 1440L + val end = 1440L for(seg in list){ if(seg.startMinute == start){ start = seg.endMinute @@ -287,20 +114,4 @@ abstract class SegmentsEntity> { return Pair(list[list.size-1].endIndex, 48) } - - fun isChangeSegmentByNewSegment(newSegment: T, oldSegment: T?): Boolean { - list.forEach loop@{ - if(it == oldSegment) { - return@loop - } - if(newSegment.canCover(it)) { - return true - }else if(newSegment.isCoveredBy(it)) { - return true - }else if(newSegment.isOverlapped(it)) { - return true - } - } - return false - } } diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasal.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasal.kt index ed1ce2add4..d1b2ab3b50 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasal.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasal.kt @@ -11,22 +11,14 @@ class TempBasal { var durationMinutes: Long = 0L var doseUnitPerHour: Float = -1f var percent: Int = 0 - var unitDefinition: UnitOrPercent? = null // percenr or U - set(_unitDefinition: UnitOrPercent?) { - field = _unitDefinition - } + var unitDefinition: UnitOrPercent? = null - - var running =false - - // val isGreaterThanMaxBasal: Boolean - // get() = isGreaterThan(25f) //todo + var running =false val percentUs: FloatArray get() { - val doseUs: FloatArray - doseUs = FloatArray((this.durationMinutes / 30).toInt()) + val doseUs = FloatArray((this.durationMinutes / 30).toInt()) for (i in doseUs.indices) { doseUs[i] = this.percent.toFloat() } @@ -34,23 +26,9 @@ class TempBasal { return doseUs } - val doseUnitPerHourArray: FloatArray - get() { - val doseUs: FloatArray - - doseUs = FloatArray((this.durationMinutes / 30).toInt()) - - val value = FloatAdjusters.ROUND2_INSULIN.apply(doseUnitPerHour) - for (i in doseUs.indices) { - doseUs[i] = value - } - return doseUs - } - val endTimestamp: Long get() = if (this.startTimestamp == 0L) 0 else this.startTimestamp + TimeUnit.MINUTES.toMillis(this.durationMinutes) - val doseUnitText: String get() = String.format("%s U/hr", FloatFormatters.insulin(doseUnitPerHour)) @@ -83,15 +61,10 @@ class TempBasal { if (this.unitDefinition == UnitOrPercent.U) { maxTempBasal = this.doseUnitPerHour } else if (this.unitDefinition == UnitOrPercent.P) { - val normalBasal = normalBasalManager.normalBasal - if (normalBasal != null) { - val maxNormalBasal = normalBasal.getMaxBasal(durationMinutes) - maxTempBasal = FloatAdjusters.ROUND2_TEMP_BASAL_PROGRAM_RATE.apply(maxNormalBasal + getDoseUnitPerHourWithPercent(maxNormalBasal)) - } + val maxNormalBasal = normalBasalManager.normalBasal.getMaxBasal(durationMinutes) + maxTempBasal = FloatAdjusters.ROUND2_TEMP_BASAL_PROGRAM_RATE.apply(maxNormalBasal + getDoseUnitPerHourWithPercent(maxNormalBasal)) } - return if (maxTempBasal > maxBasal) { - true - } else false + return maxTempBasal > maxBasal } override fun toString(): String { diff --git a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasalManager.kt b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasalManager.kt index 4ebafb2204..0de79a36f5 100644 --- a/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasalManager.kt +++ b/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/vo/TempBasalManager.kt @@ -21,11 +21,6 @@ class TempBasalManager : IPreference{ var unit = UnitOrPercent.P - init { - - } - - fun clear(){ startedBasal = null startTimestamp = 0L @@ -37,38 +32,14 @@ class TempBasalManager : IPreference{ this.startedBasal = CommonUtils.clone(tempBasal) this.startedBasal?.running = true + this.startTimestamp = System.currentTimeMillis() } - - /** - * 특정 베이젤의 인덱스 찾기 - * - * @param basal - * @return - */ - - fun updateBasalStopped() { - // 모두 정지 this.startedBasal?.running = false this.startedBasal?.startTimestamp = 0 - // subject.onNext(this) } - fun updateForDeactivation() { - // deactivation할때는 모두 정지 - updateBasalStopped() - // subject.onNext(this) - } - - - - fun updateDeactivation() { - updateBasalStopped() - } - - - fun update(other: TempBasalManager){ this.startedBasal = other.startedBasal startTimestamp = other.startTimestamp @@ -89,13 +60,4 @@ class TempBasalManager : IPreference{ override fun toString(): String { return "TempBasalManager(startedBasal=$startedBasal, startTimestamp=$startTimestamp, endTimestamp=$endTimestamp, unit=$unit)" } - - companion object { - - const val NAME = "TEMP_BASAL_MANAGER" - - val MAX_BASAL_SEQ = 20 - val MANUAL_BASAL_SEQ = MAX_BASAL_SEQ + 1 - } - } diff --git a/eopatch/src/main/res/layout/activity_eopatch.xml b/eopatch/src/main/res/layout/activity_eopatch.xml index f01206f3ff..178ff6982d 100644 --- a/eopatch/src/main/res/layout/activity_eopatch.xml +++ b/eopatch/src/main/res/layout/activity_eopatch.xml @@ -4,19 +4,16 @@ xmlns:tools="http://schemas.android.com/tools"> - - - @@ -25,24 +22,12 @@ android:layout_width="match_parent" android:layout_height="60dp"> - - - - @@ -42,7 +40,7 @@ android:layout_marginEnd="5dp" android:gravity="center" android:text="@{viewModel.programEnabledMessage}" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_basal_schedule" @@ -60,7 +58,7 @@ android:paddingStart="20dp" android:paddingEnd="20dp" android:text="@string/patch_basal_schedule_desc_2" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_basal_schedule_desc_1" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_connect_new.xml b/eopatch/src/main/res/layout/fragment_eopatch_connect_new.xml index ea291edec1..fffbe9079f 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_connect_new.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_connect_new.xml @@ -4,13 +4,10 @@ xmlns:tools="http://schemas.android.com/tools"> - - - @@ -40,7 +35,7 @@ android:layout_marginTop="7dp" android:gravity="center" android:text="@string/patch_connect_new_step" - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_connect_new" /> @@ -51,7 +46,7 @@ android:layout_height="wrap_content" android:layout_marginTop="42dp" android:text="@string/patch_connect_new_desc" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_connect_new_progress" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_overview.xml b/eopatch/src/main/res/layout/fragment_eopatch_overview.xml index 265f9ab564..c05e793ac2 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_overview.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_overview.xml @@ -99,7 +99,6 @@ android:layout_marginBottom="5dp" android:background="@color/list_delimiter" /> - - - - diff --git a/eopatch/src/main/res/layout/fragment_eopatch_remove.xml b/eopatch/src/main/res/layout/fragment_eopatch_remove.xml index 30b96ff449..f1df4bb411 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_remove.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_remove.xml @@ -5,7 +5,6 @@ - @@ -34,7 +33,7 @@ android:layout_marginTop="5dp" android:layout_marginStart="9dp" android:text="@string/patch_discard_complete_desc" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintLeft_toRightOf="@+id/image_patch_remove" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_remove_needle_cap.xml b/eopatch/src/main/res/layout/fragment_eopatch_remove_needle_cap.xml index 50de6f164e..006b034906 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_remove_needle_cap.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_remove_needle_cap.xml @@ -5,7 +5,6 @@ - @@ -29,10 +28,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" - android:text="@string/patch_remove_needle_cap" - - android:textSize="24dp" + android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -44,8 +41,7 @@ android:layout_marginTop="7dp" android:gravity="center" android:text="@string/patch_remove_needle_cap_step" - - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_remove_needle_cap" /> @@ -55,28 +51,12 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="42dp" - android:text="@string/patch_remove_needle_cap_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_remove_needle_cap_progress" /> - - @@ -114,7 +94,7 @@ android:layout_marginStart="7dp" android:layout_marginTop="5dp" android:text="@string/patch_remove_needle_cap_desc_3" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toEndOf="@+id/image_patch_remove_needle_cap" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_remove_needle_cap_desc_2" /> @@ -170,7 +150,6 @@ app:layout_constraintStart_toEndOf="@id/guideline_button" app:layout_constraintTop_toTopOf="parent" app:onSafeClick="@{() -> viewModel.moveStep(PatchStep.REMOVE_PROTECTION_TAPE)}" /> - diff --git a/eopatch/src/main/res/layout/fragment_eopatch_remove_protection_tape.xml b/eopatch/src/main/res/layout/fragment_eopatch_remove_protection_tape.xml index fb985e0d70..f12ba9996f 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_remove_protection_tape.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_remove_protection_tape.xml @@ -5,7 +5,6 @@ - @@ -23,10 +22,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" - android:text="@string/patch_remove_protection_tape" - - android:textSize="24dp" + android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -38,8 +35,7 @@ android:layout_marginTop="7dp" android:gravity="center" android:text="@string/patch_remove_protection_tape_step" - - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_remove_protection_tape" /> @@ -49,10 +45,8 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="42dp" - android:text="@string/patch_remove_protection_tape_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_remove_protection_tape_progress" /> @@ -72,10 +66,8 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="16dp" - android:text="@string/patch_remove_protection_tape_desc_2" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/img_patch_act_03" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_rotate_knob.xml b/eopatch/src/main/res/layout/fragment_eopatch_rotate_knob.xml index f21d685ee6..5da32f5bcc 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_rotate_knob.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_rotate_knob.xml @@ -5,7 +5,6 @@ - @@ -29,10 +28,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" - android:text="@string/patch_rotate_knob" - - android:textSize="24dp" + android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -44,8 +41,7 @@ android:layout_marginTop="7dp" android:gravity="center" android:text="@string/patch_rotate_knob_step" - - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_rotate_knob" /> @@ -84,7 +80,7 @@ android:layout_height="wrap_content" android:layout_marginStart="9dp" android:text="@string/needle_insertion_error_1" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintLeft_toRightOf="@+id/image_point_read01" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -105,7 +101,7 @@ android:layout_marginTop="5dp" android:layout_marginStart="9dp" android:text="@string/needle_insertion_error_2" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintLeft_toRightOf="@+id/image_point_read02" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_needle_insertion_error_1" /> @@ -127,7 +123,7 @@ android:layout_marginStart="9dp" android:paddingBottom="12dp" android:text="@string/needle_insertion_error_3" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintLeft_toRightOf="@+id/image_point_read02" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_needle_insertion_error_2" /> @@ -138,29 +134,14 @@ android:id="@+id/text_patch_rotate_knob_desc" android:layout_width="0dp" android:layout_height="wrap_content" - android:text="@string/patch_rotate_knob_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/layout_needle_insertion_error" /> - - @@ -33,7 +32,7 @@ android:layout_marginStart="9dp" android:layout_marginTop="5dp" android:text="@string/patch_safe_deactivation_desc" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toEndOf="@+id/image_patch_safe_deactivation" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -51,7 +50,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/patch_remaining_insulin" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/text_patch_safe_deactivation_remaining_usage_period" app:layout_constraintStart_toStartOf="parent" /> @@ -61,8 +60,7 @@ android:layout_height="wrap_content" android:layout_marginBottom="26dp" android:text="@string/patch_remaining_usage_period" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/text_patch_safe_deactivation_next" app:layout_constraintStart_toStartOf="parent" /> @@ -70,7 +68,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{Integer.toString(viewModel.patchRemainedInsulin > 50 ? 50 : (viewModel.patchRemainedInsulin < 1 ? 1 : viewModel.patchRemainedInsulin))}" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/layout_patch_safe_deactivation_remaining_usage_period_value" app:layout_constraintEnd_toStartOf="@+id/text_patch_dose_unit" tools:text="50" /> @@ -80,7 +78,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/all_dose_unit" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintBottom_toTopOf="@+id/layout_patch_safe_deactivation_remaining_usage_period_value" app:layout_constraintEnd_toStartOf="@+id/text_patch_dose_plus" /> @@ -89,7 +87,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.patchRemainedInsulin > 1 ? @string/symbol_plus : @string/symbol_minus}" - android:textSize="16dp" + android:textSize="16sp" app:visibleOrGone="@{(viewModel.patchRemainedInsulin <= 0 || viewModel.patchRemainedInsulin >= 51)}" app:layout_constraintBottom_toTopOf="@+id/layout_patch_safe_deactivation_remaining_usage_period_value" app:layout_constraintEnd_toEndOf="parent" @@ -109,7 +107,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.patchRemainedDays.toString()}" - android:textSize="16dp" + android:textSize="16sp" app:visibleOrGone="@{viewModel.patchRemainedDays > 0}" tools:text="N"/> @@ -118,7 +116,7 @@ android:layout_height="wrap_content" android:text="@{viewModel.patchRemainedDays > 1 ? @string/symbol_days : @string/symbol_day}" app:visibleOrGone="@{viewModel.patchRemainedDays > 0}" - android:textSize="16dp" + android:textSize="16sp" tools:text="@string/symbol_days" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_safety_check.xml b/eopatch/src/main/res/layout/fragment_eopatch_safety_check.xml index 36bb6af01d..3655262ccd 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_safety_check.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_safety_check.xml @@ -5,7 +5,6 @@ - @@ -23,10 +22,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" - android:text="@string/patch_safety_check" - - android:textSize="24dp" + android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -38,8 +35,7 @@ android:layout_marginTop="7dp" android:gravity="center" android:text="@string/patch_safety_check_step" - - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_safety_check" /> @@ -49,10 +45,8 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="42dp" - android:text="@string/patch_safety_check_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_safety_check_progress" /> @@ -84,7 +78,7 @@ android:layout_marginStart="9dp" android:layout_marginTop="27dp" android:text="@string/patch_safety_check_desc_2" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@+id/image_patch_safety_check_desc_2" app:layout_constraintTop_toBottomOf="@+id/progressbar_patch_safety_check" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_turning_off_alarm.xml b/eopatch/src/main/res/layout/fragment_eopatch_turning_off_alarm.xml index 52f20f755e..de56050263 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_turning_off_alarm.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_turning_off_alarm.xml @@ -5,7 +5,6 @@ - @@ -23,10 +22,8 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" - android:text="@string/patch_manually_turning_off_alarm_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -35,10 +32,8 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" - android:text="@string/patch_manually_turning_off_alarm_desc_2" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/text_patch_manually_turning_off_alarm_desc_1" /> @@ -47,10 +42,8 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" - android:text="@string/patch_manually_turning_off_alarm_step_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/text_patch_manually_turning_off_alarm_desc_2" /> @@ -59,10 +52,8 @@ android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" - android:text="@string/patch_manually_turning_off_alarm_step_2" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/text_patch_manually_turning_off_alarm_step_1" /> diff --git a/eopatch/src/main/res/layout/fragment_eopatch_wake_up.xml b/eopatch/src/main/res/layout/fragment_eopatch_wake_up.xml index d80bdfe5ef..e659bb02b7 100644 --- a/eopatch/src/main/res/layout/fragment_eopatch_wake_up.xml +++ b/eopatch/src/main/res/layout/fragment_eopatch_wake_up.xml @@ -29,10 +29,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" - android:text="@string/patch_wake_up" - - android:textSize="24dp" + android:textSize="24sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> @@ -45,7 +43,7 @@ android:gravity="center" android:text="@string/patch_wake_up_step" - android:textSize="12dp" + android:textSize="12sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_wake_up" /> @@ -54,10 +52,8 @@ android:id="@+id/text_patch_wake_up_desc_num_1" android:layout_width="25dp" android:layout_height="wrap_content" - android:text="@string/patch_step_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/text_patch_wake_up_desc_1" /> @@ -66,10 +62,8 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="43dp" - android:text="@string/patch_wake_up_desc_1" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toEndOf="@+id/text_patch_wake_up_desc_num_1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_wake_up_progress" /> @@ -78,10 +72,8 @@ android:id="@+id/text_patch_wake_up_desc_num_2" android:layout_width="25dp" android:layout_height="wrap_content" - android:text="@string/patch_step_desc_2" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/text_patch_wake_up_desc_2" /> @@ -90,10 +82,8 @@ android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="5dp" - android:text="@string/patch_wake_up_desc_2" - - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toEndOf="@+id/text_patch_wake_up_desc_num_2" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_wake_up_desc_1" /> @@ -114,27 +104,11 @@ android:layout_marginStart="9dp" android:layout_marginTop="12dp" android:text="@string/string_caution_not_remove_needle_cap" - android:textSize="16dp" + android:textSize="16sp" app:layout_constraintStart_toEndOf="@+id/image_point_red" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/text_patch_wake_up_desc_2" /> - - 패치 적용 알림 패치 적용이 완료되지 않았습니다.\n패치 적용을 시작합니다. 패치 통신 점검 - 패치 통신 점검 중입니다... + 패치 통신 점검 중입니다… 스마트 기기를 패치에 가까이 가져가세요. 다른 장소로 이동 후 재시도하세요. 패치 통신 오류 @@ -133,5 +133,7 @@ 완료 %1$s시간 %2$s분 남음 다음 - + 패치 통신 점검 후 다시 시도하세요. + 주입 정지가 실패하였습니다. + 주입 재개가 실패하였습니다. diff --git a/eopatch/src/main/res/values/arrays.xml b/eopatch/src/main/res/values/arrays.xml index e763eb285d..cdc341d68d 100644 --- a/eopatch/src/main/res/values/arrays.xml +++ b/eopatch/src/main/res/values/arrays.xml @@ -1,6 +1,6 @@ - + 10 U 15 U 20 U @@ -12,7 +12,7 @@ 50 U - + 10 15 20 diff --git a/eopatch/src/main/res/values/strings.xml b/eopatch/src/main/res/values/strings.xml index 5ad11bbd42..3cc1e8810e 100644 --- a/eopatch/src/main/res/values/strings.xml +++ b/eopatch/src/main/res/values/strings.xml @@ -1,5 +1,5 @@ - eopatch_low_reservior_reminders + eopatch_low_reservoir_reminders eopatch_expiration_reminders eopatch_patch_buzzer_reminders eopatch_patch_config @@ -144,5 +144,7 @@ Finish remaining time: %1$s:%2$s Next - + Retry after Patch communication check. + Suspension failed. + Resume failed. \ No newline at end of file diff --git a/eopatch/src/main/res/xml/pref_eopatch.xml b/eopatch/src/main/res/xml/pref_eopatch.xml index 4e9e6f545b..609c5f179b 100644 --- a/eopatch/src/main/res/xml/pref_eopatch.xml +++ b/eopatch/src/main/res/xml/pref_eopatch.xml @@ -4,9 +4,9 @@