Eliminate warnings and fix bug

This commit is contained in:
jungsomyeong 2022-03-04 17:46:56 +09:00
parent e4858e34bf
commit 7934851bf6
126 changed files with 969 additions and 2665 deletions

View file

@ -163,6 +163,10 @@ android {
} }
useLibrary "org.apache.http.legacy" useLibrary "org.apache.http.legacy"
dataBinding { //Deleting it causes a binding error
enabled = true
}
} }
allprojects { allprojects {

Binary file not shown.

View file

@ -105,6 +105,7 @@
<item>DanaRv2</item> <item>DanaRv2</item>
<item>DanaI</item> <item>DanaI</item>
<item>Diaconn G8</item> <item>Diaconn G8</item>
<item>Eoflow Eopatch2</item>
<item>Medtronic 512/712</item> <item>Medtronic 512/712</item>
<item>Medtronic 515/715</item> <item>Medtronic 515/715</item>
<item>Medtronic 522/722</item> <item>Medtronic 522/722</item>

View file

@ -330,6 +330,7 @@ enum class PumpType {
baseBasalStep = 0.05, baseBasalStep = 0.05,
baseBasalSpecialSteps = null, baseBasalSpecialSteps = null,
pumpCapability = PumpCapability.EopatchCapabilities, pumpCapability = PumpCapability.EopatchCapabilities,
isPatchPump = true,
source = Sources.EOPatch2); source = Sources.EOPatch2);
val description: String val description: String

View file

@ -26,20 +26,12 @@ allprojects {
dependencies { dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation (name: 'eopatch_core', ext: 'aar') implementation (name: 'eopatch_core', ext: 'aar')
// implementation (files("libs/eopatch_core.aar"))
implementation project(':core') implementation project(':core')
implementation project(':shared') implementation project(':shared')
implementation project(':database') 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 //RxAndroidBle
implementation "com.polidea.rxandroidble2:rxandroidble:$rxandroidble_version" implementation "com.polidea.rxandroidble2:rxandroidble:1.12.1"
implementation "com.jakewharton.rx2:replaying-share:$replayshare_version" implementation "com.jakewharton.rx2:replaying-share:2.2.0"
} }

Binary file not shown.

View file

@ -3,7 +3,6 @@
package="info.nightscout.androidaps.plugins.pump.eopatch"> package="info.nightscout.androidaps.plugins.pump.eopatch">
<application> <application>
<activity android:name=".ui.EopatchActivity" /> <activity android:name=".ui.EopatchActivity" />
<activity android:name=".ui.AlarmHelperActivity" /> <activity android:name=".ui.AlarmHelperActivity" />
<activity android:name=".ui.DialogHelperActivity" /> <activity android:name=".ui.DialogHelperActivity" />

View file

@ -1,87 +1,29 @@
package info.nightscout.androidaps.plugins.pump.eopatch package info.nightscout.androidaps.plugins.pump.eopatch
import java.util.concurrent.TimeUnit
interface AppConstant { interface AppConstant {
companion object { companion object {
const val BASAL_MIN_AMOUNT = 0.05f
val BASAL_MIN_AMOUNT = 0.05f const val INSULIN_UNIT_P = 0.05f
val CLICK_THROTTLE = 600L
/** const val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P
* Bluetooth Connection State
*/
val BT_STATE_NOT_CONNECT = 1
val BT_STATE_CONNECTED = 2
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 BASAL_RATE_PER_HOUR_MIN = BASAL_MIN_AMOUNT
const val INSULIN_UNIT_P = 0.05f // 최소 주입 단위
val INSULIN_UNIT_MIN_U = 0f const val SEGMENT_MAX_SIZE_48 = 48
val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P const val SEGMENT_COUNT_MAX = SEGMENT_MAX_SIZE_48
/** const val BOLUS_ACTIVE_EXTENDED_WAIT = 0x2
* On/Off
*/
val OFF = 0
val ON = 1
/** const val BOLUS_UNIT_STEP = INSULIN_UNIT_STEP_U
* 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 DAY_START_MINUTE = 0 * 60
const val DAY_END_MINUTE = 24 * 60
const val INSULIN_DURATION_MIN = 2.0f
} }
} }

View file

@ -1,37 +1,23 @@
package info.nightscout.androidaps.plugins.pump.eopatch 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 io.reactivex.disposables.Disposable
import java.util.* import java.util.*
import java.util.function.Function import kotlin.math.abs
import kotlin.math.min
object CommonUtils { object CommonUtils {
val TO_INT = Function<Number, Int> { it.toInt() } fun dispose(vararg disposable: Disposable?) {
val TO_FLOAT = Function<Number, Float> { it.toFloat() }
val TO_STRING = Function<Number, String> { it.toString() }
val TO_CLOCK = Function<Number, String>{ num -> String.format(Locale.US, "%d:%02d", num.toInt() / 60, num.toInt() % 60) }
@JvmStatic fun dispose(vararg disposable: Disposable?) {
for (d in disposable){ for (d in disposable){
d?.let { d?.let {
if (!it.isDisposed()) { if (!it.isDisposed) {
it.dispose() it.dispose()
} }
} }
} }
} }
@JvmStatic fun nullSafe(ch: CharSequence?): String { fun hasText(str: CharSequence?): Boolean {
if (ch == null) if (str == null || str.isEmpty()) {
return ""
val str = ch.toString()
return str
}
@JvmStatic fun hasText(str: CharSequence?): Boolean {
if (str == null || str.length == 0) {
return false return false
} }
val strLen = str.length val strLen = str.length
@ -43,12 +29,12 @@ object CommonUtils {
return false return false
} }
@JvmStatic fun hasText(str: String?): Boolean { fun hasText(str: String?): Boolean {
return str?.let{hasText(it as CharSequence)}?:false return str?.let{hasText(it as CharSequence)}?:false
} }
@JvmStatic fun isStringEmpty(cs: CharSequence?): Boolean { fun isStringEmpty(cs: CharSequence?): Boolean {
return cs == null || cs.length == 0 return cs == null || cs.isEmpty()
} }
@JvmStatic fun dateString(millis: Long): String { @JvmStatic fun dateString(millis: Long): String {
@ -69,109 +55,42 @@ object CommonUtils {
c.get(Calendar.SECOND)) 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<Long, Long> { fun getRemainHourMin(timeMillis: Long): Pair<Long, Long> {
val diffHours: Long val diffHours: Long
var diffMinutes: Long var diffMinutes: Long
if (timeMillis >= 0) { if (timeMillis >= 0) {
diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60) + 1 diffMinutes = abs(timeMillis / (60 * 1000) % 60) + 1
if (diffMinutes == 60L) { if (diffMinutes == 60L) {
diffMinutes = 0 diffMinutes = 0
diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) + 1 diffHours = abs(timeMillis / (60 * 60 * 1000)) + 1
} else { } else {
diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) diffHours = abs(timeMillis / (60 * 60 * 1000))
} }
} else { } else {
diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60) diffMinutes = abs(timeMillis / (60 * 1000) % 60)
diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) diffHours = abs(timeMillis / (60 * 60 * 1000))
} }
return Pair(diffHours, diffMinutes) 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 { fun nearlyEqual(a: Float, b: Float, epsilon: Float): Boolean {
val absA = Math.abs(a) val absA = abs(a)
val absB = Math.abs(b) val absB = abs(b)
val diff = Math.abs(a - b) val diff = abs(a - b)
return if (a == b) { // shortcut, handles infinities return if (a == b) {
true true
} else if (a == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) { } 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 diff < epsilon * java.lang.Float.MIN_NORMAL
} else { // use relative error } else {
diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon diff / min(absA + absB, Float.MAX_VALUE) < epsilon
} }
} }
@JvmStatic
fun nearlyNotEqual(a: Float, b: Float, epsilon: Float): Boolean { fun nearlyNotEqual(a: Float, b: Float, epsilon: Float): Boolean {
return !nearlyEqual(a, b, epsilon) return !nearlyEqual(a, b, epsilon)
} }
@JvmStatic
fun <T : Any> clone(src: T): T { fun <T : Any> clone(src: T): T {
return GsonHelper.sharedGson().fromJson(GsonHelper.sharedGson().toJson(src), src.javaClass) return GsonHelper.sharedGson().fromJson(GsonHelper.sharedGson().toJson(src), src.javaClass)
} }

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.eopatch package info.nightscout.androidaps.plugins.pump.eopatch
import android.content.Context
import android.os.SystemClock import android.os.SystemClock
import androidx.preference.Preference import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat 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.TimeChangeType
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer import io.reactivex.functions.Consumer
@ -57,12 +55,12 @@ class EopatchPumpPlugin @Inject constructor(
private val fabricPrivacy: FabricPrivacy, private val fabricPrivacy: FabricPrivacy,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val pumpSync: PumpSync, private val pumpSync: PumpSync,
private val patchmanager: IPatchManager, private val patchManager: IPatchManager,
private val alarmManager: IAlarmManager, private val alarmManager: IAlarmManager,
private val preferenceManager: IPreferenceManager private val preferenceManager: IPreferenceManager
):PumpPluginBase(PluginDescription() ):PumpPluginBase(PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
.fragmentClass(EopatchOverviewFragment::class.java.getName()) .fragmentClass(EopatchOverviewFragment::class.java.name)
.pluginIcon(R.drawable.ic_eopatch2_128) .pluginIcon(R.drawable.ic_eopatch2_128)
.pluginName(R.string.eopatch) .pluginName(R.string.eopatch)
.shortName(R.string.eopatch_shortname) .shortName(R.string.eopatch_shortname)
@ -72,8 +70,7 @@ class EopatchPumpPlugin @Inject constructor(
private val mDisposables = CompositeDisposable() private val mDisposables = CompositeDisposable()
var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2 private var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2
private set
private var mLastDataTime: Long = 0 private var mLastDataTime: Long = 0
private val mPumpDescription = PumpDescription(mPumpType) private val mPumpDescription = PumpDescription(mPumpType)
@ -83,10 +80,10 @@ class EopatchPumpPlugin @Inject constructor(
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe({ event: EventPreferenceChange -> .subscribe({ event: EventPreferenceChange ->
if (event.isChanged(rh, SettingKeys.LOW_RESERVIOR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) { if (event.isChanged(rh, SettingKeys.LOW_RESERVOIR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) {
patchmanager.changeReminderSetting() patchManager.changeReminderSetting()
} else if (event.isChanged(rh, SettingKeys.BUZZER_REMINDERS)) { } else if (event.isChanged(rh, SettingKeys.BUZZER_REMINDERS)) {
patchmanager.changeBuzzerSetting() patchManager.changeBuzzerSetting()
} }
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) } }) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
) )
@ -94,10 +91,10 @@ class EopatchPumpPlugin @Inject constructor(
mDisposables.add(rxBus mDisposables.add(rxBus
.toObservable(EventAppInitialized::class.java) .toObservable(EventAppInitialized::class.java)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribe({ event: EventAppInitialized? -> .subscribe({
aapsLogger.debug(LTag.PUMP,"EventAppInitialized") aapsLogger.debug(LTag.PUMP,"EventAppInitialized")
preferenceManager.init() preferenceManager.init()
patchmanager.init() patchManager.init()
alarmManager.init() alarmManager.init()
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) } }) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
) )
@ -106,7 +103,7 @@ class EopatchPumpPlugin @Inject constructor(
override fun specialEnableCondition(): Boolean { override fun specialEnableCondition(): Boolean {
//BG -> FG 시 패치 활성화 재진행 및 미처리 알람 발생 //BG -> FG 시 패치 활성화 재진행 및 미처리 알람 발생
if(preferenceManager.isInitDone()) { if(preferenceManager.isInitDone()) {
patchmanager.checkActivationProcess() patchManager.checkActivationProcess()
alarmManager.restartAll() alarmManager.restartAll()
} }
return super.specialEnableCondition() return super.specialEnableCondition()
@ -142,12 +139,11 @@ class EopatchPumpPlugin @Inject constructor(
} }
override fun isInitialized(): Boolean { override fun isInitialized(): Boolean {
val isInit = isConnected() && patchmanager.isActivated() return isConnected() && patchManager.isActivated
return isInit
} }
override fun isSuspended(): Boolean { override fun isSuspended(): Boolean {
return patchmanager.patchState.isNormalBasalPaused return patchManager.patchState.isNormalBasalPaused
} }
override fun isBusy(): Boolean { override fun isBusy(): Boolean {
@ -155,11 +151,11 @@ class EopatchPumpPlugin @Inject constructor(
} }
override fun isConnected(): Boolean { override fun isConnected(): Boolean {
return patchmanager.patchConnectionState.isConnected return patchManager.patchConnectionState.isConnected
} }
override fun isConnecting(): Boolean { override fun isConnecting(): Boolean {
return patchmanager.patchConnectionState.isConnecting return patchManager.patchConnectionState.isConnecting
} }
override fun isHandshakeInProgress(): Boolean { override fun isHandshakeInProgress(): Boolean {
@ -182,22 +178,24 @@ class EopatchPumpPlugin @Inject constructor(
} }
override fun getPumpStatus(reason: String) { override fun getPumpStatus(reason: String) {
if (patchmanager.isActivated()) { if (patchManager.isActivated) {
if ("SMS" == reason) { if ("SMS" == reason) {
aapsLogger.debug("Acknowledged AAPS getPumpStatus request it was requested through an SMS") aapsLogger.debug("Acknowledged AAPS getPumpStatus request it was requested through an SMS")
}else{ }else{
aapsLogger.debug("Acknowledged AAPS getPumpStatus request") aapsLogger.debug("Acknowledged AAPS getPumpStatus request")
} }
patchmanager.updateConnection().subscribe(Consumer { mDisposables.add(patchManager.updateConnection()
.subscribe(Consumer {
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
}) })
)
} }
} }
override fun setNewBasalProfile(profile: Profile): PumpEnactResult { override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
if(patchmanager.isActivated){ if(patchManager.isActivated){
if(patchmanager.patchState.isTempBasalActive || patchmanager.patchState.isBolusActive){ if(patchManager.patchState.isTempBasalActive || patchManager.patchState.isBolusActive){
return PumpEnactResult(injector) return PumpEnactResult(injector)
}else{ }else{
var isSuccess: Boolean? = null var isSuccess: Boolean? = null
@ -208,24 +206,21 @@ class EopatchPumpPlugin @Inject constructor(
} }
val nb = preferenceManager.getNormalBasalManager().convertProfileToNormalBasal(profile) val nb = preferenceManager.getNormalBasalManager().convertProfileToNormalBasal(profile)
patchmanager.startBasal(nb) mDisposables.add(patchManager.startBasal(nb)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ response -> .subscribe({ response ->
if (response.isSuccess) {
preferenceManager.getNormalBasalManager().normalBasal = nb
preferenceManager.flushNormalBasalManager()
}
result.onNext(response.isSuccess) result.onNext(response.isSuccess)
}, { throwable -> }, {
result.onNext(false) result.onNext(false)
}) })
)
do{ do{
SystemClock.sleep(100) SystemClock.sleep(100)
}while(isSuccess == null) }while(isSuccess == null)
disposable.dispose() 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 } return PumpEnactResult(injector).apply{ success = isSuccess?:false }
} }
}else{ }else{
@ -236,12 +231,12 @@ class EopatchPumpPlugin @Inject constructor(
} }
override fun isThisProfileSet(profile: Profile): Boolean { override fun isThisProfileSet(profile: Profile): Boolean {
if (!patchmanager.isActivated()) { if (!patchManager.isActivated) {
return true return true
} }
val ret = preferenceManager.getNormalBasalManager().isEqual(profile) 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 return ret
} }
@ -251,7 +246,7 @@ class EopatchPumpPlugin @Inject constructor(
override val baseBasalRate: Double override val baseBasalRate: Double
get() { get() {
if (!patchmanager.isActivated || patchmanager.patchState.isNormalBasalPaused) { if (!patchManager.isActivated || patchManager.patchState.isNormalBasalPaused) {
return 0.0 return 0.0
} }
@ -260,20 +255,20 @@ class EopatchPumpPlugin @Inject constructor(
override val reservoirLevel: Double override val reservoirLevel: Double
get() { get() {
if (!patchmanager.isActivated) { if (!patchManager.isActivated) {
return 0.0 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 override val batteryLevel: Int
get() { get() {
if(patchmanager.isActivated) { return if(patchManager.isActivated) {
return patchmanager.patchState.batteryLevel() patchManager.patchState.batteryLevel()
}else{ }else{
return 0 0
} }
} }
@ -292,7 +287,7 @@ class EopatchPumpPlugin @Inject constructor(
isSuccess = it isSuccess = it
} }
patchmanager.startCalculatorBolus(detailedBolusInfo) mDisposables.add(patchManager.startCalculatorBolus(detailedBolusInfo)
.doOnSuccess { .doOnSuccess {
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
}.subscribe({ }.subscribe({
@ -300,25 +295,26 @@ class EopatchPumpPlugin @Inject constructor(
}, { }, {
result.onNext(false) result.onNext(false)
}) })
)
do{ do{
SystemClock.sleep(100) SystemClock.sleep(100)
if(patchmanager.patchConnectionState.isConnected) { if(patchManager.patchConnectionState.isConnected) {
var delivering = patchmanager.bolusCurrent.nowBolus.injected val delivering = patchManager.bolusCurrent.nowBolus.injected
rxBus.send(EventOverviewBolusProgress.apply { rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivering, delivering) status = rh.gs(R.string.bolusdelivering, delivering)
percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100) percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100)
}) })
} }
}while(!patchmanager.bolusCurrent.nowBolus.endTimeSynced && isSuccess) }while(!patchManager.bolusCurrent.nowBolus.endTimeSynced && isSuccess)
rxBus.send(EventOverviewBolusProgress.apply { rxBus.send(EventOverviewBolusProgress.apply {
status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin) status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin)
percent = 100 percent = 100
}) })
detailedBolusInfo.insulin = patchmanager.bolusCurrent.nowBolus.injected.toDouble() detailedBolusInfo.insulin = patchManager.bolusCurrent.nowBolus.injected.toDouble()
patchmanager.addBolusToHistory(detailedBolusInfo) patchManager.addBolusToHistory(detailedBolusInfo)
disposable.dispose() disposable.dispose()
@ -329,37 +325,34 @@ class EopatchPumpPlugin @Inject constructor(
} else { } else {
// no bolus required, carb only treatment // no bolus required, carb only treatment
patchmanager.addBolusToHistory(detailedBolusInfo); patchManager.addBolusToHistory(detailedBolusInfo)
return PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(0.0) 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() { override fun stopBolusDelivering() {
patchmanager.stopNowBolus() mDisposables.add(patchManager.stopNowBolus()
.subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe { it -> .subscribe { it ->
rxBus.send(EventOverviewBolusProgress.apply { 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 { 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") aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - absoluteRate: ${absoluteRate.toFloat()}, durationInMinutes: ${durationInMinutes.toLong()}, enforceNew: $enforceNew")
if(patchmanager.patchState.isNormalBasalAct){ if(patchManager.patchState.isNormalBasalAct){
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
val tb = TempBasal.createAbsolute(durationInMinutes.toLong(), absoluteRate.toFloat()) val tb = TempBasal.createAbsolute(durationInMinutes.toLong(), absoluteRate.toFloat())
return patchmanager.startTempBasal(tb) return patchManager.startTempBasal(tb)
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.doOnSuccess { .doOnSuccess {
preferenceManager.getTempBasalManager().startedBasal = tb
preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis()
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil.now(), timestamp = dateUtil.now(),
rate = absoluteRate, rate = absoluteRate,
@ -372,7 +365,7 @@ class EopatchPumpPlugin @Inject constructor(
) )
aapsLogger.info(LTag.PUMP,"setTempBasalAbsolute - tbrCurrent:${readTBR()}") 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) .onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment("Internal error")) .comment("Internal error"))
.blockingGet() .blockingGet()
@ -384,15 +377,13 @@ class EopatchPumpPlugin @Inject constructor(
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { 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") 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() mLastDataTime = System.currentTimeMillis()
val tb = TempBasal.createPercent(durationInMinutes.toLong(), percent) val tb = TempBasal.createPercent(durationInMinutes.toLong(), percent)
return patchmanager.startTempBasal(tb) return patchManager.startTempBasal(tb)
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.doOnSuccess { .doOnSuccess {
preferenceManager.getTempBasalManager().startedBasal = tb
preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis()
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil.now(), timestamp = dateUtil.now(),
rate = percent.toDouble(), rate = percent.toDouble(),
@ -405,7 +396,7 @@ class EopatchPumpPlugin @Inject constructor(
) )
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - tbrCurrent:${readTBR()}") 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) .onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment("Internal error")) .comment("Internal error"))
.blockingGet() .blockingGet()
@ -418,7 +409,7 @@ class EopatchPumpPlugin @Inject constructor(
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
aapsLogger.info(LTag.PUMP,"setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes") aapsLogger.info(LTag.PUMP,"setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes")
return patchmanager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes)) return patchManager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes))
.doOnSuccess { .doOnSuccess {
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
pumpSync.syncExtendedBolusWithPumpId( pumpSync.syncExtendedBolusWithPumpId(
@ -431,7 +422,7 @@ class EopatchPumpPlugin @Inject constructor(
pumpSerial = serialNumber() 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) .onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false).bolusDelivered(0.0)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))) .comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.blockingGet() .blockingGet()
@ -445,14 +436,14 @@ class EopatchPumpPlugin @Inject constructor(
return PumpEnactResult(injector).success(true).enacted(false) return PumpEnactResult(injector).success(true).enacted(false)
} }
if (!patchmanager.patchState.isTempBasalActive) { if (!patchManager.patchState.isTempBasalActive) {
return if (pumpSync.expectedPumpState().temporaryBasal != null) { return if (pumpSync.expectedPumpState().temporaryBasal != null) {
PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true) PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)
}else }else
PumpEnactResult(injector).success(true).isTempCancel(true) PumpEnactResult(injector).success(true).isTempCancel(true)
} }
return patchmanager.stopTempBasal() return patchManager.stopTempBasal()
.doOnSuccess { .doOnSuccess {
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
aapsLogger.debug(LTag.PUMP,"cancelTempBasal - $it") aapsLogger.debug(LTag.PUMP,"cancelTempBasal - $it")
@ -466,15 +457,15 @@ class EopatchPumpPlugin @Inject constructor(
.doOnError{ .doOnError{
aapsLogger.error(LTag.PUMP,"cancelTempBasal() - $it") 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) .onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))) .comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.blockingGet() .blockingGet()
} }
override fun cancelExtendedBolus(): PumpEnactResult { override fun cancelExtendedBolus(): PumpEnactResult {
if(patchmanager.patchState.isExtBolusActive){ if(patchManager.patchState.isExtBolusActive){
return patchmanager.stopExtBolus() return patchManager.stopExtBolus()
.doOnSuccess { .doOnSuccess {
aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - success") aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - success")
mLastDataTime = System.currentTimeMillis() mLastDataTime = System.currentTimeMillis()
@ -485,7 +476,7 @@ class EopatchPumpPlugin @Inject constructor(
pumpSerial = serialNumber() 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) .onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error))) .comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
.blockingGet() .blockingGet()
@ -517,14 +508,14 @@ class EopatchPumpPlugin @Inject constructor(
} }
override fun serialNumber(): String { override fun serialNumber(): String {
return patchmanager.patchConfig.patchSerialNumber return patchManager.patchConfig.patchSerialNumber
} }
override val pumpDescription: PumpDescription override val pumpDescription: PumpDescription
get() = mPumpDescription get() = mPumpDescription
override fun shortStatus(veryShort: Boolean): String { override fun shortStatus(veryShort: Boolean): String {
if(patchmanager.isActivated) { if(patchManager.isActivated) {
var ret = "" var ret = ""
val activeTemp = pumpSync.expectedPumpState().temporaryBasal val activeTemp = pumpSync.expectedPumpState().temporaryBasal
if (activeTemp != null) if (activeTemp != null)
@ -534,7 +525,7 @@ class EopatchPumpPlugin @Inject constructor(
if (activeExtendedBolus != null) if (activeExtendedBolus != null)
ret += "Extended: ${activeExtendedBolus.amount} U\n" ret += "Extended: ${activeExtendedBolus.amount} U\n"
val reservoirStr = patchmanager.patchState.remainedInsulin.let { val reservoirStr = patchManager.patchState.remainedInsulin.let {
when { when {
it > 50f -> "50+ U" it > 50f -> "50+ U"
it < 1f -> "0 U" it < 1f -> "0 U"
@ -543,7 +534,7 @@ class EopatchPumpPlugin @Inject constructor(
} }
ret += "Reservoir: $reservoirStr" ret += "Reservoir: $reservoirStr"
ret += "Batt: ${patchmanager.patchState.batteryLevel()}" ret += "Battery: ${patchManager.patchState.batteryLevel()}"
return ret return ret
}else{ }else{
return "EOPatch is not enabled." return "EOPatch is not enabled."

View file

@ -4,7 +4,7 @@ import java.util.*
import java.util.function.Function import java.util.function.Function
object FloatFormatters { object FloatFormatters {
val INSULIN = Function<Number, String>{ value -> String.format(Locale.US, CommonUtils.insulinFormat(), value.toFloat()) } val INSULIN = Function<Number, String>{ value -> String.format(Locale.US, "%.2f", value.toFloat()) }
val FAT = Function<Number, String>{ value -> String.format(Locale.US, "%.1f", value.toFloat()) } val FAT = Function<Number, String>{ value -> String.format(Locale.US, "%.1f", value.toFloat()) }
val DURATION = Function<Number, String>{ value -> String.format(Locale.US, "%.1f", value.toFloat()) } val DURATION = Function<Number, String>{ value -> String.format(Locale.US, "%.1f", value.toFloat()) }
@ -16,19 +16,7 @@ object FloatFormatters {
return if (CommonUtils.isStringEmpty(suffix)) { return if (CommonUtils.isStringEmpty(suffix)) {
INSULIN.apply(value) INSULIN.apply(value)
} else { } else {
INSULIN.apply(value).toString() +" "+ suffix!! INSULIN.apply(value) +" "+ 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!!
} }
} }
@ -40,7 +28,7 @@ object FloatFormatters {
return if (CommonUtils.isStringEmpty(suffix)) { return if (CommonUtils.isStringEmpty(suffix)) {
DURATION.apply(value) DURATION.apply(value)
} else { } else {
DURATION.apply(value).toString() +" " + suffix!! DURATION.apply(value) +" " + suffix!!
} }
} }
} }

View file

@ -51,10 +51,6 @@ public class OsAlarmService extends Service {
public synchronized void startForeground() { public synchronized void startForeground() {
if (!foreground) { if (!foreground) {
//// CommonUtils.dispose(mNotificationDisposable);
// Notification builder = getNotification(this);
// startForeground(FOREGROUND_NOTIFICATION_ID, builder);
// startExerciseOrSleepMode(this);
foreground = true; foreground = true;
} }
} }

View file

@ -6,8 +6,6 @@ import android.os.SystemClock
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
import io.reactivex.* import io.reactivex.*
import io.reactivex.disposables.Disposable
import org.reactivestreams.Subscription
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -17,21 +15,10 @@ class RxAction @Inject constructor(
private val aapsSchedulers: AapsSchedulers, private val aapsSchedulers: AapsSchedulers,
private val aapsLogger: AAPSLogger private val aapsLogger: AAPSLogger
) { ) {
enum class RxVoid { enum class RxVoid {
INSTANCE INSTANCE
} }
class SilentObserver<T>(private val aapsLogger: AAPSLogger) : MaybeObserver<T>, SingleObserver<T>, Observer<T>, FlowableSubscriber<T> {
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) { private fun sleep(millis: Long) {
if (millis <= 0) if (millis <= 0)
return 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 @JvmOverloads
fun runOnMainThread(action: Runnable, delayMs: Long = 0) { 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) { { e ->
safeSingle(action, delayMs, aapsSchedulers.cpu).subscribe(SilentObserver(aapsLogger)) aapsLogger.error("SilentObserver.onError() ignore", e)
} })
@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)
} }
} }

View file

@ -9,45 +9,47 @@ import java.util.function.Function
import java.util.stream.Collectors import java.util.stream.Collectors
import java.util.stream.Stream import java.util.stream.Stream
enum class AlarmCode(defaultName: String, messageResId: Int) { enum class AlarmCode(messageResId: Int) {
A002("Empty reservoir", R.string.string_a002), A002(R.string.string_a002), //"Empty reservoir"
A003("Patch expired", R.string.string_a003), A003(R.string.string_a003), //"Patch expired"
A004("Occlusion", R.string.string_a004), A004(R.string.string_a004), //"Occlusion"
A005("Power on self test failure", R.string.string_a005), A005(R.string.string_a005), //"Power on self test failure"
A007("Inappropriate temperature", R.string.string_a007), A007(R.string.string_a007), //"Inappropriate temperature"
A016("Needle insertion Error", R.string.string_a016), A016(R.string.string_a016), //"Needle insertion Error"
A018("Patch battery Error", R.string.string_a018), A018(R.string.string_a018), //"Patch battery Error"
A019("Patch battery Error", R.string.string_a019), A019(R.string.string_a019), //"Patch battery Error"
A020("Patch activation Error", R.string.string_a020), A020(R.string.string_a020), //"Patch activation Error"
A022("Patch Error", R.string.string_a022), A022(R.string.string_a022), //"Patch Error"
A023("Patch Error", R.string.string_a023), A023(R.string.string_a023), //"Patch Error"
A034("Patch Error", R.string.string_a034), A034(R.string.string_a034), //"Patch Error"
A041("Patch Error", R.string.string_a041), A041(R.string.string_a041), //"Patch Error"
A042("Patch Error", R.string.string_a042), A042(R.string.string_a042), //"Patch Error"
A043("Patch Error", R.string.string_a043), A043(R.string.string_a043), //"Patch Error"
A044("Patch Error", R.string.string_a044), A044(R.string.string_a044), //"Patch Error"
A106("Patch Error", R.string.string_a106), A106(R.string.string_a106), //"Patch Error"
A107("Patch Error", R.string.string_a107), A107(R.string.string_a107), //"Patch Error"
A108("Patch Error", R.string.string_a108), A108(R.string.string_a108), //"Patch Error"
A116("Patch Error", R.string.string_a116), A116(R.string.string_a116), //"Patch Error"
A117("Patch Error", R.string.string_a117), A117(R.string.string_a117), //"Patch Error"
A118("Patch Error", R.string.string_a118), A118(R.string.string_a118), //"Patch Error"
B001("End of insulin suspend", R.string.string_b001), B001(R.string.string_b001), //"End of insulin suspend"
B003("Low reservoir", R.string.string_b003), B003(R.string.string_b003), //"Low reservoir"
B005("Patch operating life expired", R.string.string_b005), B005(R.string.string_b005), //"Patch operating life expired"
B006("Patch will expire soon", R.string.string_b006), B006(R.string.string_b006), //"Patch will expire soon"
B012("Incomplete Patch activation", R.string.string_b012), B012(R.string.string_b012), //"Incomplete Patch activation"
B018("Patch battery low", R.string.string_b018); 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 val alarmCategory: AlarmCategory
get() = when (type) { get() = when (type) {
TYPE_ALARM -> AlarmCategory.ALARM TYPE_ALARM -> AlarmCategory.ALARM
TYPE_ALERT -> AlarmCategory.ALERT TYPE_ALERT -> AlarmCategory.ALERT
else -> AlarmCategory.NONE else -> AlarmCategory.NONE
} }
val aeCode: Int val aeCode: Int
get() { get() {
when (type) { when (type) {
@ -57,13 +59,6 @@ enum class AlarmCode(defaultName: String, messageResId: Int) {
return -1 return -1
} }
val osAlarmId: Int
get() = (when (type) {
TYPE_ALARM -> 10000
TYPE_ALERT -> 20000
else -> 0
} + code ) * 1000 + 1
val isPatchOccurrenceAlert: Boolean val isPatchOccurrenceAlert: Boolean
get() = this == B003 || this == B005 || this == B006 || this == B018 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 == A023 || this == A034 || this == A041 || this == A042 || this == A043 || this == A044 || this == A106
|| this == A107 || this == A108 || this == A116 || this == A117 || this == A118 || this == A107 || this == A108 || this == A116 || this == A117 || this == A118
init {
type = name[0]
this.code = name.substring(1).toInt()
resId = messageResId
}
companion object { companion object {
const val TYPE_ALARM = 'A' const val TYPE_ALARM = 'A'
const val TYPE_ALERT = 'B' const val TYPE_ALERT = 'B'
@ -103,10 +92,10 @@ enum class AlarmCode(defaultName: String, messageResId: Int) {
fun getUri(alarmCode: AlarmCode): Uri { fun getUri(alarmCode: AlarmCode): Uri {
return Uri.Builder() return Uri.Builder()
.scheme(SCHEME) .scheme(SCHEME)
.authority("com.eoflow.eomapp") .authority("info.nightscout.androidaps")
.path(ALARM_KEY_PATH) .path(ALARM_KEY_PATH)
.appendQueryParameter(QUERY_CODE, alarmCode.name) .appendQueryParameter(QUERY_CODE, alarmCode.name)
.build(); .build()
} }
@JvmStatic @JvmStatic

View file

@ -26,10 +26,12 @@ import io.reactivex.Observable
import io.reactivex.Single import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.math.max
interface IAlarmManager { interface IAlarmManager {
fun init() fun init()
@ -54,6 +56,7 @@ class AlarmManager @Inject constructor() : IAlarmManager {
private lateinit var mAlarmProcess: AlarmProcess private lateinit var mAlarmProcess: AlarmProcess
private var compositeDisposable: CompositeDisposable = CompositeDisposable() private var compositeDisposable: CompositeDisposable = CompositeDisposable()
private var alarmDisposable: Disposable? = null
@Inject @Inject
fun onInit() { fun onInit() {
@ -61,27 +64,27 @@ class AlarmManager @Inject constructor() : IAlarmManager {
} }
override fun init(){ override fun init(){
EoPatchRxBus.listen(EventEoPatchAlarm::class.java) alarmDisposable = EoPatchRxBus.listen(EventEoPatchAlarm::class.java)
.map { it -> it.alarmCodes } .map { it.alarmCodes }
.doOnNext { aapsLogger.info(LTag.PUMP,"EventEoPatchAlarm Received") } .doOnNext { aapsLogger.info(LTag.PUMP,"EventEoPatchAlarm Received") }
.concatMap { .concatMap {
Observable.fromArray(it) Observable.fromArray(it)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread()) .subscribeOn(AndroidSchedulers.mainThread())
.doOnNext { alarmCodes -> .doOnNext { alarmCodes ->
alarmCodes.forEach { alarmCodes.forEach { alarmCode ->
aapsLogger.info(LTag.PUMP,"alarmCode: ${it.name}") aapsLogger.info(LTag.PUMP,"alarmCode: ${alarmCode.name}")
val valid = isValid(it) val valid = isValid(alarmCode)
if (valid) { if (valid) {
if (it.alarmCategory == AlarmCategory.ALARM || it == B012) { if (alarmCode.alarmCategory == AlarmCategory.ALARM || alarmCode == B012) {
showAlarmDialog(it) showAlarmDialog(alarmCode)
} else { } else {
showNotification(it) showNotification(alarmCode)
} }
updateState(it, AlarmState.FIRED) updateState(alarmCode, AlarmState.FIRED)
}else{ }else{
updateState(it, AlarmState.HANDLE) updateState(alarmCode, AlarmState.HANDLE)
} }
} }
} }
@ -92,17 +95,19 @@ class AlarmManager @Inject constructor() : IAlarmManager {
override fun restartAll() { override fun restartAll() {
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
val occuredAlarm = pm.getAlarms().occured.clone() as HashMap<AlarmCode, Alarms.AlarmItem> @Suppress("UNCHECKED_CAST")
val occurredAlarm= pm.getAlarms().occurred.clone() as HashMap<AlarmCode, Alarms.AlarmItem>
@Suppress("UNCHECKED_CAST")
val registeredAlarm = pm.getAlarms().registered.clone() as HashMap<AlarmCode, Alarms.AlarmItem> val registeredAlarm = pm.getAlarms().registered.clone() as HashMap<AlarmCode, Alarms.AlarmItem>
compositeDisposable.clear() compositeDisposable.clear()
if(occuredAlarm.isNotEmpty()){ if(occurredAlarm.isNotEmpty()){
EoPatchRxBus.publish(EventEoPatchAlarm(occuredAlarm.keys)) EoPatchRxBus.publish(EventEoPatchAlarm(occurredAlarm.keys))
} }
if(registeredAlarm.isNotEmpty()){ if(registeredAlarm.isNotEmpty()){
registeredAlarm.forEach { raEntry -> registeredAlarm.forEach { raEntry ->
compositeDisposable.add( 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() .subscribe()
) )
} }
@ -112,11 +117,11 @@ class AlarmManager @Inject constructor() : IAlarmManager {
private fun isValid(code: AlarmCode): Boolean{ private fun isValid(code: AlarmCode): Boolean{
return when(code){ return when(code){
A005, A016, A020, B012 -> { 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 pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning
} }
else -> { else -> {
aapsLogger.info(LTag.PUMP,"Is ${code} valid? ${pm.getPatchConfig().isActivated}") aapsLogger.info(LTag.PUMP,"Is $code valid? ${pm.getPatchConfig().isActivated}")
pm.getPatchConfig().isActivated pm.getPatchConfig().isActivated
} }
} }
@ -133,10 +138,10 @@ class AlarmManager @Inject constructor() : IAlarmManager {
} }
private fun showNotification(alarmCode: AlarmCode, timeOffset: Long = 0L){ 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) val notification = EONotification(Notification.EOELOW_PATCH_ALERTS + (alarmCode.aeCode + 10000), resourceHelper.gs(alarmCode.resId), Notification.URGENT)
notification.action(R.string.confirm) { notification.action(R.string.confirm) {
compositeDisposable.add(
Single.just(isValid(alarmCode)) Single.just(isValid(alarmCode))
.flatMap { isValid -> .flatMap { isValid ->
return@flatMap if(isValid) mAlarmProcess.doAction(context, alarmCode) return@flatMap if(isValid) mAlarmProcess.doAction(context, alarmCode)
@ -148,17 +153,17 @@ class AlarmManager @Inject constructor() : IAlarmManager {
}else{ }else{
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
} })
} }
notification.soundId = R.raw.error notification.soundId = R.raw.error
notification.date = occurredTimestamp notification.date = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.SECONDS.toMillis(timeOffset)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
} }
private fun updateState(alarmCode: AlarmCode, state: AlarmState){ private fun updateState(alarmCode: AlarmCode, state: AlarmState){
when(state){ when(state){
AlarmState.REGISTER -> pm.getAlarms().register(alarmCode, 0) 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) AlarmState.HANDLE -> pm.getAlarms().handle(alarmCode)
} }
pm.flushAlarms() pm.flushAlarms()

View file

@ -4,8 +4,7 @@ import android.content.Context
import android.content.DialogInterface 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.createIntentForCheckConnection
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForDiscarded 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.createIntentForCannulaInsertionError
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCanularInsertionError
import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode.* import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode.*
import android.content.Intent 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.R
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity 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.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.core.response.TemperatureResponse
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventDialog 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.event.EventProgressDialog
@ -40,13 +38,12 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
A002, A003, A004, A005, A018, A019, A002, A003, A004, A005, A018, A019,
A020, A022, A023, A034, A041, A042, A020, A022, A023, A034, A041, A042,
A043, A044, A106, A107, A108, A116, A043, A044, A106, A107, A108, A116,
A117, A118 -> patchDeactivationAction(context, true) A117, A118 -> patchDeactivationAction(context)
A007 -> inappropriateTemperatureAction(context) A007 -> inappropriateTemperatureAction(context)
A016 -> needleInsertionErrorAction(context) A016 -> needleInsertionErrorAction(context)
B003, B018 -> Single.just(IAlarmProcess.ALARM_HANDLED) B003, B018 -> Single.just(IAlarmProcess.ALARM_HANDLED)
B005, B006 -> Single.just(IAlarmProcess.ALARM_HANDLED) B005, B006 -> Single.just(IAlarmProcess.ALARM_HANDLED)
B012 -> 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) { private fun showCommunicationFailedDialog(onConfirmed: Runnable) {
var dialog = CommonDialog().apply { val dialog = CommonDialog().apply {
title = R.string.patch_communication_failed title = R.string.patch_communication_failed
message = R.string.patch_communication_check_helper_1 message = R.string.patch_communication_check_helper_1
positiveBtn = R.string.string_communication_check positiveBtn = R.string.string_communication_check
positiveListener = DialogInterface.OnClickListener { dialog, which -> positiveListener = DialogInterface.OnClickListener { _, _ ->
onConfirmed.run() onConfirmed.run()
dismiss() dismiss()
} }
@ -80,7 +77,7 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
Single.fromCallable { Single.fromCallable {
showCommunicationFailedDialog { showCommunicationFailedDialog {
startActivityWithSingleTop(context, startActivityWithSingleTop(context,
createIntentForCheckConnection(context, true, true)) createIntentForCheckConnection(context, goHomeAfterDiscard = true, forceDiscard = true))
} }
IAlarmProcess.ALARM_PAUSE IAlarmProcess.ALARM_PAUSE
} }
@ -95,28 +92,21 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
} }
} }
private fun patchDeactivationAction(context: Context, goHome: Boolean): Single<Int> { private fun patchDeactivationAction(context: Context): Single<Int> {
return actionWithPatchCheckConnection(context) { return actionWithPatchCheckConnection(context) {
rxBus.send(EventProgressDialog(true, R.string.string_in_progress)) rxBus.send(EventProgressDialog(true, R.string.string_in_progress))
patchManager.deactivate(6000, true) patchManager.deactivate(6000, true)
.doFinally { .doFinally {
rxBus.send(EventProgressDialog(false, R.string.string_in_progress)) 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) } .flatMap { Single.just(IAlarmProcess.ALARM_HANDLED) }
}
}
private fun changPatchAction(context: Context): Single<Int> {
return Single.fromCallable {
startActivityWithSingleTop(context, createIntentForChangePatch(context))
IAlarmProcess.ALARM_HANDLED
} }
} }
private fun needleInsertionErrorAction(context: Context): Single<Int> { private fun needleInsertionErrorAction(context: Context): Single<Int> {
return Single.fromCallable { return Single.fromCallable {
startActivityWithSingleTop(context, createIntentForCanularInsertionError(context)) startActivityWithSingleTop(context, createIntentForCannulaInsertionError(context))
IAlarmProcess.ALARM_HANDLED IAlarmProcess.ALARM_HANDLED
} }
} }

View file

@ -29,7 +29,7 @@ import javax.inject.Singleton
interface IAlarmRegistry { interface IAlarmRegistry {
fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean = false): Maybe<AlarmCode> fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean = false): Maybe<AlarmCode>
fun add(patchAeCodes: Set<PatchAeCode>) fun add(patchAeCodes: Set<PatchAeCode>)
fun remove(alarmKey: AlarmCode): Maybe<AlarmCode> fun remove(alarmCode: AlarmCode): Maybe<AlarmCode>
} }
@Singleton @Singleton
@ -60,29 +60,30 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
PatchLifecycle.SHUTDOWN -> { PatchLifecycle.SHUTDOWN -> {
val sources = ArrayList<Maybe<*>>() val sources = ArrayList<Maybe<*>>()
sources.add(Maybe.just(true)) sources.add(Maybe.just(true))
pm.getAlarms().occured.let{ pm.getAlarms().occurred.let{ occurredAlarms ->
if(it.isNotEmpty()){ if(occurredAlarms.isNotEmpty()){
it.keys.forEach { occurredAlarms.keys.forEach { alarmCode ->
sources.add( sources.add(
Maybe.just(it) Maybe.just(alarmCode)
.observeOn(aapsSchedulers.main) .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{ pm.getAlarms().registered.let{ registeredAlarms ->
if(it.isNotEmpty()){ if(registeredAlarms.isNotEmpty()){
it.keys.forEach { registeredAlarms.keys.forEach { alarmCode ->
sources.add(remove(it)) sources.add(remove(alarmCode))
} }
} }
} }
Maybe.concat(sources) compositeDisposable.add(Maybe.concat(sources)
.subscribe { .subscribe {
pm.getAlarms().clear() pm.getAlarms().clear()
pm.flushAlarms() pm.flushAlarms()
} }
)
} }
else -> Unit else -> Unit
@ -91,7 +92,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
} }
override fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean): Maybe<AlarmCode> { override fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean): Maybe<AlarmCode> {
if(pm.getAlarms().occured.containsKey(alarmCode)){ if(pm.getAlarms().occurred.containsKey(alarmCode)){
return Maybe.just(alarmCode) return Maybe.just(alarmCode)
}else { }else {
val triggerTimeMilli = System.currentTimeMillis() + triggerAfter val triggerTimeMilli = System.currentTimeMillis() + triggerAfter
@ -110,7 +111,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
Observable.fromIterable(patchAeCodes) Observable.fromIterable(patchAeCodes)
.filter{patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.getAeValue()) != null} .filter{patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.getAeValue()) != null}
.observeOn(AndroidSchedulers.mainThread()) .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)} .flatMapMaybe{aeCodeResponse -> add(AlarmCode.findByPatchAeCode(aeCodeResponse.getAeValue())!!,0L, true)}
.subscribe() .subscribe()
) )
@ -120,22 +121,21 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
return Maybe.fromCallable { return Maybe.fromCallable {
cancelOsAlarmInternal(alarmCode) cancelOsAlarmInternal(alarmCode)
val pendingIntent = createPendingIntent(alarmCode, 0) val pendingIntent = createPendingIntent(alarmCode, 0)
val now = System.currentTimeMillis()
mOsAlarmManager.setAlarmClock(AlarmClockInfo(triggerTime, pendingIntent), pendingIntent) mOsAlarmManager.setAlarmClock(AlarmClockInfo(triggerTime, pendingIntent), pendingIntent)
alarmCode alarmCode
} }
} }
override fun remove(alarmCode: AlarmCode): Maybe<AlarmCode> { override fun remove(alarmCode: AlarmCode): Maybe<AlarmCode> {
if(pm.getAlarms().registered.containsKey(alarmCode)) { return if(pm.getAlarms().registered.containsKey(alarmCode)) {
return cancelOsAlarms(alarmCode) cancelOsAlarms(alarmCode)
.doOnSuccess { .doOnSuccess {
pm.getAlarms().unregister(alarmCode) pm.getAlarms().unregister(alarmCode)
pm.flushAlarms() pm.flushAlarms()
} }
.map { integer: Int? -> alarmCode } .map { alarmCode }
}else{ }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)) 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)
} }
} }

View file

@ -21,6 +21,6 @@ class OnSafeClickListener(
} }
companion object { companion object {
// 중복 클릭 방지 시간 설정 // 중복 클릭 방지 시간 설정
private val MIN_CLICK_INTERVAL: Long = 1000 private const val MIN_CLICK_INTERVAL: Long = 1000
} }
} }

View file

@ -27,13 +27,6 @@ import io.reactivex.Observable;
import io.reactivex.Single; import io.reactivex.Single;
public interface IPatchManager { public interface IPatchManager {
/*
@Deprecated
static IPatchManager shared() {
return BaseApplication.instance.getDataComponent().getPatchManager();
}
*/
void init(); void init();
IPreferenceManager getPreferenceManager(); IPreferenceManager getPreferenceManager();
@ -74,8 +67,7 @@ public interface IPatchManager {
Single<ComboBolusStopResponse> stopComboBolus(); Single<ComboBolusStopResponse> stopComboBolus();
Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU, Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU, BolusExDuration exDuration);
BolusExDuration exDuration);
Single<? extends BolusResponse> startCalculatorBolus(DetailedBolusInfo detailedBolusInfo); Single<? extends BolusResponse> startCalculatorBolus(DetailedBolusInfo detailedBolusInfo);
@ -116,8 +108,6 @@ public interface IPatchManager {
Single<TemperatureResponse> getTemperature(); Single<TemperatureResponse> getTemperature();
void initBasalSchedule();
void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo); void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo);
void changeBuzzerSetting(); void changeBuzzerSetting();

View file

@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import com.polidea.rxandroidble2.exceptions.BleException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject; 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.DateUtil;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.shared.logging.AAPSLogger; import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP; import info.nightscout.shared.sharedPreferences.SP;
import io.reactivex.Observable; import io.reactivex.Observable;
import io.reactivex.Single; import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable; 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; import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
@ -81,29 +75,11 @@ public class PatchManager implements IPatchManager {
@Inject RxAction rxAction; @Inject RxAction rxAction;
private IPatchScanner patchScanner; private IPatchScanner patchScanner;
private CompositeDisposable mCompositeDisposable = new CompositeDisposable(); private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();
private Disposable mConnectingDisposable = null; private Disposable mConnectingDisposable = null;
@Inject @Inject
public PatchManager() { 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);
});
}
@Inject @Inject
void onInit() { void onInit() {
@ -155,7 +131,6 @@ public class PatchManager implements IPatchManager {
@Override @Override
public void init() { public void init() {
initBasalSchedule();
setConnection(); setConnection();
} }
@ -272,7 +247,27 @@ public class PatchManager implements IPatchManager {
} }
public Single<Boolean> patchActivation(long timeout) { public Single<Boolean> 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<BasalScheduleSetResponse> startBasal(NormalBasal basal) { public Single<BasalScheduleSetResponse> startBasal(NormalBasal basal) {
@ -305,8 +300,8 @@ public class PatchManager implements IPatchManager {
} }
public Single<? extends BolusResponse> startQuickBolus(float nowDoseU, public Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU,
float exDoseU, BolusExDuration exDuration) { BolusExDuration exDuration) {
return patchManager.startQuickBolus(nowDoseU, exDoseU, exDuration); return patchManager.startQuickBolus(nowDoseU, exDoseU, exDuration);
} }
@ -334,10 +329,6 @@ public class PatchManager implements IPatchManager {
return patchManager.deactivate(timeout, force); return patchManager.deactivate(timeout, force);
} }
public Single<PatchBooleanResponse> stopBuzz() {
return patchManager.stopBuzz();
}
public Single<PatchBooleanResponse> infoReminderSet(boolean infoReminder) { public Single<PatchBooleanResponse> infoReminderSet(boolean infoReminder) {
return patchManager.infoReminderSet(infoReminder); return patchManager.infoReminderSet(infoReminder);
} }
@ -361,14 +352,6 @@ public class PatchManager implements IPatchManager {
return patchScanner.scan(timeout); return patchScanner.scan(timeout);
} }
@Override
public void initBasalSchedule() {
if(pm.getNormalBasalManager().getNormalBasal() == null){
pm.getNormalBasalManager().setNormalBasal(profileFunction.getProfile());
pm.flushNormalBasalManager();
}
}
@Override @Override
public void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo) { public void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo) {
DetailedBolusInfo detailedBolusInfo = originalDetailedBolusInfo.copy(); DetailedBolusInfo detailedBolusInfo = originalDetailedBolusInfo.copy();
@ -399,12 +382,12 @@ public class PatchManager implements IPatchManager {
boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false); boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false);
if(pm.getPatchConfig().getInfoReminder() != buzzer) { if(pm.getPatchConfig().getInfoReminder() != buzzer) {
if (isActivated()) { if (isActivated()) {
infoReminderSet(buzzer) mCompositeDisposable.add(infoReminderSet(buzzer)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(patchBooleanResponse -> { .subscribe(patchBooleanResponse -> {
pm.getPatchConfig().setInfoReminder(buzzer); pm.getPatchConfig().setInfoReminder(buzzer);
pm.flushPatchConfig(); pm.flushPatchConfig();
}); }));
} else { } else {
pm.getPatchConfig().setInfoReminder(buzzer); pm.getPatchConfig().setInfoReminder(buzzer);
pm.flushPatchConfig(); pm.flushPatchConfig();
@ -414,18 +397,18 @@ public class PatchManager implements IPatchManager {
@Override @Override
public void changeReminderSetting() { 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); int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0);
PatchConfig pc = pm.getPatchConfig(); PatchConfig pc = pm.getPatchConfig();
if(pc.getLowReservoirAlertAmount() != doseUnit || pc.getPatchExpireAlertTime() != hours) { if(pc.getLowReservoirAlertAmount() != doseUnit || pc.getPatchExpireAlertTime() != hours) {
if (isActivated()) { if (isActivated()) {
setLowReservoir(doseUnit, hours) mCompositeDisposable.add(setLowReservoir(doseUnit, hours)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe(patchBooleanResponse -> { .subscribe(patchBooleanResponse -> {
pc.setLowReservoirAlertAmount(doseUnit); pc.setLowReservoirAlertAmount(doseUnit);
pc.setPatchExpireAlertTime(hours); pc.setPatchExpireAlertTime(hours);
pm.flushPatchConfig(); pm.flushPatchConfig();
}); }));
} else { } else {
pc.setLowReservoirAlertAmount(doseUnit); pc.setLowReservoirAlertAmount(doseUnit);
pc.setPatchExpireAlertTime(hours); pc.setPatchExpireAlertTime(hours);
@ -437,11 +420,9 @@ public class PatchManager implements IPatchManager {
@Override @Override
public void checkActivationProcess(){ public void checkActivationProcess(){
if(getPatchConfig().getLifecycleEvent().isSubStepRunning() if(getPatchConfig().getLifecycleEvent().isSubStepRunning()
&& !pm.getAlarms().isOccuring(AlarmCode.A005) && !pm.getAlarms().isOccurring(AlarmCode.A005)
&& !pm.getAlarms().isOccuring(AlarmCode.A020)) { && !pm.getAlarms().isOccurring(AlarmCode.A020)) {
rxAction.runOnMainThread(() -> { rxAction.runOnMainThread(() -> rxBus.send(new EventPatchActivationNotComplete()));
rxBus.send(new EventPatchActivationNotComplete());
});
} }
} }
} }

View file

@ -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.scan.IBleDevice;
import info.nightscout.androidaps.plugins.pump.eopatch.core.Patch; 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.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.BuzzerStop;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetTemperature; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetTemperature;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.PublicKeySend; 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.math.BigInteger;
import java.security.AlgorithmParameters; import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.KeyPair; import java.security.KeyPair;
@ -74,17 +72,13 @@ import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec; import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException; import java.security.spec.InvalidParameterSpecException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.crypto.KeyAgreement; import javax.crypto.KeyAgreement;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; 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.code.SettingKeys;
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventEoPatchAlarm; import info.nightscout.androidaps.plugins.pump.eopatch.event.EventEoPatchAlarm;
import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver; import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver;
@ -102,7 +96,7 @@ import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class PatchManagerImpl/* implements IPatchConstant*/ { public class PatchManagerImpl{
@Inject IPreferenceManager pm; @Inject IPreferenceManager pm;
@Inject Context context; @Inject Context context;
@Inject SP sp; @Inject SP sp;
@ -115,29 +109,23 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
@Inject NeedleSensingTask START_NEEDLE_CHECK; @Inject NeedleSensingTask START_NEEDLE_CHECK;
IBleDevice patch; IBleDevice patch;
HexString hexString;
private CompositeDisposable compositeDisposable; private final CompositeDisposable compositeDisposable;
private Observable<Intent> dateTimeChanged;
private static final long DEFAULT_API_TIME_OUT = 10; // SECONDS private static final long DEFAULT_API_TIME_OUT = 10; // SECONDS
private BuzzerStop BUZZER_STOP; private final BuzzerStop BUZZER_STOP;
private GetTemperature TEMPERATURE_GET; private final GetTemperature TEMPERATURE_GET;
private BasalStop BASAL_STOP; private final StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP;
private StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP; private final PublicKeySend PUBLIC_KEY_SET;
private PublicKeySend PUBLIC_KEY_SET; private final SequenceGet SEQUENCE_GET;
private SequenceGet SEQUENCE_GET;
@Inject @Inject
public PatchManagerImpl() { public PatchManagerImpl() {
compositeDisposable = new CompositeDisposable(); compositeDisposable = new CompositeDisposable();
hexString = new HexString();
BUZZER_STOP = new BuzzerStop(); BUZZER_STOP = new BuzzerStop();
TEMPERATURE_GET = new GetTemperature(); TEMPERATURE_GET = new GetTemperature();
BASAL_STOP = new BasalStop();
ALARM_ALERT_ERROR_BEEP_STOP = new StopAeBeep(); ALARM_ALERT_ERROR_BEEP_STOP = new StopAeBeep();
PUBLIC_KEY_SET = new PublicKeySend(); PUBLIC_KEY_SET = new PublicKeySend();
SEQUENCE_GET = new SequenceGet(); SEQUENCE_GET = new SequenceGet();
@ -153,7 +141,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
filter.addAction(ACTION_DATE_CHANGED); filter.addAction(ACTION_DATE_CHANGED);
filter.addAction(ACTION_TIMEZONE_CHANGED); filter.addAction(ACTION_TIMEZONE_CHANGED);
dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter); Observable<Intent> dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter);
compositeDisposable.add( compositeDisposable.add(
Observable.combineLatest(patch.observeConnected(), pm.observePatchLifeCycle(), Observable.combineLatest(patch.observeConnected(), pm.observePatchLifeCycle(),
@ -178,7 +166,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
compositeDisposable.add( compositeDisposable.add(
patch.observeConnected() patch.observeConnected()
.doOnNext(it -> onPatchConnected(it)) .doOnNext(this::onPatchConnected)
.subscribe()); .subscribe());
compositeDisposable.add( compositeDisposable.add(
@ -190,22 +178,22 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
compositeDisposable.add( compositeDisposable.add(
EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class) EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class)
.filter(it -> it.isFirst()) .filter(EventEoPatchAlarm::isFirst)
.filter(it -> !pm.getPatchConfig().isDeactivated()) .filter(it -> !pm.getPatchConfig().isDeactivated())
.filter(it -> patch.getConnectionState().isConnected()) .filter(it -> patch.getConnectionState().isConnected())
.concatMapIterable(it -> it.getAlarmCodes()) .concatMapIterable(EventEoPatchAlarm::getAlarmCodes)
.filter(it -> it.isPatchOccurrenceAlert()) .filter(AlarmCode::isPatchOccurrenceAlert)
.flatMap(it -> stopAeBeep(it.getAeCode()).toObservable()) .flatMap(it -> stopAeBeep(it.getAeCode()).toObservable())
.subscribe() .subscribe()
); );
compositeDisposable.add( compositeDisposable.add(
EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class) EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class)
.filter(it -> it.isFirst()) .filter(EventEoPatchAlarm::isFirst)
.filter(it -> !pm.getPatchConfig().isDeactivated()) .filter(it -> !pm.getPatchConfig().isDeactivated())
.filter(it -> patch.getConnectionState().isConnected()) .filter(it -> patch.getConnectionState().isConnected())
.concatMapIterable(it -> it.getAlarmCodes()) .concatMapIterable(EventEoPatchAlarm::getAlarmCodes)
.filter(it -> it.isPatchOccurrenceAlarm()) .filter(AlarmCode::isPatchOccurrenceAlarm)
.flatMap(it -> pauseBasalImpl(0.0f, System.currentTimeMillis(), it).toObservable()) .flatMap(it -> pauseBasalImpl(0.0f, System.currentTimeMillis(), it).toObservable())
.subscribe() .subscribe()
); );
@ -218,7 +206,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
private void onPatchConnected(boolean connected) { private void onPatchConnected(boolean connected) {
boolean activated = pm.getPatchConfig().isActivated(); boolean activated = pm.getPatchConfig().isActivated();
boolean useEncryption = pm.getPatchConfig().getSharedKey() != null; 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); int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0);
boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false); boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false);
PatchConfig pc = pm.getPatchConfig(); PatchConfig pc = pm.getPatchConfig();
@ -256,7 +244,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
.subscribe()); .subscribe());
} }
if(connected == false && activated == true){ if(!connected && activated){
pm.getPatchConfig().updatetDisconnectedTime(); pm.getPatchConfig().updatetDisconnectedTime();
} }
} }
@ -266,13 +254,15 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
patch.observeAlarmNotification() patch.observeAlarmNotification()
.subscribe( .subscribe(
this::onAlarmNotification, this::onAlarmNotification,
throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage()) throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage() != null ?
throwable.getMessage() : "AlarmNotification observation error")
), ),
patch.observeInfoNotification() patch.observeInfoNotification()
.filter(state -> pm.getPatchConfig().isActivated()) .filter(state -> pm.getPatchConfig().isActivated())
.subscribe( .subscribe(
this::onInfoNotification, 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()); consumer.accept(pm.getPatchConfig());
if (needSave) { if (needSave) {
pm.flushPatchConfig(); pm.flushPatchConfig();
} else {
pm.flushPatchConfig();
} }
} }
} }
@ -304,13 +292,10 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal(); NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal();
if (normalBasal != null) {
// 아래 코드를 실행하면 isDoseUChanged false 된다.
if(normalBasal.updateNormalBasalIndex()) { if(normalBasal.updateNormalBasalIndex()) {
pm.flushNormalBasalManager(); pm.flushNormalBasalManager();
} }
} }
}
public void connect() { public void connect() {
@ -363,7 +348,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
* Activation Process task #4 NEEDLE SENSING * Activation Process task #4 NEEDLE SENSING
* Fragment: fragment_patch_rotate_knob * Fragment: fragment_patch_rotate_knob
*/ */
public Single<Boolean> checkNeedleSensing(long timeout) { //TODO: Timeout 추가? public Single<Boolean> checkNeedleSensing(long timeout) {
return START_NEEDLE_CHECK.start() return START_NEEDLE_CHECK.start()
.timeout(timeout, TimeUnit.MILLISECONDS); .timeout(timeout, TimeUnit.MILLISECONDS);
} }
@ -398,7 +383,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
public Single<BasalScheduleSetResponse> startBasal(NormalBasal basal) { public Single<BasalScheduleSetResponse> startBasal(NormalBasal basal) {
return startNormalBasalTask.start(basal, false) return startNormalBasalTask.start(basal)
.timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS); .timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS);
} }
@ -427,22 +412,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
return pauseBasalTask.pause(pauseDurationHour, alarmOccurredTime, alarmCode); return pauseBasalTask.pause(pauseDurationHour, alarmOccurredTime, alarmCode);
} }
private Single<BasalStopResponse> 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] // IPatchManager interface [TEMP BASAL]
//============================================================================================== //==============================================================================================
@ -504,34 +473,34 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
return stopComboBolusTask.stop().timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS); return stopComboBolusTask.stop().timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS);
} }
private Single<? extends BaseResponse> stopNowAndExtBolus() { // private Single<? extends BaseResponse> stopNowAndExtBolus() {
//
boolean nowActive = pm.getPatchState().isNowBolusActive(); // boolean nowActive = pm.getPatchState().isNowBolusActive();
boolean extActive = pm.getPatchState().isExtBolusActive(); // boolean extActive = pm.getPatchState().isExtBolusActive();
//
if (nowActive && extActive) { // if (nowActive && extActive) {
return stopComboBolus(); // return stopComboBolus();
} else if (nowActive) { // } else if (nowActive) {
return stopNowBolus(); // return stopNowBolus();
} else if (extActive) { // } else if (extActive) {
return stopExtBolus(); // return stopExtBolus();
} // }
//
return Single.just(new PatchBooleanResponse(true)); // return Single.just(new PatchBooleanResponse(true));
} // }
//============================================================================================== //==============================================================================================
// IPatchManager implementation [BOLUS] // IPatchManager implementation [BOLUS]
//============================================================================================== //==============================================================================================
public void readBolusStatusFromNotification(InfoNotification noti) { public void readBolusStatusFromNotification(InfoNotification infoNotification) {
if (noti.isBolusRegAct()) { if (infoNotification.isBolusRegAct()) {
BolusCurrent bolusCurrent = pm.getBolusCurrent(); BolusCurrent bolusCurrent = pm.getBolusCurrent();
Arrays.asList(BolusType.NOW, BolusType.EXT).forEach(type -> { Arrays.asList(BolusType.NOW, BolusType.EXT).forEach(type -> {
if (noti.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요. if (infoNotification.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요.
int injectedPumpCount = noti.getInjected(type); int injectedPumpCount = infoNotification.getInjected(type);
int remainPumpCount = noti.getRemain(type); int remainPumpCount = infoNotification.getRemain(type);
bolusCurrent.updateBolusFromPatch(type, injectedPumpCount, remainPumpCount); bolusCurrent.updateBolusFromPatch(type, injectedPumpCount, remainPumpCount);
} }
}); });
@ -547,29 +516,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
return deactivateTask.run(force, timeout); return deactivateTask.run(force, timeout);
} }
public Single<? extends BaseResponse> stopAll(){
List<Single<? extends BaseResponse>> 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<PatchBooleanResponse> stopBuzz() {
return BUZZER_STOP.stop();
}
@Inject @Inject
InfoReminderTask infoReminderTask; InfoReminderTask infoReminderTask;
@ -677,8 +623,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
ECGenParameterSpec ecSpec_named = new ECGenParameterSpec(SECP256R1); ECGenParameterSpec ecSpec_named = new ECGenParameterSpec(SECP256R1);
KeyPairGenerator kpg = KeyPairGenerator.getInstance(EC); KeyPairGenerator kpg = KeyPairGenerator.getInstance(EC);
kpg.initialize(ecSpec_named); kpg.initialize(ecSpec_named);
KeyPair pair = kpg.generateKeyPair(); return kpg.generateKeyPair();
return pair;
}); });
} }
@ -729,8 +674,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
} }
public static ECPublicKey rawToEncodedECPublicKey(String curveName, byte[] rawBytes) throws public static ECPublicKey rawToEncodedECPublicKey(String curveName, byte[] rawBytes) throws
NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException {
InvalidAlgorithmParameterException {
KeyFactory kf = KeyFactory.getInstance(EC); KeyFactory kf = KeyFactory.getInstance(EC);
int mid = rawBytes.length / 2; int mid = rawBytes.length / 2;
byte[] x = Arrays.copyOfRange(rawBytes, 0, mid); byte[] x = Arrays.copyOfRange(rawBytes, 0, mid);
@ -740,7 +684,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
} }
public static ECParameterSpec ecParameterSpecForCurve(String curveName) throws public static ECParameterSpec ecParameterSpecForCurve(String curveName) throws
NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException { NoSuchAlgorithmException, InvalidParameterSpecException {
AlgorithmParameters params = AlgorithmParameters.getInstance(EC); AlgorithmParameters params = AlgorithmParameters.getInstance(EC);
params.init(new ECGenParameterSpec(curveName)); params.init(new ECGenParameterSpec(curveName));
return params.getParameterSpec(ECParameterSpec.class); return params.getParameterSpec(ECParameterSpec.class);
@ -755,7 +699,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
return keyAgreement.generateSecret(); return keyAgreement.generateSecret();
} catch (InvalidKeyException | NoSuchAlgorithmException e) { } catch (InvalidKeyException | NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
return null; return null;
} }
@ -768,8 +711,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
private static final Scheduler SS = Schedulers.single(); private static final Scheduler SS = Schedulers.single();
public BleConnectionState getPatchConnectionState() { public BleConnectionState getPatchConnectionState() {
BleConnectionState result = patch.getConnectionState(); return patch.getConnectionState();
return result;
} }
public Observable<BleConnectionState> observePatchConnectionState() { public Observable<BleConnectionState> observePatchConnectionState() {
@ -780,14 +722,3 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
patch.updateMacAddress(mac, b); patch.updateMacAddress(mac, b);
} }
} }
class AlarmFiredEventInfo
{
public AlarmCode code;
public long createTimestamp;
public AlarmFiredEventInfo(AlarmCode code, long createTimestamp) {
this.code = code;
this.createTimestamp = createTimestamp;
}
}

View file

@ -52,7 +52,7 @@ public class PatchStateManager {
final PatchState oldState = pm.getPatchState(); final PatchState oldState = pm.getPatchState();
int diff = newState.currentTime() - oldState.currentTime(); int diff = newState.currentTime() - oldState.currentTime();
if (0 <= diff && diff < 10) { // TODO 상수로 변경. if (0 <= diff && diff < 10) {
/* 10초 안에 같은 PatchState update 시 skip */ /* 10초 안에 같은 PatchState update 시 skip */
if (oldState.equalState(newState)) { if (oldState.equalState(newState)) {
return; return;
@ -267,8 +267,7 @@ public class PatchStateManager {
public synchronized void onBasalStarted(NormalBasal basal, long timestamp) { public synchronized void onBasalStarted(NormalBasal basal, long timestamp) {
if (basal != null) { if (basal != null) {
pm.getNormalBasalManager().updateBasalStarted(); pm.getNormalBasalManager().updateBasalStarted();
basal.updateNormalBasalIndex();
basal.updateNormalBasalIndex(); //normal basal index를 업데이트하여 basal change 이력이 발생하는것을 방지(df_356)
} }
pm.getPatchConfig().updateNormalBasalStarted(); // updateNormalBasalStarted 동일함... pm.getPatchConfig().updateNormalBasalStarted(); // updateNormalBasalStarted 동일함...

View file

@ -148,12 +148,12 @@ class PreferenceManager @Inject constructor(): IPreferenceManager {
aapsLogger.error(LTag.PUMP, ex.message?:"Alarms load error") aapsLogger.error(LTag.PUMP, ex.message?:"Alarms load error")
} }
aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: ${mPatchConfig}") aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: $mPatchConfig")
aapsLogger.info(LTag.PUMP,"Load from PatchState preference: ${mPatchState}") aapsLogger.info(LTag.PUMP,"Load from PatchState preference: $mPatchState")
aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: ${mBolusCurrent}") aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: $mBolusCurrent")
aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: ${mNormalBasalMgr}") aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: $mNormalBasalMgr")
aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: ${mTempBasalMgr}") aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: $mTempBasalMgr")
aapsLogger.info(LTag.PUMP,"Load from Alarms preference: ${mAlarms}") aapsLogger.info(LTag.PUMP,"Load from Alarms preference: $mAlarms")
initialized = true initialized = true
} }
@ -179,9 +179,8 @@ class PreferenceManager @Inject constructor(): IPreferenceManager {
flushBolusCurrent() flushBolusCurrent()
mTempBasalMgr.clear() mTempBasalMgr.clear()
flushTempBasalManager() flushTempBasalManager()
// mAlarms.clear()
// flushAlarms()
} }
else -> Unit
} }
} }

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
import info.nightscout.shared.logging.LTag; 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.api.SetKey;
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse; import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse;
@ -17,15 +16,11 @@ import io.reactivex.schedulers.Schedulers;
public class ActivateTask extends TaskBase { public class ActivateTask extends TaskBase {
@Inject StartNormalBasalTask startBasalTask; @Inject StartNormalBasalTask startBasalTask;
private SetKey SET_KEY; private final SetKey SET_KEY = new SetKey();
private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
@Inject @Inject
public ActivateTask() { public ActivateTask() {
super(TaskFunc.ACTIVATE); super(TaskFunc.ACTIVATE);
SET_KEY = new SetKey();
BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig();
} }
public Single<Boolean> start() { public Single<Boolean> start() {
@ -35,9 +30,9 @@ public class ActivateTask extends TaskBase {
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.observeOn(Schedulers.io()).doOnSuccess(this::onActivated) .observeOn(Schedulers.io()).doOnSuccess(this::onActivated)
.flatMap(v -> startBasalTask.start(enabled, false)) .flatMap(v -> startBasalTask.start(enabled))
.map(BaseResponse::isSuccess) .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) { private void onActivated(BaseResponse response) {

View file

@ -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.AppConstant;
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType; 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; import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent;
abstract class BolusTask extends TaskBase { abstract class BolusTask extends TaskBase {
@ -16,17 +17,17 @@ abstract class BolusTask extends TaskBase {
boolean now = (nowDoseU > 0); boolean now = (nowDoseU > 0);
boolean ext = (exDoseU > 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 endTimestamp = startTimestamp + getPumpDuration(nowDoseU);
long nowHistoryID = 1L; //record no long nowHistoryID = 1L; //record no
long exStartTimestamp = 0; long exStartTimestamp;
if (now) { if (now) {
pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp); pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp);
} }
if (ext) { if (ext) {
long estimatedExStartTimestamp = 0; long estimatedExStartTimestamp;
if (now) { if (now) {
exStartTimestamp = 0; exStartTimestamp = 0;
@ -46,12 +47,8 @@ abstract class BolusTask extends TaskBase {
} }
public void onCalcBolusStarted(float nowDoseU, float correctionBolus, float exDoseU, public void onCalcBolusStarted(float nowDoseU) {
BolusExDuration exDuration) {
boolean now = (nowDoseU > 0); boolean now = (nowDoseU > 0);
boolean ext = (exDoseU > 0);
long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720 long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720
long endTimestamp = startTimestamp + getPumpDuration(nowDoseU); long endTimestamp = startTimestamp + getPumpDuration(nowDoseU);
@ -62,24 +59,6 @@ abstract class BolusTask extends TaskBase {
pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp); 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(); pm.flushBolusCurrent();
} }
@ -88,12 +67,13 @@ abstract class BolusTask extends TaskBase {
} }
public void updateNowBolusStopped(int injected, long suspendedTimestamp) { public void updateNowBolusStopped(int injected, long suspendedTimestamp) {
BolusCurrent bolusCurrent = pm.getBolusCurrent(); BolusCurrent bolusCurrent = pm.getBolusCurrent();
long nowID = bolusCurrent.historyId(BolusType.NOW); long nowID = bolusCurrent.historyId(BolusType.NOW);
if (nowID > 0 && !bolusCurrent.endTimeSynced(BolusType.NOW)) { if (nowID > 0 && !bolusCurrent.endTimeSynced(BolusType.NOW)) {
// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P); float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P);
bolusCurrent.getNowBolus().setInjected(injectedDoseU);
bolusCurrent.getNowBolus().setEndTimestamp(stopTime);
bolusCurrent.setEndTimeSynced(BolusType.NOW, true); bolusCurrent.setEndTimeSynced(BolusType.NOW, true);
pm.flushBolusCurrent(); pm.flushBolusCurrent();
} }
@ -107,8 +87,10 @@ abstract class BolusTask extends TaskBase {
BolusCurrent bolusCurrent = pm.getBolusCurrent(); BolusCurrent bolusCurrent = pm.getBolusCurrent();
long extID = bolusCurrent.historyId(BolusType.EXT); long extID = bolusCurrent.historyId(BolusType.EXT);
if (extID > 0 && !bolusCurrent.endTimeSynced(BolusType.EXT)) { if (extID > 0 && !bolusCurrent.endTimeSynced(BolusType.EXT)) {
// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis(); long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P); float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P);
bolusCurrent.getExtBolus().setInjected(injectedDoseU);
bolusCurrent.getExtBolus().setEndTimestamp(stopTime);
bolusCurrent.setEndTimeSynced(BolusType.EXT, true); bolusCurrent.setEndTimeSynced(BolusType.EXT, true);
pm.flushBolusCurrent(); pm.flushBolusCurrent();
} }
@ -116,8 +98,8 @@ abstract class BolusTask extends TaskBase {
private long getPumpDuration(float doseU) { private long getPumpDuration(float doseU) {
if (doseU > 0) { if (doseU > 0) {
long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli(); //todo long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli();
return (long) ((doseU / AppConstant.Companion.getBOLUS_UNIT_STEP()) * pumpDuration); return (long) ((doseU / AppConstant.BOLUS_UNIT_STEP) * pumpDuration);
} }
return 0L; return 0L;
} }

View file

@ -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.core.code.BolusType;
import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus; import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject; 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.core.api.DeActivation;
import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent; 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.PatchLifecycleEvent;
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState;
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal; import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal;
import io.reactivex.Observable; import io.reactivex.Observable;
import io.reactivex.Single; import io.reactivex.Single;
@ -22,14 +20,10 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class DeactivateTask extends TaskBase { public class DeactivateTask extends TaskBase {
@Inject StopBasalTask stopBasalTask;
@Inject IPreferenceManager pm;
@Inject private final DeActivation DEACTIVATION;
StopBasalTask stopBasalTask;
@Inject
IPreferenceManager pm;
private DeActivation DEACTIVATION;
@Inject @Inject
public DeactivateTask() { public DeactivateTask() {
@ -44,16 +38,16 @@ public class DeactivateTask extends TaskBase {
DEACTIVATION.start() DEACTIVATION.start()
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.doOnSuccess(response -> onDeactivated(false))) .doOnSuccess(response -> onDeactivated()))
.map(response -> DeactivationStatus.of(response.isSuccess(), forced)) .map(response -> DeactivationStatus.of(response.isSuccess(), forced))
.firstOrError() .firstOrError()
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())) .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "DeactivateTask error"))
.onErrorResumeNext(e -> { .onErrorResumeNext(e -> {
if (forced) { if (forced) {
try { try {
onDeactivated(true); onDeactivated();
} catch (Exception t) { } 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(); return isReady();
} }
/* Schedulers.io() */ private void onDeactivated() {
private void onDeactivated(boolean forced) throws SQLException {
synchronized (lock) { synchronized (lock) {
patch.updateMacAddress(null, false); patch.updateMacAddress(null, false);
if (pm.getPatchConfig().getLifecycleEvent().isShutdown()) { if (pm.getPatchConfig().getLifecycleEvent().isShutdown()) {
return; return;
} }
cleanUpRepository(); cleanUpRepository();
pm.getNormalBasalManager().updateForDeactivation(); pm.getNormalBasalManager().updateForDeactivation();
pm.updatePatchLifeCycle(PatchLifecycleEvent.createShutdown()); pm.updatePatchLifeCycle(PatchLifecycleEvent.createShutdown());
} }
} }
private void cleanUpRepository() throws SQLException { private void cleanUpRepository() {
updateNowBolusStopped(); updateNowBolusStopped();
updateExtBolusStopped(); updateExtBolusStopped();
updateTempBasalStopped(); updateTempBasalStopped();
} }
private void updateTempBasalStopped() throws SQLException { private void updateTempBasalStopped() {
TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal(); TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal();
if (tempBasal != null) { if (tempBasal != null) {
@ -106,7 +96,6 @@ public class DeactivateTask extends TaskBase {
} }
} }
/* copied from BolusTask. */
private void updateNowBolusStopped() { private void updateNowBolusStopped() {
BolusCurrent bolusCurrent = pm.getBolusCurrent(); BolusCurrent bolusCurrent = pm.getBolusCurrent();
long nowID = bolusCurrent.historyId(BolusType.NOW); long nowID = bolusCurrent.historyId(BolusType.NOW);
@ -117,7 +106,6 @@ public class DeactivateTask extends TaskBase {
} }
} }
/* copied from BolusTask. */
private void updateExtBolusStopped() { private void updateExtBolusStopped() {
BolusCurrent bolusCurrent = pm.getBolusCurrent(); BolusCurrent bolusCurrent = pm.getBolusCurrent();
long extID = bolusCurrent.historyId(BolusType.EXT); long extID = bolusCurrent.historyId(BolusType.EXT);

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
import info.nightscout.shared.logging.LTag; import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus; 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.alarm.IAlarmRegistry;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetErrorCodes; 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 info.nightscout.androidaps.plugins.pump.eopatch.core.response.AeCodeResponse;
import io.reactivex.Single; import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
@Singleton @Singleton
public class FetchAlarmTask extends TaskBase { public class FetchAlarmTask extends TaskBase {
@Inject RxBus rxBus;
@Inject IAlarmRegistry alarmRegistry;
@Inject private final GetErrorCodes ALARM_ALERT_ERROR_CODE_GET;
RxBus rxBus;
@Inject
IAlarmRegistry alarmRegistry;
private GetErrorCodes ALARM_ALERT_ERROR_CODE_GET;
@Inject @Inject
public FetchAlarmTask() { public FetchAlarmTask() {
@ -38,7 +32,7 @@ public class FetchAlarmTask extends TaskBase {
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(aeCodeResponse -> alarmRegistry.add(aeCodeResponse.getAlarmCodes())) .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() { public synchronized void enqueue() {

View file

@ -26,17 +26,15 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class GetPatchInfoTask extends TaskBase { public class GetPatchInfoTask extends TaskBase {
@Inject UpdateConnectionTask updateConnectionTask;
@Inject private final SetGlobalTime SET_GLOBAL_TIME;
UpdateConnectionTask updateConnectionTask; private final GetSerialNumber SERIAL_NUMBER_GET;
private final GetLOT LOT_NUMBER_GET;
private SetGlobalTime SET_GLOBAL_TIME; private final GetFirmwareVersion FIRMWARE_VERSION_GET;
private GetSerialNumber SERIAL_NUMBER_GET; private final GetWakeUpTime WAKE_UP_TIME_GET;
private GetLOT LOT_NUMBER_GET; private final GetPumpDuration PUMP_DURATION_GET;
private GetFirmwareVersion FIRMWARE_VERSION_GET; private final GetModelName GET_MODEL_NAME;
private GetWakeUpTime WAKE_UP_TIME_GET;
private GetPumpDuration PUMP_DURATION_GET;
private GetModelName GET_MODEL_NAME;
@Inject @Inject
public GetPatchInfoTask() { public GetPatchInfoTask() {
@ -61,17 +59,16 @@ public class GetPatchInfoTask extends TaskBase {
PUMP_DURATION_GET.get().doOnSuccess(this::onPumpDurationResponse), PUMP_DURATION_GET.get().doOnSuccess(this::onPumpDurationResponse),
GET_MODEL_NAME.get().doOnSuccess(this::onModelNameResponse))) GET_MODEL_NAME.get().doOnSuccess(this::onModelNameResponse)))
.map(BaseResponse::isSuccess) .map(BaseResponse::isSuccess)
.filter(v -> !v) // fail false 아래로 내려간다. .filter(v -> !v)
.first(true); .first(true);
return isReady() return isReady()
.concatMapSingle(it -> tasks) .concatMapSingle(it -> tasks)
.firstOrError() .firstOrError()
// .flatMap(v -> updateConnectionTask.update()).map(v -> true)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.doOnSuccess(this::onPatchWakeupSuccess) .doOnSuccess(this::onPatchWakeupSuccess)
.doOnError(this::onPatchWakeupFailed) .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) { private void onSerialNumberResponse(SerialNumberResponse v) {
@ -91,23 +88,21 @@ public class GetPatchInfoTask extends TaskBase {
} }
private void onPumpDurationResponse(PumpDurationResponse v) { private void onPumpDurationResponse(PumpDurationResponse v) {
pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100); // 0.1 단위 pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100L);
pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100); pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100L);
pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100); pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100L);
} }
private void onModelNameResponse(ModelNameResponse modelNameResponse) { private void onModelNameResponse(ModelNameResponse modelNameResponse) {
pm.getPatchConfig().setPatchModelName(modelNameResponse.getModelName()); pm.getPatchConfig().setPatchModelName(modelNameResponse.getModelName());
} }
/* Schedulers.io() */
private void onPatchWakeupSuccess(Boolean result) { private void onPatchWakeupSuccess(Boolean result) {
synchronized (lock) { synchronized (lock) {
pm.flushPatchConfig(); pm.flushPatchConfig();
} }
} }
/* Schedulers.io() */
private void onPatchWakeupFailed(Throwable e) { private void onPatchWakeupFailed(Throwable e) {
patch.setSeq(-1); patch.setSeq(-1);
pm.getPatchConfig().updateDeactivated(); pm.getPatchConfig().updateDeactivated();

View file

@ -14,11 +14,9 @@ import io.reactivex.Single;
@Singleton @Singleton
public class InfoReminderTask extends TaskBase { public class InfoReminderTask extends TaskBase {
@Inject IPreferenceManager pm;
@Inject private final InfoReminderSet INFO_REMINDER_SET;
IPreferenceManager pm;
private InfoReminderSet INFO_REMINDER_SET;
@Inject @Inject
public InfoReminderTask() { public InfoReminderTask() {
@ -32,7 +30,7 @@ public class InfoReminderTask extends TaskBase {
.concatMapSingle(v -> INFO_REMINDER_SET.set(infoReminder)) .concatMapSingle(v -> INFO_REMINDER_SET.set(infoReminder))
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .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() { public synchronized void enqueue() {

View file

@ -6,8 +6,6 @@ import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.UserEntryLogger; import info.nightscout.androidaps.logging.UserEntryLogger;
import info.nightscout.androidaps.utils.userEntry.UserEntryMapper; import info.nightscout.androidaps.utils.userEntry.UserEntryMapper;
import info.nightscout.shared.logging.LTag; import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatchConstant;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject; import javax.inject.Inject;
@ -15,11 +13,8 @@ import javax.inject.Singleton;
import info.nightscout.androidaps.interfaces.CommandQueue; import info.nightscout.androidaps.interfaces.CommandQueue;
import info.nightscout.shared.logging.AAPSLogger; 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.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.core.response.PatchInternalSuspendTimeResponse;
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
@ -29,47 +24,44 @@ import io.reactivex.subjects.BehaviorSubject;
@Singleton @Singleton
public class InternalSuspendedTask extends BolusTask { public class InternalSuspendedTask extends BolusTask {
@Inject CommandQueue commandQueue; @Inject CommandQueue commandQueue;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject PumpSync pumpSync; @Inject PumpSync pumpSync;
@Inject UserEntryLogger uel; @Inject UserEntryLogger uel;
private GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET; private final GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET;
private BolusStop BOLUS_STOP; private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP; private final BehaviorSubject<Boolean> extendedBolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create(); private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
@Inject @Inject
public InternalSuspendedTask() { public InternalSuspendedTask() {
super(TaskFunc.INTERNAL_SUSPEND); super(TaskFunc.INTERNAL_SUSPEND);
INTERNAL_SUSPEND_TIME_GET = new GetInternalSuspendTime(); INTERNAL_SUSPEND_TIME_GET = new GetInternalSuspendTime();
BOLUS_STOP = new BolusStop();
TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop();
} }
private Observable<Boolean> getBolusSebject(){ private Observable<Boolean> getBolusSubject(){
return bolusCheckSubject.hide(); return bolusCheckSubject.hide();
} }
private Observable<Boolean> getExbolusSebject(){ private Observable<Boolean> getExtendedBolusSubject(){
return exbolusCheckSubject.hide(); return extendedBolusCheckSubject.hide();
} }
private Observable<Boolean> getBasalSebject(){ private Observable<Boolean> getBasalSubject(){
return basalCheckSubject.hide(); return basalCheckSubject.hide();
} }
public Single<Long> start(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) { public Single<Long> start(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) {
PatchState patchState = pm.getPatchState();
if (isNowBolusActive || isExtBolusActive) { if (isNowBolusActive || isExtBolusActive) {
enqueue(TaskFunc.READ_BOLUS_FINISH_TIME); enqueue(TaskFunc.READ_BOLUS_FINISH_TIME);
} }
if (isTempBasalActive) {
enqueue(TaskFunc.READ_TEMP_BASAL_FINISH_TIME);
}
if (commandQueue.isRunning(Command.CommandType.BOLUS)) { if (commandQueue.isRunning(Command.CommandType.BOLUS)) {
uel.log(UserEntryMapper.Action.CANCEL_BOLUS, UserEntryMapper.Sources.EOPatch2); uel.log(UserEntryMapper.Action.CANCEL_BOLUS, UserEntryMapper.Sources.EOPatch2);
commandQueue.cancelAllBoluses(); commandQueue.cancelAllBoluses();
@ -82,11 +74,11 @@ public class InternalSuspendedTask extends BolusTask {
commandQueue.cancelExtended(new Callback() { commandQueue.cancelExtended(new Callback() {
@Override @Override
public void run() { public void run() {
exbolusCheckSubject.onNext(true); extendedBolusCheckSubject.onNext(true);
} }
}); });
}else{ }else{
exbolusCheckSubject.onNext(true); extendedBolusCheckSubject.onNext(true);
} }
if (pumpSync.expectedPumpState().getTemporaryBasal() != null) { if (pumpSync.expectedPumpState().getTemporaryBasal() != null) {
@ -101,14 +93,13 @@ public class InternalSuspendedTask extends BolusTask {
basalCheckSubject.onNext(true); basalCheckSubject.onNext(true);
} }
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(),
return (bolusReady && exbolusReady && basalReady); (bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady))
})
.filter(ready -> ready) .filter(ready -> ready)
.flatMap(v -> isReady()) .flatMap(v -> isReady())
.concatMapSingle(v -> getInternalSuspendTime()) .concatMapSingle(v -> getInternalSuspendTime())
.firstOrError() .firstOrError()
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "InternalSuspendedTask error"));
} }
private Single<Long> getInternalSuspendTime() { private Single<Long> getInternalSuspendTime() {
@ -117,56 +108,6 @@ public class InternalSuspendedTask extends BolusTask {
.map(PatchInternalSuspendTimeResponse::getTotalSeconds); .map(PatchInternalSuspendTimeResponse::getTotalSeconds);
} }
private Single<Long> 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<Long> 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<Long> 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) { public synchronized void enqueue(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) {
boolean ready = (disposable == null || disposable.isDisposed()); boolean ready = (disposable == null || disposable.isDisposed());
@ -175,7 +116,7 @@ public class InternalSuspendedTask extends BolusTask {
.timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS) .timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS)
.subscribe(v -> { .subscribe(v -> {
bolusCheckSubject.onNext(false); bolusCheckSubject.onNext(false);
exbolusCheckSubject.onNext(false); extendedBolusCheckSubject.onNext(false);
basalCheckSubject.onNext(false); basalCheckSubject.onNext(false);
}); });
} }

View file

@ -13,9 +13,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class NeedleSensingTask extends TaskBase { public class NeedleSensingTask extends TaskBase {
@Inject IAlarmRegistry alarmRegistry;
@Inject
IAlarmRegistry alarmRegistry;
StartNeedleCheck START_NEEDLE_CHECK; StartNeedleCheck START_NEEDLE_CHECK;
UpdateConnection UPDATE_CONNECTION; UpdateConnection UPDATE_CONNECTION;
@ -38,7 +36,7 @@ public class NeedleSensingTask extends TaskBase {
.doOnNext(this::onResponse) .doOnNext(this::onResponse)
.map(patchState -> !patchState.isNeedNeedleSensing()) .map(patchState -> !patchState.isNeedNeedleSensing())
.firstOrError() .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) { private void onResponse(PatchState v) {

View file

@ -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.AlarmCode;
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry; 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.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.vo.PatchState;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalPause; 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.core.response.PatchBooleanResponse;
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import io.reactivex.Observable; import io.reactivex.Observable;
@ -40,33 +36,28 @@ public class PauseBasalTask extends BolusTask {
@Inject PumpSync pumpSync; @Inject PumpSync pumpSync;
@Inject UserEntryLogger uel; @Inject UserEntryLogger uel;
private BasalPause BASAL_PAUSE; private final BasalPause BASAL_PAUSE;
private BolusStop BOLUS_STOP;
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
private final BehaviorSubject<Boolean> extendedBolusCheckSubject = BehaviorSubject.create();
private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
@Inject @Inject
public PauseBasalTask() { public PauseBasalTask() {
super(TaskFunc.PAUSE_BASAL); super(TaskFunc.PAUSE_BASAL);
BASAL_PAUSE = new BasalPause(); BASAL_PAUSE = new BasalPause();
BOLUS_STOP = new BolusStop();
TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop();
} }
private Observable<Boolean> getBolusSebject(){ private Observable<Boolean> getBolusSubject(){
return bolusCheckSubject.hide(); return bolusCheckSubject.hide();
} }
private Observable<Boolean> getExbolusSebject(){ private Observable<Boolean> getExtendedBolusSubject(){
return exbolusCheckSubject.hide(); return extendedBolusCheckSubject.hide();
} }
private Observable<Boolean> getBasalSebject(){ private Observable<Boolean> getBasalSubject(){
return basalCheckSubject.hide(); return basalCheckSubject.hide();
} }
@ -90,11 +81,11 @@ public class PauseBasalTask extends BolusTask {
commandQueue.cancelExtended(new Callback() { commandQueue.cancelExtended(new Callback() {
@Override @Override
public void run() { public void run() {
exbolusCheckSubject.onNext(true); extendedBolusCheckSubject.onNext(true);
} }
}); });
}else{ }else{
exbolusCheckSubject.onNext(true); extendedBolusCheckSubject.onNext(true);
} }
if (pumpSync.expectedPumpState().getTemporaryBasal() != null) { if (pumpSync.expectedPumpState().getTemporaryBasal() != null) {
@ -109,71 +100,35 @@ public class PauseBasalTask extends BolusTask {
basalCheckSubject.onNext(true); basalCheckSubject.onNext(true);
} }
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(),
return (bolusReady && exbolusReady && basalReady); (bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady))
})
.filter(ready -> ready) .filter(ready -> ready)
.flatMap(v -> isReady()) .flatMap(v -> isReady())
.concatMapSingle(v -> getSuspendedTime(pausedTimestamp, alarmCode)) .concatMapSingle(v -> getSuspendedTime(pausedTimestamp))
.concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, suspendedTimestamp, alarmCode)) .concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, alarmCode))
.firstOrError() .firstOrError()
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "PauseBasalTask error"));
} }
private Single<Long> getSuspendedTime(long pausedTimestamp, @Nullable AlarmCode alarmCode) { private Single<Long> getSuspendedTime(long pausedTimestamp) {
return Single.just(pausedTimestamp); return Single.just(pausedTimestamp);
} }
private Single<Long> stopNowBolus(long pausedTimestamp, boolean isNowBolusActive) { private Single<PatchBooleanResponse> pauseBasal(float pauseDurationHour, @Nullable AlarmCode alarmCode) {
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<Long> 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<Long> 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<PatchBooleanResponse> pauseBasal(float pauseDurationHour, long suspendedTimestamp, @Nullable AlarmCode alarmCode) {
if(alarmCode == null) { if(alarmCode == null) {
return BASAL_PAUSE.pause(pauseDurationHour) return BASAL_PAUSE.pause(pauseDurationHour)
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.doOnSuccess(v -> onBasalPaused(pauseDurationHour, suspendedTimestamp, null)); .doOnSuccess(v -> onBasalPaused(pauseDurationHour, null));
} }
// 정지 알람 발생 basal pause 커맨드 전달하지 않음 - 주입 정지 이력만 생성 // 정지 알람 발생 basal pause 커맨드 전달하지 않음 - 주입 정지 이력만 생성
onBasalPaused(pauseDurationHour, suspendedTimestamp, alarmCode); onBasalPaused(pauseDurationHour, alarmCode);
return Single.just(new PatchBooleanResponse(true)); 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()) { if (!pm.getNormalBasalManager().isSuspended()) {
String strCode = (alarmCode != null) ? alarmCode.name() : null;
if (alarmCode != null) { if (alarmCode != null) {
pm.getPatchConfig().updateNormalBasalPausedSilently(); pm.getPatchConfig().updateNormalBasalPausedSilently();
} }
@ -192,23 +147,6 @@ public class PauseBasalTask extends BolusTask {
enqueue(TaskFunc.UPDATE_CONNECTION); 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) { public synchronized void enqueue(float pauseDurationHour, long pausedTime, @Nullable AlarmCode alarmCode) {
boolean ready = (disposable == null || disposable.isDisposed()); boolean ready = (disposable == null || disposable.isDisposed());
@ -217,7 +155,7 @@ public class PauseBasalTask extends BolusTask {
.timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS) .timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS)
.subscribe(v -> { .subscribe(v -> {
bolusCheckSubject.onNext(false); bolusCheckSubject.onNext(false);
exbolusCheckSubject.onNext(false); extendedBolusCheckSubject.onNext(false);
basalCheckSubject.onNext(false); basalCheckSubject.onNext(false);
}); });
} }

View file

@ -14,9 +14,8 @@ import io.reactivex.Observable;
@Singleton @Singleton
public class PrimingTask extends TaskBase { public class PrimingTask extends TaskBase {
private final UpdateConnection UPDATE_CONNECTION;
private UpdateConnection UPDATE_CONNECTION; private final StartPriming START_PRIMING;
private StartPriming START_PRIMING;
@Inject @Inject
public PrimingTask() { public PrimingTask() {
@ -31,25 +30,25 @@ public class PrimingTask extends TaskBase {
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.flatMap(v -> observePrimingSuccess(count)) .flatMap(v -> observePrimingSuccess(count))
.takeUntil(value -> (value == 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<Long> observePrimingSuccess(long count) { private Observable<Long> observePrimingSuccess(long count) {
return Observable.merge( return Observable.merge(
Observable.interval(1, TimeUnit.SECONDS).take(count + 10) Observable.interval(1, TimeUnit.SECONDS).take(count + 10)
.map(v -> v * 3) // 현재 20초 니깐 60 정도에서 채워짐. *4 괜찮을 . .map(v -> v * 3)
.doOnNext(v -> { .doOnNext(v -> {
if (v >= count) { if (v >= count) {
throw new Exception("Priming failed"); throw new Exception("Priming failed");
} }
}), // 프로그래스바 . }),
Observable.interval(3, TimeUnit.SECONDS) Observable.interval(3, TimeUnit.SECONDS)
.concatMapSingle(v -> UPDATE_CONNECTION.get()) .concatMapSingle(v -> UPDATE_CONNECTION.get())
.map(response -> PatchState.Companion.create(response.getPatchState(), System.currentTimeMillis())) .map(response -> PatchState.Companion.create(response.getPatchState(), System.currentTimeMillis()))
.filter(patchState -> patchState.isPrimingSuccess()) .filter(PatchState::isPrimingSuccess)
.map(result -> count) // 프라이밍 체크 성공시 count 리턴 .map(result -> count)
); );
} }
} }

View file

@ -15,8 +15,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class ReadBolusFinishTimeTask extends BolusTask { public class ReadBolusFinishTimeTask extends BolusTask {
private final BolusFinishTimeGet BOLUS_FINISH_TIME_GET;
private BolusFinishTimeGet BOLUS_FINISH_TIME_GET;
@Inject @Inject
public ReadBolusFinishTimeTask() { public ReadBolusFinishTimeTask() {
@ -30,7 +29,7 @@ public class ReadBolusFinishTimeTask extends BolusTask {
.firstOrError() .firstOrError()
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.doOnSuccess(this::onResponse) .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) { void onResponse(BolusFinishTimeResponse response) {

View file

@ -13,8 +13,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class ReadTempBasalFinishTimeTask extends TaskBase { public class ReadTempBasalFinishTimeTask extends TaskBase {
private final TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET;
private TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET;
@Inject @Inject
public ReadTempBasalFinishTimeTask() { public ReadTempBasalFinishTimeTask() {
@ -28,7 +27,7 @@ public class ReadTempBasalFinishTimeTask extends TaskBase {
.firstOrError() .firstOrError()
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.doOnSuccess(this::onResponse) .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) { private void onResponse(TempBasalFinishTimeResponse response) {

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; 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.shared.logging.LTag;
import info.nightscout.androidaps.plugins.pump.eopatch.ble.PatchStateManager; import info.nightscout.androidaps.plugins.pump.eopatch.ble.PatchStateManager;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalResume; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalResume;
@ -17,13 +18,11 @@ import io.reactivex.Single;
@Singleton @Singleton
public class ResumeBasalTask extends TaskBase { public class ResumeBasalTask extends TaskBase {
@Inject @Inject IAlarmRegistry alarmRegistry;
StartNormalBasalTask startNormalBasalTask; @Inject StartNormalBasalTask startNormalBasalTask;
@Inject PatchStateManager patchStateManager;
@Inject private final BasalResume BASAL_RESUME;
PatchStateManager patchStateManager;
private BasalResume BASAL_RESUME;
@Inject @Inject
public ResumeBasalTask() { public ResumeBasalTask() {
@ -32,25 +31,21 @@ public class ResumeBasalTask extends TaskBase {
} }
public synchronized Single<? extends BaseResponse> resume() { public synchronized Single<? extends BaseResponse> resume() {
if (pm.getPatchConfig().getNeedSetBasalSchedule()) { if (pm.getPatchConfig().getNeedSetBasalSchedule()) {
NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal(); return startNormalBasalTask.start(pm.getNormalBasalManager().getNormalBasal());
if (normalBasal != null) {
return startNormalBasalTask.start(normalBasal, true);
}
} }
return isReady().concatMapSingle(v -> BASAL_RESUME.resume()) return isReady().concatMapSingle(v -> BASAL_RESUME.resume())
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(v -> onResumeResponse(v)) .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()) { if (v.isSuccess()) {
patchStateManager.onBasalResumed(v.getTimestamp() + 1000); patchStateManager.onBasalResumed(v.getTimestamp() + 1000);
alarmRegistry.remove(AlarmCode.B001).subscribe();
} }
enqueue(TaskFunc.UPDATE_CONNECTION); enqueue(TaskFunc.UPDATE_CONNECTION);
} }

View file

@ -18,10 +18,9 @@ import io.reactivex.Single;
@Singleton @Singleton
public class SelfTestTask extends TaskBase { public class SelfTestTask extends TaskBase {
private final GetTemperature TEMPERATURE_GET;
private GetTemperature TEMPERATURE_GET; private final GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING;
private GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING; private final GetGlobalTime GET_GLOBAL_TIME;
private GetGlobalTime GET_GLOBAL_TIME;
@Inject @Inject
public SelfTestTask() { public SelfTestTask() {
@ -35,33 +34,17 @@ public class SelfTestTask extends TaskBase {
public Single<PatchSelfTestResult> start() { public Single<PatchSelfTestResult> start() {
Single<PatchSelfTestResult> tasks = Single.concat(Arrays.asList( Single<PatchSelfTestResult> tasks = Single.concat(Arrays.asList(
TEMPERATURE_GET.get() TEMPERATURE_GET.get()
.map(TemperatureResponse::getResult) .map(TemperatureResponse::getResult),
.doOnSuccess(this::onTemperatureResult),
BATTERY_LEVEL_GET_BEFORE_PRIMING.get() BATTERY_LEVEL_GET_BEFORE_PRIMING.get()
.map(BatteryVoltageLevelPairingResponse::getResult) .map(BatteryVoltageLevelPairingResponse::getResult),
.doOnSuccess(this::onBatteryResult),
GET_GLOBAL_TIME.get(false) GET_GLOBAL_TIME.get(false)
.map(GlobalTimeResponse::getResult) .map(GlobalTimeResponse::getResult)))
.doOnSuccess(this::onTimeResult)))
.filter(result -> result != PatchSelfTestResult.TEST_SUCCESS) .filter(result -> result != PatchSelfTestResult.TEST_SUCCESS)
.first(PatchSelfTestResult.TEST_SUCCESS); .first(PatchSelfTestResult.TEST_SUCCESS);
return isReady() return isReady()
.concatMapSingle(v -> tasks) .concatMapSingle(v -> tasks)
.firstOrError() .firstOrError()
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SelfTestTask error"));
}
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) {
} }
} }

View file

@ -16,9 +16,8 @@ import io.reactivex.Single;
@Singleton @Singleton
public class SetGlobalTimeTask extends TaskBase { public class SetGlobalTimeTask extends TaskBase {
private final SetGlobalTime SET_GLOBAL_TIME;
private SetGlobalTime SET_GLOBAL_TIME; private final GetGlobalTime GET_GLOBAL_TIME;
private GetGlobalTime GET_GLOBAL_TIME;
@Inject @Inject
public SetGlobalTimeTask() { public SetGlobalTimeTask() {
@ -37,24 +36,23 @@ public class SetGlobalTimeTask extends TaskBase {
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(v -> onSuccess()) .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 newMilli = System.currentTimeMillis();
long oldMilli = response.getGlobalTimeInMilli(); long oldMilli = response.getGlobalTimeInMilli();
long oldOffset = response.getTimeZoneOffset(); long oldOffset = response.getTimeZoneOffset();
int offset = TimeZone.getDefault().getOffset(newMilli); int offset = TimeZone.getDefault().getOffset(newMilli);
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(offset); int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(offset);
// TimeZoneOffset (8bit / signed): 타임존 offset 15분 단위을 1로 환산, Korea 경우 36값(+9:00)
int newOffset = minutes / 15; int newOffset = minutes / 15;
long diff = Math.abs(oldMilli - newMilli); long diff = Math.abs(oldMilli - newMilli);
if (diff > 60000 || oldOffset != newOffset) { if (diff > 60000 || oldOffset != newOffset) {
aapsLogger.debug(LTag.PUMPCOMM, String.format("checkPatchTime %s %s %s", diff, 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"); throw new Exception("No time set required");

View file

@ -14,11 +14,9 @@ import io.reactivex.Single;
@Singleton @Singleton
public class SetLowReservoirTask extends TaskBase { public class SetLowReservoirTask extends TaskBase {
@Inject IPreferenceManager pm;
@Inject private final SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT;
IPreferenceManager pm;
private SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT;
@Inject @Inject
public SetLowReservoirTask() { public SetLowReservoirTask() {
@ -33,7 +31,7 @@ public class SetLowReservoirTask extends TaskBase {
hours)) hours))
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .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() { public synchronized void enqueue() {

View file

@ -14,12 +14,9 @@ import io.reactivex.Single;
import static info.nightscout.androidaps.plugins.pump.eopatch.core.api.StartBonding.OPTION_NUMERIC; import static info.nightscout.androidaps.plugins.pump.eopatch.core.api.StartBonding.OPTION_NUMERIC;
/**
* (주의) API 호출 본딩을 위해서 밑단 연결이 끊어짐.
*/
@Singleton @Singleton
public class StartBondTask extends TaskBase { public class StartBondTask extends TaskBase {
private StartBonding START_BOND; private final StartBonding START_BOND;
@Inject @Inject
public StartBondTask() { public StartBondTask() {
@ -44,7 +41,7 @@ public class StartBondTask extends TaskBase {
.doOnNext(v -> prefSetMacAddress(mac)) .doOnNext(v -> prefSetMacAddress(mac))
.doOnError(e -> { .doOnError(e -> {
prefSetMacAddress(""); prefSetMacAddress("");
aapsLogger.error(LTag.PUMPCOMM, e.getMessage()); aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartBondTask error");
}) })
.firstOrError(); .firstOrError();
} }

View file

@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.shared.logging.LTag; 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.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.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
@ -16,47 +13,34 @@ import io.reactivex.Single;
@Singleton @Singleton
public class StartCalcBolusTask extends BolusTask { public class StartCalcBolusTask extends BolusTask {
private final BolusStart NOW_BOLUS_START;
private BolusStart NOW_BOLUS_START;
private ExtBolusStart EXT_BOLUS_START;
private ComboBolusStart COMBO_BOLUS_START;
@Inject @Inject
public StartCalcBolusTask() { public StartCalcBolusTask() {
super(TaskFunc.START_CALC_BOLUS); super(TaskFunc.START_CALC_BOLUS);
NOW_BOLUS_START = new BolusStart(); NOW_BOLUS_START = new BolusStart();
EXT_BOLUS_START = new ExtBolusStart();
COMBO_BOLUS_START = new ComboBolusStart();
} }
public Single<? extends BolusResponse> start(DetailedBolusInfo detailedBolusInfo) { public Single<? extends BolusResponse> 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) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin, (float)detailedBolusInfo.insulin, 0f, BolusExDuration.OFF)) .doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin))
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartCalcBolusTask error"));
} }
private Single<? extends BolusResponse> startBolusImpl(float nowDoseU, float exDoseU, private Single<? extends BolusResponse> startBolusImpl(float nowDoseU) {
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); return NOW_BOLUS_START.start(nowDoseU);
} }
}
private void onSuccess(float nowDoseU, float correctionBolus, float exDoseU, BolusExDuration exDuration) { private void onSuccess(float nowDoseU) {
onCalcBolusStarted(nowDoseU, correctionBolus, exDoseU, exDuration); onCalcBolusStarted(nowDoseU);
enqueue(TaskFunc.UPDATE_CONNECTION); enqueue(TaskFunc.UPDATE_CONNECTION);
} }
@Override @Override
protected void preCondition() throws Exception { protected void preCondition() throws Exception {
//checkPatchActivated();
checkPatchConnected(); checkPatchConnected();
} }
} }

View file

@ -16,8 +16,7 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class StartNormalBasalTask extends TaskBase { public class StartNormalBasalTask extends TaskBase {
private final BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
@Inject @Inject
PatchStateManager patchStateManager; PatchStateManager patchStateManager;
@ -28,23 +27,25 @@ public class StartNormalBasalTask extends TaskBase {
BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig(); BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig();
} }
public Single<BasalScheduleSetResponse> start(NormalBasal basal, boolean resume) { public Single<BasalScheduleSetResponse> start(NormalBasal basal) {
return isReady().concatMapSingle(v -> startJob(basal, resume)).firstOrError(); return isReady().concatMapSingle(v -> startJob(basal)).firstOrError();
} }
public Single<BasalScheduleSetResponse> startJob(NormalBasal basal, boolean resume) { public Single<BasalScheduleSetResponse> startJob(NormalBasal basal) {
return BASAL_SCHEDULE_SET_BIG.set(basal.getDoseUnitPerSegmentArray()) return BASAL_SCHEDULE_SET_BIG.set(basal.getDoseUnitPerSegmentArray())
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.doOnSuccess(v -> onStartNormalBasalResponse(v, basal, resume)) .doOnSuccess(v -> onStartNormalBasalResponse(v, basal))
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage())); .doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartNormalBasalTask error"));
} }
private void onStartNormalBasalResponse(BasalScheduleSetResponse response, private void onStartNormalBasalResponse(BasalScheduleSetResponse response, NormalBasal basal) {
NormalBasal basal, boolean resume) throws SQLException {
long timeStamp = response.getTimestamp(); long timeStamp = response.getTimestamp();
patchStateManager.onBasalStarted(basal, timeStamp+1000); patchStateManager.onBasalStarted(basal, timeStamp+1000);
pm.getNormalBasalManager().setNormalBasal(basal);
pm.flushNormalBasalManager();
enqueue(TaskFunc.UPDATE_CONNECTION); enqueue(TaskFunc.UPDATE_CONNECTION);
} }

View file

@ -15,10 +15,9 @@ import io.reactivex.Single;
@Singleton @Singleton
public class StartQuickBolusTask extends BolusTask { public class StartQuickBolusTask extends BolusTask {
private final BolusStart NOW_BOLUS_START;
private BolusStart NOW_BOLUS_START; private final ExtBolusStart EXT_BOLUS_START;
private ExtBolusStart EXT_BOLUS_START; private final ComboBolusStart COMBO_BOLUS_START;
private ComboBolusStart COMBO_BOLUS_START;
@Inject @Inject
public StartQuickBolusTask() { public StartQuickBolusTask() {
@ -35,7 +34,7 @@ public class StartQuickBolusTask extends BolusTask {
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(v -> onSuccess(nowDoseU, exDoseU, exDuration)) .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<? extends BolusResponse> startBolusImpl(float nowDoseU, float exDoseU, private Single<? extends BolusResponse> startBolusImpl(float nowDoseU, float exDoseU,

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task; 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.shared.logging.LTag;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStart; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStart;
@ -13,8 +14,8 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class StartTempBasalTask extends TaskBase { public class StartTempBasalTask extends TaskBase {
@Inject IPreferenceManager pm;
private TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START; private final TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START;
@Inject @Inject
public StartTempBasalTask() { public StartTempBasalTask() {
@ -30,10 +31,12 @@ public class StartTempBasalTask extends TaskBase {
.firstOrError() .firstOrError()
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.doOnSuccess(v -> onTempBasalStarted(tempBasal)) .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) { private void onTempBasalStarted(TempBasal tempBasal) {
pm.getTempBasalManager().updateBasalRunning(tempBasal);
pm.flushTempBasalManager();
enqueue(TaskFunc.UPDATE_CONNECTION); enqueue(TaskFunc.UPDATE_CONNECTION);
} }

View file

@ -25,17 +25,16 @@ import io.reactivex.subjects.BehaviorSubject;
@Singleton @Singleton
public class StopBasalTask extends TaskBase { public class StopBasalTask extends TaskBase {
@Inject IPreferenceManager pm; @Inject IPreferenceManager pm;
@Inject CommandQueue commandQueue; @Inject CommandQueue commandQueue;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject PumpSync pumpSync; @Inject PumpSync pumpSync;
@Inject UserEntryLogger uel; @Inject UserEntryLogger uel;
private BasalStop BASAL_STOP; private final BasalStop BASAL_STOP;
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create(); private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create(); private final BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create(); private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
@Inject @Inject
public StopBasalTask() { public StopBasalTask() {
@ -89,16 +88,15 @@ public class StopBasalTask extends TaskBase {
basalCheckSubject.onNext(true); basalCheckSubject.onNext(true);
} }
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> { return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady)
return (bolusReady && exbolusReady && basalReady); -> (bolusReady && exbolusReady && basalReady))
})
.filter(ready -> ready) .filter(ready -> ready)
.flatMap(v -> isReady()) .flatMap(v -> isReady())
.concatMapSingle(v -> BASAL_STOP.stop()) .concatMapSingle(v -> BASAL_STOP.stop())
.doOnNext(this::checkResponse) .doOnNext(this::checkResponse)
.firstOrError() .firstOrError()
.doOnSuccess(this::onBasalStopped) .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) { private void onBasalStopped(BasalStopResponse response) {

View file

@ -16,8 +16,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class StopComboBolusTask extends BolusTask { public class StopComboBolusTask extends BolusTask {
private final BolusStop BOLUS_STOP;
private BolusStop BOLUS_STOP;
@Inject @Inject
public StopComboBolusTask() { public StopComboBolusTask() {
@ -31,7 +30,7 @@ public class StopComboBolusTask extends BolusTask {
.firstOrError() .firstOrError()
.doOnSuccess(this::checkResponse) .doOnSuccess(this::checkResponse)
.doOnSuccess(this::onComboBolusStopped) .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<ComboBolusStopResponse> stopJob() { public Single<ComboBolusStopResponse> stopJob() {

View file

@ -14,19 +14,17 @@ import io.reactivex.Single;
@Singleton @Singleton
public class StopExtBolusTask extends BolusTask { public class StopExtBolusTask extends BolusTask {
private final BolusStop BOLUS_STOP;
private BolusStop BOLUS_STOP;
@Inject @Inject
public StopExtBolusTask() { public StopExtBolusTask() {
super(TaskFunc.STOP_EXT_BOLUS); super(TaskFunc.STOP_EXT_BOLUS);
BOLUS_STOP = new BolusStop(); BOLUS_STOP = new BolusStop();
} }
public Single<BolusStopResponse> stop() { public Single<BolusStopResponse> stop() {
return isReady().concatMapSingle(v -> stopJob()).firstOrError() 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<BolusStopResponse> stopJob() { public Single<BolusStopResponse> stopJob() {

View file

@ -15,13 +15,11 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
@Singleton @Singleton
public class StopNowBolusTask extends BolusTask { public class StopNowBolusTask extends BolusTask {
private final BolusStop BOLUS_STOP;
private BolusStop BOLUS_STOP;
@Inject @Inject
public StopNowBolusTask() { public StopNowBolusTask() {
super(TaskFunc.STOP_NOW_BOLUS); super(TaskFunc.STOP_NOW_BOLUS);
BOLUS_STOP = new BolusStop(); BOLUS_STOP = new BolusStop();
} }
@ -29,7 +27,7 @@ public class StopNowBolusTask extends BolusTask {
return isReady() return isReady()
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.concatMapSingle(v -> stopJob()).firstOrError() .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<BolusStopResponse> stopJob() { public Single<BolusStopResponse> stopJob() {

View file

@ -13,8 +13,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class StopTempBasalTask extends TaskBase { public class StopTempBasalTask extends TaskBase {
private final TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
@Inject @Inject
public StopTempBasalTask() { public StopTempBasalTask() {
@ -25,7 +24,7 @@ public class StopTempBasalTask extends TaskBase {
public Single<PatchBooleanResponse> stop() { public Single<PatchBooleanResponse> stop() {
return isReady().concatMapSingle(v -> stopJob()).firstOrError() 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<PatchBooleanResponse> stopJob() { public Single<PatchBooleanResponse> stopJob() {

View file

@ -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.BasalHistoryIndexGet;
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalHistoryGetExBig; import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalHistoryGetExBig;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.inject.Inject; import javax.inject.Inject;
@ -19,13 +18,11 @@ import static info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatch
@Singleton @Singleton
public class SyncBasalHistoryTask extends TaskBase { public class SyncBasalHistoryTask extends TaskBase {
@Inject IPreferenceManager pm;
@Inject private final BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET;
IPreferenceManager pm; private final BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG;
private final TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG;
private BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET;
private BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG;
private TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG;
@Inject @Inject
public SyncBasalHistoryTask() { public SyncBasalHistoryTask() {
@ -38,19 +35,10 @@ public class SyncBasalHistoryTask extends TaskBase {
public Single<Integer> sync(int end) { public Single<Integer> sync(int end) {
return Single.just(1); // 베이젤 싱크 사용 안함 return Single.just(1); // 베이젤 싱크 사용 안함
// return isReady()
// .concatMapSingle(v -> syncBoth(pm.getPatchConfig().getLastIndex(), end))
// .firstOrError()
// .doOnSuccess(this::updatePatchLastIndex);
} }
public Single<Integer> sync() { public Single<Integer> sync() {
return Single.just(1); // 베이젤 싱크 사용 안함 return Single.just(1); // 베이젤 싱크 사용 안함
// return isReady()
// .concatMapSingle(v -> getLastIndex())
// .concatMapSingle(end -> syncBoth(pm.getPatchConfig().getLastIndex(), end))
// .firstOrError()
// .doOnSuccess(this::updatePatchLastIndex);
} }
private Single<Integer> getLastIndex() { private Single<Integer> getLastIndex() {
@ -94,7 +82,7 @@ public class SyncBasalHistoryTask extends TaskBase {
} }
private int onBasalHistoryResponse(BasalHistoryResponse n, BasalHistoryResponse t, 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()) { if (!n.isSuccess() || !t.isSuccess() || n.getSeq() != t.getSeq()) {
return -1; return -1;
@ -112,7 +100,7 @@ public class SyncBasalHistoryTask extends TaskBase {
return updateInjected(normal, temp, start, end); 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) { if (pm.getPatchState().isPatchInternalSuspended() && pm.getPatchConfig().isInBasalPausedTime() == false) {
return -1; return -1;
} }

View file

@ -33,11 +33,9 @@ public class TaskQueue {
protected synchronized Observable<TaskFunc> isReady(final TaskFunc function) { protected synchronized Observable<TaskFunc> isReady(final TaskFunc function) {
return Observable.fromCallable(() -> publishTicket(function)) return Observable.fromCallable(() -> publishTicket(function))
.concatMap(v -> { .concatMap(v -> ticketSubject
return ticketSubject
.takeUntil(it -> it.number > v) .takeUntil(it -> it.number > v)
.filter(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()))) .doOnNext(v -> aapsLogger.debug(LTag.PUMPCOMM, String.format("Task #:%s started func:%s", v.number, v.func.name())))
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
.map(it -> it.func) .map(it -> it.func)
@ -86,13 +84,13 @@ public class TaskQueue {
public synchronized boolean has(TaskFunc func) { public synchronized boolean has(TaskFunc func) {
if (queue.size() > 1) { if (queue.size() > 1) {
Iterator<PatchTask> itor = queue.iterator(); Iterator<PatchTask> iterator = queue.iterator();
/* remove 1st queue */ /* remove 1st queue */
itor.next(); iterator.next();
while (itor.hasNext()) { while (iterator.hasNext()) {
PatchTask item = itor.next(); PatchTask item = iterator.next();
if (item.func == func) { if (item.func == func) {
return true; return true;
} }

View file

@ -15,9 +15,7 @@ import io.reactivex.Single;
@Singleton @Singleton
public class UpdateConnectionTask extends TaskBase { public class UpdateConnectionTask extends TaskBase {
@Inject PatchStateManager patchStateManager;
@Inject
PatchStateManager patchStateManager;
private UpdateConnection UPDATE_CONNECTION; private UpdateConnection UPDATE_CONNECTION;
@ -38,7 +36,7 @@ public class UpdateConnectionTask extends TaskBase {
.map(UpdateConnectionResponse::getPatchState) .map(UpdateConnectionResponse::getPatchState)
.map(bytes -> PatchState.Companion.create(bytes, System.currentTimeMillis())) .map(bytes -> PatchState.Companion.create(bytes, System.currentTimeMillis()))
.doOnSuccess(state -> onUpdateConnection(state)) .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) { private void onUpdateConnection(PatchState patchState) {

View file

@ -1,46 +1,7 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code package info.nightscout.androidaps.plugins.pump.eopatch.code
import com.google.android.gms.common.internal.Preconditions enum class AlarmCategory{
NONE,
enum class AlarmCategory private constructor(val rawValue: Int) { ALARM,
NONE(0), ALERT;
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
}
}
} }

View file

@ -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
}
}
}

View file

@ -10,21 +10,12 @@ enum class BasalStatus constructor(val rawValue: Int) {
val isStarted: Boolean val isStarted: Boolean
get() = this == STARTED get() = this == STARTED
val isPaused: Boolean
get() = this == PAUSED
val isSuspended: Boolean val isSuspended: Boolean
get() = this == SUSPENDED get() = this == SUSPENDED
val isStopped: Boolean val isStopped: Boolean
get() = this == STOPPED get() = this == STOPPED
val isSelected: Boolean
get() = this == SELECTED
val isSelectedGroup: Boolean
get() = isStarted || isPaused || isSuspended || isSelected
companion object { companion object {
@JvmStatic @JvmStatic
fun ofRaw(rawValue: Int?): BasalStatus { fun ofRaw(rawValue: Int?): BasalStatus {

View file

@ -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
}
}
}

View file

@ -1,10 +1,5 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code 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 import java.util.concurrent.TimeUnit
enum class BolusExDuration constructor(val index: Int, val minute: Int, val hour: Float) { 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_450(15, 450, 7.5f),
MINUTE_480(16, 480, 8.0f); MINUTE_480(16, 480, 8.0f);
val isOff: Boolean
get() = this == OFF
val isNotOff: Boolean
get() = this != OFF
fun milli(): Long { fun milli(): Long {
return TimeUnit.MINUTES.toMillis(this.minute.toLong()) return TimeUnit.MINUTES.toMillis(this.minute.toLong())
} }
companion object { companion object {
@JvmStatic
fun getItemFromIndex(index: Int): BolusExDuration {
var reverseIndices = SparseArrayCompat<BolusExDuration>()
for (duration in values()) {
reverseIndices.put(duration.index, duration)
}
val result = reverseIndices.get(index)
return result ?: OFF
}
@JvmStatic @JvmStatic
fun ofRaw(rawValue: Int): BolusExDuration { fun ofRaw(rawValue: Int): BolusExDuration {
if (rawValue == null) { for (t in values()) {
return OFF
}
for (t in BolusExDuration.values()) {
if (t.minute == rawValue) { if (t.minute == rawValue) {
return t return t
} }

View file

@ -1,20 +1,14 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code package info.nightscout.androidaps.plugins.pump.eopatch.code
enum class DeactivationStatus constructor(val rawValue: Int) { enum class DeactivationStatus {
DEACTIVATION_FAILED(0), DEACTIVATION_FAILED,
NORMAL_DEACTIVATED(1), NORMAL_DEACTIVATED,
FORCE_DEACTIVATED(2); FORCE_DEACTIVATED;
val isDeactivated: Boolean val isDeactivated: Boolean
get() = this == NORMAL_DEACTIVATED || this == FORCE_DEACTIVATED 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 { companion object {
@JvmStatic @JvmStatic
fun of(isSuccess: Boolean, forced: Boolean): DeactivationStatus { fun of(isSuccess: Boolean, forced: Boolean): DeactivationStatus {

View file

@ -1,5 +0,0 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code
enum class Dummy {
INSTANCE
}

View file

@ -1,8 +1,8 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code package info.nightscout.androidaps.plugins.pump.eopatch.code
enum class EventType { enum class EventType {
ACTIVTION_CLICKED, ACTIVATION_CLICKED,
DEACTIVTION_CLICKED, DEACTIVATION_CLICKED,
SUSPEND_CLICKED, SUSPEND_CLICKED,
RESUME_CLICKED, RESUME_CLICKED,
INVALID_BASAL_RATE, INVALID_BASAL_RATE,
@ -12,14 +12,9 @@ enum class EventType {
SHOW_PATCH_COMM_ERROR_DIALOG, SHOW_PATCH_COMM_ERROR_DIALOG,
SHOW_BONDED_DIALOG, SHOW_BONDED_DIALOG,
SHOW_CHANGE_PATCH_DIALOG, SHOW_CHANGE_PATCH_DIALOG,
SHOW_PROGRESS_DIALOG,
DISMISS_PROGRESS_DIALOG,
FINISH_ACTIVITY, FINISH_ACTIVITY,
SHOW_DISCARD_DIALOG, SHOW_DISCARD_DIALOG,
PAUSE_BASAL_FAILED, PAUSE_BASAL_FAILED,
RESUME_BASAL_FAILED, RESUME_BASAL_FAILED
CALCULATED_BOLUS_CLICKED,
EXTENDED_BOLUS_SETTINGS_CLICKED,
SAVE_CLICKED
; ;
} }

View file

@ -1,9 +1,6 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code package info.nightscout.androidaps.plugins.pump.eopatch.code
import android.content.Context enum class PatchExpireAlertTime constructor(val index: Int, val hour: Int) {
import info.nightscout.androidaps.plugins.pump.eopatch.R
enum class PatchExpireAlertTime private constructor(val index: Int, val hour: Int) {
HOUR_1(0, 1), HOUR_1(0, 1),
HOUR_2(1, 2), HOUR_2(1, 2),
HOUR_3(2, 3), HOUR_3(2, 3),
@ -28,25 +25,4 @@ enum class PatchExpireAlertTime private constructor(val index: Int, val hour: In
HOUR_22(21, 22), HOUR_22(21, 22),
HOUR_23(22, 23), HOUR_23(22, 23),
HOUR_24(23, 24); 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
}
}
} }

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code 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), SHUTDOWN(1),
BONDED(2), BONDED(2),
SAFETY_CHECK(3), SAFETY_CHECK(3),
@ -16,15 +16,4 @@ enum class PatchLifecycle private constructor(val rawValue: Int) {
val isActivated: Boolean val isActivated: Boolean
get() = this == ACTIVATED get() = this == ACTIVATED
companion object {
@JvmStatic
fun ofRaw(rawValue: Int): PatchLifecycle {
for (type in values()) {
if (type.rawValue == rawValue) {
return type
}
}
return SHUTDOWN
}
}
} }

View file

@ -21,9 +21,6 @@ enum class PatchStep {
BACK_TO_HOME, BACK_TO_HOME,
FINISH; FINISH;
val isConnectNew: Boolean
get() = this == CONNECT_NEW
val isSafeDeactivation: Boolean val isSafeDeactivation: Boolean
get() = this == SAFE_DEACTIVATION get() = this == SAFE_DEACTIVATION

View file

@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.R
class SettingKeys { class SettingKeys {
companion object{ 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 EXPIRATION_REMINDERS: Int = R.string.key_eopatch_expiration_reminders
val BUZZER_REMINDERS: Int = R.string.key_eopatch_patch_buzzer_reminders val BUZZER_REMINDERS: Int = R.string.key_eopatch_patch_buzzer_reminders

View file

@ -1,52 +1,8 @@
package info.nightscout.androidaps.plugins.pump.eopatch.code package info.nightscout.androidaps.plugins.pump.eopatch.code
import com.google.android.gms.common.internal.Preconditions enum class UnitOrPercent {
P,
enum class UnitOrPercent private constructor(val rawValue: Int, val symbol: String) { U;
P(0, "%"),
U(1, "U");
fun isPercentage() = this == P 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
}
}
} }

View file

@ -6,11 +6,6 @@ import javax.inject.Scope
@Qualifier @Qualifier
annotation class EopatchPluginQualifier annotation class EopatchPluginQualifier
@MustBeDocumented
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
@MustBeDocumented @MustBeDocumented
@Scope @Scope
@Retention(AnnotationRetention.RUNTIME) @Retention(AnnotationRetention.RUNTIME)

View file

@ -39,7 +39,6 @@ abstract class EopatchModule {
} }
@Binds @Binds
@Singleton @Singleton
abstract fun bindPatchManager(patchManager: PatchManager): IPatchManager abstract fun bindPatchManager(patchManager: PatchManager): IPatchManager

View file

@ -1,17 +1,11 @@
package info.nightscout.androidaps.plugins.pump.eopatch.dagger package info.nightscout.androidaps.plugins.pump.eopatch.dagger
import android.app.Application
import android.content.Context
import dagger.Binds
import dagger.Module import dagger.Module
import dagger.Provides 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.Alarms
import info.nightscout.androidaps.plugins.pump.eopatch.vo.NormalBasalManager 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.PatchConfig
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasalManager import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasalManager
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Singleton import javax.inject.Singleton
@Module @Module
@ -24,13 +18,13 @@ class EopatchPrefModule {
@Provides @Provides
@Singleton @Singleton
internal fun provideNormalBasalManager(sp: SP): NormalBasalManager { internal fun provideNormalBasalManager(): NormalBasalManager {
return NormalBasalManager() return NormalBasalManager()
} }
@Provides @Provides
@Singleton @Singleton
internal fun provideTempBasalManager(sp: SP): TempBasalManager { internal fun provideTempBasalManager(): TempBasalManager {
return TempBasalManager() return TempBasalManager()
} }

View file

@ -8,4 +8,4 @@ import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode
class EventEoPatchAlarm(var alarmCodes: Set<AlarmCode>, var isFirst: Boolean = false) : Event() class EventEoPatchAlarm(var alarmCodes: Set<AlarmCode>, var isFirst: Boolean = false) : Event()
class EventDialog(val dialog: DialogFragment, val show: Boolean) : Event() class EventDialog(val dialog: DialogFragment, val show: Boolean) : Event()
class EventProgressDialog(val show: Boolean, @StringRes val resId: Int = 0) : Event() class EventProgressDialog(val show: Boolean, @StringRes val resId: Int = 0) : Event()
class EventPatchActivationNotComplete() : Event() class EventPatchActivationNotComplete : Event()

View file

@ -1,13 +1,9 @@
package info.nightscout.androidaps.plugins.pump.eopatch.extension 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.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction import androidx.fragment.app.FragmentTransaction
import java.io.Serializable
fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int, addToBackStack: Boolean = false) { fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int, addToBackStack: Boolean = false) {
supportFragmentManager.transact { supportFragmentManager.transact {
@ -21,42 +17,3 @@ private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Un
action() action()
}.commit() }.commit()
} }
fun Intent.fillExtras(params: Array<out Pair<String, Any?>>){
fillIntentArguments(this, params)
}
private fun fillIntentArguments(intent: Intent, params: Array<out Pair<String, Any?>>) {
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<CharSequence>() -> intent.putExtra(it.first, value)
value.isArrayOf<String>() -> intent.putExtra(it.first, value)
value.isArrayOf<Parcelable>() -> 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
}
}

View file

@ -1,15 +1,17 @@
package info.nightscout.androidaps.plugins.pump.eopatch.extension package info.nightscout.androidaps.plugins.pump.eopatch.extension
import kotlin.math.abs
fun Float.nearlyEqual(b: Float, epsilon: Float): Boolean { fun Float.nearlyEqual(b: Float, epsilon: Float): Boolean {
val absA = Math.abs(this) val absA = abs(this)
val absB = Math.abs(b) val absB = abs(b)
val diff = Math.abs(this - b) val diff = abs(this - b)
return if (this == b) { return if (this == b) {
true true
} else if (this == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) { } else if (this == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) {
diff < epsilon * java.lang.Float.MIN_NORMAL diff < epsilon * java.lang.Float.MIN_NORMAL
} else { } else {
diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon diff / (absA + absB).coerceAtMost(Float.MAX_VALUE) < epsilon
} }
} }

View file

@ -6,29 +6,6 @@ import java.util.concurrent.TimeUnit
internal val Long.date: Date internal val Long.date: Date
get() = Calendar.getInstance().also { it.timeInMillis = this }.time get() = Calendar.getInstance().also { it.timeInMillis = this }.time
fun Long.getDiffTime(isRelative: Boolean = false): Triple<Long, Long, Long> {
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<Long, Long, Long> {
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 { fun Long.getDiffDays(isRelative: Boolean = false): Long {
val inputTimeMillis = this val inputTimeMillis = this
val currentTimeMillis = System.currentTimeMillis() val currentTimeMillis = System.currentTimeMillis()
@ -36,7 +13,3 @@ fun Long.getDiffDays(isRelative: Boolean = false): Long {
return TimeUnit.MILLISECONDS.toDays(diffTimeMillis) return TimeUnit.MILLISECONDS.toDays(diffTimeMillis)
} }
fun Long.getSeconds() : Long {
return (this/1000)*1000
}

View file

@ -7,8 +7,6 @@ import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers import io.reactivex.schedulers.Schedulers
fun <T> Single<T>.observeOnMainThread(): Single<T> = observeOn(AndroidSchedulers.mainThread())
fun <T> Single<T>.subscribeDefault(aapsLogger: AAPSLogger, onSuccess: (T) -> Unit): Disposable = subscribe(onSuccess, { fun <T> Single<T>.subscribeDefault(aapsLogger: AAPSLogger, onSuccess: (T) -> Unit): Disposable = subscribe(onSuccess, {
aapsLogger.error(LTag.PUMP, "onError", it) aapsLogger.error(LTag.PUMP, "onError", it)
}) })

View file

@ -20,29 +20,3 @@ fun String.fromHtml(): CharSequence = Html.fromHtml(this, Html.FROM_HTML_MODE_CO
fun String.isEmpty(): Boolean{ fun String.isEmpty(): Boolean{
return this.length == 0 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
}

View file

@ -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 ""
})
}

View file

@ -1,8 +1,7 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.app.AlertDialog
import android.app.ProgressDialog
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import info.nightscout.androidaps.activities.DialogAppCompatActivity import info.nightscout.androidaps.activities.DialogAppCompatActivity
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.plugins.bus.RxBus 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.EventDialog
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventProgressDialog 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.AlarmDialog
import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.ProgressDialogHelper
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -20,7 +20,7 @@ class AlarmHelperActivity : DialogAppCompatActivity() {
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private var mProgressDialog: ProgressDialog? = null private var mProgressDialog: AlertDialog? = null
@Override @Override
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@ -64,10 +64,8 @@ class AlarmHelperActivity : DialogAppCompatActivity() {
private fun showProgressDialog(resId: Int){ private fun showProgressDialog(resId: Int){
if (mProgressDialog == null && resId != 0) { if (mProgressDialog == null && resId != 0) {
mProgressDialog = ProgressDialog(this).apply { mProgressDialog = ProgressDialogHelper.get(this, getString(resId)).apply {
setMessage(getString(resId))
setCancelable(false) setCancelable(false)
setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal)
} }
mProgressDialog?.show() mProgressDialog?.show()
} }

View file

@ -18,8 +18,4 @@ class DialogHelperActivity : DialogAppCompatActivity() {
dialog.message = intent.getStringExtra("message")?:"" dialog.message = intent.getStringExtra("message")?:""
dialog.show(supportFragmentManager, "Dialog") dialog.show(supportFragmentManager, "Dialog")
} }
override fun onDestroy() {
super.onDestroy()
}
} }

View file

@ -1,23 +1,17 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.View
import android.widget.Toast import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.annotation.LayoutRes import androidx.annotation.LayoutRes
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatDelegate
import androidx.databinding.DataBindingUtil import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.core.R 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.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 info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable import io.reactivex.disposables.Disposable
@ -35,6 +29,8 @@ abstract class EoBaseActivity<B : ViewDataBinding> : NoSplashAppCompatActivity()
private val compositeDisposable = CompositeDisposable() private val compositeDisposable = CompositeDisposable()
protected lateinit var getResult: ActivityResultLauncher<Intent>
@LayoutRes @LayoutRes
abstract fun getLayoutId(): Int abstract fun getLayoutId(): Int
@ -47,18 +43,6 @@ abstract class EoBaseActivity<B : ViewDataBinding> : 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) { override fun toast(message: String) {
Toast.makeText(this@EoBaseActivity, message, Toast.LENGTH_SHORT).show() Toast.makeText(this@EoBaseActivity, message, Toast.LENGTH_SHORT).show()
} }
@ -83,26 +67,5 @@ abstract class EoBaseActivity<B : ViewDataBinding> : NoSplashAppCompatActivity()
} }
} }
override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair<String, Any?>) {
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) fun Disposable.addTo() = addTo(compositeDisposable)
} }

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.content.Context import android.content.Context
import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
@ -74,13 +73,6 @@ abstract class EoBaseFragment<B : ViewDataBinding> : DaggerFragment(), EoBaseNav
override fun finish(finishAffinity: Boolean) { override fun finish(finishAffinity: Boolean) {
baseActivity?.finish(finishAffinity) baseActivity?.finish(finishAffinity)
} }
override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair<String, Any?>) {
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) fun Disposable.addTo() = addTo(compositeDisposable)

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.annotation.StringRes import androidx.annotation.StringRes
interface EoBaseNavigator { interface EoBaseNavigator {
@ -13,8 +10,4 @@ interface EoBaseNavigator {
fun back() fun back()
fun finish(finishAffinity: Boolean = false) fun finish(finishAffinity: Boolean = false)
fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair<String, Any?>)
fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)? = null, onDiscard: (() -> Unit)? = null, goHomeAfterDiscard: Boolean = true)
} }

View file

@ -1,14 +1,13 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.app.Dialog import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.media.MediaPlayer import android.media.MediaPlayer
import android.media.RingtoneManager import android.media.RingtoneManager
import android.os.Bundle import android.os.Bundle
import android.view.MotionEvent import android.view.MotionEvent
import androidx.lifecycle.Observer import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider
import info.nightscout.androidaps.plugins.pump.eopatch.R import info.nightscout.androidaps.plugins.pump.eopatch.R
import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchLifecycle 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.databinding.ActivityEopatchBinding
import info.nightscout.androidaps.plugins.pump.eopatch.extension.replaceFragmentInActivity 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.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.plugins.pump.eopatch.ui.viewmodel.EopatchViewModel
import info.nightscout.androidaps.utils.alertDialogs.AlertDialogHelper import info.nightscout.androidaps.utils.alertDialogs.AlertDialogHelper
@ -24,7 +24,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
private var mediaPlayer: MediaPlayer? = null private var mediaPlayer: MediaPlayer? = null
private var mPatchCommCheckDialog: Dialog? = null private var mPatchCommCheckDialog: Dialog? = null
private var mProgressDialog: ProgressDialog? = null private var mProgressDialog: AlertDialog? = null
override fun getLayoutId(): Int = R.layout.activity_eopatch override fun getLayoutId(): Int = R.layout.activity_eopatch
@ -44,15 +44,16 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
viewModel?.apply { viewModel?.apply {
processIntent(intent) processIntent(intent)
patchStep.observe(this@EopatchActivity, { patchStep.observe(this@EopatchActivity) {
when (it) { when (it) {
PatchStep.SAFE_DEACTIVATION -> { PatchStep.SAFE_DEACTIVATION -> {
if(isActivated.value?:false){ if (isActivated.value == true) {
setupViewFragment(EopatchSafeDeactivationFragment.newInstance()) setupViewFragment(EopatchSafeDeactivationFragment.newInstance())
} else { } else {
this@EopatchActivity.finish() this@EopatchActivity.finish()
} }
} }
PatchStep.MANUALLY_TURNING_OFF_ALARM -> setupViewFragment(EopatchTurningOffAlarmFragment.newInstance()) PatchStep.MANUALLY_TURNING_OFF_ALARM -> setupViewFragment(EopatchTurningOffAlarmFragment.newInstance())
PatchStep.DISCARDED_FOR_CHANGE, PatchStep.DISCARDED_FOR_CHANGE,
PatchStep.DISCARDED_FROM_ALARM, PatchStep.DISCARDED_FROM_ALARM,
@ -67,7 +68,8 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance()) PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance())
// PatchStep.SETTING_REMINDER_TIME -> setupViewFragment(PatchExpirationReminderSettingFragment.newInstance()) // PatchStep.SETTING_REMINDER_TIME -> setupViewFragment(PatchExpirationReminderSettingFragment.newInstance())
PatchStep.CHECK_CONNECTION -> { PatchStep.CHECK_CONNECTION -> {
checkCommunication({ checkCommunication(
{
setResult(RESULT_OK) setResult(RESULT_OK)
this@EopatchActivity.finish() this@EopatchActivity.finish()
}, { }, {
@ -81,22 +83,26 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} else { } else {
this@EopatchActivity.finish() this@EopatchActivity.finish()
} }
}, doIntercept = true) })
} }
PatchStep.COMPLETE -> backToHome(true) PatchStep.COMPLETE -> backToHome(true)
PatchStep.FINISH -> { PatchStep.FINISH -> {
if (!intent.getBooleanExtra(EXTRA_START_FROM_MENU, false) if (!intent.getBooleanExtra(EXTRA_START_FROM_MENU, false)
|| intent.getBooleanExtra(EXTRA_GO_HOME, true)) { || intent.getBooleanExtra(EXTRA_GO_HOME, true)
) {
backToHome(false) backToHome(false)
} else { } else {
this@EopatchActivity.finish() this@EopatchActivity.finish()
} }
} }
PatchStep.BACK_TO_HOME -> backToHome(false) PatchStep.BACK_TO_HOME -> backToHome(false)
PatchStep.CANCEL -> this@EopatchActivity.finish() PatchStep.CANCEL -> this@EopatchActivity.finish()
else -> Unit else -> Unit
} }
}) }
} }
} }
} }
@ -129,14 +135,12 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} }
} }
UIEventTypeHandler.observe(this@EopatchActivity, Observer { evt -> eventHandler.observe(this@EopatchActivity) { evt ->
when (evt.peekContent()) { when (evt.peekContent()) {
EventType.SHOW_PATCH_COMM_DIALOG -> { EventType.SHOW_PATCH_COMM_DIALOG -> {
if (mProgressDialog == null) { if (mProgressDialog == null) {
mProgressDialog = ProgressDialog(this@EopatchActivity).apply { mProgressDialog = ProgressDialogHelper.get(this@EopatchActivity, getString(evt.value as Int)).apply {
setMessage(getString(evt.value as Int))
setCancelable(false) setCancelable(false)
setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal)
} }
mProgressDialog?.show() mProgressDialog?.show()
} }
@ -149,19 +153,19 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
EventType.SHOW_PATCH_COMM_ERROR_DIALOG -> { EventType.SHOW_PATCH_COMM_ERROR_DIALOG -> {
dismissRetryDialog() dismissRetryDialog()
if (patchStep.value?.isSafeDeactivation?:false || connectionTryCnt >= 2) { if (patchStep.value?.isSafeDeactivation == true || connectionTryCnt >= 2) {
val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel) 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)}" 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) mPatchCommCheckDialog = AlertDialogHelper.Builder(this@EopatchActivity)
.setTitle(R.string.patch_communication_failed) .setTitle(R.string.patch_communication_failed)
.setMessage(message) .setMessage(message)
.setCancelable(false) .setCancelable(false)
.setPositiveButton(R.string.discard, { dialog, which -> .setPositiveButton(R.string.discard) { _, _ ->
discardPatch() discardPatch()
}) }
.setNegativeButton(cancelLabel, { dialog, which -> .setNegativeButton(cancelLabel) { _, _ ->
cancelPatchCommCheck() cancelPatchCommCheck()
}) }
.show() .show()
} else { } else {
val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel) val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel)
@ -170,12 +174,12 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
.setTitle(R.string.patch_communication_failed) .setTitle(R.string.patch_communication_failed)
.setMessage(message) .setMessage(message)
.setCancelable(false) .setCancelable(false)
.setPositiveButton(R.string.retry, { dialog, which -> .setPositiveButton(R.string.retry) { _, _ ->
retryCheckCommunication() retryCheckCommunication()
}) }
.setNegativeButton(cancelLabel, { dialog, which -> .setNegativeButton(cancelLabel) { _, _ ->
cancelPatchCommCheck() cancelPatchCommCheck()
}) }
.show() .show()
} }
} }
@ -185,31 +189,34 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
AlertDialogHelper.Builder(this@EopatchActivity) AlertDialogHelper.Builder(this@EopatchActivity)
.setTitle(R.string.patch_communication_succeed) .setTitle(R.string.patch_communication_succeed)
.setMessage(R.string.patch_communication_succeed_message) .setMessage(R.string.patch_communication_succeed_message)
.setPositiveButton(R.string.confirm, { dialog, which -> .setPositiveButton(R.string.confirm) { _, _ ->
dismissPatchCommCheckDialogInternal(true) dismissPatchCommCheckDialogInternal(true)
}).show() }.show()
} }
EventType.SHOW_CHANGE_PATCH_DIALOG -> { EventType.SHOW_CHANGE_PATCH_DIALOG -> {
AlertDialogHelper.Builder(this@EopatchActivity).apply { AlertDialogHelper.Builder(this@EopatchActivity).apply {
setTitle(R.string.string_discard_patch) setTitle(R.string.string_discard_patch)
setMessage(when { setMessage(
when {
patchState.isBolusActive && patchState.isTempBasalActive -> { patchState.isBolusActive && patchState.isTempBasalActive -> {
R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc
} }
patchState.isBolusActive -> R.string.patch_change_confirm_bolus_is_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 patchState.isTempBasalActive -> R.string.patch_change_confirm_temp_basal_is_active_desc
else -> R.string.patch_change_confirm_desc else -> R.string.patch_change_confirm_desc
}) }
setPositiveButton(R.string.string_discard_patch, { dialog, which -> )
setPositiveButton(R.string.string_discard_patch) { _, _ ->
deactivatePatch() deactivatePatch()
}) }
setNegativeButton(R.string.cancel, { dialog, which -> setNegativeButton(R.string.cancel) { _, _ ->
}) }
}.show() }.show()
} }
EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish() // EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish()
EventType.SHOW_DISCARD_DIALOG -> { EventType.SHOW_DISCARD_DIALOG -> {
AlertDialogHelper.Builder(this@EopatchActivity).apply { AlertDialogHelper.Builder(this@EopatchActivity).apply {
setTitle(R.string.string_discard_patch) setTitle(R.string.string_discard_patch)
@ -218,7 +225,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} else { } else {
setMessage(R.string.string_are_you_sure_to_discard_current_patch) setMessage(R.string.string_are_you_sure_to_discard_current_patch)
} }
setPositiveButton(R.string.discard, { dialog, which -> setPositiveButton(R.string.discard) { _, _ ->
deactivate(true) { deactivate(true) {
dismissPatchCommCheckDialogInternal() dismissPatchCommCheckDialogInternal()
@ -228,17 +235,18 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
this@EopatchActivity.finish() this@EopatchActivity.finish()
} }
} }
}) }
setNegativeButton(R.string.cancel, { dialog, which -> setNegativeButton(R.string.cancel) { _, _ ->
dismissProgressDialog() dismissProgressDialog()
updateIncompletePatchActivationReminder() updateIncompletePatchActivationReminder()
}) }
}.show() }.show()
} }
else -> Unit else -> Unit
} }
}) }
} }
} }
@ -302,9 +310,8 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
const val EXTRA_START_WITH_COMM_CHECK = "EXTRA_START_WITH_COMM_CHECK" const val EXTRA_START_WITH_COMM_CHECK = "EXTRA_START_WITH_COMM_CHECK"
const val EXTRA_GO_HOME = "EXTRA_GO_HOME" const val EXTRA_GO_HOME = "EXTRA_GO_HOME"
const val EXTRA_FORCE_DISCARD = "EXTRA_FORCE_DISCARD" const val EXTRA_FORCE_DISCARD = "EXTRA_FORCE_DISCARD"
@JvmField val PATCH_INITIAL_VOLTAGE_MIN = 2700 const val NORMAL_TEMPERATURE_MIN = 4
@JvmField val NORMAL_TEMPERATURE_MIN = 4 const val NORMAL_TEMPERATURE_MAX = 45
@JvmField val NORMAL_TEMPERATURE_MAX = 45
@JvmStatic @JvmStatic
@JvmOverloads @JvmOverloads
@ -316,11 +323,6 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} }
} }
@JvmStatic
fun createIntentForActivatePatch(context: Context): Intent {
return createIntent(context, PatchStep.WAKE_UP, false)
}
@JvmStatic @JvmStatic
fun createIntentForChangePatch(context: Context): Intent { fun createIntentForChangePatch(context: Context): Intent {
return createIntent(context, PatchStep.SAFE_DEACTIVATION, false) return createIntent(context, PatchStep.SAFE_DEACTIVATION, false)
@ -335,7 +337,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} }
@JvmStatic @JvmStatic
fun createIntentForCanularInsertionError(context: Context): Intent { fun createIntentForCannulaInsertionError(context: Context): Intent {
return createIntent(context, PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR, false) return createIntent(context, PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR, false)
} }
@ -383,7 +385,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
} }
} }
fun setupViewFragment(baseFragment: EoBaseFragment<*>) { private fun setupViewFragment(baseFragment: EoBaseFragment<*>) {
replaceFragmentInActivity(baseFragment, R.id.framelayout_fragment, false) replaceFragmentInActivity(baseFragment, R.id.framelayout_fragment, false)
} }
} }

View file

@ -23,7 +23,7 @@ class EopatchConnectNewFragment : EoBaseFragment<FragmentEopatchConnectNewBindin
binding.apply { binding.apply {
viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(EopatchViewModel::class.java) viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(EopatchViewModel::class.java)
viewModel?.apply { viewModel?.apply {
setupStep.observe(viewLifecycleOwner, { setupStep.observe(viewLifecycleOwner) {
when (it) { when (it) {
SCAN_FAILED, SCAN_FAILED,
BONDING_FAILED -> checkCommunication({ retryScan() }, { moveStep(PatchStep.WAKE_UP) }) BONDING_FAILED -> checkCommunication({ retryScan() }, { moveStep(PatchStep.WAKE_UP) })
@ -32,7 +32,7 @@ class EopatchConnectNewFragment : EoBaseFragment<FragmentEopatchConnectNewBindin
ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show() ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show()
else -> Unit else -> Unit
} }
}) }
startScan() startScan()
} }

View file

@ -1,28 +1,23 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui package info.nightscout.androidaps.plugins.pump.eopatch.ui
import android.app.AlertDialog import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent import android.content.Intent
import android.os.Bundle import android.os.Bundle
import android.view.View import android.view.View
import android.widget.Toast 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 androidx.lifecycle.ViewModelProvider
import dagger.android.support.DaggerAppCompatActivity import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.eopatch.R 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.core.code.BolusType
import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchStep 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.code.EventType
import info.nightscout.androidaps.plugins.pump.eopatch.databinding.FragmentEopatchOverviewBinding 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.extension.takeOne
import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchOverviewViewModel 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.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -32,8 +27,11 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
@Inject lateinit var rxBus: RxBus @Inject lateinit var rxBus: RxBus
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
private lateinit var resultLauncherForResume: ActivityResultLauncher<Intent>
private lateinit var resultLauncherForPause: ActivityResultLauncher<Intent>
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private var pauseDuration = 0.5f
override fun getLayoutId(): Int = R.layout.fragment_eopatch_overview override fun getLayoutId(): Int = R.layout.fragment_eopatch_overview
@ -48,21 +46,42 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
binding.apply { binding.apply {
viewmodel = ViewModelProvider(this@EopatchOverviewFragment, viewModelFactory).get(EopatchOverviewViewModel::class.java) viewmodel = ViewModelProvider(this@EopatchOverviewFragment, viewModelFactory).get(EopatchOverviewViewModel::class.java)
viewmodel?.apply { viewmodel?.apply {
UIEventTypeHandler.observe(viewLifecycleOwner, Observer { evt -> eventHandler.observe(viewLifecycleOwner) { evt ->
when (evt.peekContent()) { when (evt.peekContent()) {
EventType.ACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentFromMenu(it, PatchStep.WAKE_UP)) } EventType.ACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentFromMenu(this, PatchStep.WAKE_UP)) }
EventType.DEACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentForChangePatch(it)) } EventType.DEACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentForChangePatch(this)) }
EventType.SUSPEND_CLICKED -> suspend() EventType.SUSPEND_CLICKED -> suspend()
EventType.RESUME_CLICKED -> resume() EventType.RESUME_CLICKED -> resume()
EventType.INVALID_BASAL_RATE -> Toast.makeText(activity, R.string.unsupported_basal_rate, Toast.LENGTH_SHORT).show() EventType.INVALID_BASAL_RATE -> showToast(R.string.unsupported_basal_rate)
EventType.PROFILE_NOT_SET -> Toast.makeText(activity, R.string.no_profile_selected, Toast.LENGTH_SHORT).show() 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 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() { private fun suspend() {
@ -73,12 +92,12 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
val dialog = builder.setTitle(R.string.string_suspend) val dialog = builder.setTitle(R.string.string_suspend)
.setMessage(msg) .setMessage(msg)
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> .setPositiveButton(R.string.confirm) { _, _ ->
openPauseTimePicker() openPauseTimePicker()
}) }
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which -> .setNegativeButton(R.string.cancel) { _, _ ->
}).create() }.create()
dialog.show() dialog.show()
} }
} }
@ -90,18 +109,16 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
val builder = AlertDialog.Builder(it) val builder = AlertDialog.Builder(it)
val dialog = builder.setTitle(R.string.string_resume_insulin_delivery_title) val dialog = builder.setTitle(R.string.string_resume_insulin_delivery_title)
.setMessage(R.string.string_resume_insulin_delivery_message) .setMessage(R.string.string_resume_insulin_delivery_message)
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> .setPositiveButton(R.string.confirm) { _, _ ->
if (isPatchConnected) { if (isPatchConnected) {
resumeBasal() resumeBasal()
} else { } else {
checkCommunication({ resultLauncherForResume.launch(EopatchActivity.createIntentForCheckConnection(requireContext(), true))
resumeBasal()
})
} }
}) }
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which -> .setNegativeButton(R.string.cancel) { _, _ ->
}).create() }.create()
dialog.show() dialog.show()
} }
} }
@ -114,21 +131,20 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
val listArr = requireContext().resources.getStringArray(R.array.suspend_duration_array) val listArr = requireContext().resources.getStringArray(R.array.suspend_duration_array)
var select = 0 var select = 0
val dialog = builder.setTitle(R.string.string_suspend_time_insulin_delivery_title) 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 select = which
}) }
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which -> .setPositiveButton(R.string.confirm) { _, _ ->
if (isPatchConnected) { if (isPatchConnected) {
pauseBasal((select + 1) * 0.5f) pauseBasal((select + 1) * 0.5f)
} else { } else {
checkCommunication({ pauseDuration = (select + 1) * 0.5f
pauseBasal((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() dialog.show()
} }
} }
@ -158,26 +174,4 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
} }
return "" return ""
} }
override fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair<String, Any?>) {
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()
}
} }

View file

@ -39,14 +39,14 @@ class EopatchRotateKnobFragment : EoBaseFragment<FragmentEopatchRotateKnobBindin
textRotateKnobDesc2NeedleInsertionError.visibility = View.VISIBLE textRotateKnobDesc2NeedleInsertionError.visibility = View.VISIBLE
} }
setupStep.observe(viewLifecycleOwner, { setupStep.observe(viewLifecycleOwner) {
when (it) { when (it) {
EopatchViewModel.SetupStep.NEEDLE_SENSING_FAILED -> { EopatchViewModel.SetupStep.NEEDLE_SENSING_FAILED -> {
checkCommunication({ startNeedleSensing() }) checkCommunication({ startNeedleSensing() })
} }
else -> Unit else -> Unit
} }
}) }
} }
} }
} }

View file

@ -24,12 +24,12 @@ class EopatchSafetyCheckFragment : EoBaseFragment<FragmentEopatchSafetyCheckBind
viewModel?.apply { viewModel?.apply {
initPatchStep() initPatchStep()
setupStep.observe(viewLifecycleOwner, { setupStep.observe(viewLifecycleOwner) {
when (it) { when (it) {
SAFETY_CHECK_FAILED -> checkCommunication({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) }) SAFETY_CHECK_FAILED -> checkCommunication({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) })
else -> Unit else -> Unit
} }
}) }
startSafetyCheck() startSafetyCheck()
} }

View file

@ -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.databinding.DialogCommonBinding
import info.nightscout.androidaps.plugins.pump.eopatch.ui.DialogHelperActivity import info.nightscout.androidaps.plugins.pump.eopatch.ui.DialogHelperActivity
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity
import io.reactivex.disposables.Disposable
import javax.inject.Inject import javax.inject.Inject
class ActivationNotCompleteDialog : DaggerDialogFragment() { class ActivationNotCompleteDialog : DaggerDialogFragment() {
@ -24,7 +23,6 @@ class ActivationNotCompleteDialog : DaggerDialogFragment() {
var title: String = "" var title: String = ""
private var _binding: DialogCommonBinding? = null private var _binding: DialogCommonBinding? = null
private var disposable: Disposable? = null
private val binding get() = _binding!! private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs
import android.os.Build import android.os.Build
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.HandlerThread
import android.view.* import android.view.*
import dagger.android.support.DaggerDialogFragment import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.R
@ -32,13 +33,13 @@ class AlarmDialog : DaggerDialogFragment() {
var helperActivity: AlarmHelperActivity? = null var helperActivity: AlarmHelperActivity? = null
var alarmCode: AlarmCode? = null var alarmCode: AlarmCode? = null
var code: String = "" var code: String? = null
var status: String = "" var status: String = ""
var title: String = "" var title: String = ""
var sound: Int = 0 var sound: Int = 0
private lateinit var mAlarmProcess: IAlarmProcess 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 _binding: DialogAlarmBinding? = null
private var disposable: Disposable? = null private var disposable: Disposable? = null
@ -107,7 +108,7 @@ class AlarmDialog : DaggerDialogFragment() {
aapsLogger.debug("USER ENTRY: Error dialog mute 5 min button pressed") aapsLogger.debug("USER ENTRY: Error dialog mute 5 min button pressed")
stopAlarm() stopAlarm()
isMute = true isMute = true
loopHandler.postDelayed(this::startAlarm, T.mins(5).msecs()) handler.postDelayed(this::startAlarm, T.mins(5).msecs())
} }
startAlarm() startAlarm()
@ -150,7 +151,7 @@ class AlarmDialog : DaggerDialogFragment() {
override fun dismiss() { override fun dismiss() {
super.dismissAllowingStateLoss() super.dismissAllowingStateLoss()
loopHandler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
helperActivity?.finish() helperActivity?.finish()
} }

View file

@ -28,12 +28,12 @@ class CommonDialog : DaggerDialogFragment() {
if(title != 0) setTitle(title) if(title != 0) setTitle(title)
if(message != 0) setMessage(message) if(message != 0) setMessage(message)
setPositiveButton(positiveBtn, setPositiveButton(positiveBtn,
positiveListener?:DialogInterface.OnClickListener { dialog, which -> positiveListener?:DialogInterface.OnClickListener { _, _ ->
dismiss() dismiss()
}) })
if(negativeBtn != 0) { if(negativeBtn != 0) {
setNegativeButton(negativeBtn, setNegativeButton(negativeBtn,
negativeListener ?: DialogInterface.OnClickListener { dialog, which -> negativeListener ?: DialogInterface.OnClickListener { _, _ ->
dismiss() dismiss()
}) })
} }

View file

@ -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
}
}
}

View file

@ -4,17 +4,16 @@ import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer import androidx.lifecycle.Observer
import androidx.annotation.MainThread import androidx.annotation.MainThread
import android.util.Log
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
open class SingleLiveEvent<T> : MutableLiveData<T>() { open class SingleLiveEvent<T> : MutableLiveData<T>() {
private val mPending = AtomicBoolean(false) private val mPending = AtomicBoolean(false)
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, Observer { t -> super.observe(owner) { t ->
if (mPending.compareAndSet(true, false)) { if (mPending.compareAndSet(true, false)) {
observer.onChanged(t) observer.onChanged(t)
} }
}) }
} }
@MainThread @MainThread

View file

@ -6,10 +6,8 @@ import android.content.Intent
import android.content.IntentFilter import android.content.IntentFilter
import androidx.annotation.CheckResult import androidx.annotation.CheckResult
import io.reactivex.android.MainThreadDisposable import io.reactivex.android.MainThreadDisposable
import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver.BroadcastReceiverObservable
import io.reactivex.Observable import io.reactivex.Observable
import io.reactivex.Observer import io.reactivex.Observer
import java.lang.AssertionError
class RxBroadcastReceiver private constructor() { class RxBroadcastReceiver private constructor() {
internal class BroadcastReceiverObservable : Observable<Intent> { internal class BroadcastReceiverObservable : Observable<Intent> {
@ -31,7 +29,7 @@ class RxBroadcastReceiver private constructor() {
} }
override fun subscribeActual(observer: Observer<in Intent>) { override fun subscribeActual(observer: Observer<in Intent>) {
val listener: Listener = Listener(context, observer) val listener = Listener(context, observer)
observer.onSubscribe(listener) observer.onSubscribe(listener)
context.registerReceiver(listener.receiver, intentFilter) context.registerReceiver(listener.receiver, intentFilter)
} }

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel 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 androidx.lifecycle.ViewModel
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -26,10 +23,6 @@ abstract class EoBaseViewModel<N : EoBaseNavigator> : ViewModel() {
super.onCleared() super.onCleared()
} }
fun blockTouchEvent(view: View, motionEvent: MotionEvent): Boolean {
return true
}
fun back() = navigator?.back() fun back() = navigator?.back()
fun finish() = navigator?.finish() fun finish() = navigator?.finish()

View file

@ -21,6 +21,7 @@ import io.reactivex.Observable
import io.reactivex.disposables.Disposable import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import javax.inject.Inject import javax.inject.Inject
import kotlin.math.max
import kotlin.math.roundToInt import kotlin.math.roundToInt
class EopatchOverviewViewModel @Inject constructor( class EopatchOverviewViewModel @Inject constructor(
@ -31,7 +32,7 @@ class EopatchOverviewViewModel @Inject constructor(
private val aapsSchedulers: AapsSchedulers private val aapsSchedulers: AapsSchedulers
) : EoBaseViewModel<EoBaseNavigator>() { ) : EoBaseViewModel<EoBaseNavigator>() {
private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>() private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>()
val UIEventTypeHandler : LiveData<UIEvent<EventType>> val eventHandler : LiveData<UIEvent<EventType>>
get() = _eventHandler get() = _eventHandler
private val _patchConfig = SingleLiveEvent<PatchConfig>() private val _patchConfig = SingleLiveEvent<PatchConfig>()
@ -58,6 +59,10 @@ class EopatchOverviewViewModel @Inject constructor(
val status : LiveData<String> val status : LiveData<String>
get() = _status get() = _status
private val _pauseBtnStr = SingleLiveEvent<String>()
val pauseBtnStr : LiveData<String>
get() = _pauseBtnStr
private val _alarms = SingleLiveEvent<Alarms>() private val _alarms = SingleLiveEvent<Alarms>()
val alarms : LiveData<Alarms> val alarms : LiveData<Alarms>
get() = _alarms get() = _alarms
@ -128,18 +133,18 @@ class EopatchOverviewViewModel @Inject constructor(
private fun updatePatchStatus(){ private fun updatePatchStatus(){
if(patchManager.isActivated){ if(patchManager.isActivated){
var finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis() val finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis()
var remainTimeMillis = Math.max(finishTimeMillis - System.currentTimeMillis(), 0L) val remainTimeMillis = max(finishTimeMillis - System.currentTimeMillis(), 0L)
val h = TimeUnit.MILLISECONDS.toHours(remainTimeMillis) val h = TimeUnit.MILLISECONDS.toHours(remainTimeMillis)
val m = TimeUnit.MILLISECONDS.toMinutes(remainTimeMillis - TimeUnit.HOURS.toMillis(h)) val m = TimeUnit.MILLISECONDS.toMinutes(remainTimeMillis - TimeUnit.HOURS.toMillis(h))
_status.value = if(patchManager.patchState.isNormalBasalPaused) _status.value = if(patchManager.patchState.isNormalBasalPaused)
"${rh.gs(R.string.string_suspended)}\n" + "${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_temp_basal_remained_hhmm, h.toString(), m.toString())}"
else else
rh.gs(R.string.string_running) rh.gs(R.string.string_running)
}else{ }else{
_status.value = "" _status.value = ""
} }
_pauseBtnStr.value = if(patchManager.patchState.isNormalBasalPaused) rh.gs(R.string.string_resume) else rh.gs(R.string.string_suspend)
} }
private fun updateBasalInfo(){ private fun updateBasalInfo(){
@ -166,7 +171,7 @@ class EopatchOverviewViewModel @Inject constructor(
patchManager.preferenceManager.getNormalBasalManager().setNormalBasal(profile) patchManager.preferenceManager.getNormalBasalManager().setNormalBasal(profile)
patchManager.preferenceManager.flushNormalBasalManager() patchManager.preferenceManager.flushNormalBasalManager()
_eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED)) _eventHandler.postValue(UIEvent(EventType.ACTIVATION_CLICKED))
}else if(profile != null && profile.getBasal() < 0.05){ }else if(profile != null && profile.getBasal() < 0.05){
_eventHandler.postValue(UIEvent(EventType.INVALID_BASAL_RATE)) _eventHandler.postValue(UIEvent(EventType.INVALID_BASAL_RATE))
}else{ }else{
@ -175,7 +180,7 @@ class EopatchOverviewViewModel @Inject constructor(
} }
fun onClickDeactivation(){ fun onClickDeactivation(){
_eventHandler.postValue(UIEvent(EventType.DEACTIVTION_CLICKED)) _eventHandler.postValue(UIEvent(EventType.DEACTIVATION_CLICKED))
} }
fun onClickSuspendOrResume(){ fun onClickSuspendOrResume(){
@ -190,8 +195,8 @@ class EopatchOverviewViewModel @Inject constructor(
patchManager.pauseBasal(pauseDurationHour) patchManager.pauseBasal(pauseDurationHour)
.subscribeOn(aapsSchedulers.io) .subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe({ .subscribe({ response ->
if (it.isSuccess) { if (response.isSuccess) {
navigator?.toast(R.string.string_suspended_insulin_delivery_message) navigator?.toast(R.string.string_suspended_insulin_delivery_message)
startPeriodicallyUpdate() startPeriodicallyUpdate()
} else { } else {

View file

@ -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.SingleLiveEvent
import info.nightscout.androidaps.plugins.pump.eopatch.ui.event.UIEvent 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.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.PatchLifecycleEvent
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
@ -55,24 +57,19 @@ class EopatchViewModel @Inject constructor(
var forceDiscard = false var forceDiscard = false
var connectionTryCnt = 0 var connectionTryCnt = 0
val patchConfig = patchManager.patchConfig val patchConfig: PatchConfig = patchManager.patchConfig
val patchState: PatchState = patchManager.patchState
val patchState = patchManager.patchState
private val _isActivated = MutableLiveData(patchConfig.isActivated) private val _isActivated = MutableLiveData(patchConfig.isActivated)
private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>() private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>()
val UIEventTypeHandler : LiveData<UIEvent<EventType>> val eventHandler : LiveData<UIEvent<EventType>>
get() = _eventHandler get() = _eventHandler
fun onClickActivation(){
_eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED))
}
val patchStep = MutableLiveData<PatchStep>() val patchStep = MutableLiveData<PatchStep>()
val isActivated = MutableLiveData<Boolean>(patchManager.isActivated) val isActivated = MutableLiveData(patchManager.isActivated)
val isBolusActive = patchManager.getPatchState().isBolusActive val isBolusActive = patchManager.patchState.isBolusActive
val isConnected = patchManager.patchConnectionState.isConnected val isConnected = patchManager.patchConnectionState.isConnected
val patchRemainedInsulin: LiveData<Int> val patchRemainedInsulin: LiveData<Int>
@ -86,7 +83,7 @@ class EopatchViewModel @Inject constructor(
}, 0) }, 0)
} }
private val _patchExpirationTimestamp = MutableLiveData<Long>(patchManager.patchExpiredTime) private val _patchExpirationTimestamp = MutableLiveData(patchManager.patchExpiredTime)
val patchRemainedDays: LiveData<Int> val patchRemainedDays: LiveData<Int>
get() = Transformations.map(_patchExpirationTimestamp) { get() = Transformations.map(_patchExpirationTimestamp) {
@ -106,19 +103,11 @@ class EopatchViewModel @Inject constructor(
val safetyCheckProgress: LiveData<Int> val safetyCheckProgress: LiveData<Int>
get() = _safetyCheckProgress get() = _safetyCheckProgress
private val _patchExpirationReminderTime = MutableLiveData<String>()
val patchExpirationReminderTime: LiveData<String>
get() = _patchExpirationReminderTime
private val _patchExpirationTime = MutableLiveData<String>()
val patchExpirationTime: LiveData<String>
get() = _patchExpirationTime
private val _isCommCheckFailed = MutableLiveData(false) private val _isCommCheckFailed = MutableLiveData(false)
val isCommCheckFailed: LiveData<Boolean> private val isCommCheckFailed: LiveData<Boolean>
get() = _isCommCheckFailed get() = _isCommCheckFailed
val isBonded: Boolean private val isBonded: Boolean
get() = !patchConfig.lifecycleEvent.isShutdown get() = !patchConfig.lifecycleEvent.isShutdown
val commCheckCancelLabel: LiveData<String> val commCheckCancelLabel: LiveData<String>
@ -129,15 +118,11 @@ class EopatchViewModel @Inject constructor(
} }
PatchStep.SAFE_DEACTIVATION -> R.string.patch_forced_discard PatchStep.SAFE_DEACTIVATION -> R.string.patch_forced_discard
else -> R.string.cancel else -> R.string.cancel
}) ?: "" })
} }
val programEnabledMessage: String val programEnabledMessage: String
// get() = """'기초1' program has been enabled.""" get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1")
get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1") ?: ""
val patchStepIsSafeDeactivation: Boolean
get() = patchStep.value?.isSafeDeactivation ?: false
private val _isDiscardedWithNotConn = MutableLiveData(false) private val _isDiscardedWithNotConn = MutableLiveData(false)
val isDiscardedWithNotConn: LiveData<Boolean> val isDiscardedWithNotConn: LiveData<Boolean>
@ -152,8 +137,6 @@ class EopatchViewModel @Inject constructor(
private val initPatchStepIsCheckConnection: Boolean private val initPatchStepIsCheckConnection: Boolean
get() = mInitPatchStep?.isCheckConnection ?: false get() = mInitPatchStep?.isCheckConnection ?: false
// private var mProgressDialog: PatchProgressDialog? = null
private var mCommCheckDisposable: Disposable? = null private var mCommCheckDisposable: Disposable? = null
private var mOnCommCheckSuccessListener: (() -> Unit)? = null private var mOnCommCheckSuccessListener: (() -> Unit)? = null
@ -174,8 +157,6 @@ class EopatchViewModel @Inject constructor(
private val mB012UpdateSubject = PublishSubject.create<Unit>() private val mB012UpdateSubject = PublishSubject.create<Unit>()
// private var mCurrentTextDialog: TextDialog? = null
init { init {
mB012UpdateDisposable = mB012UpdateSubject.hide() mB012UpdateDisposable = mB012UpdateSubject.hide()
.throttleFirst(500, TimeUnit.MILLISECONDS) .throttleFirst(500, TimeUnit.MILLISECONDS)
@ -222,20 +203,7 @@ class EopatchViewModel @Inject constructor(
@Synchronized @Synchronized
fun checkCommunication(onSuccessListener: () -> Unit, onCancelListener: (() -> Unit)? = null, fun checkCommunication(onSuccessListener: () -> Unit, onCancelListener: (() -> Unit)? = null,
onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false, doIntercept: Boolean = false) { onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false) {
// mPatchCommCheckDialog?.let {
// if (doIntercept) {
// mOnCommCheckSuccessListener = onSuccessListener
// mOnCommCheckCancelListener = onCancelListener
// mOnCommCheckDiscardListener = onDiscardListener
//
// if (_isCommCheckFailed.value == true) {
// retryCheckCommunication()
// }
// }
//
// }
if (doPreCheck && patchManager.patchConnectionState.isConnected) { if (doPreCheck && patchManager.patchConnectionState.isConnected) {
onSuccessListener.invoke() onSuccessListener.invoke()
return 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) _isCommCheckFailed.postValue(defaultFailedCondition)
_eventHandler.postValue(UIEvent(EventType.SHOW_PATCH_COMM_DIALOG).apply { _eventHandler.postValue(UIEvent(EventType.SHOW_PATCH_COMM_DIALOG).apply {
value = title value = title
@ -307,7 +275,7 @@ class EopatchViewModel @Inject constructor(
} }
private fun dismissPatchCommCheckDialog() { private fun dismissPatchCommCheckDialog() {
if (_isCommCheckFailed.value == false) { if (isCommCheckFailed.value == false) {
if (isBonded) { if (isBonded) {
_eventHandler.postValue(UIEvent(EventType.SHOW_BONDED_DIALOG)) _eventHandler.postValue(UIEvent(EventType.SHOW_BONDED_DIALOG))
} else { } 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( PatchLifecycle.SHUTDOWN -> patchConfig.isDeactivated.takeOne(
PatchStep.WAKE_UP, PatchStep.SAFE_DEACTIVATION) PatchStep.WAKE_UP, PatchStep.SAFE_DEACTIVATION)
PatchLifecycle.BONDED -> PatchStep.CONNECT_NEW PatchLifecycle.BONDED -> PatchStep.CONNECT_NEW
@ -567,13 +535,6 @@ class EopatchViewModel @Inject constructor(
} }
private fun onClear() { private fun onClear() {
// _patchExpirationTime.value = null
// _rotateKnobRawRes.value = null
// _patchExpirationReminderTime.value = null
// _title.value = null
// mProgressDialog = null
// mPatchCommCheckDialog = null
// mCurrentTextDialog = null
mOnCommCheckSuccessListener = null mOnCommCheckSuccessListener = null
mOnCommCheckCancelListener = null mOnCommCheckCancelListener = null
mOnCommCheckDiscardListener = null mOnCommCheckDiscardListener = null
@ -691,7 +652,7 @@ class EopatchViewModel @Inject constructor(
.doOnSubscribe { updateSetupStep(BONDING_STARTED) } .doOnSubscribe { updateSetupStep(BONDING_STARTED) }
.filter { result -> result } .filter { result -> result }
.toSingle() // 실패시 에러 반환. .toSingle() // 실패시 에러 반환.
.doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createbonded()) } .doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createBonded()) }
.doOnError { .doOnError {
if (it is TimeoutException) { if (it is TimeoutException) {
moveStep(PatchStep.WAKE_UP) moveStep(PatchStep.WAKE_UP)

View file

@ -30,6 +30,7 @@ class ViewModelFactory @Inject constructor(private val creators: Map<Class<out V
throw IllegalArgumentException("unknown model class $modelClass") throw IllegalArgumentException("unknown model class $modelClass")
} }
try { try {
@Suppress("UNCHECKED_CAST")
return creator.get() as T return creator.get() as T
} catch (e: Exception) { } catch (e: Exception) {
throw IllegalStateException(e) throw IllegalStateException(e)

View file

@ -1,9 +0,0 @@
package info.nightscout.androidaps.plugins.pump.eopatch.vo
import android.content.Intent
data class ActivityResultEvent(
val requestCode: Int,
val resultCode: Int,
val data: Intent? = null
)

View file

@ -8,7 +8,7 @@ import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.BehaviorSubject
import java.util.* import java.util.*
class Alarms(): IPreference<Alarms> { class Alarms: IPreference<Alarms> {
@Transient @Transient
private val subject: BehaviorSubject<Alarms> = BehaviorSubject.create() private val subject: BehaviorSubject<Alarms> = BehaviorSubject.create()
@ -24,7 +24,7 @@ class Alarms(): IPreference<Alarms> {
var registered = HashMap<AlarmCode, AlarmItem>() var registered = HashMap<AlarmCode, AlarmItem>()
var occured = HashMap<AlarmCode, AlarmItem>() var occurred = HashMap<AlarmCode, AlarmItem>()
init { init {
initObject() initObject()
@ -35,52 +35,52 @@ class Alarms(): IPreference<Alarms> {
fun clear(){ fun clear(){
registered.clear() registered.clear()
occured.clear() occurred.clear()
} }
fun update(other: Alarms) { fun update(other: Alarms) {
registered = other.registered 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 { val item = AlarmItem().apply {
alarmCode = alarmcode this.alarmCode = alarmCode
createTimestamp = System.currentTimeMillis() createTimestamp = System.currentTimeMillis()
triggerTimeMilli = createTimestamp + triggerAfter triggerTimeMilli = createTimestamp + triggerAfter
} }
if (isRegistered(alarmcode)){ if (isRegistered(alarmCode)){
registered.remove(alarmcode) registered.remove(alarmCode)
} }
registered.put(alarmcode, item) registered.put(alarmCode, item)
} }
fun unregister(alarmcode: AlarmCode) { fun unregister(alarmCode: AlarmCode) {
if (isRegistered(alarmcode)){ if (isRegistered(alarmCode)){
registered.remove(alarmcode) registered.remove(alarmCode)
} }
} }
fun occured(alarmcode: AlarmCode) { fun occurred(alarmCode: AlarmCode) {
val item: AlarmItem? = registered.get(alarmcode) val item: AlarmItem? = registered.get(alarmCode)
if (!isOccuring(alarmcode) && item != null) if (!isOccurring(alarmCode) && item != null)
occured.put(alarmcode, item) occurred.put(alarmCode, item)
if (isRegistered(alarmcode)) if (isRegistered(alarmCode))
registered.remove(alarmcode) registered.remove(alarmCode)
} }
fun handle(alarmcode: AlarmCode) { fun handle(alarmCode: AlarmCode) {
if (isOccuring(alarmcode)) if (isOccurring(alarmCode))
occured.remove(alarmcode) occurred.remove(alarmCode)
} }
fun isRegistered(alarmcode: AlarmCode): Boolean{ private fun isRegistered(alarmCode: AlarmCode): Boolean{
return registered.containsKey(alarmcode) return registered.containsKey(alarmCode)
} }
fun isOccuring(alarmcode: AlarmCode): Boolean{ fun isOccurring(alarmCode: AlarmCode): Boolean{
return occured.containsKey(alarmcode) return occurred.containsKey(alarmCode)
} }
override fun observe(): Observable<Alarms> { override fun observe(): Observable<Alarms> {
@ -94,15 +94,6 @@ class Alarms(): IPreference<Alarms> {
} }
override fun toString(): String { 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()
} }
} }
}

View file

@ -17,11 +17,11 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl
this.endMinute = end 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) return BasalSegment(startMinute, endMinute, doseUnitPerHour)
} }
internal override fun deep(): BasalSegment { override fun deep(): BasalSegment {
return BasalSegment(startMinute, endMinute, doseUnitPerHour) return BasalSegment(startMinute, endMinute, doseUnitPerHour)
} }
@ -29,8 +29,8 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl
segment.doseUnitPerHour = doseUnitPerHour segment.doseUnitPerHour = doseUnitPerHour
} }
internal override fun equalValue(segment: BasalSegment): Boolean { override fun equalValue(segment: BasalSegment): Boolean {
return segment != null && doseUnitPerHour == segment.doseUnitPerHour return doseUnitPerHour == segment.doseUnitPerHour
} }
companion object { companion object {

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.eopatch.vo 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.AppConstant
import info.nightscout.androidaps.plugins.pump.eopatch.GsonHelper import info.nightscout.androidaps.plugins.pump.eopatch.GsonHelper
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType
@ -179,16 +178,4 @@ class BolusCurrent(): IPreference<BolusCurrent> {
override fun toString(): String { override fun toString(): String {
return "BolusCurrent(nowBolus=$nowBolus, extBolus=$extBolus)" return "BolusCurrent(nowBolus=$nowBolus, extBolus=$extBolus)"
} }
companion object {
const val NAME = "BOLUS_CURRENT"
@JvmStatic
fun createEmpty(): BolusCurrent {
return BolusCurrent()
}
}
} }

View file

@ -4,6 +4,6 @@ import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.Observable import io.reactivex.Observable
interface IPreference<T>{ interface IPreference<T>{
open fun flush(sp: SP) fun flush(sp: SP)
open fun observe(): Observable<T> fun observe(): Observable<T>
} }

Some files were not shown because too many files have changed in this diff Show more