Eliminate warnings and fix bug
This commit is contained in:
parent
e4858e34bf
commit
7934851bf6
|
@ -163,6 +163,10 @@ android {
|
|||
}
|
||||
|
||||
useLibrary "org.apache.http.legacy"
|
||||
|
||||
dataBinding { //Deleting it causes a binding error
|
||||
enabled = true
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
|
|
Binary file not shown.
|
@ -105,6 +105,7 @@
|
|||
<item>DanaRv2</item>
|
||||
<item>DanaI</item>
|
||||
<item>Diaconn G8</item>
|
||||
<item>Eoflow Eopatch2</item>
|
||||
<item>Medtronic 512/712</item>
|
||||
<item>Medtronic 515/715</item>
|
||||
<item>Medtronic 522/722</item>
|
||||
|
|
|
@ -330,6 +330,7 @@ enum class PumpType {
|
|||
baseBasalStep = 0.05,
|
||||
baseBasalSpecialSteps = null,
|
||||
pumpCapability = PumpCapability.EopatchCapabilities,
|
||||
isPatchPump = true,
|
||||
source = Sources.EOPatch2);
|
||||
|
||||
val description: String
|
||||
|
|
|
@ -26,20 +26,12 @@ allprojects {
|
|||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation (name: 'eopatch_core', ext: 'aar')
|
||||
// implementation (files("libs/eopatch_core.aar"))
|
||||
implementation project(':core')
|
||||
implementation project(':shared')
|
||||
implementation project(':database')
|
||||
|
||||
implementation 'androidx.core:core-ktx:1.6.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.3.1'
|
||||
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
|
||||
|
||||
// RxJava
|
||||
implementation "io.reactivex.rxjava2:rxjava:$rxjava_version"
|
||||
implementation "io.reactivex.rxjava2:rxkotlin:$rxkotlin_version"
|
||||
implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version"
|
||||
|
||||
//RxAndroidBle
|
||||
implementation "com.polidea.rxandroidble2:rxandroidble:$rxandroidble_version"
|
||||
implementation "com.jakewharton.rx2:replaying-share:$replayshare_version"
|
||||
implementation "com.polidea.rxandroidble2:rxandroidble:1.12.1"
|
||||
implementation "com.jakewharton.rx2:replaying-share:2.2.0"
|
||||
}
|
Binary file not shown.
|
@ -3,7 +3,6 @@
|
|||
package="info.nightscout.androidaps.plugins.pump.eopatch">
|
||||
|
||||
<application>
|
||||
|
||||
<activity android:name=".ui.EopatchActivity" />
|
||||
<activity android:name=".ui.AlarmHelperActivity" />
|
||||
<activity android:name=".ui.DialogHelperActivity" />
|
||||
|
|
|
@ -1,87 +1,29 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch
|
||||
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
interface AppConstant {
|
||||
companion object {
|
||||
const val BASAL_MIN_AMOUNT = 0.05f
|
||||
|
||||
val BASAL_MIN_AMOUNT = 0.05f
|
||||
val CLICK_THROTTLE = 600L
|
||||
const val INSULIN_UNIT_P = 0.05f
|
||||
|
||||
/**
|
||||
* Bluetooth Connection State
|
||||
*/
|
||||
val BT_STATE_NOT_CONNECT = 1
|
||||
val BT_STATE_CONNECTED = 2
|
||||
const val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P
|
||||
|
||||
const val OFF = 0
|
||||
const val ON = 1
|
||||
|
||||
val INSULIN_DECIMAL_PLACE_VAR = 100f // 10.f; 소수점자리수 계산상수 (100.f 는 두자리)
|
||||
const val PUMP_DURATION_MILLI = 4 * 1000L
|
||||
|
||||
// 패치 1P = 1 cycle = 0.1U
|
||||
const val INSULIN_UNIT_P = 0.05f // 최소 주입 단위
|
||||
const val BASAL_RATE_PER_HOUR_MIN = BASAL_MIN_AMOUNT
|
||||
|
||||
val INSULIN_UNIT_MIN_U = 0f
|
||||
val INSULIN_UNIT_STEP_U = INSULIN_UNIT_P
|
||||
const val SEGMENT_MAX_SIZE_48 = 48
|
||||
const val SEGMENT_COUNT_MAX = SEGMENT_MAX_SIZE_48
|
||||
|
||||
/**
|
||||
* On/Off
|
||||
*/
|
||||
val OFF = 0
|
||||
val ON = 1
|
||||
const val BOLUS_ACTIVE_EXTENDED_WAIT = 0x2
|
||||
|
||||
/**
|
||||
* Pump Duration, Interval
|
||||
*/
|
||||
val PUMP_DURATION_MILLI = TimeUnit.SECONDS.toMillis(4) // 15;
|
||||
val PUMP_RESOLUTION = INSULIN_UNIT_P
|
||||
|
||||
/**
|
||||
* Basal
|
||||
*/
|
||||
val BASAL_RATE_PER_HOUR_MIN = BASAL_MIN_AMOUNT
|
||||
val BASAL_RATE_PER_HOUR_STEP = INSULIN_UNIT_STEP_U
|
||||
val BASAL_RATE_PER_HOUR_MAX = 15.0f // 30.0f; 30.00U/hr
|
||||
|
||||
val SEGMENT_MAX_SIZE_48 = 48
|
||||
val SEGMENT_MAX_SIZE = SEGMENT_MAX_SIZE_48
|
||||
|
||||
val SEGMENT_COUNT_MAX = SEGMENT_MAX_SIZE_48
|
||||
|
||||
/**
|
||||
* Bolus
|
||||
*/
|
||||
val BOLUS_NORMAL_ID = 0x1
|
||||
val BOLUS_EXTENDED_ID = 0x2
|
||||
|
||||
val BOLUS_ACTIVE_OFF = OFF
|
||||
val BOLUS_ACTIVE_NORMAL = 0x01
|
||||
val BOLUS_ACTIVE_EXTENDED_WAIT = 0x2
|
||||
val BOLUS_ACTIVE_EXTENDED = 0x04
|
||||
val BOLUS_ACTIVE_DISCONNECTED = 0x08
|
||||
|
||||
val BOLUS_UNIT_MIN = BASAL_MIN_AMOUNT
|
||||
val BOLUS_UNIT_STEP = INSULIN_UNIT_STEP_U
|
||||
val BOLUS_UNIT_MAX = 25.0f // 30.0f;
|
||||
val BOLUS_DELIVER_MIN = 0.0f
|
||||
|
||||
|
||||
|
||||
/* Wizard */
|
||||
val WIZARD_STEP_MAX = 24
|
||||
|
||||
val INFO_REMINDER_DEFAULT_VALUE = 1
|
||||
|
||||
|
||||
val DAY_START_MINUTE = 0 * 60
|
||||
val DAY_END_MINUTE = 24 * 60
|
||||
|
||||
|
||||
val SNOOZE_INTERVAL_STEP = 5
|
||||
|
||||
/* Insulin Duration */
|
||||
val INSULIN_DURATION_MIN = 2.0f
|
||||
val INSULIN_DURATION_MAX = 8.0f
|
||||
val INSULIN_DURATION_STEP = 0.5f
|
||||
const val BOLUS_UNIT_STEP = INSULIN_UNIT_STEP_U
|
||||
|
||||
const val DAY_START_MINUTE = 0 * 60
|
||||
const val DAY_END_MINUTE = 24 * 60
|
||||
const val INSULIN_DURATION_MIN = 2.0f
|
||||
}
|
||||
}
|
|
@ -1,37 +1,23 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch
|
||||
|
||||
|
||||
import android.content.Context
|
||||
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil
|
||||
import io.reactivex.disposables.Disposable
|
||||
import java.util.*
|
||||
import java.util.function.Function
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.min
|
||||
|
||||
object CommonUtils {
|
||||
val TO_INT = Function<Number, Int> { it.toInt() }
|
||||
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?) {
|
||||
fun dispose(vararg disposable: Disposable?) {
|
||||
for (d in disposable){
|
||||
d?.let {
|
||||
if (!it.isDisposed()) {
|
||||
if (!it.isDisposed) {
|
||||
it.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic fun nullSafe(ch: CharSequence?): String {
|
||||
if (ch == null)
|
||||
return ""
|
||||
val str = ch.toString()
|
||||
return str
|
||||
}
|
||||
|
||||
@JvmStatic fun hasText(str: CharSequence?): Boolean {
|
||||
if (str == null || str.length == 0) {
|
||||
fun hasText(str: CharSequence?): Boolean {
|
||||
if (str == null || str.isEmpty()) {
|
||||
return false
|
||||
}
|
||||
val strLen = str.length
|
||||
|
@ -43,12 +29,12 @@ object CommonUtils {
|
|||
return false
|
||||
}
|
||||
|
||||
@JvmStatic fun hasText(str: String?): Boolean {
|
||||
fun hasText(str: String?): Boolean {
|
||||
return str?.let{hasText(it as CharSequence)}?:false
|
||||
}
|
||||
|
||||
@JvmStatic fun isStringEmpty(cs: CharSequence?): Boolean {
|
||||
return cs == null || cs.length == 0
|
||||
fun isStringEmpty(cs: CharSequence?): Boolean {
|
||||
return cs == null || cs.isEmpty()
|
||||
}
|
||||
|
||||
@JvmStatic fun dateString(millis: Long): String {
|
||||
|
@ -69,109 +55,42 @@ object CommonUtils {
|
|||
c.get(Calendar.SECOND))
|
||||
}
|
||||
|
||||
fun getTimeString(millis: Long): String {
|
||||
val c = Calendar.getInstance()
|
||||
c.timeInMillis = millis
|
||||
return getTimeString(c)
|
||||
}
|
||||
|
||||
fun getTimeString(c: Calendar): String {
|
||||
return String.format(Locale.US, "%02d:%02d",
|
||||
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE))
|
||||
}
|
||||
|
||||
fun bytesToStringArray(byteArray: ByteArray?): String {
|
||||
if (byteArray == null || byteArray.size == 0) {
|
||||
return "null"
|
||||
}
|
||||
|
||||
val sb = StringBuilder()
|
||||
for (b in byteArray) {
|
||||
if (sb.length > 0) {
|
||||
sb.append(String.format(" %02x", b))
|
||||
} else {
|
||||
sb.append(String.format("0x%02x", b))
|
||||
}
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
fun insulinFormat(): String {
|
||||
if (AppConstant.INSULIN_UNIT_STEP_U == 0.1f) {
|
||||
return "%.1f"
|
||||
}
|
||||
return if (AppConstant.INSULIN_UNIT_STEP_U == 0.05f) {
|
||||
"%.2f"
|
||||
} else "%.2f 인슐린출력형식추가하셈"
|
||||
|
||||
}
|
||||
|
||||
fun convertInsulinFormat(context: Context, strResId: Int): String {
|
||||
if (AppConstant.INSULIN_UNIT_STEP_U == 0.1f) {
|
||||
return context.getString(strResId).replace(".2f", ".1f")
|
||||
}
|
||||
if (AppConstant.INSULIN_UNIT_STEP_U == 0.05f) {
|
||||
return context.getString(strResId)
|
||||
}
|
||||
|
||||
return context.getString(strResId).replace(".2f", ".2f 인슐린출력형식추가하셈")
|
||||
|
||||
}
|
||||
|
||||
fun getRemainHourMin(timeMillis: Long): Pair<Long, Long> {
|
||||
val diffHours: Long
|
||||
var diffMinutes: Long
|
||||
|
||||
if (timeMillis >= 0) {
|
||||
diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60) + 1
|
||||
diffMinutes = abs(timeMillis / (60 * 1000) % 60) + 1
|
||||
if (diffMinutes == 60L) {
|
||||
diffMinutes = 0
|
||||
diffHours = Math.abs(timeMillis / (60 * 60 * 1000)) + 1
|
||||
diffHours = abs(timeMillis / (60 * 60 * 1000)) + 1
|
||||
} else {
|
||||
diffHours = Math.abs(timeMillis / (60 * 60 * 1000))
|
||||
diffHours = abs(timeMillis / (60 * 60 * 1000))
|
||||
}
|
||||
} else {
|
||||
diffMinutes = Math.abs(timeMillis / (60 * 1000) % 60)
|
||||
diffHours = Math.abs(timeMillis / (60 * 60 * 1000))
|
||||
diffMinutes = abs(timeMillis / (60 * 1000) % 60)
|
||||
diffHours = abs(timeMillis / (60 * 60 * 1000))
|
||||
}
|
||||
return Pair(diffHours, diffMinutes)
|
||||
}
|
||||
|
||||
fun getTimeString(minutes: Int): String {
|
||||
return String.format("%d:%02d", minutes / 60, minutes % 60)
|
||||
}
|
||||
|
||||
fun getTimeString_hhmm(minutes: Int): String {
|
||||
return String.format("%02d:%02d", minutes / 60, minutes % 60)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun generatePumpId(date: Long, typeCode: Long = 0): Long {
|
||||
return DateTimeUtil.toATechDate(date) * 100L + typeCode
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun nearlyEqual(a: Float, b: Float, epsilon: Float): Boolean {
|
||||
val absA = Math.abs(a)
|
||||
val absB = Math.abs(b)
|
||||
val diff = Math.abs(a - b)
|
||||
return if (a == b) { // shortcut, handles infinities
|
||||
val absA = abs(a)
|
||||
val absB = abs(b)
|
||||
val diff = abs(a - b)
|
||||
return if (a == b) {
|
||||
true
|
||||
} else if (a == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) {
|
||||
// a or b is zero or both are extremely close to it
|
||||
// relative error is less meaningful here
|
||||
diff < epsilon * java.lang.Float.MIN_NORMAL
|
||||
} else { // use relative error
|
||||
diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon
|
||||
} else {
|
||||
diff / min(absA + absB, Float.MAX_VALUE) < epsilon
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun nearlyNotEqual(a: Float, b: Float, epsilon: Float): Boolean {
|
||||
return !nearlyEqual(a, b, epsilon)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun <T : Any> clone(src: T): T {
|
||||
return GsonHelper.sharedGson().fromJson(GsonHelper.sharedGson().toJson(src), src.javaClass)
|
||||
}
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import androidx.preference.Preference
|
||||
import androidx.preference.PreferenceFragmentCompat
|
||||
|
@ -34,7 +33,6 @@ import info.nightscout.androidaps.utils.T
|
|||
import info.nightscout.androidaps.utils.TimeChangeType
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.shared.sharedPreferences.SP
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.functions.Consumer
|
||||
|
@ -57,12 +55,12 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
private val fabricPrivacy: FabricPrivacy,
|
||||
private val dateUtil: DateUtil,
|
||||
private val pumpSync: PumpSync,
|
||||
private val patchmanager: IPatchManager,
|
||||
private val patchManager: IPatchManager,
|
||||
private val alarmManager: IAlarmManager,
|
||||
private val preferenceManager: IPreferenceManager
|
||||
):PumpPluginBase(PluginDescription()
|
||||
.mainType(PluginType.PUMP)
|
||||
.fragmentClass(EopatchOverviewFragment::class.java.getName())
|
||||
.fragmentClass(EopatchOverviewFragment::class.java.name)
|
||||
.pluginIcon(R.drawable.ic_eopatch2_128)
|
||||
.pluginName(R.string.eopatch)
|
||||
.shortName(R.string.eopatch_shortname)
|
||||
|
@ -72,8 +70,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
|
||||
private val mDisposables = CompositeDisposable()
|
||||
|
||||
var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2
|
||||
private set
|
||||
private var mPumpType: PumpType = PumpType.EOFLOW_EOPATCH2
|
||||
private var mLastDataTime: Long = 0
|
||||
private val mPumpDescription = PumpDescription(mPumpType)
|
||||
|
||||
|
@ -83,10 +80,10 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
.toObservable(EventPreferenceChange::class.java)
|
||||
.observeOn(Schedulers.io())
|
||||
.subscribe({ event: EventPreferenceChange ->
|
||||
if (event.isChanged(rh, SettingKeys.LOW_RESERVIOR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) {
|
||||
patchmanager.changeReminderSetting()
|
||||
if (event.isChanged(rh, SettingKeys.LOW_RESERVOIR_REMINDERS) || event.isChanged(rh, SettingKeys.EXPIRATION_REMINDERS)) {
|
||||
patchManager.changeReminderSetting()
|
||||
} else if (event.isChanged(rh, SettingKeys.BUZZER_REMINDERS)) {
|
||||
patchmanager.changeBuzzerSetting()
|
||||
patchManager.changeBuzzerSetting()
|
||||
}
|
||||
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
|
||||
)
|
||||
|
@ -94,10 +91,10 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
mDisposables.add(rxBus
|
||||
.toObservable(EventAppInitialized::class.java)
|
||||
.observeOn(Schedulers.io())
|
||||
.subscribe({ event: EventAppInitialized? ->
|
||||
.subscribe({
|
||||
aapsLogger.debug(LTag.PUMP,"EventAppInitialized")
|
||||
preferenceManager.init()
|
||||
patchmanager.init()
|
||||
patchManager.init()
|
||||
alarmManager.init()
|
||||
}) { throwable: Throwable -> fabricPrivacy.logException(throwable) }
|
||||
)
|
||||
|
@ -106,7 +103,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
override fun specialEnableCondition(): Boolean {
|
||||
//BG -> FG 시 패치 활성화 재진행 및 미처리 알람 발생
|
||||
if(preferenceManager.isInitDone()) {
|
||||
patchmanager.checkActivationProcess()
|
||||
patchManager.checkActivationProcess()
|
||||
alarmManager.restartAll()
|
||||
}
|
||||
return super.specialEnableCondition()
|
||||
|
@ -142,12 +139,11 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
override fun isInitialized(): Boolean {
|
||||
val isInit = isConnected() && patchmanager.isActivated()
|
||||
return isInit
|
||||
return isConnected() && patchManager.isActivated
|
||||
}
|
||||
|
||||
override fun isSuspended(): Boolean {
|
||||
return patchmanager.patchState.isNormalBasalPaused
|
||||
return patchManager.patchState.isNormalBasalPaused
|
||||
}
|
||||
|
||||
override fun isBusy(): Boolean {
|
||||
|
@ -155,11 +151,11 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
override fun isConnected(): Boolean {
|
||||
return patchmanager.patchConnectionState.isConnected
|
||||
return patchManager.patchConnectionState.isConnected
|
||||
}
|
||||
|
||||
override fun isConnecting(): Boolean {
|
||||
return patchmanager.patchConnectionState.isConnecting
|
||||
return patchManager.patchConnectionState.isConnecting
|
||||
}
|
||||
|
||||
override fun isHandshakeInProgress(): Boolean {
|
||||
|
@ -182,22 +178,24 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
override fun getPumpStatus(reason: String) {
|
||||
if (patchmanager.isActivated()) {
|
||||
if (patchManager.isActivated) {
|
||||
if ("SMS" == reason) {
|
||||
aapsLogger.debug("Acknowledged AAPS getPumpStatus request it was requested through an SMS")
|
||||
}else{
|
||||
aapsLogger.debug("Acknowledged AAPS getPumpStatus request")
|
||||
}
|
||||
patchmanager.updateConnection().subscribe(Consumer {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
})
|
||||
mDisposables.add(patchManager.updateConnection()
|
||||
.subscribe(Consumer {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun setNewBasalProfile(profile: Profile): PumpEnactResult {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
if(patchmanager.isActivated){
|
||||
if(patchmanager.patchState.isTempBasalActive || patchmanager.patchState.isBolusActive){
|
||||
if(patchManager.isActivated){
|
||||
if(patchManager.patchState.isTempBasalActive || patchManager.patchState.isBolusActive){
|
||||
return PumpEnactResult(injector)
|
||||
}else{
|
||||
var isSuccess: Boolean? = null
|
||||
|
@ -208,24 +206,21 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
val nb = preferenceManager.getNormalBasalManager().convertProfileToNormalBasal(profile)
|
||||
patchmanager.startBasal(nb)
|
||||
mDisposables.add(patchManager.startBasal(nb)
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe({ response ->
|
||||
if (response.isSuccess) {
|
||||
preferenceManager.getNormalBasalManager().normalBasal = nb
|
||||
preferenceManager.flushNormalBasalManager()
|
||||
}
|
||||
result.onNext(response.isSuccess)
|
||||
}, { throwable ->
|
||||
}, {
|
||||
result.onNext(false)
|
||||
})
|
||||
)
|
||||
|
||||
do{
|
||||
SystemClock.sleep(100)
|
||||
}while(isSuccess == null)
|
||||
|
||||
disposable.dispose()
|
||||
aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess?:false}");
|
||||
aapsLogger.info(LTag.PUMP, "Basal Profile was set: ${isSuccess?:false}")
|
||||
return PumpEnactResult(injector).apply{ success = isSuccess?:false }
|
||||
}
|
||||
}else{
|
||||
|
@ -236,12 +231,12 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
override fun isThisProfileSet(profile: Profile): Boolean {
|
||||
if (!patchmanager.isActivated()) {
|
||||
if (!patchManager.isActivated) {
|
||||
return true
|
||||
}
|
||||
|
||||
val ret = preferenceManager.getNormalBasalManager().isEqual(profile)
|
||||
aapsLogger.info(LTag.PUMP, "Is this profile set? ${ret}");
|
||||
aapsLogger.info(LTag.PUMP, "Is this profile set? $ret")
|
||||
return ret
|
||||
}
|
||||
|
||||
|
@ -251,7 +246,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
|
||||
override val baseBasalRate: Double
|
||||
get() {
|
||||
if (!patchmanager.isActivated || patchmanager.patchState.isNormalBasalPaused) {
|
||||
if (!patchManager.isActivated || patchManager.patchState.isNormalBasalPaused) {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
|
@ -260,20 +255,20 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
|
||||
override val reservoirLevel: Double
|
||||
get() {
|
||||
if (!patchmanager.isActivated) {
|
||||
if (!patchManager.isActivated) {
|
||||
return 0.0
|
||||
}
|
||||
val reserviorLevel = patchmanager.patchState.remainedInsulin.toDouble()
|
||||
val reservoirLevel = patchManager.patchState.remainedInsulin.toDouble()
|
||||
|
||||
return (reserviorLevel > 50.0).takeOne(50.0, reserviorLevel)
|
||||
return (reservoirLevel > 50.0).takeOne(50.0, reservoirLevel)
|
||||
}
|
||||
|
||||
override val batteryLevel: Int
|
||||
get() {
|
||||
if(patchmanager.isActivated) {
|
||||
return patchmanager.patchState.batteryLevel()
|
||||
return if(patchManager.isActivated) {
|
||||
patchManager.patchState.batteryLevel()
|
||||
}else{
|
||||
return 0
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -292,7 +287,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
isSuccess = it
|
||||
}
|
||||
|
||||
patchmanager.startCalculatorBolus(detailedBolusInfo)
|
||||
mDisposables.add(patchManager.startCalculatorBolus(detailedBolusInfo)
|
||||
.doOnSuccess {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
}.subscribe({
|
||||
|
@ -300,25 +295,26 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}, {
|
||||
result.onNext(false)
|
||||
})
|
||||
)
|
||||
|
||||
do{
|
||||
SystemClock.sleep(100)
|
||||
if(patchmanager.patchConnectionState.isConnected) {
|
||||
var delivering = patchmanager.bolusCurrent.nowBolus.injected
|
||||
if(patchManager.patchConnectionState.isConnected) {
|
||||
val delivering = patchManager.bolusCurrent.nowBolus.injected
|
||||
rxBus.send(EventOverviewBolusProgress.apply {
|
||||
status = rh.gs(R.string.bolusdelivering, delivering)
|
||||
percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100)
|
||||
})
|
||||
}
|
||||
}while(!patchmanager.bolusCurrent.nowBolus.endTimeSynced && isSuccess)
|
||||
}while(!patchManager.bolusCurrent.nowBolus.endTimeSynced && isSuccess)
|
||||
|
||||
rxBus.send(EventOverviewBolusProgress.apply {
|
||||
status = rh.gs(R.string.bolusdelivered, detailedBolusInfo.insulin)
|
||||
percent = 100
|
||||
})
|
||||
|
||||
detailedBolusInfo.insulin = patchmanager.bolusCurrent.nowBolus.injected.toDouble()
|
||||
patchmanager.addBolusToHistory(detailedBolusInfo)
|
||||
detailedBolusInfo.insulin = patchManager.bolusCurrent.nowBolus.injected.toDouble()
|
||||
patchManager.addBolusToHistory(detailedBolusInfo)
|
||||
|
||||
disposable.dispose()
|
||||
|
||||
|
@ -329,37 +325,34 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
|
||||
} else {
|
||||
// no bolus required, carb only treatment
|
||||
patchmanager.addBolusToHistory(detailedBolusInfo);
|
||||
patchManager.addBolusToHistory(detailedBolusInfo)
|
||||
|
||||
return PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(0.0)
|
||||
.carbsDelivered(detailedBolusInfo.carbs).comment(rh.gs(info.nightscout.androidaps.core.R.string.ok));
|
||||
.carbsDelivered(detailedBolusInfo.carbs).comment(rh.gs(info.nightscout.androidaps.core.R.string.ok))
|
||||
}
|
||||
}
|
||||
|
||||
override fun stopBolusDelivering() {
|
||||
patchmanager.stopNowBolus()
|
||||
.subscribeOn(aapsSchedulers.io)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
mDisposables.add(patchManager.stopNowBolus()
|
||||
.subscribeOn(aapsSchedulers.io)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.subscribe { it ->
|
||||
rxBus.send(EventOverviewBolusProgress.apply {
|
||||
status = rh.gs(R.string.bolusdelivered, (it.injectedBolusAmount * 0.05f)) //todo stoped 메세지로 변경 필요
|
||||
status = rh.gs(R.string.bolusdelivered, (it.injectedBolusAmount * 0.05f))
|
||||
})
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
|
||||
aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - absoluteRate: ${absoluteRate.toFloat()}, durationInMinutes: ${durationInMinutes.toLong()}, enforceNew: $enforceNew")
|
||||
if(patchmanager.patchState.isNormalBasalAct){
|
||||
if(patchManager.patchState.isNormalBasalAct){
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
val tb = TempBasal.createAbsolute(durationInMinutes.toLong(), absoluteRate.toFloat())
|
||||
return patchmanager.startTempBasal(tb)
|
||||
return patchManager.startTempBasal(tb)
|
||||
.subscribeOn(aapsSchedulers.io)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.doOnSuccess {
|
||||
preferenceManager.getTempBasalManager().startedBasal = tb
|
||||
preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis()
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
timestamp = dateUtil.now(),
|
||||
rate = absoluteRate,
|
||||
|
@ -372,7 +365,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
)
|
||||
aapsLogger.info(LTag.PUMP,"setTempBasalAbsolute - tbrCurrent:${readTBR()}")
|
||||
}
|
||||
.map { it -> PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).absolute(absoluteRate).isPercent(false).isTempCancel(false) }
|
||||
.map { PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).absolute(absoluteRate).isPercent(false).isTempCancel(false) }
|
||||
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
|
||||
.comment("Internal error"))
|
||||
.blockingGet()
|
||||
|
@ -384,15 +377,13 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
|
||||
override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult {
|
||||
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - percent: $percent, durationInMinutes: $durationInMinutes, enforceNew: $enforceNew")
|
||||
if(patchmanager.patchState.isNormalBasalAct && percent != 0){
|
||||
if(patchManager.patchState.isNormalBasalAct && percent != 0){
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
val tb = TempBasal.createPercent(durationInMinutes.toLong(), percent)
|
||||
return patchmanager.startTempBasal(tb)
|
||||
return patchManager.startTempBasal(tb)
|
||||
.subscribeOn(aapsSchedulers.io)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.doOnSuccess {
|
||||
preferenceManager.getTempBasalManager().startedBasal = tb
|
||||
preferenceManager.getTempBasalManager().startedBasal?.startTimestamp = System.currentTimeMillis()
|
||||
pumpSync.syncTemporaryBasalWithPumpId(
|
||||
timestamp = dateUtil.now(),
|
||||
rate = percent.toDouble(),
|
||||
|
@ -405,7 +396,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
)
|
||||
aapsLogger.info(LTag.PUMP,"setTempBasalPercent - tbrCurrent:${readTBR()}")
|
||||
}
|
||||
.map { it -> PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).percent(percent).isPercent(true).isTempCancel(false) }
|
||||
.map { PumpEnactResult(injector).success(true).enacted(true).duration(durationInMinutes).percent(percent).isPercent(true).isTempCancel(false) }
|
||||
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
|
||||
.comment("Internal error"))
|
||||
.blockingGet()
|
||||
|
@ -418,7 +409,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult {
|
||||
aapsLogger.info(LTag.PUMP,"setExtendedBolus - insulin: $insulin, durationInMinutes: $durationInMinutes")
|
||||
|
||||
return patchmanager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes))
|
||||
return patchManager.startQuickBolus(0f, insulin.toFloat(), BolusExDuration.ofRaw(durationInMinutes))
|
||||
.doOnSuccess {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
pumpSync.syncExtendedBolusWithPumpId(
|
||||
|
@ -431,7 +422,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
pumpSerial = serialNumber()
|
||||
)
|
||||
}
|
||||
.map { it -> PumpEnactResult(injector).success(true).enacted(true)}
|
||||
.map { PumpEnactResult(injector).success(true).enacted(true)}
|
||||
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false).bolusDelivered(0.0)
|
||||
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
|
||||
.blockingGet()
|
||||
|
@ -445,14 +436,14 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
return PumpEnactResult(injector).success(true).enacted(false)
|
||||
}
|
||||
|
||||
if (!patchmanager.patchState.isTempBasalActive) {
|
||||
if (!patchManager.patchState.isTempBasalActive) {
|
||||
return if (pumpSync.expectedPumpState().temporaryBasal != null) {
|
||||
PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)
|
||||
}else
|
||||
PumpEnactResult(injector).success(true).isTempCancel(true)
|
||||
}
|
||||
|
||||
return patchmanager.stopTempBasal()
|
||||
return patchManager.stopTempBasal()
|
||||
.doOnSuccess {
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
aapsLogger.debug(LTag.PUMP,"cancelTempBasal - $it")
|
||||
|
@ -466,15 +457,15 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
.doOnError{
|
||||
aapsLogger.error(LTag.PUMP,"cancelTempBasal() - $it")
|
||||
}
|
||||
.map { it -> PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
|
||||
.map { PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
|
||||
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
|
||||
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
|
||||
.blockingGet()
|
||||
}
|
||||
|
||||
override fun cancelExtendedBolus(): PumpEnactResult {
|
||||
if(patchmanager.patchState.isExtBolusActive){
|
||||
return patchmanager.stopExtBolus()
|
||||
if(patchManager.patchState.isExtBolusActive){
|
||||
return patchManager.stopExtBolus()
|
||||
.doOnSuccess {
|
||||
aapsLogger.debug(LTag.PUMP,"cancelExtendedBolus - success")
|
||||
mLastDataTime = System.currentTimeMillis()
|
||||
|
@ -485,7 +476,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
pumpSerial = serialNumber()
|
||||
)
|
||||
}
|
||||
.map { it -> PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
|
||||
.map { PumpEnactResult(injector).success(true).enacted(true).isTempCancel(true)}
|
||||
.onErrorReturnItem(PumpEnactResult(injector).success(false).enacted(false)
|
||||
.comment(rh.gs(info.nightscout.androidaps.core.R.string.error)))
|
||||
.blockingGet()
|
||||
|
@ -517,14 +508,14 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
override fun serialNumber(): String {
|
||||
return patchmanager.patchConfig.patchSerialNumber
|
||||
return patchManager.patchConfig.patchSerialNumber
|
||||
}
|
||||
|
||||
override val pumpDescription: PumpDescription
|
||||
get() = mPumpDescription
|
||||
|
||||
override fun shortStatus(veryShort: Boolean): String {
|
||||
if(patchmanager.isActivated) {
|
||||
if(patchManager.isActivated) {
|
||||
var ret = ""
|
||||
val activeTemp = pumpSync.expectedPumpState().temporaryBasal
|
||||
if (activeTemp != null)
|
||||
|
@ -534,7 +525,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
if (activeExtendedBolus != null)
|
||||
ret += "Extended: ${activeExtendedBolus.amount} U\n"
|
||||
|
||||
val reservoirStr = patchmanager.patchState.remainedInsulin.let {
|
||||
val reservoirStr = patchManager.patchState.remainedInsulin.let {
|
||||
when {
|
||||
it > 50f -> "50+ U"
|
||||
it < 1f -> "0 U"
|
||||
|
@ -543,7 +534,7 @@ class EopatchPumpPlugin @Inject constructor(
|
|||
}
|
||||
|
||||
ret += "Reservoir: $reservoirStr"
|
||||
ret += "Batt: ${patchmanager.patchState.batteryLevel()}"
|
||||
ret += "Battery: ${patchManager.patchState.batteryLevel()}"
|
||||
return ret
|
||||
}else{
|
||||
return "EOPatch is not enabled."
|
||||
|
|
|
@ -4,7 +4,7 @@ import java.util.*
|
|||
import java.util.function.Function
|
||||
|
||||
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 DURATION = Function<Number, String>{ value -> String.format(Locale.US, "%.1f", value.toFloat()) }
|
||||
|
||||
|
@ -16,19 +16,7 @@ object FloatFormatters {
|
|||
return if (CommonUtils.isStringEmpty(suffix)) {
|
||||
INSULIN.apply(value)
|
||||
} else {
|
||||
INSULIN.apply(value).toString() +" "+ suffix!!
|
||||
}
|
||||
}
|
||||
|
||||
fun fat(value: Float): String {
|
||||
return FAT.apply(value)
|
||||
}
|
||||
|
||||
fun fat(value: Float, suffix: String?): String {
|
||||
return if (CommonUtils.isStringEmpty(suffix)) {
|
||||
FAT.apply(value)
|
||||
} else {
|
||||
FAT.apply(value).toString() + suffix!!
|
||||
INSULIN.apply(value) +" "+ suffix!!
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -40,7 +28,7 @@ object FloatFormatters {
|
|||
return if (CommonUtils.isStringEmpty(suffix)) {
|
||||
DURATION.apply(value)
|
||||
} else {
|
||||
DURATION.apply(value).toString() +" " + suffix!!
|
||||
DURATION.apply(value) +" " + suffix!!
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -51,10 +51,6 @@ public class OsAlarmService extends Service {
|
|||
|
||||
public synchronized void startForeground() {
|
||||
if (!foreground) {
|
||||
//// CommonUtils.dispose(mNotificationDisposable);
|
||||
// Notification builder = getNotification(this);
|
||||
// startForeground(FOREGROUND_NOTIFICATION_ID, builder);
|
||||
// startExerciseOrSleepMode(this);
|
||||
foreground = true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,8 +6,6 @@ import android.os.SystemClock
|
|||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.shared.logging.AAPSLogger
|
||||
import io.reactivex.*
|
||||
import io.reactivex.disposables.Disposable
|
||||
import org.reactivestreams.Subscription
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
@ -17,21 +15,10 @@ class RxAction @Inject constructor(
|
|||
private val aapsSchedulers: AapsSchedulers,
|
||||
private val aapsLogger: AAPSLogger
|
||||
) {
|
||||
|
||||
enum class RxVoid {
|
||||
INSTANCE
|
||||
}
|
||||
|
||||
class SilentObserver<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) {
|
||||
if (millis <= 0)
|
||||
return
|
||||
|
@ -56,63 +43,14 @@ class RxAction @Inject constructor(
|
|||
}
|
||||
}
|
||||
|
||||
private fun safeSingle(action: Runnable, delayMs: Long, scheduler: Scheduler): Single<*> {
|
||||
return single(action, delayMs, scheduler)
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun runOnComputationThread(action: Runnable, delayMs: Long = 0) {
|
||||
single(action, delayMs, aapsSchedulers.cpu).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun runOnIoThread(action: Runnable, delayMs: Long = 0) {
|
||||
single(action, delayMs, aapsSchedulers.io).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun runOnNewThread(action: Runnable, delayMs: Long = 0) {
|
||||
single(action, delayMs, aapsSchedulers.newThread).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun runOnMainThread(action: Runnable, delayMs: Long = 0) {
|
||||
single(action, delayMs, aapsSchedulers.main).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
single(action, delayMs, aapsSchedulers.main)
|
||||
.subscribe({
|
||||
|
||||
@JvmOverloads
|
||||
fun safeRunOnComputationThread(action: Runnable, delayMs: Long = 0) {
|
||||
safeSingle(action, delayMs, aapsSchedulers.cpu).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun safeRunOnIoThread(action: Runnable, delayMs: Long = 0) {
|
||||
safeSingle(action, delayMs, aapsSchedulers.io).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun safeRunOnNewThread(action: Runnable, delayMs: Long = 0) {
|
||||
safeSingle(action, delayMs, aapsSchedulers.newThread).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
fun safeRunOnMainThread(action: Runnable, delayMs: Long = 0) {
|
||||
safeSingle(action, delayMs, aapsSchedulers.main).subscribe(SilentObserver(aapsLogger))
|
||||
}
|
||||
|
||||
fun singleOnMainThread(action: Runnable, delayMs: Long): Single<*> {
|
||||
return single(action, delayMs, aapsSchedulers.main)
|
||||
}
|
||||
|
||||
fun singleOnComputationThread(action: Runnable, delayMs: Long): Single<*> {
|
||||
return single(action, delayMs, aapsSchedulers.cpu)
|
||||
}
|
||||
|
||||
fun singleOnIoThread(action: Runnable, delayMs: Long): Single<*> {
|
||||
return single(action, delayMs, aapsSchedulers.io)
|
||||
}
|
||||
|
||||
fun singleOnNewThread(action: Runnable, delayMs: Long): Single<*> {
|
||||
return single(action, delayMs, aapsSchedulers.newThread)
|
||||
},
|
||||
{ e ->
|
||||
aapsLogger.error("SilentObserver.onError() ignore", e)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,45 +9,47 @@ import java.util.function.Function
|
|||
import java.util.stream.Collectors
|
||||
import java.util.stream.Stream
|
||||
|
||||
enum class AlarmCode(defaultName: String, messageResId: Int) {
|
||||
A002("Empty reservoir", R.string.string_a002),
|
||||
A003("Patch expired", R.string.string_a003),
|
||||
A004("Occlusion", R.string.string_a004),
|
||||
A005("Power on self test failure", R.string.string_a005),
|
||||
A007("Inappropriate temperature", R.string.string_a007),
|
||||
A016("Needle insertion Error", R.string.string_a016),
|
||||
A018("Patch battery Error", R.string.string_a018),
|
||||
A019("Patch battery Error", R.string.string_a019),
|
||||
A020("Patch activation Error", R.string.string_a020),
|
||||
A022("Patch Error", R.string.string_a022),
|
||||
A023("Patch Error", R.string.string_a023),
|
||||
A034("Patch Error", R.string.string_a034),
|
||||
A041("Patch Error", R.string.string_a041),
|
||||
A042("Patch Error", R.string.string_a042),
|
||||
A043("Patch Error", R.string.string_a043),
|
||||
A044("Patch Error", R.string.string_a044),
|
||||
A106("Patch Error", R.string.string_a106),
|
||||
A107("Patch Error", R.string.string_a107),
|
||||
A108("Patch Error", R.string.string_a108),
|
||||
A116("Patch Error", R.string.string_a116),
|
||||
A117("Patch Error", R.string.string_a117),
|
||||
A118("Patch Error", R.string.string_a118),
|
||||
B001("End of insulin suspend", R.string.string_b001),
|
||||
B003("Low reservoir", R.string.string_b003),
|
||||
B005("Patch operating life expired", R.string.string_b005),
|
||||
B006("Patch will expire soon", R.string.string_b006),
|
||||
B012("Incomplete Patch activation", R.string.string_b012),
|
||||
B018("Patch battery low", R.string.string_b018);
|
||||
enum class AlarmCode(messageResId: Int) {
|
||||
A002(R.string.string_a002), //"Empty reservoir"
|
||||
A003(R.string.string_a003), //"Patch expired"
|
||||
A004(R.string.string_a004), //"Occlusion"
|
||||
A005(R.string.string_a005), //"Power on self test failure"
|
||||
A007(R.string.string_a007), //"Inappropriate temperature"
|
||||
A016(R.string.string_a016), //"Needle insertion Error"
|
||||
A018(R.string.string_a018), //"Patch battery Error"
|
||||
A019(R.string.string_a019), //"Patch battery Error"
|
||||
A020(R.string.string_a020), //"Patch activation Error"
|
||||
A022(R.string.string_a022), //"Patch Error"
|
||||
A023(R.string.string_a023), //"Patch Error"
|
||||
A034(R.string.string_a034), //"Patch Error"
|
||||
A041(R.string.string_a041), //"Patch Error"
|
||||
A042(R.string.string_a042), //"Patch Error"
|
||||
A043(R.string.string_a043), //"Patch Error"
|
||||
A044(R.string.string_a044), //"Patch Error"
|
||||
A106(R.string.string_a106), //"Patch Error"
|
||||
A107(R.string.string_a107), //"Patch Error"
|
||||
A108(R.string.string_a108), //"Patch Error"
|
||||
A116(R.string.string_a116), //"Patch Error"
|
||||
A117(R.string.string_a117), //"Patch Error"
|
||||
A118(R.string.string_a118), //"Patch Error"
|
||||
B001(R.string.string_b001), //"End of insulin suspend"
|
||||
B003(R.string.string_b003), //"Low reservoir"
|
||||
B005(R.string.string_b005), //"Patch operating life expired"
|
||||
B006(R.string.string_b006), //"Patch will expire soon"
|
||||
B012(R.string.string_b012), //"Incomplete Patch activation"
|
||||
B018(R.string.string_b018); //"Patch battery low"
|
||||
|
||||
val type: Char = name[0]
|
||||
val code: Int = name.substring(1).toInt()
|
||||
val resId: Int = messageResId
|
||||
|
||||
val type: Char
|
||||
val code: Int
|
||||
val resId: Int
|
||||
val alarmCategory: AlarmCategory
|
||||
get() = when (type) {
|
||||
TYPE_ALARM -> AlarmCategory.ALARM
|
||||
TYPE_ALERT -> AlarmCategory.ALERT
|
||||
else -> AlarmCategory.NONE
|
||||
}
|
||||
|
||||
val aeCode: Int
|
||||
get() {
|
||||
when (type) {
|
||||
|
@ -57,13 +59,6 @@ enum class AlarmCode(defaultName: String, messageResId: Int) {
|
|||
return -1
|
||||
}
|
||||
|
||||
val osAlarmId: Int
|
||||
get() = (when (type) {
|
||||
TYPE_ALARM -> 10000
|
||||
TYPE_ALERT -> 20000
|
||||
else -> 0
|
||||
} + code ) * 1000 + 1
|
||||
|
||||
val isPatchOccurrenceAlert: Boolean
|
||||
get() = this == B003 || this == B005 || this == B006 || this == B018
|
||||
|
||||
|
@ -72,12 +67,6 @@ enum class AlarmCode(defaultName: String, messageResId: Int) {
|
|||
|| this == A023 || this == A034 || this == A041 || this == A042 || this == A043 || this == A044 || this == A106
|
||||
|| this == A107 || this == A108 || this == A116 || this == A117 || this == A118
|
||||
|
||||
init {
|
||||
type = name[0]
|
||||
this.code = name.substring(1).toInt()
|
||||
resId = messageResId
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val TYPE_ALARM = 'A'
|
||||
const val TYPE_ALERT = 'B'
|
||||
|
@ -103,10 +92,10 @@ enum class AlarmCode(defaultName: String, messageResId: Int) {
|
|||
fun getUri(alarmCode: AlarmCode): Uri {
|
||||
return Uri.Builder()
|
||||
.scheme(SCHEME)
|
||||
.authority("com.eoflow.eomapp")
|
||||
.authority("info.nightscout.androidaps")
|
||||
.path(ALARM_KEY_PATH)
|
||||
.appendQueryParameter(QUERY_CODE, alarmCode.name)
|
||||
.build();
|
||||
.build()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
|
|
|
@ -26,10 +26,12 @@ import io.reactivex.Observable
|
|||
import io.reactivex.Single
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.disposables.Disposable
|
||||
import io.reactivex.schedulers.Schedulers
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
import kotlin.math.max
|
||||
|
||||
interface IAlarmManager {
|
||||
fun init()
|
||||
|
@ -54,6 +56,7 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
private lateinit var mAlarmProcess: AlarmProcess
|
||||
|
||||
private var compositeDisposable: CompositeDisposable = CompositeDisposable()
|
||||
private var alarmDisposable: Disposable? = null
|
||||
|
||||
@Inject
|
||||
fun onInit() {
|
||||
|
@ -61,27 +64,27 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
}
|
||||
|
||||
override fun init(){
|
||||
EoPatchRxBus.listen(EventEoPatchAlarm::class.java)
|
||||
.map { it -> it.alarmCodes }
|
||||
alarmDisposable = EoPatchRxBus.listen(EventEoPatchAlarm::class.java)
|
||||
.map { it.alarmCodes }
|
||||
.doOnNext { aapsLogger.info(LTag.PUMP,"EventEoPatchAlarm Received") }
|
||||
.concatMap {
|
||||
Observable.fromArray(it)
|
||||
.observeOn(Schedulers.io())
|
||||
.subscribeOn(AndroidSchedulers.mainThread())
|
||||
.doOnNext { alarmCodes ->
|
||||
alarmCodes.forEach {
|
||||
aapsLogger.info(LTag.PUMP,"alarmCode: ${it.name}")
|
||||
val valid = isValid(it)
|
||||
alarmCodes.forEach { alarmCode ->
|
||||
aapsLogger.info(LTag.PUMP,"alarmCode: ${alarmCode.name}")
|
||||
val valid = isValid(alarmCode)
|
||||
if (valid) {
|
||||
if (it.alarmCategory == AlarmCategory.ALARM || it == B012) {
|
||||
showAlarmDialog(it)
|
||||
if (alarmCode.alarmCategory == AlarmCategory.ALARM || alarmCode == B012) {
|
||||
showAlarmDialog(alarmCode)
|
||||
} else {
|
||||
showNotification(it)
|
||||
showNotification(alarmCode)
|
||||
}
|
||||
|
||||
updateState(it, AlarmState.FIRED)
|
||||
updateState(alarmCode, AlarmState.FIRED)
|
||||
}else{
|
||||
updateState(it, AlarmState.HANDLE)
|
||||
updateState(alarmCode, AlarmState.HANDLE)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -92,17 +95,19 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
|
||||
override fun restartAll() {
|
||||
val now = System.currentTimeMillis()
|
||||
val occuredAlarm = pm.getAlarms().occured.clone() as HashMap<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>
|
||||
compositeDisposable.clear()
|
||||
if(occuredAlarm.isNotEmpty()){
|
||||
EoPatchRxBus.publish(EventEoPatchAlarm(occuredAlarm.keys))
|
||||
if(occurredAlarm.isNotEmpty()){
|
||||
EoPatchRxBus.publish(EventEoPatchAlarm(occurredAlarm.keys))
|
||||
}
|
||||
|
||||
if(registeredAlarm.isNotEmpty()){
|
||||
registeredAlarm.forEach { raEntry ->
|
||||
compositeDisposable.add(
|
||||
mAlarmRegistry.add(raEntry.key, Math.max(OS_REGISTER_GAP, raEntry.value.triggerTimeMilli - now))
|
||||
mAlarmRegistry.add(raEntry.key, max(OS_REGISTER_GAP, raEntry.value.triggerTimeMilli - now))
|
||||
.subscribe()
|
||||
)
|
||||
}
|
||||
|
@ -112,11 +117,11 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
private fun isValid(code: AlarmCode): Boolean{
|
||||
return when(code){
|
||||
A005, A016, A020, B012 -> {
|
||||
aapsLogger.info(LTag.PUMP,"Is ${code} valid? ${pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning}")
|
||||
aapsLogger.info(LTag.PUMP,"Is $code valid? ${pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning}")
|
||||
pm.getPatchConfig().hasMacAddress() && pm.getPatchConfig().lifecycleEvent.isSubStepRunning
|
||||
}
|
||||
else -> {
|
||||
aapsLogger.info(LTag.PUMP,"Is ${code} valid? ${pm.getPatchConfig().isActivated}")
|
||||
aapsLogger.info(LTag.PUMP,"Is $code valid? ${pm.getPatchConfig().isActivated}")
|
||||
pm.getPatchConfig().isActivated
|
||||
}
|
||||
}
|
||||
|
@ -133,11 +138,11 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
}
|
||||
|
||||
private fun showNotification(alarmCode: AlarmCode, timeOffset: Long = 0L){
|
||||
var occurredTimestamp: Long = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.SECONDS.toMillis(timeOffset)
|
||||
val notification = EONotification(Notification.EOELOW_PATCH_ALERTS + (alarmCode.aeCode + 10000), resourceHelper.gs(alarmCode.resId), Notification.URGENT)
|
||||
|
||||
notification.action(R.string.confirm) {
|
||||
Single.just(isValid(alarmCode))
|
||||
compositeDisposable.add(
|
||||
Single.just(isValid(alarmCode))
|
||||
.flatMap { isValid ->
|
||||
return@flatMap if(isValid) mAlarmProcess.doAction(context, alarmCode)
|
||||
else Single.just(IAlarmProcess.ALARM_HANDLED)
|
||||
|
@ -148,17 +153,17 @@ class AlarmManager @Inject constructor() : IAlarmManager {
|
|||
}else{
|
||||
rxBus.send(EventNewNotification(notification))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
notification.soundId = R.raw.error
|
||||
notification.date = occurredTimestamp
|
||||
notification.date = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.SECONDS.toMillis(timeOffset)
|
||||
rxBus.send(EventNewNotification(notification))
|
||||
}
|
||||
|
||||
private fun updateState(alarmCode: AlarmCode, state: AlarmState){
|
||||
when(state){
|
||||
AlarmState.REGISTER -> pm.getAlarms().register(alarmCode, 0)
|
||||
AlarmState.FIRED -> pm.getAlarms().occured(alarmCode)
|
||||
AlarmState.FIRED -> pm.getAlarms().occurred(alarmCode)
|
||||
AlarmState.HANDLE -> pm.getAlarms().handle(alarmCode)
|
||||
}
|
||||
pm.flushAlarms()
|
||||
|
|
|
@ -4,8 +4,7 @@ import android.content.Context
|
|||
import android.content.DialogInterface
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCheckConnection
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForDiscarded
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForChangePatch
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCanularInsertionError
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity.Companion.createIntentForCannulaInsertionError
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode.*
|
||||
import android.content.Intent
|
||||
|
@ -13,7 +12,6 @@ import info.nightscout.androidaps.plugins.bus.RxBus
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.R
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.TemperatureResponse
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventDialog
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventProgressDialog
|
||||
|
@ -40,13 +38,12 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
|
|||
A002, A003, A004, A005, A018, A019,
|
||||
A020, A022, A023, A034, A041, A042,
|
||||
A043, A044, A106, A107, A108, A116,
|
||||
A117, A118 -> patchDeactivationAction(context, true)
|
||||
A117, A118 -> patchDeactivationAction(context)
|
||||
A007 -> inappropriateTemperatureAction(context)
|
||||
A016 -> needleInsertionErrorAction(context)
|
||||
B003, B018 -> Single.just(IAlarmProcess.ALARM_HANDLED)
|
||||
B005, B006 -> Single.just(IAlarmProcess.ALARM_HANDLED)
|
||||
B012 -> Single.just(IAlarmProcess.ALARM_HANDLED)
|
||||
else -> Single.just(IAlarmProcess.ALARM_HANDLED)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -56,11 +53,11 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
|
|||
}
|
||||
|
||||
private fun showCommunicationFailedDialog(onConfirmed: Runnable) {
|
||||
var dialog = CommonDialog().apply {
|
||||
val dialog = CommonDialog().apply {
|
||||
title = R.string.patch_communication_failed
|
||||
message = R.string.patch_communication_check_helper_1
|
||||
positiveBtn = R.string.string_communication_check
|
||||
positiveListener = DialogInterface.OnClickListener { dialog, which ->
|
||||
positiveListener = DialogInterface.OnClickListener { _, _ ->
|
||||
onConfirmed.run()
|
||||
dismiss()
|
||||
}
|
||||
|
@ -80,7 +77,7 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
|
|||
Single.fromCallable {
|
||||
showCommunicationFailedDialog {
|
||||
startActivityWithSingleTop(context,
|
||||
createIntentForCheckConnection(context, true, true))
|
||||
createIntentForCheckConnection(context, goHomeAfterDiscard = true, forceDiscard = true))
|
||||
}
|
||||
IAlarmProcess.ALARM_PAUSE
|
||||
}
|
||||
|
@ -95,28 +92,21 @@ class AlarmProcess(val patchManager: IPatchManager, val rxBus: RxBus) : IAlarmPr
|
|||
}
|
||||
}
|
||||
|
||||
private fun patchDeactivationAction(context: Context, goHome: Boolean): Single<Int> {
|
||||
private fun patchDeactivationAction(context: Context): Single<Int> {
|
||||
return actionWithPatchCheckConnection(context) {
|
||||
rxBus.send(EventProgressDialog(true, R.string.string_in_progress))
|
||||
patchManager.deactivate(6000, true)
|
||||
.doFinally {
|
||||
rxBus.send(EventProgressDialog(false, R.string.string_in_progress))
|
||||
startActivityWithSingleTop(context, createIntentForDiscarded(context, goHome))
|
||||
startActivityWithSingleTop(context, createIntentForDiscarded(context))
|
||||
}
|
||||
.flatMap { ok: DeactivationStatus? -> Single.just(IAlarmProcess.ALARM_HANDLED) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun changPatchAction(context: Context): Single<Int> {
|
||||
return Single.fromCallable {
|
||||
startActivityWithSingleTop(context, createIntentForChangePatch(context))
|
||||
IAlarmProcess.ALARM_HANDLED
|
||||
.flatMap { Single.just(IAlarmProcess.ALARM_HANDLED) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun needleInsertionErrorAction(context: Context): Single<Int> {
|
||||
return Single.fromCallable {
|
||||
startActivityWithSingleTop(context, createIntentForCanularInsertionError(context))
|
||||
startActivityWithSingleTop(context, createIntentForCannulaInsertionError(context))
|
||||
IAlarmProcess.ALARM_HANDLED
|
||||
}
|
||||
}
|
||||
|
|
|
@ -29,7 +29,7 @@ import javax.inject.Singleton
|
|||
interface IAlarmRegistry {
|
||||
fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean = false): Maybe<AlarmCode>
|
||||
fun add(patchAeCodes: Set<PatchAeCode>)
|
||||
fun remove(alarmKey: AlarmCode): Maybe<AlarmCode>
|
||||
fun remove(alarmCode: AlarmCode): Maybe<AlarmCode>
|
||||
}
|
||||
|
||||
@Singleton
|
||||
|
@ -60,29 +60,30 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
|
|||
PatchLifecycle.SHUTDOWN -> {
|
||||
val sources = ArrayList<Maybe<*>>()
|
||||
sources.add(Maybe.just(true))
|
||||
pm.getAlarms().occured.let{
|
||||
if(it.isNotEmpty()){
|
||||
it.keys.forEach {
|
||||
pm.getAlarms().occurred.let{ occurredAlarms ->
|
||||
if(occurredAlarms.isNotEmpty()){
|
||||
occurredAlarms.keys.forEach { alarmCode ->
|
||||
sources.add(
|
||||
Maybe.just(it)
|
||||
Maybe.just(alarmCode)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.doOnSuccess { rxBus.send(EventDismissNotification(Notification.EOELOW_PATCH_ALERTS + (it.aeCode + 10000))) }
|
||||
.doOnSuccess { rxBus.send(EventDismissNotification(Notification.EOELOW_PATCH_ALERTS + (alarmCode.aeCode + 10000))) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
pm.getAlarms().registered.let{
|
||||
if(it.isNotEmpty()){
|
||||
it.keys.forEach {
|
||||
sources.add(remove(it))
|
||||
pm.getAlarms().registered.let{ registeredAlarms ->
|
||||
if(registeredAlarms.isNotEmpty()){
|
||||
registeredAlarms.keys.forEach { alarmCode ->
|
||||
sources.add(remove(alarmCode))
|
||||
}
|
||||
}
|
||||
}
|
||||
Maybe.concat(sources)
|
||||
compositeDisposable.add(Maybe.concat(sources)
|
||||
.subscribe {
|
||||
pm.getAlarms().clear()
|
||||
pm.flushAlarms()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
else -> Unit
|
||||
|
@ -91,7 +92,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
|
|||
}
|
||||
|
||||
override fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean): Maybe<AlarmCode> {
|
||||
if(pm.getAlarms().occured.containsKey(alarmCode)){
|
||||
if(pm.getAlarms().occurred.containsKey(alarmCode)){
|
||||
return Maybe.just(alarmCode)
|
||||
}else {
|
||||
val triggerTimeMilli = System.currentTimeMillis() + triggerAfter
|
||||
|
@ -110,7 +111,7 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
|
|||
Observable.fromIterable(patchAeCodes)
|
||||
.filter{patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.getAeValue()) != null}
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.filter { patchAeCodes -> AlarmCode.findByPatchAeCode(patchAeCodes.getAeValue()) != null }
|
||||
.filter { aeCodes -> AlarmCode.findByPatchAeCode(aeCodes.getAeValue()) != null }
|
||||
.flatMapMaybe{aeCodeResponse -> add(AlarmCode.findByPatchAeCode(aeCodeResponse.getAeValue())!!,0L, true)}
|
||||
.subscribe()
|
||||
)
|
||||
|
@ -120,22 +121,21 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
|
|||
return Maybe.fromCallable {
|
||||
cancelOsAlarmInternal(alarmCode)
|
||||
val pendingIntent = createPendingIntent(alarmCode, 0)
|
||||
val now = System.currentTimeMillis()
|
||||
mOsAlarmManager.setAlarmClock(AlarmClockInfo(triggerTime, pendingIntent), pendingIntent)
|
||||
alarmCode
|
||||
}
|
||||
}
|
||||
|
||||
override fun remove(alarmCode: AlarmCode): Maybe<AlarmCode> {
|
||||
if(pm.getAlarms().registered.containsKey(alarmCode)) {
|
||||
return cancelOsAlarms(alarmCode)
|
||||
return if(pm.getAlarms().registered.containsKey(alarmCode)) {
|
||||
cancelOsAlarms(alarmCode)
|
||||
.doOnSuccess {
|
||||
pm.getAlarms().unregister(alarmCode)
|
||||
pm.flushAlarms()
|
||||
}
|
||||
.map { integer: Int? -> alarmCode }
|
||||
.map { alarmCode }
|
||||
}else{
|
||||
return Maybe.just(alarmCode)
|
||||
Maybe.just(alarmCode)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -158,8 +158,8 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry {
|
|||
}
|
||||
}
|
||||
|
||||
private fun createPendingIntent(alarmCode: AlarmCode, flag: Int): PendingIntent {
|
||||
private fun createPendingIntent(alarmCode: AlarmCode, flag: Int): PendingIntent? {
|
||||
val intent = Intent(mContext, OsAlarmReceiver::class.java).setData(getUri(alarmCode))
|
||||
return PendingIntent.getBroadcast(mContext, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
return PendingIntent.getBroadcast(mContext, 1, intent, flag)
|
||||
}
|
||||
}
|
|
@ -21,6 +21,6 @@ class OnSafeClickListener(
|
|||
}
|
||||
companion object {
|
||||
// 중복 클릭 방지 시간 설정
|
||||
private val MIN_CLICK_INTERVAL: Long = 1000
|
||||
private const val MIN_CLICK_INTERVAL: Long = 1000
|
||||
}
|
||||
}
|
|
@ -27,13 +27,6 @@ import io.reactivex.Observable;
|
|||
import io.reactivex.Single;
|
||||
|
||||
public interface IPatchManager {
|
||||
|
||||
/*
|
||||
@Deprecated
|
||||
static IPatchManager shared() {
|
||||
return BaseApplication.instance.getDataComponent().getPatchManager();
|
||||
}
|
||||
*/
|
||||
void init();
|
||||
|
||||
IPreferenceManager getPreferenceManager();
|
||||
|
@ -74,8 +67,7 @@ public interface IPatchManager {
|
|||
|
||||
Single<ComboBolusStopResponse> stopComboBolus();
|
||||
|
||||
Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU,
|
||||
BolusExDuration exDuration);
|
||||
Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU, BolusExDuration exDuration);
|
||||
|
||||
Single<? extends BolusResponse> startCalculatorBolus(DetailedBolusInfo detailedBolusInfo);
|
||||
|
||||
|
@ -116,8 +108,6 @@ public interface IPatchManager {
|
|||
|
||||
Single<TemperatureResponse> getTemperature();
|
||||
|
||||
void initBasalSchedule();
|
||||
|
||||
void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo);
|
||||
|
||||
void changeBuzzerSetting();
|
||||
|
|
|
@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble;
|
|||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
|
||||
import com.polidea.rxandroidble2.exceptions.BleException;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
@ -51,16 +49,12 @@ import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal;
|
|||
import info.nightscout.androidaps.utils.DateUtil;
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper;
|
||||
import info.nightscout.shared.logging.AAPSLogger;
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.shared.sharedPreferences.SP;
|
||||
import io.reactivex.Observable;
|
||||
import io.reactivex.Single;
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers;
|
||||
import io.reactivex.disposables.CompositeDisposable;
|
||||
import io.reactivex.disposables.Disposable;
|
||||
import io.reactivex.exceptions.OnErrorNotImplementedException;
|
||||
import io.reactivex.exceptions.UndeliverableException;
|
||||
import io.reactivex.plugins.RxJavaPlugins;
|
||||
import io.reactivex.schedulers.Schedulers;
|
||||
|
||||
@Singleton
|
||||
|
@ -81,29 +75,11 @@ public class PatchManager implements IPatchManager {
|
|||
@Inject RxAction rxAction;
|
||||
|
||||
private IPatchScanner patchScanner;
|
||||
private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
|
||||
private final CompositeDisposable mCompositeDisposable = new CompositeDisposable();
|
||||
private Disposable mConnectingDisposable = null;
|
||||
|
||||
@Inject
|
||||
public PatchManager() {
|
||||
setupRxAndroidBle();
|
||||
}
|
||||
|
||||
private void setupRxAndroidBle() {
|
||||
RxJavaPlugins.setErrorHandler(throwable -> {
|
||||
if (throwable instanceof UndeliverableException) {
|
||||
if (throwable.getCause() instanceof BleException) {
|
||||
return;
|
||||
}
|
||||
aapsLogger.error(LTag.PUMPBTCOMM, "rx UndeliverableException Error Handler");
|
||||
return;
|
||||
} else if (throwable instanceof OnErrorNotImplementedException) {
|
||||
aapsLogger.error(LTag.PUMPBTCOMM, "rx exception Error Handler");
|
||||
return;
|
||||
}
|
||||
throw new RuntimeException("Unexpected Throwable in RxJavaPlugins error handler", throwable);
|
||||
});
|
||||
}
|
||||
public PatchManager() {}
|
||||
|
||||
@Inject
|
||||
void onInit() {
|
||||
|
@ -155,7 +131,6 @@ public class PatchManager implements IPatchManager {
|
|||
|
||||
@Override
|
||||
public void init() {
|
||||
initBasalSchedule();
|
||||
setConnection();
|
||||
}
|
||||
|
||||
|
@ -272,7 +247,27 @@ public class PatchManager implements IPatchManager {
|
|||
}
|
||||
|
||||
public Single<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) {
|
||||
|
@ -305,8 +300,8 @@ public class PatchManager implements IPatchManager {
|
|||
}
|
||||
|
||||
|
||||
public Single<? extends BolusResponse> startQuickBolus(float nowDoseU,
|
||||
float exDoseU, BolusExDuration exDuration) {
|
||||
public Single<? extends BolusResponse> startQuickBolus(float nowDoseU, float exDoseU,
|
||||
BolusExDuration exDuration) {
|
||||
return patchManager.startQuickBolus(nowDoseU, exDoseU, exDuration);
|
||||
}
|
||||
|
||||
|
@ -334,10 +329,6 @@ public class PatchManager implements IPatchManager {
|
|||
return patchManager.deactivate(timeout, force);
|
||||
}
|
||||
|
||||
public Single<PatchBooleanResponse> stopBuzz() {
|
||||
return patchManager.stopBuzz();
|
||||
}
|
||||
|
||||
public Single<PatchBooleanResponse> infoReminderSet(boolean infoReminder) {
|
||||
return patchManager.infoReminderSet(infoReminder);
|
||||
}
|
||||
|
@ -361,14 +352,6 @@ public class PatchManager implements IPatchManager {
|
|||
return patchScanner.scan(timeout);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initBasalSchedule() {
|
||||
if(pm.getNormalBasalManager().getNormalBasal() == null){
|
||||
pm.getNormalBasalManager().setNormalBasal(profileFunction.getProfile());
|
||||
pm.flushNormalBasalManager();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addBolusToHistory(DetailedBolusInfo originalDetailedBolusInfo) {
|
||||
DetailedBolusInfo detailedBolusInfo = originalDetailedBolusInfo.copy();
|
||||
|
@ -399,12 +382,12 @@ public class PatchManager implements IPatchManager {
|
|||
boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false);
|
||||
if(pm.getPatchConfig().getInfoReminder() != buzzer) {
|
||||
if (isActivated()) {
|
||||
infoReminderSet(buzzer)
|
||||
mCompositeDisposable.add(infoReminderSet(buzzer)
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(patchBooleanResponse -> {
|
||||
pm.getPatchConfig().setInfoReminder(buzzer);
|
||||
pm.flushPatchConfig();
|
||||
});
|
||||
}));
|
||||
} else {
|
||||
pm.getPatchConfig().setInfoReminder(buzzer);
|
||||
pm.flushPatchConfig();
|
||||
|
@ -414,18 +397,18 @@ public class PatchManager implements IPatchManager {
|
|||
|
||||
@Override
|
||||
public void changeReminderSetting() {
|
||||
int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVIOR_REMINDERS(), 0);
|
||||
int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVOIR_REMINDERS(), 0);
|
||||
int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0);
|
||||
PatchConfig pc = pm.getPatchConfig();
|
||||
if(pc.getLowReservoirAlertAmount() != doseUnit || pc.getPatchExpireAlertTime() != hours) {
|
||||
if (isActivated()) {
|
||||
setLowReservoir(doseUnit, hours)
|
||||
mCompositeDisposable.add(setLowReservoir(doseUnit, hours)
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.subscribe(patchBooleanResponse -> {
|
||||
pc.setLowReservoirAlertAmount(doseUnit);
|
||||
pc.setPatchExpireAlertTime(hours);
|
||||
pm.flushPatchConfig();
|
||||
});
|
||||
}));
|
||||
} else {
|
||||
pc.setLowReservoirAlertAmount(doseUnit);
|
||||
pc.setPatchExpireAlertTime(hours);
|
||||
|
@ -437,11 +420,9 @@ public class PatchManager implements IPatchManager {
|
|||
@Override
|
||||
public void checkActivationProcess(){
|
||||
if(getPatchConfig().getLifecycleEvent().isSubStepRunning()
|
||||
&& !pm.getAlarms().isOccuring(AlarmCode.A005)
|
||||
&& !pm.getAlarms().isOccuring(AlarmCode.A020)) {
|
||||
rxAction.runOnMainThread(() -> {
|
||||
rxBus.send(new EventPatchActivationNotComplete());
|
||||
});
|
||||
&& !pm.getAlarms().isOccurring(AlarmCode.A005)
|
||||
&& !pm.getAlarms().isOccurring(AlarmCode.A020)) {
|
||||
rxAction.runOnMainThread(() -> rxBus.send(new EventPatchActivationNotComplete()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -42,7 +42,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.BleConnectionSt
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.IBleDevice;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.Patch;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.scan.PatchSelfTestResult;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BuzzerStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetTemperature;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.PublicKeySend;
|
||||
|
@ -59,7 +58,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus;
|
|||
|
||||
import java.math.BigInteger;
|
||||
import java.security.AlgorithmParameters;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.KeyPair;
|
||||
|
@ -74,17 +72,13 @@ import java.security.spec.ECPoint;
|
|||
import java.security.spec.ECPublicKeySpec;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.InvalidParameterSpecException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.crypto.KeyAgreement;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.util.HexString;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.SettingKeys;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventEoPatchAlarm;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver;
|
||||
|
@ -102,7 +96,7 @@ import io.reactivex.functions.Consumer;
|
|||
import io.reactivex.schedulers.Schedulers;
|
||||
|
||||
@Singleton
|
||||
public class PatchManagerImpl/* implements IPatchConstant*/ {
|
||||
public class PatchManagerImpl{
|
||||
@Inject IPreferenceManager pm;
|
||||
@Inject Context context;
|
||||
@Inject SP sp;
|
||||
|
@ -115,29 +109,23 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
@Inject NeedleSensingTask START_NEEDLE_CHECK;
|
||||
|
||||
IBleDevice patch;
|
||||
HexString hexString;
|
||||
|
||||
private CompositeDisposable compositeDisposable;
|
||||
|
||||
private Observable<Intent> dateTimeChanged;
|
||||
private final CompositeDisposable compositeDisposable;
|
||||
|
||||
private static final long DEFAULT_API_TIME_OUT = 10; // SECONDS
|
||||
|
||||
private BuzzerStop BUZZER_STOP;
|
||||
private GetTemperature TEMPERATURE_GET;
|
||||
private BasalStop BASAL_STOP;
|
||||
private StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP;
|
||||
private PublicKeySend PUBLIC_KEY_SET;
|
||||
private SequenceGet SEQUENCE_GET;
|
||||
private final BuzzerStop BUZZER_STOP;
|
||||
private final GetTemperature TEMPERATURE_GET;
|
||||
private final StopAeBeep ALARM_ALERT_ERROR_BEEP_STOP;
|
||||
private final PublicKeySend PUBLIC_KEY_SET;
|
||||
private final SequenceGet SEQUENCE_GET;
|
||||
|
||||
@Inject
|
||||
public PatchManagerImpl() {
|
||||
compositeDisposable = new CompositeDisposable();
|
||||
hexString = new HexString();
|
||||
|
||||
BUZZER_STOP = new BuzzerStop();
|
||||
TEMPERATURE_GET = new GetTemperature();
|
||||
BASAL_STOP = new BasalStop();
|
||||
ALARM_ALERT_ERROR_BEEP_STOP = new StopAeBeep();
|
||||
PUBLIC_KEY_SET = new PublicKeySend();
|
||||
SEQUENCE_GET = new SequenceGet();
|
||||
|
@ -153,7 +141,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
filter.addAction(ACTION_DATE_CHANGED);
|
||||
filter.addAction(ACTION_TIMEZONE_CHANGED);
|
||||
|
||||
dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter);
|
||||
Observable<Intent> dateTimeChanged = RxBroadcastReceiver.Companion.create(context, filter);
|
||||
|
||||
compositeDisposable.add(
|
||||
Observable.combineLatest(patch.observeConnected(), pm.observePatchLifeCycle(),
|
||||
|
@ -178,7 +166,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
|
||||
compositeDisposable.add(
|
||||
patch.observeConnected()
|
||||
.doOnNext(it -> onPatchConnected(it))
|
||||
.doOnNext(this::onPatchConnected)
|
||||
.subscribe());
|
||||
|
||||
compositeDisposable.add(
|
||||
|
@ -190,22 +178,22 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
|
||||
compositeDisposable.add(
|
||||
EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class)
|
||||
.filter(it -> it.isFirst())
|
||||
.filter(EventEoPatchAlarm::isFirst)
|
||||
.filter(it -> !pm.getPatchConfig().isDeactivated())
|
||||
.filter(it -> patch.getConnectionState().isConnected())
|
||||
.concatMapIterable(it -> it.getAlarmCodes())
|
||||
.filter(it -> it.isPatchOccurrenceAlert())
|
||||
.concatMapIterable(EventEoPatchAlarm::getAlarmCodes)
|
||||
.filter(AlarmCode::isPatchOccurrenceAlert)
|
||||
.flatMap(it -> stopAeBeep(it.getAeCode()).toObservable())
|
||||
.subscribe()
|
||||
);
|
||||
|
||||
compositeDisposable.add(
|
||||
EoPatchRxBus.INSTANCE.listen(EventEoPatchAlarm.class)
|
||||
.filter(it -> it.isFirst())
|
||||
.filter(EventEoPatchAlarm::isFirst)
|
||||
.filter(it -> !pm.getPatchConfig().isDeactivated())
|
||||
.filter(it -> patch.getConnectionState().isConnected())
|
||||
.concatMapIterable(it -> it.getAlarmCodes())
|
||||
.filter(it -> it.isPatchOccurrenceAlarm())
|
||||
.concatMapIterable(EventEoPatchAlarm::getAlarmCodes)
|
||||
.filter(AlarmCode::isPatchOccurrenceAlarm)
|
||||
.flatMap(it -> pauseBasalImpl(0.0f, System.currentTimeMillis(), it).toObservable())
|
||||
.subscribe()
|
||||
);
|
||||
|
@ -218,7 +206,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
private void onPatchConnected(boolean connected) {
|
||||
boolean activated = pm.getPatchConfig().isActivated();
|
||||
boolean useEncryption = pm.getPatchConfig().getSharedKey() != null;
|
||||
int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVIOR_REMINDERS(), 0);
|
||||
int doseUnit = sp.getInt(SettingKeys.Companion.getLOW_RESERVOIR_REMINDERS(), 0);
|
||||
int hours = sp.getInt(SettingKeys.Companion.getEXPIRATION_REMINDERS(), 0);
|
||||
boolean buzzer = sp.getBoolean(SettingKeys.Companion.getBUZZER_REMINDERS(), false);
|
||||
PatchConfig pc = pm.getPatchConfig();
|
||||
|
@ -256,7 +244,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
.subscribe());
|
||||
}
|
||||
|
||||
if(connected == false && activated == true){
|
||||
if(!connected && activated){
|
||||
pm.getPatchConfig().updatetDisconnectedTime();
|
||||
}
|
||||
}
|
||||
|
@ -266,13 +254,15 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
patch.observeAlarmNotification()
|
||||
.subscribe(
|
||||
this::onAlarmNotification,
|
||||
throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage())
|
||||
throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage() != null ?
|
||||
throwable.getMessage() : "AlarmNotification observation error")
|
||||
),
|
||||
patch.observeInfoNotification()
|
||||
.filter(state -> pm.getPatchConfig().isActivated())
|
||||
.subscribe(
|
||||
this::onInfoNotification,
|
||||
throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage())
|
||||
throwable -> aapsLogger.error(LTag.PUMP, throwable.getMessage() != null ?
|
||||
throwable.getMessage() : "InfoNotification observation error")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
@ -294,8 +284,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
consumer.accept(pm.getPatchConfig());
|
||||
if (needSave) {
|
||||
pm.flushPatchConfig();
|
||||
} else {
|
||||
pm.flushPatchConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -304,11 +292,8 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
|
||||
NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal();
|
||||
|
||||
if (normalBasal != null) {
|
||||
// 아래 코드를 실행하면 isDoseUChanged 가 false 가 된다.
|
||||
if(normalBasal.updateNormalBasalIndex()) {
|
||||
pm.flushNormalBasalManager();
|
||||
}
|
||||
if(normalBasal.updateNormalBasalIndex()) {
|
||||
pm.flushNormalBasalManager();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -363,7 +348,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
* Activation Process task #4 NEEDLE SENSING
|
||||
* Fragment: fragment_patch_rotate_knob
|
||||
*/
|
||||
public Single<Boolean> checkNeedleSensing(long timeout) { //TODO: Timeout 추가?
|
||||
public Single<Boolean> checkNeedleSensing(long timeout) {
|
||||
return START_NEEDLE_CHECK.start()
|
||||
.timeout(timeout, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
@ -398,7 +383,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
|
||||
public Single<BasalScheduleSetResponse> startBasal(NormalBasal basal) {
|
||||
|
||||
return startNormalBasalTask.start(basal, false)
|
||||
return startNormalBasalTask.start(basal)
|
||||
.timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
|
@ -427,22 +412,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
return pauseBasalTask.pause(pauseDurationHour, alarmOccurredTime, alarmCode);
|
||||
}
|
||||
|
||||
private Single<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]
|
||||
//==============================================================================================
|
||||
|
@ -504,34 +473,34 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
return stopComboBolusTask.stop().timeout(DEFAULT_API_TIME_OUT, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private Single<? extends BaseResponse> stopNowAndExtBolus() {
|
||||
|
||||
boolean nowActive = pm.getPatchState().isNowBolusActive();
|
||||
boolean extActive = pm.getPatchState().isExtBolusActive();
|
||||
|
||||
if (nowActive && extActive) {
|
||||
return stopComboBolus();
|
||||
} else if (nowActive) {
|
||||
return stopNowBolus();
|
||||
} else if (extActive) {
|
||||
return stopExtBolus();
|
||||
}
|
||||
|
||||
return Single.just(new PatchBooleanResponse(true));
|
||||
}
|
||||
// private Single<? extends BaseResponse> stopNowAndExtBolus() {
|
||||
//
|
||||
// boolean nowActive = pm.getPatchState().isNowBolusActive();
|
||||
// boolean extActive = pm.getPatchState().isExtBolusActive();
|
||||
//
|
||||
// if (nowActive && extActive) {
|
||||
// return stopComboBolus();
|
||||
// } else if (nowActive) {
|
||||
// return stopNowBolus();
|
||||
// } else if (extActive) {
|
||||
// return stopExtBolus();
|
||||
// }
|
||||
//
|
||||
// return Single.just(new PatchBooleanResponse(true));
|
||||
// }
|
||||
|
||||
//==============================================================================================
|
||||
// IPatchManager implementation [BOLUS]
|
||||
//==============================================================================================
|
||||
|
||||
public void readBolusStatusFromNotification(InfoNotification noti) {
|
||||
if (noti.isBolusRegAct()) {
|
||||
public void readBolusStatusFromNotification(InfoNotification infoNotification) {
|
||||
if (infoNotification.isBolusRegAct()) {
|
||||
BolusCurrent bolusCurrent = pm.getBolusCurrent();
|
||||
|
||||
Arrays.asList(BolusType.NOW, BolusType.EXT).forEach(type -> {
|
||||
if (noti.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요.
|
||||
int injectedPumpCount = noti.getInjected(type);
|
||||
int remainPumpCount = noti.getRemain(type);
|
||||
if (infoNotification.isBolusRegAct(type)) { // 완료되었어도 업데이트 필요.
|
||||
int injectedPumpCount = infoNotification.getInjected(type);
|
||||
int remainPumpCount = infoNotification.getRemain(type);
|
||||
bolusCurrent.updateBolusFromPatch(type, injectedPumpCount, remainPumpCount);
|
||||
}
|
||||
});
|
||||
|
@ -547,29 +516,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
return deactivateTask.run(force, timeout);
|
||||
}
|
||||
|
||||
public Single<? 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
|
||||
InfoReminderTask infoReminderTask;
|
||||
|
||||
|
@ -677,8 +623,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
ECGenParameterSpec ecSpec_named = new ECGenParameterSpec(SECP256R1);
|
||||
KeyPairGenerator kpg = KeyPairGenerator.getInstance(EC);
|
||||
kpg.initialize(ecSpec_named);
|
||||
KeyPair pair = kpg.generateKeyPair();
|
||||
return pair;
|
||||
return kpg.generateKeyPair();
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -729,8 +674,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
}
|
||||
|
||||
public static ECPublicKey rawToEncodedECPublicKey(String curveName, byte[] rawBytes) throws
|
||||
NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException,
|
||||
InvalidAlgorithmParameterException {
|
||||
NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException {
|
||||
KeyFactory kf = KeyFactory.getInstance(EC);
|
||||
int mid = rawBytes.length / 2;
|
||||
byte[] x = Arrays.copyOfRange(rawBytes, 0, mid);
|
||||
|
@ -740,7 +684,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
}
|
||||
|
||||
public static ECParameterSpec ecParameterSpecForCurve(String curveName) throws
|
||||
NoSuchAlgorithmException, InvalidParameterSpecException, InvalidAlgorithmParameterException {
|
||||
NoSuchAlgorithmException, InvalidParameterSpecException {
|
||||
AlgorithmParameters params = AlgorithmParameters.getInstance(EC);
|
||||
params.init(new ECGenParameterSpec(curveName));
|
||||
return params.getParameterSpec(ECParameterSpec.class);
|
||||
|
@ -755,7 +699,6 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
|
||||
return keyAgreement.generateSecret();
|
||||
} catch (InvalidKeyException | NoSuchAlgorithmException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
|
@ -768,8 +711,7 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
private static final Scheduler SS = Schedulers.single();
|
||||
|
||||
public BleConnectionState getPatchConnectionState() {
|
||||
BleConnectionState result = patch.getConnectionState();
|
||||
return result;
|
||||
return patch.getConnectionState();
|
||||
}
|
||||
|
||||
public Observable<BleConnectionState> observePatchConnectionState() {
|
||||
|
@ -780,14 +722,3 @@ public class PatchManagerImpl/* implements IPatchConstant*/ {
|
|||
patch.updateMacAddress(mac, b);
|
||||
}
|
||||
}
|
||||
|
||||
class AlarmFiredEventInfo
|
||||
{
|
||||
public AlarmCode code;
|
||||
public long createTimestamp;
|
||||
|
||||
public AlarmFiredEventInfo(AlarmCode code, long createTimestamp) {
|
||||
this.code = code;
|
||||
this.createTimestamp = createTimestamp;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -52,7 +52,7 @@ public class PatchStateManager {
|
|||
final PatchState oldState = pm.getPatchState();
|
||||
|
||||
int diff = newState.currentTime() - oldState.currentTime();
|
||||
if (0 <= diff && diff < 10) { // TODO 상수로 변경.
|
||||
if (0 <= diff && diff < 10) {
|
||||
/* 10초 안에 같은 PatchState update 시 skip */
|
||||
if (oldState.equalState(newState)) {
|
||||
return;
|
||||
|
@ -267,8 +267,7 @@ public class PatchStateManager {
|
|||
public synchronized void onBasalStarted(NormalBasal basal, long timestamp) {
|
||||
if (basal != null) {
|
||||
pm.getNormalBasalManager().updateBasalStarted();
|
||||
|
||||
basal.updateNormalBasalIndex(); //normal basal index를 업데이트하여 basal change 이력이 또 발생하는것을 방지(df_356)
|
||||
basal.updateNormalBasalIndex();
|
||||
}
|
||||
|
||||
pm.getPatchConfig().updateNormalBasalStarted(); // updateNormalBasalStarted 도 동일함...
|
||||
|
|
|
@ -148,12 +148,12 @@ class PreferenceManager @Inject constructor(): IPreferenceManager {
|
|||
aapsLogger.error(LTag.PUMP, ex.message?:"Alarms load error")
|
||||
}
|
||||
|
||||
aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: ${mPatchConfig}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from PatchState preference: ${mPatchState}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: ${mBolusCurrent}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: ${mNormalBasalMgr}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: ${mTempBasalMgr}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from Alarms preference: ${mAlarms}")
|
||||
aapsLogger.info(LTag.PUMP,"Load from PatchConfig preference: $mPatchConfig")
|
||||
aapsLogger.info(LTag.PUMP,"Load from PatchState preference: $mPatchState")
|
||||
aapsLogger.info(LTag.PUMP,"Load from BolusCurrent preference: $mBolusCurrent")
|
||||
aapsLogger.info(LTag.PUMP,"Load from NormalBasal preference: $mNormalBasalMgr")
|
||||
aapsLogger.info(LTag.PUMP,"Load from TempBasal preference: $mTempBasalMgr")
|
||||
aapsLogger.info(LTag.PUMP,"Load from Alarms preference: $mAlarms")
|
||||
initialized = true
|
||||
}
|
||||
|
||||
|
@ -179,9 +179,8 @@ class PreferenceManager @Inject constructor(): IPreferenceManager {
|
|||
flushBolusCurrent()
|
||||
mTempBasalMgr.clear()
|
||||
flushTempBasalManager()
|
||||
// mAlarms.clear()
|
||||
// flushAlarms()
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
|
||||
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalScheduleSetBig;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.SetKey;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.BaseResponse;
|
||||
|
||||
|
@ -17,15 +16,11 @@ import io.reactivex.schedulers.Schedulers;
|
|||
public class ActivateTask extends TaskBase {
|
||||
@Inject StartNormalBasalTask startBasalTask;
|
||||
|
||||
private SetKey SET_KEY;
|
||||
private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
|
||||
|
||||
private final SetKey SET_KEY = new SetKey();
|
||||
|
||||
@Inject
|
||||
public ActivateTask() {
|
||||
super(TaskFunc.ACTIVATE);
|
||||
SET_KEY = new SetKey();
|
||||
BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig();
|
||||
}
|
||||
|
||||
public Single<Boolean> start() {
|
||||
|
@ -35,9 +30,9 @@ public class ActivateTask extends TaskBase {
|
|||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.observeOn(Schedulers.io()).doOnSuccess(this::onActivated)
|
||||
.flatMap(v -> startBasalTask.start(enabled, false))
|
||||
.flatMap(v -> startBasalTask.start(enabled))
|
||||
.map(BaseResponse::isSuccess)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ActivateTask error"));
|
||||
}
|
||||
|
||||
private void onActivated(BaseResponse response) {
|
||||
|
|
|
@ -4,6 +4,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.BolusExDuration;
|
|||
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.util.FloatAdjusters;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent;
|
||||
|
||||
abstract class BolusTask extends TaskBase {
|
||||
|
@ -16,17 +17,17 @@ abstract class BolusTask extends TaskBase {
|
|||
boolean now = (nowDoseU > 0);
|
||||
boolean ext = (exDoseU > 0);
|
||||
|
||||
long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720
|
||||
long startTimestamp = now ? System.currentTimeMillis() : 0;
|
||||
long endTimestamp = startTimestamp + getPumpDuration(nowDoseU);
|
||||
|
||||
long nowHistoryID = 1L; //record no
|
||||
long exStartTimestamp = 0;
|
||||
long exStartTimestamp;
|
||||
|
||||
if (now) {
|
||||
pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp);
|
||||
}
|
||||
if (ext) {
|
||||
long estimatedExStartTimestamp = 0;
|
||||
long estimatedExStartTimestamp;
|
||||
|
||||
if (now) {
|
||||
exStartTimestamp = 0;
|
||||
|
@ -46,12 +47,8 @@ abstract class BolusTask extends TaskBase {
|
|||
}
|
||||
|
||||
|
||||
public void onCalcBolusStarted(float nowDoseU, float correctionBolus, float exDoseU,
|
||||
BolusExDuration exDuration) {
|
||||
|
||||
public void onCalcBolusStarted(float nowDoseU) {
|
||||
boolean now = (nowDoseU > 0);
|
||||
boolean ext = (exDoseU > 0);
|
||||
|
||||
|
||||
long startTimestamp = now ? System.currentTimeMillis() : 0; // dm_1720
|
||||
long endTimestamp = startTimestamp + getPumpDuration(nowDoseU);
|
||||
|
@ -62,24 +59,6 @@ abstract class BolusTask extends TaskBase {
|
|||
pm.getBolusCurrent().startNowBolus(nowHistoryID, nowDoseU, startTimestamp, endTimestamp);
|
||||
}
|
||||
|
||||
long exStartTimestamp = 0;
|
||||
|
||||
if (ext) {
|
||||
long estimatedExStartTimestamp = 0;
|
||||
|
||||
if (now) {
|
||||
exStartTimestamp = 0;
|
||||
}
|
||||
else {
|
||||
estimatedExStartTimestamp = System.currentTimeMillis();
|
||||
exStartTimestamp = estimatedExStartTimestamp;
|
||||
}
|
||||
long exEndTimestamp = exStartTimestamp + exDuration.milli();
|
||||
long extHistoryID = 2L; //record no
|
||||
pm.getBolusCurrent().startExtBolus(extHistoryID, exDoseU, exStartTimestamp,
|
||||
exEndTimestamp, exDuration.milli());
|
||||
}
|
||||
|
||||
pm.flushBolusCurrent();
|
||||
}
|
||||
|
||||
|
@ -88,12 +67,13 @@ abstract class BolusTask extends TaskBase {
|
|||
}
|
||||
|
||||
public void updateNowBolusStopped(int injected, long suspendedTimestamp) {
|
||||
|
||||
BolusCurrent bolusCurrent = pm.getBolusCurrent();
|
||||
long nowID = bolusCurrent.historyId(BolusType.NOW);
|
||||
if (nowID > 0 && !bolusCurrent.endTimeSynced(BolusType.NOW)) {
|
||||
// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
|
||||
// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P);
|
||||
long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
|
||||
float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P);
|
||||
bolusCurrent.getNowBolus().setInjected(injectedDoseU);
|
||||
bolusCurrent.getNowBolus().setEndTimestamp(stopTime);
|
||||
bolusCurrent.setEndTimeSynced(BolusType.NOW, true);
|
||||
pm.flushBolusCurrent();
|
||||
}
|
||||
|
@ -107,8 +87,10 @@ abstract class BolusTask extends TaskBase {
|
|||
BolusCurrent bolusCurrent = pm.getBolusCurrent();
|
||||
long extID = bolusCurrent.historyId(BolusType.EXT);
|
||||
if (extID > 0 && !bolusCurrent.endTimeSynced(BolusType.EXT)) {
|
||||
// long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
|
||||
// float injectedDoseU = FloatAdjusters.INSTANCE.getFLOOR2_BOLUS().apply(injected * AppConstant.INSULIN_UNIT_P);
|
||||
long stopTime = (suspendedTimestamp > 0) ? suspendedTimestamp : System.currentTimeMillis();
|
||||
float injectedDoseU = FloatAdjusters.FLOOR2_BOLUS.apply(injected * AppConstant.INSULIN_UNIT_P);
|
||||
bolusCurrent.getExtBolus().setInjected(injectedDoseU);
|
||||
bolusCurrent.getExtBolus().setEndTimestamp(stopTime);
|
||||
bolusCurrent.setEndTimeSynced(BolusType.EXT, true);
|
||||
pm.flushBolusCurrent();
|
||||
}
|
||||
|
@ -116,8 +98,8 @@ abstract class BolusTask extends TaskBase {
|
|||
|
||||
private long getPumpDuration(float doseU) {
|
||||
if (doseU > 0) {
|
||||
long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli(); //todo
|
||||
return (long) ((doseU / AppConstant.Companion.getBOLUS_UNIT_STEP()) * pumpDuration);
|
||||
long pumpDuration = pm.getPatchConfig().getPumpDurationSmallMilli();
|
||||
return (long) ((doseU / AppConstant.BOLUS_UNIT_STEP) * pumpDuration);
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
|
|
@ -5,7 +5,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager;
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.DeactivationStatus;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
@ -14,7 +13,6 @@ import javax.inject.Singleton;
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.DeActivation;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.BolusCurrent;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchLifecycleEvent;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal;
|
||||
import io.reactivex.Observable;
|
||||
import io.reactivex.Single;
|
||||
|
@ -22,14 +20,10 @@ import io.reactivex.schedulers.Schedulers;
|
|||
|
||||
@Singleton
|
||||
public class DeactivateTask extends TaskBase {
|
||||
@Inject StopBasalTask stopBasalTask;
|
||||
@Inject IPreferenceManager pm;
|
||||
|
||||
@Inject
|
||||
StopBasalTask stopBasalTask;
|
||||
|
||||
@Inject
|
||||
IPreferenceManager pm;
|
||||
|
||||
private DeActivation DEACTIVATION;
|
||||
private final DeActivation DEACTIVATION;
|
||||
|
||||
@Inject
|
||||
public DeactivateTask() {
|
||||
|
@ -44,16 +38,16 @@ public class DeactivateTask extends TaskBase {
|
|||
DEACTIVATION.start()
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.observeOn(Schedulers.io())
|
||||
.doOnSuccess(response -> onDeactivated(false)))
|
||||
.doOnSuccess(response -> onDeactivated()))
|
||||
.map(response -> DeactivationStatus.of(response.isSuccess(), forced))
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "DeactivateTask error"))
|
||||
.onErrorResumeNext(e -> {
|
||||
if (forced) {
|
||||
try {
|
||||
onDeactivated(true);
|
||||
onDeactivated();
|
||||
} catch (Exception t) {
|
||||
aapsLogger.error(LTag.PUMPCOMM, e.getMessage());
|
||||
aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "DeactivateTask error");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -73,31 +67,27 @@ public class DeactivateTask extends TaskBase {
|
|||
return isReady();
|
||||
}
|
||||
|
||||
/* Schedulers.io() */
|
||||
private void onDeactivated(boolean forced) throws SQLException {
|
||||
private void onDeactivated() {
|
||||
synchronized (lock) {
|
||||
patch.updateMacAddress(null, false);
|
||||
|
||||
if (pm.getPatchConfig().getLifecycleEvent().isShutdown()) {
|
||||
return;
|
||||
}
|
||||
|
||||
cleanUpRepository();
|
||||
|
||||
pm.getNormalBasalManager().updateForDeactivation();
|
||||
|
||||
pm.updatePatchLifeCycle(PatchLifecycleEvent.createShutdown());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanUpRepository() throws SQLException {
|
||||
private void cleanUpRepository() {
|
||||
updateNowBolusStopped();
|
||||
updateExtBolusStopped();
|
||||
updateTempBasalStopped();
|
||||
}
|
||||
|
||||
private void updateTempBasalStopped() throws SQLException {
|
||||
private void updateTempBasalStopped() {
|
||||
TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal();
|
||||
|
||||
if (tempBasal != null) {
|
||||
|
@ -106,7 +96,6 @@ public class DeactivateTask extends TaskBase {
|
|||
}
|
||||
}
|
||||
|
||||
/* copied from BolusTask. */
|
||||
private void updateNowBolusStopped() {
|
||||
BolusCurrent bolusCurrent = pm.getBolusCurrent();
|
||||
long nowID = bolusCurrent.historyId(BolusType.NOW);
|
||||
|
@ -117,7 +106,6 @@ public class DeactivateTask extends TaskBase {
|
|||
}
|
||||
}
|
||||
|
||||
/* copied from BolusTask. */
|
||||
private void updateExtBolusStopped() {
|
||||
BolusCurrent bolusCurrent = pm.getBolusCurrent();
|
||||
long extID = bolusCurrent.historyId(BolusType.EXT);
|
||||
|
|
|
@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
|
|||
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.bus.RxBus;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetErrorCodes;
|
||||
|
||||
|
@ -13,18 +12,13 @@ import javax.inject.Singleton;
|
|||
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.AeCodeResponse;
|
||||
import io.reactivex.Single;
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers;
|
||||
|
||||
@Singleton
|
||||
public class FetchAlarmTask extends TaskBase {
|
||||
@Inject RxBus rxBus;
|
||||
@Inject IAlarmRegistry alarmRegistry;
|
||||
|
||||
@Inject
|
||||
RxBus rxBus;
|
||||
|
||||
@Inject
|
||||
IAlarmRegistry alarmRegistry;
|
||||
|
||||
private GetErrorCodes ALARM_ALERT_ERROR_CODE_GET;
|
||||
private final GetErrorCodes ALARM_ALERT_ERROR_CODE_GET;
|
||||
|
||||
@Inject
|
||||
public FetchAlarmTask() {
|
||||
|
@ -38,7 +32,7 @@ public class FetchAlarmTask extends TaskBase {
|
|||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnSuccess(aeCodeResponse -> alarmRegistry.add(aeCodeResponse.getAlarmCodes()))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "FetchAlarmTask error"));
|
||||
}
|
||||
|
||||
public synchronized void enqueue() {
|
||||
|
|
|
@ -26,17 +26,15 @@ import io.reactivex.schedulers.Schedulers;
|
|||
|
||||
@Singleton
|
||||
public class GetPatchInfoTask extends TaskBase {
|
||||
@Inject UpdateConnectionTask updateConnectionTask;
|
||||
|
||||
@Inject
|
||||
UpdateConnectionTask updateConnectionTask;
|
||||
|
||||
private SetGlobalTime SET_GLOBAL_TIME;
|
||||
private GetSerialNumber SERIAL_NUMBER_GET;
|
||||
private GetLOT LOT_NUMBER_GET;
|
||||
private GetFirmwareVersion FIRMWARE_VERSION_GET;
|
||||
private GetWakeUpTime WAKE_UP_TIME_GET;
|
||||
private GetPumpDuration PUMP_DURATION_GET;
|
||||
private GetModelName GET_MODEL_NAME;
|
||||
private final SetGlobalTime SET_GLOBAL_TIME;
|
||||
private final GetSerialNumber SERIAL_NUMBER_GET;
|
||||
private final GetLOT LOT_NUMBER_GET;
|
||||
private final GetFirmwareVersion FIRMWARE_VERSION_GET;
|
||||
private final GetWakeUpTime WAKE_UP_TIME_GET;
|
||||
private final GetPumpDuration PUMP_DURATION_GET;
|
||||
private final GetModelName GET_MODEL_NAME;
|
||||
|
||||
@Inject
|
||||
public GetPatchInfoTask() {
|
||||
|
@ -61,17 +59,16 @@ public class GetPatchInfoTask extends TaskBase {
|
|||
PUMP_DURATION_GET.get().doOnSuccess(this::onPumpDurationResponse),
|
||||
GET_MODEL_NAME.get().doOnSuccess(this::onModelNameResponse)))
|
||||
.map(BaseResponse::isSuccess)
|
||||
.filter(v -> !v) // fail 시 false 가 아래로 내려간다.
|
||||
.filter(v -> !v)
|
||||
.first(true);
|
||||
|
||||
return isReady()
|
||||
.concatMapSingle(it -> tasks)
|
||||
.firstOrError()
|
||||
// .flatMap(v -> updateConnectionTask.update()).map(v -> true)
|
||||
.observeOn(Schedulers.io())
|
||||
.doOnSuccess(this::onPatchWakeupSuccess)
|
||||
.doOnError(this::onPatchWakeupFailed)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "GetPatchInfoTask error"));
|
||||
}
|
||||
|
||||
private void onSerialNumberResponse(SerialNumberResponse v) {
|
||||
|
@ -91,23 +88,21 @@ public class GetPatchInfoTask extends TaskBase {
|
|||
}
|
||||
|
||||
private void onPumpDurationResponse(PumpDurationResponse v) {
|
||||
pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100); // 0.1 초 단위
|
||||
pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100);
|
||||
pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100);
|
||||
pm.getPatchConfig().setPumpDurationLargeMilli(v.getDurationL() * 100L);
|
||||
pm.getPatchConfig().setPumpDurationMediumMilli(v.getDurationM() * 100L);
|
||||
pm.getPatchConfig().setPumpDurationSmallMilli(v.getDurationS() * 100L);
|
||||
}
|
||||
|
||||
private void onModelNameResponse(ModelNameResponse modelNameResponse) {
|
||||
pm.getPatchConfig().setPatchModelName(modelNameResponse.getModelName());
|
||||
}
|
||||
|
||||
/* Schedulers.io() */
|
||||
private void onPatchWakeupSuccess(Boolean result) {
|
||||
synchronized (lock) {
|
||||
pm.flushPatchConfig();
|
||||
}
|
||||
}
|
||||
|
||||
/* Schedulers.io() */
|
||||
private void onPatchWakeupFailed(Throwable e) {
|
||||
patch.setSeq(-1);
|
||||
pm.getPatchConfig().updateDeactivated();
|
||||
|
|
|
@ -14,11 +14,9 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class InfoReminderTask extends TaskBase {
|
||||
@Inject IPreferenceManager pm;
|
||||
|
||||
@Inject
|
||||
IPreferenceManager pm;
|
||||
|
||||
private InfoReminderSet INFO_REMINDER_SET;
|
||||
private final InfoReminderSet INFO_REMINDER_SET;
|
||||
|
||||
@Inject
|
||||
public InfoReminderTask() {
|
||||
|
@ -32,7 +30,7 @@ public class InfoReminderTask extends TaskBase {
|
|||
.concatMapSingle(v -> INFO_REMINDER_SET.set(infoReminder))
|
||||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "InfoReminderTask error"));
|
||||
}
|
||||
|
||||
public synchronized void enqueue() {
|
||||
|
|
|
@ -6,8 +6,6 @@ import info.nightscout.androidaps.interfaces.PumpSync;
|
|||
import info.nightscout.androidaps.logging.UserEntryLogger;
|
||||
import info.nightscout.androidaps.utils.userEntry.UserEntryMapper;
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatchConstant;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
@ -15,11 +13,8 @@ import javax.inject.Singleton;
|
|||
|
||||
import info.nightscout.androidaps.interfaces.CommandQueue;
|
||||
import info.nightscout.shared.logging.AAPSLogger;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.GetInternalSuspendTime;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.PatchInternalSuspendTimeResponse;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState;
|
||||
import info.nightscout.androidaps.queue.Callback;
|
||||
import info.nightscout.androidaps.queue.commands.Command;
|
||||
|
||||
|
@ -29,47 +24,44 @@ import io.reactivex.subjects.BehaviorSubject;
|
|||
|
||||
@Singleton
|
||||
public class InternalSuspendedTask extends BolusTask {
|
||||
|
||||
@Inject CommandQueue commandQueue;
|
||||
@Inject AAPSLogger aapsLogger;
|
||||
@Inject PumpSync pumpSync;
|
||||
@Inject UserEntryLogger uel;
|
||||
|
||||
private GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET;
|
||||
private BolusStop BOLUS_STOP;
|
||||
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
|
||||
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
private final GetInternalSuspendTime INTERNAL_SUSPEND_TIME_GET;
|
||||
private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> extendedBolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
|
||||
@Inject
|
||||
public InternalSuspendedTask() {
|
||||
super(TaskFunc.INTERNAL_SUSPEND);
|
||||
|
||||
INTERNAL_SUSPEND_TIME_GET = new GetInternalSuspendTime();
|
||||
BOLUS_STOP = new BolusStop();
|
||||
TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getBolusSebject(){
|
||||
private Observable<Boolean> getBolusSubject(){
|
||||
return bolusCheckSubject.hide();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getExbolusSebject(){
|
||||
return exbolusCheckSubject.hide();
|
||||
private Observable<Boolean> getExtendedBolusSubject(){
|
||||
return extendedBolusCheckSubject.hide();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getBasalSebject(){
|
||||
private Observable<Boolean> getBasalSubject(){
|
||||
return basalCheckSubject.hide();
|
||||
}
|
||||
|
||||
public Single<Long> start(boolean isNowBolusActive, boolean isExtBolusActive, boolean isTempBasalActive) {
|
||||
PatchState patchState = pm.getPatchState();
|
||||
|
||||
if (isNowBolusActive || isExtBolusActive) {
|
||||
enqueue(TaskFunc.READ_BOLUS_FINISH_TIME);
|
||||
}
|
||||
|
||||
if (isTempBasalActive) {
|
||||
enqueue(TaskFunc.READ_TEMP_BASAL_FINISH_TIME);
|
||||
}
|
||||
|
||||
if (commandQueue.isRunning(Command.CommandType.BOLUS)) {
|
||||
uel.log(UserEntryMapper.Action.CANCEL_BOLUS, UserEntryMapper.Sources.EOPatch2);
|
||||
commandQueue.cancelAllBoluses();
|
||||
|
@ -82,11 +74,11 @@ public class InternalSuspendedTask extends BolusTask {
|
|||
commandQueue.cancelExtended(new Callback() {
|
||||
@Override
|
||||
public void run() {
|
||||
exbolusCheckSubject.onNext(true);
|
||||
extendedBolusCheckSubject.onNext(true);
|
||||
}
|
||||
});
|
||||
}else{
|
||||
exbolusCheckSubject.onNext(true);
|
||||
extendedBolusCheckSubject.onNext(true);
|
||||
}
|
||||
|
||||
if (pumpSync.expectedPumpState().getTemporaryBasal() != null) {
|
||||
|
@ -101,14 +93,13 @@ public class InternalSuspendedTask extends BolusTask {
|
|||
basalCheckSubject.onNext(true);
|
||||
}
|
||||
|
||||
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> {
|
||||
return (bolusReady && exbolusReady && basalReady);
|
||||
})
|
||||
return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(),
|
||||
(bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady))
|
||||
.filter(ready -> ready)
|
||||
.flatMap(v -> isReady())
|
||||
.concatMapSingle(v -> getInternalSuspendTime())
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "InternalSuspendedTask error"));
|
||||
}
|
||||
|
||||
private Single<Long> getInternalSuspendTime() {
|
||||
|
@ -117,56 +108,6 @@ public class InternalSuspendedTask extends BolusTask {
|
|||
.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) {
|
||||
boolean ready = (disposable == null || disposable.isDisposed());
|
||||
|
||||
|
@ -175,7 +116,7 @@ public class InternalSuspendedTask extends BolusTask {
|
|||
.timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS)
|
||||
.subscribe(v -> {
|
||||
bolusCheckSubject.onNext(false);
|
||||
exbolusCheckSubject.onNext(false);
|
||||
extendedBolusCheckSubject.onNext(false);
|
||||
basalCheckSubject.onNext(false);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -13,9 +13,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class NeedleSensingTask extends TaskBase {
|
||||
|
||||
@Inject
|
||||
IAlarmRegistry alarmRegistry;
|
||||
@Inject IAlarmRegistry alarmRegistry;
|
||||
|
||||
StartNeedleCheck START_NEEDLE_CHECK;
|
||||
UpdateConnection UPDATE_CONNECTION;
|
||||
|
@ -38,7 +36,7 @@ public class NeedleSensingTask extends TaskBase {
|
|||
.doOnNext(this::onResponse)
|
||||
.map(patchState -> !patchState.isNeedNeedleSensing())
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "NeedleSensingTask error"));
|
||||
}
|
||||
|
||||
private void onResponse(PatchState v) {
|
||||
|
|
|
@ -18,13 +18,9 @@ import info.nightscout.shared.logging.LTag;
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatchConstant;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalPause;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStop;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.response.PatchBooleanResponse;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasal;
|
||||
import info.nightscout.androidaps.queue.Callback;
|
||||
import info.nightscout.androidaps.queue.commands.Command;
|
||||
import io.reactivex.Observable;
|
||||
|
@ -40,33 +36,28 @@ public class PauseBasalTask extends BolusTask {
|
|||
@Inject PumpSync pumpSync;
|
||||
@Inject UserEntryLogger uel;
|
||||
|
||||
private BasalPause BASAL_PAUSE;
|
||||
private BolusStop BOLUS_STOP;
|
||||
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
|
||||
|
||||
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
private final BasalPause BASAL_PAUSE;
|
||||
|
||||
private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> extendedBolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
|
||||
@Inject
|
||||
public PauseBasalTask() {
|
||||
super(TaskFunc.PAUSE_BASAL);
|
||||
|
||||
BASAL_PAUSE = new BasalPause();
|
||||
BOLUS_STOP = new BolusStop();
|
||||
TEMP_BASAL_SCHEDULE_STOP = new TempBasalScheduleStop();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getBolusSebject(){
|
||||
private Observable<Boolean> getBolusSubject(){
|
||||
return bolusCheckSubject.hide();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getExbolusSebject(){
|
||||
return exbolusCheckSubject.hide();
|
||||
private Observable<Boolean> getExtendedBolusSubject(){
|
||||
return extendedBolusCheckSubject.hide();
|
||||
}
|
||||
|
||||
private Observable<Boolean> getBasalSebject(){
|
||||
private Observable<Boolean> getBasalSubject(){
|
||||
return basalCheckSubject.hide();
|
||||
}
|
||||
|
||||
|
@ -90,11 +81,11 @@ public class PauseBasalTask extends BolusTask {
|
|||
commandQueue.cancelExtended(new Callback() {
|
||||
@Override
|
||||
public void run() {
|
||||
exbolusCheckSubject.onNext(true);
|
||||
extendedBolusCheckSubject.onNext(true);
|
||||
}
|
||||
});
|
||||
}else{
|
||||
exbolusCheckSubject.onNext(true);
|
||||
extendedBolusCheckSubject.onNext(true);
|
||||
}
|
||||
|
||||
if (pumpSync.expectedPumpState().getTemporaryBasal() != null) {
|
||||
|
@ -109,71 +100,35 @@ public class PauseBasalTask extends BolusTask {
|
|||
basalCheckSubject.onNext(true);
|
||||
}
|
||||
|
||||
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> {
|
||||
return (bolusReady && exbolusReady && basalReady);
|
||||
})
|
||||
return Observable.zip(getBolusSubject(), getExtendedBolusSubject(), getBasalSubject(),
|
||||
(bolusReady, extendedBolusReady, basalReady) -> (bolusReady && extendedBolusReady && basalReady))
|
||||
.filter(ready -> ready)
|
||||
.flatMap(v -> isReady())
|
||||
.concatMapSingle(v -> getSuspendedTime(pausedTimestamp, alarmCode))
|
||||
.concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, suspendedTimestamp, alarmCode))
|
||||
.concatMapSingle(v -> getSuspendedTime(pausedTimestamp))
|
||||
.concatMapSingle(suspendedTimestamp -> pauseBasal(pauseDurationHour, alarmCode))
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "PauseBasalTask error"));
|
||||
}
|
||||
|
||||
private Single<Long> getSuspendedTime(long pausedTimestamp, @Nullable AlarmCode alarmCode) {
|
||||
private Single<Long> getSuspendedTime(long pausedTimestamp) {
|
||||
return Single.just(pausedTimestamp);
|
||||
}
|
||||
|
||||
private Single<Long> stopNowBolus(long pausedTimestamp, boolean isNowBolusActive) {
|
||||
if (isNowBolusActive) {
|
||||
return BOLUS_STOP.stop(IPatchConstant.NOW_BOLUS_ID)
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.doOnSuccess(v -> onNowBolusStopped(v.getInjectedBolusAmount(), pausedTimestamp))
|
||||
.map(v -> pausedTimestamp);
|
||||
}
|
||||
|
||||
return Single.just(pausedTimestamp);
|
||||
}
|
||||
|
||||
private Single<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) {
|
||||
private Single<PatchBooleanResponse> pauseBasal(float pauseDurationHour, @Nullable AlarmCode alarmCode) {
|
||||
if(alarmCode == null) {
|
||||
return BASAL_PAUSE.pause(pauseDurationHour)
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.doOnSuccess(v -> onBasalPaused(pauseDurationHour, suspendedTimestamp, null));
|
||||
.doOnSuccess(v -> onBasalPaused(pauseDurationHour, null));
|
||||
}
|
||||
|
||||
// 정지 알람 발생 시 basal pause 커맨드 전달하지 않음 - 주입 정지 이력만 생성
|
||||
onBasalPaused(pauseDurationHour, suspendedTimestamp, alarmCode);
|
||||
onBasalPaused(pauseDurationHour, alarmCode);
|
||||
|
||||
return Single.just(new PatchBooleanResponse(true));
|
||||
}
|
||||
|
||||
private void onBasalPaused(float pauseDurationHour, long suspendedTimestamp, @Nullable AlarmCode alarmCode) {
|
||||
private void onBasalPaused(float pauseDurationHour, @Nullable AlarmCode alarmCode) {
|
||||
if (!pm.getNormalBasalManager().isSuspended()) {
|
||||
String strCode = (alarmCode != null) ? alarmCode.name() : null;
|
||||
|
||||
if (alarmCode != null) {
|
||||
pm.getPatchConfig().updateNormalBasalPausedSilently();
|
||||
}
|
||||
|
@ -192,23 +147,6 @@ public class PauseBasalTask extends BolusTask {
|
|||
enqueue(TaskFunc.UPDATE_CONNECTION);
|
||||
}
|
||||
|
||||
private void onNowBolusStopped(int injectedBolusAmount, long suspendedTimestamp) {
|
||||
updateNowBolusStopped(injectedBolusAmount, suspendedTimestamp);
|
||||
}
|
||||
|
||||
private void onExtBolusStopped(int injectedBolusAmount, long suspendedTimestamp) {
|
||||
updateExtBolusStopped(injectedBolusAmount, suspendedTimestamp);
|
||||
}
|
||||
|
||||
private void onTempBasalCanceled(long suspendedTimestamp) {
|
||||
TempBasal tempBasal = pm.getTempBasalManager().getStartedBasal();
|
||||
|
||||
if (tempBasal != null) {
|
||||
pm.getTempBasalManager().updateBasalStopped();
|
||||
pm.flushTempBasalManager();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void enqueue(float pauseDurationHour, long pausedTime, @Nullable AlarmCode alarmCode) {
|
||||
boolean ready = (disposable == null || disposable.isDisposed());
|
||||
|
||||
|
@ -217,7 +155,7 @@ public class PauseBasalTask extends BolusTask {
|
|||
.timeout(TASK_ENQUEUE_TIME_OUT, TimeUnit.SECONDS)
|
||||
.subscribe(v -> {
|
||||
bolusCheckSubject.onNext(false);
|
||||
exbolusCheckSubject.onNext(false);
|
||||
extendedBolusCheckSubject.onNext(false);
|
||||
basalCheckSubject.onNext(false);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -14,9 +14,8 @@ import io.reactivex.Observable;
|
|||
|
||||
@Singleton
|
||||
public class PrimingTask extends TaskBase {
|
||||
|
||||
private UpdateConnection UPDATE_CONNECTION;
|
||||
private StartPriming START_PRIMING;
|
||||
private final UpdateConnection UPDATE_CONNECTION;
|
||||
private final StartPriming START_PRIMING;
|
||||
|
||||
@Inject
|
||||
public PrimingTask() {
|
||||
|
@ -31,25 +30,25 @@ public class PrimingTask extends TaskBase {
|
|||
.doOnNext(this::checkResponse)
|
||||
.flatMap(v -> observePrimingSuccess(count))
|
||||
.takeUntil(value -> (value == count))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "PrimingTask error"));
|
||||
}
|
||||
|
||||
private Observable<Long> observePrimingSuccess(long count) {
|
||||
|
||||
return Observable.merge(
|
||||
Observable.interval(1, TimeUnit.SECONDS).take(count + 10)
|
||||
.map(v -> v * 3) // 현재 20초 니깐 60 정도에서 꽉 채워짐. *4 도 괜찮을 듯.
|
||||
.map(v -> v * 3)
|
||||
.doOnNext(v -> {
|
||||
if (v >= count) {
|
||||
throw new Exception("Priming failed");
|
||||
}
|
||||
}), // 프로그래스바 용.
|
||||
}),
|
||||
|
||||
Observable.interval(3, TimeUnit.SECONDS)
|
||||
.concatMapSingle(v -> UPDATE_CONNECTION.get())
|
||||
.map(response -> PatchState.Companion.create(response.getPatchState(), System.currentTimeMillis()))
|
||||
.filter(patchState -> patchState.isPrimingSuccess())
|
||||
.map(result -> count) // 프라이밍 체크 용 성공시 count 값 리턴
|
||||
.filter(PatchState::isPrimingSuccess)
|
||||
.map(result -> count)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,8 +15,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class ReadBolusFinishTimeTask extends BolusTask {
|
||||
|
||||
private BolusFinishTimeGet BOLUS_FINISH_TIME_GET;
|
||||
private final BolusFinishTimeGet BOLUS_FINISH_TIME_GET;
|
||||
|
||||
@Inject
|
||||
public ReadBolusFinishTimeTask() {
|
||||
|
@ -30,7 +29,7 @@ public class ReadBolusFinishTimeTask extends BolusTask {
|
|||
.firstOrError()
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.doOnSuccess(this::onResponse)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ReadBolusFinishTimeTask error"));
|
||||
}
|
||||
|
||||
void onResponse(BolusFinishTimeResponse response) {
|
||||
|
|
|
@ -13,8 +13,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class ReadTempBasalFinishTimeTask extends TaskBase {
|
||||
|
||||
private TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET;
|
||||
private final TempBasalFinishTimeGet TEMP_BASAL_FINISH_TIME_GET;
|
||||
|
||||
@Inject
|
||||
public ReadTempBasalFinishTimeTask() {
|
||||
|
@ -28,7 +27,7 @@ public class ReadTempBasalFinishTimeTask extends TaskBase {
|
|||
.firstOrError()
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.doOnSuccess(this::onResponse)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ReadTempBasalFinishTimeTask error"));
|
||||
}
|
||||
|
||||
private void onResponse(TempBasalFinishTimeResponse response) {
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
|
||||
|
||||
import info.nightscout.shared.logging.AAPSLogger;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.alarm.IAlarmRegistry;
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ble.PatchStateManager;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalResume;
|
||||
|
@ -17,13 +18,11 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class ResumeBasalTask extends TaskBase {
|
||||
@Inject
|
||||
StartNormalBasalTask startNormalBasalTask;
|
||||
@Inject IAlarmRegistry alarmRegistry;
|
||||
@Inject StartNormalBasalTask startNormalBasalTask;
|
||||
@Inject PatchStateManager patchStateManager;
|
||||
|
||||
@Inject
|
||||
PatchStateManager patchStateManager;
|
||||
|
||||
private BasalResume BASAL_RESUME;
|
||||
private final BasalResume BASAL_RESUME;
|
||||
|
||||
@Inject
|
||||
public ResumeBasalTask() {
|
||||
|
@ -32,25 +31,21 @@ public class ResumeBasalTask extends TaskBase {
|
|||
}
|
||||
|
||||
public synchronized Single<? extends BaseResponse> resume() {
|
||||
|
||||
if (pm.getPatchConfig().getNeedSetBasalSchedule()) {
|
||||
NormalBasal normalBasal = pm.getNormalBasalManager().getNormalBasal();
|
||||
|
||||
if (normalBasal != null) {
|
||||
return startNormalBasalTask.start(normalBasal, true);
|
||||
}
|
||||
return startNormalBasalTask.start(pm.getNormalBasalManager().getNormalBasal());
|
||||
}
|
||||
|
||||
return isReady().concatMapSingle(v -> BASAL_RESUME.resume())
|
||||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnSuccess(v -> onResumeResponse(v))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "ResumeBasalTask error"));
|
||||
}
|
||||
|
||||
private void onResumeResponse(PatchBooleanResponse v) throws SQLException {
|
||||
private void onResumeResponse(PatchBooleanResponse v) {
|
||||
if (v.isSuccess()) {
|
||||
patchStateManager.onBasalResumed(v.getTimestamp() + 1000);
|
||||
alarmRegistry.remove(AlarmCode.B001).subscribe();
|
||||
}
|
||||
enqueue(TaskFunc.UPDATE_CONNECTION);
|
||||
}
|
||||
|
|
|
@ -18,10 +18,9 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class SelfTestTask extends TaskBase {
|
||||
|
||||
private GetTemperature TEMPERATURE_GET;
|
||||
private GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING;
|
||||
private GetGlobalTime GET_GLOBAL_TIME;
|
||||
private final GetTemperature TEMPERATURE_GET;
|
||||
private final GetVoltageLevelB4Priming BATTERY_LEVEL_GET_BEFORE_PRIMING;
|
||||
private final GetGlobalTime GET_GLOBAL_TIME;
|
||||
|
||||
@Inject
|
||||
public SelfTestTask() {
|
||||
|
@ -35,33 +34,17 @@ public class SelfTestTask extends TaskBase {
|
|||
public Single<PatchSelfTestResult> start() {
|
||||
Single<PatchSelfTestResult> tasks = Single.concat(Arrays.asList(
|
||||
TEMPERATURE_GET.get()
|
||||
.map(TemperatureResponse::getResult)
|
||||
.doOnSuccess(this::onTemperatureResult),
|
||||
.map(TemperatureResponse::getResult),
|
||||
BATTERY_LEVEL_GET_BEFORE_PRIMING.get()
|
||||
.map(BatteryVoltageLevelPairingResponse::getResult)
|
||||
.doOnSuccess(this::onBatteryResult),
|
||||
.map(BatteryVoltageLevelPairingResponse::getResult),
|
||||
GET_GLOBAL_TIME.get(false)
|
||||
.map(GlobalTimeResponse::getResult)
|
||||
.doOnSuccess(this::onTimeResult)))
|
||||
.map(GlobalTimeResponse::getResult)))
|
||||
.filter(result -> result != PatchSelfTestResult.TEST_SUCCESS)
|
||||
.first(PatchSelfTestResult.TEST_SUCCESS);
|
||||
|
||||
return isReady()
|
||||
.concatMapSingle(v -> tasks)
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
}
|
||||
|
||||
private void onTemperatureResult(PatchSelfTestResult patchSelfTestResult) {
|
||||
if (patchSelfTestResult != PatchSelfTestResult.TEST_SUCCESS) {
|
||||
}
|
||||
}
|
||||
|
||||
private void onBatteryResult(PatchSelfTestResult patchSelfTestResult) {
|
||||
if (patchSelfTestResult != PatchSelfTestResult.TEST_SUCCESS) {
|
||||
}
|
||||
}
|
||||
|
||||
private void onTimeResult(PatchSelfTestResult patchSelfTestResult) {
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SelfTestTask error"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,9 +16,8 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class SetGlobalTimeTask extends TaskBase {
|
||||
|
||||
private SetGlobalTime SET_GLOBAL_TIME;
|
||||
private GetGlobalTime GET_GLOBAL_TIME;
|
||||
private final SetGlobalTime SET_GLOBAL_TIME;
|
||||
private final GetGlobalTime GET_GLOBAL_TIME;
|
||||
|
||||
@Inject
|
||||
public SetGlobalTimeTask() {
|
||||
|
@ -37,24 +36,23 @@ public class SetGlobalTimeTask extends TaskBase {
|
|||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnSuccess(v -> onSuccess())
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SetGlobalTimeTask error"));
|
||||
}
|
||||
|
||||
private boolean checkPatchTime(GlobalTimeResponse response) throws Exception {
|
||||
private void checkPatchTime(GlobalTimeResponse response) throws Exception {
|
||||
|
||||
long newMilli = System.currentTimeMillis();
|
||||
long oldMilli = response.getGlobalTimeInMilli();
|
||||
long oldOffset = response.getTimeZoneOffset();
|
||||
int offset = TimeZone.getDefault().getOffset(newMilli);
|
||||
int minutes = (int) TimeUnit.MILLISECONDS.toMinutes(offset);
|
||||
// TimeZoneOffset (8bit / signed): 타임존 offset 15분 단위을 1로 환산, Korea 의 경우 36값(+9:00)
|
||||
int newOffset = minutes / 15;
|
||||
|
||||
long diff = Math.abs(oldMilli - newMilli);
|
||||
|
||||
if (diff > 60000 || oldOffset != newOffset) {
|
||||
aapsLogger.debug(LTag.PUMPCOMM, String.format("checkPatchTime %s %s %s", diff, oldOffset, newOffset));
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Exception("No time set required");
|
||||
|
|
|
@ -14,11 +14,9 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class SetLowReservoirTask extends TaskBase {
|
||||
@Inject IPreferenceManager pm;
|
||||
|
||||
@Inject
|
||||
IPreferenceManager pm;
|
||||
|
||||
private SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT;
|
||||
private final SetLowReservoirLevelAndExpireAlert SET_LOW_RESERVOIR_N_EXPIRE_ALERT;
|
||||
|
||||
@Inject
|
||||
public SetLowReservoirTask() {
|
||||
|
@ -33,7 +31,7 @@ public class SetLowReservoirTask extends TaskBase {
|
|||
hours))
|
||||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "SetLowReservoirTask error"));
|
||||
}
|
||||
|
||||
public synchronized void enqueue() {
|
||||
|
|
|
@ -14,12 +14,9 @@ import io.reactivex.Single;
|
|||
|
||||
import static info.nightscout.androidaps.plugins.pump.eopatch.core.api.StartBonding.OPTION_NUMERIC;
|
||||
|
||||
/**
|
||||
* (주의) API 호출 후 본딩을 위해서 밑단 연결이 끊어짐.
|
||||
*/
|
||||
@Singleton
|
||||
public class StartBondTask extends TaskBase {
|
||||
private StartBonding START_BOND;
|
||||
private final StartBonding START_BOND;
|
||||
|
||||
@Inject
|
||||
public StartBondTask() {
|
||||
|
@ -44,7 +41,7 @@ public class StartBondTask extends TaskBase {
|
|||
.doOnNext(v -> prefSetMacAddress(mac))
|
||||
.doOnError(e -> {
|
||||
prefSetMacAddress("");
|
||||
aapsLogger.error(LTag.PUMPCOMM, e.getMessage());
|
||||
aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartBondTask error");
|
||||
})
|
||||
.firstOrError();
|
||||
}
|
||||
|
|
|
@ -2,11 +2,8 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
|
|||
|
||||
import info.nightscout.androidaps.data.DetailedBolusInfo;
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.BolusExDuration;
|
||||
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BolusStart;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.ComboBolusStart;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.ExtBolusStart;
|
||||
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Singleton;
|
||||
|
@ -16,47 +13,34 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class StartCalcBolusTask extends BolusTask {
|
||||
|
||||
private BolusStart NOW_BOLUS_START;
|
||||
private ExtBolusStart EXT_BOLUS_START;
|
||||
private ComboBolusStart COMBO_BOLUS_START;
|
||||
private final BolusStart NOW_BOLUS_START;
|
||||
|
||||
@Inject
|
||||
public StartCalcBolusTask() {
|
||||
super(TaskFunc.START_CALC_BOLUS);
|
||||
|
||||
NOW_BOLUS_START = new BolusStart();
|
||||
EXT_BOLUS_START = new ExtBolusStart();
|
||||
COMBO_BOLUS_START = new ComboBolusStart();
|
||||
}
|
||||
|
||||
public Single<? 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)
|
||||
.firstOrError()
|
||||
.doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin, (float)detailedBolusInfo.insulin, 0f, BolusExDuration.OFF))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnSuccess(v -> onSuccess((float)detailedBolusInfo.insulin))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartCalcBolusTask error"));
|
||||
}
|
||||
|
||||
private Single<? extends BolusResponse> startBolusImpl(float nowDoseU, float exDoseU,
|
||||
BolusExDuration exDuration) {
|
||||
if (nowDoseU > 0 && exDoseU > 0) {
|
||||
return COMBO_BOLUS_START.start(nowDoseU, exDoseU, exDuration.getMinute());
|
||||
} else if (exDoseU > 0) {
|
||||
return EXT_BOLUS_START.start(exDoseU, exDuration.getMinute());
|
||||
} else {
|
||||
return NOW_BOLUS_START.start(nowDoseU);
|
||||
}
|
||||
private Single<? extends BolusResponse> startBolusImpl(float nowDoseU) {
|
||||
return NOW_BOLUS_START.start(nowDoseU);
|
||||
}
|
||||
|
||||
private void onSuccess(float nowDoseU, float correctionBolus, float exDoseU, BolusExDuration exDuration) {
|
||||
onCalcBolusStarted(nowDoseU, correctionBolus, exDoseU, exDuration);
|
||||
private void onSuccess(float nowDoseU) {
|
||||
onCalcBolusStarted(nowDoseU);
|
||||
enqueue(TaskFunc.UPDATE_CONNECTION);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void preCondition() throws Exception {
|
||||
//checkPatchActivated();
|
||||
checkPatchConnected();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,8 +16,7 @@ import io.reactivex.schedulers.Schedulers;
|
|||
|
||||
@Singleton
|
||||
public class StartNormalBasalTask extends TaskBase {
|
||||
|
||||
private BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
|
||||
private final BasalScheduleSetBig BASAL_SCHEDULE_SET_BIG;
|
||||
|
||||
@Inject
|
||||
PatchStateManager patchStateManager;
|
||||
|
@ -28,23 +27,25 @@ public class StartNormalBasalTask extends TaskBase {
|
|||
BASAL_SCHEDULE_SET_BIG = new BasalScheduleSetBig();
|
||||
}
|
||||
|
||||
public Single<BasalScheduleSetResponse> start(NormalBasal basal, boolean resume) {
|
||||
return isReady().concatMapSingle(v -> startJob(basal, resume)).firstOrError();
|
||||
public Single<BasalScheduleSetResponse> start(NormalBasal basal) {
|
||||
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())
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.observeOn(Schedulers.io())
|
||||
.doOnSuccess(v -> onStartNormalBasalResponse(v, basal, resume))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnSuccess(v -> onStartNormalBasalResponse(v, basal))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartNormalBasalTask error"));
|
||||
}
|
||||
|
||||
private void onStartNormalBasalResponse(BasalScheduleSetResponse response,
|
||||
NormalBasal basal, boolean resume) throws SQLException {
|
||||
private void onStartNormalBasalResponse(BasalScheduleSetResponse response, NormalBasal basal) {
|
||||
|
||||
long timeStamp = response.getTimestamp();
|
||||
patchStateManager.onBasalStarted(basal, timeStamp+1000);
|
||||
|
||||
pm.getNormalBasalManager().setNormalBasal(basal);
|
||||
pm.flushNormalBasalManager();
|
||||
enqueue(TaskFunc.UPDATE_CONNECTION);
|
||||
}
|
||||
|
||||
|
|
|
@ -15,10 +15,9 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class StartQuickBolusTask extends BolusTask {
|
||||
|
||||
private BolusStart NOW_BOLUS_START;
|
||||
private ExtBolusStart EXT_BOLUS_START;
|
||||
private ComboBolusStart COMBO_BOLUS_START;
|
||||
private final BolusStart NOW_BOLUS_START;
|
||||
private final ExtBolusStart EXT_BOLUS_START;
|
||||
private final ComboBolusStart COMBO_BOLUS_START;
|
||||
|
||||
@Inject
|
||||
public StartQuickBolusTask() {
|
||||
|
@ -35,7 +34,7 @@ public class StartQuickBolusTask extends BolusTask {
|
|||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnSuccess(v -> onSuccess(nowDoseU, exDoseU, exDuration))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartQuickBolusTask error"));
|
||||
}
|
||||
|
||||
private Single<? extends BolusResponse> startBolusImpl(float nowDoseU, float exDoseU,
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ble.task;
|
||||
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPreferenceManager;
|
||||
import info.nightscout.shared.logging.LTag;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalScheduleStart;
|
||||
|
||||
|
@ -13,8 +14,8 @@ import io.reactivex.schedulers.Schedulers;
|
|||
|
||||
@Singleton
|
||||
public class StartTempBasalTask extends TaskBase {
|
||||
|
||||
private TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START;
|
||||
@Inject IPreferenceManager pm;
|
||||
private final TempBasalScheduleStart TEMP_BASAL_SCHEDULE_START;
|
||||
|
||||
@Inject
|
||||
public StartTempBasalTask() {
|
||||
|
@ -30,10 +31,12 @@ public class StartTempBasalTask extends TaskBase {
|
|||
.firstOrError()
|
||||
.observeOn(Schedulers.io())
|
||||
.doOnSuccess(v -> onTempBasalStarted(tempBasal))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StartTempBasalTask error"));
|
||||
}
|
||||
|
||||
private void onTempBasalStarted(TempBasal tempBasal) {
|
||||
pm.getTempBasalManager().updateBasalRunning(tempBasal);
|
||||
pm.flushTempBasalManager();
|
||||
enqueue(TaskFunc.UPDATE_CONNECTION);
|
||||
}
|
||||
|
||||
|
|
|
@ -25,17 +25,16 @@ import io.reactivex.subjects.BehaviorSubject;
|
|||
|
||||
@Singleton
|
||||
public class StopBasalTask extends TaskBase {
|
||||
|
||||
@Inject IPreferenceManager pm;
|
||||
@Inject CommandQueue commandQueue;
|
||||
@Inject AAPSLogger aapsLogger;
|
||||
@Inject PumpSync pumpSync;
|
||||
@Inject UserEntryLogger uel;
|
||||
|
||||
private BasalStop BASAL_STOP;
|
||||
private BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
|
||||
private BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
private final BasalStop BASAL_STOP;
|
||||
private final BehaviorSubject<Boolean> bolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> exbolusCheckSubject = BehaviorSubject.create();
|
||||
private final BehaviorSubject<Boolean> basalCheckSubject = BehaviorSubject.create();
|
||||
|
||||
@Inject
|
||||
public StopBasalTask() {
|
||||
|
@ -89,16 +88,15 @@ public class StopBasalTask extends TaskBase {
|
|||
basalCheckSubject.onNext(true);
|
||||
}
|
||||
|
||||
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady) -> {
|
||||
return (bolusReady && exbolusReady && basalReady);
|
||||
})
|
||||
return Observable.zip(getBolusSebject(), getExbolusSebject(), getBasalSebject(), (bolusReady, exbolusReady, basalReady)
|
||||
-> (bolusReady && exbolusReady && basalReady))
|
||||
.filter(ready -> ready)
|
||||
.flatMap(v -> isReady())
|
||||
.concatMapSingle(v -> BASAL_STOP.stop())
|
||||
.doOnNext(this::checkResponse)
|
||||
.firstOrError()
|
||||
.doOnSuccess(this::onBasalStopped)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopBasalTask error"));
|
||||
}
|
||||
|
||||
private void onBasalStopped(BasalStopResponse response) {
|
||||
|
|
|
@ -16,8 +16,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class StopComboBolusTask extends BolusTask {
|
||||
|
||||
private BolusStop BOLUS_STOP;
|
||||
private final BolusStop BOLUS_STOP;
|
||||
|
||||
@Inject
|
||||
public StopComboBolusTask() {
|
||||
|
@ -31,7 +30,7 @@ public class StopComboBolusTask extends BolusTask {
|
|||
.firstOrError()
|
||||
.doOnSuccess(this::checkResponse)
|
||||
.doOnSuccess(this::onComboBolusStopped)
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopComboBolusTask error"));
|
||||
}
|
||||
|
||||
public Single<ComboBolusStopResponse> stopJob() {
|
||||
|
|
|
@ -14,19 +14,17 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class StopExtBolusTask extends BolusTask {
|
||||
|
||||
private BolusStop BOLUS_STOP;
|
||||
private final BolusStop BOLUS_STOP;
|
||||
|
||||
@Inject
|
||||
public StopExtBolusTask() {
|
||||
super(TaskFunc.STOP_EXT_BOLUS);
|
||||
|
||||
BOLUS_STOP = new BolusStop();
|
||||
}
|
||||
|
||||
public Single<BolusStopResponse> stop() {
|
||||
return isReady().concatMapSingle(v -> stopJob()).firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopExtBolusTask error"));
|
||||
}
|
||||
|
||||
public Single<BolusStopResponse> stopJob() {
|
||||
|
|
|
@ -15,13 +15,11 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
|
|||
|
||||
@Singleton
|
||||
public class StopNowBolusTask extends BolusTask {
|
||||
|
||||
private BolusStop BOLUS_STOP;
|
||||
private final BolusStop BOLUS_STOP;
|
||||
|
||||
@Inject
|
||||
public StopNowBolusTask() {
|
||||
super(TaskFunc.STOP_NOW_BOLUS);
|
||||
|
||||
BOLUS_STOP = new BolusStop();
|
||||
}
|
||||
|
||||
|
@ -29,7 +27,7 @@ public class StopNowBolusTask extends BolusTask {
|
|||
return isReady()
|
||||
.observeOn(AndroidSchedulers.mainThread())
|
||||
.concatMapSingle(v -> stopJob()).firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopNowBolusTask error"));
|
||||
}
|
||||
|
||||
public Single<BolusStopResponse> stopJob() {
|
||||
|
|
|
@ -13,8 +13,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class StopTempBasalTask extends TaskBase {
|
||||
|
||||
private TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
|
||||
private final TempBasalScheduleStop TEMP_BASAL_SCHEDULE_STOP;
|
||||
|
||||
@Inject
|
||||
public StopTempBasalTask() {
|
||||
|
@ -25,7 +24,7 @@ public class StopTempBasalTask extends TaskBase {
|
|||
|
||||
public Single<PatchBooleanResponse> stop() {
|
||||
return isReady().concatMapSingle(v -> stopJob()).firstOrError()
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "StopTempBasalTask error"));
|
||||
}
|
||||
|
||||
public Single<PatchBooleanResponse> stopJob() {
|
||||
|
|
|
@ -5,7 +5,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalHistoryGetE
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.BasalHistoryIndexGet;
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.api.TempBasalHistoryGetExBig;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import javax.inject.Inject;
|
||||
|
@ -19,13 +18,11 @@ import static info.nightscout.androidaps.plugins.pump.eopatch.core.define.IPatch
|
|||
|
||||
@Singleton
|
||||
public class SyncBasalHistoryTask extends TaskBase {
|
||||
@Inject IPreferenceManager pm;
|
||||
|
||||
@Inject
|
||||
IPreferenceManager pm;
|
||||
|
||||
private BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET;
|
||||
private BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG;
|
||||
private TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG;
|
||||
private final BasalHistoryIndexGet BASAL_HISTORY_INDEX_GET;
|
||||
private final BasalHistoryGetExBig BASAL_HISTORY_GET_EX_BIG;
|
||||
private final TempBasalHistoryGetExBig TEMP_BASAL_HISTORY_GET_EX_BIG;
|
||||
|
||||
@Inject
|
||||
public SyncBasalHistoryTask() {
|
||||
|
@ -38,19 +35,10 @@ public class SyncBasalHistoryTask extends TaskBase {
|
|||
|
||||
public Single<Integer> sync(int end) {
|
||||
return Single.just(1); // 베이젤 싱크 사용 안함
|
||||
// return isReady()
|
||||
// .concatMapSingle(v -> syncBoth(pm.getPatchConfig().getLastIndex(), end))
|
||||
// .firstOrError()
|
||||
// .doOnSuccess(this::updatePatchLastIndex);
|
||||
}
|
||||
|
||||
public Single<Integer> sync() {
|
||||
return Single.just(1); // 베이젤 싱크 사용 안함
|
||||
// return isReady()
|
||||
// .concatMapSingle(v -> getLastIndex())
|
||||
// .concatMapSingle(end -> syncBoth(pm.getPatchConfig().getLastIndex(), end))
|
||||
// .firstOrError()
|
||||
// .doOnSuccess(this::updatePatchLastIndex);
|
||||
}
|
||||
|
||||
private Single<Integer> getLastIndex() {
|
||||
|
@ -94,7 +82,7 @@ public class SyncBasalHistoryTask extends TaskBase {
|
|||
}
|
||||
|
||||
private int onBasalHistoryResponse(BasalHistoryResponse n, BasalHistoryResponse t,
|
||||
int startRequested, int end) throws SQLException {
|
||||
int startRequested, int end) {
|
||||
|
||||
if (!n.isSuccess() || !t.isSuccess() || n.getSeq() != t.getSeq()) {
|
||||
return -1;
|
||||
|
@ -112,7 +100,7 @@ public class SyncBasalHistoryTask extends TaskBase {
|
|||
return updateInjected(normal, temp, start, end);
|
||||
}
|
||||
|
||||
public synchronized int updateInjected(float[] normal, float[] temp, int start, int end) throws SQLException {
|
||||
public synchronized int updateInjected(float[] normal, float[] temp, int start, int end) {
|
||||
if (pm.getPatchState().isPatchInternalSuspended() && pm.getPatchConfig().isInBasalPausedTime() == false) {
|
||||
return -1;
|
||||
}
|
||||
|
|
|
@ -33,11 +33,9 @@ public class TaskQueue {
|
|||
|
||||
protected synchronized Observable<TaskFunc> isReady(final TaskFunc function) {
|
||||
return Observable.fromCallable(() -> publishTicket(function))
|
||||
.concatMap(v -> {
|
||||
return ticketSubject
|
||||
.takeUntil(it -> it.number > v)
|
||||
.filter(it -> it.number == v);
|
||||
})
|
||||
.concatMap(v -> ticketSubject
|
||||
.takeUntil(it -> it.number > v)
|
||||
.filter(it -> it.number == v))
|
||||
.doOnNext(v -> aapsLogger.debug(LTag.PUMPCOMM, String.format("Task #:%s started func:%s", v.number, v.func.name())))
|
||||
.observeOn(Schedulers.io())
|
||||
.map(it -> it.func)
|
||||
|
@ -86,13 +84,13 @@ public class TaskQueue {
|
|||
|
||||
public synchronized boolean has(TaskFunc func) {
|
||||
if (queue.size() > 1) {
|
||||
Iterator<PatchTask> itor = queue.iterator();
|
||||
Iterator<PatchTask> iterator = queue.iterator();
|
||||
|
||||
/* remove 1st queue */
|
||||
itor.next();
|
||||
iterator.next();
|
||||
|
||||
while (itor.hasNext()) {
|
||||
PatchTask item = itor.next();
|
||||
while (iterator.hasNext()) {
|
||||
PatchTask item = iterator.next();
|
||||
if (item.func == func) {
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -15,9 +15,7 @@ import io.reactivex.Single;
|
|||
|
||||
@Singleton
|
||||
public class UpdateConnectionTask extends TaskBase {
|
||||
|
||||
@Inject
|
||||
PatchStateManager patchStateManager;
|
||||
@Inject PatchStateManager patchStateManager;
|
||||
|
||||
private UpdateConnection UPDATE_CONNECTION;
|
||||
|
||||
|
@ -38,7 +36,7 @@ public class UpdateConnectionTask extends TaskBase {
|
|||
.map(UpdateConnectionResponse::getPatchState)
|
||||
.map(bytes -> PatchState.Companion.create(bytes, System.currentTimeMillis()))
|
||||
.doOnSuccess(state -> onUpdateConnection(state))
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, e.getMessage()));
|
||||
.doOnError(e -> aapsLogger.error(LTag.PUMPCOMM, (e.getMessage() != null) ? e.getMessage() : "UpdateConnectionTask error"));
|
||||
}
|
||||
|
||||
private void onUpdateConnection(PatchState patchState) {
|
||||
|
|
|
@ -1,46 +1,7 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
import com.google.android.gms.common.internal.Preconditions
|
||||
|
||||
enum class AlarmCategory private constructor(val rawValue: Int) {
|
||||
NONE(0),
|
||||
ALARM(1),
|
||||
ALERT(2);
|
||||
|
||||
companion object {
|
||||
|
||||
|
||||
/**
|
||||
* rawValue로 값을 찾기, 못찾으면 null을 리턴
|
||||
*/
|
||||
fun ofRaw(rawValue: Int?): AlarmCategory? {
|
||||
if (rawValue == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
for (t in AlarmCategory.values()) {
|
||||
if (t.rawValue == rawValue) {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴
|
||||
*/
|
||||
fun ofRaw(rawValue: Int?, defaultValue: AlarmCategory): AlarmCategory {
|
||||
Preconditions.checkNotNull(defaultValue)
|
||||
if (rawValue == null) {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
for (t in AlarmCategory.values()) {
|
||||
if (t.rawValue == rawValue) {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
enum class AlarmCategory{
|
||||
NONE,
|
||||
ALARM,
|
||||
ALERT;
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
|
@ -10,21 +10,12 @@ enum class BasalStatus constructor(val rawValue: Int) {
|
|||
val isStarted: Boolean
|
||||
get() = this == STARTED
|
||||
|
||||
val isPaused: Boolean
|
||||
get() = this == PAUSED
|
||||
|
||||
val isSuspended: Boolean
|
||||
get() = this == SUSPENDED
|
||||
|
||||
val isStopped: Boolean
|
||||
get() = this == STOPPED
|
||||
|
||||
val isSelected: Boolean
|
||||
get() = this == SELECTED
|
||||
|
||||
val isSelectedGroup: Boolean
|
||||
get() = isStarted || isPaused || isSuspended || isSelected
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun ofRaw(rawValue: Int?): BasalStatus {
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,10 +1,5 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
import android.content.Context
|
||||
import androidx.collection.SparseArrayCompat
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.CommonUtils
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.R
|
||||
import java.util.*
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
enum class BolusExDuration constructor(val index: Int, val minute: Int, val hour: Float) {
|
||||
|
@ -26,34 +21,14 @@ enum class BolusExDuration constructor(val index: Int, val minute: Int, val hour
|
|||
MINUTE_450(15, 450, 7.5f),
|
||||
MINUTE_480(16, 480, 8.0f);
|
||||
|
||||
val isOff: Boolean
|
||||
get() = this == OFF
|
||||
|
||||
val isNotOff: Boolean
|
||||
get() = this != OFF
|
||||
|
||||
fun milli(): Long {
|
||||
return TimeUnit.MINUTES.toMillis(this.minute.toLong())
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun getItemFromIndex(index: Int): BolusExDuration {
|
||||
var reverseIndices = SparseArrayCompat<BolusExDuration>()
|
||||
for (duration in values()) {
|
||||
reverseIndices.put(duration.index, duration)
|
||||
}
|
||||
val result = reverseIndices.get(index)
|
||||
return result ?: OFF
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun ofRaw(rawValue: Int): BolusExDuration {
|
||||
if (rawValue == null) {
|
||||
return OFF
|
||||
}
|
||||
|
||||
for (t in BolusExDuration.values()) {
|
||||
for (t in values()) {
|
||||
if (t.minute == rawValue) {
|
||||
return t
|
||||
}
|
||||
|
|
|
@ -1,20 +1,14 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
|
||||
enum class DeactivationStatus constructor(val rawValue: Int) {
|
||||
DEACTIVATION_FAILED(0),
|
||||
NORMAL_DEACTIVATED(1),
|
||||
FORCE_DEACTIVATED(2);
|
||||
enum class DeactivationStatus {
|
||||
DEACTIVATION_FAILED,
|
||||
NORMAL_DEACTIVATED,
|
||||
FORCE_DEACTIVATED;
|
||||
|
||||
val isDeactivated: Boolean
|
||||
get() = this == NORMAL_DEACTIVATED || this == FORCE_DEACTIVATED
|
||||
|
||||
val isNormalSuccess: Boolean
|
||||
get() = this == NORMAL_DEACTIVATED
|
||||
|
||||
val isNormalFailed: Boolean
|
||||
get() = this == DEACTIVATION_FAILED || this == FORCE_DEACTIVATED
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun of(isSuccess: Boolean, forced: Boolean): DeactivationStatus {
|
||||
|
|
|
@ -1,5 +0,0 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
enum class Dummy {
|
||||
INSTANCE
|
||||
}
|
|
@ -1,8 +1,8 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
enum class EventType {
|
||||
ACTIVTION_CLICKED,
|
||||
DEACTIVTION_CLICKED,
|
||||
ACTIVATION_CLICKED,
|
||||
DEACTIVATION_CLICKED,
|
||||
SUSPEND_CLICKED,
|
||||
RESUME_CLICKED,
|
||||
INVALID_BASAL_RATE,
|
||||
|
@ -12,14 +12,9 @@ enum class EventType {
|
|||
SHOW_PATCH_COMM_ERROR_DIALOG,
|
||||
SHOW_BONDED_DIALOG,
|
||||
SHOW_CHANGE_PATCH_DIALOG,
|
||||
SHOW_PROGRESS_DIALOG,
|
||||
DISMISS_PROGRESS_DIALOG,
|
||||
FINISH_ACTIVITY,
|
||||
SHOW_DISCARD_DIALOG,
|
||||
PAUSE_BASAL_FAILED,
|
||||
RESUME_BASAL_FAILED,
|
||||
CALCULATED_BOLUS_CLICKED,
|
||||
EXTENDED_BOLUS_SETTINGS_CLICKED,
|
||||
SAVE_CLICKED
|
||||
RESUME_BASAL_FAILED
|
||||
;
|
||||
}
|
||||
|
|
|
@ -1,9 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
import android.content.Context
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.R
|
||||
|
||||
enum class PatchExpireAlertTime private constructor(val index: Int, val hour: Int) {
|
||||
enum class PatchExpireAlertTime constructor(val index: Int, val hour: Int) {
|
||||
HOUR_1(0, 1),
|
||||
HOUR_2(1, 2),
|
||||
HOUR_3(2, 3),
|
||||
|
@ -28,25 +25,4 @@ enum class PatchExpireAlertTime private constructor(val index: Int, val hour: In
|
|||
HOUR_22(21, 22),
|
||||
HOUR_23(22, 23),
|
||||
HOUR_24(23, 24);
|
||||
|
||||
companion object {
|
||||
|
||||
fun atIndex(index: Int): PatchExpireAlertTime {
|
||||
for (i in values()) {
|
||||
if (i.index == index) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return HOUR_1
|
||||
}
|
||||
|
||||
fun atHour(hour: Int): PatchExpireAlertTime {
|
||||
for (i in values()) {
|
||||
if (i.hour == hour) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return HOUR_1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
enum class PatchLifecycle private constructor(val rawValue: Int) {
|
||||
enum class PatchLifecycle constructor(val rawValue: Int) {
|
||||
SHUTDOWN(1),
|
||||
BONDED(2),
|
||||
SAFETY_CHECK(3),
|
||||
|
@ -16,15 +16,4 @@ enum class PatchLifecycle private constructor(val rawValue: Int) {
|
|||
val isActivated: Boolean
|
||||
get() = this == ACTIVATED
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
fun ofRaw(rawValue: Int): PatchLifecycle {
|
||||
for (type in values()) {
|
||||
if (type.rawValue == rawValue) {
|
||||
return type
|
||||
}
|
||||
}
|
||||
return SHUTDOWN
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,9 +21,6 @@ enum class PatchStep {
|
|||
BACK_TO_HOME,
|
||||
FINISH;
|
||||
|
||||
val isConnectNew: Boolean
|
||||
get() = this == CONNECT_NEW
|
||||
|
||||
val isSafeDeactivation: Boolean
|
||||
get() = this == SAFE_DEACTIVATION
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.R
|
|||
|
||||
class SettingKeys {
|
||||
companion object{
|
||||
val LOW_RESERVIOR_REMINDERS: Int = R.string.key_eopatch_low_reservior_reminders
|
||||
val LOW_RESERVOIR_REMINDERS: Int = R.string.key_eopatch_low_reservoir_reminders
|
||||
val EXPIRATION_REMINDERS: Int = R.string.key_eopatch_expiration_reminders
|
||||
val BUZZER_REMINDERS: Int = R.string.key_eopatch_patch_buzzer_reminders
|
||||
|
||||
|
|
|
@ -1,52 +1,8 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.code
|
||||
|
||||
import com.google.android.gms.common.internal.Preconditions
|
||||
|
||||
enum class UnitOrPercent private constructor(val rawValue: Int, val symbol: String) {
|
||||
P(0, "%"),
|
||||
U(1, "U");
|
||||
|
||||
enum class UnitOrPercent {
|
||||
P,
|
||||
U;
|
||||
|
||||
fun isPercentage() = this == P
|
||||
fun isU() = this == U
|
||||
|
||||
companion object {
|
||||
|
||||
val U_PER_HOUR = "U/hr"
|
||||
val U_PER_DAY = "U/day"
|
||||
|
||||
|
||||
/**
|
||||
* rawValue로 값을 찾기, 못찾으면 null을 리턴
|
||||
*/
|
||||
fun ofRaw(rawValue: Int?): UnitOrPercent? {
|
||||
if (rawValue == null) {
|
||||
return null
|
||||
}
|
||||
|
||||
for (t in UnitOrPercent.values()) {
|
||||
if (t.rawValue == rawValue) {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* rawValue로 값을 찾기, 못찾으면 defaultValue을 리턴
|
||||
*/
|
||||
fun ofRaw(rawValue: Int?, defaultValue: UnitOrPercent): UnitOrPercent {
|
||||
Preconditions.checkNotNull(defaultValue)
|
||||
if (rawValue == null) {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
for (t in UnitOrPercent.values()) {
|
||||
if (t.rawValue == rawValue) {
|
||||
return t
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,11 +6,6 @@ import javax.inject.Scope
|
|||
@Qualifier
|
||||
annotation class EopatchPluginQualifier
|
||||
|
||||
@MustBeDocumented
|
||||
@Scope
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
annotation class ActivityScope
|
||||
|
||||
@MustBeDocumented
|
||||
@Scope
|
||||
@Retention(AnnotationRetention.RUNTIME)
|
||||
|
|
|
@ -39,7 +39,6 @@ abstract class EopatchModule {
|
|||
|
||||
}
|
||||
|
||||
|
||||
@Binds
|
||||
@Singleton
|
||||
abstract fun bindPatchManager(patchManager: PatchManager): IPatchManager
|
||||
|
|
|
@ -1,17 +1,11 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.dagger
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import dagger.Binds
|
||||
import dagger.Module
|
||||
import dagger.Provides
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ble.*
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.Alarms
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.NormalBasalManager
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchConfig
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.TempBasalManager
|
||||
import info.nightscout.shared.sharedPreferences.SP
|
||||
import javax.inject.Singleton
|
||||
|
||||
@Module
|
||||
|
@ -24,13 +18,13 @@ class EopatchPrefModule {
|
|||
|
||||
@Provides
|
||||
@Singleton
|
||||
internal fun provideNormalBasalManager(sp: SP): NormalBasalManager {
|
||||
internal fun provideNormalBasalManager(): NormalBasalManager {
|
||||
return NormalBasalManager()
|
||||
}
|
||||
|
||||
@Provides
|
||||
@Singleton
|
||||
internal fun provideTempBasalManager(sp: SP): TempBasalManager {
|
||||
internal fun provideTempBasalManager(): TempBasalManager {
|
||||
return TempBasalManager()
|
||||
}
|
||||
|
||||
|
|
|
@ -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 EventDialog(val dialog: DialogFragment, val show: Boolean) : Event()
|
||||
class EventProgressDialog(val show: Boolean, @StringRes val resId: Int = 0) : Event()
|
||||
class EventPatchActivationNotComplete() : Event()
|
||||
class EventPatchActivationNotComplete : Event()
|
|
@ -1,13 +1,9 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.extension
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Parcelable
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.fragment.app.Fragment
|
||||
import androidx.fragment.app.FragmentManager
|
||||
import androidx.fragment.app.FragmentTransaction
|
||||
import java.io.Serializable
|
||||
|
||||
fun AppCompatActivity.replaceFragmentInActivity(fragment: Fragment, frameId: Int, addToBackStack: Boolean = false) {
|
||||
supportFragmentManager.transact {
|
||||
|
@ -20,43 +16,4 @@ private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Un
|
|||
beginTransaction().apply {
|
||||
action()
|
||||
}.commit()
|
||||
}
|
||||
|
||||
fun Intent.fillExtras(params: Array<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
|
||||
}
|
||||
}
|
|
@ -1,15 +1,17 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.extension
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
fun Float.nearlyEqual(b: Float, epsilon: Float): Boolean {
|
||||
val absA = Math.abs(this)
|
||||
val absB = Math.abs(b)
|
||||
val diff = Math.abs(this - b)
|
||||
val absA = abs(this)
|
||||
val absB = abs(b)
|
||||
val diff = abs(this - b)
|
||||
return if (this == b) {
|
||||
true
|
||||
} else if (this == 0f || b == 0f || absA + absB < java.lang.Float.MIN_NORMAL) {
|
||||
diff < epsilon * java.lang.Float.MIN_NORMAL
|
||||
} else {
|
||||
diff / Math.min(absA + absB, Float.MAX_VALUE) < epsilon
|
||||
diff / (absA + absB).coerceAtMost(Float.MAX_VALUE) < epsilon
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -6,29 +6,6 @@ import java.util.concurrent.TimeUnit
|
|||
internal val Long.date: Date
|
||||
get() = Calendar.getInstance().also { it.timeInMillis = this }.time
|
||||
|
||||
fun Long.getDiffTime(isRelative: Boolean = false): Triple<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 {
|
||||
val inputTimeMillis = this
|
||||
val currentTimeMillis = System.currentTimeMillis()
|
||||
|
@ -36,7 +13,3 @@ fun Long.getDiffDays(isRelative: Boolean = false): Long {
|
|||
|
||||
return TimeUnit.MILLISECONDS.toDays(diffTimeMillis)
|
||||
}
|
||||
|
||||
fun Long.getSeconds() : Long {
|
||||
return (this/1000)*1000
|
||||
}
|
||||
|
|
|
@ -7,8 +7,6 @@ import io.reactivex.android.schedulers.AndroidSchedulers
|
|||
import io.reactivex.disposables.Disposable
|
||||
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, {
|
||||
aapsLogger.error(LTag.PUMP, "onError", it)
|
||||
})
|
||||
|
|
|
@ -20,29 +20,3 @@ fun String.fromHtml(): CharSequence = Html.fromHtml(this, Html.FROM_HTML_MODE_CO
|
|||
fun String.isEmpty(): Boolean{
|
||||
return this.length == 0
|
||||
}
|
||||
|
||||
fun String.getSeparatorForLog(): String {
|
||||
return StringBuilder().let {
|
||||
for (i in 0 until length) {
|
||||
it.append("=")
|
||||
}
|
||||
it.toString()
|
||||
}
|
||||
}
|
||||
|
||||
fun String.convertUtcToLocalDate(): Date {
|
||||
val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
|
||||
val convertDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
|
||||
val timeZone = TimeZone.getDefault()
|
||||
|
||||
var parseDate = format.parse(this)
|
||||
|
||||
val convertedDate = convertDateFormat.format(parseDate)
|
||||
parseDate = convertDateFormat.parse(convertedDate)
|
||||
|
||||
val locTime = convertDateFormat.format(parseDate.time + timeZone.getOffset(parseDate.time)).replace("+0000", "")
|
||||
|
||||
val retDate = convertDateFormat.parse(locTime)
|
||||
|
||||
return retDate
|
||||
}
|
|
@ -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 ""
|
||||
})
|
||||
}
|
|
@ -1,8 +1,7 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.app.AlertDialog
|
||||
import android.app.ProgressDialog
|
||||
import android.os.Bundle
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import info.nightscout.androidaps.activities.DialogAppCompatActivity
|
||||
import info.nightscout.androidaps.core.R
|
||||
import info.nightscout.androidaps.plugins.bus.RxBus
|
||||
|
@ -10,6 +9,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.alarm.AlarmCode
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventDialog
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.event.EventProgressDialog
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.AlarmDialog
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.ProgressDialogHelper
|
||||
import info.nightscout.shared.sharedPreferences.SP
|
||||
import io.reactivex.android.schedulers.AndroidSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -20,7 +20,7 @@ class AlarmHelperActivity : DialogAppCompatActivity() {
|
|||
@Inject lateinit var rxBus: RxBus
|
||||
|
||||
private var disposable: CompositeDisposable = CompositeDisposable()
|
||||
private var mProgressDialog: ProgressDialog? = null
|
||||
private var mProgressDialog: AlertDialog? = null
|
||||
|
||||
@Override
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
|
@ -64,10 +64,8 @@ class AlarmHelperActivity : DialogAppCompatActivity() {
|
|||
|
||||
private fun showProgressDialog(resId: Int){
|
||||
if (mProgressDialog == null && resId != 0) {
|
||||
mProgressDialog = ProgressDialog(this).apply {
|
||||
setMessage(getString(resId))
|
||||
mProgressDialog = ProgressDialogHelper.get(this, getString(resId)).apply {
|
||||
setCancelable(false)
|
||||
setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal)
|
||||
}
|
||||
mProgressDialog?.show()
|
||||
}
|
||||
|
|
|
@ -18,8 +18,4 @@ class DialogHelperActivity : DialogAppCompatActivity() {
|
|||
dialog.message = intent.getStringExtra("message")?:""
|
||||
dialog.show(supportFragmentManager, "Dialog")
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
|
@ -1,23 +1,17 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.annotation.LayoutRes
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.appcompat.app.AppCompatDelegate
|
||||
import androidx.databinding.DataBindingUtil
|
||||
import androidx.databinding.ViewDataBinding
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
|
||||
import info.nightscout.androidaps.core.R
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.EoPatchRxBus
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.dagger.EopatchPluginQualifier
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.fillExtras
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.subscribeDefault
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.ActivityResultEvent
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
import io.reactivex.disposables.Disposable
|
||||
|
@ -35,6 +29,8 @@ abstract class EoBaseActivity<B : ViewDataBinding> : NoSplashAppCompatActivity()
|
|||
|
||||
private val compositeDisposable = CompositeDisposable()
|
||||
|
||||
protected lateinit var getResult: ActivityResultLauncher<Intent>
|
||||
|
||||
@LayoutRes
|
||||
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) {
|
||||
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)
|
||||
}
|
|
@ -1,7 +1,6 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
|
@ -74,13 +73,6 @@ abstract class EoBaseFragment<B : ViewDataBinding> : DaggerFragment(), EoBaseNav
|
|||
override fun finish(finishAffinity: Boolean) {
|
||||
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)
|
||||
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.annotation.StringRes
|
||||
|
||||
interface EoBaseNavigator {
|
||||
|
@ -13,8 +10,4 @@ interface EoBaseNavigator {
|
|||
fun back()
|
||||
|
||||
fun finish(finishAffinity: Boolean = false)
|
||||
|
||||
fun startActivityForResult(action: Context.() -> Intent, requestCode: Int, vararg params: Pair<String, Any?>)
|
||||
|
||||
fun checkCommunication(onSuccess: () -> Unit, onCancel: (() -> Unit)? = null, onDiscard: (() -> Unit)? = null, goHomeAfterDiscard: Boolean = true)
|
||||
}
|
|
@ -1,14 +1,13 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.app.Dialog
|
||||
import android.app.ProgressDialog
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.media.MediaPlayer
|
||||
import android.media.RingtoneManager
|
||||
import android.os.Bundle
|
||||
import android.view.MotionEvent
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.R
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchLifecycle
|
||||
|
@ -17,6 +16,7 @@ import info.nightscout.androidaps.plugins.pump.eopatch.code.EventType
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.databinding.ActivityEopatchBinding
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.replaceFragmentInActivity
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.takeOne
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs.ProgressDialogHelper
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchViewModel
|
||||
import info.nightscout.androidaps.utils.alertDialogs.AlertDialogHelper
|
||||
|
||||
|
@ -24,7 +24,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
|
||||
private var mediaPlayer: MediaPlayer? = null
|
||||
private var mPatchCommCheckDialog: Dialog? = null
|
||||
private var mProgressDialog: ProgressDialog? = null
|
||||
private var mProgressDialog: AlertDialog? = null
|
||||
|
||||
override fun getLayoutId(): Int = R.layout.activity_eopatch
|
||||
|
||||
|
@ -44,59 +44,65 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
viewModel?.apply {
|
||||
processIntent(intent)
|
||||
|
||||
patchStep.observe(this@EopatchActivity, {
|
||||
patchStep.observe(this@EopatchActivity) {
|
||||
when (it) {
|
||||
PatchStep.SAFE_DEACTIVATION -> {
|
||||
if(isActivated.value?:false){
|
||||
PatchStep.SAFE_DEACTIVATION -> {
|
||||
if (isActivated.value == true) {
|
||||
setupViewFragment(EopatchSafeDeactivationFragment.newInstance())
|
||||
}else{
|
||||
} else {
|
||||
this@EopatchActivity.finish()
|
||||
}
|
||||
}
|
||||
|
||||
PatchStep.MANUALLY_TURNING_OFF_ALARM -> setupViewFragment(EopatchTurningOffAlarmFragment.newInstance())
|
||||
PatchStep.DISCARDED_FOR_CHANGE,
|
||||
PatchStep.DISCARDED_FROM_ALARM,
|
||||
PatchStep.DISCARDED -> setupViewFragment(EopatchRemoveFragment.newInstance())
|
||||
PatchStep.WAKE_UP -> setupViewFragment(EopatchWakeUpFragment.newInstance())
|
||||
PatchStep.CONNECT_NEW -> setupViewFragment(EopatchConnectNewFragment.newInstance())
|
||||
PatchStep.REMOVE_NEEDLE_CAP -> setupViewFragment(EopatchRemoveNeedleCapFragment.newInstance())
|
||||
PatchStep.REMOVE_PROTECTION_TAPE -> setupViewFragment(EopatchRemoveProtectionTapeFragment.newInstance())
|
||||
PatchStep.SAFETY_CHECK -> setupViewFragment(EopatchSafetyCheckFragment.newInstance())
|
||||
PatchStep.DISCARDED -> setupViewFragment(EopatchRemoveFragment.newInstance())
|
||||
PatchStep.WAKE_UP -> setupViewFragment(EopatchWakeUpFragment.newInstance())
|
||||
PatchStep.CONNECT_NEW -> setupViewFragment(EopatchConnectNewFragment.newInstance())
|
||||
PatchStep.REMOVE_NEEDLE_CAP -> setupViewFragment(EopatchRemoveNeedleCapFragment.newInstance())
|
||||
PatchStep.REMOVE_PROTECTION_TAPE -> setupViewFragment(EopatchRemoveProtectionTapeFragment.newInstance())
|
||||
PatchStep.SAFETY_CHECK -> setupViewFragment(EopatchSafetyCheckFragment.newInstance())
|
||||
PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR,
|
||||
PatchStep.ROTATE_KNOB -> setupViewFragment(EopatchRotateKnobFragment.newInstance())
|
||||
PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance())
|
||||
PatchStep.ROTATE_KNOB -> setupViewFragment(EopatchRotateKnobFragment.newInstance())
|
||||
PatchStep.BASAL_SCHEDULE -> setupViewFragment(EopatchBasalScheduleFragment.newInstance())
|
||||
// PatchStep.SETTING_REMINDER_TIME -> setupViewFragment(PatchExpirationReminderSettingFragment.newInstance())
|
||||
PatchStep.CHECK_CONNECTION -> {
|
||||
checkCommunication({
|
||||
setResult(RESULT_OK)
|
||||
this@EopatchActivity.finish()
|
||||
}, {
|
||||
setResult(RESULT_CANCELED)
|
||||
this@EopatchActivity.finish()
|
||||
}, {
|
||||
setResult(RESULT_DISCARDED)
|
||||
PatchStep.CHECK_CONNECTION -> {
|
||||
checkCommunication(
|
||||
{
|
||||
setResult(RESULT_OK)
|
||||
this@EopatchActivity.finish()
|
||||
}, {
|
||||
setResult(RESULT_CANCELED)
|
||||
this@EopatchActivity.finish()
|
||||
}, {
|
||||
setResult(RESULT_DISCARDED)
|
||||
|
||||
if (intent.getBooleanExtra(EXTRA_GO_HOME, true)) {
|
||||
backToHome(false)
|
||||
} else {
|
||||
this@EopatchActivity.finish()
|
||||
}
|
||||
}, doIntercept = true)
|
||||
if (intent.getBooleanExtra(EXTRA_GO_HOME, true)) {
|
||||
backToHome(false)
|
||||
} else {
|
||||
this@EopatchActivity.finish()
|
||||
}
|
||||
})
|
||||
}
|
||||
PatchStep.COMPLETE -> backToHome(true)
|
||||
PatchStep.FINISH -> {
|
||||
|
||||
PatchStep.COMPLETE -> backToHome(true)
|
||||
|
||||
PatchStep.FINISH -> {
|
||||
if (!intent.getBooleanExtra(EXTRA_START_FROM_MENU, false)
|
||||
|| intent.getBooleanExtra(EXTRA_GO_HOME, true)) {
|
||||
|| intent.getBooleanExtra(EXTRA_GO_HOME, true)
|
||||
) {
|
||||
backToHome(false)
|
||||
} else {
|
||||
this@EopatchActivity.finish()
|
||||
}
|
||||
}
|
||||
PatchStep.BACK_TO_HOME -> backToHome(false)
|
||||
PatchStep.CANCEL -> this@EopatchActivity.finish()
|
||||
else -> Unit
|
||||
|
||||
PatchStep.BACK_TO_HOME -> backToHome(false)
|
||||
PatchStep.CANCEL -> this@EopatchActivity.finish()
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -129,14 +135,12 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
}
|
||||
}
|
||||
|
||||
UIEventTypeHandler.observe(this@EopatchActivity, Observer { evt ->
|
||||
eventHandler.observe(this@EopatchActivity) { evt ->
|
||||
when (evt.peekContent()) {
|
||||
EventType.SHOW_PATCH_COMM_DIALOG -> {
|
||||
if (mProgressDialog == null) {
|
||||
mProgressDialog = ProgressDialog(this@EopatchActivity).apply {
|
||||
setMessage(getString(evt.value as Int))
|
||||
mProgressDialog = ProgressDialogHelper.get(this@EopatchActivity, getString(evt.value as Int)).apply {
|
||||
setCancelable(false)
|
||||
setProgressStyle(android.R.style.Widget_ProgressBar_Horizontal)
|
||||
}
|
||||
mProgressDialog?.show()
|
||||
}
|
||||
|
@ -149,33 +153,33 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
|
||||
EventType.SHOW_PATCH_COMM_ERROR_DIALOG -> {
|
||||
dismissRetryDialog()
|
||||
if (patchStep.value?.isSafeDeactivation?:false || connectionTryCnt >= 2) {
|
||||
val cancelLabel = commCheckCancelLabel.value?:getString(R.string.cancel)
|
||||
if (patchStep.value?.isSafeDeactivation == true || connectionTryCnt >= 2) {
|
||||
val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel)
|
||||
val message = "${getString(R.string.patch_comm_error_during_discard_desc_2)}\n${getString(R.string.patch_communication_check_helper_2)}"
|
||||
mPatchCommCheckDialog = AlertDialogHelper.Builder(this@EopatchActivity)
|
||||
.setTitle(R.string.patch_communication_failed)
|
||||
.setMessage(message)
|
||||
.setCancelable(false)
|
||||
.setPositiveButton(R.string.discard, { dialog, which ->
|
||||
.setPositiveButton(R.string.discard) { _, _ ->
|
||||
discardPatch()
|
||||
})
|
||||
.setNegativeButton(cancelLabel, { dialog, which ->
|
||||
}
|
||||
.setNegativeButton(cancelLabel) { _, _ ->
|
||||
cancelPatchCommCheck()
|
||||
})
|
||||
}
|
||||
.show()
|
||||
}else{
|
||||
val cancelLabel = commCheckCancelLabel.value?:getString(R.string.cancel)
|
||||
} else {
|
||||
val cancelLabel = commCheckCancelLabel.value ?: getString(R.string.cancel)
|
||||
val message = "${getString(R.string.patch_communication_check_helper_1)}\n${getString(R.string.patch_communication_check_helper_2)}"
|
||||
mPatchCommCheckDialog = AlertDialogHelper.Builder(this@EopatchActivity)
|
||||
.setTitle(R.string.patch_communication_failed)
|
||||
.setMessage(message)
|
||||
.setCancelable(false)
|
||||
.setPositiveButton(R.string.retry, { dialog, which ->
|
||||
.setPositiveButton(R.string.retry) { _, _ ->
|
||||
retryCheckCommunication()
|
||||
})
|
||||
.setNegativeButton(cancelLabel, { dialog, which ->
|
||||
}
|
||||
.setNegativeButton(cancelLabel) { _, _ ->
|
||||
cancelPatchCommCheck()
|
||||
})
|
||||
}
|
||||
.show()
|
||||
}
|
||||
}
|
||||
|
@ -185,31 +189,34 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
AlertDialogHelper.Builder(this@EopatchActivity)
|
||||
.setTitle(R.string.patch_communication_succeed)
|
||||
.setMessage(R.string.patch_communication_succeed_message)
|
||||
.setPositiveButton(R.string.confirm, { dialog, which ->
|
||||
.setPositiveButton(R.string.confirm) { _, _ ->
|
||||
dismissPatchCommCheckDialogInternal(true)
|
||||
}).show()
|
||||
}.show()
|
||||
}
|
||||
|
||||
EventType.SHOW_CHANGE_PATCH_DIALOG -> {
|
||||
AlertDialogHelper.Builder(this@EopatchActivity).apply {
|
||||
setTitle(R.string.string_discard_patch)
|
||||
setMessage(when {
|
||||
patchState.isBolusActive && patchState.isTempBasalActive -> {
|
||||
R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc
|
||||
}
|
||||
patchState.isBolusActive -> R.string.patch_change_confirm_bolus_is_active_desc
|
||||
patchState.isTempBasalActive -> R.string.patch_change_confirm_temp_basal_is_active_desc
|
||||
else -> R.string.patch_change_confirm_desc
|
||||
})
|
||||
setPositiveButton(R.string.string_discard_patch, { dialog, which ->
|
||||
deactivatePatch()
|
||||
})
|
||||
setNegativeButton(R.string.cancel, { dialog, which ->
|
||||
setMessage(
|
||||
when {
|
||||
patchState.isBolusActive && patchState.isTempBasalActive -> {
|
||||
R.string.patch_change_confirm_bolus_and_temp_basal_are_active_desc
|
||||
}
|
||||
|
||||
})
|
||||
patchState.isBolusActive -> R.string.patch_change_confirm_bolus_is_active_desc
|
||||
patchState.isTempBasalActive -> R.string.patch_change_confirm_temp_basal_is_active_desc
|
||||
else -> R.string.patch_change_confirm_desc
|
||||
}
|
||||
)
|
||||
setPositiveButton(R.string.string_discard_patch) { _, _ ->
|
||||
deactivatePatch()
|
||||
}
|
||||
setNegativeButton(R.string.cancel) { _, _ ->
|
||||
|
||||
}
|
||||
}.show()
|
||||
}
|
||||
EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish()
|
||||
// EventType.SHOW_BONDED_DIALOG -> this@EopatchActivity.finish()
|
||||
EventType.SHOW_DISCARD_DIALOG -> {
|
||||
AlertDialogHelper.Builder(this@EopatchActivity).apply {
|
||||
setTitle(R.string.string_discard_patch)
|
||||
|
@ -218,7 +225,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
} else {
|
||||
setMessage(R.string.string_are_you_sure_to_discard_current_patch)
|
||||
}
|
||||
setPositiveButton(R.string.discard, { dialog, which ->
|
||||
setPositiveButton(R.string.discard) { _, _ ->
|
||||
deactivate(true) {
|
||||
dismissPatchCommCheckDialogInternal()
|
||||
|
||||
|
@ -228,17 +235,18 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
this@EopatchActivity.finish()
|
||||
}
|
||||
}
|
||||
})
|
||||
setNegativeButton(R.string.cancel, { dialog, which ->
|
||||
}
|
||||
setNegativeButton(R.string.cancel) { _, _ ->
|
||||
dismissProgressDialog()
|
||||
updateIncompletePatchActivationReminder()
|
||||
})
|
||||
}
|
||||
}.show()
|
||||
|
||||
}
|
||||
else -> Unit
|
||||
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -302,9 +310,8 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
const val EXTRA_START_WITH_COMM_CHECK = "EXTRA_START_WITH_COMM_CHECK"
|
||||
const val EXTRA_GO_HOME = "EXTRA_GO_HOME"
|
||||
const val EXTRA_FORCE_DISCARD = "EXTRA_FORCE_DISCARD"
|
||||
@JvmField val PATCH_INITIAL_VOLTAGE_MIN = 2700
|
||||
@JvmField val NORMAL_TEMPERATURE_MIN = 4
|
||||
@JvmField val NORMAL_TEMPERATURE_MAX = 45
|
||||
const val NORMAL_TEMPERATURE_MIN = 4
|
||||
const val NORMAL_TEMPERATURE_MAX = 45
|
||||
|
||||
@JvmStatic
|
||||
@JvmOverloads
|
||||
|
@ -316,11 +323,6 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun createIntentForActivatePatch(context: Context): Intent {
|
||||
return createIntent(context, PatchStep.WAKE_UP, false)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun createIntentForChangePatch(context: Context): Intent {
|
||||
return createIntent(context, PatchStep.SAFE_DEACTIVATION, false)
|
||||
|
@ -335,7 +337,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
}
|
||||
|
||||
@JvmStatic
|
||||
fun createIntentForCanularInsertionError(context: Context): Intent {
|
||||
fun createIntentForCannulaInsertionError(context: Context): Intent {
|
||||
return createIntent(context, PatchStep.ROTATE_KNOB_NEEDLE_INSERTION_ERROR, false)
|
||||
}
|
||||
|
||||
|
@ -383,7 +385,7 @@ class EopatchActivity : EoBaseActivity<ActivityEopatchBinding>() {
|
|||
}
|
||||
}
|
||||
|
||||
fun setupViewFragment(baseFragment: EoBaseFragment<*>) {
|
||||
private fun setupViewFragment(baseFragment: EoBaseFragment<*>) {
|
||||
replaceFragmentInActivity(baseFragment, R.id.framelayout_fragment, false)
|
||||
}
|
||||
}
|
|
@ -23,16 +23,16 @@ class EopatchConnectNewFragment : EoBaseFragment<FragmentEopatchConnectNewBindin
|
|||
binding.apply {
|
||||
viewModel = ViewModelProvider(requireActivity(), viewModelFactory).get(EopatchViewModel::class.java)
|
||||
viewModel?.apply {
|
||||
setupStep.observe(viewLifecycleOwner, {
|
||||
setupStep.observe(viewLifecycleOwner) {
|
||||
when (it) {
|
||||
SCAN_FAILED,
|
||||
BONDING_FAILED -> checkCommunication ({ retryScan() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
GET_PATCH_INFO_FAILED -> checkCommunication ({ getPatchInfo() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
SELF_TEST_FAILED -> checkCommunication ({ selfTest() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show()
|
||||
else -> Unit
|
||||
BONDING_FAILED -> checkCommunication({ retryScan() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
GET_PATCH_INFO_FAILED -> checkCommunication({ getPatchInfo() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
SELF_TEST_FAILED -> checkCommunication({ selfTest() }, { moveStep(PatchStep.WAKE_UP) })
|
||||
ACTIVATION_FAILED -> Toast.makeText(requireContext(), "Activation failed!", Toast.LENGTH_LONG).show()
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
startScan()
|
||||
}
|
||||
|
|
|
@ -1,28 +1,23 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui
|
||||
|
||||
import android.app.AlertDialog
|
||||
import android.app.ProgressDialog
|
||||
import android.content.Context
|
||||
import android.content.DialogInterface
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.Toast
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.annotation.StringRes
|
||||
import androidx.lifecycle.ViewModelProvider
|
||||
import dagger.android.support.DaggerAppCompatActivity
|
||||
import info.nightscout.androidaps.plugins.bus.RxBus
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.R
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.EoPatchRxBus
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.PatchStep
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.code.EventType
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.databinding.FragmentEopatchOverviewBinding
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.fillExtras
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.subscribeDefault
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.extension.takeOne
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchOverviewViewModel
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.ActivityResultEvent
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.shared.logging.AAPSLogger
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -32,8 +27,11 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
@Inject lateinit var rxBus: RxBus
|
||||
@Inject lateinit var aapsSchedulers: AapsSchedulers
|
||||
@Inject lateinit var aapsLogger: AAPSLogger
|
||||
private lateinit var resultLauncherForResume: ActivityResultLauncher<Intent>
|
||||
private lateinit var resultLauncherForPause: ActivityResultLauncher<Intent>
|
||||
|
||||
private var disposable: CompositeDisposable = CompositeDisposable()
|
||||
private var pauseDuration = 0.5f
|
||||
|
||||
override fun getLayoutId(): Int = R.layout.fragment_eopatch_overview
|
||||
|
||||
|
@ -48,21 +46,42 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
binding.apply {
|
||||
viewmodel = ViewModelProvider(this@EopatchOverviewFragment, viewModelFactory).get(EopatchOverviewViewModel::class.java)
|
||||
viewmodel?.apply {
|
||||
UIEventTypeHandler.observe(viewLifecycleOwner, Observer { evt ->
|
||||
when(evt.peekContent()){
|
||||
EventType.ACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentFromMenu(it, PatchStep.WAKE_UP)) }
|
||||
EventType.DEACTIVTION_CLICKED -> requireContext().let { startActivity(EopatchActivity.createIntentForChangePatch(it)) }
|
||||
EventType.SUSPEND_CLICKED -> suspend()
|
||||
eventHandler.observe(viewLifecycleOwner) { evt ->
|
||||
when (evt.peekContent()) {
|
||||
EventType.ACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentFromMenu(this, PatchStep.WAKE_UP)) }
|
||||
EventType.DEACTIVATION_CLICKED -> requireContext().apply { startActivity(EopatchActivity.createIntentForChangePatch(this)) }
|
||||
EventType.SUSPEND_CLICKED -> suspend()
|
||||
EventType.RESUME_CLICKED -> resume()
|
||||
EventType.INVALID_BASAL_RATE -> Toast.makeText(activity, R.string.unsupported_basal_rate, Toast.LENGTH_SHORT).show()
|
||||
EventType.PROFILE_NOT_SET -> Toast.makeText(activity, R.string.no_profile_selected, Toast.LENGTH_SHORT).show()
|
||||
EventType.INVALID_BASAL_RATE -> showToast(R.string.unsupported_basal_rate)
|
||||
EventType.PROFILE_NOT_SET -> showToast(R.string.no_profile_selected)
|
||||
EventType.PAUSE_BASAL_FAILED -> showToast(R.string.string_pause_failed)
|
||||
EventType.RESUME_BASAL_FAILED -> showToast(R.string.string_resume_failed)
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
resultLauncherForResume = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
|
||||
when (it.resultCode) {
|
||||
DaggerAppCompatActivity.RESULT_OK -> resumeBasal()
|
||||
DaggerAppCompatActivity.RESULT_CANCELED -> showToast(R.string.string_resume_failed)
|
||||
}
|
||||
}
|
||||
|
||||
resultLauncherForPause = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
|
||||
when (it.resultCode) {
|
||||
DaggerAppCompatActivity.RESULT_OK -> {
|
||||
pauseBasal(pauseDuration)
|
||||
pauseDuration = 0.5f
|
||||
}
|
||||
DaggerAppCompatActivity.RESULT_CANCELED -> showToast(R.string.string_pause_failed)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun showToast(@StringRes strId: Int){
|
||||
Toast.makeText(requireContext(), strId, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
private fun suspend() {
|
||||
|
@ -73,12 +92,12 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
|
||||
val dialog = builder.setTitle(R.string.string_suspend)
|
||||
.setMessage(msg)
|
||||
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which ->
|
||||
.setPositiveButton(R.string.confirm) { _, _ ->
|
||||
openPauseTimePicker()
|
||||
})
|
||||
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which ->
|
||||
}
|
||||
.setNegativeButton(R.string.cancel) { _, _ ->
|
||||
|
||||
}).create()
|
||||
}.create()
|
||||
dialog.show()
|
||||
}
|
||||
}
|
||||
|
@ -90,18 +109,16 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
val builder = AlertDialog.Builder(it)
|
||||
val dialog = builder.setTitle(R.string.string_resume_insulin_delivery_title)
|
||||
.setMessage(R.string.string_resume_insulin_delivery_message)
|
||||
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which ->
|
||||
if(isPatchConnected) {
|
||||
.setPositiveButton(R.string.confirm) { _, _ ->
|
||||
if (isPatchConnected) {
|
||||
resumeBasal()
|
||||
}else{
|
||||
checkCommunication({
|
||||
resumeBasal()
|
||||
})
|
||||
} else {
|
||||
resultLauncherForResume.launch(EopatchActivity.createIntentForCheckConnection(requireContext(), true))
|
||||
}
|
||||
})
|
||||
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which ->
|
||||
}
|
||||
.setNegativeButton(R.string.cancel) { _, _ ->
|
||||
|
||||
}).create()
|
||||
}.create()
|
||||
dialog.show()
|
||||
}
|
||||
}
|
||||
|
@ -114,21 +131,20 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
val listArr = requireContext().resources.getStringArray(R.array.suspend_duration_array)
|
||||
var select = 0
|
||||
val dialog = builder.setTitle(R.string.string_suspend_time_insulin_delivery_title)
|
||||
.setSingleChoiceItems(listArr, 0, DialogInterface.OnClickListener { dialog, which ->
|
||||
.setSingleChoiceItems(listArr, 0) { _, which ->
|
||||
select = which
|
||||
})
|
||||
.setPositiveButton(R.string.confirm, DialogInterface.OnClickListener { dialog, which ->
|
||||
}
|
||||
.setPositiveButton(R.string.confirm) { _, _ ->
|
||||
if (isPatchConnected) {
|
||||
pauseBasal((select + 1) * 0.5f)
|
||||
} else {
|
||||
checkCommunication({
|
||||
pauseBasal((select + 1) * 0.5f)
|
||||
})
|
||||
pauseDuration = (select + 1) * 0.5f
|
||||
resultLauncherForPause.launch(EopatchActivity.createIntentForCheckConnection(requireContext(), true))
|
||||
}
|
||||
})
|
||||
.setNegativeButton(R.string.cancel, DialogInterface.OnClickListener { dialog, which ->
|
||||
}
|
||||
.setNegativeButton(R.string.cancel) { _, _ ->
|
||||
|
||||
}).create()
|
||||
}.create()
|
||||
dialog.show()
|
||||
}
|
||||
}
|
||||
|
@ -158,26 +174,4 @@ class EopatchOverviewFragment: EoBaseFragment<FragmentEopatchOverviewBinding>()
|
|||
}
|
||||
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()
|
||||
}
|
||||
|
||||
}
|
|
@ -39,14 +39,14 @@ class EopatchRotateKnobFragment : EoBaseFragment<FragmentEopatchRotateKnobBindin
|
|||
textRotateKnobDesc2NeedleInsertionError.visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
setupStep.observe(viewLifecycleOwner, {
|
||||
setupStep.observe(viewLifecycleOwner) {
|
||||
when (it) {
|
||||
EopatchViewModel.SetupStep.NEEDLE_SENSING_FAILED -> {
|
||||
checkCommunication({ startNeedleSensing() })
|
||||
}
|
||||
else -> Unit
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -24,12 +24,12 @@ class EopatchSafetyCheckFragment : EoBaseFragment<FragmentEopatchSafetyCheckBind
|
|||
viewModel?.apply {
|
||||
initPatchStep()
|
||||
|
||||
setupStep.observe(viewLifecycleOwner, {
|
||||
setupStep.observe(viewLifecycleOwner) {
|
||||
when (it) {
|
||||
SAFETY_CHECK_FAILED -> checkCommunication ({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) })
|
||||
else -> Unit
|
||||
SAFETY_CHECK_FAILED -> checkCommunication({ retrySafetyCheck() }, { moveStep(PatchStep.SAFETY_CHECK) })
|
||||
else -> Unit
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
startSafetyCheck()
|
||||
}
|
||||
|
|
|
@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ble.IPatchManager
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.databinding.DialogCommonBinding
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.DialogHelperActivity
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EopatchActivity
|
||||
import io.reactivex.disposables.Disposable
|
||||
import javax.inject.Inject
|
||||
|
||||
class ActivationNotCompleteDialog : DaggerDialogFragment() {
|
||||
|
@ -24,7 +23,6 @@ class ActivationNotCompleteDialog : DaggerDialogFragment() {
|
|||
var title: String = ""
|
||||
|
||||
private var _binding: DialogCommonBinding? = null
|
||||
private var disposable: Disposable? = null
|
||||
private val binding get() = _binding!!
|
||||
|
||||
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
|
||||
|
|
|
@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.pump.eopatch.ui.dialogs
|
|||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.view.*
|
||||
import dagger.android.support.DaggerDialogFragment
|
||||
import info.nightscout.androidaps.core.R
|
||||
|
@ -32,13 +33,13 @@ class AlarmDialog : DaggerDialogFragment() {
|
|||
|
||||
var helperActivity: AlarmHelperActivity? = null
|
||||
var alarmCode: AlarmCode? = null
|
||||
var code: String = ""
|
||||
var code: String? = null
|
||||
var status: String = ""
|
||||
var title: String = ""
|
||||
var sound: Int = 0
|
||||
|
||||
private lateinit var mAlarmProcess: IAlarmProcess
|
||||
private var loopHandler = Handler()
|
||||
private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper)
|
||||
|
||||
private var _binding: DialogAlarmBinding? = null
|
||||
private var disposable: Disposable? = null
|
||||
|
@ -107,7 +108,7 @@ class AlarmDialog : DaggerDialogFragment() {
|
|||
aapsLogger.debug("USER ENTRY: Error dialog mute 5 min button pressed")
|
||||
stopAlarm()
|
||||
isMute = true
|
||||
loopHandler.postDelayed(this::startAlarm, T.mins(5).msecs())
|
||||
handler.postDelayed(this::startAlarm, T.mins(5).msecs())
|
||||
}
|
||||
startAlarm()
|
||||
|
||||
|
@ -150,7 +151,7 @@ class AlarmDialog : DaggerDialogFragment() {
|
|||
|
||||
override fun dismiss() {
|
||||
super.dismissAllowingStateLoss()
|
||||
loopHandler.removeCallbacksAndMessages(null)
|
||||
handler.removeCallbacksAndMessages(null)
|
||||
helperActivity?.finish()
|
||||
}
|
||||
|
||||
|
|
|
@ -28,12 +28,12 @@ class CommonDialog : DaggerDialogFragment() {
|
|||
if(title != 0) setTitle(title)
|
||||
if(message != 0) setMessage(message)
|
||||
setPositiveButton(positiveBtn,
|
||||
positiveListener?:DialogInterface.OnClickListener { dialog, which ->
|
||||
positiveListener?:DialogInterface.OnClickListener { _, _ ->
|
||||
dismiss()
|
||||
})
|
||||
if(negativeBtn != 0) {
|
||||
setNegativeButton(negativeBtn,
|
||||
negativeListener ?: DialogInterface.OnClickListener { dialog, which ->
|
||||
negativeListener ?: DialogInterface.OnClickListener { _, _ ->
|
||||
dismiss()
|
||||
})
|
||||
}
|
||||
|
|
|
@ -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
|
||||
}
|
||||
}
|
||||
}
|
|
@ -4,17 +4,16 @@ import androidx.lifecycle.LifecycleOwner
|
|||
import androidx.lifecycle.MutableLiveData
|
||||
import androidx.lifecycle.Observer
|
||||
import androidx.annotation.MainThread
|
||||
import android.util.Log
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
open class SingleLiveEvent<T> : MutableLiveData<T>() {
|
||||
private val mPending = AtomicBoolean(false)
|
||||
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
|
||||
super.observe(owner, Observer { t ->
|
||||
super.observe(owner) { t ->
|
||||
if (mPending.compareAndSet(true, false)) {
|
||||
observer.onChanged(t)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@MainThread
|
||||
|
|
|
@ -6,10 +6,8 @@ import android.content.Intent
|
|||
import android.content.IntentFilter
|
||||
import androidx.annotation.CheckResult
|
||||
import io.reactivex.android.MainThreadDisposable
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.receiver.RxBroadcastReceiver.BroadcastReceiverObservable
|
||||
import io.reactivex.Observable
|
||||
import io.reactivex.Observer
|
||||
import java.lang.AssertionError
|
||||
|
||||
class RxBroadcastReceiver private constructor() {
|
||||
internal class BroadcastReceiverObservable : Observable<Intent> {
|
||||
|
@ -31,7 +29,7 @@ class RxBroadcastReceiver private constructor() {
|
|||
}
|
||||
|
||||
override fun subscribeActual(observer: Observer<in Intent>) {
|
||||
val listener: Listener = Listener(context, observer)
|
||||
val listener = Listener(context, observer)
|
||||
observer.onSubscribe(listener)
|
||||
context.registerReceiver(listener.receiver, intentFilter)
|
||||
}
|
||||
|
|
|
@ -1,8 +1,5 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel
|
||||
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import androidx.annotation.Keep
|
||||
import androidx.lifecycle.ViewModel
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator
|
||||
import io.reactivex.disposables.CompositeDisposable
|
||||
|
@ -26,10 +23,6 @@ abstract class EoBaseViewModel<N : EoBaseNavigator> : ViewModel() {
|
|||
super.onCleared()
|
||||
}
|
||||
|
||||
fun blockTouchEvent(view: View, motionEvent: MotionEvent): Boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
fun back() = navigator?.back()
|
||||
|
||||
fun finish() = navigator?.finish()
|
||||
|
|
|
@ -21,6 +21,7 @@ import io.reactivex.Observable
|
|||
import io.reactivex.disposables.Disposable
|
||||
import java.util.concurrent.TimeUnit
|
||||
import javax.inject.Inject
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class EopatchOverviewViewModel @Inject constructor(
|
||||
|
@ -31,7 +32,7 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
private val aapsSchedulers: AapsSchedulers
|
||||
) : EoBaseViewModel<EoBaseNavigator>() {
|
||||
private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>()
|
||||
val UIEventTypeHandler : LiveData<UIEvent<EventType>>
|
||||
val eventHandler : LiveData<UIEvent<EventType>>
|
||||
get() = _eventHandler
|
||||
|
||||
private val _patchConfig = SingleLiveEvent<PatchConfig>()
|
||||
|
@ -58,6 +59,10 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
val status : LiveData<String>
|
||||
get() = _status
|
||||
|
||||
private val _pauseBtnStr = SingleLiveEvent<String>()
|
||||
val pauseBtnStr : LiveData<String>
|
||||
get() = _pauseBtnStr
|
||||
|
||||
private val _alarms = SingleLiveEvent<Alarms>()
|
||||
val alarms : LiveData<Alarms>
|
||||
get() = _alarms
|
||||
|
@ -128,18 +133,18 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
|
||||
private fun updatePatchStatus(){
|
||||
if(patchManager.isActivated){
|
||||
var finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis()
|
||||
var remainTimeMillis = Math.max(finishTimeMillis - System.currentTimeMillis(), 0L)
|
||||
val finishTimeMillis = patchConfig.value?.basalPauseFinishTimestamp?:System.currentTimeMillis()
|
||||
val remainTimeMillis = max(finishTimeMillis - System.currentTimeMillis(), 0L)
|
||||
val h = TimeUnit.MILLISECONDS.toHours(remainTimeMillis)
|
||||
val m = TimeUnit.MILLISECONDS.toMinutes(remainTimeMillis - TimeUnit.HOURS.toMillis(h))
|
||||
_status.value = if(patchManager.patchState.isNormalBasalPaused)
|
||||
"${rh.gs(R.string.string_suspended)}\n" +
|
||||
"${rh.gs(R.string.string_temp_basal_remained_hhmm, h.toString(), m.toString())}"
|
||||
"${rh.gs(R.string.string_suspended)}\n${rh.gs(R.string.string_temp_basal_remained_hhmm, h.toString(), m.toString())}"
|
||||
else
|
||||
rh.gs(R.string.string_running)
|
||||
}else{
|
||||
_status.value = ""
|
||||
}
|
||||
_pauseBtnStr.value = if(patchManager.patchState.isNormalBasalPaused) rh.gs(R.string.string_resume) else rh.gs(R.string.string_suspend)
|
||||
}
|
||||
|
||||
private fun updateBasalInfo(){
|
||||
|
@ -166,7 +171,7 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
patchManager.preferenceManager.getNormalBasalManager().setNormalBasal(profile)
|
||||
patchManager.preferenceManager.flushNormalBasalManager()
|
||||
|
||||
_eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED))
|
||||
_eventHandler.postValue(UIEvent(EventType.ACTIVATION_CLICKED))
|
||||
}else if(profile != null && profile.getBasal() < 0.05){
|
||||
_eventHandler.postValue(UIEvent(EventType.INVALID_BASAL_RATE))
|
||||
}else{
|
||||
|
@ -175,7 +180,7 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
}
|
||||
|
||||
fun onClickDeactivation(){
|
||||
_eventHandler.postValue(UIEvent(EventType.DEACTIVTION_CLICKED))
|
||||
_eventHandler.postValue(UIEvent(EventType.DEACTIVATION_CLICKED))
|
||||
}
|
||||
|
||||
fun onClickSuspendOrResume(){
|
||||
|
@ -190,8 +195,8 @@ class EopatchOverviewViewModel @Inject constructor(
|
|||
patchManager.pauseBasal(pauseDurationHour)
|
||||
.subscribeOn(aapsSchedulers.io)
|
||||
.observeOn(aapsSchedulers.main)
|
||||
.subscribe({
|
||||
if (it.isSuccess) {
|
||||
.subscribe({ response ->
|
||||
if (response.isSuccess) {
|
||||
navigator?.toast(R.string.string_suspended_insulin_delivery_message)
|
||||
startPeriodicallyUpdate()
|
||||
} else {
|
||||
|
|
|
@ -25,7 +25,9 @@ import info.nightscout.androidaps.plugins.pump.eopatch.ui.EoBaseNavigator
|
|||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.event.SingleLiveEvent
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.event.UIEvent
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.ui.viewmodel.EopatchViewModel.SetupStep.*
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchConfig
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchLifecycleEvent
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.vo.PatchState
|
||||
import info.nightscout.androidaps.utils.resources.ResourceHelper
|
||||
import info.nightscout.androidaps.utils.rx.AapsSchedulers
|
||||
import info.nightscout.shared.logging.AAPSLogger
|
||||
|
@ -55,24 +57,19 @@ class EopatchViewModel @Inject constructor(
|
|||
var forceDiscard = false
|
||||
var connectionTryCnt = 0
|
||||
|
||||
val patchConfig = patchManager.patchConfig
|
||||
|
||||
val patchState = patchManager.patchState
|
||||
val patchConfig: PatchConfig = patchManager.patchConfig
|
||||
val patchState: PatchState = patchManager.patchState
|
||||
|
||||
private val _isActivated = MutableLiveData(patchConfig.isActivated)
|
||||
|
||||
private val _eventHandler = SingleLiveEvent<UIEvent<EventType>>()
|
||||
val UIEventTypeHandler : LiveData<UIEvent<EventType>>
|
||||
val eventHandler : LiveData<UIEvent<EventType>>
|
||||
get() = _eventHandler
|
||||
|
||||
fun onClickActivation(){
|
||||
_eventHandler.postValue(UIEvent(EventType.ACTIVTION_CLICKED))
|
||||
}
|
||||
|
||||
val patchStep = MutableLiveData<PatchStep>()
|
||||
|
||||
val isActivated = MutableLiveData<Boolean>(patchManager.isActivated)
|
||||
val isBolusActive = patchManager.getPatchState().isBolusActive
|
||||
val isActivated = MutableLiveData(patchManager.isActivated)
|
||||
val isBolusActive = patchManager.patchState.isBolusActive
|
||||
val isConnected = patchManager.patchConnectionState.isConnected
|
||||
|
||||
val patchRemainedInsulin: LiveData<Int>
|
||||
|
@ -86,7 +83,7 @@ class EopatchViewModel @Inject constructor(
|
|||
}, 0)
|
||||
}
|
||||
|
||||
private val _patchExpirationTimestamp = MutableLiveData<Long>(patchManager.patchExpiredTime)
|
||||
private val _patchExpirationTimestamp = MutableLiveData(patchManager.patchExpiredTime)
|
||||
|
||||
val patchRemainedDays: LiveData<Int>
|
||||
get() = Transformations.map(_patchExpirationTimestamp) {
|
||||
|
@ -106,19 +103,11 @@ class EopatchViewModel @Inject constructor(
|
|||
val safetyCheckProgress: LiveData<Int>
|
||||
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)
|
||||
val isCommCheckFailed: LiveData<Boolean>
|
||||
private val isCommCheckFailed: LiveData<Boolean>
|
||||
get() = _isCommCheckFailed
|
||||
|
||||
val isBonded: Boolean
|
||||
private val isBonded: Boolean
|
||||
get() = !patchConfig.lifecycleEvent.isShutdown
|
||||
|
||||
val commCheckCancelLabel: LiveData<String>
|
||||
|
@ -129,15 +118,11 @@ class EopatchViewModel @Inject constructor(
|
|||
}
|
||||
PatchStep.SAFE_DEACTIVATION -> R.string.patch_forced_discard
|
||||
else -> R.string.cancel
|
||||
}) ?: ""
|
||||
})
|
||||
}
|
||||
|
||||
val programEnabledMessage: String
|
||||
// get() = """'기초1' program has been enabled."""
|
||||
get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1") ?: ""
|
||||
|
||||
val patchStepIsSafeDeactivation: Boolean
|
||||
get() = patchStep.value?.isSafeDeactivation ?: false
|
||||
get() = rh.gs(R.string.patch_basal_schedule_desc_1,"기초1")
|
||||
|
||||
private val _isDiscardedWithNotConn = MutableLiveData(false)
|
||||
val isDiscardedWithNotConn: LiveData<Boolean>
|
||||
|
@ -152,8 +137,6 @@ class EopatchViewModel @Inject constructor(
|
|||
private val initPatchStepIsCheckConnection: Boolean
|
||||
get() = mInitPatchStep?.isCheckConnection ?: false
|
||||
|
||||
// private var mProgressDialog: PatchProgressDialog? = null
|
||||
|
||||
private var mCommCheckDisposable: Disposable? = null
|
||||
|
||||
private var mOnCommCheckSuccessListener: (() -> Unit)? = null
|
||||
|
@ -174,8 +157,6 @@ class EopatchViewModel @Inject constructor(
|
|||
|
||||
private val mB012UpdateSubject = PublishSubject.create<Unit>()
|
||||
|
||||
// private var mCurrentTextDialog: TextDialog? = null
|
||||
|
||||
init {
|
||||
mB012UpdateDisposable = mB012UpdateSubject.hide()
|
||||
.throttleFirst(500, TimeUnit.MILLISECONDS)
|
||||
|
@ -222,20 +203,7 @@ class EopatchViewModel @Inject constructor(
|
|||
|
||||
@Synchronized
|
||||
fun checkCommunication(onSuccessListener: () -> Unit, onCancelListener: (() -> Unit)? = null,
|
||||
onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false, doIntercept: Boolean = false) {
|
||||
// mPatchCommCheckDialog?.let {
|
||||
// if (doIntercept) {
|
||||
// mOnCommCheckSuccessListener = onSuccessListener
|
||||
// mOnCommCheckCancelListener = onCancelListener
|
||||
// mOnCommCheckDiscardListener = onDiscardListener
|
||||
//
|
||||
// if (_isCommCheckFailed.value == true) {
|
||||
// retryCheckCommunication()
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
onDiscardListener: (() -> Unit)? = null, doPreCheck: Boolean = false) {
|
||||
if (doPreCheck && patchManager.patchConnectionState.isConnected) {
|
||||
onSuccessListener.invoke()
|
||||
return
|
||||
|
@ -286,7 +254,7 @@ class EopatchViewModel @Inject constructor(
|
|||
}
|
||||
}
|
||||
|
||||
fun showPatchCommCheckDialog(defaultFailedCondition: Boolean = false, @StringRes title: Int = R.string.string_connecting) {
|
||||
private fun showPatchCommCheckDialog(defaultFailedCondition: Boolean = false, @StringRes title: Int = R.string.string_connecting) {
|
||||
_isCommCheckFailed.postValue(defaultFailedCondition)
|
||||
_eventHandler.postValue(UIEvent(EventType.SHOW_PATCH_COMM_DIALOG).apply {
|
||||
value = title
|
||||
|
@ -307,7 +275,7 @@ class EopatchViewModel @Inject constructor(
|
|||
}
|
||||
|
||||
private fun dismissPatchCommCheckDialog() {
|
||||
if (_isCommCheckFailed.value == false) {
|
||||
if (isCommCheckFailed.value == false) {
|
||||
if (isBonded) {
|
||||
_eventHandler.postValue(UIEvent(EventType.SHOW_BONDED_DIALOG))
|
||||
} else {
|
||||
|
@ -554,7 +522,7 @@ class EopatchViewModel @Inject constructor(
|
|||
}
|
||||
}
|
||||
|
||||
fun convertToPatchStep(lifecycle: PatchLifecycle) = when (lifecycle) {
|
||||
private fun convertToPatchStep(lifecycle: PatchLifecycle) = when (lifecycle) {
|
||||
PatchLifecycle.SHUTDOWN -> patchConfig.isDeactivated.takeOne(
|
||||
PatchStep.WAKE_UP, PatchStep.SAFE_DEACTIVATION)
|
||||
PatchLifecycle.BONDED -> PatchStep.CONNECT_NEW
|
||||
|
@ -567,13 +535,6 @@ class EopatchViewModel @Inject constructor(
|
|||
}
|
||||
|
||||
private fun onClear() {
|
||||
// _patchExpirationTime.value = null
|
||||
// _rotateKnobRawRes.value = null
|
||||
// _patchExpirationReminderTime.value = null
|
||||
// _title.value = null
|
||||
// mProgressDialog = null
|
||||
// mPatchCommCheckDialog = null
|
||||
// mCurrentTextDialog = null
|
||||
mOnCommCheckSuccessListener = null
|
||||
mOnCommCheckCancelListener = null
|
||||
mOnCommCheckDiscardListener = null
|
||||
|
@ -691,7 +652,7 @@ class EopatchViewModel @Inject constructor(
|
|||
.doOnSubscribe { updateSetupStep(BONDING_STARTED) }
|
||||
.filter { result -> result }
|
||||
.toSingle() // 실패시 에러 반환.
|
||||
.doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createbonded()) }
|
||||
.doOnSuccess { patchManager.updatePatchLifeCycle(PatchLifecycleEvent.createBonded()) }
|
||||
.doOnError {
|
||||
if (it is TimeoutException) {
|
||||
moveStep(PatchStep.WAKE_UP)
|
||||
|
|
|
@ -30,6 +30,7 @@ class ViewModelFactory @Inject constructor(private val creators: Map<Class<out V
|
|||
throw IllegalArgumentException("unknown model class $modelClass")
|
||||
}
|
||||
try {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return creator.get() as T
|
||||
} catch (e: Exception) {
|
||||
throw IllegalStateException(e)
|
||||
|
|
|
@ -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
|
||||
)
|
|
@ -8,7 +8,7 @@ import io.reactivex.Observable
|
|||
import io.reactivex.subjects.BehaviorSubject
|
||||
import java.util.*
|
||||
|
||||
class Alarms(): IPreference<Alarms> {
|
||||
class Alarms: IPreference<Alarms> {
|
||||
@Transient
|
||||
private val subject: BehaviorSubject<Alarms> = BehaviorSubject.create()
|
||||
|
||||
|
@ -24,7 +24,7 @@ class Alarms(): IPreference<Alarms> {
|
|||
|
||||
var registered = HashMap<AlarmCode, AlarmItem>()
|
||||
|
||||
var occured = HashMap<AlarmCode, AlarmItem>()
|
||||
var occurred = HashMap<AlarmCode, AlarmItem>()
|
||||
|
||||
init {
|
||||
initObject()
|
||||
|
@ -35,52 +35,52 @@ class Alarms(): IPreference<Alarms> {
|
|||
|
||||
fun clear(){
|
||||
registered.clear()
|
||||
occured.clear()
|
||||
occurred.clear()
|
||||
}
|
||||
|
||||
fun update(other: Alarms) {
|
||||
registered = other.registered
|
||||
occured = other.occured
|
||||
occurred = other.occurred
|
||||
}
|
||||
|
||||
fun register(alarmcode: AlarmCode, triggerAfter: Long) {
|
||||
fun register(alarmCode: AlarmCode, triggerAfter: Long) {
|
||||
val item = AlarmItem().apply {
|
||||
alarmCode = alarmcode
|
||||
this.alarmCode = alarmCode
|
||||
createTimestamp = System.currentTimeMillis()
|
||||
triggerTimeMilli = createTimestamp + triggerAfter
|
||||
}
|
||||
if (isRegistered(alarmcode)){
|
||||
registered.remove(alarmcode)
|
||||
if (isRegistered(alarmCode)){
|
||||
registered.remove(alarmCode)
|
||||
}
|
||||
registered.put(alarmcode, item)
|
||||
registered.put(alarmCode, item)
|
||||
|
||||
}
|
||||
|
||||
fun unregister(alarmcode: AlarmCode) {
|
||||
if (isRegistered(alarmcode)){
|
||||
registered.remove(alarmcode)
|
||||
fun unregister(alarmCode: AlarmCode) {
|
||||
if (isRegistered(alarmCode)){
|
||||
registered.remove(alarmCode)
|
||||
}
|
||||
}
|
||||
|
||||
fun occured(alarmcode: AlarmCode) {
|
||||
val item: AlarmItem? = registered.get(alarmcode)
|
||||
if (!isOccuring(alarmcode) && item != null)
|
||||
occured.put(alarmcode, item)
|
||||
if (isRegistered(alarmcode))
|
||||
registered.remove(alarmcode)
|
||||
fun occurred(alarmCode: AlarmCode) {
|
||||
val item: AlarmItem? = registered.get(alarmCode)
|
||||
if (!isOccurring(alarmCode) && item != null)
|
||||
occurred.put(alarmCode, item)
|
||||
if (isRegistered(alarmCode))
|
||||
registered.remove(alarmCode)
|
||||
}
|
||||
|
||||
fun handle(alarmcode: AlarmCode) {
|
||||
if (isOccuring(alarmcode))
|
||||
occured.remove(alarmcode)
|
||||
fun handle(alarmCode: AlarmCode) {
|
||||
if (isOccurring(alarmCode))
|
||||
occurred.remove(alarmCode)
|
||||
}
|
||||
|
||||
fun isRegistered(alarmcode: AlarmCode): Boolean{
|
||||
return registered.containsKey(alarmcode)
|
||||
private fun isRegistered(alarmCode: AlarmCode): Boolean{
|
||||
return registered.containsKey(alarmCode)
|
||||
}
|
||||
|
||||
fun isOccuring(alarmcode: AlarmCode): Boolean{
|
||||
return occured.containsKey(alarmcode)
|
||||
fun isOccurring(alarmCode: AlarmCode): Boolean{
|
||||
return occurred.containsKey(alarmCode)
|
||||
}
|
||||
|
||||
override fun observe(): Observable<Alarms> {
|
||||
|
@ -94,15 +94,6 @@ class Alarms(): IPreference<Alarms> {
|
|||
}
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -17,11 +17,11 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl
|
|||
this.endMinute = end
|
||||
}
|
||||
|
||||
internal override fun duplicate(startMinute: Long, endMinute: Long): BasalSegment {
|
||||
override fun duplicate(startMinute: Long, endMinute: Long): BasalSegment {
|
||||
return BasalSegment(startMinute, endMinute, doseUnitPerHour)
|
||||
}
|
||||
|
||||
internal override fun deep(): BasalSegment {
|
||||
override fun deep(): BasalSegment {
|
||||
return BasalSegment(startMinute, endMinute, doseUnitPerHour)
|
||||
}
|
||||
|
||||
|
@ -29,8 +29,8 @@ data class BasalSegment (var start: Long, var end: Long, var doseUnitPerHour: Fl
|
|||
segment.doseUnitPerHour = doseUnitPerHour
|
||||
}
|
||||
|
||||
internal override fun equalValue(segment: BasalSegment): Boolean {
|
||||
return segment != null && doseUnitPerHour == segment.doseUnitPerHour
|
||||
override fun equalValue(segment: BasalSegment): Boolean {
|
||||
return doseUnitPerHour == segment.doseUnitPerHour
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package info.nightscout.androidaps.plugins.pump.eopatch.vo
|
||||
|
||||
import android.content.Context
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.AppConstant
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.GsonHelper
|
||||
import info.nightscout.androidaps.plugins.pump.eopatch.core.code.BolusType
|
||||
|
@ -179,16 +178,4 @@ class BolusCurrent(): IPreference<BolusCurrent> {
|
|||
override fun toString(): String {
|
||||
return "BolusCurrent(nowBolus=$nowBolus, extBolus=$extBolus)"
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
const val NAME = "BOLUS_CURRENT"
|
||||
|
||||
@JvmStatic
|
||||
fun createEmpty(): BolusCurrent {
|
||||
return BolusCurrent()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -4,6 +4,6 @@ import info.nightscout.shared.sharedPreferences.SP
|
|||
import io.reactivex.Observable
|
||||
|
||||
interface IPreference<T>{
|
||||
open fun flush(sp: SP)
|
||||
open fun observe(): Observable<T>
|
||||
fun flush(sp: SP)
|
||||
fun observe(): Observable<T>
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue