From b7bc33c1d8098a586d06986db8a066211b8caede Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 18 Sep 2023 18:50:00 +0200 Subject: [PATCH 1/9] simplify :android-wear-shared:shared --- app-wear-shared/shared/src/main/res/values-sw600dp/layout.xml | 3 --- app-wear-shared/shared/src/main/res/values/layout.xml | 3 --- .../info/nightscout/core/graph/data/TherapyEventDataPoint.kt | 2 +- .../nightscout/implementation/resources/ResourceHelperImpl.kt | 2 +- .../nightscout/plugins/general/overview/OverviewFragment.kt | 2 +- 5 files changed, 3 insertions(+), 9 deletions(-) delete mode 100644 app-wear-shared/shared/src/main/res/values-sw600dp/layout.xml delete mode 100644 app-wear-shared/shared/src/main/res/values/layout.xml diff --git a/app-wear-shared/shared/src/main/res/values-sw600dp/layout.xml b/app-wear-shared/shared/src/main/res/values-sw600dp/layout.xml deleted file mode 100644 index 7c98f55487..0000000000 --- a/app-wear-shared/shared/src/main/res/values-sw600dp/layout.xml +++ /dev/null @@ -1,3 +0,0 @@ - - true - \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/res/values/layout.xml b/app-wear-shared/shared/src/main/res/values/layout.xml deleted file mode 100644 index 57f058c48b..0000000000 --- a/app-wear-shared/shared/src/main/res/values/layout.xml +++ /dev/null @@ -1,3 +0,0 @@ - - false - \ No newline at end of file diff --git a/core/main/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt b/core/main/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt index 2d5e6bc024..2bbb05206b 100644 --- a/core/main/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt +++ b/core/main/src/main/java/info/nightscout/core/graph/data/TherapyEventDataPoint.kt @@ -50,7 +50,7 @@ class TherapyEventDataPoint( } override val paintStyle: Paint.Style = Paint.Style.FILL // not used - override val size get() = if (rh.gb(info.nightscout.shared.R.bool.isTablet)) 12.0f else 10.0f + override val size get() = if (rh.gb(info.nightscout.core.ui.R.bool.isTablet)) 12.0f else 10.0f override fun color(context: Context?): Int { return when (data.type) { TherapyEvent.Type.ANNOUNCEMENT -> rh.gac(context, info.nightscout.core.ui.R.attr.notificationAnnouncement) diff --git a/implementation/src/main/java/info/nightscout/implementation/resources/ResourceHelperImpl.kt b/implementation/src/main/java/info/nightscout/implementation/resources/ResourceHelperImpl.kt index 62d24e8825..145a9b240b 100644 --- a/implementation/src/main/java/info/nightscout/implementation/resources/ResourceHelperImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/resources/ResourceHelperImpl.kt @@ -93,7 +93,7 @@ class ResourceHelperImpl @Inject constructor(var context: Context, private val f return (dp * scale + 0.5f).toInt() } - override fun shortTextMode(): Boolean = !gb(info.nightscout.shared.R.bool.isTablet) + override fun shortTextMode(): Boolean = !gb(info.nightscout.core.ui.R.bool.isTablet) override fun gac(context: Context?, attributeId: Int): Int = (ContextThemeWrapper(context ?: this.context, info.nightscout.core.ui.R.style.AppTheme)).getThemeColor(attributeId) diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt index f06bb93822..0a19977f25 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt @@ -190,7 +190,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList smallHeight = screenHeight <= Constants.SMALL_HEIGHT val landscape = screenHeight < screenWidth - skinProvider.activeSkin().preProcessLandscapeOverviewLayout(binding, landscape, rh.gb(info.nightscout.shared.R.bool.isTablet), smallHeight) + skinProvider.activeSkin().preProcessLandscapeOverviewLayout(binding, landscape, rh.gb(info.nightscout.core.ui.R.bool.isTablet), smallHeight) binding.nsclientCard.visibility = config.NSCLIENT.toVisibility() binding.notifications.setHasFixedSize(false) From 81eb4f3a1cf30c7e4b445f20fa07c138d5faea61 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 18 Sep 2023 21:00:54 +0200 Subject: [PATCH 2/9] simplify :app-wear-shared:shared --- .../extensions/PackageManagerExtension.kt | 0 .../shared/impl/di/SharedImplModule.kt | 24 + .../impl}/logging/AAPSLoggerProduction.kt | 4 +- .../shared/impl/rx/AapsSchedulersImpl.kt | 16 + .../shared/impl/rx/bus/RxBusImpl.kt | 34 ++ .../nightscout/shared/utils/DateUtilImpl.kt | 470 +++++++++++++++++ .../src/main/res/drawable/background.xml | 6 +- .../src/main/res/drawable/detailed_dial.xml | 306 +++++++++++ .../src/main/res/drawable/hour_hand.xml | 9 + .../src/main/res/drawable/minute_hand.xml | 9 + .../src/main/res/drawable/second_hand.xml | 9 + .../src/main/res/drawable/simplified_dial.xml | 66 +++ .../main/res/drawable/watchface_custom.png | Bin app-wear-shared/shared-tests/build.gradle | 4 +- .../nightscout/sharedtests}/AAPSLoggerTest.kt | 5 +- .../info/nightscout/sharedtests/TestBase.kt | 3 +- .../sharedtests/TestBaseWithProfile.kt | 10 +- .../sharedtests/rx/TestAapsSchedulers.kt | 17 + .../java/info/nightscout/rx/AapsSchedulers.kt | 17 +- .../main/java/info/nightscout/rx/bus/RxBus.kt | 26 +- .../java/info/nightscout/rx/di/RxModule.kt | 25 - .../info/nightscout/shared/di/SharedModule.kt | 9 - .../info/nightscout/shared/utils/DateUtil.kt | 494 ++---------------- .../src/main/res/drawable/detailed_dial.xml | 183 ------- .../src/main/res/drawable/hour_hand.xml | 4 - .../src/main/res/drawable/minute_hand.xml | 4 - .../src/main/res/drawable/second_hand.xml | 4 - .../src/main/res/drawable/simplified_dial.xml | 39 -- .../nightscout/androidaps/di/AppComponent.kt | 8 +- .../interfaces/utils/DecimalFormatter.kt | 0 .../ui/src/main/res/values-sw600dp/layout.xml | 3 + core/ui/src/main/res/values/layout.xml | 3 + core/validators/build.gradle | 1 + .../maintenance/MaintenanceFragment.kt | 3 +- plugins/main/build.gradle | 1 + .../general/overview/OverviewPlugin.kt | 3 +- plugins/source/build.gradle | 1 + plugins/sync/build.gradle | 1 + .../nightscout/pump/combo/ComboFragment.kt | 8 +- pump/diaconn/build.gradle | 1 + .../pump/eopatch/alarm/AlarmRegistry.kt | 49 +- .../omnipod/dash/history/DashHistoryTest.kt | 2 +- .../driver/comm/endecrypt/EnDecryptTest.kt | 2 +- .../dash/driver/comm/pair/KeyExchangeTest.kt | 2 +- .../driver/comm/session/EapMessageTest.kt | 2 +- .../dash/driver/comm/session/MilenageTest.kt | 2 +- pump/omnipod-eros/build.gradle | 2 + .../manager/AapsErosPodStateManagerTest.kt | 6 +- .../nightscout/androidaps/di/WearModule.kt | 4 - .../androidaps/watchfaces/CustomWatchface.kt | 49 +- .../watchfaces/DigitalStyleWatchface.kt | 3 - .../heartrate/HeartRateListenerTest.kt | 26 +- 52 files changed, 1145 insertions(+), 834 deletions(-) rename app-wear-shared/{shared => shared-impl}/src/main/java/info/nightscout/shared/extensions/PackageManagerExtension.kt (100%) rename app-wear-shared/{shared/src/main/java/info/nightscout/rx => shared-impl/src/main/java/info/nightscout/shared/impl}/logging/AAPSLoggerProduction.kt (96%) create mode 100644 app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/AapsSchedulersImpl.kt create mode 100644 app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/bus/RxBusImpl.kt create mode 100644 app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt rename app-wear-shared/{shared => shared-impl}/src/main/res/drawable/background.xml (66%) create mode 100644 app-wear-shared/shared-impl/src/main/res/drawable/detailed_dial.xml create mode 100644 app-wear-shared/shared-impl/src/main/res/drawable/hour_hand.xml create mode 100644 app-wear-shared/shared-impl/src/main/res/drawable/minute_hand.xml create mode 100644 app-wear-shared/shared-impl/src/main/res/drawable/second_hand.xml create mode 100644 app-wear-shared/shared-impl/src/main/res/drawable/simplified_dial.xml rename app-wear-shared/{shared => shared-impl}/src/main/res/drawable/watchface_custom.png (100%) rename app-wear-shared/{shared/src/main/java/info/nightscout/rx/logging => shared-tests/src/main/java/info/nightscout/sharedtests}/AAPSLoggerTest.kt (95%) create mode 100644 app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/rx/TestAapsSchedulers.kt delete mode 100644 app-wear-shared/shared/src/main/java/info/nightscout/rx/di/RxModule.kt delete mode 100644 app-wear-shared/shared/src/main/java/info/nightscout/shared/di/SharedModule.kt delete mode 100644 app-wear-shared/shared/src/main/res/drawable/detailed_dial.xml delete mode 100644 app-wear-shared/shared/src/main/res/drawable/hour_hand.xml delete mode 100644 app-wear-shared/shared/src/main/res/drawable/minute_hand.xml delete mode 100644 app-wear-shared/shared/src/main/res/drawable/second_hand.xml delete mode 100644 app-wear-shared/shared/src/main/res/drawable/simplified_dial.xml rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt (100%) create mode 100644 core/ui/src/main/res/values-sw600dp/layout.xml create mode 100644 core/ui/src/main/res/values/layout.xml diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/extensions/PackageManagerExtension.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/extensions/PackageManagerExtension.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/extensions/PackageManagerExtension.kt rename to app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/extensions/PackageManagerExtension.kt diff --git a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/di/SharedImplModule.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/di/SharedImplModule.kt index 3bf15a91d9..f823e124f4 100644 --- a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/di/SharedImplModule.kt +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/di/SharedImplModule.kt @@ -4,10 +4,18 @@ import android.content.Context import androidx.preference.PreferenceManager import dagger.Module import dagger.Provides +import info.nightscout.rx.AapsSchedulers +import info.nightscout.rx.bus.RxBus import info.nightscout.rx.interfaces.L +import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.shared.impl.logging.AAPSLoggerProduction import info.nightscout.shared.impl.logging.LImpl +import info.nightscout.shared.impl.rx.AapsSchedulersImpl +import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.impl.sharedPreferences.SPImplementation import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import javax.inject.Singleton @Module( @@ -23,4 +31,20 @@ open class SharedImplModule { @Provides @Singleton fun provideL(sp: SP): L = LImpl(sp) + + @Provides + @Singleton + fun provideDateUtil(context: Context): DateUtil = DateUtilImpl(context) + + @Provides + @Singleton + fun provideAAPSLogger(l: L): AAPSLogger = AAPSLoggerProduction(l) + + @Provides + @Singleton + fun provideRxBus(aapsSchedulers: AapsSchedulers, aapsLogger: AAPSLogger): RxBus = RxBusImpl(aapsSchedulers, aapsLogger) + + @Provides + @Singleton + internal fun provideSchedulers(): AapsSchedulers = AapsSchedulersImpl() } \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerProduction.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/logging/AAPSLoggerProduction.kt similarity index 96% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerProduction.kt rename to app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/logging/AAPSLoggerProduction.kt index 4a6bcd8900..7335f9c842 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerProduction.kt +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/logging/AAPSLoggerProduction.kt @@ -1,6 +1,8 @@ -package info.nightscout.rx.logging +package info.nightscout.shared.impl.logging import info.nightscout.rx.interfaces.L +import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.rx.logging.LTag import org.slf4j.LoggerFactory /** diff --git a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/AapsSchedulersImpl.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/AapsSchedulersImpl.kt new file mode 100644 index 0000000000..a4f5c62847 --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/AapsSchedulersImpl.kt @@ -0,0 +1,16 @@ +package info.nightscout.shared.impl.rx + +import info.nightscout.rx.AapsSchedulers +import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers +import io.reactivex.rxjava3.core.Scheduler +import io.reactivex.rxjava3.schedulers.Schedulers +import javax.inject.Singleton + +@Singleton +class AapsSchedulersImpl : AapsSchedulers { + + override val main: Scheduler = AndroidSchedulers.mainThread() + override val io: Scheduler = Schedulers.io() + override val cpu: Scheduler = Schedulers.computation() + override val newThread: Scheduler = Schedulers.newThread() +} \ No newline at end of file diff --git a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/bus/RxBusImpl.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/bus/RxBusImpl.kt new file mode 100644 index 0000000000..6338303dd3 --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/impl/rx/bus/RxBusImpl.kt @@ -0,0 +1,34 @@ +package info.nightscout.shared.impl.rx.bus + +import info.nightscout.annotations.OpenForTesting +import info.nightscout.rx.AapsSchedulers +import info.nightscout.rx.bus.RxBus +import info.nightscout.rx.events.Event +import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.rx.logging.LTag +import io.reactivex.rxjava3.core.Observable +import io.reactivex.rxjava3.subjects.PublishSubject +import javax.inject.Inject +import javax.inject.Singleton + +@OpenForTesting +@Singleton +class RxBusImpl @Inject constructor( + val aapsSchedulers: AapsSchedulers, + val aapsLogger: AAPSLogger +) : RxBus { + + private val publisher = PublishSubject.create() + + override fun send(event: Event) { + aapsLogger.debug(LTag.EVENTS, "Sending $event") + publisher.onNext(event) + } + + // Listen should return an Observable and not the publisher + // Using ofType we filter only events that match that class type + override fun toObservable(eventType: Class): Observable = + publisher + .subscribeOn(aapsSchedulers.io) + .ofType(eventType) +} \ No newline at end of file diff --git a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt new file mode 100644 index 0000000000..ee093019d6 --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt @@ -0,0 +1,470 @@ +package info.nightscout.shared.utils + +import android.content.Context +import android.os.Build +import androidx.annotation.RequiresApi +import androidx.collection.LongSparseArray +import info.nightscout.annotations.OpenForTesting +import info.nightscout.shared.R +import info.nightscout.shared.SafeParse +import info.nightscout.shared.interfaces.ResourceHelper +import org.apache.commons.lang3.time.DateUtils.isSameDay +import org.joda.time.DateTime +import org.joda.time.format.DateTimeFormat +import org.joda.time.format.ISODateTimeFormat +import java.security.SecureRandom +import java.text.DateFormat +import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.text.SimpleDateFormat +import java.time.Instant +import java.time.ZoneId +import java.time.ZoneOffset +import java.util.Calendar +import java.util.Date +import java.util.EnumSet +import java.util.GregorianCalendar +import java.util.Locale +import java.util.TimeZone +import java.util.concurrent.TimeUnit +import java.util.regex.Pattern +import java.util.stream.Collectors +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.ceil +import kotlin.math.floor + +/** + * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj + * with TZ + */ +@OpenForTesting +@Singleton +class DateUtilImpl @Inject constructor(private val context: Context) : DateUtil { + + /** + * The date format in iso. + */ + @Suppress("PrivatePropertyName", "SpellCheckingInspection") + private val FORMAT_DATE_ISO_OUT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" + + /** + * Takes in an ISO date string of the following format: + * yyyy-mm-ddThh:mm:ss.ms+HoMo + * + * @param isoDateString the iso date string + * @return the date + */ + override fun fromISODateString(isoDateString: String): Long { + val parser = ISODateTimeFormat.dateTimeParser() + val dateTime = DateTime.parse(isoDateString, parser) + return dateTime.toDate().time + } + + /** + * Render date + * + * @param date the date obj + * @return the iso-formatted date string + */ + override fun toISOString(date: Long): String { + val f: DateFormat = SimpleDateFormat(FORMAT_DATE_ISO_OUT, Locale.getDefault()) + f.timeZone = TimeZone.getTimeZone("UTC") + return f.format(date) + } + + @Suppress("SpellCheckingInspection") + override fun toISOAsUTC(timestamp: Long): String { + val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'", Locale.US) + format.timeZone = TimeZone.getTimeZone("UTC") + return format.format(timestamp) + } + + @Suppress("SpellCheckingInspection") + override fun toISONoZone(timestamp: Long): String { + val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US) + format.timeZone = TimeZone.getDefault() + return format.format(timestamp) + } + + override fun secondsOfTheDayToMilliseconds(seconds: Int): Long { + val calendar: Calendar = GregorianCalendar() + calendar[Calendar.MONTH] = 0 // Set january to be sure we miss DST changing + calendar[Calendar.HOUR_OF_DAY] = seconds / 60 / 60 + calendar[Calendar.MINUTE] = seconds / 60 % 60 + calendar[Calendar.SECOND] = 0 + return calendar.timeInMillis + } + + override fun toSeconds(hhColonMm: String): Int { + val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)") + val m = p.matcher(hhColonMm) + var retVal = 0 + if (m.find()) { + retVal = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60 + if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") retVal -= 12 * 60 * 60 + if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") retVal += 12 * 60 * 60 + } + return retVal + } + + override fun dateString(mills: Long): String { + val df = DateFormat.getDateInstance(DateFormat.SHORT) + return df.format(mills) + } + + override fun dateStringRelative(mills: Long, rh: ResourceHelper): String { + val df = DateFormat.getDateInstance(DateFormat.SHORT) + val day = df.format(mills) + val beginOfToday = beginOfDay(now()) + return if (mills < now()) // Past + when { + mills > beginOfToday -> rh.gs(R.string.today) + mills > beginOfToday - T.days(1).msecs() -> rh.gs(R.string.yesterday) + mills > beginOfToday - T.days(7).msecs() -> dayAgo(mills, rh, true) + else -> day + } + else // Future + when { + mills < beginOfToday + T.days(1).msecs() -> rh.gs(R.string.later_today) + mills < beginOfToday + T.days(2).msecs() -> rh.gs(R.string.tomorrow) + mills < beginOfToday + T.days(7).msecs() -> dayAgo(mills, rh, true) + else -> day + } + } + + override fun dateStringShort(mills: Long): String { + var format = "MM/dd" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "dd/MM" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + override fun timeString(): String = timeString(now()) + override fun timeString(mills: Long): String { + var format = "hh:mma" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "HH:mm" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + override fun secondString(): String = secondString(now()) + override fun secondString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("ss")) + + override fun minuteString(): String = minuteString(now()) + override fun minuteString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("mm")) + + override fun hourString(): String = hourString(now()) + override fun hourString(mills: Long): String { + var format = "hh" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "HH" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + override fun amPm(): String = amPm(now()) + override fun amPm(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("a")) + + override fun dayNameString(format: String): String = dayNameString(now(), format) + override fun dayNameString(mills: Long, format: String): String = + DateTime(mills).toString(DateTimeFormat.forPattern(format)) + + override fun dayString(): String = dayString(now()) + override fun dayString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("dd")) + + override fun monthString(format: String): String = monthString(now(), format) + override fun monthString(mills: Long, format: String): String = + DateTime(mills).toString(DateTimeFormat.forPattern(format)) + + override fun weekString(): String = weekString(now()) + override fun weekString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("ww")) + + override fun timeStringWithSeconds(mills: Long): String { + var format = "hh:mm:ssa" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "HH:mm:ss" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + override fun dateAndTimeRangeString(start: Long, end: Long): String { + return dateAndTimeString(start) + " - " + timeString(end) + } + + override fun timeRangeString(start: Long, end: Long): String { + return timeString(start) + " - " + timeString(end) + } + + override fun dateAndTimeString(mills: Long): String { + return if (mills == 0L) "" else dateString(mills) + " " + timeString(mills) + } + + override fun dateAndTimeAndSecondsString(mills: Long): String { + return if (mills == 0L) "" else dateString(mills) + " " + timeStringWithSeconds(mills) + } + + override fun minAgo(rh: ResourceHelper, time: Long?): String { + if (time == null) return "" + val minutes = ((now() - time) / 1000 / 60).toInt() + return rh.gs(R.string.minago, minutes) + } + + override fun minAgoShort(time: Long?): String { + if (time == null) return "" + val minutes = ((time - now()) / 1000 / 60).toInt() + return (if (minutes > 0) "+" else "") + minutes + } + + override fun minAgoLong(rh: ResourceHelper, time: Long?): String { + if (time == null) return "" + val minutes = ((now() - time) / 1000 / 60).toInt() + return rh.gs(R.string.minago_long, minutes) + } + + override fun hourAgo(time: Long, rh: ResourceHelper): String { + val hours = (now() - time) / 1000.0 / 60 / 60 + return rh.gs(R.string.hoursago, hours) + } + + override fun dayAgo(time: Long, rh: ResourceHelper, round: Boolean): String { + var days = (now() - time) / 1000.0 / 60 / 60 / 24 + if (round) { + return if (now() > time) { + days = ceil(days) + rh.gs(R.string.days_ago_round, days) + } else { + days = floor(days) + rh.gs(R.string.in_days_round, days) + } + } + return if (now() > time) + rh.gs(R.string.days_ago, days) + else + rh.gs(R.string.in_days, days) + } + + override fun beginOfDay(mills: Long): Long { + val givenDate = Calendar.getInstance() + givenDate.timeInMillis = mills + givenDate[Calendar.HOUR_OF_DAY] = 0 + givenDate[Calendar.MINUTE] = 0 + givenDate[Calendar.SECOND] = 0 + givenDate[Calendar.MILLISECOND] = 0 + return givenDate.timeInMillis + } + + override fun timeStringFromSeconds(seconds: Int): String { + val cached = timeStrings[seconds.toLong()] + if (cached != null) return cached + val t = timeString(secondsOfTheDayToMilliseconds(seconds)) + timeStrings.put(seconds.toLong(), t) + return t + } + + override fun timeFrameString(timeInMillis: Long, rh: ResourceHelper): String { + var remainingTimeMinutes = timeInMillis / (1000 * 60) + val remainingTimeHours = remainingTimeMinutes / 60 + remainingTimeMinutes %= 60 + return "(" + (if (remainingTimeHours > 0) remainingTimeHours.toString() + rh.gs(R.string.shorthour) + " " else "") + remainingTimeMinutes + "')" + } + + override fun sinceString(timestamp: Long, rh: ResourceHelper): String { + return timeFrameString(System.currentTimeMillis() - timestamp, rh) + } + + override fun untilString(timestamp: Long, rh: ResourceHelper): String { + return timeFrameString(timestamp - System.currentTimeMillis(), rh) + } + + override fun now(): Long { + return System.currentTimeMillis() + } + + override fun nowWithoutMilliseconds(): Long { + var n = System.currentTimeMillis() + n -= n % 1000 + return n + } + + override fun isOlderThan(date: Long, minutes: Long): Boolean { + val diff = now() - date + return diff > T.mins(minutes).msecs() + } + + override fun getTimeZoneOffsetMs(): Long { + return GregorianCalendar().timeZone.rawOffset.toLong() + } + + override fun getTimeZoneOffsetMinutes(timestamp: Long): Int { + return TimeZone.getDefault().getOffset(timestamp) / 60000 + } + + override fun isSameDay(timestamp1: Long, timestamp2: Long) = isSameDay(Date(timestamp1), Date(timestamp2)) + + override fun isSameDayGroup(timestamp1: Long, timestamp2: Long): Boolean { + val now = now() + if (now in (timestamp1 + 1) until timestamp2 || now in (timestamp2 + 1) until timestamp1) + return false + return isSameDay(Date(timestamp1), Date(timestamp2)) + } + + //Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0} + override fun computeDiff(date1: Long, date2: Long): Map { + val units: MutableList = ArrayList(EnumSet.allOf(TimeUnit::class.java)) + units.reverse() + val result: MutableMap = LinkedHashMap() + var millisecondsRest = date2 - date1 + for (unit in units) { + val diff = unit.convert(millisecondsRest, TimeUnit.MILLISECONDS) + val diffInMillisecondsForUnit = unit.toMillis(diff) + millisecondsRest -= diffInMillisecondsForUnit + result[unit] = diff + } + return result + } + + override fun age(milliseconds: Long, useShortText: Boolean, rh: ResourceHelper): String { + val diff = computeDiff(0L, milliseconds) + var days = " " + rh.gs(R.string.days) + " " + var hours = " " + rh.gs(R.string.hours) + " " + var minutes = " " + rh.gs(R.string.unit_minutes) + " " + if (useShortText) { + days = rh.gs(R.string.shortday) + hours = rh.gs(R.string.shorthour) + minutes = rh.gs(R.string.shortminute) + } + var result = "" + if (diff.getOrDefault(TimeUnit.DAYS, -1) > 0) result += diff[TimeUnit.DAYS].toString() + days + if (diff.getOrDefault(TimeUnit.HOURS, -1) > 0) result += diff[TimeUnit.HOURS].toString() + hours + if (diff[TimeUnit.DAYS] == 0L) result += diff[TimeUnit.MINUTES].toString() + minutes + return result + } + + override fun niceTimeScalar(time: Long, rh: ResourceHelper): String { + var t = time + var unit = rh.gs(R.string.unit_second) + t /= 1000 + if (t != 1L) unit = rh.gs(R.string.unit_seconds) + if (t > 59) { + unit = rh.gs(R.string.unit_minute) + t /= 60 + if (t != 1L) unit = rh.gs(R.string.unit_minutes) + if (t > 59) { + unit = rh.gs(R.string.unit_hour) + t /= 60 + if (t != 1L) unit = rh.gs(R.string.unit_hours) + if (t > 24) { + unit = rh.gs(R.string.unit_day) + t /= 24 + if (t != 1L) unit = rh.gs(R.string.unit_days) + if (t > 28) { + unit = rh.gs(R.string.unit_week) + t /= 7 + @Suppress("KotlinConstantConditions") + if (t != 1L) unit = rh.gs(R.string.unit_weeks) + } + } + } + } + //if (t != 1) unit = unit + "s"; //implemented plurality in every step, because in other languages plurality of time is not every time adding the same character + return qs(t.toDouble(), 0) + " " + unit + } + + override fun qs(x: Double, numDigits: Int): String { + var digits = numDigits + if (digits == -1) { + digits = 0 + if ((x.toInt() % x == 0.0)) { + digits++ + if ((x.toInt() * 10 / 10).toDouble() != x) { + digits++ + if ((x.toInt() * 100 / 100).toDouble() != x) digits++ + } + } + } + if (dfs == null) { + val localDfs = DecimalFormatSymbols() + localDfs.decimalSeparator = '.' + dfs = localDfs // avoid race condition + } + val thisDf: DecimalFormat? + // use singleton if on ui thread otherwise allocate new as DecimalFormat is not thread safe + if (Thread.currentThread().id == 1L) { + if (df == null) { + val localDf = DecimalFormat("#", dfs) + localDf.minimumIntegerDigits = 1 + df = localDf // avoid race condition + } + thisDf = df + } else { + thisDf = DecimalFormat("#", dfs) + } + thisDf?.maximumFractionDigits = digits + return thisDf?.format(x) ?: "" + } + + override fun formatHHMM(timeAsSeconds: Int): String { + val hour = timeAsSeconds / 60 / 60 + val minutes = (timeAsSeconds - hour * 60 * 60) / 60 + val df = DecimalFormat("00") + return df.format(hour.toLong()) + ":" + df.format(minutes.toLong()) + } + + @RequiresApi(Build.VERSION_CODES.O) + override fun timeZoneByOffset(offsetInMilliseconds: Long): TimeZone = + TimeZone.getTimeZone( + if (offsetInMilliseconds == 0L) ZoneId.of("UTC") + else ZoneId.getAvailableZoneIds() + .stream() + .map(ZoneId::of) + .filter { z -> z.rules.getOffset(Instant.now()).totalSeconds == ZoneOffset.ofHours((offsetInMilliseconds / 1000 / 3600).toInt()).totalSeconds } + .collect(Collectors.toList()) + .firstOrNull() ?: ZoneId.of("UTC") + ) + + override fun timeStampToUtcDateMillis(timestamp: Long): Long { + val current = Calendar.getInstance().apply { timeInMillis = timestamp } + return Calendar.getInstance().apply { + set(Calendar.YEAR, current[Calendar.YEAR]) + set(Calendar.MONTH, current[Calendar.MONTH]) + set(Calendar.DAY_OF_MONTH, current[Calendar.DAY_OF_MONTH]) + }.timeInMillis + } + + override fun mergeUtcDateToTimestamp(timestamp: Long, dateUtcMillis: Long): Long { + val selected = Calendar.getInstance().apply { timeInMillis = dateUtcMillis } + return Calendar.getInstance().apply { + timeInMillis = timestamp + set(Calendar.YEAR, selected[Calendar.YEAR]) + set(Calendar.MONTH, selected[Calendar.MONTH]) + set(Calendar.DAY_OF_MONTH, selected[Calendar.DAY_OF_MONTH]) + }.timeInMillis + } + + override fun mergeHourMinuteToTimestamp(timestamp: Long, hour: Int, minute: Int, randomSecond: Boolean): Long { + return Calendar.getInstance().apply { + timeInMillis = timestamp + set(Calendar.HOUR_OF_DAY, hour) + set(Calendar.MINUTE, minute) + if (randomSecond) set(Calendar.SECOND, seconds++) + }.timeInMillis + } + + companion object { + + private val timeStrings = LongSparseArray() + private var seconds: Int = (SecureRandom().nextDouble() * 59.0).toInt() + + // singletons to avoid repeated allocation + private var dfs: DecimalFormatSymbols? = null + private var df: DecimalFormat? = null + } +} diff --git a/app-wear-shared/shared/src/main/res/drawable/background.xml b/app-wear-shared/shared-impl/src/main/res/drawable/background.xml similarity index 66% rename from app-wear-shared/shared/src/main/res/drawable/background.xml rename to app-wear-shared/shared-impl/src/main/res/drawable/background.xml index 76226923e6..e8f62fdfa3 100644 --- a/app-wear-shared/shared/src/main/res/drawable/background.xml +++ b/app-wear-shared/shared-impl/src/main/res/drawable/background.xml @@ -3,7 +3,7 @@ android:height="24dp" android:viewportWidth="24" android:viewportHeight="24"> - + diff --git a/app-wear-shared/shared-impl/src/main/res/drawable/detailed_dial.xml b/app-wear-shared/shared-impl/src/main/res/drawable/detailed_dial.xml new file mode 100644 index 0000000000..d3a62c944e --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/res/drawable/detailed_dial.xml @@ -0,0 +1,306 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app-wear-shared/shared-impl/src/main/res/drawable/hour_hand.xml b/app-wear-shared/shared-impl/src/main/res/drawable/hour_hand.xml new file mode 100644 index 0000000000..fc748e1b8f --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/res/drawable/hour_hand.xml @@ -0,0 +1,9 @@ + + + diff --git a/app-wear-shared/shared-impl/src/main/res/drawable/minute_hand.xml b/app-wear-shared/shared-impl/src/main/res/drawable/minute_hand.xml new file mode 100644 index 0000000000..8e11c2fa1d --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/res/drawable/minute_hand.xml @@ -0,0 +1,9 @@ + + + diff --git a/app-wear-shared/shared-impl/src/main/res/drawable/second_hand.xml b/app-wear-shared/shared-impl/src/main/res/drawable/second_hand.xml new file mode 100644 index 0000000000..e768022ba5 --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/res/drawable/second_hand.xml @@ -0,0 +1,9 @@ + + + diff --git a/app-wear-shared/shared-impl/src/main/res/drawable/simplified_dial.xml b/app-wear-shared/shared-impl/src/main/res/drawable/simplified_dial.xml new file mode 100644 index 0000000000..aa440fe5ab --- /dev/null +++ b/app-wear-shared/shared-impl/src/main/res/drawable/simplified_dial.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + diff --git a/app-wear-shared/shared/src/main/res/drawable/watchface_custom.png b/app-wear-shared/shared-impl/src/main/res/drawable/watchface_custom.png similarity index 100% rename from app-wear-shared/shared/src/main/res/drawable/watchface_custom.png rename to app-wear-shared/shared-impl/src/main/res/drawable/watchface_custom.png diff --git a/app-wear-shared/shared-tests/build.gradle b/app-wear-shared/shared-tests/build.gradle index da77123e24..9c4a8730fa 100644 --- a/app-wear-shared/shared-tests/build.gradle +++ b/app-wear-shared/shared-tests/build.gradle @@ -14,16 +14,18 @@ apply from: "${project.rootDir}/core/main/jacoco_global.gradle" android { namespace 'info.nightscout.sharedtests' - } +} dependencies { implementation project(':database:entities') implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:utils') implementation project(':implementation') + api "org.mockito:mockito-junit-jupiter:$mockito_version" api "org.mockito.kotlin:mockito-kotlin:5.1.0" api "org.junit.jupiter:junit-jupiter-api:$junit_jupiter_version" diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerTest.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/AAPSLoggerTest.kt similarity index 95% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerTest.kt rename to app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/AAPSLoggerTest.kt index 88142c93a8..562aa66403 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLoggerTest.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/AAPSLoggerTest.kt @@ -1,4 +1,7 @@ -package info.nightscout.rx.logging +package info.nightscout.sharedtests + +import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.rx.logging.LTag /** * Created by adrian on 2019-12-27. diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt index 1e52c7fbea..35f4960822 100644 --- a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt @@ -2,8 +2,7 @@ package info.nightscout.sharedtests import android.annotation.SuppressLint import info.nightscout.rx.AapsSchedulers -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.rx.TestAapsSchedulers import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.extension.ExtendWith import org.mockito.ArgumentMatcher diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt index cb2ceb610f..8a03a6fbbb 100644 --- a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt @@ -19,11 +19,11 @@ import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileStore import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits -import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import org.json.JSONObject import org.junit.jupiter.api.BeforeEach import org.mockito.ArgumentMatchers.anyDouble @@ -45,11 +45,11 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var context: Context @Mock lateinit var sp: SP - lateinit var dateUtil: DateUtil + lateinit var dateUtil: DateUtilImpl lateinit var profileUtil: ProfileUtil lateinit var decimalFormatter: DecimalFormatter lateinit var hardLimits: HardLimits - val rxBus = RxBus(aapsSchedulers, aapsLogger) + val rxBus = RxBusImpl(aapsSchedulers, aapsLogger) val profileInjector = HasAndroidInjector { AndroidInjector { @@ -82,7 +82,7 @@ open class TestBaseWithProfile : TestBase() { invalidProfileJSON = "{\"dia\":\"1\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"3\"}," + "{\"time\":\"2:00\",\"value\":\"3.4\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4.5\"}]," + "\"target_high\":[{\"time\":\"00:00\",\"value\":\"7\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" - dateUtil = Mockito.spy(DateUtil(context)) + dateUtil = Mockito.spy(DateUtilImpl(context)) decimalFormatter = DecimalFormatterImpl(rh) profileUtil = ProfileUtilImpl(sp, decimalFormatter) testPumpPlugin = TestPumpPlugin(profileInjector) diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/rx/TestAapsSchedulers.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/rx/TestAapsSchedulers.kt new file mode 100644 index 0000000000..e9b18431ce --- /dev/null +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/rx/TestAapsSchedulers.kt @@ -0,0 +1,17 @@ +package info.nightscout.sharedtests.rx + +import info.nightscout.rx.AapsSchedulers +import io.reactivex.rxjava3.core.Scheduler +import io.reactivex.rxjava3.schedulers.Schedulers + +/** + * Created by adrian on 12.04.20. + */ + +class TestAapsSchedulers : AapsSchedulers { + + override val main: Scheduler = Schedulers.trampoline() + override val io: Scheduler = Schedulers.trampoline() + override val cpu: Scheduler = Schedulers.trampoline() + override val newThread: Scheduler = Schedulers.trampoline() +} \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt index 4377909f3d..af6f4f1cda 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt @@ -1,30 +1,15 @@ package info.nightscout.rx -import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Scheduler -import io.reactivex.rxjava3.schedulers.Schedulers /** * Created by adrian on 12.04.20. */ interface AapsSchedulers { + val main: Scheduler val io: Scheduler val cpu: Scheduler val newThread: Scheduler -} - -class DefaultAapsSchedulers : AapsSchedulers { - override val main: Scheduler = AndroidSchedulers.mainThread() - override val io: Scheduler = Schedulers.io() - override val cpu: Scheduler = Schedulers.computation() - override val newThread: Scheduler = Schedulers.newThread() -} - -class TestAapsSchedulers : AapsSchedulers { - override val main: Scheduler = Schedulers.trampoline() - override val io: Scheduler = Schedulers.trampoline() - override val cpu: Scheduler = Schedulers.trampoline() - override val newThread: Scheduler = Schedulers.trampoline() } \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt index 438fad7ed9..e2649036c5 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt @@ -1,33 +1,13 @@ package info.nightscout.rx.bus -import info.nightscout.annotations.OpenForTesting -import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.events.Event -import info.nightscout.rx.logging.AAPSLogger -import info.nightscout.rx.logging.LTag import io.reactivex.rxjava3.core.Observable -import io.reactivex.rxjava3.subjects.PublishSubject -import javax.inject.Inject -import javax.inject.Singleton -@OpenForTesting -@Singleton -class RxBus @Inject constructor( - val aapsSchedulers: AapsSchedulers, - val aapsLogger: AAPSLogger -) { +interface RxBus { - private val publisher = PublishSubject.create() - - fun send(event: Event) { - aapsLogger.debug(LTag.EVENTS, "Sending $event") - publisher.onNext(event) - } + fun send(event: Event) // Listen should return an Observable and not the publisher // Using ofType we filter only events that match that class type - fun toObservable(eventType: Class): Observable = - publisher - .subscribeOn(aapsSchedulers.io) - .ofType(eventType) + fun toObservable(eventType: Class): Observable } \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/di/RxModule.kt b/app-wear-shared/shared/src/main/java/info/nightscout/rx/di/RxModule.kt deleted file mode 100644 index 0e584cf5e7..0000000000 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/di/RxModule.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.nightscout.rx.di - -import dagger.Module -import dagger.Provides -import info.nightscout.rx.AapsSchedulers -import info.nightscout.rx.DefaultAapsSchedulers -import info.nightscout.rx.interfaces.L -import info.nightscout.rx.logging.AAPSLogger -import info.nightscout.rx.logging.AAPSLoggerProduction -import javax.inject.Singleton - -@Module( - includes = [ - ] -) -open class RxModule { - - @Provides - @Singleton - internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers() - - @Provides - @Singleton - fun provideAAPSLogger(l: L): AAPSLogger = AAPSLoggerProduction(l) -} \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/di/SharedModule.kt b/app-wear-shared/shared/src/main/java/info/nightscout/shared/di/SharedModule.kt deleted file mode 100644 index 735de9f807..0000000000 --- a/app-wear-shared/shared/src/main/java/info/nightscout/shared/di/SharedModule.kt +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.shared.di - -import dagger.Module - -@Module( - includes = [ - ] -) -open class SharedModule \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt b/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt index 361a52b600..41afa1adb2 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt +++ b/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt @@ -1,52 +1,16 @@ package info.nightscout.shared.utils -import android.content.Context import android.os.Build import androidx.annotation.RequiresApi -import androidx.collection.LongSparseArray -import info.nightscout.annotations.OpenForTesting -import info.nightscout.shared.R -import info.nightscout.shared.SafeParse import info.nightscout.shared.interfaces.ResourceHelper -import org.apache.commons.lang3.time.DateUtils.isSameDay -import org.joda.time.DateTime -import org.joda.time.format.DateTimeFormat -import org.joda.time.format.ISODateTimeFormat -import java.security.SecureRandom -import java.text.DateFormat -import java.text.DecimalFormat -import java.text.DecimalFormatSymbols -import java.text.SimpleDateFormat -import java.time.Instant -import java.time.ZoneId -import java.time.ZoneOffset -import java.util.Calendar -import java.util.Date -import java.util.EnumSet -import java.util.GregorianCalendar -import java.util.Locale import java.util.TimeZone import java.util.concurrent.TimeUnit -import java.util.regex.Pattern -import java.util.stream.Collectors -import javax.inject.Inject -import javax.inject.Singleton -import kotlin.math.ceil -import kotlin.math.floor /** * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj * with TZ */ -@OpenForTesting -@Singleton -class DateUtil @Inject constructor(private val context: Context) { - - /** - * The date format in iso. - */ - @Suppress("PrivatePropertyName", "SpellCheckingInspection") - private val FORMAT_DATE_ISO_OUT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" +interface DateUtil { /** * Takes in an ISO date string of the following format: @@ -55,11 +19,7 @@ class DateUtil @Inject constructor(private val context: Context) { * @param isoDateString the iso date string * @return the date */ - fun fromISODateString(isoDateString: String): Long { - val parser = ISODateTimeFormat.dateTimeParser() - val dateTime = DateTime.parse(isoDateString, parser) - return dateTime.toDate().time - } + fun fromISODateString(isoDateString: String): Long /** * Render date @@ -67,404 +27,66 @@ class DateUtil @Inject constructor(private val context: Context) { * @param date the date obj * @return the iso-formatted date string */ - fun toISOString(date: Long): String { - val f: DateFormat = SimpleDateFormat(FORMAT_DATE_ISO_OUT, Locale.getDefault()) - f.timeZone = TimeZone.getTimeZone("UTC") - return f.format(date) - } - - @Suppress("SpellCheckingInspection") - fun toISOAsUTC(timestamp: Long): String { - val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'", Locale.US) - format.timeZone = TimeZone.getTimeZone("UTC") - return format.format(timestamp) - } - - @Suppress("SpellCheckingInspection") - fun toISONoZone(timestamp: Long): String { - val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US) - format.timeZone = TimeZone.getDefault() - return format.format(timestamp) - } - - fun secondsOfTheDayToMilliseconds(seconds: Int): Long { - val calendar: Calendar = GregorianCalendar() - calendar[Calendar.MONTH] = 0 // Set january to be sure we miss DST changing - calendar[Calendar.HOUR_OF_DAY] = seconds / 60 / 60 - calendar[Calendar.MINUTE] = seconds / 60 % 60 - calendar[Calendar.SECOND] = 0 - return calendar.timeInMillis - } - - fun toSeconds(hhColonMm: String): Int { - val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)") - val m = p.matcher(hhColonMm) - var retVal = 0 - if (m.find()) { - retVal = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60 - if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") retVal -= 12 * 60 * 60 - if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") retVal += 12 * 60 * 60 - } - return retVal - } - - fun dateString(mills: Long): String { - val df = DateFormat.getDateInstance(DateFormat.SHORT) - return df.format(mills) - } - - fun dateStringRelative(mills: Long, rh: ResourceHelper): String { - val df = DateFormat.getDateInstance(DateFormat.SHORT) - val day = df.format(mills) - val beginOfToday = beginOfDay(now()) - return if (mills < now()) // Past - when { - mills > beginOfToday -> rh.gs(R.string.today) - mills > beginOfToday - T.days(1).msecs() -> rh.gs(R.string.yesterday) - mills > beginOfToday - T.days(7).msecs() -> dayAgo(mills, rh, true) - else -> day - } - else // Future - when { - mills < beginOfToday + T.days(1).msecs() -> rh.gs(R.string.later_today) - mills < beginOfToday + T.days(2).msecs() -> rh.gs(R.string.tomorrow) - mills < beginOfToday + T.days(7).msecs() -> dayAgo(mills, rh, true) - else -> day - } - } - - fun dateStringShort(mills: Long): String { - var format = "MM/dd" - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "dd/MM" - } - return DateTime(mills).toString(DateTimeFormat.forPattern(format)) - } - - fun timeString(): String = timeString(now()) - fun timeString(mills: Long): String { - var format = "hh:mma" - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH:mm" - } - return DateTime(mills).toString(DateTimeFormat.forPattern(format)) - } - - fun secondString(): String = secondString(now()) - fun secondString(mills: Long): String = - DateTime(mills).toString(DateTimeFormat.forPattern("ss")) - - fun minuteString(): String = minuteString(now()) - fun minuteString(mills: Long): String = - DateTime(mills).toString(DateTimeFormat.forPattern("mm")) - - fun hourString(): String = hourString(now()) - fun hourString(mills: Long): String { - var format = "hh" - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH" - } - return DateTime(mills).toString(DateTimeFormat.forPattern(format)) - } - - fun amPm(): String = amPm(now()) - fun amPm(mills: Long): String = - DateTime(mills).toString(DateTimeFormat.forPattern("a")) - - fun dayNameString(format: String = "E"): String = dayNameString(now(), format) - fun dayNameString(mills: Long, format: String = "E"): String = - DateTime(mills).toString(DateTimeFormat.forPattern(format)) - + fun toISOString(date: Long): String + fun toISOAsUTC(timestamp: Long): String + fun toISONoZone(timestamp: Long): String + fun secondsOfTheDayToMilliseconds(seconds: Int): Long + fun toSeconds(hhColonMm: String): Int + fun dateString(mills: Long): String + fun dateStringRelative(mills: Long, rh: ResourceHelper): String + fun dateStringShort(mills: Long): String + fun timeString(): String + fun timeString(mills: Long): String + fun secondString(): String + fun secondString(mills: Long): String + fun minuteString(): String + fun minuteString(mills: Long): String + fun hourString(): String + fun hourString(mills: Long): String + fun amPm(): String + fun amPm(mills: Long): String + fun dayNameString(format: String = "E"): String + fun dayNameString(mills: Long, format: String = "E"): String fun dayString(): String = dayString(now()) - fun dayString(mills: Long): String = - DateTime(mills).toString(DateTimeFormat.forPattern("dd")) + fun dayString(mills: Long): String + fun monthString(format: String = "MMM"): String + fun monthString(mills: Long, format: String = "MMM"): String + fun weekString(): String + fun weekString(mills: Long): String + fun timeStringWithSeconds(mills: Long): String + fun dateAndTimeRangeString(start: Long, end: Long): String + fun timeRangeString(start: Long, end: Long): String + fun dateAndTimeString(mills: Long): String + fun dateAndTimeAndSecondsString(mills: Long): String + fun minAgo(rh: ResourceHelper, time: Long?): String + fun minAgoShort(time: Long?): String + fun minAgoLong(rh: ResourceHelper, time: Long?): String + fun hourAgo(time: Long, rh: ResourceHelper): String + fun dayAgo(time: Long, rh: ResourceHelper, round: Boolean = false): String + fun beginOfDay(mills: Long): Long + fun timeStringFromSeconds(seconds: Int): String + fun timeFrameString(timeInMillis: Long, rh: ResourceHelper): String + fun sinceString(timestamp: Long, rh: ResourceHelper): String + fun untilString(timestamp: Long, rh: ResourceHelper): String + fun now(): Long + fun nowWithoutMilliseconds(): Long + fun isOlderThan(date: Long, minutes: Long): Boolean + fun getTimeZoneOffsetMs(): Long + fun getTimeZoneOffsetMinutes(timestamp: Long): Int + fun isSameDay(timestamp1: Long, timestamp2: Long): Boolean - fun monthString(format: String = "MMM"): String = monthString(now(), format) - fun monthString(mills: Long, format: String = "MMM"): String = - DateTime(mills).toString(DateTimeFormat.forPattern(format)) - - fun weekString(): String = weekString(now()) - fun weekString(mills: Long): String = - DateTime(mills).toString(DateTimeFormat.forPattern("ww")) - - fun timeStringWithSeconds(mills: Long): String { - var format = "hh:mm:ssa" - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH:mm:ss" - } - return DateTime(mills).toString(DateTimeFormat.forPattern(format)) - } - - fun dateAndTimeRangeString(start: Long, end: Long): String { - return dateAndTimeString(start) + " - " + timeString(end) - } - - fun timeRangeString(start: Long, end: Long): String { - return timeString(start) + " - " + timeString(end) - } - - fun dateAndTimeString(mills: Long): String { - return if (mills == 0L) "" else dateString(mills) + " " + timeString(mills) - } - - fun dateAndTimeAndSecondsString(mills: Long): String { - return if (mills == 0L) "" else dateString(mills) + " " + timeStringWithSeconds(mills) - } - - fun minAgo(rh: ResourceHelper, time: Long?): String { - if (time == null) return "" - val minutes = ((now() - time) / 1000 / 60).toInt() - return rh.gs(R.string.minago, minutes) - } - - fun minAgoShort(time: Long?): String { - if (time == null) return "" - val minutes = ((time - now()) / 1000 / 60).toInt() - return (if (minutes > 0) "+" else "") + minutes - } - - fun minAgoLong(rh: ResourceHelper, time: Long?): String { - if (time == null) return "" - val minutes = ((now() - time) / 1000 / 60).toInt() - return rh.gs(R.string.minago_long, minutes) - } - - fun hourAgo(time: Long, rh: ResourceHelper): String { - val hours = (now() - time) / 1000.0 / 60 / 60 - return rh.gs(R.string.hoursago, hours) - } - - fun dayAgo(time: Long, rh: ResourceHelper, round: Boolean = false): String { - var days = (now() - time) / 1000.0 / 60 / 60 / 24 - if (round) { - return if (now() > time) { - days = ceil(days) - rh.gs(R.string.days_ago_round, days) - } else { - days = floor(days) - rh.gs(R.string.in_days_round, days) - } - } - return if (now() > time) - rh.gs(R.string.days_ago, days) - else - rh.gs(R.string.in_days, days) - } - - fun beginOfDay(mills: Long): Long { - val givenDate = Calendar.getInstance() - givenDate.timeInMillis = mills - givenDate[Calendar.HOUR_OF_DAY] = 0 - givenDate[Calendar.MINUTE] = 0 - givenDate[Calendar.SECOND] = 0 - givenDate[Calendar.MILLISECOND] = 0 - return givenDate.timeInMillis - } - - fun timeStringFromSeconds(seconds: Int): String { - val cached = timeStrings[seconds.toLong()] - if (cached != null) return cached - val t = timeString(secondsOfTheDayToMilliseconds(seconds)) - timeStrings.put(seconds.toLong(), t) - return t - } - - fun timeFrameString(timeInMillis: Long, rh: ResourceHelper): String { - var remainingTimeMinutes = timeInMillis / (1000 * 60) - val remainingTimeHours = remainingTimeMinutes / 60 - remainingTimeMinutes %= 60 - return "(" + (if (remainingTimeHours > 0) remainingTimeHours.toString() + rh.gs(R.string.shorthour) + " " else "") + remainingTimeMinutes + "')" - } - - fun sinceString(timestamp: Long, rh: ResourceHelper): String { - return timeFrameString(System.currentTimeMillis() - timestamp, rh) - } - - fun untilString(timestamp: Long, rh: ResourceHelper): String { - return timeFrameString(timestamp - System.currentTimeMillis(), rh) - } - - fun now(): Long { - return System.currentTimeMillis() - } - - fun nowWithoutMilliseconds(): Long { - var n = System.currentTimeMillis() - n -= n % 1000 - return n - } - - fun isOlderThan(date: Long, minutes: Long): Boolean { - val diff = now() - date - return diff > T.mins(minutes).msecs() - } - - fun getTimeZoneOffsetMs(): Long { - return GregorianCalendar().timeZone.rawOffset.toLong() - } - - fun getTimeZoneOffsetMinutes(timestamp: Long): Int { - return TimeZone.getDefault().getOffset(timestamp) / 60000 - } - - fun isSameDay(timestamp1: Long, timestamp2: Long) = isSameDay(Date(timestamp1), Date(timestamp2)) - - fun isSameDayGroup(timestamp1: Long, timestamp2: Long): Boolean { - val now = now() - if (now in (timestamp1 + 1) until timestamp2 || now in (timestamp2 + 1) until timestamp1) - return false - return isSameDay(Date(timestamp1), Date(timestamp2)) - } + fun isSameDayGroup(timestamp1: Long, timestamp2: Long): Boolean //Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0} - fun computeDiff(date1: Long, date2: Long): Map { - val units: MutableList = ArrayList(EnumSet.allOf(TimeUnit::class.java)) - units.reverse() - val result: MutableMap = LinkedHashMap() - var millisecondsRest = date2 - date1 - for (unit in units) { - val diff = unit.convert(millisecondsRest, TimeUnit.MILLISECONDS) - val diffInMillisecondsForUnit = unit.toMillis(diff) - millisecondsRest -= diffInMillisecondsForUnit - result[unit] = diff - } - return result - } - - fun age(milliseconds: Long, useShortText: Boolean, rh: ResourceHelper): String { - val diff = computeDiff(0L, milliseconds) - var days = " " + rh.gs(R.string.days) + " " - var hours = " " + rh.gs(R.string.hours) + " " - var minutes = " " + rh.gs(R.string.unit_minutes) + " " - if (useShortText) { - days = rh.gs(R.string.shortday) - hours = rh.gs(R.string.shorthour) - minutes = rh.gs(R.string.shortminute) - } - var result = "" - if (diff.getOrDefault(TimeUnit.DAYS, -1) > 0) result += diff[TimeUnit.DAYS].toString() + days - if (diff.getOrDefault(TimeUnit.HOURS, -1) > 0) result += diff[TimeUnit.HOURS].toString() + hours - if (diff[TimeUnit.DAYS] == 0L) result += diff[TimeUnit.MINUTES].toString() + minutes - return result - } - - fun niceTimeScalar(time: Long, rh: ResourceHelper): String { - var t = time - var unit = rh.gs(R.string.unit_second) - t /= 1000 - if (t != 1L) unit = rh.gs(R.string.unit_seconds) - if (t > 59) { - unit = rh.gs(R.string.unit_minute) - t /= 60 - if (t != 1L) unit = rh.gs(R.string.unit_minutes) - if (t > 59) { - unit = rh.gs(R.string.unit_hour) - t /= 60 - if (t != 1L) unit = rh.gs(R.string.unit_hours) - if (t > 24) { - unit = rh.gs(R.string.unit_day) - t /= 24 - if (t != 1L) unit = rh.gs(R.string.unit_days) - if (t > 28) { - unit = rh.gs(R.string.unit_week) - t /= 7 - @Suppress("KotlinConstantConditions") - if (t != 1L) unit = rh.gs(R.string.unit_weeks) - } - } - } - } - //if (t != 1) unit = unit + "s"; //implemented plurality in every step, because in other languages plurality of time is not every time adding the same character - return qs(t.toDouble(), 0) + " " + unit - } - - fun qs(x: Double, numDigits: Int): String { - var digits = numDigits - if (digits == -1) { - digits = 0 - if ((x.toInt() % x == 0.0)) { - digits++ - if ((x.toInt() * 10 / 10).toDouble() != x) { - digits++ - if ((x.toInt() * 100 / 100).toDouble() != x) digits++ - } - } - } - if (dfs == null) { - val localDfs = DecimalFormatSymbols() - localDfs.decimalSeparator = '.' - dfs = localDfs // avoid race condition - } - val thisDf: DecimalFormat? - // use singleton if on ui thread otherwise allocate new as DecimalFormat is not thread safe - if (Thread.currentThread().id == 1L) { - if (df == null) { - val localDf = DecimalFormat("#", dfs) - localDf.minimumIntegerDigits = 1 - df = localDf // avoid race condition - } - thisDf = df - } else { - thisDf = DecimalFormat("#", dfs) - } - thisDf?.maximumFractionDigits = digits - return thisDf?.format(x) ?: "" - } - - fun formatHHMM(timeAsSeconds: Int): String { - val hour = timeAsSeconds / 60 / 60 - val minutes = (timeAsSeconds - hour * 60 * 60) / 60 - val df = DecimalFormat("00") - return df.format(hour.toLong()) + ":" + df.format(minutes.toLong()) - } + fun computeDiff(date1: Long, date2: Long): Map + fun age(milliseconds: Long, useShortText: Boolean, rh: ResourceHelper): String + fun niceTimeScalar(time: Long, rh: ResourceHelper): String + fun qs(x: Double, numDigits: Int): String + fun formatHHMM(timeAsSeconds: Int): String @RequiresApi(Build.VERSION_CODES.O) - fun timeZoneByOffset(offsetInMilliseconds: Long): TimeZone = - TimeZone.getTimeZone( - if (offsetInMilliseconds == 0L) ZoneId.of("UTC") - else ZoneId.getAvailableZoneIds() - .stream() - .map(ZoneId::of) - .filter { z -> z.rules.getOffset(Instant.now()).totalSeconds == ZoneOffset.ofHours((offsetInMilliseconds / 1000 / 3600).toInt()).totalSeconds } - .collect(Collectors.toList()) - .firstOrNull() ?: ZoneId.of("UTC") - ) - - fun timeStampToUtcDateMillis(timestamp: Long): Long { - val current = Calendar.getInstance().apply { timeInMillis = timestamp } - return Calendar.getInstance().apply { - set(Calendar.YEAR, current[Calendar.YEAR]) - set(Calendar.MONTH, current[Calendar.MONTH]) - set(Calendar.DAY_OF_MONTH, current[Calendar.DAY_OF_MONTH]) - }.timeInMillis - } - - fun mergeUtcDateToTimestamp(timestamp: Long, dateUtcMillis: Long): Long { - val selected = Calendar.getInstance().apply { timeInMillis = dateUtcMillis } - return Calendar.getInstance().apply { - timeInMillis = timestamp - set(Calendar.YEAR, selected[Calendar.YEAR]) - set(Calendar.MONTH, selected[Calendar.MONTH]) - set(Calendar.DAY_OF_MONTH, selected[Calendar.DAY_OF_MONTH]) - }.timeInMillis - } - - fun mergeHourMinuteToTimestamp(timestamp: Long, hour: Int, minute: Int, randomSecond: Boolean = false): Long { - return Calendar.getInstance().apply { - timeInMillis = timestamp - set(Calendar.HOUR_OF_DAY, hour) - set(Calendar.MINUTE, minute) - if (randomSecond) set(Calendar.SECOND, seconds++) - }.timeInMillis - } - - companion object { - - private val timeStrings = LongSparseArray() - private var seconds: Int = (SecureRandom().nextDouble() * 59.0).toInt() - - // singletons to avoid repeated allocation - private var dfs: DecimalFormatSymbols? = null - private var df: DecimalFormat? = null - } + fun timeZoneByOffset(offsetInMilliseconds: Long): TimeZone + fun timeStampToUtcDateMillis(timestamp: Long): Long + fun mergeUtcDateToTimestamp(timestamp: Long, dateUtcMillis: Long): Long + fun mergeHourMinuteToTimestamp(timestamp: Long, hour: Int, minute: Int, randomSecond: Boolean = false): Long } diff --git a/app-wear-shared/shared/src/main/res/drawable/detailed_dial.xml b/app-wear-shared/shared/src/main/res/drawable/detailed_dial.xml deleted file mode 100644 index fa5c92bde2..0000000000 --- a/app-wear-shared/shared/src/main/res/drawable/detailed_dial.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app-wear-shared/shared/src/main/res/drawable/hour_hand.xml b/app-wear-shared/shared/src/main/res/drawable/hour_hand.xml deleted file mode 100644 index c29364421b..0000000000 --- a/app-wear-shared/shared/src/main/res/drawable/hour_hand.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/app-wear-shared/shared/src/main/res/drawable/minute_hand.xml b/app-wear-shared/shared/src/main/res/drawable/minute_hand.xml deleted file mode 100644 index ae37534d34..0000000000 --- a/app-wear-shared/shared/src/main/res/drawable/minute_hand.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/app-wear-shared/shared/src/main/res/drawable/second_hand.xml b/app-wear-shared/shared/src/main/res/drawable/second_hand.xml deleted file mode 100644 index 96464ba7a8..0000000000 --- a/app-wear-shared/shared/src/main/res/drawable/second_hand.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - diff --git a/app-wear-shared/shared/src/main/res/drawable/simplified_dial.xml b/app-wear-shared/shared/src/main/res/drawable/simplified_dial.xml deleted file mode 100644 index 63cca01bfb..0000000000 --- a/app-wear-shared/shared/src/main/res/drawable/simplified_dial.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - diff --git a/app/src/main/java/info/nightscout/androidaps/di/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/di/AppComponent.kt index f96fd72374..26e84713c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/di/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/di/AppComponent.kt @@ -8,7 +8,6 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.danar.di.DanaRModule import info.nightscout.androidaps.insight.di.InsightDatabaseModule import info.nightscout.androidaps.insight.di.InsightModule -import info.nightscout.plugins.sync.di.OpenHumansModule import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule import info.nightscout.androidaps.plugins.pump.eopatch.dagger.EopatchModule import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule @@ -24,6 +23,7 @@ import info.nightscout.insulin.di.InsulinModule import info.nightscout.plugins.aps.di.ApsModule import info.nightscout.plugins.constraints.di.PluginsConstraintsModule import info.nightscout.plugins.di.PluginsModule +import info.nightscout.plugins.sync.di.OpenHumansModule import info.nightscout.plugins.sync.di.SyncModule import info.nightscout.pump.combo.di.ComboModule import info.nightscout.pump.combov2.di.ComboV2Module @@ -31,11 +31,9 @@ import info.nightscout.pump.common.di.PumpCommonModule import info.nightscout.pump.dana.di.DanaHistoryModule import info.nightscout.pump.dana.di.DanaModule import info.nightscout.pump.danars.di.DanaRSModule -import info.nightscout.pump.medtrum.di.MedtrumModule import info.nightscout.pump.diaconn.di.DiaconnG8Module +import info.nightscout.pump.medtrum.di.MedtrumModule import info.nightscout.pump.virtual.di.VirtualPumpModule -import info.nightscout.rx.di.RxModule -import info.nightscout.shared.di.SharedModule import info.nightscout.shared.impl.di.SharedImplModule import info.nightscout.source.di.SourceModule import info.nightscout.ui.di.UiModule @@ -62,8 +60,6 @@ import javax.inject.Singleton InsulinModule::class, OpenHumansModule::class, PluginsModule::class, - RxModule::class, - SharedModule::class, SharedImplModule::class, UiModule::class, ValidatorsModule::class, diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt rename to core/interfaces/src/main/java/info/nightscout/interfaces/utils/DecimalFormatter.kt diff --git a/core/ui/src/main/res/values-sw600dp/layout.xml b/core/ui/src/main/res/values-sw600dp/layout.xml new file mode 100644 index 0000000000..7c98f55487 --- /dev/null +++ b/core/ui/src/main/res/values-sw600dp/layout.xml @@ -0,0 +1,3 @@ + + true + \ No newline at end of file diff --git a/core/ui/src/main/res/values/layout.xml b/core/ui/src/main/res/values/layout.xml new file mode 100644 index 0000000000..57f058c48b --- /dev/null +++ b/core/ui/src/main/res/values/layout.xml @@ -0,0 +1,3 @@ + + false + \ No newline at end of file diff --git a/core/validators/build.gradle b/core/validators/build.gradle index b864f8f969..c96c66abe0 100644 --- a/core/validators/build.gradle +++ b/core/validators/build.gradle @@ -17,5 +17,6 @@ android { dependencies { implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') api "com.google.android.material:material:$material_version" } \ No newline at end of file diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/MaintenanceFragment.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/MaintenanceFragment.kt index a00baaca9b..544e8dd99a 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/MaintenanceFragment.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/MaintenanceFragment.kt @@ -32,7 +32,6 @@ import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventPreferenceChange import info.nightscout.rx.logging.AAPSLogger import info.nightscout.rx.logging.LTag -import info.nightscout.shared.extensions.runOnUiThread import info.nightscout.shared.extensions.toVisibility import info.nightscout.shared.interfaces.ResourceHelper import io.reactivex.rxjava3.core.Completable @@ -106,7 +105,7 @@ class MaintenanceFragment : DaggerFragment() { onError = { aapsLogger.error("Error clearing databases", it) }, onComplete = { rxBus.send(EventPreferenceChange(rh.gs(info.nightscout.core.utils.R.string.key_units))) - runOnUiThread { activity.recreate() } + info.nightscout.shared.extensions.runOnUiThread { activity.recreate() } } ) uel.log(Action.RESET_DATABASES, Sources.Maintenance) diff --git a/plugins/main/build.gradle b/plugins/main/build.gradle index 07d9669272..dfd942ee1a 100644 --- a/plugins/main/build.gradle +++ b/plugins/main/build.gradle @@ -16,6 +16,7 @@ android { dependencies { implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:graphview') diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewPlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewPlugin.kt index 6b514eb010..8094509045 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewPlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewPlugin.kt @@ -34,6 +34,7 @@ import info.nightscout.rx.events.EventNewHistoryData import info.nightscout.rx.events.EventPumpStatusChanged import info.nightscout.rx.events.EventUpdateOverviewCalcProgress import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -72,7 +73,7 @@ class OverviewPlugin @Inject constructor( private var disposable: CompositeDisposable = CompositeDisposable() - override val overviewBus = RxBus(aapsSchedulers, aapsLogger) + override val overviewBus = RxBusImpl(aapsSchedulers, aapsLogger) override fun addNotificationWithDialogResponse(id: Int, text: String, level: Int, @StringRes actionButtonId: Int, title: String, message: String) { rxBus.send( diff --git a/plugins/source/build.gradle b/plugins/source/build.gradle index 9a3c60f00b..92d8f31d79 100644 --- a/plugins/source/build.gradle +++ b/plugins/source/build.gradle @@ -17,6 +17,7 @@ android { dependencies { implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:interfaces') diff --git a/plugins/sync/build.gradle b/plugins/sync/build.gradle index 2551c23cb3..63f799cc9c 100644 --- a/plugins/sync/build.gradle +++ b/plugins/sync/build.gradle @@ -16,6 +16,7 @@ android { dependencies { implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:main') diff --git a/pump/combo/src/main/java/info/nightscout/pump/combo/ComboFragment.kt b/pump/combo/src/main/java/info/nightscout/pump/combo/ComboFragment.kt index 5273087c94..012713ed01 100644 --- a/pump/combo/src/main/java/info/nightscout/pump/combo/ComboFragment.kt +++ b/pump/combo/src/main/java/info/nightscout/pump/combo/ComboFragment.kt @@ -19,7 +19,6 @@ import info.nightscout.pump.combo.ruffyscripter.PumpState import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventQueueChanged -import info.nightscout.shared.extensions.runOnUiThread import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import io.reactivex.rxjava3.disposables.CompositeDisposable @@ -62,7 +61,7 @@ class ComboFragment : DaggerFragment() { binding.comboRefreshButton.isEnabled = false commandQueue.readStatus(rh.gs(info.nightscout.core.ui.R.string.user_request), object : Callback() { override fun run() { - runOnUiThread { binding.comboRefreshButton.isEnabled = true } + activity?.runOnUiThread { binding.comboRefreshButton.isEnabled = true } } }) } @@ -153,14 +152,17 @@ class ComboFragment : DaggerFragment() { binding.comboInsulinstate.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.defaultTextColor)) binding.comboInsulinstate.setTypeface(null, Typeface.NORMAL) } + PumpState.LOW -> { binding.comboInsulinstate.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.omniYellowColor)) binding.comboInsulinstate.setTypeface(null, Typeface.BOLD) } + PumpState.EMPTY -> { binding.comboInsulinstate.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.warningColor)) binding.comboInsulinstate.setTypeface(null, Typeface.BOLD) } + else -> { binding.comboInsulinstate.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.defaultTextColor)) binding.comboInsulinstate.setTypeface(null, Typeface.NORMAL) @@ -175,10 +177,12 @@ class ComboFragment : DaggerFragment() { binding.comboLastconnection.setText(R.string.combo_pump_connected_now) binding.comboLastconnection.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.defaultTextColor)) } + comboPlugin.pump.lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis() -> { binding.comboLastconnection.text = rh.gs(R.string.combo_no_pump_connection, min) binding.comboLastconnection.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.warningColor)) } + else -> { binding.comboLastconnection.text = minAgo binding.comboLastconnection.setTextColor(rh.gac(context, info.nightscout.core.ui.R.attr.defaultTextColor)) diff --git a/pump/diaconn/build.gradle b/pump/diaconn/build.gradle index 81af70ba94..f6e0c7934b 100644 --- a/pump/diaconn/build.gradle +++ b/pump/diaconn/build.gradle @@ -26,6 +26,7 @@ android { dependencies { implementation project(':app-wear-shared:shared') + implementation project(':app-wear-shared:shared-impl') implementation project(':core:libraries') implementation project(':core:interfaces') implementation project(':core:utils') diff --git a/pump/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt b/pump/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt index ae020d1ccf..9897559ff8 100644 --- a/pump/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt +++ b/pump/eopatch/src/main/java/info/nightscout/androidaps/plugins/pump/eopatch/alarm/AlarmRegistry.kt @@ -27,6 +27,7 @@ import javax.inject.Inject import javax.inject.Singleton interface IAlarmRegistry { + fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean = false): Maybe fun add(patchAeCodes: Set) fun remove(alarmCode: AlarmCode): Maybe @@ -34,11 +35,13 @@ interface IAlarmRegistry { @Singleton class AlarmRegistry @Inject constructor() : IAlarmRegistry { + @Inject lateinit var mContext: Context @Inject lateinit var pm: IPreferenceManager @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var dateUtil: DateUtil private lateinit var mOsAlarmManager: AlarmManager private var mDisposable: Disposable? = null @@ -49,19 +52,21 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { mDisposable = pm.observePatchLifeCycle() .observeOn(aapsSchedulers.main) .subscribe { - when(it){ + when (it) { PatchLifecycle.REMOVE_NEEDLE_CAP -> { val triggerAfter = pm.getPatchConfig().patchWakeupTimestamp + TimeUnit.HOURS.toMillis(1) - System.currentTimeMillis() compositeDisposable.add(add(AlarmCode.A020, triggerAfter).subscribe()) } - PatchLifecycle.ACTIVATED -> { + + PatchLifecycle.ACTIVATED -> { } - PatchLifecycle.SHUTDOWN -> { + + PatchLifecycle.SHUTDOWN -> { val sources = ArrayList>() sources.add(Maybe.just(true)) - pm.getAlarms().occurred.let{ occurredAlarms -> - if(occurredAlarms.isNotEmpty()){ + pm.getAlarms().occurred.let { occurredAlarms -> + if (occurredAlarms.isNotEmpty()) { occurredAlarms.keys.forEach { alarmCode -> sources.add( Maybe.just(alarmCode) @@ -71,30 +76,30 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { } } } - pm.getAlarms().registered.let{ registeredAlarms -> - if(registeredAlarms.isNotEmpty()){ + pm.getAlarms().registered.let { registeredAlarms -> + if (registeredAlarms.isNotEmpty()) { registeredAlarms.keys.forEach { alarmCode -> sources.add(remove(alarmCode)) } } } compositeDisposable.add(Maybe.concat(sources) - .subscribe { - pm.getAlarms().clear() - pm.flushAlarms() - } + .subscribe { + pm.getAlarms().clear() + pm.flushAlarms() + } ) } - else -> Unit + else -> Unit } } } override fun add(alarmCode: AlarmCode, triggerAfter: Long, isFirst: Boolean): Maybe { - if(pm.getAlarms().occurred.containsKey(alarmCode)){ + if (pm.getAlarms().occurred.containsKey(alarmCode)) { return Maybe.just(alarmCode) - }else { + } else { val triggerTimeMilli = System.currentTimeMillis() + triggerAfter pm.getAlarms().register(alarmCode, triggerAfter) pm.flushAlarms() @@ -109,11 +114,11 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { override fun add(patchAeCodes: Set) { compositeDisposable.add( Observable.fromIterable(patchAeCodes) - .filter{patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.aeValue) != null} - .observeOn(aapsSchedulers.main) - .filter { aeCodes -> AlarmCode.findByPatchAeCode(aeCodes.aeValue) != null } - .flatMapMaybe{aeCodeResponse -> add(AlarmCode.findByPatchAeCode(aeCodeResponse.aeValue)!!, 0L, true)} - .subscribe() + .filter { patchAeCodeItem -> AlarmCode.findByPatchAeCode(patchAeCodeItem.aeValue) != null } + .observeOn(aapsSchedulers.main) + .filter { aeCodes -> AlarmCode.findByPatchAeCode(aeCodes.aeValue) != null } + .flatMapMaybe { aeCodeResponse -> add(AlarmCode.findByPatchAeCode(aeCodeResponse.aeValue)!!, 0L, true) } + .subscribe() ) } @@ -121,21 +126,21 @@ class AlarmRegistry @Inject constructor() : IAlarmRegistry { return Maybe.fromCallable { cancelOsAlarmInternal(alarmCode) val pendingIntent = createPendingIntent(alarmCode, 0) - aapsLogger.debug("[${alarmCode}] OS Alarm added. ${DateUtil(mContext).toISOString(triggerTime)}") + aapsLogger.debug("[${alarmCode}] OS Alarm added. ${dateUtil.toISOString(triggerTime)}") mOsAlarmManager.setAlarmClock(AlarmClockInfo(triggerTime, pendingIntent), pendingIntent) alarmCode } } override fun remove(alarmCode: AlarmCode): Maybe { - return if(pm.getAlarms().registered.containsKey(alarmCode)) { + return if (pm.getAlarms().registered.containsKey(alarmCode)) { cancelOsAlarms(alarmCode) .doOnSuccess { pm.getAlarms().unregister(alarmCode) pm.flushAlarms() } .map { alarmCode } - }else{ + } else { Maybe.just(alarmCode) } } diff --git a/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt b/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt index 3ce25b2115..1dfda4ffc1 100644 --- a/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt +++ b/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.Omnipod import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordDao import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.AAPSLoggerTest import org.junit.Before import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test diff --git a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/endecrypt/EnDecryptTest.kt b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/endecrypt/EnDecryptTest.kt index 735938a9e8..d8ef9a4200 100644 --- a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/endecrypt/EnDecryptTest.kt +++ b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/endecrypt/EnDecryptTest.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.endecry import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.core.utils.toHex -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.AAPSLoggerTest import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.spongycastle.util.encoders.Hex diff --git a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/KeyExchangeTest.kt b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/KeyExchangeTest.kt index 43a71e621c..0b95e71c27 100644 --- a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/KeyExchangeTest.kt +++ b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/KeyExchangeTest.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.Rand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.X25519KeyGenerator import info.nightscout.core.utils.toHex import info.nightscout.interfaces.Config -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.AAPSLoggerTest import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test diff --git a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessageTest.kt b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessageTest.kt index d8871467bf..c399939cd3 100644 --- a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessageTest.kt +++ b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessageTest.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.session import info.nightscout.core.utils.toHex -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.AAPSLoggerTest import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.spongycastle.util.encoders.Hex diff --git a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/MilenageTest.kt b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/MilenageTest.kt index ad82492289..2c7914eb24 100644 --- a/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/MilenageTest.kt +++ b/pump/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/MilenageTest.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.session import info.nightscout.core.utils.toHex import info.nightscout.interfaces.Config -import info.nightscout.rx.logging.AAPSLoggerTest +import info.nightscout.sharedtests.AAPSLoggerTest import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test diff --git a/pump/omnipod-eros/build.gradle b/pump/omnipod-eros/build.gradle index c3ff28071f..7974db371f 100644 --- a/pump/omnipod-eros/build.gradle +++ b/pump/omnipod-eros/build.gradle @@ -37,6 +37,8 @@ dependencies { implementation project(':pump:rileylink') implementation project(':pump:omnipod-common') + testImplementation project(':app-wear-shared:shared-impl') + api "androidx.room:room-ktx:$room_version" api "androidx.room:room-runtime:$room_version" api "androidx.room:room-rxjava3:$room_version" diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt index 782ecc7604..9d63fafec5 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.manager import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FirmwareVersion import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.sharedPreferences.SP import info.nightscout.sharedtests.TestBase +import info.nightscout.sharedtests.rx.TestAapsSchedulers import org.joda.time.DateTime import org.joda.time.DateTimeUtils import org.joda.time.DateTimeZone @@ -19,7 +19,7 @@ class AapsErosPodStateManagerTest : TestBase() { @Mock lateinit var sp: SP - private val rxBus = RxBus(TestAapsSchedulers(), aapsLogger) + private val rxBus = RxBusImpl(TestAapsSchedulers(), aapsLogger) @Test fun times() { val timeZone = DateTimeZone.UTC diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt index 014b247cc8..a4b8295bbd 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt @@ -6,8 +6,6 @@ import dagger.Module import dagger.Provides import dagger.android.HasAndroidInjector import info.nightscout.androidaps.WearApp -import info.nightscout.rx.di.RxModule -import info.nightscout.shared.di.SharedModule import info.nightscout.shared.impl.di.SharedImplModule import kotlinx.datetime.Clock @@ -16,8 +14,6 @@ import kotlinx.datetime.Clock includes = [ WearModule.AppBindings::class, WearActivitiesModule::class, - RxModule::class, - SharedModule::class, SharedImplModule::class ] ) diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt index cfb1765d17..f3f5d7ddba 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CustomWatchface.kt @@ -35,15 +35,15 @@ import info.nightscout.androidaps.watchfaces.utils.BaseWatchFace import info.nightscout.rx.logging.LTag import info.nightscout.rx.weardata.CUSTOM_VERSION import info.nightscout.rx.weardata.CwfData -import info.nightscout.rx.weardata.ResFileMap -import info.nightscout.rx.weardata.CwfResDataMap import info.nightscout.rx.weardata.CwfMetadataKey import info.nightscout.rx.weardata.CwfMetadataMap -import info.nightscout.rx.weardata.ResData -import info.nightscout.rx.weardata.ResFormat +import info.nightscout.rx.weardata.CwfResDataMap import info.nightscout.rx.weardata.EventData import info.nightscout.rx.weardata.JsonKeyValues import info.nightscout.rx.weardata.JsonKeys.* +import info.nightscout.rx.weardata.ResData +import info.nightscout.rx.weardata.ResFileMap +import info.nightscout.rx.weardata.ResFormat import info.nightscout.rx.weardata.ViewKeys import info.nightscout.rx.weardata.ZipWatchfaceFormat import info.nightscout.shared.extensions.toVisibility @@ -208,7 +208,7 @@ class CustomWatchface : BaseWatchFace() { it.clearColorFilter() view.setImageDrawable(it) } ?: apply { - view.setImageDrawable(id.defaultDrawable?.let {resources.getDrawable(it)}) + view.setImageDrawable(id.defaultDrawable?.let { resources.getDrawable(it) }) if (viewJson.has(COLOR.key)) view.setColorFilter(getColor(viewJson.optString(COLOR.key))) else @@ -217,7 +217,7 @@ class CustomWatchface : BaseWatchFace() { } } - } ?:apply { + } ?: apply { view.visibility = View.GONE if (view is TextView) { view.text = "" @@ -301,7 +301,7 @@ class CustomWatchface : BaseWatchFace() { } val metadataMap = ZipWatchfaceFormat.loadMetadata(json) val drawableDataMap: CwfResDataMap = mutableMapOf() - getResourceByteArray(info.nightscout.shared.R.drawable.watchface_custom)?.let { + getResourceByteArray(info.nightscout.shared.impl.R.drawable.watchface_custom)?.let { drawableDataMap[ResFileMap.CUSTOM_WATCHFACE.fileName] = ResData(it, ResFormat.PNG) } return EventData.ActionSetCustomWatchface(CwfData(json.toString(4), metadataMap, drawableDataMap)) @@ -394,7 +394,7 @@ class CustomWatchface : BaseWatchFace() { @StringRes val pref: Int?, @IdRes val defaultDrawable: Int?, val customDrawable: ResFileMap?, - val customHigh:ResFileMap?, + val customHigh: ResFileMap?, val customLow: ResFileMap? ) { @@ -402,7 +402,7 @@ class CustomWatchface : BaseWatchFace() { ViewKeys.BACKGROUND.key, R.id.background, null, - info.nightscout.shared.R.drawable.background, + info.nightscout.shared.impl.R.drawable.background, ResFileMap.BACKGROUND, ResFileMap.BACKGROUND_HIGH, ResFileMap.BACKGROUND_LOW @@ -448,7 +448,7 @@ class CustomWatchface : BaseWatchFace() { ViewKeys.COVER_PLATE.key, R.id.cover_plate, null, - info.nightscout.shared.R.drawable.simplified_dial, + info.nightscout.shared.impl.R.drawable.simplified_dial, ResFileMap.COVER_PLATE, ResFileMap.COVER_PLATE_HIGH, ResFileMap.COVER_PLATE_LOW @@ -457,7 +457,7 @@ class CustomWatchface : BaseWatchFace() { ViewKeys.HOUR_HAND.key, R.id.hour_hand, null, - info.nightscout.shared.R.drawable.hour_hand, + info.nightscout.shared.impl.R.drawable.hour_hand, ResFileMap.HOUR_HAND, ResFileMap.HOUR_HAND_HIGH, ResFileMap.HOUR_HAND_LOW @@ -466,7 +466,7 @@ class CustomWatchface : BaseWatchFace() { ViewKeys.MINUTE_HAND.key, R.id.minute_hand, null, - info.nightscout.shared.R.drawable.minute_hand, + info.nightscout.shared.impl.R.drawable.minute_hand, ResFileMap.MINUTE_HAND, ResFileMap.MINUTE_HAND_HIGH, ResFileMap.MINUTE_HAND_LOW @@ -475,7 +475,7 @@ class CustomWatchface : BaseWatchFace() { ViewKeys.SECOND_HAND.key, R.id.second_hand, R.string.key_show_seconds, - info.nightscout.shared.R.drawable.second_hand, + info.nightscout.shared.impl.R.drawable.second_hand, ResFileMap.SECOND_HAND, ResFileMap.SECOND_HAND_HIGH, ResFileMap.SECOND_HAND_LOW @@ -491,16 +491,25 @@ class CustomWatchface : BaseWatchFace() { fun drawable(resources: Resources, drawableDataMap: CwfResDataMap, sgvLevel: Long): Drawable? = customDrawable?.let { cd -> when (sgvLevel) { - 1L -> { customHigh?.let {drawableDataMap[customHigh.fileName]}?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) } - 0L -> { drawableDataMap[cd.fileName]?.toDrawable(resources) } - -1L -> { customLow?.let {drawableDataMap[customLow.fileName]}?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) } + 1L -> { + customHigh?.let { drawableDataMap[customHigh.fileName] }?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) + } + + 0L -> { + drawableDataMap[cd.fileName]?.toDrawable(resources) + } + + -1L -> { + customLow?.let { drawableDataMap[customLow.fileName] }?.toDrawable(resources) ?: drawableDataMap[cd.fileName]?.toDrawable(resources) + } + else -> drawableDataMap[cd.fileName]?.toDrawable(resources) } } } } -private enum class TrendArrowMap(val symbol: String, @DrawableRes val icon: Int,val customDrawable: ResFileMap?) { +private enum class TrendArrowMap(val symbol: String, @DrawableRes val icon: Int, val customDrawable: ResFileMap?) { NONE("??", R.drawable.ic_invalid, ResFileMap.ARROW_NONE), TRIPLE_UP("X", R.drawable.ic_doubleup, ResFileMap.ARROW_DOUBLE_UP), DOUBLE_UP("\u21c8", R.drawable.ic_doubleup, ResFileMap.ARROW_DOUBLE_UP), @@ -515,8 +524,8 @@ private enum class TrendArrowMap(val symbol: String, @DrawableRes val icon: Int, companion object { fun drawable(direction: String?, resources: Resources, drawableDataMap: CwfResDataMap): Drawable { - val arrow = values().firstOrNull { it.symbol == direction } ?:NONE - return arrow.customDrawable?. let {drawableDataMap[arrow.customDrawable.fileName]}?.toDrawable(resources) ?:resources.getDrawable(arrow.icon) + val arrow = values().firstOrNull { it.symbol == direction } ?: NONE + return arrow.customDrawable?.let { drawableDataMap[arrow.customDrawable.fileName] }?.toDrawable(resources) ?: resources.getDrawable(arrow.icon) } } @@ -558,7 +567,7 @@ private enum class FontMap(val key: String, var font: Typeface, @FontRes val fon resDataMap.filter { (_, resData) -> resData.format == ResFormat.TTF || resData.format == ResFormat.OTF }.forEach { (key, resData) -> - customFonts[key.lowercase()] = resData.toTypeface() ?:Typeface.DEFAULT + customFonts[key.lowercase()] = resData.toTypeface() ?: Typeface.DEFAULT } } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt index b9db42cdd9..8cac6aecc7 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -7,16 +7,13 @@ import android.support.wearable.watchface.WatchFaceStyle import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout -import android.widget.TextView import androidx.core.content.ContextCompat import androidx.viewbinding.ViewBinding import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.ActivityDigitalstyleBinding -import info.nightscout.shared.extensions.toVisibility import info.nightscout.androidaps.watchfaces.utils.BaseWatchFace import info.nightscout.rx.logging.LTag - class DigitalStyleWatchface : BaseWatchFace() { private lateinit var binding: ActivityDigitalstyleBinding diff --git a/wear/src/test/java/info/nightscout/androidaps/heartrate/HeartRateListenerTest.kt b/wear/src/test/java/info/nightscout/androidaps/heartrate/HeartRateListenerTest.kt index 7b542b1afc..10d734a525 100644 --- a/wear/src/test/java/info/nightscout/androidaps/heartrate/HeartRateListenerTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/heartrate/HeartRateListenerTest.kt @@ -4,8 +4,8 @@ import android.content.Context import android.hardware.Sensor import android.hardware.SensorManager import info.nightscout.rx.AapsSchedulers -import info.nightscout.rx.logging.AAPSLoggerTest import info.nightscout.rx.weardata.EventData.ActionHeartRate +import info.nightscout.sharedtests.AAPSLoggerTest import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.disposables.Disposable import org.junit.jupiter.api.AfterEach @@ -22,8 +22,9 @@ import org.mockito.Mockito.`when` import java.util.concurrent.TimeUnit internal class HeartRateListenerTest { + private val aapsLogger = AAPSLoggerTest() - private val aapsSchedulers = object: AapsSchedulers { + private val aapsSchedulers = object : AapsSchedulers { override val main: Scheduler = mock(Scheduler::class.java) override val io: Scheduler = mock(Scheduler::class.java) override val cpu: Scheduler = mock(Scheduler::class.java) @@ -35,11 +36,15 @@ internal class HeartRateListenerTest { private fun create(timestampMillis: Long): HeartRateListener { val ctx = mock(Context::class.java) - `when`(aapsSchedulers.io.schedulePeriodicallyDirect( - any(), eq(60_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS))).thenReturn(schedule) + `when`( + aapsSchedulers.io.schedulePeriodicallyDirect( + any(), eq(60_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS) + ) + ).thenReturn(schedule) val listener = HeartRateListener(ctx, aapsLogger, aapsSchedulers, timestampMillis) verify(aapsSchedulers.io).schedulePeriodicallyDirect( - any(), eq(60_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS)) + any(), eq(60_000L), eq(60_000L), eq(TimeUnit.MILLISECONDS) + ) listener.sendHeartRate = { hr -> heartRates.add(hr) } return listener } @@ -49,10 +54,11 @@ internal class HeartRateListenerTest { timestamp: Long, heartRate: Int, sensorType: Int? = Sensor.TYPE_HEART_RATE, - accuracy: Int = SensorManager.SENSOR_STATUS_ACCURACY_HIGH) { + accuracy: Int = SensorManager.SENSOR_STATUS_ACCURACY_HIGH + ) { listener.onSensorChanged(sensorType, accuracy, timestamp, floatArrayOf(heartRate.toFloat())) } - + @BeforeEach fun before() { heartRates.clear() @@ -66,7 +72,7 @@ internal class HeartRateListenerTest { Mockito.verifyNoInteractions(aapsSchedulers.newThread) verify(schedule).dispose() } - + @Test fun onSensorChanged() { val start = System.currentTimeMillis() @@ -95,7 +101,7 @@ internal class HeartRateListenerTest { sendSensorEvent(listener, start, 80) assertEquals(0, heartRates.size) assertEquals(80, listener.currentHeartRateBpm) - sendSensorEvent(listener, start + d1,100) + sendSensorEvent(listener, start + d1, 100) assertEquals(0, heartRates.size) assertEquals(100, listener.currentHeartRateBpm) @@ -117,7 +123,7 @@ internal class HeartRateListenerTest { listener.send(start + d1) assertEquals(1, heartRates.size) - sendSensorEvent(listener, start + d1,100) + sendSensorEvent(listener, start + d1, 100) assertEquals(1, heartRates.size) listener.send(start + d2) assertEquals(2, heartRates.size) From ebcea9eed85888af4e98de24fc5192345c6a0565 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 18 Sep 2023 23:28:32 +0200 Subject: [PATCH 3/9] simplify :core:utils --- core/interfaces/build.gradle | 5 +++- .../nightscout/core/utils/ActionModeHelper.kt | 1 + .../info/nightscout/core/utils/CryptoUtil.kt | 1 + .../core/utils/extensions/HtmlString.kt | 0 .../core/utils/extensions/JSONObjectExt.kt | 0 .../core/utils/fabric/FabricPrivacy.kt | 0 .../core/utils/worker/LoggingWorker.kt | 0 .../src/main/res/drawable/ic_sort.xml | 0 .../src/main/res/drawable/ic_trash.xml | 0 .../src/main/res/menu/menu_actions.xml | 0 .../main/res/menu/menu_delete_selection.xml | 0 core/main/src/main/res/values/strings.xml | 5 ++++ core/utils/build.gradle | 5 +++- .../core/utils/receivers/DataWorkerStorage.kt | 2 +- .../src/main/res/values-af-rZA/strings.xml | 2 -- .../src/main/res/values-bg-rBG/strings.xml | 8 ------ .../src/main/res/values-ca-rES/strings.xml | 2 -- .../src/main/res/values-cs-rCZ/strings.xml | 8 ------ .../src/main/res/values-da-rDK/strings.xml | 8 ------ .../src/main/res/values-de-rDE/strings.xml | 8 ------ .../src/main/res/values-el-rGR/strings.xml | 8 ------ .../src/main/res/values-es-rES/strings.xml | 8 ------ .../src/main/res/values-fr-rFR/strings.xml | 8 ------ .../src/main/res/values-ga-rIE/strings.xml | 2 -- .../src/main/res/values-hr-rHR/strings.xml | 2 -- .../src/main/res/values-hu-rHU/strings.xml | 2 -- .../src/main/res/values-it-rIT/strings.xml | 8 ------ .../src/main/res/values-iw-rIL/strings.xml | 8 ------ .../src/main/res/values-ja-rJP/strings.xml | 2 -- .../src/main/res/values-ko-rKR/strings.xml | 8 ------ .../src/main/res/values-lt-rLT/strings.xml | 8 ------ .../src/main/res/values-nl-rNL/strings.xml | 8 ------ .../src/main/res/values-no-rNO/strings.xml | 8 ------ .../src/main/res/values-pl-rPL/strings.xml | 8 ------ .../src/main/res/values-pt-rBR/strings.xml | 8 ------ .../src/main/res/values-pt-rPT/strings.xml | 8 ------ .../src/main/res/values-ro-rRO/strings.xml | 4 --- .../src/main/res/values-ru-rRU/strings.xml | 8 ------ .../src/main/res/values-sk-rSK/strings.xml | 8 ------ .../src/main/res/values-sr-rCS/strings.xml | 2 -- .../src/main/res/values-sv-rSE/strings.xml | 8 ------ .../src/main/res/values-tr-rTR/strings.xml | 8 ------ .../src/main/res/values-uk-rUA/strings.xml | 2 -- .../src/main/res/values-zh-rCN/strings.xml | 8 ------ core/utils/src/main/res/values/strings.xml | 9 ------- crowdin.yml | 2 -- database/entities/build.gradle | 3 +++ plugins/constraints/build.gradle | 1 + pump/combo/build.gradle | 1 + pump/dana/build.gradle | 1 + pump/danar/build.gradle | 1 + pump/danars/build.gradle | 1 + pump/diaconn/build.gradle | 1 + pump/eopatch/build.gradle | 1 + pump/medtronic/build.gradle | 1 + .../pump/medtrum/services/MedtrumService.kt | 25 ++++++++++++++++--- pump/omnipod-dash/build.gradle | 1 + pump/omnipod-eros/build.gradle | 1 + pump/pump-common/build.gradle | 1 + .../ui/activities/QuickWizardListActivity.kt | 2 +- wear/build.gradle | 1 + 61 files changed, 54 insertions(+), 206 deletions(-) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt (99%) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/CryptoUtil.kt (99%) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/extensions/HtmlString.kt (100%) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/extensions/JSONObjectExt.kt (100%) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/fabric/FabricPrivacy.kt (100%) rename core/{utils => main}/src/main/java/info/nightscout/core/utils/worker/LoggingWorker.kt (100%) rename core/{utils => main}/src/main/res/drawable/ic_sort.xml (100%) rename core/{utils => main}/src/main/res/drawable/ic_trash.xml (100%) rename core/{utils => main}/src/main/res/menu/menu_actions.xml (100%) rename core/{utils => main}/src/main/res/menu/menu_delete_selection.xml (100%) delete mode 100644 core/utils/src/main/res/values-af-rZA/strings.xml delete mode 100644 core/utils/src/main/res/values-bg-rBG/strings.xml delete mode 100644 core/utils/src/main/res/values-ca-rES/strings.xml delete mode 100644 core/utils/src/main/res/values-cs-rCZ/strings.xml delete mode 100644 core/utils/src/main/res/values-da-rDK/strings.xml delete mode 100644 core/utils/src/main/res/values-de-rDE/strings.xml delete mode 100644 core/utils/src/main/res/values-el-rGR/strings.xml delete mode 100644 core/utils/src/main/res/values-es-rES/strings.xml delete mode 100644 core/utils/src/main/res/values-fr-rFR/strings.xml delete mode 100644 core/utils/src/main/res/values-ga-rIE/strings.xml delete mode 100644 core/utils/src/main/res/values-hr-rHR/strings.xml delete mode 100644 core/utils/src/main/res/values-hu-rHU/strings.xml delete mode 100644 core/utils/src/main/res/values-it-rIT/strings.xml delete mode 100644 core/utils/src/main/res/values-iw-rIL/strings.xml delete mode 100644 core/utils/src/main/res/values-ja-rJP/strings.xml delete mode 100644 core/utils/src/main/res/values-ko-rKR/strings.xml delete mode 100644 core/utils/src/main/res/values-lt-rLT/strings.xml delete mode 100644 core/utils/src/main/res/values-nl-rNL/strings.xml delete mode 100644 core/utils/src/main/res/values-no-rNO/strings.xml delete mode 100644 core/utils/src/main/res/values-pl-rPL/strings.xml delete mode 100644 core/utils/src/main/res/values-pt-rBR/strings.xml delete mode 100644 core/utils/src/main/res/values-pt-rPT/strings.xml delete mode 100644 core/utils/src/main/res/values-ro-rRO/strings.xml delete mode 100644 core/utils/src/main/res/values-ru-rRU/strings.xml delete mode 100644 core/utils/src/main/res/values-sk-rSK/strings.xml delete mode 100644 core/utils/src/main/res/values-sr-rCS/strings.xml delete mode 100644 core/utils/src/main/res/values-sv-rSE/strings.xml delete mode 100644 core/utils/src/main/res/values-tr-rTR/strings.xml delete mode 100644 core/utils/src/main/res/values-uk-rUA/strings.xml delete mode 100644 core/utils/src/main/res/values-zh-rCN/strings.xml delete mode 100644 core/utils/src/main/res/values/strings.xml diff --git a/core/interfaces/build.gradle b/core/interfaces/build.gradle index 4cd1087543..5edc89c128 100644 --- a/core/interfaces/build.gradle +++ b/core/interfaces/build.gradle @@ -13,6 +13,9 @@ apply from: "${project.rootDir}/core/main/android_module_dependencies.gradle" android { namespace 'info.nightscout.interfaces' + defaultConfig { + minSdkVersion 25 // for wear + } } dependencies { @@ -22,7 +25,7 @@ dependencies { // (ResourceHelper, AAPSLogger interface) implementation project(':app-wear-shared:shared') implementation project(':database:entities') - // implementation project(':core:ns-sdk') + // implementation project(':core:ns-sdk') api "androidx.appcompat:appcompat:$appcompat_version" diff --git a/core/utils/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt b/core/main/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt similarity index 99% rename from core/utils/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt rename to core/main/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt index fc79710d7f..856d2309ee 100644 --- a/core/utils/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt +++ b/core/main/src/main/java/info/nightscout/core/utils/ActionModeHelper.kt @@ -8,6 +8,7 @@ import android.view.MenuItem import androidx.core.view.MenuCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity +import info.nightscout.core.main.R import info.nightscout.shared.interfaces.ResourceHelper class ActionModeHelper(val rh: ResourceHelper, val activity: FragmentActivity?, val fragment: Fragment?) { diff --git a/core/utils/src/main/java/info/nightscout/core/utils/CryptoUtil.kt b/core/main/src/main/java/info/nightscout/core/utils/CryptoUtil.kt similarity index 99% rename from core/utils/src/main/java/info/nightscout/core/utils/CryptoUtil.kt rename to core/main/src/main/java/info/nightscout/core/utils/CryptoUtil.kt index d8a44d6c9f..c2dfaca653 100644 --- a/core/utils/src/main/java/info/nightscout/core/utils/CryptoUtil.kt +++ b/core/main/src/main/java/info/nightscout/core/utils/CryptoUtil.kt @@ -23,6 +23,7 @@ class CryptoUtil @Inject constructor( ) { companion object { + private const val IV_LENGTH_BYTE = 12 private const val TAG_LENGTH_BIT = 128 private const val AES_KEY_SIZE_BIT = 256 diff --git a/core/utils/src/main/java/info/nightscout/core/utils/extensions/HtmlString.kt b/core/main/src/main/java/info/nightscout/core/utils/extensions/HtmlString.kt similarity index 100% rename from core/utils/src/main/java/info/nightscout/core/utils/extensions/HtmlString.kt rename to core/main/src/main/java/info/nightscout/core/utils/extensions/HtmlString.kt diff --git a/core/utils/src/main/java/info/nightscout/core/utils/extensions/JSONObjectExt.kt b/core/main/src/main/java/info/nightscout/core/utils/extensions/JSONObjectExt.kt similarity index 100% rename from core/utils/src/main/java/info/nightscout/core/utils/extensions/JSONObjectExt.kt rename to core/main/src/main/java/info/nightscout/core/utils/extensions/JSONObjectExt.kt diff --git a/core/utils/src/main/java/info/nightscout/core/utils/fabric/FabricPrivacy.kt b/core/main/src/main/java/info/nightscout/core/utils/fabric/FabricPrivacy.kt similarity index 100% rename from core/utils/src/main/java/info/nightscout/core/utils/fabric/FabricPrivacy.kt rename to core/main/src/main/java/info/nightscout/core/utils/fabric/FabricPrivacy.kt diff --git a/core/utils/src/main/java/info/nightscout/core/utils/worker/LoggingWorker.kt b/core/main/src/main/java/info/nightscout/core/utils/worker/LoggingWorker.kt similarity index 100% rename from core/utils/src/main/java/info/nightscout/core/utils/worker/LoggingWorker.kt rename to core/main/src/main/java/info/nightscout/core/utils/worker/LoggingWorker.kt diff --git a/core/utils/src/main/res/drawable/ic_sort.xml b/core/main/src/main/res/drawable/ic_sort.xml similarity index 100% rename from core/utils/src/main/res/drawable/ic_sort.xml rename to core/main/src/main/res/drawable/ic_sort.xml diff --git a/core/utils/src/main/res/drawable/ic_trash.xml b/core/main/src/main/res/drawable/ic_trash.xml similarity index 100% rename from core/utils/src/main/res/drawable/ic_trash.xml rename to core/main/src/main/res/drawable/ic_trash.xml diff --git a/core/utils/src/main/res/menu/menu_actions.xml b/core/main/src/main/res/menu/menu_actions.xml similarity index 100% rename from core/utils/src/main/res/menu/menu_actions.xml rename to core/main/src/main/res/menu/menu_actions.xml diff --git a/core/utils/src/main/res/menu/menu_delete_selection.xml b/core/main/src/main/res/menu/menu_delete_selection.xml similarity index 100% rename from core/utils/src/main/res/menu/menu_delete_selection.xml rename to core/main/src/main/res/menu/menu_delete_selection.xml diff --git a/core/main/src/main/res/values/strings.xml b/core/main/src/main/res/values/strings.xml index cf363cea0c..f77b9c1073 100644 --- a/core/main/src/main/res/values/strings.xml +++ b/core/main/src/main/res/values/strings.xml @@ -2,4 +2,9 @@ %1$d g + %1$d selected + Remove Items + Sort Items + Remove Selected Items + Sort \ No newline at end of file diff --git a/core/utils/build.gradle b/core/utils/build.gradle index 510fda7ba3..6ef6d4a957 100644 --- a/core/utils/build.gradle +++ b/core/utils/build.gradle @@ -18,7 +18,10 @@ android { dependencies { - implementation project(':app-wear-shared:shared') + api "com.google.dagger:dagger-android:$dagger_version" + api "com.google.dagger:dagger-android-support:$dagger_version" + + api "net.danlew:android.joda:$joda_version" //Firebase api platform('com.google.firebase:firebase-bom:32.3.1') diff --git a/core/utils/src/main/java/info/nightscout/core/utils/receivers/DataWorkerStorage.kt b/core/utils/src/main/java/info/nightscout/core/utils/receivers/DataWorkerStorage.kt index 83649bb3fb..ada8a89f39 100644 --- a/core/utils/src/main/java/info/nightscout/core/utils/receivers/DataWorkerStorage.kt +++ b/core/utils/src/main/java/info/nightscout/core/utils/receivers/DataWorkerStorage.kt @@ -2,11 +2,11 @@ package info.nightscout.core.utils.receivers import android.content.Context import android.os.Bundle +import androidx.annotation.OpenForTesting import androidx.work.Data import androidx.work.ExistingWorkPolicy import androidx.work.OneTimeWorkRequest import androidx.work.WorkManager -import info.nightscout.annotations.OpenForTesting import org.json.JSONArray import org.json.JSONObject import javax.inject.Inject diff --git a/core/utils/src/main/res/values-af-rZA/strings.xml b/core/utils/src/main/res/values-af-rZA/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-af-rZA/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-bg-rBG/strings.xml b/core/utils/src/main/res/values-bg-rBG/strings.xml deleted file mode 100644 index 055832ff21..0000000000 --- a/core/utils/src/main/res/values-bg-rBG/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d избрано - Премахни артикули - Подреди артикули - Премахнете избраните елементи - Сортирай - diff --git a/core/utils/src/main/res/values-ca-rES/strings.xml b/core/utils/src/main/res/values-ca-rES/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-ca-rES/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-cs-rCZ/strings.xml b/core/utils/src/main/res/values-cs-rCZ/strings.xml deleted file mode 100644 index 32aff04aef..0000000000 --- a/core/utils/src/main/res/values-cs-rCZ/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - Vybráno: %1$d - Odebrat položky - Seřadit položky - Odebrat vybrané položky - Seřadit - diff --git a/core/utils/src/main/res/values-da-rDK/strings.xml b/core/utils/src/main/res/values-da-rDK/strings.xml deleted file mode 100644 index e042c690b2..0000000000 --- a/core/utils/src/main/res/values-da-rDK/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d valgt - Fjern Emner - Sortér Emner - Fjern valgte emner - Sortér - diff --git a/core/utils/src/main/res/values-de-rDE/strings.xml b/core/utils/src/main/res/values-de-rDE/strings.xml deleted file mode 100644 index 9dee92e75d..0000000000 --- a/core/utils/src/main/res/values-de-rDE/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d ausgewählt - Entferne Elemente - Sortiere Elemente - lösche ausgewählte Elemente - Sortieren - diff --git a/core/utils/src/main/res/values-el-rGR/strings.xml b/core/utils/src/main/res/values-el-rGR/strings.xml deleted file mode 100644 index 763ea6bd89..0000000000 --- a/core/utils/src/main/res/values-el-rGR/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - Επιλέχθηκε %1$d - Αφαίρεση Στοιχείων - Ταξινόμηση Στοιχείων - Αφαίρεση Επιλεγμένων Στοιχείων - Ταξινόμηση - diff --git a/core/utils/src/main/res/values-es-rES/strings.xml b/core/utils/src/main/res/values-es-rES/strings.xml deleted file mode 100644 index 51cc673ea7..0000000000 --- a/core/utils/src/main/res/values-es-rES/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d seleccionado - Eliminar elementos - Ordenar elementos - Eliminar elementos seleccionados - Ordenar - diff --git a/core/utils/src/main/res/values-fr-rFR/strings.xml b/core/utils/src/main/res/values-fr-rFR/strings.xml deleted file mode 100644 index 43e2479768..0000000000 --- a/core/utils/src/main/res/values-fr-rFR/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d séléctionné(s) - Supprimer les éléments - Trier les éléments - Supprimer les éléments sélectionnés - Trier - diff --git a/core/utils/src/main/res/values-ga-rIE/strings.xml b/core/utils/src/main/res/values-ga-rIE/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-ga-rIE/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-hr-rHR/strings.xml b/core/utils/src/main/res/values-hr-rHR/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-hr-rHR/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-hu-rHU/strings.xml b/core/utils/src/main/res/values-hu-rHU/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-hu-rHU/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-it-rIT/strings.xml b/core/utils/src/main/res/values-it-rIT/strings.xml deleted file mode 100644 index 7f0600516d..0000000000 --- a/core/utils/src/main/res/values-it-rIT/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d selezionati - Rimuovi elementi - Ordina elementi - Rimuovi elementi selezionati - Ordina - diff --git a/core/utils/src/main/res/values-iw-rIL/strings.xml b/core/utils/src/main/res/values-iw-rIL/strings.xml deleted file mode 100644 index c59cf26f89..0000000000 --- a/core/utils/src/main/res/values-iw-rIL/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d נבחרו - פריטים שהוסרו - מיין פריטים - הסר פריטים נבחרים - מיין - diff --git a/core/utils/src/main/res/values-ja-rJP/strings.xml b/core/utils/src/main/res/values-ja-rJP/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-ja-rJP/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-ko-rKR/strings.xml b/core/utils/src/main/res/values-ko-rKR/strings.xml deleted file mode 100644 index 3ec59ea4e0..0000000000 --- a/core/utils/src/main/res/values-ko-rKR/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d 선택됨 - 항목 제거하기 - 항목 분류하기 - 선택된 항목 제거하기 - 분류 - diff --git a/core/utils/src/main/res/values-lt-rLT/strings.xml b/core/utils/src/main/res/values-lt-rLT/strings.xml deleted file mode 100644 index 4bda3c08d1..0000000000 --- a/core/utils/src/main/res/values-lt-rLT/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d pasirinkta - Pašalinti elementus - Rūšiuoti elementus - Pašalinti pasirinktus elementus - Rūšiuoti - diff --git a/core/utils/src/main/res/values-nl-rNL/strings.xml b/core/utils/src/main/res/values-nl-rNL/strings.xml deleted file mode 100644 index 4132f90084..0000000000 --- a/core/utils/src/main/res/values-nl-rNL/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d geselecteerd - Items verwijderen - Sorteer items - Verwijder geselecteerde items - Sorteren - diff --git a/core/utils/src/main/res/values-no-rNO/strings.xml b/core/utils/src/main/res/values-no-rNO/strings.xml deleted file mode 100644 index 4ce3dd56a6..0000000000 --- a/core/utils/src/main/res/values-no-rNO/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d valgt - Slett elementer - Sorter elementer - Slett valgte elementer - Sorter - diff --git a/core/utils/src/main/res/values-pl-rPL/strings.xml b/core/utils/src/main/res/values-pl-rPL/strings.xml deleted file mode 100644 index fa05f69045..0000000000 --- a/core/utils/src/main/res/values-pl-rPL/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - Wybrany %1$d - Usuń pozycje - Sortuj pozycje - Usuń zaznaczone pozycje - Sortuj - diff --git a/core/utils/src/main/res/values-pt-rBR/strings.xml b/core/utils/src/main/res/values-pt-rBR/strings.xml deleted file mode 100644 index 8759ee512a..0000000000 --- a/core/utils/src/main/res/values-pt-rBR/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - Selecionado %1$d - Remover itens - Ordenar Itens - Remover itens selecionados - Ordenar - diff --git a/core/utils/src/main/res/values-pt-rPT/strings.xml b/core/utils/src/main/res/values-pt-rPT/strings.xml deleted file mode 100644 index 607a8d88f2..0000000000 --- a/core/utils/src/main/res/values-pt-rPT/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d selecionados - Remover itens - Ordenar itens - Remover itens selecionados - Ordenar - diff --git a/core/utils/src/main/res/values-ro-rRO/strings.xml b/core/utils/src/main/res/values-ro-rRO/strings.xml deleted file mode 100644 index 06b7aac6f5..0000000000 --- a/core/utils/src/main/res/values-ro-rRO/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - Sortează - diff --git a/core/utils/src/main/res/values-ru-rRU/strings.xml b/core/utils/src/main/res/values-ru-rRU/strings.xml deleted file mode 100644 index bc6a581292..0000000000 --- a/core/utils/src/main/res/values-ru-rRU/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - Выбрано: %1$d - Удалить элементы - Сортировать элементы - Удалить выбранные элементы - Сортировать - diff --git a/core/utils/src/main/res/values-sk-rSK/strings.xml b/core/utils/src/main/res/values-sk-rSK/strings.xml deleted file mode 100644 index 12d8e52129..0000000000 --- a/core/utils/src/main/res/values-sk-rSK/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d vybraných - Odstrániť položky - Zoradiť položky - Odstrániť vybrané položky - Zoradiť - diff --git a/core/utils/src/main/res/values-sr-rCS/strings.xml b/core/utils/src/main/res/values-sr-rCS/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-sr-rCS/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-sv-rSE/strings.xml b/core/utils/src/main/res/values-sv-rSE/strings.xml deleted file mode 100644 index b009e2f499..0000000000 --- a/core/utils/src/main/res/values-sv-rSE/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d valt - Ta bort objekt - Sortera objekt - Ta bort valda objekt - Sortera - diff --git a/core/utils/src/main/res/values-tr-rTR/strings.xml b/core/utils/src/main/res/values-tr-rTR/strings.xml deleted file mode 100644 index cd3a6d5e1d..0000000000 --- a/core/utils/src/main/res/values-tr-rTR/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - %1$d seçildi - Öğeleri kaldır - Öğeleri Sırala - Seçilen öğeleri kaldır - Sırala - diff --git a/core/utils/src/main/res/values-uk-rUA/strings.xml b/core/utils/src/main/res/values-uk-rUA/strings.xml deleted file mode 100644 index 3ea04e700d..0000000000 --- a/core/utils/src/main/res/values-uk-rUA/strings.xml +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/core/utils/src/main/res/values-zh-rCN/strings.xml b/core/utils/src/main/res/values-zh-rCN/strings.xml deleted file mode 100644 index b32b881107..0000000000 --- a/core/utils/src/main/res/values-zh-rCN/strings.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - 已选中 %1$d 项 - 删除项目 - 项目排序 - 删除选中项 - 排序 - diff --git a/core/utils/src/main/res/values/strings.xml b/core/utils/src/main/res/values/strings.xml deleted file mode 100644 index 246de562c5..0000000000 --- a/core/utils/src/main/res/values/strings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - %1$d selected - Remove Items - Sort Items - Remove Selected Items - Sort - - \ No newline at end of file diff --git a/crowdin.yml b/crowdin.yml index 34356aa616..b5640c7a63 100644 --- a/crowdin.yml +++ b/crowdin.yml @@ -41,8 +41,6 @@ files: translation: /core/main/src/main/res/values-%android_code%/strings.xml - source: /core/interfaces/src/main/res/values/strings.xml translation: /core/interfaces/src/main/res/values-%android_code%/strings.xml - - source: /core/utils/src/main/res/values/strings.xml - translation: /core/utils/src/main/res/values-%android_code%/strings.xml - source: /core/ui/src/main/res/values/protection.xml translation: /core/ui/src/main/res/values-%android_code%/protection.xml - source: /core/validators/src/main/res/values/validator.xml diff --git a/database/entities/build.gradle b/database/entities/build.gradle index 918416feb0..e951e0cbdd 100644 --- a/database/entities/build.gradle +++ b/database/entities/build.gradle @@ -12,6 +12,9 @@ apply from: "${project.rootDir}/core/main/test_dependencies.gradle" android { namespace 'info.nightscout.database.entities' + defaultConfig { + minSdkVersion 25 // for wear + } buildFeatures { buildConfig = false diff --git a/plugins/constraints/build.gradle b/plugins/constraints/build.gradle index 6ae2a5865b..05ab1fb88a 100644 --- a/plugins/constraints/build.gradle +++ b/plugins/constraints/build.gradle @@ -18,6 +18,7 @@ android { dependencies { implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') implementation project(':core:validators') diff --git a/pump/combo/build.gradle b/pump/combo/build.gradle index ff6202ea71..d558afb179 100644 --- a/pump/combo/build.gradle +++ b/pump/combo/build.gradle @@ -21,6 +21,7 @@ android { dependencies { implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') implementation project(':app-wear-shared:shared') diff --git a/pump/dana/build.gradle b/pump/dana/build.gradle index aedc35aff8..67222caccc 100644 --- a/pump/dana/build.gradle +++ b/pump/dana/build.gradle @@ -27,6 +27,7 @@ android { dependencies { implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') implementation project(':app-wear-shared:shared') diff --git a/pump/danar/build.gradle b/pump/danar/build.gradle index 5a29590ff8..a3ad984f0c 100644 --- a/pump/danar/build.gradle +++ b/pump/danar/build.gradle @@ -18,6 +18,7 @@ dependencies { implementation 'androidx.media3:media3-common:1.1.1' implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') implementation project(':core:validators') diff --git a/pump/danars/build.gradle b/pump/danars/build.gradle index ceed13054c..dc6142ef05 100644 --- a/pump/danars/build.gradle +++ b/pump/danars/build.gradle @@ -31,6 +31,7 @@ android { dependencies { implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') implementation project(':core:validators') diff --git a/pump/diaconn/build.gradle b/pump/diaconn/build.gradle index f6e0c7934b..0d0b4f6d38 100644 --- a/pump/diaconn/build.gradle +++ b/pump/diaconn/build.gradle @@ -29,6 +29,7 @@ dependencies { implementation project(':app-wear-shared:shared-impl') implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') diff --git a/pump/eopatch/build.gradle b/pump/eopatch/build.gradle index 224acbbcac..a2baa19b46 100644 --- a/pump/eopatch/build.gradle +++ b/pump/eopatch/build.gradle @@ -24,6 +24,7 @@ dependencies { implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') diff --git a/pump/medtronic/build.gradle b/pump/medtronic/build.gradle index b44c33cb15..c724e23a24 100644 --- a/pump/medtronic/build.gradle +++ b/pump/medtronic/build.gradle @@ -18,6 +18,7 @@ dependencies { implementation project(':core:libraries') implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') implementation project(':core:validators') diff --git a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt index 569ed1b587..a94d4dde69 100644 --- a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt +++ b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt @@ -14,11 +14,10 @@ import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction +import info.nightscout.interfaces.pump.BolusProgressData import info.nightscout.interfaces.pump.DetailedBolusInfo import info.nightscout.interfaces.pump.DetailedBolusInfoStorage -import info.nightscout.interfaces.pump.BolusProgressData import info.nightscout.interfaces.pump.PumpSync -import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.Callback import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction @@ -28,7 +27,27 @@ import info.nightscout.pump.medtrum.R import info.nightscout.pump.medtrum.code.ConnectionState import info.nightscout.pump.medtrum.comm.enums.AlarmState import info.nightscout.pump.medtrum.comm.enums.MedtrumPumpState -import info.nightscout.pump.medtrum.comm.packets.* +import info.nightscout.pump.medtrum.comm.packets.ActivatePacket +import info.nightscout.pump.medtrum.comm.packets.AuthorizePacket +import info.nightscout.pump.medtrum.comm.packets.CancelBolusPacket +import info.nightscout.pump.medtrum.comm.packets.CancelTempBasalPacket +import info.nightscout.pump.medtrum.comm.packets.ClearPumpAlarmPacket +import info.nightscout.pump.medtrum.comm.packets.GetDeviceTypePacket +import info.nightscout.pump.medtrum.comm.packets.GetRecordPacket +import info.nightscout.pump.medtrum.comm.packets.GetTimePacket +import info.nightscout.pump.medtrum.comm.packets.MedtrumPacket +import info.nightscout.pump.medtrum.comm.packets.NotificationPacket +import info.nightscout.pump.medtrum.comm.packets.PrimePacket +import info.nightscout.pump.medtrum.comm.packets.ResumePumpPacket +import info.nightscout.pump.medtrum.comm.packets.SetBasalProfilePacket +import info.nightscout.pump.medtrum.comm.packets.SetBolusPacket +import info.nightscout.pump.medtrum.comm.packets.SetPatchPacket +import info.nightscout.pump.medtrum.comm.packets.SetTempBasalPacket +import info.nightscout.pump.medtrum.comm.packets.SetTimePacket +import info.nightscout.pump.medtrum.comm.packets.SetTimeZonePacket +import info.nightscout.pump.medtrum.comm.packets.StopPatchPacket +import info.nightscout.pump.medtrum.comm.packets.SubscribePacket +import info.nightscout.pump.medtrum.comm.packets.SynchronizePacket import info.nightscout.pump.medtrum.util.MedtrumSnUtil import info.nightscout.rx.AapsSchedulers import info.nightscout.rx.bus.RxBus diff --git a/pump/omnipod-dash/build.gradle b/pump/omnipod-dash/build.gradle index 72c2bd4d84..f36ba39872 100644 --- a/pump/omnipod-dash/build.gradle +++ b/pump/omnipod-dash/build.gradle @@ -30,6 +30,7 @@ dependencies { implementation project(':app-wear-shared:shared') implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') implementation project(':core:validators') diff --git a/pump/omnipod-eros/build.gradle b/pump/omnipod-eros/build.gradle index 7974db371f..6407f5b795 100644 --- a/pump/omnipod-eros/build.gradle +++ b/pump/omnipod-eros/build.gradle @@ -30,6 +30,7 @@ dependencies { implementation project(':app-wear-shared:shared') implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') implementation project(':core:validators') diff --git a/pump/pump-common/build.gradle b/pump/pump-common/build.gradle index ba01b3436f..9112c217ad 100644 --- a/pump/pump-common/build.gradle +++ b/pump/pump-common/build.gradle @@ -16,6 +16,7 @@ android { dependencies { implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:utils') implementation project(':app-wear-shared:shared') diff --git a/ui/src/main/java/info/nightscout/ui/activities/QuickWizardListActivity.kt b/ui/src/main/java/info/nightscout/ui/activities/QuickWizardListActivity.kt index d89a38c967..dd80707759 100644 --- a/ui/src/main/java/info/nightscout/ui/activities/QuickWizardListActivity.kt +++ b/ui/src/main/java/info/nightscout/ui/activities/QuickWizardListActivity.kt @@ -156,7 +156,7 @@ class QuickWizardListActivity : TranslatedDaggerAppCompatActivity(), OnStartDrag } addMenuProvider(object : MenuProvider { override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) { - menuInflater.inflate(info.nightscout.core.utils.R.menu.menu_actions, menu) + menuInflater.inflate(info.nightscout.core.main.R.menu.menu_actions, menu) } override fun onMenuItemSelected(menuItem: MenuItem): Boolean = diff --git a/wear/build.gradle b/wear/build.gradle index a7638ba42d..d8d8690654 100644 --- a/wear/build.gradle +++ b/wear/build.gradle @@ -95,6 +95,7 @@ allprojects { dependencies { implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') + implementation project(':core:interfaces') implementation fileTree(include: ['*.jar'], dir: 'libs') From 8be62d4e3eb111df8d832185185e0791ddebb775 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 18 Sep 2023 23:58:37 +0200 Subject: [PATCH 4/9] eliminate :app-wear-shared:shared --- app-wear-shared/shared-impl/build.gradle | 2 +- .../nightscout/shared/utils/DateUtilImpl.kt | 2 +- app-wear-shared/shared-tests/build.gradle | 1 - app-wear-shared/shared/.gitignore | 1 - app-wear-shared/shared/build.gradle | 44 -------- app-wear-shared/shared/consumer-rules.pro | 0 app-wear-shared/shared/proguard-rules.pro | 21 ---- .../shared/src/main/AndroidManifest.xml | 4 - .../src/main/res/values-af-rZA/strings.xml | 25 ----- .../src/main/res/values-bg-rBG/strings.xml | 92 ---------------- .../src/main/res/values-ca-rES/strings.xml | 28 ----- .../src/main/res/values-cs-rCZ/strings.xml | 95 ---------------- .../src/main/res/values-da-rDK/strings.xml | 93 ---------------- .../src/main/res/values-de-rDE/strings.xml | 92 ---------------- .../src/main/res/values-el-rGR/strings.xml | 95 ---------------- .../src/main/res/values-es-rES/strings.xml | 95 ---------------- .../src/main/res/values-fr-rFR/strings.xml | 93 ---------------- .../src/main/res/values-ga-rIE/strings.xml | 26 ----- .../src/main/res/values-hr-rHR/strings.xml | 14 --- .../src/main/res/values-hu-rHU/strings.xml | 9 -- .../src/main/res/values-it-rIT/strings.xml | 93 ---------------- .../src/main/res/values-iw-rIL/strings.xml | 54 --------- .../src/main/res/values-ja-rJP/strings.xml | 37 ------- .../src/main/res/values-ko-rKR/strings.xml | 92 ---------------- .../src/main/res/values-lt-rLT/strings.xml | 93 ---------------- .../src/main/res/values-nl-rNL/strings.xml | 95 ---------------- .../src/main/res/values-no-rNO/strings.xml | 95 ---------------- .../src/main/res/values-pl-rPL/strings.xml | 93 ---------------- .../src/main/res/values-pt-rBR/strings.xml | 60 ---------- .../src/main/res/values-pt-rPT/strings.xml | 91 ---------------- .../src/main/res/values-ro-rRO/strings.xml | 28 ----- .../src/main/res/values-ru-rRU/strings.xml | 84 -------------- .../src/main/res/values-sk-rSK/strings.xml | 95 ---------------- .../src/main/res/values-sr-rCS/strings.xml | 6 - .../src/main/res/values-sv-rSE/strings.xml | 90 --------------- .../src/main/res/values-tr-rTR/strings.xml | 95 ---------------- .../src/main/res/values-uk-rUA/strings.xml | 6 - .../src/main/res/values-zh-rCN/strings.xml | 37 ------- .../shared/src/main/res/values/strings.xml | 103 ------------------ app/build.gradle | 1 - core/interfaces/build.gradle | 33 ++++-- .../nightscout/annotations/OpenForTesting.kt | 0 .../annotations/InterfacesOpenForTesting.kt | 15 --- .../info/nightscout/interfaces/GlucoseUnit.kt | 0 .../interfaces/plugin/PluginDescription.kt | 4 +- .../java/info/nightscout/rx/AapsSchedulers.kt | 0 .../main/java/info/nightscout/rx/bus/RxBus.kt | 0 .../java/info/nightscout/rx/events/Event.kt | 0 .../rx/events/EventAcceptOpenLoopChange.kt | 0 .../info/nightscout/rx/events/EventAppExit.kt | 0 .../rx/events/EventAppInitialized.kt | 0 .../EventAutosensCalculationFinished.kt | 0 .../nightscout/rx/events/EventBTChange.kt | 0 .../rx/events/EventBucketedDataCreated.kt | 0 .../rx/events/EventChargingState.kt | 0 .../rx/events/EventConfigBuilderChange.kt | 0 .../rx/events/EventCustomActionsChanged.kt | 0 .../events/EventCustomCalculationFinished.kt | 0 .../rx/events/EventDanaRSyncStatus.kt | 0 .../rx/events/EventDeviceStatusChange.kt | 0 .../rx/events/EventDiaconnG8PumpLogReset.kt | 0 .../EventDismissBolusProgressIfRunning.kt | 0 .../rx/events/EventDismissNotification.kt | 0 .../EventEffectiveProfileSwitchChanged.kt | 0 .../rx/events/EventExtendedBolusChange.kt | 0 .../rx/events/EventFoodDatabaseChanged.kt | 0 .../rx/events/EventInitializationChanged.kt | 0 .../rx/events/EventLocalProfileChanged.kt | 0 .../info/nightscout/rx/events/EventLoop.kt | 0 .../rx/events/EventLoopUpdateGui.kt | 0 .../rx/events/EventMobileDataToWear.kt | 0 .../nightscout/rx/events/EventMobileToWear.kt | 0 .../rx/events/EventNSClientNewLog.kt | 0 .../rx/events/EventNSClientRestart.kt | 0 .../rx/events/EventNetworkChange.kt | 0 .../info/nightscout/rx/events/EventNewBG.kt | 0 .../rx/events/EventNewHistoryData.kt | 0 .../rx/events/EventNewOpenLoopNotification.kt | 0 .../nightscout/rx/events/EventNtpStatus.kt | 0 .../rx/events/EventOfflineChange.kt | 0 .../rx/events/EventOverviewBolusProgress.kt | 0 .../rx/events/EventPreferenceChange.kt | 0 .../rx/events/EventProfileStoreChanged.kt | 0 .../rx/events/EventProfileSwitchChanged.kt | 0 .../rx/events/EventPumpStatusChanged.kt | 2 +- .../nightscout/rx/events/EventQueueChanged.kt | 0 .../nightscout/rx/events/EventRebuildTabs.kt | 0 .../rx/events/EventRefreshButtonState.kt | 0 .../rx/events/EventRefreshOverview.kt | 0 .../nightscout/rx/events/EventSWRLStatus.kt | 0 .../nightscout/rx/events/EventSWSyncStatus.kt | 0 .../nightscout/rx/events/EventSWUpdate.kt | 0 .../info/nightscout/rx/events/EventScale.kt | 0 .../info/nightscout/rx/events/EventStatus.kt | 0 .../rx/events/EventTempBasalChange.kt | 0 .../rx/events/EventTempTargetChange.kt | 0 .../nightscout/rx/events/EventThemeSwitch.kt | 0 .../rx/events/EventTherapyEventChange.kt | 0 .../rx/events/EventTreatmentChange.kt | 0 .../nightscout/rx/events/EventUpdateGui.kt | 0 .../events/EventUpdateOverviewCalcProgress.kt | 0 .../rx/events/EventUpdateOverviewGraph.kt | 0 .../rx/events/EventUpdateOverviewIobCob.kt | 0 .../events/EventUpdateOverviewSensitivity.kt | 0 .../rx/events/EventWearCwfExported.kt | 0 .../rx/events/EventWearDataToMobile.kt | 0 .../nightscout/rx/events/EventWearToMobile.kt | 0 .../rx/events/EventWearUpdateGui.kt | 0 .../nightscout/rx/events/EventXdripNewLog.kt | 0 .../java/info/nightscout/rx/interfaces/L.kt | 0 .../nightscout/rx/interfaces/LogElement.kt | 0 .../info/nightscout/rx/logging/AAPSLogger.kt | 0 .../nightscout/rx/logging/BundleLogger.kt | 0 .../java/info/nightscout/rx/logging/LTag.kt | 0 .../rx/weardata/CustomWatchfaceFormat.kt | 2 +- .../info/nightscout/rx/weardata/EventData.kt | 0 .../java/info/nightscout/shared/SafeParse.kt | 0 .../nightscout/shared/extensions/UIUtils.kt | 0 .../shared/interfaces/ProfileUtil.kt | 0 .../shared/interfaces/ResourceHelper.kt | 0 .../nightscout/shared/sharedPreferences/SP.kt | 0 .../info/nightscout/shared/utils/DateUtil.kt | 0 .../java/info/nightscout/shared/utils/T.kt | 0 .../src/main/res/values/strings.xml | 100 +++++++++++++++++ .../src/main/res/values/wear_paths.xml | 0 .../nightscout/annotations/OpenForTesting.kt | 0 .../annotations/InterfacesOpenForTesting.kt | 8 -- .../info/nightscout/rx/RxSchedulerRule.kt | 0 .../nightscout/rx/weardata/EventDataTest.kt | 0 .../info/nightscout/shared/SafeParseTest.kt | 0 core/main/build.gradle | 1 - .../data/EffectiveProfileSwitchDataPoint.kt | 2 +- .../nightscout/core/utils/DateUtilTest.kt | 2 +- core/validators/build.gradle | 2 +- implementation/build.gradle | 1 - .../implementation/TranslatorImpl.kt | 4 +- .../implementation/stats/TddCalculatorImpl.kt | 2 +- .../implementation/stats/TirImpl.kt | 2 +- .../stats/TotalDailyDoseExtension.kt | 2 +- .../UserEntryPresentationHelperImpl.kt | 4 +- insight/build.gradle | 1 - .../pump/insight/LocalInsightFragment.java | 2 +- plugins/aps/build.gradle | 1 - plugins/automation/build.gradle | 3 +- .../automation/triggers/TriggerBolusAgo.kt | 2 +- plugins/configuration/build.gradle | 1 - .../CustomWatchfaceImportListActivity.kt | 2 +- plugins/constraints/build.gradle | 1 - plugins/insulin/build.gradle | 1 - plugins/main/build.gradle | 1 - .../general/overview/ui/StatusLightHandler.kt | 8 +- .../wear/wearintegration/DataHandlerMobile.kt | 4 +- .../DataLayerListenerServiceMobile.kt | 4 +- plugins/sensitivity/build.gradle | 1 - plugins/smoothing/build.gradle | 1 - plugins/source/build.gradle | 1 - plugins/sync/build.gradle | 1 - .../sync/nsclientV3/NSClientV3Plugin.kt | 4 +- pump/combo/build.gradle | 1 - pump/combov2/build.gradle | 7 +- .../pump/combov2/ComboV2Fragment.kt | 4 +- pump/dana/build.gradle | 1 - .../info/nightscout/pump/dana/DanaFragment.kt | 2 +- pump/danar/build.gradle | 4 +- .../services/DanaRv2ExecutionService.java | 2 +- pump/danars/build.gradle | 1 - .../pump/danars/services/DanaRSService.kt | 2 +- pump/diaconn/build.gradle | 1 - .../pump/diaconn/DiaconnG8Fragment.kt | 2 +- .../pump/diaconn/service/DiaconnG8Service.kt | 2 +- pump/eopatch/build.gradle | 3 +- pump/medtronic/build.gradle | 1 - .../pump/medtronic/MedtronicFragment.kt | 2 +- pump/medtrum/build.gradle | 3 +- .../ui/viewmodel/MedtrumOverviewViewModel.kt | 2 +- pump/omnipod-common/build.gradle | 1 - pump/omnipod-dash/build.gradle | 1 - pump/omnipod-eros/build.gradle | 1 - pump/pump-common/build.gradle | 1 - .../pump/common/defs/PumpDriverState.kt | 4 +- pump/rileylink/build.gradle | 1 - pump/virtual/build.gradle | 1 - settings.gradle | 1 - ui/build.gradle | 1 - .../ui/activityMonitor/ActivityMonitor.kt | 2 +- .../info/nightscout/ui/dialogs/CarbsDialog.kt | 2 +- .../nightscout/ui/dialogs/InsulinDialog.kt | 12 +- .../ui/dialogs/ProfileViewerDialog.kt | 2 +- wear/build.gradle | 1 - .../androidaps/comm/DataHandlerWear.kt | 4 +- .../comm/DataLayerListenerServiceWear.kt | 4 +- .../interaction/actions/BolusActivity.kt | 4 +- .../interaction/actions/TreatmentActivity.kt | 4 +- .../androidaps/watchfaces/CustomWatchface.kt | 6 +- workflow/build.gradle | 5 +- 195 files changed, 192 insertions(+), 2311 deletions(-) delete mode 100644 app-wear-shared/shared/.gitignore delete mode 100644 app-wear-shared/shared/build.gradle delete mode 100644 app-wear-shared/shared/consumer-rules.pro delete mode 100644 app-wear-shared/shared/proguard-rules.pro delete mode 100644 app-wear-shared/shared/src/main/AndroidManifest.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-af-rZA/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-bg-rBG/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ca-rES/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-cs-rCZ/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-da-rDK/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-de-rDE/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-es-rES/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ga-rIE/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-hr-rHR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-hu-rHU/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-it-rIT/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-iw-rIL/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ja-rJP/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ko-rKR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-lt-rLT/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-no-rNO/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-pl-rPL/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-pt-rPT/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ro-rRO/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-sk-rSK/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-sr-rCS/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-sv-rSE/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-tr-rTR/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-uk-rUA/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values-zh-rCN/strings.xml delete mode 100644 app-wear-shared/shared/src/main/res/values/strings.xml rename {app-wear-shared/shared => core/interfaces}/src/debug/java/info/nightscout/annotations/OpenForTesting.kt (100%) delete mode 100644 core/interfaces/src/debug/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/AapsSchedulers.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/bus/RxBus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/Event.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventAcceptOpenLoopChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventAppExit.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventAppInitialized.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventAutosensCalculationFinished.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventBTChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventBucketedDataCreated.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventChargingState.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventConfigBuilderChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventCustomActionsChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventCustomCalculationFinished.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventDanaRSyncStatus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventDeviceStatusChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventDiaconnG8PumpLogReset.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventDismissBolusProgressIfRunning.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventDismissNotification.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventEffectiveProfileSwitchChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventExtendedBolusChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventFoodDatabaseChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventInitializationChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventLocalProfileChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventLoop.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventLoopUpdateGui.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventMobileDataToWear.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventMobileToWear.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNSClientNewLog.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNSClientRestart.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNetworkChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNewBG.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNewHistoryData.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNewOpenLoopNotification.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventNtpStatus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventOfflineChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventOverviewBolusProgress.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventPreferenceChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventProfileStoreChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventProfileSwitchChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt (97%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventQueueChanged.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventRebuildTabs.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventRefreshButtonState.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventRefreshOverview.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventSWRLStatus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventSWSyncStatus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventSWUpdate.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventScale.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventStatus.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventTempBasalChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventTempTargetChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventThemeSwitch.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventTherapyEventChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventTreatmentChange.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventUpdateGui.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventUpdateOverviewCalcProgress.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventUpdateOverviewGraph.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventUpdateOverviewIobCob.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventUpdateOverviewSensitivity.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventWearCwfExported.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventWearDataToMobile.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventWearToMobile.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventWearUpdateGui.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/events/EventXdripNewLog.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/interfaces/L.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/interfaces/LogElement.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/logging/AAPSLogger.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/logging/BundleLogger.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/logging/LTag.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt (99%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/rx/weardata/EventData.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/SafeParse.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/extensions/UIUtils.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/interfaces/ResourceHelper.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/sharedPreferences/SP.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/utils/DateUtil.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/java/info/nightscout/shared/utils/T.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/main/res/values/wear_paths.xml (100%) rename {app-wear-shared/shared => core/interfaces}/src/release/java/info/nightscout/annotations/OpenForTesting.kt (100%) delete mode 100644 core/interfaces/src/release/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt rename {app-wear-shared/shared => core/interfaces}/src/test/java/info/nightscout/rx/RxSchedulerRule.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/test/java/info/nightscout/rx/weardata/EventDataTest.kt (100%) rename {app-wear-shared/shared => core/interfaces}/src/test/java/info/nightscout/shared/SafeParseTest.kt (100%) diff --git a/app-wear-shared/shared-impl/build.gradle b/app-wear-shared/shared-impl/build.gradle index f2c115b890..da83429250 100644 --- a/app-wear-shared/shared-impl/build.gradle +++ b/app-wear-shared/shared-impl/build.gradle @@ -21,5 +21,5 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') + implementation project(':core:interfaces') } \ No newline at end of file diff --git a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt index ee093019d6..579c21e60c 100644 --- a/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt +++ b/app-wear-shared/shared-impl/src/main/java/info/nightscout/shared/utils/DateUtilImpl.kt @@ -5,7 +5,7 @@ import android.os.Build import androidx.annotation.RequiresApi import androidx.collection.LongSparseArray import info.nightscout.annotations.OpenForTesting -import info.nightscout.shared.R +import info.nightscout.interfaces.R import info.nightscout.shared.SafeParse import info.nightscout.shared.interfaces.ResourceHelper import org.apache.commons.lang3.time.DateUtils.isSameDay diff --git a/app-wear-shared/shared-tests/build.gradle b/app-wear-shared/shared-tests/build.gradle index 9c4a8730fa..97a502c731 100644 --- a/app-wear-shared/shared-tests/build.gradle +++ b/app-wear-shared/shared-tests/build.gradle @@ -18,7 +18,6 @@ android { dependencies { implementation project(':database:entities') - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/app-wear-shared/shared/.gitignore b/app-wear-shared/shared/.gitignore deleted file mode 100644 index 42afabfd2a..0000000000 --- a/app-wear-shared/shared/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build \ No newline at end of file diff --git a/app-wear-shared/shared/build.gradle b/app-wear-shared/shared/build.gradle deleted file mode 100644 index c97de505bb..0000000000 --- a/app-wear-shared/shared/build.gradle +++ /dev/null @@ -1,44 +0,0 @@ -plugins { - id 'com.android.library' - id 'kotlin-android' - id 'kotlin-kapt' - id 'kotlinx-serialization' - id 'kotlin-allopen' -} - -apply from: "${project.rootDir}/core/main/android_dependencies.gradle" -apply from: "${project.rootDir}/core/main/android_module_dependencies.gradle" -apply from: "${project.rootDir}/core/main/allopen_dependencies.gradle" -apply from: "${project.rootDir}/core/main/test_dependencies.gradle" -apply from: "${project.rootDir}/core/main/jacoco_global.gradle" - -android { - - namespace 'info.nightscout.shared' - defaultConfig { - minSdkVersion 25 // for wear - } -} - -dependencies { - api "androidx.preference:preference-ktx:$preferencektx_version" - api "net.danlew:android.joda:$joda_version" - - api "com.google.dagger:dagger:$dagger_version" - api "com.google.dagger:dagger-android:$dagger_version" - api "com.google.dagger:dagger-android-support:$dagger_version" - - //Logger - api 'org.slf4j:slf4j-api:1.7.36' // 2.0.x breaks logging. Code change needed - api 'com.github.tony19:logback-android:2.0.0' - - api "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinx_serialization_version" - api "org.jetbrains.kotlinx:kotlinx-serialization-protobuf:$kotlinx_serialization_version" - api "com.caverock:androidsvg:$caverock_androidsvg_version" - api "org.apache.commons:commons-lang3:$commonslang3_version" - - //RxBus - api "io.reactivex.rxjava3:rxjava:$rxjava_version" - api "io.reactivex.rxjava3:rxkotlin:$rxkotlin_version" - api "io.reactivex.rxjava3:rxandroid:$rxandroid_version" -} \ No newline at end of file diff --git a/app-wear-shared/shared/consumer-rules.pro b/app-wear-shared/shared/consumer-rules.pro deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/app-wear-shared/shared/proguard-rules.pro b/app-wear-shared/shared/proguard-rules.pro deleted file mode 100644 index 481bb43481..0000000000 --- a/app-wear-shared/shared/proguard-rules.pro +++ /dev/null @@ -1,21 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/AndroidManifest.xml b/app-wear-shared/shared/src/main/AndroidManifest.xml deleted file mode 100644 index 44008a4332..0000000000 --- a/app-wear-shared/shared/src/main/AndroidManifest.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/res/values-af-rZA/strings.xml b/app-wear-shared/shared/src/main/res/values-af-rZA/strings.xml deleted file mode 100644 index 6f9ad74f9e..0000000000 --- a/app-wear-shared/shared/src/main/res/values-af-rZA/strings.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - h - dae - ure - sekonde - minuut - uur - dag - week - sekondes - minute - ure - dae - weke - m - d - - Koppel vir %1$d s - Handskudding - Gekoppel - Ontkoppel - - diff --git a/app-wear-shared/shared/src/main/res/values-bg-rBG/strings.xml b/app-wear-shared/shared/src/main/res/values-bg-rBG/strings.xml deleted file mode 100644 index e23a023f6b..0000000000 --- a/app-wear-shared/shared/src/main/res/values-bg-rBG/strings.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - преди %1$d мин - Преди %1$d минути - преди %1$.1f ч - преди %1$.1f дни - преди %1$.0f дни - за %1$.0f дни - за %1$.0f дни - ч - дни - часа - секунда - минута - час - ден - седмица - секунди - минути - часове - дни - седмици - м - д - По-късно днес - Утре - Днес - Вчера - - Свързване %1$d сек - Сдвояване - Свързана - Разкачане - Изчакване за разкачане - - Създадено: %1$s - Автор: %1$s - Име: %1$s - Име на файла: %1$s - Plugin версия: %1$s - Име: %1$s (%2$s) - Покажи IOB - Покажи подробен IOB - Покажи COB - Покажи Делта - Показвай подробна делта - Покажи средна делта - Покажи батерия на телефон - Покажи батерия на устройство - Покажи базал - Покажи Loop Статус - Покажи КЗ - Покажи BGI - Покажи делта стрелка - Покажи \"преди\" - Watchface по подразбиране, можете да изберете бутон ЕКСПОРТИРАНЕ НА WATCHFACE за създаване на шаблон - Watchface по подразбиране - Фоново изображение - Графики (КЗ, базал, прогнозни криви...) - Изображение над графика и под текстови полета - Свободен текст 1 - Свободен текст 2 - Свободен текст 3 - Свободен текст 4 - IOB надпис или IOB Общо (при подробен IOB) - IOB Общо или (Bolus_IOB|Basal_IOB) при подробен IOB - COB надпис - COB стойност - Краткоср. Δ - Средна делта (15мин) - Батерия на телефона (%) - Global loop батерия (%) - Базал - BGI стойност - Време (ЧЧ:MM или ЧЧ:MM:СС) - Час (ЧЧ) - Минути (MM) - Секунди (СС) - AM или PM - Ден от седмицата - Ден (ДД) - Месец (кратко) - Loop статус и \"преди\" - Делта стрелка - Последно получена КЗ преди минути - КЗ стойност - Изображение над текст (циферблат...) - Изображение на стрелка за часове (Аналогов часовник) - Изображение на стрелка за минути (Аналогов часовник) - Изображение на стрелка за секунди (Аналогов часовник) - diff --git a/app-wear-shared/shared/src/main/res/values-ca-rES/strings.xml b/app-wear-shared/shared/src/main/res/values-ca-rES/strings.xml deleted file mode 100644 index e2a9ff86bd..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ca-rES/strings.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - Fa %1$d m - Fa %1$.1f h - h - dies - hores - segon - minut - hora - dia - setmana - segons - minuts - hores - dies - setmanes - m - d - - Connectant %1$d s - Establint comunicació - Connectat - Desconnectant - S\'està esperant la desconnexió - - diff --git a/app-wear-shared/shared/src/main/res/values-cs-rCZ/strings.xml b/app-wear-shared/shared/src/main/res/values-cs-rCZ/strings.xml deleted file mode 100644 index 487005d290..0000000000 --- a/app-wear-shared/shared/src/main/res/values-cs-rCZ/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - před %1$d min - před %1$d minutamí - před %1$.1f h - Před %1$.1f dny - Před %1$.0f dny - za %1$.0f dní - za %1$.0f dní - h - dnů - hodin - sekund - minut - hodina - den - týden - sekund - minut - hodin - dní - týdnů - m - d - Později během dneška - Zítra - Dnes - Včera - - Připojování %1$d sec - Navazování spojení - Připojeno - Odpojuji - Čekám na odpojení - - Vytvořeno: %1$s - Autor: %1$s - Jméno %1$s - Název souboru: %1$s - Verze pluginu: %1$s - Jméno: %1$s (%2$s) - Informace: %1$s - Zobrazit IOB - Zobrazit detailní IOB - Zobrazit COB - Zobrazit deltu - Zobrazit detailní deltu - Zobrazit průměrnou deltu - Zobrazit stav baterie telefonu - Zobrazit stav baterie dalších zařízení - Zobrazit bazál - Zobrazit stav smyčky - Zobrazit glykémii - Zobrazit BGI - Zobrazit trendovou šipku - Zobrazit aktualizováno před - Zobrazit číslo týdne - Výchozí ciferník. Můžete kliknout na tlačítko EXPORTOVAT CIFERNÍK pro vygenerování šablony - Výchozí ciferník - Tapeta - Grafy (glykémie, bazály, křivky předpovědí...) - Obrázek před grafem a za textovými poli - Volný text 1 - Volný text 2 - Volný text 3 - Volný text 4 - Štítek IOB nebo suma IOB při zapnutých detailech - Suma IOB nebo (Bolus_IOB|Basal_IOB) při zapnutých detailech - Štítek COB - Hodnota COB - Krátkodobý průměr - Průměrný rozdíl glykémií (15min) - Baterie telefonu (%) - Baterie smyčky (%) - Bazální dávka - Hodnota BGI - Čas (HH:MM nebo HH:MM:SS) - Hodiny (HH) - Minuty (MM) - Sekundy (SS) - AM nebo PM - Jméno dne v týdnu - Den (DD) - Číslo týdne (ww) - Název měsíce (krátký) - Stav smyčky a čas - Trendová šipka - Před minutami pro poslední přijaté glykémie - Hodnota glykémie - Úvodní obrázek před textem (vytáčení...) - Obrázek hodinové ručičky (Analogové hodinky) - Obrázek minutové ručičky (Analogové hodinky) - Obrázek druhé ručičky (Analogové hodinky) - diff --git a/app-wear-shared/shared/src/main/res/values-da-rDK/strings.xml b/app-wear-shared/shared/src/main/res/values-da-rDK/strings.xml deleted file mode 100644 index f35084621c..0000000000 --- a/app-wear-shared/shared/src/main/res/values-da-rDK/strings.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - %1$d min. siden - %1$d minutter siden - %1$.1f t siden - %1$.1f dage siden - %1$.0f dage siden - om %1$.0f dage - om %1$.0f dage - t - dage - timer - sekund - minut - time - dag - uge - sekunder - minutter - timer - dage - uger - min - d - Senere i dag - I morgen - I dag - I går - - Opretter forbindelse i %1$d s - Forbindelse verificeres - Tilsuttet - Afbryder - Venter på afbrydelse - - Oprettet den: %1$s - Forfatter: %1$s - Navn: %1$s - Filnavn: %1$s - Plugin version: %1$s - Navn: %1$s (%2$s) - Oplysning: %1$s - Vis IOB - Vis detaljeret IOB - Vis COB - Vis Delta - Vis detaljeret Delta - Show GnsDelta - Vis Telefonbatteri - Vis Rig-batteri - Vis Basalrate - Vis Loop-status - Vis BS - Vis BSI - Vis Retningspil - Vis alder - Standard urskive, du kan klikke på EKSPORTÉR URSKIVE-knappen for at generere en skabelon - Standard Urskive - Baggrundsbillede - Grafer (BS, basal, prognoselinjer...) - Billede foran graf og bag tekstfelter - Fritekst 1 - Fri tekst 2 - Fri tekst 3 - Fri tekst 4 - IOB-etiket eller IOB-sum, hvis givet - IOB-sum eller (Bolus_IOB|Basal_IOB) hvis givet - COB-etiket - COB-værdi - Kort BG-delta - Gennemsnitlig BG-delta (15min) - Telefonbatteri (%) - Globalt loop batteri (%) - Basalrate - BGI-værdi - Tid (TT:MM eller TT:MM:SS) - Time (TT) - Minut (MM) - Sekund (SS) - AM eller PM - Navn på ugedag - Dag (DD) - Måned navn (kort) - Loop status og tid - Retningspil - Minutter siden sidst modtaget BS - BS-værdi - Dækbillede foran tekst (opkald...) - Billede af timeviser (Analogur) - Billede af minutviser (Analogur) - Billede af sekundviser (Analogur) - diff --git a/app-wear-shared/shared/src/main/res/values-de-rDE/strings.xml b/app-wear-shared/shared/src/main/res/values-de-rDE/strings.xml deleted file mode 100644 index 94321c069d..0000000000 --- a/app-wear-shared/shared/src/main/res/values-de-rDE/strings.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - vor %1$d Min. - vor %1$d Minuten - vor %1$.1f Stunde - vor %1$.1f Tagen - vor %1$.0f Tagen - in %1$.0f Tagen - in %1$.0f Tagen - h - Tage - Stunden - Sekunde - Minute - Stunde - Tag - Woche - Sekunden - Minuten - Stunden - Tage - Wochen - m - d - Später heute - Morgen - Heute - Gestern - - Verbindungsaufbau seit %1$d s - Handshaking - Verbunden - Verbindung wird getrennt - Warte auf Trennung der Verbindung - - Erstellt am: %1$s - Autor: %1$s - Name: %1$s - Dateiname: %1$s - Plugin-Version: %1$s - Name: %1$s (%2$s) - IOB anzeigen - Zeige detailliertes IOB - COB anzeigen - Abweichung anzeigen - Zeige detailliertes Delta - Durchschnittl. Abweichung anzeigen - Akkustand Smartphone - Akkustand Rig - Basalrate anzeigen - Loop Status anzeigen - BZ anzeigen - Zeige BGI - Trendpfeil anzeigen - Min. seit letztem Wert - Standard-Watchface, Du kannst auf den Knopf WATCHFACE exportieren drücken, um eine Vorlage zu generieren - Standard-Watchface - Hintergrundbild - Diagramme (BG, Basal, Vorhersage...) - Bild vor Graph und hinter Textfeldern - Freitextfeld 1 - Freitextfeld 2 - Freitextfeld 3 - Freitextfeld 4 - IOB Bezeichnung oder IOB Sum wenn detailliert - IOB-Summe oder (Bolus_IOB|Basal_IOB) wenn detailliert - COB-Bezeichnung - COB-Wert - Kurzes BG Delta - Durchschnittliches BG-Delta (15min) - Telefon-Akku (%) - Globale Loop Akku (%) - Basalrate - BGI-Wert - Uhrzeit (HH:MM oder HH:MM:SS) - Stunde (HH) - Minuten (MM) - Sekunde (SS) - AM oder PM - Wochentagname - Tag (DD) - Monatsname (kurz) - Loop-Status und Historie - Richtungspfeil - Minuten vor dem letzten erhaltenen BG - Blutzuckerwert - Titelbild vor dem Text (wählen...) - Bild des Stundenzeiger (Analog Uhr) - Bild des Minutenzeiger (Analog Uhr) - Bild des Sekundenzeigers (Analog Uhr) - diff --git a/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml b/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml deleted file mode 100644 index e8c20ac480..0000000000 --- a/app-wear-shared/shared/src/main/res/values-el-rGR/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - %1$d λ πριν - %1$d λεπτά πριν - %1$.1f ω πριν - %1$.1f ημέρες πριν - %1$.0f ημέρες πριν - σε %1$.0f ημέρες - σε %1$.0f ημέρες - h - ημέρες - ώρες - δευτερόλεπτο - λεπτό - ώρα - ημέρα - εβδομάδα - δευτερόλεπτα - λεπτά - ώρες - ημέρες - εβδομάδες - m - ημ - Αργότερα σήμερα - Αύριο - Σήμερα - Χθες - - Σύνδεση για %1$d δευτερόλεπτα - Δημιουργία σύνδεσης - Συνδέθηκε - Αποσυνδέεται - Αναμονή για αποσύνδεση - - Δημιουργήθηκε: %1$s - Συντάκτης: %1$s - Όνομα: %1$s - Όνομα αρχείου: %1$s - Έκδοση πρόσθετου: %1$s - Όνομα: %1$s (%2$s) - Πληροφορίες: %1$s - Εμφάνιση IOB - Εμφάνιση λεπτομερούς IOB - Εμφάνιση COB - Εμφάνιση Διαφοράς - Εμφάνιση λεπτομερούς Διαφοράς - Εμφάνιση Μέσης Διαφοράς - Εμφάνιση Μπαταρίας Τηλεφώνου - Εμφάνιση Μπαταρίας Rig - Εμφάνιση Βασικού Ρυθμού - Εμφάνιση Κατάστασης Κυκλώματος - Εμφάνιση γλυκόζης αίματος - Εμφάνιση BGI - Εμφάνιση Βέλους Κατεύθυνσης - Εμφάνιση Πριν - Εμφάνιση αριθμού Εβδομάδας - Προεπιλεγμένη πρόσοψη ρολογιού, μπορείτε να κάνετε κλικ στο κουμπί ΕΞΑΓΩΓΗ ΠΡΟΣΟΨΗΣ για να δημιουργήσετε ένα πρότυπο - Προεπιλεγμένη πρόσοψη ρολογιού - Εικόνα φόντου - Γραφήματα (BG, βασικός, γραμμές πρόβλεψης...) - Εικόνα μπροστά από το γράφημα και πίσω από τα πεδία κειμένου - Ελεύθερο κείμενο 1 - Ελεύθερο κείμενο 2 - Ελεύθερο κείμενο 3 - Ελεύθερο κείμενο 4 - Ετικέτα IOB ή Άθροισμα IOB εάν είναι λεπτομερές - Άθροισμα IOB ή (Bolus_IOB|Basal_IOB) εάν είναι λεπτομερές - Ετικέτα COB - Τιμή COB - Βραχυπρόθεσμη διαφορά BG - Μέση διαφορά BG (15λεπτά) - Μπαταρία τηλεφώνου (%) - Μπαταρία συνολικού κυκλώματος (%) - Βασικός Ρυθμός - Τιμή BGI - Ώρα (ΩΩ:ΛΛ ή ΩΩ:ΜΜ:ΣΣ) - Ώρα (HH) - Λεπτό (MM) - Δευτερόλεπτο (SS) - ΠΜ ή ΜΜ - Όνομα της ημέρας της εβδομάδας - Ημέρα (DD) - Αριθμός Εβδομάδας (ww) - Όνομα μήνα (σύντομο) - Κατάσταση κυκλώματος και πριν - Βέλος κατεύθυνσης - Λεπτά πριν από την τελευταία λήψη BG - Τιμή γλυκόζης αίματος - Εικόνα εξωφύλλου μπροστά από το κείμενο (κλήσεις...) - Εικόνα ώρας χεριού (Αναλογικό ρολόι) - Εικόνα λεπτού χεριού (Αναλογικό ρολόι) - Εικόνα δευτερολέπτου χεριού (Αναλογικό ρολόι) - diff --git a/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml b/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml deleted file mode 100644 index 026bf80160..0000000000 --- a/app-wear-shared/shared/src/main/res/values-es-rES/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - hace %1$d m - Hace %1$d minutos - hace %1$.1f h - Hace %1$.1f día - Hace %1$.0f días - en %1$.0f días - en %1$.0f días - h - días - horas - segundo - minuto - hora - día - semana - segundos - minutos - horas - días - semanas - m - d - Más tarde hoy - Mañana - Hoy - Ayer - - Conectando durante %1$d s - Estableciendo comunicación - Conectado - Desconectando - Esperando la desconexión - - Creada: %1$s - Autor: %1$s - Nombre: %1$s - Nombre del archivo: %1$s - Versión del plugin: %1$s - Nombre: %1$s (%2$s) - Info: %1$s - Mostrar IOB - Mostrar IOB detallada - Mostrar COB - Mostrar delta - Mostrar delta detallado - Mostrar delta promedio - Mostrar batería del teléfono - Mostrar batería global del lazo - Mostrar la tasa basal - Mostrar estado del lazo - Mostrar glucosa - Mostrar BGI (Índice de glucosa en sangre) - Mostrar flecha de dirección - Mostrar \"hace\" - Mostrar número de semana - Esfera predeterminada, puedes hacer clic en el botón EXPORTAR ESFERA para generar una plantilla - Esfera por defecto - Imagen de fondo - Gráficos (glucosa, basal, líneas de predicción...) - Imagen frente al gráfico y detrás de campos de texto - Texto libre 1 - Texto libre 2 - Texto libre 3 - Texto libre 4 - Etiqueta IOB o Suma IOB si es detallada - Suma de IOB o (Bolos_IOB|Basal_IOB) si se detalla - Etiqueta COB - Valor COB - Delta corto de glucosa - Delta promedio de glucosa (15min) - Batería del teléfono (%) - Batería global de lazo (%) - Tasa Basal - Valor BGI - Tiempo (HH:MM o HH:MM:SS) - Hora (HH) - Minuto (MM) - Segundo (SS) - AM o PM - Nombre del día de la semana - Día (DD) - Número de semana (ww) - Nombre del mes (corto) - Estado del bucle y hace - Flecha de dirección - Minutos atrás del último valor de glucosa recibido - Valor de glucosa - Imagen de portada delante del texto (diales...) - Imagen de la aguja horaria (reloj analógico) - Imagen del minutero (reloj analógico) - Imagen del segundero (reloj analógico) - diff --git a/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml b/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml deleted file mode 100644 index d5b3b0ac07..0000000000 --- a/app-wear-shared/shared/src/main/res/values-fr-rFR/strings.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - il y a %1$d m - Il y a %1$d minutes - il y a %1$.1f h - Il y a %1$.1f jours - Il y a %1$.0f jours - en %1$.0f jours - en %1$.0f jours - h - jours - heures - seconde - minute - heure - jour - semaine - secondes - minutes - heures - jours - semaines - m - j - Plus tard aujourd\'hui - Demain - Aujourd’hui - Hier - - Connexion en cours %1$ds - Connexion - Connectée - Déconnexion en cours - Attente de déconnexion - - Créé le : %1$s - Auteur : %1$s - Nom : %1$s - Nom du fichier : %1$s - Version du plugin : %1$s - Nom : %1$s (%2$s) - Infos : %1$s - Afficher IA - Afficher IA détaillée - Afficher GA - Montrer le delta - Afficher Delta Détaillé - Afficher le delta moyen - Afficher la batterie du téléphone - Afficher la batterie de la plateforme - Afficher Basale - Afficher État Boucle - Afficher Glycémie - Afficher IGly - Afficher Flèche - Afficher Min Passées - Cadran par défaut, vous pouvez cliquer sur le bouton EXPORTER WATCHFACE pour générer un modèle - Cadran par défaut - Image d\'arrière-plan - Graphiques (Gly, basal, lignes de prédiction...) - Image devant le graphique et derrière les champs de texte - Texte libre 1 - Texte libre 2 - Texte libre 3 - Texte libre 4 - Libellé \"IA\" ou valeur IA globale si détaillé Ok - Valeur IA globale ou (IA_Bolus|IA_Basal) si détaillé Ok - Libellé \"GA\" - Valeur de GA - Delta Glycémie (5min) - Delta glycémie moyen (15min) - Batterie du téléphone (%) - Batterie de la boucle globale (%) - Débit Basal - Valeur de IGly - Heure (HH:MM ou HH:MM:SS) - Heure (HH) - Minute (MM) - Seconde (SS) - AM ou PM - Nom du jour de la semaine - Jour (JJ) - Nom du mois (court) - État de la boucle et délais - Flèche de direction - Minutes depuis la dernière Glycémie reçue - Valeur de Ia Gly - Image de couverture devant le texte (cadrans...) - Image de l\'aiģuille de l\'heure (Montre Analogique) - Image de l\'aiguille des minutes (Montre Analogique) - Image de l\'aiguille des secondes (Montre Analogique) - diff --git a/app-wear-shared/shared/src/main/res/values-ga-rIE/strings.xml b/app-wear-shared/shared/src/main/res/values-ga-rIE/strings.xml deleted file mode 100644 index 7f4c422d88..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ga-rIE/strings.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - %1$d nóim ó shin - %1$.1f u ó shin - u - - uair - soicind - nóiméad - uair - - seachtain - soicind - nóiméad - uair - - seachtaine - n - - - Ag nascadh le %1$d s - Nasctha - Dícheangal - - diff --git a/app-wear-shared/shared/src/main/res/values-hr-rHR/strings.xml b/app-wear-shared/shared/src/main/res/values-hr-rHR/strings.xml deleted file mode 100644 index a098b3c42d..0000000000 --- a/app-wear-shared/shared/src/main/res/values-hr-rHR/strings.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - Prije %1$.1f dana - Prije %1$.0f dana - Danas - - Povezivanje %1$d s - Povezivanje - Povezano - Odspajanje - Čeka se prekid veze - - diff --git a/app-wear-shared/shared/src/main/res/values-hu-rHU/strings.xml b/app-wear-shared/shared/src/main/res/values-hu-rHU/strings.xml deleted file mode 100644 index a30f9e054a..0000000000 --- a/app-wear-shared/shared/src/main/res/values-hu-rHU/strings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - p - n - - Kapcsolódva - - diff --git a/app-wear-shared/shared/src/main/res/values-it-rIT/strings.xml b/app-wear-shared/shared/src/main/res/values-it-rIT/strings.xml deleted file mode 100644 index f6dc6021a6..0000000000 --- a/app-wear-shared/shared/src/main/res/values-it-rIT/strings.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - %1$d m fa - %1$d minuti fa - %1$.1f h fa - %1$.1f giorni fa - %1$.0f giorni fa - in %1$.0f giorni - in %1$.0f giorni - h - giorni - ore - secondi - minuti - ora - giorno - settimana - secondi - minuti - ore - giorni - settimane - m - d - Più tardì oggi - Domani - Oggi - Ieri - - In connessione per %1$d s - Connessione - Connesso - Disconnessione - In attesa della disconnessione - - Creato: %1$s - Autore: %1$s - Nome: %1$s - Nome file: %1$s - Versione plugin: %1$s - Nome: %1$s (%2$s) - Info: %1$s - Mostra IOB - Mostra IOB dettagliato - Mostra COB - Mostra delta - Mostra delta dettagliato - Mostra delta medio - Mostra batteria telefono - Mostra batteria rig - Mostra velocità basale - Mostra stato loop - Mostra BG - Mostra BGI - Mostra frecce direzionali - Mostra Indietro - Watchface predefinita, puoi fare click sul tasto ESPORTA WATCHFACE per generare un template - Watchface predefinita - Immagine sfondo - Grafici (BG, basale, linee di previsione...) - Immagine davanti al grafico e dietro i campi di testo - Testo libero 1 - Testo libero 2 - Testo libero 3 - Testo libero 4 - Etichetta IOB o somma IOB se in dettaglio - Somma IOB o (Bolo_IOB|Basale_IOB) se in dettaglio - Etichetta COB - Valore COB - Delta BG breve - Delta BG medio (15min) - Batteria telefono (%) - Batteria globale loop (%) - Velocità basale - Valore BGI - Tempo (HH:MM o HH:MM:SS) - Ora (HH) - Minuto (MM) - Secondo (SS) - AM o PM - Nome del giorno della settimana - Giorno (DD) - Nome del mese (breve) - Stato loop e indietro - Freccia direzionale - Minuti addietro per l\'ultimo valore BG ricevuto - Valore BG - Immagine di copertina davanti al testo (quadranti...) - Immagine lancetta ore (orologio analogico) - Immagine lancetta minuti (orologio analogico) - Immagine lancetta secondi (orologio analogico) - diff --git a/app-wear-shared/shared/src/main/res/values-iw-rIL/strings.xml b/app-wear-shared/shared/src/main/res/values-iw-rIL/strings.xml deleted file mode 100644 index c1642ab32d..0000000000 --- a/app-wear-shared/shared/src/main/res/values-iw-rIL/strings.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - לפני %1$d דקות - לפני %1$d דקות - לפני %1$.1f שעות - לפני %1$.1f ימים - לפני %1$.0f ימים - בעוד %1$.0f ימים - בעוד %1$.0f ימים - ש\' - ימים - שעות - שניה - דקה - שעה - יום - שבוע - שניות - דקות - שעות - ימים - שבועות - דק\' - י\' - מאוחר יותר היום - מחר - היום - אתמול - - חיבור אל %1$s - לוחץ יד - מחובר - מתנתק - ממתין לניתוק - - נוצר ב: %1$s - יוצר/ת: %1$s - שם: %1$s - שם קובץ: %1$s - גרסת פלאגין: %1$s - שם: %1$s (%2$s) - הצג אינסולין פעיל - הצגת אינס\' פעיל מפורט - הצג פח\' פעילות - הצג דלתא - הצג דלתא מפורטת - הצג דלתא ממוצעת - הצג את סוללת הטלפון - הצג סוללת ריג - הצג מינון בזאלי - ברירת המחדל של פני השעון, ניתן ללחוץ על כפתור ייצוא פני שעון כדי ליצור תבנית - ברירת מחדל פני שעון - diff --git a/app-wear-shared/shared/src/main/res/values-ja-rJP/strings.xml b/app-wear-shared/shared/src/main/res/values-ja-rJP/strings.xml deleted file mode 100644 index d78b6c6230..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ja-rJP/strings.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - %1$d 分前 - %1$d 分前 - %1$.1f 時間前 - %1$.1f 日前 - %1$.0f 日前 - in %1$.0f 日 - in %1$.0f 日 - - 日間 - 時間 - - - - - - - - 時間 - - 週間 - - - 今日中 - 明日 - 今日 - 昨日 - - %1$d 秒間接続中 - ハンドシェイク中です - 接続されました - 切断中 - 切断待ち - - diff --git a/app-wear-shared/shared/src/main/res/values-ko-rKR/strings.xml b/app-wear-shared/shared/src/main/res/values-ko-rKR/strings.xml deleted file mode 100644 index 09e6124d50..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ko-rKR/strings.xml +++ /dev/null @@ -1,92 +0,0 @@ - - - - %1$d 분 전 - %1$d분 전 - %1$.1f 시간 전 - %1$.1f일 전 - %1$.0f 일 전 - %1$.0f 일 이내에 - %1$.0f 일 이내에 - 시간 - - 시간 - - - - - - - - - - - - - 오늘 늦게 - 내일 - 오늘 - 어제 - - %1$d 초 동안 연결중 - 통신 확인 - 연결됨 - 연결끊기중 - 연결 해제 대기 중 - - 생성 시간: %1$s - 작성자: %1$s - 이름: %1$s - 파일 이름: %1$s - 플러그인 버전: %1$s - 이름: %1$s (%2$s) - IOB 표시 - IOB 자세한 표시 - COB 표시 - 델타 표시하기 - 자세한 델타 표시하기 - 평균 델타 표시하기 - 핸드폰 배터리 표시하기 - 리그 베터리 표시하기 - Basal 값 표시하기 - 루프 상태 표시하기 - BG 표시하기 - BGI 표시하기 - 화살표 표시하기 - 이전 표시하기 - 기본 시계, 워치페이스 내보내기 버튼을 클릭하여 템플릿을 생성할 수 있습니다. - 기본 워치페이스 - 배경화면 이미지 - 그래픽 (혈당, basal, 예측 선...) - 그래프 앞 그리고 문자 필드 뒤 이미지 - 무료 문자 1 - 무료 문자 2 - 무료 문자 3 - 무료 문자 4 - 자세한 경우 IOB 레이블 또는 IOB 합계 - 자세한 경우 IOB 합계 또는 (Bolus_IOB|Basal_IOB) - COB 레이블 - COB 값 - 단기 BG 델타 - 평균 BG 델타 (15분) - 핸드폰 베터리 (%) - 글로벌 루프 베터리 (%) - Basal양 - BGI 값 - 시간 (HH:MM 또는 HH:MM:SS) - 시간 (HH) - 분 (MM) - 초 (SS) - 오전 또는 오후 - 요일 - 일 (DD) - 월명 (짧게) - 루프 상태 및 이전 - 방향 화살표 - 몇 분 전에 마지막으로 받은 BG - BG 값 - 문자 앞의 표지 이미지 (다이얼...) - 시침 이미지 (아날로그 시계) - 분침 이미지 (아날로그 시계) - 초침 이미지 (아날로그 시계) - diff --git a/app-wear-shared/shared/src/main/res/values-lt-rLT/strings.xml b/app-wear-shared/shared/src/main/res/values-lt-rLT/strings.xml deleted file mode 100644 index 2c287ad28f..0000000000 --- a/app-wear-shared/shared/src/main/res/values-lt-rLT/strings.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - prieš %1$d min. - Prieš %1$d min. - Prieš %1$.1f val. - Prieš %1$s d. - Prieš %1$.0f d. - Po %1$.0f d. - Po %1$.0f d. - val. - d. - val. - sek. - min. - val. - d. - sav. - sekundės - min. - val. - d. - savaičių - m - d - Šiandien vėliau - Rytoj - Šiandien - Vakar - - Jungiamasi %1$d s - Ryšio užmezgimas - Prisijungta - Atsijungiama - Laukiama atsijungimo - - Sukurta: %1$s - Autorius: %1$s - Vardas: %1$s - Failo pavadinimas: %1$s - Įskiepio versija: %1$s - Pavadinimas: %1$s (%2$s) - Info: %1$s - Rodyti AIO - Rodyti detalų AIO - Rodyti AAO - Rodyti pokytį - Rodyti glikemijos pokyčius detaliai - Rodyti vidutinį pokytį - Rodyti telefono bateriją - Rodyti įrenginio bateriją - Rodyti valandinę bazę - Rodyti Ciklo statusą - Rodyti KG - Rodyti GĮ - Rodyti krypties rodyklę - Laikas nuo pask. vertės - Numatytasis ekranas. Paspaudus EKSPORTUOTI, bus sukurtas ruošinys - Numatytasis ekranas - Fono paveiksliukas - Grafikai (glikemija, bazė, prognozės...) - Paveiksliukas už teksto ir prieš grafiką - Laisvas tekstas 1 - Laisvas tekstas 2 - Laisvas tekstas 3 - Laisvas tekstas 4 - Sudėtinis arba detalus AIO - Sudėtinis arba detalus (Boluso_AIO|Bazės_AIO) AIO - AAO žyma - AAO vertė - Trumpo laikotarpio pokytis - Vidutinis pokytis (15 min) - Telefono baterija (%) - Baterija (%) - Bazė - KGI vertė - Laikas (val:min arba val:min:sek) - Val. - Min. - Sek. - AM ar PM - Savaitės diena - Diena (d.) - Mėnuo (sutrump.) - Ciklo būsena - Tendencijos rodyklė - Prieš kiek minučių nuskaityta glikemija - Glikemija - Paveiksliukas prieš tekstą (skambučius...) - Analoginio laikrodžio valandinė rodyklė - Analoginio laikrodžio minutinė rodyklė - Analoginio laikrodžio sekundinė rodyklė - diff --git a/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml b/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml deleted file mode 100644 index ecf4281832..0000000000 --- a/app-wear-shared/shared/src/main/res/values-nl-rNL/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - %1$d m geleden - %1$d minuten geleden - %1$.1f uur geleden - %1$.1f dagen geleden - %1$.0f dagen geleden - over %1$.0f dagen - binnen %1$.0f dagen - u - dagen - uren - seconde - minuut - uur - dag - week - seconden - minuten - uren - dagen - weken - m - d - Later vandaag - Morgen - Vandaag - Gisteren - - Verbonden gedurende %1$d s - Handshaking - Verbonden - Verbinding aan het verbreken - Wachten op het loskoppelen - - Gemaakt op: %1$s - Auteur: %1$s - Naam: %1$s - Bestandsnaam: %1$s - Plugin versie: %1$s - Naam: %1$s (%2$s) - Info: %1$s - Toon IOB - Toon gedetailleerde IOB - Toon COB - Toon Delta - Toon gedetailleerde Delta - Toon gemiddelde delta - Toon Telefoon Batterij - Toon Rig batterij - Toon basaalstand - Toon Loop Status - Toon BG - Toon BGI - Toon richtingspijl - Toon tijd geleden - Weeknummer weergeven - Standaard watchface, u kunt op de EXPORT WATCHFACE knop klikken om een sjabloon te genereren - Standaard watchface - Achtergrondafbeelding - Grafieken (BG, basaal, voorspellingslijnen...) - Afbeelding voor de grafiek en achter tekstvelden - Vrije tekst 1 - Vrije tekst 2 - Vrije tekst 3 - Vrije tekst 4 - IOB label of IOB totaal indien gedetailleerd - IOB totaal of (Bolus_IOB|Basal_IOB) indien gedetailleerd - COB label - COB waarde - Korte BG delta - Gemiddelde BG delta (15min) - Batterij Telefoon (%) - Globale loop batterij (%) - Basaal stand - BGI waarde - Tijd (UU:MM of UU:MM:SS) - Uur (UU) - Minuut (MM) - Seconde (SS) - AM of PM - Naam van de dag van de week - Dag (DD) - Weeknummer (ww) - Maand (kort) - Loop status en tijd geleden - Richtingspijl - Minuten geleden voor laatst ontvangen BG - BG waarde - Masker afbeelding over tekst (bijv. uren indicators) - Afbeelding van uren wijzer (analoog horloge) - Afbeelding van minuut wijzer (analoog horloge) - Afbeelding van seconde wijzer (analoog horloge) - diff --git a/app-wear-shared/shared/src/main/res/values-no-rNO/strings.xml b/app-wear-shared/shared/src/main/res/values-no-rNO/strings.xml deleted file mode 100644 index a6024c111f..0000000000 --- a/app-wear-shared/shared/src/main/res/values-no-rNO/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - %1$d min siden - %1$d minutter siden - %1$.1f timer siden - %1$.1f dager siden - %1$.0f dager siden - om %1$.0f dager - om %1$.0f dager - t - dager - timer - sekund - minutt - time - dag - uke - sekunder - minutter - timer - dager - uker - m - d - Senere i dag - I morgen - Idag - I går - - Tilkobler i %1$d sek - Tilkobling verifiseres - Tilkoblet - Frakobler - Venter på frakobling - - Opprettet: %1$s - Laget av: %1$s - Navn: %1$s - Filnavn: %1$s - Plugin-versjon: %1$s - Navn: %1$s (%2$s) - Info: %1$s - Vis IOB - Vis detaljert IOB - Vis COB - Vis Delta - Vis detaljert Delta - Vis Gj. snitt Delta - Vis telefonbatteri - Vis riggens batteri - Vis basalrate - Vis loop status - Vis BS - Vis BS - Vis retningspil - Vis tid siden - Vis ukenummer - Standard klokkebakgrunn, du kan klikke på EKSPORTER KLOKKEBAKGRUNN for å lage en mal - Standard klokkebakgrunn - Bakgrunnsbilde - Grafer (BS, basal, prediksjonslinjer...) - Bilde foran grafer og bak tekstfelter - Fritekst 1 - Fritekst 2 - Fritekst 3 - Fritekst 4 - IOB-merkelapp eller IOB-sum hvis angitt - IOB-sum eller (Bolus_IOB|Basal_IOB) hvis angitt - COB etikett - COB verdi - Kort BS-endring - Gj.snitt BS-endring (15min) - Telefonbatteri (%) - Rig-batteri (%) - Basalrate - BGI verdi - Tid (TT:MM eller TT:MM:SS) - Time (TT) - Minutt (MM) - Sekund (SS) - AM eller PM - Navn på ukedag - Dag (DD) - Ukenummer (ww) - Navn på måned (kort) - Loop-status og tid siden - Retningspil - Minutter siden BS sist ble mottatt - BS-verdi - Bilde foran tekst (urvisere...) - Bilde av timeviser (analog klokke) - Bilde av minuttviser (analog klokke) - Bilde av sekundviser (analog klokke) - diff --git a/app-wear-shared/shared/src/main/res/values-pl-rPL/strings.xml b/app-wear-shared/shared/src/main/res/values-pl-rPL/strings.xml deleted file mode 100644 index b3eedc562a..0000000000 --- a/app-wear-shared/shared/src/main/res/values-pl-rPL/strings.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - %1$d min temu - %1$d minut temu - %1$.1f godz. temu - %1$.1f dni temu - %1$.0f dni temu - za %1$.0f dni - za %1$.0f dni - h - dni - godzin - sekunda - minuta - godzina - dzień - tydzień - sekund - minut - godzin - dni - tygodni - m - d - Dzisiaj, później - Jutro - Dziś - Wczoraj - - Łączenie przez %1$d s - Nawiązywanie połączenia - Połączono - Rozłączanie - Oczekiwanie na rozłączenie - - Utworzono: %1$s - Autor: %1$s - Nazwa: %1$s - Nazwa pliku: %1$s - Wersja wtyczki: %1$s - Nazwa: %1$s (%2$s) - Info: %1$s - Pokaż IOB - Pokaż szczegółowe IOB - Pokaż COB - Pokaż Deltę - Pokaż szczegółowo Deltę - Pokaż Śr. Deltę - Pokaż Baterię Telefonu - Pokaż Baterię Zestawu - Pokaż Dawkę Bazową - Pokaż Status Pętli - Pokaż glikemię - Pokaż BGI - Pokaż Strzałkę Trendu - Pokaż Aktualność - Domyślna tarcza, możesz kliknąć na EXPORTUJ TARCZĘ aby wygenerować szablon - Domyślna Tarcza - Obraz w tle - Wykresy (glikemia, baza, prognozy...) - Obraz przed wykresem i za polami tekstowymi - Wolne pole tekstowe 1 - Wolne pole tekstowe 2 - Wolne pole tekstowe 3 - Wolne pole tekstowe 4 - Etykieta IOB lub suma IOB przy szczegółowym IOB - Suma IOB lub (Bolus_IOB|Basal_IOB) jeśli szczegółowo - Etykieta COB - Wartość COB - Krótka delta glikemii - Średnia delta glikemii (15min) - Bateria telefonu (%) - Globalna bateria pętli (%) - Wartości bazy - Wartość BGI - Czas (HH:MM or HH:MM:SS) - Godzina (HH) - Minuta (MM) - Sekunda (SS) - AM lub PM - Nazwa dnia tygodnia - Dzień (DD) - Nazwa miesiąca (krótka) - Status pętli i aktualność - Strzałka trendu - Minut od ostatniego otrzymania glikemii - Wartość glikemii - Obraz nakładki przed tekstem (tarcze...) - Obraz lub wskazówka godzinowa (Tarcza Analogowa) - Obraz lub wskazówka minutowa (Tarcza Analogowa) - Obraz lub wskazówka sekundowa (Tarcza Analogowa) - diff --git a/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml b/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml deleted file mode 100644 index 9f5d4585a4..0000000000 --- a/app-wear-shared/shared/src/main/res/values-pt-rBR/strings.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - %1$d min atrás - %1$d minutos atrás - %1$.1fh atrás - %1$d dias atrás - %1$.0f dias atrás - em %1$.0f dias - em %1$.0f dias - h - dias - horas - segundo - minuto - hora - dia - semana - segundos - minutos - horas - dias - semanas - m - d - Hoje, Mais tarde - Amanhã - Hoje - Ontem - - Conectando para %1$d - Cumprimento - Conectado - A desligar - Aguardando a desconexão - - Criado por %1$s - Autor: %1$s - Nome: %1$s - Nome do arquivo: %1$s - Versão do plugin: %1$s - Nome: %1$s (%2$s) - Informações: %1$s - Mostrar IA - Mostrar detalhes da IA - Mostrar CA - Mostrar Delta - Mostrar Delta detalho - Mostrar média de delta - Mostrar bateria do telefone - Mostrar bateria de rig - Mostrar Taxa Basal - Mostrar Status do Loop - Mostrar glicemia - Mostrar BGI - Mostrar seta de tendência - Exibir atrás - Watchface padrão, você pode clicar no botão EXPORTAR WATCHFACE para gerar um modelo - Watchface padrão - diff --git a/app-wear-shared/shared/src/main/res/values-pt-rPT/strings.xml b/app-wear-shared/shared/src/main/res/values-pt-rPT/strings.xml deleted file mode 100644 index 6d5a05175a..0000000000 --- a/app-wear-shared/shared/src/main/res/values-pt-rPT/strings.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - %1$d m atrás - %%1$d minutos atrás - %1$.1f h atrás - %1$.1f dias atrás - %1$.0f dias atrás - em %1$.0f dias - em %1$.0f dias - h - dias - horas - segundo - minuto - hora - dia - semana - segundos - minutos - horas - dias - semanas - m - d - Hoje mais tarde - Amanhã - Hoje - Ontem - - A ligar durante %1$d s - Cumprimento - Ligado - A desconectar - A aguardar a desconexão - - Criado em: %1$s - Autor: %1$s - Nome: %1$s - Nome do ficheiro: %1$s - Versão do plugin: %1$s - Nome: %1$s (%2$s) - Mostrar IA - Mostrar IA detalhada - Mostrar HCA - Mostrar Delta - Mostrar Delta detalhado - Mostrar Delta Médio - Mostrar Bateria Telefone - Mostrar Bateria Equipamento - Mostrar Taxa Basal - Mostrar Estado Loop - Mostrar glicemia - Mostrar IG - Mostrar Seta Direcção - Mostrar Atrás - Watchface padrão, pode clicar no botão EXPORTAR WATCHFACE para gerar um modelo - Watchface padrão - Imagem de fundo - Gráficos (GLIC, basal, linhas de previsão...) - Imagem na frente do gráfico e atrás dos campos de texto - Texto livre 1 - Texto livre 2 - Texto livre 3 - Texto livre 4 - Etiqueta de IA ou Soma IA se detalhada - Soma IA ou (Bolus_IA|Basal_IA) se detalhada - Etiqueta HCA - valor HCA - Delta curto da glicemia - Delta da glicemia média (15min) - Bateria do telefone (%) - Bateria do loop (%) - Taxa Basal - Valor de IG - Horário (HH:MM ou HH:MM:SS) - Hora (HH) - Minuto (MM) - Segundo (SS) - AM ou PM - Nome do Dia da Semana - Dia (DD) - Nome do Mês (curto) - Seta de direção - Minutos desde a recepção do último valor de GLIC - Valor de GLIC - Imagem da capa na frente do texto - Imagem do ponteiro das horas (Relógio Analógico) - Imagem do ponteiro dos minutos (Relógio Analógico) - Imagem do ponteiro dos segundos (Relógio Analógico) - diff --git a/app-wear-shared/shared/src/main/res/values-ro-rRO/strings.xml b/app-wear-shared/shared/src/main/res/values-ro-rRO/strings.xml deleted file mode 100644 index 10ce7af4ed..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ro-rRO/strings.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - %1$d min în urmă - %1$.1f ore în urmă - h - zile - ore - secundă - minut - oră - zi - săptămână - secunde - minute - ore - zile - săptămâni - m - z - - Conectat de %1$d s - Împerechere - Conectat - Se deconectează - Se așteaptă deconectarea - - diff --git a/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml b/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml deleted file mode 100644 index c2a98e4c23..0000000000 --- a/app-wear-shared/shared/src/main/res/values-ru-rRU/strings.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - %1$d мин. назад - %1$d минут назад - %1$.1fч. назад - %1$s дн назад - %1$s дн назад - через %1$.0f дн - через %1$.0f дн - ч - дн - час - сек - мин - час - дн - нед - сек - мин - час - дн - нед - м - д - Позднее сегодня - Завтра - Cегодня - Вчера - - Связь установлена за %1$d сек - Подтверждение связи - соединение установлено - разъединение - Ожидание разъединения - - Создано: %1$s - Автор: %1$s - Название: %1$s - Имя файла: %1$s - Версия плагина: %1$s - Информация: %1$s - Отображать IOB - Отображать IOB подробно - Отображать COB - Отображать дельту - Отображать дельту подробно - Отображать усредненную дельту - Отображать заряд телефона - Отображать заряд батареи системы - Отображать базал - Отображать состояние цикла - Отображать ГК - Отображать BGI (ГКИ) - Отображать стрелку тренда - Циферблат по умолчанию, вы можете нажать на EXPORT WATCHFACE чтобы создать шаблон - Циферблат по умолчанию - Фоновое изображение - Графики (ГК, базал, линии прогнозов...) - Метка IOB, или общего IOB для подробного отображения - Общий IOB, или (IOB_болюса|IOB_базы) для подробного отображения - Метка COB - Значение COB - Краткая дельта ГК - Средняя дельта ГК (15 мин) - Заряд телефона (%) - Заряд системы ИПЖ (%) - Базальная скорость - Значение ГКИ - Время (ЧЧ:ММ или ЧЧ:ММ:СС) - Часы (ЧЧ) - Минуты (ММ) - Секунды (СС) - AM или PM - Название дня недели - Число (ДД) - Название месяца (краткое) - Стрелка тренда - Минут с последнего чтения ГК - Значение ГК - Изображение для часовой стрелки (Аналоговые часы) - Изображение для минутной стрелки (Аналоговые часы) - Изображение для секундной стрелки (Аналоговые часы) - diff --git a/app-wear-shared/shared/src/main/res/values-sk-rSK/strings.xml b/app-wear-shared/shared/src/main/res/values-sk-rSK/strings.xml deleted file mode 100644 index 150cfd10f9..0000000000 --- a/app-wear-shared/shared/src/main/res/values-sk-rSK/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - pred %1$d min - pred %1$d minútami - pred %1$.1f h - Pred %1$.1f dňami - Pred %1$.0f dňami - za %1$.0f dní - za %1$.0f dní - h - dní - hodín - sekunda - minúta - hodina - deň - týždeň - sekúnd - minút - hodín - dní - týždňov - m - d - Neskôr počas dňa - Zajtra - Dnes - včera - - Pripájanie %1$d sek - Overovanie - Pripojené - Odpájanie - Čakám na odpojenie - - Vytvorené: %1$s - Autor: %1$s - Meno: %1$s - Názov súboru: %1$s - Verzia pluginu: %1$s - Meno: %1$s (%2$s) - Informácie: %1$s - Zobraziť IOB - Zobraziť detailný IOB - Zobraziť COB - Zobraziť odchýlku - Zobraziť detailnú odchylku - Zobraziť priemernú odchýlku - Zobraziť stav batérie telefónu - Zobrazovať stav batérie ďalších zariadení - Zobraziť bazál - Zobraziť stav uzavretého okruhu - Zobraziť glykémiu - Zobraziť BGI - Zobraziť trendovú šípku - Zobraziť aktualizované pred - Zobraziť číslo týždňa - Predvolený ciferník. Môžete kliknúť na tlačítko EXPORTOVAŤ CIFERNÍK pre vygenerovanie šablóny - Predvolený ciferník - Obrázok pozadia - Grafy (glykémie, bazály, krivky predpovedí...) - Obrázok pred grafom a za textovými poliami - Voľný text 1 - Voľný text 2 - Voľný text 3 - Voľný text 4 - Štítok IOB alebo suma IOB pri zapnutých detailoch - Suma IOB alebo (Bolus_IOB|Basal_IOB) pri zapnutých detailoch - Štítok COB - Hodnota COB - Krátkodobý priemer - Priemerný rozdiel glykémií (15min) - Batéria telefónu (%) - Batéria uzavretého okruhu (%) - Bazálna dávka - Hodnota BGI - Čas (HH:MM alebo HH:MM:SS) - Hodiny (HH) - Minúty (MM) - Sekundy (SS) - AM alebo PM - Meno dňa v týždni - Deň (DD) - Číslo týždňa (ww) - Názov mesiaca (krátky) - Stav uzavretého okruhu a čas - Trendová šípka - Pred minútami pre poslednú prijatú glykémiu - Hodnota glykémie - Úvodný obrázok pred textom (číselníky...) - Obrázok hodinovej ručičky (Analógové hodinky) - Obrázok minútovej ručičky (Analógové hodinky) - Obrázok sekundovej ručičky (Analógové hodinky) - diff --git a/app-wear-shared/shared/src/main/res/values-sr-rCS/strings.xml b/app-wear-shared/shared/src/main/res/values-sr-rCS/strings.xml deleted file mode 100644 index dc0f7891d7..0000000000 --- a/app-wear-shared/shared/src/main/res/values-sr-rCS/strings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/app-wear-shared/shared/src/main/res/values-sv-rSE/strings.xml b/app-wear-shared/shared/src/main/res/values-sv-rSE/strings.xml deleted file mode 100644 index 5ad7b03058..0000000000 --- a/app-wear-shared/shared/src/main/res/values-sv-rSE/strings.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - - %1$.1f tim sedan - %1$.1f dagar sedan - %1$.0f dagar sedan - om %1$.0f dagar - om %1$.0f dagar - h - dagar - timmar - sekund - minut - timme - dag - vecka - sekunder - minuter - timmar - dagar - veckor - m - d - Senare idag - Imorgon - Idag - Igår - - Ansluter (%1$d s) - Anslutningen verifieras - Ansluten - Kopplar från - Väntar på frånkoppling - - Skapad den: %1$s - Skapad av: %1$s - Namn: %1$s - Filnamn: %1$s - Plugin-version: %1$s - Namn: %1$s (%2$s) - Visa IOB - Visa detaljerad IOB - Visa COB - Visa delta - Visa detaljerad delta - Visa genomsnittlig delta - Visa telefonens batterinivå - Visa riggens batterinivå - Visa basaldos - Visa loop-status - Visa BG - Visa BGI - Visa riktningspil - Visa tid sedan - Standard-urtavla - du kan klicka på EXPORTERA URTAVLA för att generera en mall - Standard-urtavla - Bakgrundsbild - Grafer (BG, basal, prognoslinjer...) - Bild framför graf och bakom textfält - Fritext 1 - Fritext 2 - Fritext 3 - Fritext 4 - IOB-etikett. Total IOB om detaljerad - Total IOB. (Bolus_IOB|Basal_IOB) om detaljerad - COB-etikett - COB-värde - Kort BG-delta - Genomsnittligt BG-delta (15min) - Telefonens batterinivå (%) - Globalt loop-batteri (%) - Basaldos - BGI-värde - Tid (HH:MM eller HH:MM:SS) - Timme (HH) - Minut (MM) - Sekund (SS) - AM eller PM - Namn på veckodagen - Dag (DD) - Månadens namn (kort) - Loop status och tid - Visa riktningspil - Minuter sedan senast mottaget BG - BG-värde - Omslagsbild framför text (visare...) - Bild för timvisare (analog klocka) - Bild för minutvisare (analog klocka) - Bild för sekundvisare (analog klocka) - diff --git a/app-wear-shared/shared/src/main/res/values-tr-rTR/strings.xml b/app-wear-shared/shared/src/main/res/values-tr-rTR/strings.xml deleted file mode 100644 index 0b16af5b0d..0000000000 --- a/app-wear-shared/shared/src/main/res/values-tr-rTR/strings.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - %1$d dak önce - %1$d dakika önce - %1$.1f s önce - %1$.1f gün önce - %1$.0f gün önce - %1$.0f gün içinde - %1$.0f gün içinde - s - gün - saat - saniye - dakika - saat - gün - hafta - saniye - dakika - saat - gün - hafta - d - g - Bugünden sonra - Yarın - Bugün - Dün - - %1$d bağlanıyor - Bağlandı - Bağlandı - Bağlantı kesiliyor - Bağlantının kesilmesi bekleniyor - - Oluşturuldu: %1$s - Yetki: %1$s - İsim: %1$s - Dosya adı: %1$s - Eklenti sürümü: %1$s - İsim: %1$s (%2$s) - Bilgi: %1$s - AİNS Göster - Detalı AİNS göster - AKRB göster - Deltayı göster - Detaylı Delta göster - OrtDelta\'yı Göster - Telefon Pilini Göster - Teçhizat Pilini Göster - Bazal Oranı Göster - Döngü Durumunu Göster - KŞ\'ni göster - KŞ Etkisi Göster - Yön Oku Göster - Önce Göster - Hafta sayısını göster - Varsayılan saat arayüzü; bir şablon oluşturmak için SAAT ARAYÜZÜNÜ DIŞA AKTAR butonuna tıklayabilirsiniz - Varsayılan saat arayüzü - Arka plan görüntüsü - Grafik (KŞ, bazal, tahmin çizgileri...) - Grafiğin önündeki ve metin alanlarının arkasındaki resim - Serbest metin 1 - Serbest metin 2 - Serbest metin 3 - Serbest metin 4 - Ayrıntılıysa AİNS etiketi veya AİNS Toplamı - AİNS Toplamı veya ayrıntılıysa (Bolus_AİNS|Basal_AİNS) - AKRB etiketi - AKRB değeri - Kısa KŞ delta - Ortalama KŞ delta (15dk) - Telefon pili (%) - Global döngü pili (%) - Bazal Oranı - KŞ etkisi değeri - Saat (SS:DD veya SS:DD:SS) - Saat (SS) - Dakika (DD) - Saniye (SS) - AM veya PM - Haftanın gününün adı - Gün (GG) - Hafta sayısı - Ay adı (kısa) - Döngü durumu ve öncesi - Yön Okları - Birkaç dakika önce son alınan KŞ - KŞ değeri - Metnin önündeki kapak resmi (kadranlar...) - Akrep şekli (Analog Saat) - Yelkovan şekli (Analog Saat) - Saniye şekli (Analog Saat) - diff --git a/app-wear-shared/shared/src/main/res/values-uk-rUA/strings.xml b/app-wear-shared/shared/src/main/res/values-uk-rUA/strings.xml deleted file mode 100644 index dc0f7891d7..0000000000 --- a/app-wear-shared/shared/src/main/res/values-uk-rUA/strings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/app-wear-shared/shared/src/main/res/values-zh-rCN/strings.xml b/app-wear-shared/shared/src/main/res/values-zh-rCN/strings.xml deleted file mode 100644 index 484f6371f1..0000000000 --- a/app-wear-shared/shared/src/main/res/values-zh-rCN/strings.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - %1$d 分钟前 - %1$d 分钟前 - %1$.1f 小时前 - %1$.1f 天前 - %1$.0f 天前 - 在 %1$.0f 天内 - 在 %1$.0f 天内 - h - - 小时 - - 分钟 - 小时 - - - - 分钟 - 小时 - - - m - d - 今天稍后 - 明天 - 今天 - 昨天 - - 正在连接 %1$d s - 握手 - 已连接 - 正在断开连接 - 正在等待连接 - - diff --git a/app-wear-shared/shared/src/main/res/values/strings.xml b/app-wear-shared/shared/src/main/res/values/strings.xml deleted file mode 100644 index 6198eb283a..0000000000 --- a/app-wear-shared/shared/src/main/res/values/strings.xml +++ /dev/null @@ -1,103 +0,0 @@ - - - insulin_button_increment_1 - insulin_button_increment_2 - insulin_button_increment_3 - - - %1$d m ago - %1$d minutes ago - %1$.1f h ago - %1$.1f days ago - %1$.0f days ago - in %1$.0f days - in %1$.0f days - h - days - hours - second - minute - hour - day - week - seconds - minutes - hours - days - weeks - m - d - Later today - Tomorrow - Today - Yesterday - - - Connecting for %1$d s - Handshaking - Connected - Disconnecting - Waiting for disconnection - - - Created at: %1$s - Author: %1$s - Name: %1$s - File name: %1$s - Plugin version: %1$s - Name: %1$s (%2$s) - Info: %1$s - %1$s - Show IOB - Show detailed IOB - Show COB - Show Delta - Show detailed Delta - Show AvgDelta - Show Phone Battery - Show Rig Battery - Show Basal Rate - Show Loop Status - Show BG - Show BGI - Show Direction Arrow - Show Ago - Show Week number - Default watchface, you can click on EXPORT WATCHFACE button to generate a template - Default Watchface - Background image - Graphs (BG, basal, prediction lines...) - Image in front of graph and behind text fields - Free text 1 - Free text 2 - Free text 3 - Free text 4 - IOB label or IOB Sum if detailed - IOB Sum or (Bolus_IOB|Basal_IOB) if detailed - COB label - COB value - Short BG delta - Average BG delta (15min) - Phone battery (%) - Global loop battery (%) - Basal Rate - BGI value - Time (HH:MM or HH:MM:SS) - Hour (HH) - Minute (MM) - Second (SS) - AM or PM - Name of day of the week - Day (DD) - Week number (ww) - Month name (short) - Loop status and ago - Direction arrow - Mintutes ago for last received BG - BG value - Cover image in front of text (dials…) - Image of hour hand (Analog Watch) - Image of minute hand (Analog Watch) - Image of second hand (Analog Watch) - - \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index 98fb131cb4..78739798b0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -181,7 +181,6 @@ dependencies { // in order to use internet's versions you'd need to enable Jetifier again // https://github.com/nightscout/graphview.git // https://github.com/nightscout/iconify.git - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':core:main') implementation project(':core:graphview') diff --git a/core/interfaces/build.gradle b/core/interfaces/build.gradle index 5edc89c128..3cc11c5d58 100644 --- a/core/interfaces/build.gradle +++ b/core/interfaces/build.gradle @@ -9,6 +9,9 @@ plugins { apply from: "${project.rootDir}/core/main/android_dependencies.gradle" apply from: "${project.rootDir}/core/main/android_module_dependencies.gradle" +apply from: "${project.rootDir}/core/main/allopen_dependencies.gradle" +apply from: "${project.rootDir}/core/main/test_dependencies.gradle" +apply from: "${project.rootDir}/core/main/jacoco_global.gradle" android { @@ -19,25 +22,31 @@ android { } dependencies { - // I don't like this low level dependency but it helps - // to move more code to interface module - // database module is compiled longer anyway - // (ResourceHelper, AAPSLogger interface) - implementation project(':app-wear-shared:shared') implementation project(':database:entities') - // implementation project(':core:ns-sdk') api "androidx.appcompat:appcompat:$appcompat_version" + api "androidx.preference:preference-ktx:$preferencektx_version" + api "net.danlew:android.joda:$joda_version" + - // Dagger api "com.google.dagger:dagger:$dagger_version" api "com.google.dagger:dagger-android:$dagger_version" + api "com.google.dagger:dagger-android-support:$dagger_version" + + //Logger + api 'org.slf4j:slf4j-api:1.7.36' // 2.0.x breaks logging. Code change needed + api 'com.github.tony19:logback-android:2.0.0' + + api "org.jetbrains.kotlinx:kotlinx-serialization-json:$kotlinx_serialization_version" + api "org.jetbrains.kotlinx:kotlinx-serialization-protobuf:$kotlinx_serialization_version" + api "com.caverock:androidsvg:$caverock_androidsvg_version" + api "org.apache.commons:commons-lang3:$commonslang3_version" + + //RxBus + api "io.reactivex.rxjava3:rxjava:$rxjava_version" + api "io.reactivex.rxjava3:rxkotlin:$rxkotlin_version" + api "io.reactivex.rxjava3:rxandroid:$rxandroid_version" // WorkerClasses api "androidx.work:work-runtime-ktx:$work_version" -} - -allOpen { - // allows mocking for classes w/o directly opening them for release builds - annotation 'info.nightscout.interfaces.annotations.InterfacesOpenForTesting' } \ No newline at end of file diff --git a/app-wear-shared/shared/src/debug/java/info/nightscout/annotations/OpenForTesting.kt b/core/interfaces/src/debug/java/info/nightscout/annotations/OpenForTesting.kt similarity index 100% rename from app-wear-shared/shared/src/debug/java/info/nightscout/annotations/OpenForTesting.kt rename to core/interfaces/src/debug/java/info/nightscout/annotations/OpenForTesting.kt diff --git a/core/interfaces/src/debug/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt b/core/interfaces/src/debug/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt deleted file mode 100644 index e7e07b1a4b..0000000000 --- a/core/interfaces/src/debug/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt +++ /dev/null @@ -1,15 +0,0 @@ -package info.nightscout.interfaces.annotations - -/** - * This is the actual annotation that makes the class open. Don't use it directly, only through [InterfacesOpenForTesting] - * which has a NOOP replacement in production. - */ -@Target(AnnotationTarget.ANNOTATION_CLASS) -annotation class InterfacesOpenClass - -/** - * Annotate a class with [InterfacesOpenForTesting] if it should be extendable for testing. - */ -@InterfacesOpenClass -@Target(AnnotationTarget.CLASS) -annotation class InterfacesOpenForTesting \ No newline at end of file diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt rename to core/interfaces/src/main/java/info/nightscout/interfaces/GlucoseUnit.kt diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/plugin/PluginDescription.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/plugin/PluginDescription.kt index af5418d15c..166f009c0d 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/plugin/PluginDescription.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/plugin/PluginDescription.kt @@ -1,8 +1,8 @@ package info.nightscout.interfaces.plugin -import info.nightscout.interfaces.annotations.InterfacesOpenForTesting +import info.nightscout.annotations.OpenForTesting -@InterfacesOpenForTesting +@OpenForTesting class PluginDescription { var mainType = PluginType.GENERAL diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt b/core/interfaces/src/main/java/info/nightscout/rx/AapsSchedulers.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/AapsSchedulers.kt rename to core/interfaces/src/main/java/info/nightscout/rx/AapsSchedulers.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt b/core/interfaces/src/main/java/info/nightscout/rx/bus/RxBus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/bus/RxBus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/bus/RxBus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/Event.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/Event.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/Event.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/Event.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAcceptOpenLoopChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventAcceptOpenLoopChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAcceptOpenLoopChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventAcceptOpenLoopChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAppExit.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventAppExit.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAppExit.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventAppExit.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAppInitialized.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventAppInitialized.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAppInitialized.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventAppInitialized.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAutosensCalculationFinished.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventAutosensCalculationFinished.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventAutosensCalculationFinished.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventAutosensCalculationFinished.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventBTChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventBTChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventBTChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventBTChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventBucketedDataCreated.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventBucketedDataCreated.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventBucketedDataCreated.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventBucketedDataCreated.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventChargingState.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventChargingState.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventChargingState.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventChargingState.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventConfigBuilderChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventConfigBuilderChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventConfigBuilderChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventConfigBuilderChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventCustomActionsChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventCustomActionsChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventCustomActionsChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventCustomActionsChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventCustomCalculationFinished.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventCustomCalculationFinished.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventCustomCalculationFinished.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventCustomCalculationFinished.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDanaRSyncStatus.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventDanaRSyncStatus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDanaRSyncStatus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventDanaRSyncStatus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDeviceStatusChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventDeviceStatusChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDeviceStatusChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventDeviceStatusChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDiaconnG8PumpLogReset.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventDiaconnG8PumpLogReset.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDiaconnG8PumpLogReset.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventDiaconnG8PumpLogReset.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDismissBolusProgressIfRunning.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventDismissBolusProgressIfRunning.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDismissBolusProgressIfRunning.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventDismissBolusProgressIfRunning.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDismissNotification.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventDismissNotification.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventDismissNotification.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventDismissNotification.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventEffectiveProfileSwitchChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventEffectiveProfileSwitchChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventEffectiveProfileSwitchChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventEffectiveProfileSwitchChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventExtendedBolusChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventExtendedBolusChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventExtendedBolusChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventExtendedBolusChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventFoodDatabaseChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventFoodDatabaseChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventFoodDatabaseChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventFoodDatabaseChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventInitializationChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventInitializationChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventInitializationChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventInitializationChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLocalProfileChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventLocalProfileChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLocalProfileChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventLocalProfileChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLoop.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventLoop.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLoop.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventLoop.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLoopUpdateGui.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventLoopUpdateGui.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventLoopUpdateGui.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventLoopUpdateGui.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventMobileDataToWear.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventMobileDataToWear.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventMobileDataToWear.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventMobileDataToWear.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventMobileToWear.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventMobileToWear.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventMobileToWear.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventMobileToWear.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNSClientNewLog.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNSClientNewLog.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNSClientNewLog.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNSClientNewLog.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNSClientRestart.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNSClientRestart.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNSClientRestart.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNSClientRestart.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNetworkChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNetworkChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNetworkChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNetworkChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewBG.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNewBG.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewBG.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNewBG.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewHistoryData.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNewHistoryData.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewHistoryData.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNewHistoryData.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewOpenLoopNotification.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNewOpenLoopNotification.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNewOpenLoopNotification.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNewOpenLoopNotification.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNtpStatus.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventNtpStatus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventNtpStatus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventNtpStatus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventOfflineChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventOfflineChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventOfflineChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventOfflineChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventOverviewBolusProgress.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventOverviewBolusProgress.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventOverviewBolusProgress.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventOverviewBolusProgress.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventPreferenceChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventPreferenceChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventPreferenceChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventPreferenceChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventProfileStoreChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventProfileStoreChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventProfileStoreChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventProfileStoreChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventProfileSwitchChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventProfileSwitchChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventProfileSwitchChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventProfileSwitchChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt similarity index 97% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt index 0cf7a63171..84160e7b5d 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt +++ b/core/interfaces/src/main/java/info/nightscout/rx/events/EventPumpStatusChanged.kt @@ -1,7 +1,7 @@ package info.nightscout.rx.events import android.content.Context -import info.nightscout.shared.R +import info.nightscout.interfaces.R class EventPumpStatusChanged : EventStatus { diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventQueueChanged.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventQueueChanged.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventQueueChanged.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventQueueChanged.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRebuildTabs.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventRebuildTabs.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRebuildTabs.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventRebuildTabs.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRefreshButtonState.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventRefreshButtonState.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRefreshButtonState.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventRefreshButtonState.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRefreshOverview.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventRefreshOverview.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventRefreshOverview.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventRefreshOverview.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWRLStatus.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventSWRLStatus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWRLStatus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventSWRLStatus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWSyncStatus.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventSWSyncStatus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWSyncStatus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventSWSyncStatus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWUpdate.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventSWUpdate.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventSWUpdate.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventSWUpdate.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventScale.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventScale.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventScale.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventScale.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventStatus.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventStatus.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventStatus.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventStatus.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTempBasalChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventTempBasalChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTempBasalChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventTempBasalChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTempTargetChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventTempTargetChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTempTargetChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventTempTargetChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventThemeSwitch.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventThemeSwitch.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventThemeSwitch.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventThemeSwitch.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTherapyEventChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventTherapyEventChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTherapyEventChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventTherapyEventChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTreatmentChange.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventTreatmentChange.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventTreatmentChange.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventTreatmentChange.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateGui.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateGui.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateGui.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateGui.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewCalcProgress.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewCalcProgress.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewCalcProgress.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewCalcProgress.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewGraph.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewGraph.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewGraph.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewGraph.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewIobCob.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewIobCob.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewIobCob.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewIobCob.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewSensitivity.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewSensitivity.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventUpdateOverviewSensitivity.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventUpdateOverviewSensitivity.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearCwfExported.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventWearCwfExported.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearCwfExported.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventWearCwfExported.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearDataToMobile.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventWearDataToMobile.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearDataToMobile.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventWearDataToMobile.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearToMobile.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventWearToMobile.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearToMobile.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventWearToMobile.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearUpdateGui.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventWearUpdateGui.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventWearUpdateGui.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventWearUpdateGui.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventXdripNewLog.kt b/core/interfaces/src/main/java/info/nightscout/rx/events/EventXdripNewLog.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/events/EventXdripNewLog.kt rename to core/interfaces/src/main/java/info/nightscout/rx/events/EventXdripNewLog.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/interfaces/L.kt b/core/interfaces/src/main/java/info/nightscout/rx/interfaces/L.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/interfaces/L.kt rename to core/interfaces/src/main/java/info/nightscout/rx/interfaces/L.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/interfaces/LogElement.kt b/core/interfaces/src/main/java/info/nightscout/rx/interfaces/LogElement.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/interfaces/LogElement.kt rename to core/interfaces/src/main/java/info/nightscout/rx/interfaces/LogElement.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLogger.kt b/core/interfaces/src/main/java/info/nightscout/rx/logging/AAPSLogger.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/AAPSLogger.kt rename to core/interfaces/src/main/java/info/nightscout/rx/logging/AAPSLogger.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/BundleLogger.kt b/core/interfaces/src/main/java/info/nightscout/rx/logging/BundleLogger.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/BundleLogger.kt rename to core/interfaces/src/main/java/info/nightscout/rx/logging/BundleLogger.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/LTag.kt b/core/interfaces/src/main/java/info/nightscout/rx/logging/LTag.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/logging/LTag.kt rename to core/interfaces/src/main/java/info/nightscout/rx/logging/LTag.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt b/core/interfaces/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt similarity index 99% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt rename to core/interfaces/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt index dc659d29f5..a7f56a4e01 100644 --- a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt +++ b/core/interfaces/src/main/java/info/nightscout/rx/weardata/CustomWatchfaceFormat.kt @@ -8,7 +8,7 @@ import android.graphics.drawable.Drawable import android.graphics.drawable.PictureDrawable import androidx.annotation.StringRes import com.caverock.androidsvg.SVG -import info.nightscout.shared.R +import info.nightscout.interfaces.R import kotlinx.serialization.Serializable import org.json.JSONObject import java.io.BufferedOutputStream diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/EventData.kt b/core/interfaces/src/main/java/info/nightscout/rx/weardata/EventData.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/rx/weardata/EventData.kt rename to core/interfaces/src/main/java/info/nightscout/rx/weardata/EventData.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/SafeParse.kt b/core/interfaces/src/main/java/info/nightscout/shared/SafeParse.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/SafeParse.kt rename to core/interfaces/src/main/java/info/nightscout/shared/SafeParse.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/extensions/UIUtils.kt b/core/interfaces/src/main/java/info/nightscout/shared/extensions/UIUtils.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/extensions/UIUtils.kt rename to core/interfaces/src/main/java/info/nightscout/shared/extensions/UIUtils.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt b/core/interfaces/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt rename to core/interfaces/src/main/java/info/nightscout/shared/interfaces/ProfileUtil.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ResourceHelper.kt b/core/interfaces/src/main/java/info/nightscout/shared/interfaces/ResourceHelper.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/interfaces/ResourceHelper.kt rename to core/interfaces/src/main/java/info/nightscout/shared/interfaces/ResourceHelper.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences/SP.kt b/core/interfaces/src/main/java/info/nightscout/shared/sharedPreferences/SP.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/sharedPreferences/SP.kt rename to core/interfaces/src/main/java/info/nightscout/shared/sharedPreferences/SP.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt b/core/interfaces/src/main/java/info/nightscout/shared/utils/DateUtil.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/DateUtil.kt rename to core/interfaces/src/main/java/info/nightscout/shared/utils/DateUtil.kt diff --git a/app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/T.kt b/core/interfaces/src/main/java/info/nightscout/shared/utils/T.kt similarity index 100% rename from app-wear-shared/shared/src/main/java/info/nightscout/shared/utils/T.kt rename to core/interfaces/src/main/java/info/nightscout/shared/utils/T.kt diff --git a/core/interfaces/src/main/res/values/strings.xml b/core/interfaces/src/main/res/values/strings.xml index 983f5ad355..25af997279 100644 --- a/core/interfaces/src/main/res/values/strings.xml +++ b/core/interfaces/src/main/res/values/strings.xml @@ -3,4 +3,104 @@ Pump driver changed. + insulin_button_increment_1 + insulin_button_increment_2 + insulin_button_increment_3 + + + %1$d m ago + %1$d minutes ago + %1$.1f h ago + %1$.1f days ago + %1$.0f days ago + in %1$.0f days + in %1$.0f days + h + days + hours + second + minute + hour + day + week + seconds + minutes + hours + days + weeks + m + d + Later today + Tomorrow + Today + Yesterday + + + Connecting for %1$d s + Handshaking + Connected + Disconnecting + Waiting for disconnection + + + Created at: %1$s + Author: %1$s + Name: %1$s + File name: %1$s + Plugin version: %1$s + Name: %1$s (%2$s) + Info: %1$s + %1$s + Show IOB + Show detailed IOB + Show COB + Show Delta + Show detailed Delta + Show AvgDelta + Show Phone Battery + Show Rig Battery + Show Basal Rate + Show Loop Status + Show BG + Show BGI + Show Direction Arrow + Show Ago + Show Week number + Default watchface, you can click on EXPORT WATCHFACE button to generate a template + Default Watchface + Background image + Graphs (BG, basal, prediction lines...) + Image in front of graph and behind text fields + Free text 1 + Free text 2 + Free text 3 + Free text 4 + IOB label or IOB Sum if detailed + IOB Sum or (Bolus_IOB|Basal_IOB) if detailed + COB label + COB value + Short BG delta + Average BG delta (15min) + Phone battery (%) + Global loop battery (%) + Basal Rate + BGI value + Time (HH:MM or HH:MM:SS) + Hour (HH) + Minute (MM) + Second (SS) + AM or PM + Name of day of the week + Day (DD) + Week number (ww) + Month name (short) + Loop status and ago + Direction arrow + Mintutes ago for last received BG + BG value + Cover image in front of text (dials…) + Image of hour hand (Analog Watch) + Image of minute hand (Analog Watch) + Image of second hand (Analog Watch) + diff --git a/app-wear-shared/shared/src/main/res/values/wear_paths.xml b/core/interfaces/src/main/res/values/wear_paths.xml similarity index 100% rename from app-wear-shared/shared/src/main/res/values/wear_paths.xml rename to core/interfaces/src/main/res/values/wear_paths.xml diff --git a/app-wear-shared/shared/src/release/java/info/nightscout/annotations/OpenForTesting.kt b/core/interfaces/src/release/java/info/nightscout/annotations/OpenForTesting.kt similarity index 100% rename from app-wear-shared/shared/src/release/java/info/nightscout/annotations/OpenForTesting.kt rename to core/interfaces/src/release/java/info/nightscout/annotations/OpenForTesting.kt diff --git a/core/interfaces/src/release/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt b/core/interfaces/src/release/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt deleted file mode 100644 index 9f92faa1f7..0000000000 --- a/core/interfaces/src/release/java/info/nightscout/interfaces/annotations/InterfacesOpenForTesting.kt +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.interfaces.annotations - -/** - * Annotate a class with InterfacesOpenForTestingif it should be extendable for testing. - * In production the class remains final. - */ -@Target(AnnotationTarget.CLASS) -annotation class InterfacesOpenForTesting \ No newline at end of file diff --git a/app-wear-shared/shared/src/test/java/info/nightscout/rx/RxSchedulerRule.kt b/core/interfaces/src/test/java/info/nightscout/rx/RxSchedulerRule.kt similarity index 100% rename from app-wear-shared/shared/src/test/java/info/nightscout/rx/RxSchedulerRule.kt rename to core/interfaces/src/test/java/info/nightscout/rx/RxSchedulerRule.kt diff --git a/app-wear-shared/shared/src/test/java/info/nightscout/rx/weardata/EventDataTest.kt b/core/interfaces/src/test/java/info/nightscout/rx/weardata/EventDataTest.kt similarity index 100% rename from app-wear-shared/shared/src/test/java/info/nightscout/rx/weardata/EventDataTest.kt rename to core/interfaces/src/test/java/info/nightscout/rx/weardata/EventDataTest.kt diff --git a/app-wear-shared/shared/src/test/java/info/nightscout/shared/SafeParseTest.kt b/core/interfaces/src/test/java/info/nightscout/shared/SafeParseTest.kt similarity index 100% rename from app-wear-shared/shared/src/test/java/info/nightscout/shared/SafeParseTest.kt rename to core/interfaces/src/test/java/info/nightscout/shared/SafeParseTest.kt diff --git a/core/main/build.gradle b/core/main/build.gradle index cc5c7b7392..4f27351da0 100644 --- a/core/main/build.gradle +++ b/core/main/build.gradle @@ -13,7 +13,6 @@ apply from: "${project.rootDir}/core/main/test_dependencies.gradle" apply from: "${project.rootDir}/core/main/jacoco_global.gradle" dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':core:graphview') implementation project(':core:interfaces') diff --git a/core/main/src/main/java/info/nightscout/core/graph/data/EffectiveProfileSwitchDataPoint.kt b/core/main/src/main/java/info/nightscout/core/graph/data/EffectiveProfileSwitchDataPoint.kt index 6588a0d24e..339ffa097e 100644 --- a/core/main/src/main/java/info/nightscout/core/graph/data/EffectiveProfileSwitchDataPoint.kt +++ b/core/main/src/main/java/info/nightscout/core/graph/data/EffectiveProfileSwitchDataPoint.kt @@ -19,7 +19,7 @@ class EffectiveProfileSwitchDataPoint( get() = "" + (if (data.originalPercentage != 100) "${data.originalPercentage}%" else "") + (if (data.originalPercentage != 100 && data.originalTimeshift != 0L) "," else "") + - (if (data.originalTimeshift != 0L) (T.msecs(data.originalTimeshift).hours().toString() + rh.gs(info.nightscout.shared.R.string.shorthour)) else "") + (if (data.originalTimeshift != 0L) (T.msecs(data.originalTimeshift).hours().toString() + rh.gs(info.nightscout.interfaces.R.string.shorthour)) else "") override val duration = 0L override val shape = PointsWithLabelGraphSeries.Shape.PROFILE override val size = 2f diff --git a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt index e8707962c1..472a062f98 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt @@ -89,7 +89,7 @@ class DateUtilTest : TestBase() { } */ @Test fun timeFrameStringTest() { - `when`(rh.gs(info.nightscout.shared.R.string.shorthour)).thenReturn("h") + `when`(rh.gs(info.nightscout.interfaces.R.string.shorthour)).thenReturn("h") Assertions.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), rh)) } } diff --git a/core/validators/build.gradle b/core/validators/build.gradle index c96c66abe0..a0233c2a1c 100644 --- a/core/validators/build.gradle +++ b/core/validators/build.gradle @@ -16,7 +16,7 @@ android { dependencies { - implementation project(':app-wear-shared:shared') + implementation project(':core:interfaces') implementation project(':app-wear-shared:shared-impl') api "com.google.android.material:material:$material_version" } \ No newline at end of file diff --git a/implementation/build.gradle b/implementation/build.gradle index 177a3b439f..51b6af396d 100644 --- a/implementation/build.gradle +++ b/implementation/build.gradle @@ -15,7 +15,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:main') diff --git a/implementation/src/main/java/info/nightscout/implementation/TranslatorImpl.kt b/implementation/src/main/java/info/nightscout/implementation/TranslatorImpl.kt index 6d6fa99f61..9188069b78 100644 --- a/implementation/src/main/java/info/nightscout/implementation/TranslatorImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/TranslatorImpl.kt @@ -107,10 +107,10 @@ class TranslatorImpl @Inject internal constructor( override fun translate(units: ValueWithUnit?): String = when (units) { is ValueWithUnit.Gram -> rh.gs(info.nightscout.core.ui.R.string.shortgram) - is ValueWithUnit.Hour -> rh.gs(info.nightscout.shared.R.string.shorthour) + is ValueWithUnit.Hour -> rh.gs(info.nightscout.interfaces.R.string.shorthour) is ValueWithUnit.Insulin -> rh.gs(info.nightscout.core.ui.R.string.insulin_unit_shortname) is ValueWithUnit.Mgdl -> rh.gs(info.nightscout.core.ui.R.string.mgdl) - is ValueWithUnit.Minute -> rh.gs(info.nightscout.shared.R.string.shortminute) + is ValueWithUnit.Minute -> rh.gs(info.nightscout.interfaces.R.string.shortminute) is ValueWithUnit.Mmoll -> rh.gs(info.nightscout.core.ui.R.string.mmol) is ValueWithUnit.Percent -> rh.gs(info.nightscout.core.ui.R.string.shortpercent) is ValueWithUnit.UnitPerHour -> rh.gs(info.nightscout.core.ui.R.string.profile_ins_units_per_hour) diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/TddCalculatorImpl.kt b/implementation/src/main/java/info/nightscout/implementation/stats/TddCalculatorImpl.kt index bd68592865..8b6ca19cdf 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/TddCalculatorImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/TddCalculatorImpl.kt @@ -164,7 +164,7 @@ class TddCalculatorImpl @Inject constructor( } todayTdd?.let { layout.addView(TextView(context).apply { - text = rh.gs(info.nightscout.shared.R.string.today) + text = rh.gs(info.nightscout.interfaces.R.string.today) setTypeface(typeface, Typeface.BOLD) gravity = Gravity.CENTER_HORIZONTAL setTextAppearance(android.R.style.TextAppearance_Material_Medium) diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/TirImpl.kt b/implementation/src/main/java/info/nightscout/implementation/stats/TirImpl.kt index b57ebe56ee..4eed035b41 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/TirImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/TirImpl.kt @@ -69,7 +69,7 @@ class TirImpl(override val date: Long, override val lowThreshold: Double, overri val lp = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f) row.layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT) row.gravity = Gravity.CENTER_HORIZONTAL - row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 0 }; text = "%02d".format(days) + " " + rh.gs(info.nightscout.shared.R.string.days) }) + row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 0 }; text = "%02d".format(days) + " " + rh.gs(info.nightscout.interfaces.R.string.days) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 1 }; text = rh.gs(info.nightscout.core.ui.R.string.formatPercent, belowPct()) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 2 }; text = rh.gs(info.nightscout.core.ui.R.string.formatPercent, inRangePct()) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 3 }; text = rh.gs(info.nightscout.core.ui.R.string.formatPercent, abovePct()) }) diff --git a/implementation/src/main/java/info/nightscout/implementation/stats/TotalDailyDoseExtension.kt b/implementation/src/main/java/info/nightscout/implementation/stats/TotalDailyDoseExtension.kt index 85f711a224..ce57b0bdc2 100644 --- a/implementation/src/main/java/info/nightscout/implementation/stats/TotalDailyDoseExtension.kt +++ b/implementation/src/main/java/info/nightscout/implementation/stats/TotalDailyDoseExtension.kt @@ -54,7 +54,7 @@ fun TotalDailyDose.toTableRow(context: Context, rh: ResourceHelper, days: Int, i if ((total.isNaN() || bolusAmount.isNaN() || basalAmount.isNaN() || carbs.isNaN()).not()) { row.layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT) row.gravity = Gravity.CENTER_HORIZONTAL - row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 0 }; text = "%02d".format(days) + " " + rh.gs(info.nightscout.shared.R.string.days) }) + row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 0 }; text = "%02d".format(days) + " " + rh.gs(info.nightscout.interfaces.R.string.days) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 1 }; text = rh.gs(info.nightscout.core.ui.R.string.format_insulin_units1, total) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 2 }; text = rh.gs(info.nightscout.core.ui.R.string.format_insulin_units1, bolusAmount) }) row.addView(TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL; layoutParams = lp.apply { column = 3 }; text = rh.gs(info.nightscout.core.ui.R.string.format_insulin_units1, basalAmount) }) diff --git a/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt b/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt index 6a2c4fe9d1..00ac6dd1c7 100644 --- a/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/userEntry/UserEntryPresentationHelperImpl.kt @@ -170,8 +170,8 @@ class UserEntryPresentationHelperImpl @Inject constructor( csvString(info.nightscout.core.ui.R.string.insulin_unit_shortname), csvString(info.nightscout.core.ui.R.string.profile_ins_units_per_hour), csvString(info.nightscout.core.ui.R.string.shortpercent), - csvString(info.nightscout.shared.R.string.shorthour), - csvString(info.nightscout.shared.R.string.shortminute), + csvString(info.nightscout.interfaces.R.string.shorthour), + csvString(info.nightscout.interfaces.R.string.shortminute), csvString(info.nightscout.core.ui.R.string.ue_none) ) + "\n" diff --git a/insight/build.gradle b/insight/build.gradle index 10c064743f..78ebd94579 100644 --- a/insight/build.gradle +++ b/insight/build.gradle @@ -30,7 +30,6 @@ dependencies { implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') - implementation project(':app-wear-shared:shared') implementation project(':pump:pump-common') api "androidx.room:room-ktx:$room_version" diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 07064764eb..cf0392107d 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -221,7 +221,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick string = info.nightscout.core.ui.R.string.connecting; break; case CONNECTED: - string = info.nightscout.shared.R.string.connected; + string = info.nightscout.interfaces.R.string.connected; break; case RECOVERING: string = R.string.recovering; diff --git a/plugins/aps/build.gradle b/plugins/aps/build.gradle index 633891e71c..e24cfbe42a 100644 --- a/plugins/aps/build.gradle +++ b/plugins/aps/build.gradle @@ -15,7 +15,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:main') diff --git a/plugins/automation/build.gradle b/plugins/automation/build.gradle index c41a3d430d..2fecd1f02e 100644 --- a/plugins/automation/build.gradle +++ b/plugins/automation/build.gradle @@ -17,14 +17,13 @@ android { dependencies { implementation project(':core:graphview') + implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') implementation project(':core:validators') implementation project(':database:entities') implementation project(':database:impl') - implementation project(':app-wear-shared:shared') - implementation project(':core:interfaces') testImplementation project(':app-wear-shared:shared-tests') testImplementation project(':implementation') diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBolusAgo.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBolusAgo.kt index d784811c5b..2b0c75b3b2 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBolusAgo.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBolusAgo.kt @@ -83,7 +83,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { LayoutBuilder() .add(StaticLabel(rh, R.string.lastboluslabel, this)) .add(comparator) - .add(LabelWithElement(rh, rh.gs(R.string.lastboluslabel) + ": ", rh.gs(info.nightscout.shared.R.string.unit_minutes), minutesAgo)) + .add(LabelWithElement(rh, rh.gs(R.string.lastboluslabel) + ": ", rh.gs(info.nightscout.interfaces.R.string.unit_minutes), minutesAgo)) .build(root) } } \ No newline at end of file diff --git a/plugins/configuration/build.gradle b/plugins/configuration/build.gradle index e407d97d9e..f052fe6843 100644 --- a/plugins/configuration/build.gradle +++ b/plugins/configuration/build.gradle @@ -17,7 +17,6 @@ android { dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt index 6a4bbc8b2a..f1f5727a53 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/maintenance/activities/CustomWatchfaceImportListActivity.kt @@ -93,7 +93,7 @@ class CustomWatchfaceImportListActivity: TranslatedDaggerAppCompatActivity() { val drawable = customWatchfaceFile.resDatas[ResFileMap.CUSTOM_WATCHFACE.fileName]?.toDrawable(resources) with(holder.customWatchfaceImportListItemBinding) { val fileName = metadata[CWF_FILENAME]?.let { "$it${ZipWatchfaceFormat.CWF_EXTENTION}"} ?:"" - filelistName.text = rh.gs(info.nightscout.shared.R.string.metadata_wear_import_filename, fileName) + filelistName.text = rh.gs(info.nightscout.interfaces.R.string.metadata_wear_import_filename, fileName) filelistName.tag = customWatchfaceFile customWatchface.setImageDrawable(drawable) customName.text = rh.gs(CWF_NAME.label, metadata[CWF_NAME]) diff --git a/plugins/constraints/build.gradle b/plugins/constraints/build.gradle index 05ab1fb88a..119eb33d88 100644 --- a/plugins/constraints/build.gradle +++ b/plugins/constraints/build.gradle @@ -16,7 +16,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:ui') diff --git a/plugins/insulin/build.gradle b/plugins/insulin/build.gradle index 74d0c33bc4..31c8144ae0 100644 --- a/plugins/insulin/build.gradle +++ b/plugins/insulin/build.gradle @@ -16,7 +16,6 @@ android { dependencies { - implementation project(':app-wear-shared:shared') implementation project(':core:graphview') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/plugins/main/build.gradle b/plugins/main/build.gradle index dfd942ee1a..3f14652c4c 100644 --- a/plugins/main/build.gradle +++ b/plugins/main/build.gradle @@ -15,7 +15,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt index b55d8710aa..b499553e72 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/ui/StatusLightHandler.kt @@ -146,11 +146,11 @@ class StatusLightHandler @Inject constructor( } private fun TherapyEvent.age(useShortText: Boolean, rh: ResourceHelper, dateUtil: DateUtil): String { val diff = dateUtil.computeDiff(timestamp, System.currentTimeMillis()) - var days = " " + rh.gs(info.nightscout.shared.R.string.days) + " " - var hours = " " + rh.gs(info.nightscout.shared.R.string.hours) + " " + var days = " " + rh.gs(info.nightscout.interfaces.R.string.days) + " " + var hours = " " + rh.gs(info.nightscout.interfaces.R.string.hours) + " " if (useShortText) { - days = rh.gs(info.nightscout.shared.R.string.shortday) - hours = rh.gs(info.nightscout.shared.R.string.shorthour) + days = rh.gs(info.nightscout.interfaces.R.string.shortday) + hours = rh.gs(info.nightscout.interfaces.R.string.shorthour) } return diff[TimeUnit.DAYS].toString() + days + diff[TimeUnit.HOURS] + hours } diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt index 2f9e46f04b..fbb7e0701a 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -750,8 +750,8 @@ class DataHandlerMobile @Inject constructor( bolusPercentage = sp.getInt(info.nightscout.core.utils.R.string.key_boluswizard_percentage, 100), maxCarbs = sp.getInt(info.nightscout.core.utils.R.string.key_treatmentssafety_maxcarbs, 48), maxBolus = sp.getDouble(info.nightscout.core.utils.R.string.key_treatmentssafety_maxbolus, 3.0), - insulinButtonIncrement1 = sp.getDouble(info.nightscout.shared.R.string.key_insulin_button_increment_1, Constants.INSULIN_PLUS1_DEFAULT), - insulinButtonIncrement2 = sp.getDouble(info.nightscout.shared.R.string.key_insulin_button_increment_2, Constants.INSULIN_PLUS2_DEFAULT), + insulinButtonIncrement1 = sp.getDouble(info.nightscout.interfaces.R.string.key_insulin_button_increment_1, Constants.INSULIN_PLUS1_DEFAULT), + insulinButtonIncrement2 = sp.getDouble(info.nightscout.interfaces.R.string.key_insulin_button_increment_2, Constants.INSULIN_PLUS2_DEFAULT), carbsButtonIncrement1 = sp.getInt(info.nightscout.core.utils.R.string.key_carbs_button_increment_1, Constants.CARBS_FAV1_DEFAULT), carbsButtonIncrement2 = sp.getInt(info.nightscout.core.utils.R.string.key_carbs_button_increment_2, Constants.CARBS_FAV2_DEFAULT) ) diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt index 5ac3495db4..b868b87f72 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt @@ -77,8 +77,8 @@ class DataLayerListenerServiceMobile : WearableListenerService() { private val disposable = CompositeDisposable() - private val rxPath get() = getString(info.nightscout.shared.R.string.path_rx_bridge) - private val rxDataPath get() = getString(info.nightscout.shared.R.string.path_rx_data_bridge) + private val rxPath get() = getString(info.nightscout.interfaces.R.string.path_rx_bridge) + private val rxDataPath get() = getString(info.nightscout.interfaces.R.string.path_rx_data_bridge) @ExperimentalSerializationApi override fun onCreate() { AndroidInjection.inject(this) diff --git a/plugins/sensitivity/build.gradle b/plugins/sensitivity/build.gradle index 48544e8cd5..451ec3783e 100644 --- a/plugins/sensitivity/build.gradle +++ b/plugins/sensitivity/build.gradle @@ -16,7 +16,6 @@ android { dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:interfaces') diff --git a/plugins/smoothing/build.gradle b/plugins/smoothing/build.gradle index 8a10643212..aab84d1216 100644 --- a/plugins/smoothing/build.gradle +++ b/plugins/smoothing/build.gradle @@ -17,7 +17,6 @@ android { dependencies { implementation project(':database:entities') - implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') implementation project(':core:ui') } \ No newline at end of file diff --git a/plugins/source/build.gradle b/plugins/source/build.gradle index 92d8f31d79..962f225c5d 100644 --- a/plugins/source/build.gradle +++ b/plugins/source/build.gradle @@ -16,7 +16,6 @@ android { dependencies { - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') diff --git a/plugins/sync/build.gradle b/plugins/sync/build.gradle index 63f799cc9c..e097e626a7 100644 --- a/plugins/sync/build.gradle +++ b/plugins/sync/build.gradle @@ -15,7 +15,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':database:entities') implementation project(':database:impl') diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt index 83b32ad668..bf0b62f41c 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclientV3/NSClientV3Plugin.kt @@ -158,12 +158,12 @@ class NSClientV3Plugin @Inject constructor( when { sp.getBoolean(R.string.key_ns_paused, false) -> rh.gs(info.nightscout.core.ui.R.string.paused) isAllowed.not() -> blockingReason - sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_use_ws, true) && wsConnected -> "WS: " + rh.gs(info.nightscout.shared.R.string.connected) + sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_use_ws, true) && wsConnected -> "WS: " + rh.gs(info.nightscout.interfaces.R.string.connected) sp.getBoolean(info.nightscout.core.utils.R.string.key_ns_use_ws, true) && !wsConnected -> "WS: " + rh.gs(R.string.not_connected) lastOperationError != null -> rh.gs(info.nightscout.core.ui.R.string.error) nsAndroidClient?.lastStatus == null -> rh.gs(R.string.not_connected) workIsRunning() -> rh.gs(R.string.working) - nsAndroidClient?.lastStatus?.apiPermissions?.isFull() == true -> rh.gs(info.nightscout.shared.R.string.connected) + nsAndroidClient?.lastStatus?.apiPermissions?.isFull() == true -> rh.gs(info.nightscout.interfaces.R.string.connected) nsAndroidClient?.lastStatus?.apiPermissions?.isRead() == true -> rh.gs(R.string.read_only) else -> rh.gs(info.nightscout.core.ui.R.string.unknown) } diff --git a/pump/combo/build.gradle b/pump/combo/build.gradle index d558afb179..ea42b5a33f 100644 --- a/pump/combo/build.gradle +++ b/pump/combo/build.gradle @@ -24,7 +24,6 @@ dependencies { implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') - implementation project(':app-wear-shared:shared') testImplementation project(':app-wear-shared:shared-tests') diff --git a/pump/combov2/build.gradle b/pump/combov2/build.gradle index 852ed510ac..fd35c11a7e 100644 --- a/pump/combov2/build.gradle +++ b/pump/combov2/build.gradle @@ -15,10 +15,11 @@ dependencies { implementation project(':core:interfaces') implementation project(':core:ui') implementation project(':core:utils') - implementation project(':app-wear-shared:shared') implementation(project(":pump:combov2:comboctl")) - implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version") - implementation("org.jetbrains.kotlinx:kotlinx-datetime:$kotlinx_datetime_version") + + api "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" + api "org.jetbrains.kotlinx:kotlinx-datetime:$kotlinx_datetime_version" + // This is necessary to avoid errors like these which otherwise come up often at runtime: // "WARNING: Failed to transform class kotlinx/datetime/TimeZone$Companion // java.lang.NoClassDefFoundError: kotlinx/serialization/KSerializer" diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Fragment.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Fragment.kt index 8439dd4295..4ae87a043c 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Fragment.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Fragment.kt @@ -240,7 +240,7 @@ class ComboV2Fragment : DaggerFragment() { } in 60..(30 * 60) -> { - binding.combov2LastConnection.text = rh.gs(info.nightscout.shared.R.string.minago, secondsPassed / 60) + binding.combov2LastConnection.text = rh.gs(info.nightscout.interfaces.R.string.minago, secondsPassed / 60) binding.combov2LastConnection.setTextColor(Color.WHITE) } @@ -267,7 +267,7 @@ class ComboV2Fragment : DaggerFragment() { rh.gs(R.string.combov2_less_than_one_minute_ago) else -> - rh.gs(info.nightscout.shared.R.string.minago, secondsPassed / 60) + rh.gs(info.nightscout.interfaces.R.string.minago, secondsPassed / 60) } binding.combov2LastBolus.text = diff --git a/pump/dana/build.gradle b/pump/dana/build.gradle index 67222caccc..e15b20fb70 100644 --- a/pump/dana/build.gradle +++ b/pump/dana/build.gradle @@ -30,7 +30,6 @@ dependencies { implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') - implementation project(':app-wear-shared:shared') api "androidx.room:room-ktx:$room_version" api "androidx.room:room-runtime:$room_version" diff --git a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaFragment.kt b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaFragment.kt index acd4e7b830..87e5817b37 100644 --- a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaFragment.kt +++ b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaFragment.kt @@ -207,7 +207,7 @@ class DanaFragment : DaggerFragment() { if (pump.lastConnection != 0L) { val agoMilliseconds = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMilliseconds.toDouble() / 60.0 / 1000.0).toInt() - binding.lastConnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(info.nightscout.shared.R.string.minago, agoMin) + ")" + binding.lastConnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(info.nightscout.interfaces.R.string.minago, agoMin) + ")" warnColors.setColor(binding.lastConnection, agoMin.toDouble(), 16.0, 31.0) } if (pump.lastBolusTime != 0L) { diff --git a/pump/danar/build.gradle b/pump/danar/build.gradle index a3ad984f0c..79b21390b3 100644 --- a/pump/danar/build.gradle +++ b/pump/danar/build.gradle @@ -15,8 +15,6 @@ android { } dependencies { - implementation 'androidx.media3:media3-common:1.1.1' - implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:utils') @@ -24,6 +22,8 @@ dependencies { implementation project(':core:validators') implementation project(':pump:dana') + api 'androidx.media3:media3-common:1.1.1' + testImplementation project(':app-wear-shared:shared-tests') testImplementation project(':core:main') } \ No newline at end of file diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java index f723ac765d..9c30704f35 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java @@ -405,7 +405,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { rxBus.send(new EventPumpStatusChanged(rh.gs(info.nightscout.pump.dana.R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(new MsgStatus(injector)); bolusingEvent.setPercent(100); - rxBus.send(new EventPumpStatusChanged(rh.gs(info.nightscout.shared.R.string.disconnecting))); + rxBus.send(new EventPumpStatusChanged(rh.gs(info.nightscout.interfaces.R.string.disconnecting))); } }); return !start.getFailed(); diff --git a/pump/danars/build.gradle b/pump/danars/build.gradle index dc6142ef05..f8fe783a48 100644 --- a/pump/danars/build.gradle +++ b/pump/danars/build.gradle @@ -36,7 +36,6 @@ dependencies { implementation project(':core:ui') implementation project(':core:validators') implementation project(':pump:dana') - implementation project(':app-wear-shared:shared') testImplementation project(':app-wear-shared:shared-tests') testImplementation project(':core:main') diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt index 1a63f6433c..a230a49c53 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt @@ -346,7 +346,7 @@ class DanaRSService : DaggerService() { rxBus.send(EventPumpStatusChanged(rh.gs(info.nightscout.pump.dana.R.string.gettingbolusstatus))) sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus bolusingEvent.percent = 100 - rxBus.send(EventPumpStatusChanged(rh.gs(info.nightscout.shared.R.string.disconnecting))) + rxBus.send(EventPumpStatusChanged(rh.gs(info.nightscout.interfaces.R.string.disconnecting))) } }) return !start.failed diff --git a/pump/diaconn/build.gradle b/pump/diaconn/build.gradle index 0d0b4f6d38..95c51bd3af 100644 --- a/pump/diaconn/build.gradle +++ b/pump/diaconn/build.gradle @@ -25,7 +25,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':app-wear-shared:shared-impl') implementation project(':core:libraries') implementation project(':core:interfaces') diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Fragment.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Fragment.kt index eab7ce0a82..196134e88b 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Fragment.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Fragment.kt @@ -160,7 +160,7 @@ class DiaconnG8Fragment : DaggerFragment() { if (pump.lastConnection != 0L) { val agoMsec = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt() - binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(info.nightscout.shared.R.string.minago, agoMin) + ")" + binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + rh.gs(info.nightscout.interfaces.R.string.minago, agoMin) + ")" warnColors.setColor(binding.lastconnection, agoMin.toDouble(), 16.0, 31.0) } if (pump.lastBolusTime != 0L) { diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/service/DiaconnG8Service.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/service/DiaconnG8Service.kt index 3c766a5058..24c0a03ffc 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/service/DiaconnG8Service.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/service/DiaconnG8Service.kt @@ -538,7 +538,7 @@ class DiaconnG8Service : DaggerService() { if(!diaconnG8Pump.isPumpVersionGe3_53) { bolusingEvent.percent = 100 } - rxBus.send(EventPumpStatusChanged(rh.gs(info.nightscout.shared.R.string.disconnecting))) + rxBus.send(EventPumpStatusChanged(rh.gs(info.nightscout.interfaces.R.string.disconnecting))) } }) return !start.failed diff --git a/pump/eopatch/build.gradle b/pump/eopatch/build.gradle index a2baa19b46..281a2187b4 100644 --- a/pump/eopatch/build.gradle +++ b/pump/eopatch/build.gradle @@ -21,12 +21,11 @@ dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation project(':pump:eopatch-core') implementation project(':core:libraries') - implementation project(':app-wear-shared:shared') - implementation project(':database:entities') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:utils') implementation project(':core:ui') + implementation project(':database:entities') api "com.google.guava:guava:$guava_version" diff --git a/pump/medtronic/build.gradle b/pump/medtronic/build.gradle index c724e23a24..f842108c8d 100644 --- a/pump/medtronic/build.gradle +++ b/pump/medtronic/build.gradle @@ -16,7 +16,6 @@ android { dependencies { implementation project(':core:libraries') - implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:ui') diff --git a/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index f449b22fb0..bec36b69a6 100644 --- a/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/pump/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -275,7 +275,7 @@ class MedtronicFragment : DaggerFragment() { } else if (medtronicPumpStatus.lastConnection + 30 * 60 * 1000 < System.currentTimeMillis()) { if (min < 60) { - binding.lastConnection.text = rh.gs(info.nightscout.shared.R.string.minago, min) + binding.lastConnection.text = rh.gs(info.nightscout.interfaces.R.string.minago, min) } else if (min < 1440) { val h = (min / 60).toInt() binding.lastConnection.text = (rh.gq(info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R.plurals.duration_hours, h, h) + " " diff --git a/pump/medtrum/build.gradle b/pump/medtrum/build.gradle index f1f2e6a263..9107869f50 100644 --- a/pump/medtrum/build.gradle +++ b/pump/medtrum/build.gradle @@ -19,15 +19,14 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':core:libraries') implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:ui') + implementation project(':core:utils') implementation project(':core:validators') implementation project(':pump:pump-common') - implementation project(':core:utils') testImplementation project(':app-wear-shared:shared-tests') testImplementation project(':core:main') diff --git a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/ui/viewmodel/MedtrumOverviewViewModel.kt b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/ui/viewmodel/MedtrumOverviewViewModel.kt index 8291983817..dcc15dc074 100644 --- a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/ui/viewmodel/MedtrumOverviewViewModel.kt +++ b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/ui/viewmodel/MedtrumOverviewViewModel.kt @@ -177,7 +177,7 @@ class MedtrumOverviewViewModel @Inject constructor( if (medtrumPump.lastConnection != 0L) { val agoMilliseconds = System.currentTimeMillis() - medtrumPump.lastConnection val agoMinutes = agoMilliseconds / 1000 / 60 - _lastConnectionMinAgo.postValue(rh.gs(info.nightscout.shared.R.string.minago, agoMinutes)) + _lastConnectionMinAgo.postValue(rh.gs(info.nightscout.interfaces.R.string.minago, agoMinutes)) } if (medtrumPump.lastBolusTime != 0L) { val agoMilliseconds = System.currentTimeMillis() - medtrumPump.lastBolusTime diff --git a/pump/omnipod-common/build.gradle b/pump/omnipod-common/build.gradle index 51397ea938..2258b47333 100644 --- a/pump/omnipod-common/build.gradle +++ b/pump/omnipod-common/build.gradle @@ -20,7 +20,6 @@ dependencies { implementation project(':core:interfaces') implementation project(':core:ui') implementation project(':core:utils') - implementation project(':app-wear-shared:shared') api "androidx.constraintlayout:constraintlayout:$constraintlayout_version" api "androidx.fragment:fragment-ktx:$fragmentktx_version" diff --git a/pump/omnipod-dash/build.gradle b/pump/omnipod-dash/build.gradle index f36ba39872..2021a42fa5 100644 --- a/pump/omnipod-dash/build.gradle +++ b/pump/omnipod-dash/build.gradle @@ -27,7 +27,6 @@ android { dependencies { implementation project(':database:entities') implementation project(':database:impl') - implementation project(':app-wear-shared:shared') implementation project(':core:libraries') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/pump/omnipod-eros/build.gradle b/pump/omnipod-eros/build.gradle index 6407f5b795..92da56024e 100644 --- a/pump/omnipod-eros/build.gradle +++ b/pump/omnipod-eros/build.gradle @@ -27,7 +27,6 @@ android { dependencies { implementation project(':database:entities') implementation project(':database:impl') - implementation project(':app-wear-shared:shared') implementation project(':core:libraries') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/pump/pump-common/build.gradle b/pump/pump-common/build.gradle index 9112c217ad..1f69307954 100644 --- a/pump/pump-common/build.gradle +++ b/pump/pump-common/build.gradle @@ -18,7 +18,6 @@ dependencies { implementation project(':core:interfaces') implementation project(':core:main') implementation project(':core:utils') - implementation project(':app-wear-shared:shared') implementation('com.thoughtworks.xstream:xstream:1.4.20') { exclude group: 'xmlpull', module: 'xmlpull' diff --git a/pump/pump-common/src/main/java/info/nightscout/pump/common/defs/PumpDriverState.kt b/pump/pump-common/src/main/java/info/nightscout/pump/common/defs/PumpDriverState.kt index 432cb2d074..601a0db542 100644 --- a/pump/pump-common/src/main/java/info/nightscout/pump/common/defs/PumpDriverState.kt +++ b/pump/pump-common/src/main/java/info/nightscout/pump/common/defs/PumpDriverState.kt @@ -9,14 +9,14 @@ enum class PumpDriverState(var resourceId: Int) { NotInitialized(R.string.pump_status_not_initialized), // this state should be set only when driver is created Connecting(info.nightscout.core.ui.R.string.connecting), // - Connected(info.nightscout.shared.R.string.connected), // + Connected(info.nightscout.interfaces.R.string.connected), // Initialized(R.string.pump_status_initialized), // this is weird state that probably won't be used, since its more driver centric that communication centric EncryptCommunication(R.string.pump_status_encrypt), // Ready(R.string.pump_status_ready), Busy(R.string.pump_status_busy), // Suspended(R.string.pump_status_suspended), // ExecutingCommand(R.string.pump_status_executing_command), - Disconnecting(info.nightscout.shared.R.string.disconnecting), + Disconnecting(info.nightscout.interfaces.R.string.disconnecting), Disconnected(info.nightscout.core.ui.R.string.disconnected); fun isConnected(): Boolean = this == Connected || this == Initialized || this == Busy || this == Suspended diff --git a/pump/rileylink/build.gradle b/pump/rileylink/build.gradle index 03620015ee..439dfa0917 100644 --- a/pump/rileylink/build.gradle +++ b/pump/rileylink/build.gradle @@ -15,7 +15,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':core:interfaces') implementation project(':core:ui') implementation project(':pump:pump-common') diff --git a/pump/virtual/build.gradle b/pump/virtual/build.gradle index ecdf3d7798..f22de01853 100644 --- a/pump/virtual/build.gradle +++ b/pump/virtual/build.gradle @@ -17,7 +17,6 @@ android { } dependencies { - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':core:interfaces') implementation project(':core:main') diff --git a/settings.gradle b/settings.gradle index 816e1ae58d..02f044b440 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,6 +1,5 @@ include ':app' include ':wear' -include ':app-wear-shared:shared' include ':app-wear-shared:shared-impl' include ':app-wear-shared:shared-tests' include ':core:main' diff --git a/ui/build.gradle b/ui/build.gradle index 65f2b951c7..43d3d72941 100644 --- a/ui/build.gradle +++ b/ui/build.gradle @@ -17,7 +17,6 @@ android { dependencies { implementation project(':core:libraries') implementation project(':core:graphview') - implementation project(':app-wear-shared:shared') implementation project(':database:entities') implementation project(':database:impl') implementation project(':core:interfaces') diff --git a/ui/src/main/java/info/nightscout/ui/activityMonitor/ActivityMonitor.kt b/ui/src/main/java/info/nightscout/ui/activityMonitor/ActivityMonitor.kt index 07bfea0f9e..410806021b 100644 --- a/ui/src/main/java/info/nightscout/ui/activityMonitor/ActivityMonitor.kt +++ b/ui/src/main/java/info/nightscout/ui/activityMonitor/ActivityMonitor.kt @@ -102,7 +102,7 @@ class ActivityMonitor @Inject constructor( row.gravity = Gravity.CENTER_HORIZONTAL row.addView(TextView(context).apply { layoutParams = lp.apply { column = 0 }; text = activity }) row.addView(TextView(context).apply { layoutParams = lp.apply { column = 1 }; text = duration }) - row.addView(TextView(context).apply { layoutParams = lp.apply { column = 2 }; text = rh.gs(info.nightscout.shared.R.string.in_days, days.toDouble()) }) + row.addView(TextView(context).apply { layoutParams = lp.apply { column = 2 }; text = rh.gs(info.nightscout.interfaces.R.string.in_days, days.toDouble()) }) } ) } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt index 0cc7b4cb5d..927733e1e7 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt @@ -276,7 +276,7 @@ class CarbsDialog : DialogFragmentWithDate() { actions.add(rh.gs(info.nightscout.core.ui.R.string.alarminxmin, timeOffset).formatColor(context, rh, info.nightscout.core.ui.R.attr.infoColor)) val duration = binding.duration.value.toInt() if (duration > 0) - actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + duration + rh.gs(info.nightscout.shared.R.string.shorthour)) + actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + duration + rh.gs(info.nightscout.interfaces.R.string.shorthour)) if (carbsAfterConstraints > 0) { actions.add( rh.gs(info.nightscout.core.ui.R.string.carbs) + ": " + " Date: Tue, 19 Sep 2023 13:50:25 +0200 Subject: [PATCH 5/9] refactor ConstraintObject --- .../info/nightscout/sharedtests/TestBase.kt | 4 + .../sharedtests/TestBaseWithProfile.kt | 5 +- .../nightscout/androidaps/RealPumpTest.kt | 186 +++++---- .../androidaps/SetupWizardActivityTest.kt | 354 ++++++++-------- .../nightscout/androidaps/MainActivity.kt | 4 +- .../info/nightscout/androidaps/MainApp.kt | 3 +- .../androidaps/di/ServicesModule.kt | 2 - .../plugins/aps/loop/LoopPluginTest.kt | 8 +- .../configBuilder/ConfigBuilderPluginTest.kt | 3 +- .../constraints/ConstraintsCheckerTest.kt | 42 +- .../plugins/safety/SafetyPluginTest.kt | 136 ++++--- .../info/nightscout/interfaces/Constants.kt | 5 - .../interfaces/constraints/Constraint.kt | 121 +----- .../interfaces/constraints/Constraints.kt | 58 --- .../constraints/ConstraintsChecker.kt | 36 ++ .../constraints/PluginConstraints.kt | 28 ++ core/main/build.gradle | 1 + .../core/constraints/ConstraintObject.kt | 121 ++++++ .../nightscout/core/wizard/BolusWizard.kt | 8 +- .../nightscout/core/data/ConstraintTest.kt | 62 +-- .../info/nightscout/core/data/IobTotalTest.kt | 3 +- .../info/nightscout/core/data/ProfileTest.kt | 7 +- .../nightscout/core/utils/DateUtilTest.kt | 44 +- core/main/test_dependencies.gradle | 1 + .../queue/CommandQueueImplementation.kt | 16 +- .../queue/CommandQueueImplementationTest.kt | 19 +- .../implementation/queue/QueueThreadTest.kt | 17 +- .../implementation/wizard/BolusWizardTest.kt | 9 +- .../pump/insight/LocalInsightPlugin.java | 25 +- .../nightscout/plugins/aps/APSResultObject.kt | 26 +- .../nightscout/plugins/aps/OpenAPSFragment.kt | 2 +- .../plugins/aps/loop/LoopFragment.kt | 10 +- .../nightscout/plugins/aps/loop/LoopPlugin.kt | 13 +- .../openAPSAMA/DetermineBasalAdapterAMAJS.kt | 7 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.kt | 21 +- .../openAPSSMB/DetermineBasalAdapterSMBJS.kt | 4 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.kt | 43 +- .../OpenAPSSMBDynamicISFPlugin.kt | 4 +- .../plugins/aps/loop/APSResultTest.kt | 24 +- plugins/automation/build.gradle | 1 + .../nightscout/automation/AutomationPlugin.kt | 8 +- .../automation/AutomationEventTest.kt | 3 +- .../automation/BolusTimerImplTest.kt | 16 +- .../automation/CarbTimerImplTest.kt | 9 +- .../automation/actions/ActionAlarmTest.kt | 2 - .../actions/ActionNotificationTest.kt | 6 +- .../automation/actions/ActionsTestBase.kt | 12 +- .../automation/triggers/TriggerTestBase.kt | 3 +- ...aintsImpl.kt => ConstraintsCheckerImpl.kt} | 116 ++++-- .../bgQualityCheck/BgQualityCheckPlugin.kt | 6 +- .../di/PluginsConstraintsModule.kt | 6 +- .../constraints/dstHelper/DstHelperPlugin.kt | 6 +- .../objectives/ObjectivesPlugin.kt | 20 +- .../objectives/objectives/Objective4.kt | 8 +- .../objectives/objectives/Objective5.kt | 4 +- .../objectives/objectives/Objective6.kt | 4 +- .../phoneChecker/PhoneCheckerPlugin.kt | 20 +- .../constraints/safety/SafetyPlugin.kt | 64 +-- .../SignatureVerifierPlugin.kt | 6 +- .../storage/StorageConstraintPlugin.kt | 6 +- .../versionChecker/VersionCheckerPlugin.kt | 10 +- .../BgQualityCheckPluginTest.kt | 384 ++++++++++++++++-- .../objectives/ObjectivesPluginTest.kt | 25 +- .../storage/StorageConstraintPluginTest.kt | 13 +- .../insulin/InsulinOrefFreePeakPluginTest.kt | 2 - .../general/overview/OverviewFragment.kt | 8 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 16 +- .../wear/wearintegration/DataHandlerMobile.kt | 22 +- .../SmsCommunicatorPluginTest.kt | 29 +- .../plugins/iob/AutosensDataStoreTest.kt | 3 +- .../sensitivity/SensitivityOref1Plugin.kt | 6 +- .../sync/nsclient/ReceiverDelegateTest.kt | 2 - .../nsclientV3/workers/DataSyncWorkerTest.kt | 2 - .../nsclientV3/workers/LoadBgWorkerTest.kt | 2 - .../nightscout/pump/combo/ComboPlugin.java | 86 ++-- .../nightscout/pump/combo/ComboPluginTest.kt | 13 +- pump/combov2/build.gradle | 1 + .../nightscout/pump/combov2/ComboV2Plugin.kt | 211 ++++++---- .../danaRKorean/DanaRKoreanPlugin.kt | 12 +- .../services/DanaRKoreanExecutionService.java | 16 +- .../androidaps/danaRv2/DanaRv2Plugin.java | 41 +- .../androidaps/danar/AbstractDanaRPlugin.java | 23 +- .../androidaps/danar/DanaRPlugin.java | 43 +- .../androidaps/danar/comm/MessageBase.kt | 4 +- .../androidaps/danar/comm/MsgBolusStart.kt | 5 +- .../danar/comm/MsgBolusStartWithSpeed.kt | 9 +- .../danar/comm/MsgSetExtendedBolusStart.kt | 15 +- .../nightscout/pump/danaR/DanaRPluginTest.kt | 25 +- .../pump/danaR/comm/DanaRTestBase.kt | 11 +- .../pump/danaR/comm/MessageHashTableRTest.kt | 4 +- .../pump/danaR/comm/MsgBolusStartTest.kt | 4 +- .../danaR/comm/MsgBolusStartWithSpeedTest.kt | 4 +- .../comm/MsgSetExtendedBolusStartTest.kt | 4 +- .../pump/danaRKorean/DanaRKoreanPluginTest.kt | 25 +- .../comm/MessageHashTableRKoreanTest.kt | 4 +- .../pump/danaRv2/DanaRv2PluginTest.kt | 25 +- .../danaRv2/comm/MessageHashTableRv2Test.kt | 4 +- .../nightscout/pump/danars/DanaRSPlugin.kt | 28 +- .../DanaRSPacketBolusSetStepBolusStart.kt | 8 +- .../pump/danars/services/DanaRSService.kt | 4 +- .../pump/danars/DanaRSPluginTest.kt | 19 +- .../nightscout/pump/danars/DanaRSTestBase.kt | 11 + .../danars/comm/DanaRsMessageHashTableTest.kt | 8 +- .../DanaRsPacketBolusSetStepBolusStartTest.kt | 8 +- ...naRsPacketNotifyDeliveryRateDisplayTest.kt | 4 +- .../pump/diaconn/DiaconnG8Plugin.kt | 26 +- .../pump/medtronic/MedtronicTestBase.kt | 3 - .../comm/MedtronicHistoryDataUTest.kt | 4 - .../nightscout/pump/medtrum/MedtrumPlugin.kt | 10 +- .../pump/medtrum/services/MedtrumService.kt | 6 +- pump/omnipod-dash/build.gradle | 1 + .../omnipod/dash/history/DashHistoryTest.kt | 1 - .../omnipod/eros/history/ErosHistoryTest.kt | 1 + .../omnipod/eros/OmnipodErosPumpPluginTest.kt | 6 +- .../manager/AapsErosPodStateManagerTest.kt | 4 - .../pump/common/PumpPluginAbstract.kt | 4 +- .../pump/virtual/VirtualPumpPluginUTest.kt | 2 - .../info/nightscout/ui/dialogs/CarbsDialog.kt | 10 +- .../ui/dialogs/ExtendedBolusDialog.kt | 10 +- .../info/nightscout/ui/dialogs/FillDialog.kt | 10 +- .../nightscout/ui/dialogs/InsulinDialog.kt | 10 +- .../info/nightscout/ui/dialogs/LoopDialog.kt | 18 +- .../nightscout/ui/dialogs/TempBasalDialog.kt | 12 +- .../nightscout/ui/dialogs/TempTargetDialog.kt | 4 +- .../nightscout/ui/dialogs/TreatmentDialog.kt | 14 +- .../nightscout/ui/dialogs/WizardDialog.kt | 8 +- .../java/info/nightscout/ui/widget/Widget.kt | 10 +- 127 files changed, 1818 insertions(+), 1367 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt delete mode 100644 core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraints.kt create mode 100644 core/interfaces/src/main/java/info/nightscout/interfaces/constraints/ConstraintsChecker.kt create mode 100644 core/interfaces/src/main/java/info/nightscout/interfaces/constraints/PluginConstraints.kt create mode 100644 core/main/src/main/java/info/nightscout/core/constraints/ConstraintObject.kt rename plugins/constraints/src/main/java/info/nightscout/plugins/constraints/{ConstraintsImpl.kt => ConstraintsCheckerImpl.kt} (57%) diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt index 35f4960822..dabbc8c6fa 100644 --- a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBase.kt @@ -2,6 +2,8 @@ package info.nightscout.sharedtests import android.annotation.SuppressLint import info.nightscout.rx.AapsSchedulers +import info.nightscout.rx.bus.RxBus +import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.sharedtests.rx.TestAapsSchedulers import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.extension.ExtendWith @@ -19,11 +21,13 @@ open class TestBase { val aapsLogger = AAPSLoggerTest() val aapsSchedulers: AapsSchedulers = TestAapsSchedulers() + lateinit var rxBus: RxBus @BeforeEach fun setupLocale() { Locale.setDefault(Locale.ENGLISH) System.setProperty("disableFirebase", "true") + rxBus = RxBusImpl(aapsSchedulers, aapsLogger) } @SuppressLint("CheckResult") diff --git a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt index 8a03a6fbbb..67bb7a48e0 100644 --- a/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt +++ b/app-wear-shared/shared-tests/src/main/java/info/nightscout/sharedtests/TestBaseWithProfile.kt @@ -19,10 +19,10 @@ import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileStore import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.interfaces.utils.HardLimits -import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.interfaces.ProfileUtil import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.DateUtilImpl import org.json.JSONObject import org.junit.jupiter.api.BeforeEach @@ -45,11 +45,10 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var context: Context @Mock lateinit var sp: SP - lateinit var dateUtil: DateUtilImpl + lateinit var dateUtil: DateUtil lateinit var profileUtil: ProfileUtil lateinit var decimalFormatter: DecimalFormatter lateinit var hardLimits: HardLimits - val rxBus = RxBusImpl(aapsSchedulers, aapsLogger) val profileInjector = HasAndroidInjector { AndroidInjector { diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index 43ff3c41e7..c248fcbfb3 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -1,102 +1,98 @@ package info.nightscout.androidaps -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.filters.LargeTest -import org.junit.runner.RunWith - -@LargeTest -@RunWith(AndroidJUnit4::class) +//@LargeTest +//@RunWith(AndroidJUnit4::class) class RealPumpTest { -/* - companion object { - const val R_PASSWORD = 1234 - const val R_SERIAL = "PBB00013LR_P" - } - - private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" - - @Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin - @Inject lateinit var randomBgPlugin :RandomBgPlugin - @Inject lateinit var localProfilePlugin: LocalProfilePlugin - @Inject lateinit var profileFunction: ProfileFunction - @Inject lateinit var insulinOrefUltraRapidActingPlugin: InsulinOrefUltraRapidActingPlugin - @Inject lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin - @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin - @Inject lateinit var loopPlugin: LoopPlugin - @Inject lateinit var actionsPlugin: ActionsPlugin - @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin - @Inject lateinit var objectivesPlugin: ObjectivesPlugin - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - @Inject lateinit var sp: SP - - @Rule - @JvmField - var mActivityTestRule = ActivityTestRule(MainActivity::class.java) - - @Rule - @JvmField - var mGrantPermissionRule: GrantPermissionRule = - GrantPermissionRule.grant( - android.Manifest.permission.ACCESS_FINE_LOCATION, - android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, - android.Manifest.permission.WRITE_EXTERNAL_STORAGE - ) - - @Before - fun clear() { - sp.clear() - sp.putBoolean(R.string.key_setupwizard_processed, true) - sp.putString(R.string.key_aps_mode, "closed") - MainApp.getDbHelper().resetDatabases() - MainApp.devBranch = false - } - - private fun preparePlugins() { - // Source - configBuilderPlugin.performPluginSwitch(randomBgPlugin,true, PluginType.BGSOURCE) - // Profile - configBuilderPlugin.performPluginSwitch(localProfilePlugin, true, PluginType.PROFILE) - val profile = Profile(JSONObject(validProfile), Constants.MGDL) - Assert.assertTrue(profile.isValid("Test")) - localProfilePlugin.profiles.clear() - localProfilePlugin.numOfProfiles = 0 - val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile") - localProfilePlugin.addProfile(singleProfile) - val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, dateUtil._now()) - treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch) - // Insulin - configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN) - // Pump - sp.putInt(R.string.key_danar_password, R_PASSWORD) - sp.putString(R.string.key_danar_bt_name, R_SERIAL) - configBuilderPlugin.performPluginSwitch((pump as PluginBase), true, PluginType.PUMP) - // Sensitivity - configBuilderPlugin.performPluginSwitch(sensitivityOref1Plugin, true, PluginType.SENSITIVITY) - // APS - configBuilderPlugin.performPluginSwitch(openAPSSMBPlugin, true, PluginType.APS) - configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP) - - // Enable common - configBuilderPlugin.performPluginSwitch(actionsPlugin, true, ) - - // Disable unneeded - MainApp.getPluginsList().remove(objectivesPlugin) - } - - @Test - fun doTest() { - Assert.assertTrue(isRunningTest()) - preparePlugins() - - while (!pump.isInitialized) { - //log.debug("Waiting for initialization") - SystemClock.sleep(1000) + /* + companion object { + const val R_PASSWORD = 1234 + const val R_SERIAL = "PBB00013LR_P" } - while (true) { - //log.debug("Tick") - SystemClock.sleep(1000) + private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + + @Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin + @Inject lateinit var randomBgPlugin :RandomBgPlugin + @Inject lateinit var localProfilePlugin: LocalProfilePlugin + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var insulinOrefUltraRapidActingPlugin: InsulinOrefUltraRapidActingPlugin + @Inject lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin + @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin + @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var actionsPlugin: ActionsPlugin + @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject lateinit var objectivesPlugin: ObjectivesPlugin + @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var sp: SP + + @Rule + @JvmField + var mActivityTestRule = ActivityTestRule(MainActivity::class.java) + + @Rule + @JvmField + var mGrantPermissionRule: GrantPermissionRule = + GrantPermissionRule.grant( + android.Manifest.permission.ACCESS_FINE_LOCATION, + android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE + ) + + @Before + fun clear() { + sp.clear() + sp.putBoolean(R.string.key_setupwizard_processed, true) + sp.putString(R.string.key_aps_mode, "closed") + MainApp.getDbHelper().resetDatabases() + MainApp.devBranch = false } - } - */ + + private fun preparePlugins() { + // Source + configBuilderPlugin.performPluginSwitch(randomBgPlugin,true, PluginType.BGSOURCE) + // Profile + configBuilderPlugin.performPluginSwitch(localProfilePlugin, true, PluginType.PROFILE) + val profile = Profile(JSONObject(validProfile), Constants.MGDL) + Assert.assertTrue(profile.isValid("Test")) + localProfilePlugin.profiles.clear() + localProfilePlugin.numOfProfiles = 0 + val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile") + localProfilePlugin.addProfile(singleProfile) + val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, dateUtil._now()) + treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch) + // Insulin + configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN) + // Pump + sp.putInt(R.string.key_danar_password, R_PASSWORD) + sp.putString(R.string.key_danar_bt_name, R_SERIAL) + configBuilderPlugin.performPluginSwitch((pump as PluginBase), true, PluginType.PUMP) + // Sensitivity + configBuilderPlugin.performPluginSwitch(sensitivityOref1Plugin, true, PluginType.SENSITIVITY) + // APS + configBuilderPlugin.performPluginSwitch(openAPSSMBPlugin, true, PluginType.APS) + configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP) + + // Enable common + configBuilderPlugin.performPluginSwitch(actionsPlugin, true, ) + + // Disable unneeded + MainApp.getPluginsList().remove(objectivesPlugin) + } + + @Test + fun doTest() { + Assert.assertTrue(isRunningTest()) + preparePlugins() + + while (!pump.isInitialized) { + //log.debug("Waiting for initialization") + SystemClock.sleep(1000) + } + + while (true) { + //log.debug("Tick") + SystemClock.sleep(1000) + } + } + */ } \ No newline at end of file diff --git a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt index ba6a794cab..d5efa1841c 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt @@ -1,195 +1,191 @@ package info.nightscout.androidaps -import androidx.test.ext.junit.runners.AndroidJUnit4 -import androidx.test.filters.LargeTest -import org.junit.runner.RunWith - -@LargeTest -@RunWith(AndroidJUnit4::class) +//@LargeTest +//@RunWith(AndroidJUnit4::class) class SetupWizardActivityTest { -/* - @Rule - @JvmField - var mActivityTestRule = ActivityTestRule(SetupWizardActivity::class.java) + /* + @Rule + @JvmField + var mActivityTestRule = ActivityTestRule(SetupWizardActivity::class.java) - @Rule - @JvmField - var mGrantPermissionRule: GrantPermissionRule = - GrantPermissionRule.grant( - android.Manifest.permission.ACCESS_FINE_LOCATION, - android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, - android.Manifest.permission.WRITE_EXTERNAL_STORAGE - ) + @Rule + @JvmField + var mGrantPermissionRule: GrantPermissionRule = + GrantPermissionRule.grant( + android.Manifest.permission.ACCESS_FINE_LOCATION, + android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + android.Manifest.permission.WRITE_EXTERNAL_STORAGE + ) - @Before - fun clear() { - sp.clear() - } -/* - -To run from command line -gradlew connectedFullDebugAndroidTest - -do not run when your production phone is connected !!! - -do this before for running in emulator -adb shell settings put global window_animation_scale 0 & -adb shell settings put global transition_animation_scale 0 & -adb shell settings put global animator_duration_scale 0 & - */ - - @Test - fun setupWizardActivityTest() { - sp.clear() - Assert.assertTrue(isRunningTest()) - // Welcome page - onView(withId(R.id.next_button)).perform(click()) - // Language selection - onView(withText("English")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Agreement page - onView(withText("I UNDERSTAND AND AGREE")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Location permission - var askButton = onView(withText("Ask for permission")) - if (askButton.isDisplayed()) { - askButton.perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) + @Before + fun clear() { + sp.clear() } - // Store permission - askButton = onView(withText("Ask for permission")) - if (askButton.isDisplayed()) { - askButton.perform(scrollTo(), click()) - onView(withText("OK")).perform(click()) + /* + + To run from command line + gradlew connectedFullDebugAndroidTest + + do not run when your production phone is connected !!! + + do this before for running in emulator + adb shell settings put global window_animation_scale 0 & + adb shell settings put global transition_animation_scale 0 & + adb shell settings put global animator_duration_scale 0 & + */ + + @Test + fun setupWizardActivityTest() { + sp.clear() + Assert.assertTrue(isRunningTest()) + // Welcome page + onView(withId(R.id.next_button)).perform(click()) + // Language selection + onView(withText("English")).perform(scrollTo(), click()) onView(withId(R.id.next_button)).waitAndPerform(click()) - } - // Import settings : skip of found - askButton = onView(withText("IMPORT SETTINGS")) - if (askButton.isDisplayed()) { + // Agreement page + onView(withText("I UNDERSTAND AND AGREE")).perform(scrollTo(), click()) onView(withId(R.id.next_button)).waitAndPerform(click()) - } - // Units selection - onView(withText("mmol/L")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).perform(click()) - // Display target selection - onView(withText("4.2")).perform(scrollTo(), ViewActions.replaceText("5")) - onView(withText("10.0")).perform(scrollTo(), ViewActions.replaceText("11")) - onView(withId(R.id.next_button)).perform(click()) - // NSClient - onView(withId(R.id.next_button)).perform(click()) - // Age selection - onView(withText("Adult")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Insulin selection - onView(withText("Ultra-Rapid Oref")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // BG source selection - onView(withText("Random BG")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Profile selection - onView(withText("Local Profile")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Local profile - DIA - onView(withTagValue(Matchers.`is`("LP_DIA"))).perform(scrollTo(), ViewActions.replaceText("6.0")) - // Local profile - IC - onView(withId(R.id.ic_tab)).perform(scrollTo(), click()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("IC-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("2"), ViewActions.closeSoftKeyboard()) - // Local profile - ISF - onView(withId(R.id.isf_tab)).perform(scrollTo(), click()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("ISF-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("3"), ViewActions.closeSoftKeyboard()) - // Local profile - BAS - onView(withId(R.id.basal_tab)).perform(scrollTo(), click()) - onView(childAtPosition(Matchers.allOf(withId(R.id.localprofile_basal), childAtPosition(withClassName(Matchers.`is`("android.widget.LinearLayout")), 6)), 2)) - .perform(scrollTo(), click()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("1.1"), ViewActions.closeSoftKeyboard()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-1")), isDisplayed())) - .perform(ViewActions.replaceText("1.2"), ViewActions.closeSoftKeyboard()) - onView(Matchers.allOf(withId(R.id.timelistedit_time), childAtPosition(childAtPosition(withId(R.id.localprofile_basal), 2), 0))) - .perform(scrollTo(), click()) - onData(Matchers.anything()).inAdapterView(childAtPosition(withClassName(Matchers.`is`("android.widget.PopupWindow\$PopupBackgroundView")), 0)).atPosition(13) - .perform(click()) - // Local profile - TARGET - onView(withId(R.id.target_tab)).perform(scrollTo(), click()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-1-0")), isDisplayed())) - .perform(ViewActions.replaceText("6"), ViewActions.closeSoftKeyboard()) - onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-2-0")), isDisplayed())) - .perform(ViewActions.replaceText("6.5"), ViewActions.closeSoftKeyboard()) - onView(withText("Save")).perform(scrollTo(), click()) - onView(Matchers.allOf(withId(R.id.localprofile_profileswitch), isDisplayed())) - .perform(scrollTo(), click()) - onView(allOf(withId(R.id.ok), isDisplayed())).perform(click()) - // confirm dialog - //onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone - clickOkInDialog() - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Profile switch - askButton = onView(withText("Do Profile Switch")) - if (askButton.isDisplayed()) { - askButton.perform(scrollTo(), click()) + // Location permission + var askButton = onView(withText("Ask for permission")) + if (askButton.isDisplayed()) { + askButton.perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + } + // Store permission + askButton = onView(withText("Ask for permission")) + if (askButton.isDisplayed()) { + askButton.perform(scrollTo(), click()) + onView(withText("OK")).perform(click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + } + // Import settings : skip of found + askButton = onView(withText("IMPORT SETTINGS")) + if (askButton.isDisplayed()) { + onView(withId(R.id.next_button)).waitAndPerform(click()) + } + // Units selection + onView(withText("mmol/L")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).perform(click()) + // Display target selection + onView(withText("4.2")).perform(scrollTo(), ViewActions.replaceText("5")) + onView(withText("10.0")).perform(scrollTo(), ViewActions.replaceText("11")) + onView(withId(R.id.next_button)).perform(click()) + // NSClient + onView(withId(R.id.next_button)).perform(click()) + // Age selection + onView(withText("Adult")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Insulin selection + onView(withText("Ultra-Rapid Oref")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // BG source selection + onView(withText("Random BG")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Profile selection + onView(withText("Local Profile")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Local profile - DIA + onView(withTagValue(Matchers.`is`("LP_DIA"))).perform(scrollTo(), ViewActions.replaceText("6.0")) + // Local profile - IC + onView(withId(R.id.ic_tab)).perform(scrollTo(), click()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("IC-1-0")), isDisplayed())) + .perform(ViewActions.replaceText("2"), ViewActions.closeSoftKeyboard()) + // Local profile - ISF + onView(withId(R.id.isf_tab)).perform(scrollTo(), click()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("ISF-1-0")), isDisplayed())) + .perform(ViewActions.replaceText("3"), ViewActions.closeSoftKeyboard()) + // Local profile - BAS + onView(withId(R.id.basal_tab)).perform(scrollTo(), click()) + onView(childAtPosition(Matchers.allOf(withId(R.id.localprofile_basal), childAtPosition(withClassName(Matchers.`is`("android.widget.LinearLayout")), 6)), 2)) + .perform(scrollTo(), click()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-0")), isDisplayed())) + .perform(ViewActions.replaceText("1.1"), ViewActions.closeSoftKeyboard()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("BASAL-1-1")), isDisplayed())) + .perform(ViewActions.replaceText("1.2"), ViewActions.closeSoftKeyboard()) + onView(Matchers.allOf(withId(R.id.timelistedit_time), childAtPosition(childAtPosition(withId(R.id.localprofile_basal), 2), 0))) + .perform(scrollTo(), click()) + onData(Matchers.anything()).inAdapterView(childAtPosition(withClassName(Matchers.`is`("android.widget.PopupWindow\$PopupBackgroundView")), 0)).atPosition(13) + .perform(click()) + // Local profile - TARGET + onView(withId(R.id.target_tab)).perform(scrollTo(), click()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-1-0")), isDisplayed())) + .perform(ViewActions.replaceText("6"), ViewActions.closeSoftKeyboard()) + onView(Matchers.allOf(withTagValue(Matchers.`is`("TARGET-2-0")), isDisplayed())) + .perform(ViewActions.replaceText("6.5"), ViewActions.closeSoftKeyboard()) + onView(withText("Save")).perform(scrollTo(), click()) + onView(Matchers.allOf(withId(R.id.localprofile_profileswitch), isDisplayed())) + .perform(scrollTo(), click()) onView(allOf(withId(R.id.ok), isDisplayed())).perform(click()) - // onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone + // confirm dialog + //onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone clickOkInDialog() - while (ProfileFunctions.getInstance().profile == null) SystemClock.sleep(100) onView(withId(R.id.next_button)).waitAndPerform(click()) - } - // Pump - onView(withText("Virtual Pump")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // APS - onView(withText("OpenAPS SMB")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Open Closed Loop - onView(withText("Closed Loop")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Loop - askButton = onView(withText("Enable loop")) - if (askButton.isDisplayed()) { - askButton.perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - } - // Sensitivity - onView(withText("Sensitivity Oref1")).perform(scrollTo(), click()) - onView(withId(R.id.next_button)).waitAndPerform(click()) - // Objectives - onView(allOf(withText("Start"), isDisplayed())).perform(scrollTo(), click()) - onView(withId(R.id.finish_button)).waitAndPerform(click()) - - // Verify settings - Assert.assertEquals(Constants.MMOL, ProfileFunctions.getSystemUnits()) - Assert.assertEquals(17.0, HardLimits.maxBolus(), 0.0001) // Adult - Assert.assertTrue(RandomBgPlugin.isEnabled(PluginType.BGSOURCE)) - Assert.assertTrue(LocalProfilePlugin.isEnabled(PluginType.PROFILE)) - val p = ProfileFunctions.getInstance().profile - Assert.assertNotNull(p) - Assert.assertEquals(2.0, p!!.ic, 0.0001) - Assert.assertEquals(3.0 * Constants.MMOLL_TO_MGDL, p.isfMgdl, 0.0001) - Assert.assertEquals(1.1, p.getBasalTimeFromMidnight(0), 0.0001) - Assert.assertEquals(6.0 * Constants.MMOLL_TO_MGDL, p.targetLowMgdl, 0.0001) - Assert.assertTrue(VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP)) - Assert.assertTrue(OpenAPSSMBPlugin.getPlugin().isEnabled()) - Assert.assertTrue(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) - Assert.assertTrue(SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) - Assert.assertTrue(ObjectivesPlugin.objectives[0].isStarted) - } - - private fun childAtPosition( - parentMatcher: Matcher, position: Int): Matcher { - - return object : TypeSafeMatcher() { - override fun describeTo(description: Description) { - description.appendText("Child at position $position in parent ") - parentMatcher.describeTo(description) + // Profile switch + askButton = onView(withText("Do Profile Switch")) + if (askButton.isDisplayed()) { + askButton.perform(scrollTo(), click()) + onView(allOf(withId(R.id.ok), isDisplayed())).perform(click()) + // onView(Matchers.allOf(withText("OK"), isDisplayed())).perform(click()) not working on real phone + clickOkInDialog() + while (ProfileFunctions.getInstance().profile == null) SystemClock.sleep(100) + onView(withId(R.id.next_button)).waitAndPerform(click()) } + // Pump + onView(withText("Virtual Pump")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // APS + onView(withText("OpenAPS SMB")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Open Closed Loop + onView(withText("Closed Loop")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Loop + askButton = onView(withText("Enable loop")) + if (askButton.isDisplayed()) { + askButton.perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + } + // Sensitivity + onView(withText("Sensitivity Oref1")).perform(scrollTo(), click()) + onView(withId(R.id.next_button)).waitAndPerform(click()) + // Objectives + onView(allOf(withText("Start"), isDisplayed())).perform(scrollTo(), click()) + onView(withId(R.id.finish_button)).waitAndPerform(click()) - public override fun matchesSafely(view: View): Boolean { - val parent = view.parent - return parent is ViewGroup && parentMatcher.matches(parent) - && view == parent.getChildAt(position) + // Verify settings + Assert.assertEquals(Constants.MMOL, ProfileFunctions.getSystemUnits()) + Assert.assertEquals(17.0, HardLimits.maxBolus(), 0.0001) // Adult + Assert.assertTrue(RandomBgPlugin.isEnabled(PluginType.BGSOURCE)) + Assert.assertTrue(LocalProfilePlugin.isEnabled(PluginType.PROFILE)) + val p = ProfileFunctions.getInstance().profile + Assert.assertNotNull(p) + Assert.assertEquals(2.0, p!!.ic, 0.0001) + Assert.assertEquals(3.0 * Constants.MMOLL_TO_MGDL, p.isfMgdl, 0.0001) + Assert.assertEquals(1.1, p.getBasalTimeFromMidnight(0), 0.0001) + Assert.assertEquals(6.0 * Constants.MMOLL_TO_MGDL, p.targetLowMgdl, 0.0001) + Assert.assertTrue(VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP)) + Assert.assertTrue(OpenAPSSMBPlugin.getPlugin().isEnabled()) + Assert.assertTrue(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) + Assert.assertTrue(SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) + Assert.assertTrue(ObjectivesPlugin.objectives[0].isStarted) + } + + private fun childAtPosition( + parentMatcher: Matcher, position: Int): Matcher { + + return object : TypeSafeMatcher() { + override fun describeTo(description: Description) { + description.appendText("Child at position $position in parent ") + parentMatcher.describeTo(description) + } + + public override fun matchesSafely(view: View): Boolean { + val parent = view.parent + return parent is ViewGroup && parentMatcher.matches(parent) + && view == parent.getChildAt(position) + } } } - } - */ + */ } diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index 9adbcafd07..ffc876d687 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -52,7 +52,7 @@ import info.nightscout.database.entities.UserEntry.Sources import info.nightscout.interfaces.AndroidPermission import info.nightscout.interfaces.Config import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.maintenance.PrefFileListProvider import info.nightscout.interfaces.plugin.ActivePlugin @@ -96,7 +96,7 @@ class MainActivity : DaggerAppCompatActivityWithResult() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var iconsProvider: IconsProvider - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin @Inject lateinit var uel: UserEntryLogger @Inject lateinit var profileFunction: ProfileFunction diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt index 67b544ed75..3c3e6b1a9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -38,6 +38,7 @@ import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.versionChecker.VersionCheckerUtils +import info.nightscout.plugins.aps.utils.StaticInjector import info.nightscout.plugins.general.overview.notifications.NotificationStore import info.nightscout.plugins.general.themes.ThemeSwitcherPlugin import info.nightscout.rx.logging.AAPSLogger @@ -77,7 +78,7 @@ class MainApp : DaggerApplication() { @Inject lateinit var compatDBHelper: CompatDBHelper @Inject lateinit var repository: AppRepository @Inject lateinit var dateUtil: DateUtil - @Suppress("unused") @Inject lateinit var staticInjector: info.nightscout.plugins.aps.utils.StaticInjector// TODO avoid , here fake only to initialize + @Suppress("unused") @Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize @Inject lateinit var uel: UserEntryLogger @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var notificationStore: NotificationStore diff --git a/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt b/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt deleted file mode 100644 index 200b83579f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt +++ /dev/null @@ -1,2 +0,0 @@ -package info.nightscout.androidaps.di - diff --git a/app/src/test/java/info/nightscout/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/plugins/aps/loop/LoopPluginTest.kt index 7f74063515..69c9d56b79 100644 --- a/app/src/test/java/info/nightscout/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/plugins/aps/loop/LoopPluginTest.kt @@ -8,8 +8,7 @@ import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.ApsMode import info.nightscout.interfaces.Config -import info.nightscout.sdk.interfaces.RunningConfiguration -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin @@ -20,7 +19,7 @@ import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.receivers.ReceiverStatusStore import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.virtual.VirtualPumpPlugin -import info.nightscout.rx.bus.RxBus +import info.nightscout.sdk.interfaces.RunningConfiguration import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -34,8 +33,7 @@ import org.mockito.Mockito.`when` class LoopPluginTest : TestBase() { @Mock lateinit var sp: SP - private val rxBus: RxBus = RxBus(aapsSchedulers, aapsLogger) - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var rh: ResourceHelper @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var context: Context diff --git a/app/src/test/java/info/nightscout/plugins/configBuilder/ConfigBuilderPluginTest.kt b/app/src/test/java/info/nightscout/plugins/configBuilder/ConfigBuilderPluginTest.kt index 3013ce8090..3061e18835 100644 --- a/app/src/test/java/info/nightscout/plugins/configBuilder/ConfigBuilderPluginTest.kt +++ b/app/src/test/java/info/nightscout/plugins/configBuilder/ConfigBuilderPluginTest.kt @@ -8,7 +8,6 @@ import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.ui.UiInteraction -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.sharedtests.TestBase @@ -37,6 +36,6 @@ class ConfigBuilderPluginTest : TestBase() { @BeforeEach fun prepareMock() { - configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, rh, sp, RxBus(aapsSchedulers, aapsLogger), activePlugin, uel, pumpSync, protectionCheck, uiInteraction) + configBuilderPlugin = ConfigBuilderPlugin(injector, aapsLogger, rh, sp, rxBus, activePlugin, uel, pumpSync, protectionCheck, uiInteraction) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt index ad5bac6590..627ff00b5e 100644 --- a/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/plugins/constraints/ConstraintsCheckerTest.kt @@ -9,13 +9,14 @@ import info.nightscout.androidaps.insight.database.InsightDatabase import info.nightscout.androidaps.insight.database.InsightDatabaseDao import info.nightscout.androidaps.insight.database.InsightDbHelper import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.database.impl.AppRepository import info.nightscout.implementation.iob.GlucoseStatusProviderImpl import info.nightscout.interfaces.ApsMode import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints import info.nightscout.interfaces.constraints.Objectives +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.maintenance.PrefFileListProvider import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginType @@ -74,7 +75,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { private lateinit var danaPump: DanaPump private lateinit var insightDbHelper: InsightDbHelper - private lateinit var constraintChecker: ConstraintsImpl + private lateinit var constraintChecker: ConstraintsCheckerImpl private lateinit var safetyPlugin: SafetyPlugin private lateinit var objectivesPlugin: ObjectivesPlugin private lateinit var comboPlugin: ComboPlugin @@ -94,6 +95,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { if (it is PumpEnactResult) { it.context = context } + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } } } @@ -134,7 +138,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { `when`(sp.getString(R.string.key_danar_bt_name, "")).thenReturn("") //SafetyPlugin - constraintChecker = ConstraintsImpl(activePlugin) + constraintChecker = ConstraintsCheckerImpl(activePlugin, injector) val glucoseStatusProvider = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculator, dateUtil, decimalFormatter) @@ -226,7 +230,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { constraintsPluginsList.add(insightPlugin) constraintsPluginsList.add(openAPSAMAPlugin) constraintsPluginsList.add(openAPSSMBPlugin) - `when`(activePlugin.getSpecificPluginsListByInterface(Constraints::class.java)).thenReturn(constraintsPluginsList) + `when`(activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java)).thenReturn(constraintsPluginsList) objectivesPlugin.onStart() } @@ -268,7 +272,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val c = constraintChecker.isAutosensModeEnabled() assertThat(c.reasonList).hasSize(2) // Safety & Objectives assertThat(c.mostLimitedReasonList).hasSize(2) // Safety & Objectives - assertThat( c.value()).isFalse() + assertThat(c.value()).isFalse() } // Safety @@ -278,7 +282,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val c = constraintChecker.isAdvancedFilteringEnabled() assertThat(c.reasonList).hasSize(1) // Safety assertThat(c.mostLimitedReasonList).hasSize(1) // Safety - assertThat( c.value()).isFalse() + assertThat(c.value()).isFalse() } // SMB should limit @@ -286,7 +290,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { fun isSuperBolusEnabledTest() { openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true) val c = constraintChecker.isSuperBolusEnabled() - assertThat( c.value()).isFalse() // SMB should limit + assertThat(c.value()).isFalse() // SMB should limit } // Safety & Objectives @@ -296,11 +300,11 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { objectivesPlugin.objectives[Objectives.SMB_OBJECTIVE].startedOn = 0 `when`(sp.getBoolean(info.nightscout.plugins.aps.R.string.key_use_smb, false)).thenReturn(false) `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) -// `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(Constraint(true)) +// `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(ConstraintObject(true)) val c = constraintChecker.isSMBModeEnabled() assertThat(c.reasonList).hasSize(3) // 2x Safety & Objectives assertThat(c.mostLimitedReasonList).hasSize(3) // 2x Safety & Objectives - assertThat( c.value()).isFalse() + assertThat(c.value()).isFalse() } // applyBasalConstraints tests @@ -326,9 +330,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxBasalAllowed(validProfile) - assertThat( d.value()).isWithin( 0.01).of(0.8) + assertThat(d.value()).isWithin(0.01).of(0.8) assertThat(d.reasonList).hasSize(3) - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit") + assertThat(d.getMostLimitedReasons()).isEqualTo("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit") } @Test @@ -355,7 +359,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val i = constraintChecker.getMaxBasalPercentAllowed(validProfile) assertThat(i.value()).isEqualTo(200) assertThat(i.reasonList).hasSize(6) - assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max percent rate to 200% because of pump limit") + assertThat(i.getMostLimitedReasons()).isEqualTo("Safety: Limiting max percent rate to 200% because of pump limit") } // applyBolusConstraints tests @@ -380,9 +384,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxBolusAllowed() - assertThat( d.value()).isWithin( 0.01).of(3.0) + assertThat(d.value()).isWithin(0.01).of(3.0) assertThat(d.reasonList).hasSize(4) // 2x Safety & RS & R - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") + assertThat(d.getMostLimitedReasons()).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") } // applyCarbsConstraints tests @@ -395,7 +399,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { val i = constraintChecker.getMaxCarbsAllowed() assertThat(i.value()).isEqualTo(48) assertThat(i.reasonList).hasSize(1) - assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") + assertThat(i.getMostLimitedReasons()).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") } // applyMaxIOBConstraints tests @@ -410,9 +414,9 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxIOBAllowed() - assertThat( d.value()).isWithin( 0.01).of(1.5) + assertThat(d.value()).isWithin(0.01).of(1.5) assertThat(d.reasonList).hasSize(2) - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") + assertThat(d.getMostLimitedReasons()).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") } @Test @@ -426,8 +430,8 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { // Apply all limits val d = constraintChecker.getMaxIOBAllowed() - assertThat( d.value()).isWithin( 0.01).of(3.0) + assertThat(d.value()).isWithin(0.01).of(3.0) assertThat(d.reasonList).hasSize(2) - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") + assertThat(d.getMostLimitedReasons()).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") } } diff --git a/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt index 56e88846d8..d473e1c789 100644 --- a/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/plugins/safety/SafetyPluginTest.kt @@ -3,12 +3,12 @@ package info.nightscout.plugins.safety import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.ApsMode -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profiling.Profiler @@ -29,7 +29,7 @@ import org.mockito.Mockito.`when` class SafetyPluginTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var profiler: Profiler @@ -43,7 +43,13 @@ class SafetyPluginTest : TestBaseWithProfile() { private lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin private lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin - private val injector = HasAndroidInjector { AndroidInjector { } } + private val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } private val pumpDescription = PumpDescription() @BeforeEach @@ -86,9 +92,8 @@ class SafetyPluginTest : TestBaseWithProfile() { @Test fun pumpDescriptionShouldLimitLoopInvocation() { pumpDescription.isTempBasalCapable = false - var c = Constraint(true) - c = safetyPlugin.isLoopInvocationAllowed(c) - assertThat(c.getReasons(aapsLogger)).isEqualTo("Safety: Pump is not temp basal capable") + val c = safetyPlugin.isLoopInvocationAllowed(ConstraintObject(true, injector)) + assertThat(c.getReasons()).isEqualTo("Safety: Pump is not temp basal capable") assertThat(c.value()).isFalse() } @@ -96,47 +101,42 @@ class SafetyPluginTest : TestBaseWithProfile() { fun disabledEngineeringModeShouldLimitClosedLoop() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.CLOSED.name) `when`(config.isEngineeringModeOrRelease()).thenReturn(false) - var c = Constraint(true) - c = safetyPlugin.isClosedLoopAllowed(c) - assertThat(c.getReasons(aapsLogger)).contains("Running dev version. Closed loop is disabled.") + val c = safetyPlugin.isClosedLoopAllowed(ConstraintObject(true, injector)) + assertThat(c.getReasons()).contains("Running dev version. Closed loop is disabled.") assertThat(c.value()).isFalse() } @Test fun setOpenLoopInPreferencesShouldLimitClosedLoop() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)).thenReturn(ApsMode.OPEN.name) - var c = Constraint(true) - c = safetyPlugin.isClosedLoopAllowed(c) - assertThat(c.getReasons(aapsLogger)).contains("Closed loop mode disabled in preferences") + val c = safetyPlugin.isClosedLoopAllowed(ConstraintObject(true, injector)) + assertThat(c.getReasons()).contains("Closed loop mode disabled in preferences") assertThat(c.value()).isFalse() } @Test fun notEnabledSMBInPreferencesDisablesSMB() { `when`(sp.getBoolean(info.nightscout.plugins.aps.R.string.key_use_smb, false)).thenReturn(false) - `when`(constraintChecker.isClosedLoopAllowed(anyObject())).thenReturn(Constraint(true)) - var c = Constraint(true) - c = openAPSSMBPlugin.isSMBModeEnabled(c) - assertThat(c.getReasons(aapsLogger)).contains("SMB disabled in preferences") + `when`(constraintChecker.isClosedLoopAllowed(anyObject())).thenReturn(ConstraintObject(true, injector)) + val c = openAPSSMBPlugin.isSMBModeEnabled(ConstraintObject(true, injector)) + assertThat(c.getReasons()).contains("SMB disabled in preferences") assertThat(c.value()).isFalse() } @Test fun openLoopPreventsSMB() { `when`(sp.getBoolean(info.nightscout.plugins.aps.R.string.key_use_smb, false)).thenReturn(true) - `when`(constraintChecker.isClosedLoopAllowed(anyObject())).thenReturn(Constraint(false)) - var c = Constraint(true) - c = safetyPlugin.isSMBModeEnabled(c) - assertThat(c.getReasons(aapsLogger)).contains("SMB not allowed in open loop mode") + `when`(constraintChecker.isClosedLoopAllowed()).thenReturn(ConstraintObject(false, injector)) + val c = safetyPlugin.isSMBModeEnabled(ConstraintObject(true, injector)) + assertThat(c.getReasons()).contains("SMB not allowed in open loop mode") assertThat(c.value()).isFalse() } @Test fun bgSourceShouldPreventSMBAlways() { `when`(activePlugin.activeBgSource).thenReturn(glimpPlugin) - var c = Constraint(true) - c = safetyPlugin.isAdvancedFilteringEnabled(c) - assertThat(c.getReasons(aapsLogger)).isEqualTo("Safety: SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") + val c = safetyPlugin.isAdvancedFilteringEnabled(ConstraintObject(true, injector)) + assertThat(c.getReasons()).isEqualTo("Safety: SMB always and after carbs disabled because active BG source doesn\\'t support advanced filtering") assertThat(c.value()).isFalse() } @@ -146,24 +146,26 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getDouble(info.nightscout.plugins.aps.R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0) `when`(sp.getDouble(info.nightscout.plugins.aps.R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0) `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - val c = Constraint(Constants.REALLYHIGHBASALRATE) + val c = ConstraintObject(Double.MAX_VALUE, injector) safetyPlugin.applyBasalConstraints(c, validProfile) assertThat(c.value()).isWithin(0.01).of(2.0) - assertThat(c.getReasons(aapsLogger)).isEqualTo( + assertThat(c.getReasons()).isEqualTo( """ Safety: Limiting max basal rate to 2.00 U/h because of hard limit - """.trimIndent()) - assertThat(c.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max basal rate to 2.00 U/h because of hard limit") + """.trimIndent() + ) + assertThat(c.getMostLimitedReasons()).isEqualTo("Safety: Limiting max basal rate to 2.00 U/h because of hard limit") } @Test fun doNotAllowNegativeBasalRate() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - val d = Constraint(-0.5) + val d = ConstraintObject(-0.5, injector) safetyPlugin.applyBasalConstraints(d, validProfile) assertThat(d.value()).isWithin(0.01).of(0.0) - assertThat(d.getReasons(aapsLogger)).isEqualTo( - "Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value") + assertThat(d.getReasons()).isEqualTo( + "Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value" + ) } @Test @@ -173,19 +175,20 @@ class SafetyPluginTest : TestBaseWithProfile() { `when`(sp.getDouble(info.nightscout.plugins.aps.R.string.key_openapsama_current_basal_safety_multiplier, 4.0)).thenReturn(4.0) `when`(sp.getDouble(info.nightscout.plugins.aps.R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0) `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - val i = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) + val i = ConstraintObject(Int.MAX_VALUE, injector) safetyPlugin.applyBasalPercentConstraints(i, validProfile) assertThat(i.value()).isEqualTo(200) - assertThat(i.getReasons(aapsLogger)).isEqualTo( + assertThat(i.getReasons()).isEqualTo( """ -Safety: Percent rate 1111111% recalculated to 11111.11 U/h with current basal 1.00 U/h +Safety: Percent rate 2147483647% recalculated to 21474836.47 U/h with current basal 1.00 U/h Safety: Limiting max basal rate to 2.00 U/h because of hard limit Safety: Limiting max percent rate to 200% because of pump limit Safety: Limiting max basal rate to 500.00 U/h because of pump limit """.trimIndent() ) - assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo( - "Safety: Limiting max percent rate to 200% because of pump limit") + assertThat(i.getMostLimitedReasons()).isEqualTo( + "Safety: Limiting max percent rate to 200% because of pump limit" + ) } @Test @@ -196,57 +199,58 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getDouble(info.nightscout.plugins.aps.R.string.key_openapsama_max_daily_safety_multiplier, 3.0)).thenReturn(3.0) `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true) - val i = Constraint(Constants.REALLYHIGHBASALRATE) + val i = ConstraintObject(Double.MAX_VALUE, injector) openAPSSMBPlugin.applyBasalConstraints(i, validProfile) assertThat(i.value()).isWithin(0.01).of(1.0) - assertThat(i.getReasons(aapsLogger)).isEqualTo( + assertThat(i.getReasons()).isEqualTo( """ OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences OpenAPSSMB: Limiting max basal rate to 4.00 U/h because of max basal multiplier OpenAPSSMB: Limiting max basal rate to 3.00 U/h because of max daily basal multiplier - """.trimIndent()) - assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences") + """.trimIndent() + ) + assertThat(i.getMostLimitedReasons()).isEqualTo("OpenAPSSMB: Limiting max basal rate to 1.00 U/h because of max value in preferences") } @Test fun doNotAllowNegativePercentBasalRate() { `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - val i = Constraint(-22) + val i = ConstraintObject(-22, injector) safetyPlugin.applyBasalPercentConstraints(i, validProfile) assertThat(i.value()).isEqualTo(0) - assertThat(i.getReasons(aapsLogger)).isEqualTo( + assertThat(i.getReasons()).isEqualTo( """ Safety: Percent rate -22% recalculated to -0.22 U/h with current basal 1.00 U/h Safety: Limiting max basal rate to 0.00 U/h because of it must be positive value Safety: Limiting max percent rate to 0% because of pump limit - """.trimIndent()) - assertThat(i.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting max percent rate to 0% because of pump limit") + """.trimIndent() + ) + assertThat(i.getMostLimitedReasons()).isEqualTo("Safety: Limiting max percent rate to 0% because of pump limit") } @Test fun bolusAmountShouldBeLimited() { `when`(sp.getDouble(info.nightscout.core.utils.R.string.key_treatmentssafety_maxbolus, 3.0)).thenReturn(3.0) `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - var d = Constraint(Constants.REALLYHIGHBOLUS) - d = safetyPlugin.applyBolusConstraints(d) + val d = safetyPlugin.applyBolusConstraints(ConstraintObject(Double.MAX_VALUE, injector)) assertThat(d.value()).isWithin(0.01).of(3.0) - assertThat(d.getReasons(aapsLogger)).isEqualTo( + assertThat(d.getReasons()).isEqualTo( """ Safety: Limiting bolus to 3.0 U because of max value in preferences Safety: Limiting bolus to 5.0 U because of hard limit - """.trimIndent()) - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") + """.trimIndent() + ) + assertThat(d.getMostLimitedReasons()).isEqualTo("Safety: Limiting bolus to 3.0 U because of max value in preferences") } @Test fun doNotAllowNegativeBolusAmount() { `when`(sp.getDouble(info.nightscout.core.utils.R.string.key_treatmentssafety_maxbolus, 3.0)).thenReturn(3.0) `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("child") - var d = Constraint(-22.0) - d = safetyPlugin.applyBolusConstraints(d) + val d = safetyPlugin.applyBolusConstraints(ConstraintObject(-22.0, injector)) assertThat(d.value()).isWithin(0.01).of(0.0) - assertThat(d.getReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") + assertThat(d.getReasons()).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") + assertThat(d.getMostLimitedReasons()).isEqualTo("Safety: Limiting bolus to 0.0 U because of it must be positive value") } @Test @@ -255,15 +259,15 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getInt(info.nightscout.core.utils.R.string.key_treatmentssafety_maxcarbs, 48)).thenReturn(48) // Negative carbs not allowed - var i = Constraint(-22) + var i: Constraint = ConstraintObject(-22, injector) safetyPlugin.applyCarbsConstraints(i) assertThat(i.value()).isEqualTo(0) - assertThat(i.getReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 0 g because of it must be positive value") + assertThat(i.getReasons()).isEqualTo("Safety: Limiting carbs to 0 g because of it must be positive value") // Apply all limits - i = safetyPlugin.applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS)) + i = safetyPlugin.applyCarbsConstraints(ConstraintObject(Int.MAX_VALUE, injector)) assertThat(i.value()).isEqualTo(48) - assertThat(i.getReasons(aapsLogger)).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") + assertThat(i.getReasons()).isEqualTo("Safety: Limiting carbs to 48 g because of max value in preferences") } @Test @@ -278,24 +282,24 @@ Safety: Limiting max basal rate to 500.00 U/h because of pump limit `when`(sp.getString(info.nightscout.core.utils.R.string.key_age, "")).thenReturn("teenage") // Apply all limits - var d = Constraint(Constants.REALLYHIGHIOB) + var d: Constraint = ConstraintObject(Double.MAX_VALUE, injector) d = safetyPlugin.applyMaxIOBConstraints(d) assertThat(d.value()).isWithin(0.01).of(HardLimits.MAX_IOB_LGS) - assertThat(d.getReasons(aapsLogger)).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") + assertThat(d.getReasons()).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") + assertThat(d.getMostLimitedReasons()).isEqualTo("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend") // Apply all limits - d = Constraint(Constants.REALLYHIGHIOB) + d = ConstraintObject(Double.MAX_VALUE, injector) val a = openAPSAMAPlugin.applyMaxIOBConstraints(d) assertThat(a.value()).isWithin(0.01).of(1.5) - assertThat(d.getReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences\nOpenAPSAMA: Limiting IOB to 7.0 U because of hard limit") - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") + assertThat(d.getReasons()).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences\nOpenAPSAMA: Limiting IOB to 7.0 U because of hard limit") + assertThat(d.getMostLimitedReasons()).isEqualTo("OpenAPSAMA: Limiting IOB to 1.5 U because of max value in preferences") // Apply all limits - d = Constraint(Constants.REALLYHIGHIOB) + d = ConstraintObject(Double.MAX_VALUE, injector) val s = openAPSSMBPlugin.applyMaxIOBConstraints(d) assertThat(s.value()).isWithin(0.01).of(3.0) - assertThat(d.getReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences\nOpenAPSSMB: Limiting IOB to 22.0 U because of hard limit") - assertThat(d.getMostLimitedReasons(aapsLogger)).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") + assertThat(d.getReasons()).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences\nOpenAPSSMB: Limiting IOB to 22.0 U because of hard limit") + assertThat(d.getMostLimitedReasons()).isEqualTo("OpenAPSSMB: Limiting IOB to 3.0 U because of max value in preferences") } } diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt index fccdfcbc8f..e0c3bacd59 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt @@ -10,11 +10,6 @@ object Constants { const val MMOLL_TO_MGDL = 18.0 // 18.0182; const val MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL const val defaultDIA = 5.0 - const val REALLYHIGHBASALRATE = 1111111.0 - const val REALLYHIGHPERCENTBASALRATE = 1111111 - const val REALLYHIGHBOLUS = 1111111.0 - const val REALLYHIGHCARBS = 1111111 - const val REALLYHIGHIOB = 1111111.0 const val notificationID = 556677 // SMS COMMUNICATOR diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraint.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraint.kt index a332b9328d..e508da3fef 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraint.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraint.kt @@ -1,115 +1,18 @@ package info.nightscout.interfaces.constraints -import info.nightscout.rx.logging.AAPSLogger -import info.nightscout.rx.logging.LTag - -class Constraint>(private var value: T) { - - private var originalValue: T - private val reasons: MutableList = ArrayList() - private val mostLimiting: MutableList = ArrayList() - fun value(): T { - return value - } - - fun originalValue(): T { - return originalValue - } - - fun set(aapsLogger: AAPSLogger, value: T): Constraint { - this.value = value - originalValue = value - aapsLogger.debug(LTag.CONSTRAINTS, "Setting value $value") - return this - } - - fun set(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint { - aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") - this.value = value - addReason(reason, from) - addMostLimingReason(reason, from) - return this - } - - fun setIfDifferent(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint { - if (this.value != value) { - aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") - this.value = value - addReason(reason, from) - addMostLimingReason(reason, from) - } - return this - } - - fun setIfSmaller(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint { - if (value < this.value) { - aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") - this.value = value - mostLimiting.clear() - addMostLimingReason(reason, from) - } - if (value < originalValue) { - addReason(reason, from) - } - return this - } - - fun setIfGreater(aapsLogger: AAPSLogger, value: T, reason: String, from: Any): Constraint { - if (value > this.value) { - aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") - this.value = value - mostLimiting.clear() - addMostLimingReason(reason, from) - } - if (value > originalValue) { - addReason(reason, from) - } - return this - } - - private fun translateFrom(from: Any): String { - return from.javaClass.simpleName.replace("Plugin", "") - } - - fun addReason(reason: String, from: Any) { - reasons.add(translateFrom(from) + ": " + reason) - } - - private fun addMostLimingReason(reason: String, from: Any) { - mostLimiting.add(translateFrom(from) + ": " + reason) - } - - fun getReasons(aapsLogger: AAPSLogger): String { - val sb = StringBuilder() - for ((count, r) in reasons.withIndex()) { - if (count != 0) sb.append("\n") - sb.append(r) - } - aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") - return sb.toString() - } +interface Constraint> { + fun value(): T + fun originalValue(): T + fun set(value: T): Constraint + fun set(value: T, reason: String, from: Any): Constraint + fun setIfDifferent(value: T, reason: String, from: Any): Constraint + fun setIfSmaller(value: T, reason: String, from: Any): Constraint + fun setIfGreater(value: T, reason: String, from: Any): Constraint + fun addReason(reason: String, from: Any) + fun getReasons(): String val reasonList: List - get() = reasons - - fun getMostLimitedReasons(aapsLogger: AAPSLogger): String { - val sb = StringBuilder() - for ((count, r) in mostLimiting.withIndex()) { - if (count != 0) sb.append("\n") - sb.append(r) - } - aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") - return sb.toString() - } - + fun getMostLimitedReasons(): String val mostLimitedReasonList: List - get() = mostLimiting - - fun copyReasons(another: Constraint<*>) { - reasons.addAll(another.reasonList) - } - - init { - originalValue = value - } + fun copyReasons(another: Constraint<*>) } \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraints.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraints.kt deleted file mode 100644 index c7ed46d688..0000000000 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/Constraints.kt +++ /dev/null @@ -1,58 +0,0 @@ -package info.nightscout.interfaces.constraints - -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.profile.Profile - -/** - * Constraints interface - * - * Every function has a param from previous chained call - * Function can limit the value even more and add another reason of restriction - * - * see [info.nightscout.plugins.constraints.ConstraintsImpl] - * which iterates over all registered plugins with [Constraints] implemented - * - * @return updated parameter - */ -interface Constraints { - - fun isLoopInvocationAllowed(value: Constraint = Constraint(true)): Constraint = value - fun isClosedLoopAllowed(value: Constraint = Constraint(true)): Constraint = value - fun isLgsAllowed(value: Constraint = Constraint(true)): Constraint = value - fun isAutosensModeEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isSMBModeEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isDynIsfModeEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isUAMEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isAdvancedFilteringEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isSuperBolusEnabled(value: Constraint = Constraint(true)): Constraint = value - fun isAutomationEnabled(value: Constraint = Constraint(true)): Constraint = value - fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint = absoluteRate - fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint = percentRate - fun applyBolusConstraints(insulin: Constraint): Constraint = insulin - fun applyExtendedBolusConstraints(insulin: Constraint): Constraint = insulin - fun applyCarbsConstraints(carbs: Constraint): Constraint = carbs - fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = maxIob - - /* - * Determine max values by walking through all constraints - */ - fun getMaxBasalAllowed(profile: Profile): Constraint = - applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile) - - fun getMaxBasalPercentAllowed(profile: Profile): Constraint = - applyBasalPercentConstraints(Constraint(Constants.REALLYHIGHPERCENTBASALRATE), profile) - - fun getMaxBolusAllowed(): Constraint = - applyBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) - - fun getMaxExtendedBolusAllowed(): Constraint = - applyExtendedBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) - - fun getMaxCarbsAllowed(): Constraint = - applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS)) - - fun getMaxIOBAllowed(): Constraint = - applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB)) - - -} \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/ConstraintsChecker.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/ConstraintsChecker.kt new file mode 100644 index 0000000000..c1f3dde85d --- /dev/null +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/ConstraintsChecker.kt @@ -0,0 +1,36 @@ +package info.nightscout.interfaces.constraints + +import info.nightscout.interfaces.profile.Profile + +/** + * Constraints interface + * + * Every function has a param from previous chained call + * Function can limit the value even more and add another reason of restriction + * + * see [info.nightscout.plugins.constraints.ConstraintsCheckerImpl] + * which iterates over all registered plugins with [ConstraintsChecker] implemented + */ +interface ConstraintsChecker : PluginConstraints { + + fun isLoopInvocationAllowed(): Constraint + fun isClosedLoopAllowed(): Constraint + fun isLgsAllowed(): Constraint + fun isAutosensModeEnabled(): Constraint + fun isSMBModeEnabled(): Constraint + fun isDynIsfModeEnabled(): Constraint + fun isUAMEnabled(): Constraint + fun isAdvancedFilteringEnabled(): Constraint + fun isSuperBolusEnabled(): Constraint + fun isAutomationEnabled(): Constraint + + /* + * Determine max values by walking through all constraints + */ + fun getMaxBasalAllowed(profile: Profile): Constraint + fun getMaxBasalPercentAllowed(profile: Profile): Constraint + fun getMaxBolusAllowed(): Constraint + fun getMaxExtendedBolusAllowed(): Constraint + fun getMaxCarbsAllowed(): Constraint + fun getMaxIOBAllowed(): Constraint +} \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/PluginConstraints.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/PluginConstraints.kt new file mode 100644 index 0000000000..abc4cb45e3 --- /dev/null +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/constraints/PluginConstraints.kt @@ -0,0 +1,28 @@ +package info.nightscout.interfaces.constraints + +import info.nightscout.interfaces.profile.Profile + +/** + * PluginConstraints interface + * + * Allows to every plugin implement own constraints + */ +interface PluginConstraints { + + fun isLoopInvocationAllowed(value: Constraint): Constraint = value + fun isClosedLoopAllowed(value: Constraint): Constraint = value + fun isLgsAllowed(value: Constraint): Constraint = value + fun isAutosensModeEnabled(value: Constraint): Constraint = value + fun isSMBModeEnabled(value: Constraint): Constraint = value + fun isDynIsfModeEnabled(value: Constraint): Constraint = value + fun isUAMEnabled(value: Constraint): Constraint = value + fun isAdvancedFilteringEnabled(value: Constraint): Constraint = value + fun isSuperBolusEnabled(value: Constraint): Constraint = value + fun isAutomationEnabled(value: Constraint): Constraint = value + fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint = absoluteRate + fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint = percentRate + fun applyBolusConstraints(insulin: Constraint): Constraint = insulin + fun applyExtendedBolusConstraints(insulin: Constraint): Constraint = insulin + fun applyCarbsConstraints(carbs: Constraint): Constraint = carbs + fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = maxIob +} \ No newline at end of file diff --git a/core/main/build.gradle b/core/main/build.gradle index 4f27351da0..95c63acdde 100644 --- a/core/main/build.gradle +++ b/core/main/build.gradle @@ -20,6 +20,7 @@ dependencies { implementation project(':core:utils') testImplementation project(':app-wear-shared:shared-tests') + testImplementation project(':app-wear-shared:shared-impl') api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" diff --git a/core/main/src/main/java/info/nightscout/core/constraints/ConstraintObject.kt b/core/main/src/main/java/info/nightscout/core/constraints/ConstraintObject.kt new file mode 100644 index 0000000000..afda3ffa62 --- /dev/null +++ b/core/main/src/main/java/info/nightscout/core/constraints/ConstraintObject.kt @@ -0,0 +1,121 @@ +package info.nightscout.core.constraints + +import dagger.android.HasAndroidInjector +import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.rx.logging.AAPSLogger +import info.nightscout.rx.logging.LTag +import javax.inject.Inject + +class ConstraintObject>(private var value: T, injector: HasAndroidInjector) : Constraint { + + @Inject lateinit var aapsLogger: AAPSLogger + + private var originalValue: T + private val reasons: MutableList = ArrayList() + private val mostLimiting: MutableList = ArrayList() + override fun value(): T { + return value + } + + override fun originalValue(): T { + return originalValue + } + + override fun set(value: T): Constraint { + this.value = value + originalValue = value + aapsLogger.debug(LTag.CONSTRAINTS, "Setting value $value") + return this + } + + override fun set(value: T, reason: String, from: Any): Constraint { + aapsLogger.debug(LTag.CONSTRAINTS, "Setting value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") + this.value = value + addReason(reason, from) + addMostLimingReason(reason, from) + return this + } + + override fun setIfDifferent(value: T, reason: String, from: Any): Constraint { + if (this.value != value) { + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of different value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") + this.value = value + addReason(reason, from) + addMostLimingReason(reason, from) + } + return this + } + + override fun setIfSmaller(value: T, reason: String, from: Any): Constraint { + if (value < this.value) { + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of smaller value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") + this.value = value + mostLimiting.clear() + addMostLimingReason(reason, from) + } + if (value < originalValue) { + addReason(reason, from) + } + return this + } + + override fun setIfGreater(value: T, reason: String, from: Any): Constraint { + if (value > this.value) { + aapsLogger.debug(LTag.CONSTRAINTS, "Setting because of greater value " + this.value + " -> " + value + " (" + reason + ")[" + translateFrom(from) + "]") + this.value = value + mostLimiting.clear() + addMostLimingReason(reason, from) + } + if (value > originalValue) { + addReason(reason, from) + } + return this + } + + private fun translateFrom(from: Any): String { + return from.javaClass.simpleName.replace("Plugin", "") + } + + override fun addReason(reason: String, from: Any) { + reasons.add(translateFrom(from) + ": " + reason) + } + + private fun addMostLimingReason(reason: String, from: Any) { + mostLimiting.add(translateFrom(from) + ": " + reason) + } + + override fun getReasons(): String { + val sb = StringBuilder() + for ((count, r) in reasons.withIndex()) { + if (count != 0) sb.append("\n") + sb.append(r) + } + aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") + return sb.toString() + } + + override val reasonList: List + get() = reasons + + override fun getMostLimitedReasons(): String { + val sb = StringBuilder() + for ((count, r) in mostLimiting.withIndex()) { + if (count != 0) sb.append("\n") + sb.append(r) + } + aapsLogger.debug(LTag.CONSTRAINTS, "Limiting original value: $originalValue to $value. Reason: $sb") + return sb.toString() + } + + override val mostLimitedReasonList: List + get() = mostLimiting + + override fun copyReasons(another: Constraint<*>) { + reasons.addAll(another.reasonList) + } + + init { + injector.androidInjector().inject(this) + originalValue = value + } +} \ No newline at end of file diff --git a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt index 3c925fe15b..f623f9681e 100644 --- a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt +++ b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt @@ -4,6 +4,7 @@ import android.content.Context import android.text.Spanned import com.google.common.base.Joiner import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.highValueToUnitsToString import info.nightscout.core.extensions.lowValueToUnitsToString import info.nightscout.core.iob.round @@ -19,8 +20,7 @@ import info.nightscout.database.entities.ValueWithUnit import info.nightscout.interfaces.Config import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.automation.Automation -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.iob.GlucoseStatusProvider @@ -63,7 +63,7 @@ class BolusWizard @Inject constructor( @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileUtil: ProfileUtil - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var loop: Loop @@ -273,7 +273,7 @@ class BolusWizard @Inject constructor( val bolusStep = activePlugin.activePump.pumpDescription.bolusStep calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep) - insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() + insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(calculatedTotalInsulin, injector)).value() aapsLogger.debug(this.toString()) return this diff --git a/core/main/src/test/java/info/nightscout/core/data/ConstraintTest.kt b/core/main/src/test/java/info/nightscout/core/data/ConstraintTest.kt index 77589bd104..e961021203 100644 --- a/core/main/src/test/java/info/nightscout/core/data/ConstraintTest.kt +++ b/core/main/src/test/java/info/nightscout/core/data/ConstraintTest.kt @@ -1,6 +1,8 @@ package info.nightscout.core.data -import info.nightscout.interfaces.constraints.Constraint +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -11,41 +13,49 @@ import org.junit.jupiter.api.Test */ class ConstraintTest : TestBase() { + private val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } + @Test fun doTests() { - val b = Constraint(true) + val b = ConstraintObject(true, injector) Assertions.assertEquals(true, b.value()) - Assertions.assertEquals("", b.getReasons(aapsLogger)) - Assertions.assertEquals("", b.getMostLimitedReasons(aapsLogger)) - b.set(aapsLogger, false) + Assertions.assertEquals("", b.getReasons()) + Assertions.assertEquals("", b.getMostLimitedReasons()) + b.set(false) Assertions.assertEquals(false, b.value()) - Assertions.assertEquals("", b.getReasons(aapsLogger)) - Assertions.assertEquals("", b.getMostLimitedReasons(aapsLogger)) - b.set(aapsLogger, true, "Set true", this) + Assertions.assertEquals("", b.getReasons()) + Assertions.assertEquals("", b.getMostLimitedReasons()) + b.set(true, "Set true", this) Assertions.assertEquals(true, b.value()) - Assertions.assertEquals("ConstraintTest: Set true", b.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set true", b.getMostLimitedReasons(aapsLogger)) - b.set(aapsLogger, false, "Set false", this) + Assertions.assertEquals("ConstraintTest: Set true", b.getReasons()) + Assertions.assertEquals("ConstraintTest: Set true", b.getMostLimitedReasons()) + b.set(false, "Set false", this) Assertions.assertEquals(false, b.value()) - Assertions.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getMostLimitedReasons(aapsLogger)) - val d = Constraint(10.0) - d.set(aapsLogger, 5.0, "Set 5d", this) + Assertions.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getReasons()) + Assertions.assertEquals("ConstraintTest: Set true\nConstraintTest: Set false", b.getMostLimitedReasons()) + val d = ConstraintObject(10.0, injector) + d.set(5.0, "Set 5d", this) Assertions.assertEquals(5.0, d.value(), 0.01) - Assertions.assertEquals("ConstraintTest: Set 5d", d.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons(aapsLogger)) - d.setIfSmaller(aapsLogger, 6.0, "Set 6d", this) + Assertions.assertEquals("ConstraintTest: Set 5d", d.getReasons()) + Assertions.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons()) + d.setIfSmaller(6.0, "Set 6d", this) Assertions.assertEquals(5.0, d.value(), 0.01) - Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d", d.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons(aapsLogger)) - d.setIfSmaller(aapsLogger, 4.0, "Set 4d", this) + Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d", d.getReasons()) + Assertions.assertEquals("ConstraintTest: Set 5d", d.getMostLimitedReasons()) + d.setIfSmaller(4.0, "Set 4d", this) Assertions.assertEquals(4.0, d.value(), 0.01) - Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d", d.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set 4d", d.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d", d.getReasons()) + Assertions.assertEquals("ConstraintTest: Set 4d", d.getMostLimitedReasons()) Assertions.assertEquals(10.0, d.originalValue(), 0.01) - d.setIfDifferent(aapsLogger, 7.0, "Set 7d", this) + d.setIfDifferent(7.0, "Set 7d", this) Assertions.assertEquals(7.0, d.value(), 0.01) - Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getReasons(aapsLogger)) - Assertions.assertEquals("ConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("ConstraintTest: Set 5d\nConstraintTest: Set 6d\nConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getReasons()) + Assertions.assertEquals("ConstraintTest: Set 4d\nConstraintTest: Set 7d", d.getMostLimitedReasons()) Assertions.assertEquals(10.0, d.originalValue(), 0.01) } diff --git a/core/main/src/test/java/info/nightscout/core/data/IobTotalTest.kt b/core/main/src/test/java/info/nightscout/core/data/IobTotalTest.kt index dd32259395..8067daef2a 100644 --- a/core/main/src/test/java/info/nightscout/core/data/IobTotalTest.kt +++ b/core/main/src/test/java/info/nightscout/core/data/IobTotalTest.kt @@ -9,6 +9,7 @@ import info.nightscout.core.iob.plus import info.nightscout.core.iob.round import info.nightscout.interfaces.iob.IobTotal import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -25,7 +26,7 @@ class IobTotalTest : TestBase() { @BeforeEach fun prepare() { - dateUtil = DateUtil(context) + dateUtil = DateUtilImpl(context) now = dateUtil.now() } diff --git a/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt b/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt index c26357af2e..100f5fac12 100644 --- a/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt +++ b/core/main/src/test/java/info/nightscout/core/data/ProfileTest.kt @@ -7,11 +7,10 @@ import info.nightscout.core.profile.ProfileSealed import info.nightscout.interfaces.Config import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.utils.HardLimits -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.sharedtests.HardLimitsMock import info.nightscout.sharedtests.TestBase import info.nightscout.sharedtests.TestPumpPlugin @@ -37,7 +36,6 @@ class ProfileTest : TestBase() { @Mock lateinit var sp: SP private lateinit var hardLimits: HardLimits - private lateinit var rxBus: RxBus private lateinit var dateUtil: DateUtil private lateinit var testPumpPlugin: TestPumpPlugin @@ -59,8 +57,7 @@ class ProfileTest : TestBase() { @BeforeEach fun prepare() { testPumpPlugin = TestPumpPlugin { AndroidInjector { } } - dateUtil = DateUtil(context) - rxBus = RxBus(TestAapsSchedulers(), aapsLogger) + dateUtil = DateUtilImpl(context) hardLimits = HardLimitsMock(sp, rh) `when`(activePluginProvider.activePump).thenReturn(testPumpPlugin) `when`(rh.gs(info.nightscout.core.ui.R.string.profile_per_unit)).thenReturn("/U") diff --git a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt index 472a062f98..fb3258894e 100644 --- a/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt +++ b/core/main/src/test/java/info/nightscout/core/utils/DateUtilTest.kt @@ -3,13 +3,13 @@ package info.nightscout.core.utils import android.content.Context import com.google.common.truth.Truth.assertThat import info.nightscout.shared.interfaces.ResourceHelper -import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.shared.utils.T import info.nightscout.sharedtests.TestBase -import org.junit.jupiter.api.Assertions -import org.junit.jupiter.api.Test -import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito.`when` import java.util.Date @@ -41,45 +41,45 @@ class DateUtilTest : TestBase() { @Test fun fromISODateStringTest() { - Assertions.assertEquals(1511124634417L, DateUtil(context).fromISODateString("2017-11-19T22:50:34.417+0200")) - Assertions.assertEquals(1511124634000L, DateUtil(context).fromISODateString("2017-11-19T22:50:34+0200")) - Assertions.assertEquals(1512317365000L, DateUtil(context).fromISODateString("2017-12-03T16:09:25.000Z")) - Assertions.assertEquals(1513902750000L, DateUtil(context).fromISODateString("2017-12-22T00:32:30Z")) + Assertions.assertEquals(1511124634417L, DateUtilImpl(context).fromISODateString("2017-11-19T22:50:34.417+0200")) + Assertions.assertEquals(1511124634000L, DateUtilImpl(context).fromISODateString("2017-11-19T22:50:34+0200")) + Assertions.assertEquals(1512317365000L, DateUtilImpl(context).fromISODateString("2017-12-03T16:09:25.000Z")) + Assertions.assertEquals(1513902750000L, DateUtilImpl(context).fromISODateString("2017-12-22T00:32:30Z")) } @Test fun toISOStringTest() { - Assertions.assertEquals("2017-12-22T00:32:30.000Z", DateUtil(context).toISOString(1513902750000L)) + Assertions.assertEquals("2017-12-22T00:32:30.000Z", DateUtilImpl(context).toISOString(1513902750000L)) } @Test fun secondsOfTheDayToMillisecondsTest() { - Assertions.assertTrue(Date(DateUtil(context).secondsOfTheDayToMilliseconds((T.hours(1).secs() + T.mins(1).secs() + 1).toInt())).toString().contains("01:01:00")) + Assertions.assertTrue(Date(DateUtilImpl(context).secondsOfTheDayToMilliseconds((T.hours(1).secs() + T.mins(1).secs() + 1).toInt())).toString().contains("01:01:00")) } @Test fun toSecondsTest() { - Assertions.assertEquals(3600, DateUtil(context).toSeconds("01:00").toLong()) - Assertions.assertEquals(3600, DateUtil(context).toSeconds("01:00 a.m.").toLong()) - Assertions.assertEquals(3600, DateUtil(context).toSeconds("01:00 AM").toLong()) + Assertions.assertEquals(3600, DateUtilImpl(context).toSeconds("01:00").toLong()) + Assertions.assertEquals(3600, DateUtilImpl(context).toSeconds("01:00 a.m.").toLong()) + Assertions.assertEquals(3600, DateUtilImpl(context).toSeconds("01:00 AM").toLong()) } @Test fun dateStringTest() { - assertThat(DateUtil(context).dateString(1513902750000L)).contains("22") + assertThat(DateUtilImpl(context).dateString(1513902750000L)).contains("22") } @Test fun timeStringTest() { - Assertions.assertTrue(DateUtil(context).timeString(1513902750000L).contains("32")) + Assertions.assertTrue(DateUtilImpl(context).timeString(1513902750000L).contains("32")) } @Test fun dateAndTimeStringTest() { - assertThat(DateUtil(context).dateAndTimeString(1513902750000L)).contains("22") - assertThat(DateUtil(context).dateAndTimeString(1513902750000L)).contains("32") + assertThat(DateUtilImpl(context).dateAndTimeString(1513902750000L)).contains("22") + assertThat(DateUtilImpl(context).dateAndTimeString(1513902750000L)).contains("32") } @Test fun dateAndTimeRangeStringTest() { - assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") - assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") - assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") - assertThat(DateUtil(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") + assertThat(DateUtilImpl(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") + assertThat(DateUtilImpl(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") + assertThat(DateUtilImpl(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("22") + assertThat(DateUtilImpl(context).dateAndTimeRangeString(1513902750000L, 1513902750000L)).contains("32") } /* @@ -90,6 +90,6 @@ class DateUtilTest : TestBase() { */ @Test fun timeFrameStringTest() { `when`(rh.gs(info.nightscout.interfaces.R.string.shorthour)).thenReturn("h") - Assertions.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), rh)) + Assertions.assertEquals("(1h 1')", DateUtilImpl(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), rh)) } } diff --git a/core/main/test_dependencies.gradle b/core/main/test_dependencies.gradle index b4f8cf5370..04c57f1f70 100644 --- a/core/main/test_dependencies.gradle +++ b/core/main/test_dependencies.gradle @@ -12,6 +12,7 @@ dependencies { androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' androidTestImplementation "androidx.test.ext:junit-ktx:$androidx_junit_version" androidTestImplementation "androidx.test:rules:$androidx_rules_version" + androidTestImplementation "org.junit.jupiter:junit-jupiter-api:$junit_jupiter_version" androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' } diff --git a/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt b/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt index e66580353d..0a5fedafdd 100644 --- a/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt +++ b/implementation/src/main/java/info/nightscout/implementation/queue/CommandQueueImplementation.kt @@ -9,6 +9,7 @@ import android.text.Spanned import androidx.appcompat.app.AppCompatActivity import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.events.EventNewNotification import info.nightscout.core.extensions.getCustomizedName import info.nightscout.core.profile.ProfileSealed @@ -42,8 +43,7 @@ import info.nightscout.implementation.queue.commands.CommandTempBasalPercent import info.nightscout.implementation.queue.commands.CommandUpdateTime import info.nightscout.interfaces.AndroidPermission import info.nightscout.interfaces.Config -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin @@ -85,7 +85,7 @@ class CommandQueueImplementation @Inject constructor( private val rxBus: RxBus, private val aapsSchedulers: AapsSchedulers, private val rh: ResourceHelper, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val profileFunction: ProfileFunction, private val activePlugin: ActivePlugin, private val context: Context, @@ -310,8 +310,8 @@ class CommandQueueImplementation @Inject constructor( removeAll(type) } // apply constraints - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() - detailedBolusInfo.carbs = constraintChecker.applyCarbsConstraints(Constraint(detailedBolusInfo.carbs.toInt())).value().toDouble() + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)).value() + detailedBolusInfo.carbs = constraintChecker.applyCarbsConstraints(ConstraintObject(detailedBolusInfo.carbs.toInt(), injector)).value().toDouble() // add new command to queue if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) { add(CommandSMBBolus(injector, detailedBolusInfo, callback)) @@ -368,7 +368,7 @@ class CommandQueueImplementation @Inject constructor( } // remove all unfinished removeAll(CommandType.TEMPBASAL) - val rateAfterConstraints = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val rateAfterConstraints = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, injector), profile).value() // add new command to queue add(CommandTempBasalAbsolute(injector, rateAfterConstraints, durationInMinutes, enforceNew, profile, tbrType, callback)) notifyAboutNewCommand() @@ -383,7 +383,7 @@ class CommandQueueImplementation @Inject constructor( } // remove all unfinished removeAll(CommandType.TEMPBASAL) - val percentAfterConstraints = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value() + val percentAfterConstraints = constraintChecker.applyBasalPercentConstraints(ConstraintObject(percent, injector), profile).value() // add new command to queue add(CommandTempBasalPercent(injector, percentAfterConstraints, durationInMinutes, enforceNew, profile, tbrType, callback)) notifyAboutNewCommand() @@ -396,7 +396,7 @@ class CommandQueueImplementation @Inject constructor( callback?.result(executingNowError())?.run() return false } - val rateAfterConstraints = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + val rateAfterConstraints = constraintChecker.applyExtendedBolusConstraints(ConstraintObject(insulin, injector)).value() // remove all unfinished removeAll(CommandType.EXTENDEDBOLUS) // add new command to queue diff --git a/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt b/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt index f77ea1b704..d331d044ce 100644 --- a/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/queue/CommandQueueImplementationTest.kt @@ -5,6 +5,7 @@ import android.os.Handler import android.os.PowerManager import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.database.ValueWrapper import info.nightscout.database.entities.Bolus @@ -16,8 +17,7 @@ import info.nightscout.implementation.queue.commands.CommandLoadHistory import info.nightscout.implementation.queue.commands.CommandTempBasalPercent import info.nightscout.interfaces.AndroidPermission import info.nightscout.interfaces.Config -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction @@ -50,7 +50,7 @@ import java.util.Calendar class CommandQueueImplementationTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var powerManager: PowerManager @Mock lateinit var repository: AppRepository @Mock lateinit var uiInteraction: UiInteraction @@ -63,7 +63,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { rxBus: RxBus, aapsSchedulers: AapsSchedulers, rh: ResourceHelper, - constraintChecker: Constraints, + constraintChecker: ConstraintsChecker, profileFunction: ProfileFunction, activePlugin: ActivePlugin, context: Context, @@ -88,6 +88,9 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { private val injector = HasAndroidInjector { AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } if (it is Command) { it.aapsLogger = aapsLogger it.rh = rh @@ -140,14 +143,14 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { ) `when`(profileFunction.getProfile()).thenReturn(validProfile) - val bolusConstraint = Constraint(0.0) + val bolusConstraint = ConstraintObject(0.0, injector) `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(bolusConstraint) `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(bolusConstraint) - val carbsConstraint = Constraint(0) + val carbsConstraint = ConstraintObject(0, injector) `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(carbsConstraint) - val rateConstraint = Constraint(0.0) + val rateConstraint = ConstraintObject(0.0, injector) `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(rateConstraint) - val percentageConstraint = Constraint(0) + val percentageConstraint = ConstraintObject(0, injector) `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint) `when`(rh.gs(info.nightscout.core.ui.R.string.connectiontimedout)).thenReturn("Connection timed out") `when`(rh.gs(info.nightscout.core.ui.R.string.format_insulin_units)).thenReturn("%1\$.2f U") diff --git a/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt b/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt index f8e3494ac5..efbfd84f95 100644 --- a/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/queue/QueueThreadTest.kt @@ -4,11 +4,11 @@ import android.content.Context import android.os.PowerManager import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.database.impl.AppRepository import info.nightscout.implementation.queue.commands.CommandTempBasalAbsolute import info.nightscout.interfaces.AndroidPermission -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.defs.PumpDescription @@ -25,7 +25,7 @@ import org.mockito.Mockito class QueueThreadTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var powerManager: PowerManager @Mock lateinit var repository: AppRepository @Mock lateinit var androidPermission: AndroidPermission @@ -34,6 +34,9 @@ class QueueThreadTest : TestBaseWithProfile() { private val injector = HasAndroidInjector { AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } if (it is Command) { it.aapsLogger = aapsLogger it.rh = rh @@ -64,14 +67,14 @@ class QueueThreadTest : TestBaseWithProfile() { Mockito.`when`(context.getSystemService(Context.POWER_SERVICE)).thenReturn(powerManager) Mockito.`when`(profileFunction.getProfile()).thenReturn(validProfile) - val bolusConstraint = Constraint(0.0) + val bolusConstraint = ConstraintObject(0.0, injector) Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(bolusConstraint) Mockito.`when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(bolusConstraint) - val carbsConstraint = Constraint(0) + val carbsConstraint = ConstraintObject(0, injector) Mockito.`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(carbsConstraint) - val rateConstraint = Constraint(0.0) + val rateConstraint = ConstraintObject(0.0, injector) Mockito.`when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(rateConstraint) - val percentageConstraint = Constraint(0) + val percentageConstraint = ConstraintObject(0, injector) Mockito.`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())) .thenReturn(percentageConstraint) Mockito.`when`(rh.gs(ArgumentMatchers.eq(info.nightscout.core.ui.R.string.temp_basal_absolute), anyObject(), anyObject())).thenReturn("TEMP BASAL %1\$.2f U/h %2\$d min") diff --git a/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt b/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt index 707134a5ab..1435c70843 100644 --- a/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/wizard/BolusWizardTest.kt @@ -8,12 +8,11 @@ import info.nightscout.implementation.iob.GlucoseStatusProviderImpl import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.IobTotal import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.pump.defs.PumpDescription import info.nightscout.interfaces.queue.CommandQueue -import info.nightscout.rx.bus.RxBus import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.Test import org.mockito.Mock @@ -24,7 +23,7 @@ class BolusWizardTest : TestBaseWithProfile() { private val pumpBolusStep = 0.1 - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var loop: Loop @Mock lateinit var autosensDataStore: AutosensDataStore @@ -34,7 +33,7 @@ class BolusWizardTest : TestBaseWithProfile() { if (it is BolusWizard) { it.aapsLogger = aapsLogger it.rh = rh - it.rxBus = RxBus(aapsSchedulers, aapsLogger) + it.rxBus = rxBus it.profileFunction = profileFunction it.constraintChecker = constraintChecker it.activePlugin = activePlugin @@ -113,7 +112,7 @@ class BolusWizardTest : TestBaseWithProfile() { useAlarm = false ) val bolusForBg54 = bw.calculatedTotalInsulin - assertThat(bolusForBg54).isWithin( 0.01).of(bolusForBg42) + assertThat(bolusForBg54).isWithin(0.01).of(bolusForBg42) } @Test diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 60f7e05443..34c5314473 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -103,7 +103,7 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.core.events.EventNewNotification; import info.nightscout.interfaces.Config; import info.nightscout.interfaces.constraints.Constraint; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.PluginConstraints; import info.nightscout.interfaces.notifications.Notification; import info.nightscout.interfaces.plugin.OwnDatabasePlugin; import info.nightscout.interfaces.plugin.PluginDescription; @@ -134,9 +134,10 @@ import info.nightscout.shared.utils.DateUtil; import info.nightscout.shared.utils.T; @Singleton -public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, Constraints, OwnDatabasePlugin, +public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, PluginConstraints, OwnDatabasePlugin, InsightConnectionService.StateCallback { + public static final String ALERT_CHANNEL_ID = "AAPS-InsightAlert"; private final AAPSLogger aapsLogger; private final RxBus rxBus; private final ResourceHelper rh; @@ -148,13 +149,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, private final InsightDbHelper insightDbHelper; private final PumpSync pumpSync; private final InsightDatabase insightDatabase; - - public static final String ALERT_CHANNEL_ID = "AAPS-InsightAlert"; - private final PumpDescription pumpDescription; + private final Object $bolusLock = new Object[0]; + public double lastBolusAmount = 0; + public long lastBolusTimestamp = 0L; private InsightAlertService alertService; private InsightConnectionService connectionService; - private long timeOffset; private final ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder binder) { @@ -174,8 +174,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, connectionService = null; } }; - - private final Object $bolusLock = new Object[0]; + private long timeOffset; private int bolusID; private boolean bolusCancelled; private BasalProfile activeBasalProfile; @@ -192,8 +191,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, private List activeBoluses; private boolean statusLoaded; private TBROverNotificationBlock tbrOverNotificationBlock; - public double lastBolusAmount = 0; - public long lastBolusTimestamp = 0L; @Inject public LocalInsightPlugin( @@ -1589,22 +1586,22 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Insight, @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, getPumpDescription().getMaxTempPercent(), rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); + percentRate.setIfGreater(0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().getMaxTempPercent(), rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, getPumpDescription().getMaxTempPercent(), rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); return percentRate; } @NonNull @Override public Constraint applyBolusConstraints(@NonNull Constraint insulin) { if (!limitsFetched) return insulin; - insulin.setIfSmaller(getAapsLogger(), maximumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, maximumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); + insulin.setIfSmaller(maximumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, maximumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); if (insulin.value() < minimumBolusAmount) { //TODO: Add function to Constraints or use different approach // This only works if the interface of the InsightPlugin is called last. // If not, another constraint could theoretically set the value between 0 and minimumBolusAmount - insulin.set(getAapsLogger(), 0d, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, minimumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); + insulin.set(0d, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, minimumBolusAmount, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this); } return insulin; } diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt index c630615858..3ad966c702 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/APSResultObject.kt @@ -9,7 +9,7 @@ import info.nightscout.core.utils.HtmlHelper import info.nightscout.database.entities.GlucoseValue import info.nightscout.interfaces.aps.APSResult import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.iob.IobTotal import info.nightscout.interfaces.plugin.ActivePlugin @@ -34,7 +34,7 @@ import kotlin.math.max open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) : APSResult { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var sp: SP @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var iobCobCalculator: IobCobCalculator @@ -74,12 +74,12 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) val pump = activePlugin.activePump if (isChangeRequested) { // rate - var ret: String = if (rate == 0.0 && duration == 0) "${rh.gs(info.nightscout.core.ui.R.string.cancel_temp)} " - else if (rate == -1.0) "${rh.gs(info.nightscout.core.ui.R.string.let_temp_basal_run)}\n" - else if (usePercent) "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${decimalFormatter.to2Decimal(percent.toDouble())}% (${decimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + - "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " - else "${rh.gs(info.nightscout.core.ui.R.string.rate)}: ${decimalFormatter.to2Decimal(rate)} U/h (${decimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + - "${rh.gs(info.nightscout.core.ui.R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " + var ret: String = if (rate == 0.0 && duration == 0) "${rh.gs(R.string.cancel_temp)} " + else if (rate == -1.0) "${rh.gs(R.string.let_temp_basal_run)}\n" + else if (usePercent) "${rh.gs(R.string.rate)}: ${decimalFormatter.to2Decimal(percent.toDouble())}% (${decimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + + "${rh.gs(R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " + else "${rh.gs(R.string.rate)}: ${decimalFormatter.to2Decimal(rate)} U/h (${decimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + + "${rh.gs(R.string.duration)}: ${decimalFormatter.to2Decimal(duration.toDouble())} min " // smb if (smb != 0.0) ret += "SMB: ${decimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump.pumpDescription.bolusStep)} " if (isCarbsRequired) { @@ -92,7 +92,7 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) } return if (isCarbsRequired) { carbsRequiredText - } else rh.gs(info.nightscout.core.ui.R.string.nochangerequested) + } else rh.gs(R.string.nochangerequested) } override fun toSpanned(): Spanned { @@ -100,17 +100,17 @@ open class APSResultObject @Inject constructor(val injector: HasAndroidInjector) if (isChangeRequested) { // rate var ret: String = - if (rate == 0.0 && duration == 0) rh.gs(info.nightscout.core.ui.R.string.cancel_temp) + "
" else if (rate == -1.0) rh.gs(info.nightscout.core.ui.R.string.let_temp_basal_run) + "
" else if (usePercent) "" + rh.gs( - info.nightscout.core.ui.R.string.rate + if (rate == 0.0 && duration == 0) rh.gs(R.string.cancel_temp) + "
" else if (rate == -1.0) rh.gs(R.string.let_temp_basal_run) + "
" else if (usePercent) "" + rh.gs( + R.string.rate ) + ": " + decimalFormatter.to2Decimal( percent.toDouble() ) + "% " + "(" + decimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0) + " U/h)
" + - "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + rh.gs(info.nightscout.core.ui.R.string.rate) + ": " + decimalFormatter.to2Decimal( + "" + rh.gs(R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" else "" + rh.gs(R.string.rate) + ": " + decimalFormatter.to2Decimal( rate ) + " U/h " + "(" + decimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100.0) + "%)
" + - "" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" + "" + rh.gs(R.string.duration) + ": " + decimalFormatter.to2Decimal(duration.toDouble()) + " min
" // smb if (smb != 0.0) ret += "" + "SMB" + ": " + decimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump.pumpDescription.bolusStep) + "
" diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/OpenAPSFragment.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/OpenAPSFragment.kt index 568819f482..81c6df8f15 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/OpenAPSFragment.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/OpenAPSFragment.kt @@ -150,7 +150,7 @@ class OpenAPSFragment : DaggerFragment(), MenuProvider { binding.mealdata.text = jsonFormatter.format(determineBasalAdapter.mealDataParam) binding.scriptdebugdata.text = determineBasalAdapter.scriptDebug.replace("\\s+".toRegex(), " ") openAPSPlugin.lastAPSResult?.inputConstraints?.let { - binding.constraints.text = it.getReasons(aapsLogger) + binding.constraints.text = it.getReasons() } } if (openAPSPlugin.lastAPSRun != 0L) { diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt index 031f100c20..1cd172046e 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopFragment.kt @@ -12,12 +12,13 @@ import android.view.ViewGroup import androidx.core.view.MenuCompat import androidx.core.view.MenuProvider import androidx.lifecycle.Lifecycle +import dagger.android.HasAndroidInjector import dagger.android.support.DaggerFragment +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.pump.toHtml import info.nightscout.core.utils.HtmlHelper import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraint import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.plugins.aps.R import info.nightscout.plugins.aps.databinding.LoopFragmentBinding @@ -44,6 +45,7 @@ class LoopFragment : DaggerFragment(), MenuProvider { @Inject lateinit var loop: Loop @Inject lateinit var dateUtil: DateUtil @Inject lateinit var decimalFormatter: DecimalFormatter + @Inject lateinit var injector: HasAndroidInjector @Suppress("PrivatePropertyName") private val ID_MENU_RUN = 501 @@ -150,12 +152,12 @@ class LoopFragment : DaggerFragment(), MenuProvider { var constraints = it.constraintsProcessed?.let { constraintsProcessed -> - val allConstraints = Constraint(0.0) + val allConstraints = ConstraintObject(0.0, injector) constraintsProcessed.rateConstraint?.let { rateConstraint -> allConstraints.copyReasons(rateConstraint) } constraintsProcessed.smbConstraint?.let { smbConstraint -> allConstraints.copyReasons(smbConstraint) } - allConstraints.getMostLimitedReasons(aapsLogger) + allConstraints.getMostLimitedReasons() } ?: "" - constraints += loop.closedLoopEnabled?.getReasons(aapsLogger) ?: "" + constraints += loop.closedLoopEnabled?.getReasons() ?: "" binding.constraints.text = constraints binding.swipeRefresh.isRefreshing = false } diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopPlugin.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopPlugin.kt index 660b9b92e1..787938d90a 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopPlugin.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/loop/LoopPlugin.kt @@ -14,6 +14,7 @@ import android.os.SystemClock import androidx.core.app.NotificationCompat import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.events.EventNewNotification import info.nightscout.core.extensions.convertedToAbsolute import info.nightscout.core.extensions.convertedToPercent @@ -36,7 +37,7 @@ import info.nightscout.interfaces.aps.APSResult import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.aps.Loop.LastRun import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.notifications.Notification @@ -91,7 +92,7 @@ class LoopPlugin @Inject constructor( private val rxBus: RxBus, private val sp: SP, private val config: Config, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, rh: ResourceHelper, private val profileFunction: ProfileFunction, private val context: Context, @@ -230,7 +231,7 @@ class LoopPlugin @Inject constructor( if (!loopEnabled.value()) { val message = """ ${rh.gs(info.nightscout.core.ui.R.string.loop_disabled)} - ${loopEnabled.getReasons(aapsLogger)} + ${loopEnabled.getReasons()} """.trimIndent() aapsLogger.debug(LTag.APS, message) rxBus.send(EventLoopSetLastRunGui(message)) @@ -274,11 +275,11 @@ class LoopPlugin @Inject constructor( // check rate for constraints val resultAfterConstraints = apsResult.newAndClone(injector) - resultAfterConstraints.rateConstraint = Constraint(resultAfterConstraints.rate) + resultAfterConstraints.rateConstraint = ConstraintObject(resultAfterConstraints.rate, injector) resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint!!, profile).value() - resultAfterConstraints.percentConstraint = Constraint(resultAfterConstraints.percent) + resultAfterConstraints.percentConstraint = ConstraintObject(resultAfterConstraints.percent, injector) resultAfterConstraints.percent = constraintChecker.applyBasalPercentConstraints(resultAfterConstraints.percentConstraint!!, profile).value() - resultAfterConstraints.smbConstraint = Constraint(resultAfterConstraints.smb) + resultAfterConstraints.smbConstraint = ConstraintObject(resultAfterConstraints.smb, injector) resultAfterConstraints.smb = constraintChecker.applyBolusConstraints(resultAfterConstraints.smbConstraint!!).value() // safety check for multiple SMBs diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt index 99f56f187d..4ae6517b9c 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt @@ -7,7 +7,7 @@ import info.nightscout.core.extensions.plannedRemainingMinutes import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.DetermineBasalAdapter import info.nightscout.interfaces.aps.SMBDefaults -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.iob.IobTotal @@ -43,7 +43,7 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader private val injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculator: IobCobCalculator @@ -107,7 +107,8 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader makeParam(profile, rhino, scope), makeParam(autosensData, rhino, scope), makeParam(mealData, rhino, scope), - setTempBasalFunctionsObj) + setTempBasalFunctionsObj + ) val jsResult = determineBasalObj.call(rhino, scope, scope, params) as NativeObject scriptDebug = LoggerCallback.scriptDebug diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index 61af8fa1b6..ae7e8192c3 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -3,6 +3,7 @@ package info.nightscout.plugins.aps.openAPSAMA import android.content.Context import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.target import info.nightscout.core.utils.MidnightUtils import info.nightscout.core.utils.fabric.FabricPrivacy @@ -12,7 +13,8 @@ import info.nightscout.interfaces.aps.APS import info.nightscout.interfaces.aps.AutosensResult import info.nightscout.interfaces.aps.DetermineBasalAdapter import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin @@ -46,7 +48,7 @@ class OpenAPSAMAPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBus, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, rh: ResourceHelper, private val profileFunction: ProfileFunction, private val context: Context, @@ -69,7 +71,7 @@ class OpenAPSAMAPlugin @Inject constructor( .preferencesId(R.xml.pref_openapsama) .description(R.string.description_ama), aapsLogger, rh, injector -), APS, Constraints { +), APS, PluginConstraints { // last values override var lastAPSRun: Long = 0 @@ -114,7 +116,7 @@ class OpenAPSAMAPlugin @Inject constructor( aapsLogger.debug(LTag.APS, rh.gs(R.string.openapsma_no_glucose_data)) return } - val inputConstraints = Constraint(0.0) // fake. only for collecting all results + val inputConstraints = ConstraintObject(0.0, injector) // fake. only for collecting all results val maxBasal = constraintChecker.getMaxBasalAllowed(profile).also { inputConstraints.copyReasons(it) }.value() @@ -237,8 +239,8 @@ class OpenAPSAMAPlugin @Inject constructor( override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { if (isEnabled()) { val maxIobPref: Double = sp.getDouble(R.string.key_openapsma_max_iob, 1.5) - maxIob.setIfSmaller(aapsLogger, maxIobPref, rh.gs(R.string.limiting_iob, maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this) - maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobAMA(), rh.gs(R.string.limiting_iob, hardLimits.maxIobAMA(), rh.gs(R.string.hardlimit)), this) + maxIob.setIfSmaller(maxIobPref, rh.gs(R.string.limiting_iob, maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this) + maxIob.setIfSmaller(hardLimits.maxIobAMA(), rh.gs(R.string.limiting_iob, hardLimits.maxIobAMA(), rh.gs(R.string.hardlimit)), this) } return maxIob } @@ -250,27 +252,26 @@ class OpenAPSAMAPlugin @Inject constructor( maxBasal = profile.getMaxDailyBasal() absoluteRate.addReason(rh.gs(R.string.increasing_max_basal), this) } - absoluteRate.setIfSmaller(aapsLogger, maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxBasal, rh.gs(R.string.maxvalueinpreferences)), this) + absoluteRate.setIfSmaller(maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxBasal, rh.gs(R.string.maxvalueinpreferences)), this) // Check percentRate but absolute rate too, because we know real current basal in pump val maxBasalMultiplier = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0) val maxFromBasalMultiplier = floor(maxBasalMultiplier * profile.getBasal() * 100) / 100 absoluteRate.setIfSmaller( - aapsLogger, maxFromBasalMultiplier, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromBasalMultiplier, rh.gs(R.string.max_basal_multiplier)), this ) val maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0) val maxFromDaily = floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100 - absoluteRate.setIfSmaller(aapsLogger, maxFromDaily, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromDaily, rh.gs(R.string.max_daily_basal_multiplier)), this) + absoluteRate.setIfSmaller(maxFromDaily, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromDaily, rh.gs(R.string.max_daily_basal_multiplier)), this) } return absoluteRate } override fun isAutosensModeEnabled(value: Constraint): Constraint { val enabled = sp.getBoolean(R.string.key_openapsama_use_autosens, false) - if (!enabled) value.set(aapsLogger, false, rh.gs(R.string.autosens_disabled_in_preferences), this) + if (!enabled) value.set(false, rh.gs(R.string.autosens_disabled_in_preferences), this) return value } } \ No newline at end of file diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index 89c7e6f9ba..bc15d9ccde 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -7,7 +7,7 @@ import info.nightscout.core.extensions.plannedRemainingMinutes import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.DetermineBasalAdapter import info.nightscout.interfaces.aps.SMBDefaults -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatus import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.iob.IobTotal @@ -42,7 +42,7 @@ import javax.inject.Inject class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader: ScriptReader, private val injector: HasAndroidInjector) : DetermineBasalAdapter { @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculator: IobCobCalculator diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 5d528e4b5d..8c93012f07 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -4,6 +4,7 @@ import android.content.Context import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreference import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.target import info.nightscout.core.utils.MidnightUtils import info.nightscout.database.ValueWrapper @@ -14,7 +15,8 @@ import info.nightscout.interfaces.aps.DetermineBasalAdapter import info.nightscout.interfaces.aps.SMBDefaults import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin @@ -44,7 +46,7 @@ open class OpenAPSSMBPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, private val rxBus: RxBus, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, rh: ResourceHelper, private val profileFunction: ProfileFunction, val context: Context, @@ -69,7 +71,7 @@ open class OpenAPSSMBPlugin @Inject constructor( .description(R.string.description_smb) .setDefault(), aapsLogger, rh, injector -), APS, Constraints { +), APS, PluginConstraints { // DynamicISF specific var tdd1D: Double? = null @@ -77,7 +79,7 @@ open class OpenAPSSMBPlugin @Inject constructor( var tddLast24H: Double? = null var tddLast4H: Double? = null var tddLast8to4H: Double? = null - var dynIsfEnabled: Constraint = Constraint(false) + var dynIsfEnabled: Constraint = ConstraintObject(false, injector) // last values override var lastAPSRun: Long = 0 @@ -129,7 +131,7 @@ open class OpenAPSSMBPlugin @Inject constructor( return } - val inputConstraints = Constraint(0.0) // fake. only for collecting all results + val inputConstraints = ConstraintObject(0.0, injector) // fake. only for collecting all results val maxBasal = constraintChecker.getMaxBasalAllowed(profile).also { inputConstraints.copyReasons(it) }.value() @@ -207,19 +209,19 @@ open class OpenAPSSMBPlugin @Inject constructor( val iobArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart) startPart = System.currentTimeMillis() - val smbAllowed = Constraint(!tempBasalFallback).also { + val smbAllowed = ConstraintObject(!tempBasalFallback, injector).also { constraintChecker.isSMBModeEnabled(it) inputConstraints.copyReasons(it) } - val advancedFiltering = Constraint(!tempBasalFallback).also { + val advancedFiltering = ConstraintObject(!tempBasalFallback, injector).also { constraintChecker.isAdvancedFilteringEnabled(it) inputConstraints.copyReasons(it) } - val uam = Constraint(true).also { + val uam = ConstraintObject(true, injector).also { constraintChecker.isUAMEnabled(it) inputConstraints.copyReasons(it) } - dynIsfEnabled = Constraint(true).also { + dynIsfEnabled = ConstraintObject(true, injector).also { constraintChecker.isDynIsfModeEnabled(it) inputConstraints.copyReasons(it) } @@ -239,12 +241,12 @@ open class OpenAPSSMBPlugin @Inject constructor( if (tdd1D == null || tdd7D == null || tddLast4H == null || tddLast8to4H == null || tddLast24H == null) { inputConstraints.copyReasons( - Constraint(false).also { - it.set(aapsLogger, false, rh.gs(R.string.fallback_smb_no_tdd), this) + ConstraintObject(false, injector).also { + it.set(false, rh.gs(R.string.fallback_smb_no_tdd), this) } ) inputConstraints.copyReasons( - Constraint(false).apply { set(aapsLogger, true, "tdd1D=$tdd1D tdd7D=$tdd7D tddLast4H=$tddLast4H tddLast8to4H=$tddLast8to4H tddLast24H=$tddLast24H", this) } + ConstraintObject(false, injector).apply { set(true, "tdd1D=$tdd1D tdd7D=$tdd7D tddLast4H=$tddLast4H tddLast8to4H=$tddLast8to4H tddLast24H=$tddLast24H", this) } ) } @@ -293,15 +295,15 @@ open class OpenAPSSMBPlugin @Inject constructor( } override fun isSuperBolusEnabled(value: Constraint): Constraint { - value.set(aapsLogger, false) + value.set(false) return value } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { if (isEnabled()) { val maxIobPref: Double = sp.getDouble(R.string.key_openapssmb_max_iob, 3.0) - maxIob.setIfSmaller(aapsLogger, maxIobPref, rh.gs(R.string.limiting_iob, maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this) - maxIob.setIfSmaller(aapsLogger, hardLimits.maxIobSMB(), rh.gs(R.string.limiting_iob, hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this) + maxIob.setIfSmaller(maxIobPref, rh.gs(R.string.limiting_iob, maxIobPref, rh.gs(R.string.maxvalueinpreferences)), this) + maxIob.setIfSmaller(hardLimits.maxIobSMB(), rh.gs(R.string.limiting_iob, hardLimits.maxIobSMB(), rh.gs(R.string.hardlimit)), this) } return maxIob } @@ -313,39 +315,38 @@ open class OpenAPSSMBPlugin @Inject constructor( maxBasal = profile.getMaxDailyBasal() absoluteRate.addReason(rh.gs(R.string.increasing_max_basal), this) } - absoluteRate.setIfSmaller(aapsLogger, maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxBasal, rh.gs(R.string.maxvalueinpreferences)), this) + absoluteRate.setIfSmaller(maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxBasal, rh.gs(R.string.maxvalueinpreferences)), this) // Check percentRate but absolute rate too, because we know real current basal in pump val maxBasalMultiplier = sp.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4.0) val maxFromBasalMultiplier = floor(maxBasalMultiplier * profile.getBasal() * 100) / 100 absoluteRate.setIfSmaller( - aapsLogger, maxFromBasalMultiplier, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromBasalMultiplier, rh.gs(R.string.max_basal_multiplier)), this ) val maxBasalFromDaily = sp.getDouble(R.string.key_openapsama_max_daily_safety_multiplier, 3.0) val maxFromDaily = floor(profile.getMaxDailyBasal() * maxBasalFromDaily * 100) / 100 - absoluteRate.setIfSmaller(aapsLogger, maxFromDaily, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromDaily, rh.gs(R.string.max_daily_basal_multiplier)), this) + absoluteRate.setIfSmaller(maxFromDaily, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, maxFromDaily, rh.gs(R.string.max_daily_basal_multiplier)), this) } return absoluteRate } override fun isSMBModeEnabled(value: Constraint): Constraint { val enabled = sp.getBoolean(R.string.key_use_smb, false) - if (!enabled) value.set(aapsLogger, false, rh.gs(R.string.smb_disabled_in_preferences), this) + if (!enabled) value.set(false, rh.gs(R.string.smb_disabled_in_preferences), this) return value } override fun isUAMEnabled(value: Constraint): Constraint { val enabled = sp.getBoolean(R.string.key_use_uam, false) - if (!enabled) value.set(aapsLogger, false, rh.gs(R.string.uam_disabled_in_preferences), this) + if (!enabled) value.set(false, rh.gs(R.string.uam_disabled_in_preferences), this) return value } override fun isAutosensModeEnabled(value: Constraint): Constraint { val enabled = sp.getBoolean(R.string.key_openapsama_use_autosens, false) - if (!enabled) value.set(aapsLogger, false, rh.gs(R.string.autosens_disabled_in_preferences), this) + if (!enabled) value.set(false, rh.gs(R.string.autosens_disabled_in_preferences), this) return value } diff --git a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt index 2b83d11856..9ade4e2cde 100644 --- a/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt +++ b/plugins/aps/src/main/java/info/nightscout/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt @@ -6,7 +6,7 @@ import info.nightscout.annotations.OpenForTesting import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.aps.DetermineBasalAdapter import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin @@ -32,7 +32,7 @@ class OpenAPSSMBDynamicISFPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBus, - constraintChecker: Constraints, + constraintChecker: ConstraintsChecker, rh: ResourceHelper, profileFunction: ProfileFunction, context: Context, diff --git a/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt b/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt index 422da5253c..3f926606f6 100644 --- a/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt +++ b/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt @@ -2,11 +2,11 @@ package info.nightscout.plugins.aps.loop import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.JsonHelper.safeGetDouble import info.nightscout.database.entities.TemporaryBasal import info.nightscout.interfaces.aps.APSResult -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.Assertions @@ -18,11 +18,11 @@ import org.mockito.Mockito.`when` class APSResultTest : TestBaseWithProfile() { - @Mock lateinit var constraints: Constraints + @Mock lateinit var constraintsChecker: ConstraintsChecker private val injector = HasAndroidInjector { AndroidInjector { } } - private var closedLoopEnabled = Constraint(false) + private var closedLoopEnabled = ConstraintObject(false, injector) private fun APSResult.percent(percent: Int): APSResult { this.percent = percent @@ -55,7 +55,7 @@ class APSResultTest : TestBaseWithProfile() { val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } .also { it.aapsLogger = aapsLogger - it.constraintChecker = constraints + it.constraintChecker = constraintsChecker it.sp = sp it.activePlugin = activePlugin it.iobCobCalculator = iobCobCalculator @@ -70,7 +70,7 @@ class APSResultTest : TestBaseWithProfile() { apsResult.usePercent(true) // closed loop mode return original request - closedLoopEnabled.set(aapsLogger, true) + closedLoopEnabled.set(true) `when`(iobCobCalculator.getTempBasalIncludingConvertedExtended(ArgumentMatchers.anyLong())).thenReturn(null) apsResult.tempBasalRequested(false) Assertions.assertEquals(false, apsResult.isChangeRequested) @@ -78,7 +78,7 @@ class APSResultTest : TestBaseWithProfile() { Assertions.assertEquals(true, apsResult.isChangeRequested) // open loop - closedLoopEnabled.set(aapsLogger, false) + closedLoopEnabled.set(false) // no change requested `when`(iobCobCalculator.getTempBasalIncludingConvertedExtended(ArgumentMatchers.anyLong())).thenReturn(null) apsResult.tempBasalRequested(false) @@ -184,7 +184,7 @@ class APSResultTest : TestBaseWithProfile() { apsResult.usePercent(false) // open loop - closedLoopEnabled.set(aapsLogger, false) + closedLoopEnabled.set(false) // request 100% when no temp is running `when`(iobCobCalculator.getTempBasalIncludingConvertedExtended(ArgumentMatchers.anyLong())).thenReturn(null) apsResult.tempBasalRequested(true).rate(1.0).duration(30) @@ -296,7 +296,7 @@ class APSResultTest : TestBaseWithProfile() { val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } .also { it.aapsLogger = aapsLogger - it.constraintChecker = constraints + it.constraintChecker = constraintsChecker it.sp = sp it.activePlugin = activePlugin it.iobCobCalculator = iobCobCalculator @@ -309,11 +309,11 @@ class APSResultTest : TestBaseWithProfile() { } @Test fun jsonTest() { - closedLoopEnabled.set(aapsLogger, true) + closedLoopEnabled.set(true) val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } .also { it.aapsLogger = aapsLogger - it.constraintChecker = constraints + it.constraintChecker = constraintsChecker it.sp = sp it.activePlugin = activePlugin it.iobCobCalculator = iobCobCalculator @@ -328,7 +328,7 @@ class APSResultTest : TestBaseWithProfile() { @BeforeEach fun prepare() { - `when`(constraints.isClosedLoopAllowed(anyObject())).thenReturn(closedLoopEnabled) + `when`(constraintsChecker.isClosedLoopAllowed(anyObject())).thenReturn(closedLoopEnabled) `when`(sp.getDouble(ArgumentMatchers.anyInt(), ArgumentMatchers.anyDouble())).thenReturn(30.0) `when`(profileFunction.getProfile()).thenReturn(validProfile) } diff --git a/plugins/automation/build.gradle b/plugins/automation/build.gradle index 2fecd1f02e..94a09517e0 100644 --- a/plugins/automation/build.gradle +++ b/plugins/automation/build.gradle @@ -26,6 +26,7 @@ dependencies { implementation project(':database:impl') testImplementation project(':app-wear-shared:shared-tests') + testImplementation project(':app-wear-shared:shared-impl') testImplementation project(':implementation') testImplementation project(':plugins:main') diff --git a/plugins/automation/src/main/java/info/nightscout/automation/AutomationPlugin.kt b/plugins/automation/src/main/java/info/nightscout/automation/AutomationPlugin.kt index 725788bebb..7d2c20da06 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/AutomationPlugin.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/AutomationPlugin.kt @@ -49,7 +49,7 @@ import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.automation.Automation import info.nightscout.interfaces.automation.AutomationEvent -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription @@ -87,7 +87,7 @@ class AutomationPlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val loop: Loop, private val rxBus: RxBus, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, aapsLogger: AAPSLogger, private val aapsSchedulers: AapsSchedulers, private val config: Config, @@ -244,7 +244,7 @@ class AutomationPlugin @Inject constructor( } val enabled = constraintChecker.isAutomationEnabled() if (!enabled.value()) { - executionLog.add(enabled.getMostLimitedReasons(aapsLogger)) + executionLog.add(enabled.getMostLimitedReasons()) rxBus.send(EventAutomationUpdateGui()) commonEventsEnabled = false } @@ -413,7 +413,7 @@ class AutomationPlugin @Inject constructor( } /** - * Generate reminder via [info.nightscout.interfaces.utils.TimerUtil] + * Generate reminder via [info.nightscout.automation.ui.TimerUtil] * * @param seconds seconds to the future */ diff --git a/plugins/automation/src/test/java/info/nightscout/automation/AutomationEventTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/AutomationEventTest.kt index 195baece55..84e723e73d 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/AutomationEventTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/AutomationEventTest.kt @@ -10,7 +10,6 @@ import info.nightscout.automation.triggers.TriggerConnectorTest import info.nightscout.automation.triggers.TriggerDummy import info.nightscout.interfaces.ConfigBuilder import info.nightscout.interfaces.aps.Loop -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.sharedtests.TestBase import org.json.JSONObject @@ -36,7 +35,7 @@ class AutomationEventTest : TestBase() { it.loopPlugin = loopPlugin it.rh = rh it.configBuilder = configBuilder - it.rxBus = RxBus(aapsSchedulers, aapsLogger) + it.rxBus = rxBus } } } diff --git a/plugins/automation/src/test/java/info/nightscout/automation/BolusTimerImplTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/BolusTimerImplTest.kt index c598d29860..a5d6a4a35d 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/BolusTimerImplTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/BolusTimerImplTest.kt @@ -10,13 +10,13 @@ import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.Config import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -32,8 +32,7 @@ class BolusTimerImplTest : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var loop: Loop - @Mock lateinit var rxBus: RxBus - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var config: Config @Mock lateinit var locationServiceHelper: LocationServiceHelper @Mock lateinit var activePlugin: ActivePlugin @@ -49,16 +48,17 @@ class BolusTimerImplTest : TestBase() { } } private lateinit var dateUtil: DateUtil - private lateinit var automationPlugin: AutomationPlugin @BeforeEach fun init() { Mockito.`when`(rh.gs(anyInt())).thenReturn("") Mockito.`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) - dateUtil = DateUtil(context) - automationPlugin = AutomationPlugin(injector, rh, context, sp, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, aapsSchedulers, config, locationServiceHelper, dateUtil, - activePlugin, timerUtil) + dateUtil = DateUtilImpl(context) + automationPlugin = AutomationPlugin( + injector, rh, context, sp, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, aapsSchedulers, config, locationServiceHelper, dateUtil, + activePlugin, timerUtil + ) } @Test diff --git a/plugins/automation/src/test/java/info/nightscout/automation/CarbTimerImplTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/CarbTimerImplTest.kt index ab6416eb4d..4d4ca8d8c3 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/CarbTimerImplTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/CarbTimerImplTest.kt @@ -10,13 +10,13 @@ import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.Config import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -33,8 +33,7 @@ class CarbTimerImplTest : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var loop: Loop - @Mock lateinit var rxBus: RxBus - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var config: Config @Mock lateinit var locationServiceHelper: LocationServiceHelper @Mock lateinit var activePlugin: ActivePlugin @@ -57,7 +56,7 @@ class CarbTimerImplTest : TestBase() { fun init() { Mockito.`when`(rh.gs(anyInt())).thenReturn("") Mockito.`when`(profileFunction.getUnits()).thenReturn(GlucoseUnit.MGDL) - dateUtil = DateUtil(context) + dateUtil = DateUtilImpl(context) timerUtil = TimerUtil(context) automationPlugin = AutomationPlugin( injector, rh, context, sp, fabricPrivacy, loop, rxBus, constraintChecker, aapsLogger, aapsSchedulers, config, locationServiceHelper, dateUtil, diff --git a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionAlarmTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionAlarmTest.kt index 11b7cc8518..b4ff42be96 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionAlarmTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionAlarmTest.kt @@ -9,7 +9,6 @@ import info.nightscout.automation.ui.TimerUtil import info.nightscout.interfaces.Config import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.queue.Callback -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.sharedtests.TestBase @@ -23,7 +22,6 @@ import org.mockito.Mockito.`when` class ActionAlarmTest : TestBase() { @Mock lateinit var rh: ResourceHelper - @Mock lateinit var rxBus: RxBus @Mock lateinit var context: Context @Mock lateinit var dateUtil: DateUtil @Mock lateinit var config: Config diff --git a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionNotificationTest.kt b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionNotificationTest.kt index a8fc633ab6..1cf9a096c7 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionNotificationTest.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionNotificationTest.kt @@ -26,7 +26,7 @@ class ActionNotificationTest : TestBase() { @Mock lateinit var rh: ResourceHelper @Mock lateinit var context: Context - @Mock lateinit var rxBus: RxBus + @Mock lateinit var rxBusMocked: RxBus @Mock lateinit var repository: AppRepository private lateinit var sut: ActionNotification @@ -34,7 +34,7 @@ class ActionNotificationTest : TestBase() { AndroidInjector { if (it is ActionNotification) { it.rh = rh - it.rxBus = rxBus + it.rxBus = rxBusMocked it.repository = repository } if (it is PumpEnactResult) { @@ -78,7 +78,7 @@ class ActionNotificationTest : TestBase() { Assertions.assertTrue(result.success) } }) - Mockito.verify(rxBus, Mockito.times(2)).send(anyObject()) + Mockito.verify(rxBusMocked, Mockito.times(2)).send(anyObject()) //Mockito.verify(repository, Mockito.times(1)).runTransaction(any(Transaction::class.java)) } diff --git a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt index 1e5ede19a8..0976da4cc7 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/actions/ActionsTestBase.kt @@ -3,29 +3,24 @@ package info.nightscout.automation.actions import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.automation.triggers.Trigger -import info.nightscout.database.entities.DeviceStatus +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.database.entities.OfflineEvent import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.ConfigBuilder import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.Profile -import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.profile.ProfileSource -import info.nightscout.interfaces.pump.Pump import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.queue.CommandQueue -import info.nightscout.interfaces.receivers.ReceiverStatusStore import info.nightscout.interfaces.smsCommunicator.SmsCommunicator import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.interfaces.ResourceHelper -import info.nightscout.shared.utils.DateUtil import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.BeforeEach import org.mockito.Mock @@ -45,7 +40,7 @@ ActionsTestBase : TestBaseWithProfile() { private var suspended = false override var lastRun: Loop.LastRun? = Loop.LastRun() - override var closedLoopEnabled: Constraint? = Constraint(true) + override var closedLoopEnabled: Constraint? = ConstraintObject(true, injector) override val isSuspended: Boolean = suspended override val isLGS: Boolean = false override val isSuperBolus: Boolean = false @@ -174,6 +169,9 @@ ActionsTestBase : TestBaseWithProfile() { it.rh = rh it.aapsLogger = aapsLogger } + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } } } diff --git a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt index 21aed46957..825a61499a 100644 --- a/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt +++ b/plugins/automation/src/test/java/info/nightscout/automation/triggers/TriggerTestBase.kt @@ -8,7 +8,6 @@ import info.nightscout.database.impl.AppRepository import info.nightscout.implementation.iob.GlucoseStatusProviderImpl import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.receivers.ReceiverStatusStore -import info.nightscout.rx.bus.RxBus import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.BeforeEach import org.mockito.Mock @@ -31,7 +30,7 @@ open class TriggerTestBase : TestBaseWithProfile() { AndroidInjector { if (it is Trigger) { it.aapsLogger = aapsLogger - it.rxBus = RxBus(aapsSchedulers, aapsLogger) + it.rxBus = rxBus it.rh = rh it.profileFunction = profileFunction it.sp = sp diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsImpl.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsCheckerImpl.kt similarity index 57% rename from plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsImpl.kt rename to plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsCheckerImpl.kt index 990e860a28..09b1688ec8 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsImpl.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/ConstraintsCheckerImpl.kt @@ -1,109 +1,135 @@ package info.nightscout.plugins.constraints +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile import javax.inject.Inject import javax.inject.Singleton @Singleton -class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin) : Constraints { +class ConstraintsCheckerImpl @Inject constructor( + private val activePlugin: ActivePlugin, + val injector: HasAndroidInjector +) : ConstraintsChecker { + + override fun isLoopInvocationAllowed(): Constraint = isLoopInvocationAllowed(ConstraintObject(true, injector)) override fun isLoopInvocationAllowed(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isLoopInvocationAllowed(value) } return value } + override fun isClosedLoopAllowed(): Constraint = isClosedLoopAllowed(ConstraintObject(true, injector)) + override fun isClosedLoopAllowed(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isClosedLoopAllowed(value) } return value } + override fun isLgsAllowed(): Constraint = isLgsAllowed(ConstraintObject(true, injector)) + override fun isLgsAllowed(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isLgsAllowed(value) } return value } + override fun isAutosensModeEnabled(): Constraint = isAutosensModeEnabled(ConstraintObject(true, injector)) + override fun isAutosensModeEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isAutosensModeEnabled(value) } return value } + override fun isSMBModeEnabled(): Constraint = isSMBModeEnabled(ConstraintObject(true, injector)) + override fun isSMBModeEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isSMBModeEnabled(value) } return value } + override fun isDynIsfModeEnabled(): Constraint = isDynIsfModeEnabled(ConstraintObject(true, injector)) + override fun isDynIsfModeEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isDynIsfModeEnabled(value) } return value } + override fun isUAMEnabled(): Constraint = isUAMEnabled(ConstraintObject(true, injector)) + override fun isUAMEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isUAMEnabled(value) } return value } + override fun isAdvancedFilteringEnabled(): Constraint = isAdvancedFilteringEnabled(ConstraintObject(true, injector)) + override fun isAdvancedFilteringEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isAdvancedFilteringEnabled(value) } return value } + override fun isSuperBolusEnabled(): Constraint = isSuperBolusEnabled(ConstraintObject(true, injector)) + override fun isSuperBolusEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isSuperBolusEnabled(value) } return value } + override fun isAutomationEnabled(): Constraint = isAutomationEnabled(ConstraintObject(true, injector)) + override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.applyBasalConstraints(absoluteRate, profile) } @@ -111,9 +137,9 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constrain = p as Constraints + val constrain = p as PluginConstraints if (!p.isEnabled()) continue constrain.applyBasalPercentConstraints(percentRate, profile) } @@ -121,9 +147,9 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun applyBolusConstraints(insulin: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constrain = p as Constraints + val constrain = p as PluginConstraints if (!p.isEnabled()) continue constrain.applyBolusConstraints(insulin) } @@ -131,9 +157,9 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constrain = p as Constraints + val constrain = p as PluginConstraints if (!p.isEnabled()) continue constrain.applyExtendedBolusConstraints(insulin) } @@ -141,9 +167,9 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun applyCarbsConstraints(carbs: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constrain = p as Constraints + val constrain = p as PluginConstraints if (!p.isEnabled()) continue constrain.applyCarbsConstraints(carbs) } @@ -151,9 +177,9 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constrain = p as Constraints + val constrain = p as PluginConstraints if (!p.isEnabled()) continue constrain.applyMaxIOBConstraints(maxIob) } @@ -161,12 +187,34 @@ class ConstraintsImpl @Inject constructor(private val activePlugin: ActivePlugin } override fun isAutomationEnabled(value: Constraint): Constraint { - val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(Constraints::class.java) + val constraintsPlugins = activePlugin.getSpecificPluginsListByInterface(PluginConstraints::class.java) for (p in constraintsPlugins) { - val constraint = p as Constraints + val constraint = p as PluginConstraints if (!p.isEnabled()) continue constraint.isAutomationEnabled(value) } return value } + + /* + * Determine max values by walking through all constraints + */ + + override fun getMaxBasalAllowed(profile: Profile): Constraint = + applyBasalConstraints(ConstraintObject(Double.MAX_VALUE, injector), profile) + + override fun getMaxBasalPercentAllowed(profile: Profile): Constraint = + applyBasalPercentConstraints(ConstraintObject(Int.MAX_VALUE, injector), profile) + + override fun getMaxBolusAllowed(): Constraint = + applyBolusConstraints(ConstraintObject(Double.MAX_VALUE, injector)) + + override fun getMaxExtendedBolusAllowed(): Constraint = + applyExtendedBolusConstraints(ConstraintObject(Double.MAX_VALUE, injector)) + + override fun getMaxCarbsAllowed(): Constraint = + applyCarbsConstraints(ConstraintObject(Int.MAX_VALUE, injector)) + + override fun getMaxIOBAllowed(): Constraint = + applyMaxIOBConstraints(ConstraintObject(Double.MAX_VALUE, injector)) } \ No newline at end of file diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt index 13f92597cc..3e2a9adf07 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt @@ -5,7 +5,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase @@ -48,7 +48,7 @@ class BgQualityCheckPlugin @Inject constructor( .showInList(false) .pluginName(R.string.bg_quality), aapsLogger, rh, injector -), Constraints, BgQualityCheck { +), PluginConstraints, BgQualityCheck { private var disposable: CompositeDisposable = CompositeDisposable() @@ -71,7 +71,7 @@ class BgQualityCheckPlugin @Inject constructor( // Fallback to LGS if BG values are doubled override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = if (state == BgQualityCheck.State.DOUBLED) - maxIob.set(aapsLogger, 0.0, "Doubled values in BGSource", this) + maxIob.set(0.0, "Doubled values in BGSource", this) else maxIob diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/di/PluginsConstraintsModule.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/di/PluginsConstraintsModule.kt index 3fbc067aa2..f212ea58de 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/di/PluginsConstraintsModule.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/di/PluginsConstraintsModule.kt @@ -3,9 +3,9 @@ package info.nightscout.plugins.constraints.di import dagger.Binds import dagger.Module import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.versionChecker.VersionCheckerUtils -import info.nightscout.plugins.constraints.ConstraintsImpl +import info.nightscout.plugins.constraints.ConstraintsCheckerImpl import info.nightscout.plugins.constraints.bgQualityCheck.BgQualityCheckPlugin import info.nightscout.plugins.constraints.versionChecker.VersionCheckerUtilsImpl @@ -24,6 +24,6 @@ abstract class PluginsConstraintsModule { @Binds fun bindVersionCheckerUtils(versionCheckerUtils: VersionCheckerUtilsImpl): VersionCheckerUtils @Binds fun bindBgQualityCheck(bgQualityCheck: BgQualityCheckPlugin): BgQualityCheck - @Binds fun bindsConstraints(constraintsImpl: ConstraintsImpl): Constraints + @Binds fun bindsConstraintChecker(constraintsCheckerImpl: ConstraintsCheckerImpl): ConstraintsChecker } } \ No newline at end of file diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/dstHelper/DstHelperPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/dstHelper/DstHelperPlugin.kt index ba7293a6ee..d51b2d833e 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -3,7 +3,7 @@ package info.nightscout.plugins.constraints.dstHelper import dagger.android.HasAndroidInjector import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase @@ -35,7 +35,7 @@ class DstHelperPlugin @Inject constructor( .showInList(false) .pluginName(R.string.dst_plugin_name), aapsLogger, rh, injector -), Constraints { +), PluginConstraints { companion object { @@ -74,7 +74,7 @@ class DstHelperPlugin @Inject constructor( } else { aapsLogger.debug(LTag.CONSTRAINTS, "Loop already suspended") } - value.set(aapsLogger, false, "DST in last 3 hours.", this) + value.set(false, "DST in last 3 hours.", this) } return value } diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/ObjectivesPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/ObjectivesPlugin.kt index d1aa0a557c..9fec153972 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -3,7 +3,6 @@ package info.nightscout.plugins.constraints.objectives import dagger.android.HasAndroidInjector import info.nightscout.interfaces.Config import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints import info.nightscout.interfaces.constraints.Objectives import info.nightscout.interfaces.constraints.Objectives.Companion.AUTOSENS_OBJECTIVE import info.nightscout.interfaces.constraints.Objectives.Companion.AUTO_OBJECTIVE @@ -12,6 +11,7 @@ import info.nightscout.interfaces.constraints.Objectives.Companion.FIRST_OBJECTI import info.nightscout.interfaces.constraints.Objectives.Companion.MAXBASAL_OBJECTIVE import info.nightscout.interfaces.constraints.Objectives.Companion.MAXIOB_ZERO_CL_OBJECTIVE import info.nightscout.interfaces.constraints.Objectives.Companion.SMB_OBJECTIVE +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription @@ -54,7 +54,7 @@ class ObjectivesPlugin @Inject constructor( .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), aapsLogger, rh, injector -), Constraints, Objectives { +), PluginConstraints, Objectives { var objectives: MutableList = ArrayList() @@ -112,49 +112,49 @@ class ObjectivesPlugin @Inject constructor( */ override fun isLoopInvocationAllowed(value: Constraint): Constraint { if (!objectives[FIRST_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this) return value } override fun isLgsAllowed(value: Constraint): Constraint { if (!objectives[MAXBASAL_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, MAXBASAL_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, MAXBASAL_OBJECTIVE + 1), this) return value } override fun isClosedLoopAllowed(value: Constraint): Constraint { if (!objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) return value } override fun isAutosensModeEnabled(value: Constraint): Constraint { if (!objectives[AUTOSENS_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this) return value } override fun isSMBModeEnabled(value: Constraint): Constraint { if (!objectives[SMB_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this) return value } override fun isDynIsfModeEnabled(value: Constraint): Constraint { if (!objectives[DYN_ISF_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, DYN_ISF_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, DYN_ISF_OBJECTIVE + 1), this) return value } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { if (objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted && !objectives[MAXIOB_ZERO_CL_OBJECTIVE].isAccomplished) - maxIob.set(aapsLogger, 0.0, rh.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) + maxIob.set(0.0, rh.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this) return maxIob } override fun isAutomationEnabled(value: Constraint): Constraint { if (!objectives[AUTO_OBJECTIVE].isStarted) - value.set(aapsLogger, false, rh.gs(R.string.objectivenotstarted, AUTO_OBJECTIVE + 1), this) + value.set(false, rh.gs(R.string.objectivenotstarted, AUTO_OBJECTIVE + 1), this) return value } diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective4.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective4.kt index a1398fe8ef..49c035bb2f 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective4.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective4.kt @@ -1,9 +1,8 @@ package info.nightscout.plugins.constraints.objectives.objectives import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.plugins.constraints.R @@ -14,12 +13,13 @@ class Objective4(injector: HasAndroidInjector) : Objective(injector, "maxbasal", @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin + init { tasks.add( object : Task(this, R.string.objectives_maxbasal_gate) { override fun isCompleted(): Boolean { val profile = profileFunction.getProfile() ?: return false - val maxBasalSet = (activePlugin.activeAPS as Constraints).applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile) + val maxBasalSet = (activePlugin.activeAPS as PluginConstraints).applyBasalConstraints(ConstraintObject(Double.MAX_VALUE, injector), profile) val maxDailyBasal = profile.getMaxDailyBasal() return maxBasalSet.value() > 2.8 * maxDailyBasal } diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective5.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective5.kt index d73cd22a2f..65dbe484e8 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective5.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective5.kt @@ -1,7 +1,7 @@ package info.nightscout.plugins.constraints.objectives.objectives import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.plugins.constraints.R import info.nightscout.plugins.constraints.safety.SafetyPlugin import info.nightscout.shared.utils.T @@ -17,7 +17,7 @@ class Objective5(injector: HasAndroidInjector) : Objective(injector, "maxiobzero tasks.add( object : Task(this, R.string.closedmodeenabled) { override fun isCompleted(): Boolean { - val closedLoopEnabled = Constraint(true) + val closedLoopEnabled = ConstraintObject(true, injector) safetyPlugin.isClosedLoopAllowed(closedLoopEnabled) return closedLoopEnabled.value() } diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective6.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective6.kt index a9030b8c2c..0b0b586b5d 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective6.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/objectives/objectives/Objective6.kt @@ -2,7 +2,7 @@ package info.nightscout.plugins.constraints.objectives.objectives import dagger.android.HasAndroidInjector import info.nightscout.interfaces.ApsMode -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.plugins.constraints.R import info.nightscout.shared.utils.T import javax.inject.Inject @@ -10,7 +10,7 @@ import javax.inject.Inject @Suppress("SpellCheckingInspection") class Objective6(injector: HasAndroidInjector) : Objective(injector, "maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate) { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker init { tasks.add(MinimumDurationTask(this, T.days(1).msecs())) diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt index 689bdd57a0..bab63a246d 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt @@ -4,7 +4,7 @@ import android.content.Context import android.os.Build import com.scottyab.rootbeer.RootBeer import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType @@ -22,13 +22,13 @@ class PhoneCheckerPlugin @Inject constructor( private val context: Context ) : PluginBase( PluginDescription() - .mainType(PluginType.CONSTRAINTS) - .neverVisible(true) - .alwaysEnabled(true) - .showInList(false) - .pluginName(R.string.phone_checker), + .mainType(PluginType.CONSTRAINTS) + .neverVisible(true) + .alwaysEnabled(true) + .showInList(false) + .pluginName(R.string.phone_checker), aapsLogger, rh, injector -), Constraints { +), PluginConstraints { var phoneRooted: Boolean = false var devMode: Boolean = false @@ -36,8 +36,10 @@ class PhoneCheckerPlugin @Inject constructor( val manufacturer: String = Build.MANUFACTURER private fun isDevModeEnabled(): Boolean { - return android.provider.Settings.Secure.getInt(context.contentResolver, - android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0 + return android.provider.Settings.Secure.getInt( + context.contentResolver, + android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0 + ) != 0 } override fun onStart() { diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt index 3c104f31e0..1ce7e85d93 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/safety/SafetyPlugin.kt @@ -1,6 +1,7 @@ package info.nightscout.plugins.constraints.safety import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.extensions.putDouble import info.nightscout.core.utils.extensions.putInt import info.nightscout.core.utils.extensions.putString @@ -10,7 +11,8 @@ import info.nightscout.core.utils.extensions.storeString import info.nightscout.interfaces.ApsMode import info.nightscout.interfaces.Config import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.constraints.Safety import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.notifications.Notification @@ -39,7 +41,7 @@ class SafetyPlugin @Inject constructor( aapsLogger: AAPSLogger, rh: ResourceHelper, private val sp: SP, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val activePlugin: ActivePlugin, private val hardLimits: HardLimits, private val config: Config, @@ -56,57 +58,57 @@ class SafetyPlugin @Inject constructor( .pluginName(R.string.safety) .preferencesId(R.xml.pref_safety), aapsLogger, rh, injector -), Constraints, Safety { +), PluginConstraints, Safety { /** * Constraints interface */ override fun isLoopInvocationAllowed(value: Constraint): Constraint { - if (!activePlugin.activePump.pumpDescription.isTempBasalCapable) value.set(aapsLogger, false, rh.gs(R.string.pumpisnottempbasalcapable), this) + if (!activePlugin.activePump.pumpDescription.isTempBasalCapable) value.set(false, rh.gs(R.string.pumpisnottempbasalcapable), this) return value } override fun isClosedLoopAllowed(value: Constraint): Constraint { val mode = ApsMode.fromString(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)) - if (mode == ApsMode.OPEN) value.set(aapsLogger, false, rh.gs(R.string.closedmodedisabledinpreferences), this) + if (mode == ApsMode.OPEN) value.set(false, rh.gs(R.string.closedmodedisabledinpreferences), this) if (!config.isEngineeringModeOrRelease()) { if (value.value()) { uiInteraction.addNotification(Notification.TOAST_ALARM, rh.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL) } - value.set(aapsLogger, false, rh.gs(R.string.closed_loop_disabled_on_dev_branch), this) + value.set(false, rh.gs(R.string.closed_loop_disabled_on_dev_branch), this) } val pump = activePlugin.activePump if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { - value.set(aapsLogger, false, rh.gs(R.string.closed_loop_disabled_with_eb), this) + value.set(false, rh.gs(R.string.closed_loop_disabled_with_eb), this) } return value } override fun isSMBModeEnabled(value: Constraint): Constraint { val closedLoop = constraintChecker.isClosedLoopAllowed() - if (!closedLoop.value()) value.set(aapsLogger, false, rh.gs(R.string.smbnotallowedinopenloopmode), this) + if (!closedLoop.value()) value.set(false, rh.gs(R.string.smbnotallowedinopenloopmode), this) return value } override fun isAdvancedFilteringEnabled(value: Constraint): Constraint { val bgSource = activePlugin.activeBgSource - if (!bgSource.advancedFilteringSupported()) value.set(aapsLogger, false, rh.gs(R.string.smbalwaysdisabled), this) + if (!bgSource.advancedFilteringSupported()) value.set(false, rh.gs(R.string.smbalwaysdisabled), this) return value } override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - absoluteRate.setIfGreater(aapsLogger, 0.0, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) - absoluteRate.setIfSmaller(aapsLogger, hardLimits.maxBasal(), rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, hardLimits.maxBasal(), rh.gs(R.string.hardlimit)), this) + absoluteRate.setIfGreater(0.0, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + absoluteRate.setIfSmaller(hardLimits.maxBasal(), rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, hardLimits.maxBasal(), rh.gs(R.string.hardlimit)), this) val pump = activePlugin.activePump // check for pump max if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 - absoluteRate.setIfSmaller(aapsLogger, pumpLimit, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, pumpLimit, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + absoluteRate.setIfSmaller(pumpLimit, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, pumpLimit, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) } // do rounding if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { - absoluteRate.set(aapsLogger, Round.roundTo(absoluteRate.value(), pump.pumpDescription.tempAbsoluteStep)) + absoluteRate.set(Round.roundTo(absoluteRate.value(), pump.pumpDescription.tempAbsoluteStep)) } return absoluteRate } @@ -119,52 +121,58 @@ class SafetyPlugin @Inject constructor( currentBasal ) + " U/h", this ) - val absoluteConstraint = Constraint(absoluteRate) + val absoluteConstraint = ConstraintObject(absoluteRate, injector) applyBasalConstraints(absoluteConstraint, profile) percentRate.copyReasons(absoluteConstraint) val pump = activePlugin.activePump var percentRateAfterConst = java.lang.Double.valueOf(absoluteConstraint.value() / currentBasal * 100).toInt() - percentRateAfterConst = if (percentRateAfterConst < 100) Round.ceilTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() else Round.floorTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() - percentRate.set(aapsLogger, percentRateAfterConst, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, percentRateAfterConst, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + percentRateAfterConst = + if (percentRateAfterConst < 100) Round.ceilTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()) + .toInt() else Round.floorTo(percentRateAfterConst.toDouble(), pump.pumpDescription.tempPercentStep.toDouble()).toInt() + percentRate.set(percentRateAfterConst, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, percentRateAfterConst, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) { val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 - percentRate.setIfSmaller(aapsLogger, pumpLimit.toInt(), rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, pumpLimit, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + percentRate.setIfSmaller(pumpLimit.toInt(), rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, pumpLimit, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) } return percentRate } override fun applyBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfGreater(aapsLogger, 0.0, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + insulin.setIfGreater(0.0, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) val maxBolus = sp.getDouble(info.nightscout.core.utils.R.string.key_treatmentssafety_maxbolus, 3.0) - insulin.setIfSmaller(aapsLogger, maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, maxBolus, rh.gs(R.string.maxvalueinpreferences)), this) - insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), rh.gs(info.nightscout.core.ui.R.string.limitingbolus, hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this) + insulin.setIfSmaller(maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, maxBolus, rh.gs(R.string.maxvalueinpreferences)), this) + insulin.setIfSmaller(hardLimits.maxBolus(), rh.gs(info.nightscout.core.ui.R.string.limitingbolus, hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this) val pump = activePlugin.activePump val rounded = pump.pumpDescription.pumpType.determineCorrectBolusSize(insulin.value()) - insulin.setIfDifferent(aapsLogger, rounded, rh.gs(info.nightscout.core.ui.R.string.pumplimit), this) + insulin.setIfDifferent(rounded, rh.gs(info.nightscout.core.ui.R.string.pumplimit), this) return insulin } override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfGreater(aapsLogger, 0.0, rh.gs(R.string.limitingextendedbolus, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + insulin.setIfGreater(0.0, rh.gs(R.string.limitingextendedbolus, 0.0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) val maxBolus = sp.getDouble(info.nightscout.core.utils.R.string.key_treatmentssafety_maxbolus, 3.0) - insulin.setIfSmaller(aapsLogger, maxBolus, rh.gs(R.string.limitingextendedbolus, maxBolus, rh.gs(R.string.maxvalueinpreferences)), this) - insulin.setIfSmaller(aapsLogger, hardLimits.maxBolus(), rh.gs(R.string.limitingextendedbolus, hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this) + insulin.setIfSmaller(maxBolus, rh.gs(R.string.limitingextendedbolus, maxBolus, rh.gs(R.string.maxvalueinpreferences)), this) + insulin.setIfSmaller(hardLimits.maxBolus(), rh.gs(R.string.limitingextendedbolus, hardLimits.maxBolus(), rh.gs(R.string.hardlimit)), this) val pump = activePlugin.activePump val rounded = pump.pumpDescription.pumpType.determineCorrectExtendedBolusSize(insulin.value()) - insulin.setIfDifferent(aapsLogger, rounded, rh.gs(info.nightscout.core.ui.R.string.pumplimit), this) + insulin.setIfDifferent(rounded, rh.gs(info.nightscout.core.ui.R.string.pumplimit), this) return insulin } override fun applyCarbsConstraints(carbs: Constraint): Constraint { - carbs.setIfGreater(aapsLogger, 0, rh.gs(R.string.limitingcarbs, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + carbs.setIfGreater(0, rh.gs(R.string.limitingcarbs, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) val maxCarbs = sp.getInt(info.nightscout.core.utils.R.string.key_treatmentssafety_maxcarbs, 48) - carbs.setIfSmaller(aapsLogger, maxCarbs, rh.gs(R.string.limitingcarbs, maxCarbs, rh.gs(R.string.maxvalueinpreferences)), this) + carbs.setIfSmaller(maxCarbs, rh.gs(R.string.limitingcarbs, maxCarbs, rh.gs(R.string.maxvalueinpreferences)), this) return carbs } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { val apsMode = ApsMode.fromString(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)) - if (apsMode == ApsMode.LGS) maxIob.setIfSmaller(aapsLogger, HardLimits.MAX_IOB_LGS, rh.gs(info.nightscout.core.ui.R.string.limiting_iob, HardLimits.MAX_IOB_LGS, rh.gs(info.nightscout.core.ui.R.string.lowglucosesuspend)), this) + if (apsMode == ApsMode.LGS) maxIob.setIfSmaller( + HardLimits.MAX_IOB_LGS, + rh.gs(info.nightscout.core.ui.R.string.limiting_iob, HardLimits.MAX_IOB_LGS, rh.gs(info.nightscout.core.ui.R.string.lowglucosesuspend)), + this + ) return maxIob } diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index 6aaff96f09..97f966f3e1 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -6,7 +6,7 @@ import android.os.Handler import android.os.HandlerThread import dagger.android.HasAndroidInjector import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription @@ -54,7 +54,7 @@ class SignatureVerifierPlugin @Inject constructor( .showInList(false) .pluginName(R.string.signature_verifier), aapsLogger, rh, injector -), Constraints { +), PluginConstraints { private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) @@ -88,7 +88,7 @@ class SignatureVerifierPlugin @Inject constructor( override fun isLoopInvocationAllowed(value: Constraint): Constraint { if (hasIllegalSignature()) { showNotification() - value.set(aapsLogger, false) + value.set(false) } if (shouldDownloadCerts()) { handler.post { diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/storage/StorageConstraintPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/storage/StorageConstraintPlugin.kt index 53d10c5296..677d1d7709 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/storage/StorageConstraintPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/storage/StorageConstraintPlugin.kt @@ -6,7 +6,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting import info.nightscout.interfaces.Constants import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription @@ -34,13 +34,13 @@ class StorageConstraintPlugin @Inject constructor( .showInList(false) .pluginName(R.string.storage), aapsLogger, rh, injector -), Constraints { +), PluginConstraints { override fun isClosedLoopAllowed(value: Constraint): Constraint { val diskFree = availableInternalMemorySize() if (diskFree < Constants.MINIMUM_FREE_SPACE) { aapsLogger.debug(LTag.CONSTRAINTS, "Closed loop disabled. Internal storage free (Mb):$diskFree") - value.set(aapsLogger, false, rh.gs(R.string.disk_full, Constants.MINIMUM_FREE_SPACE), this) + value.set(false, rh.gs(R.string.disk_full, Constants.MINIMUM_FREE_SPACE), this) activeNames.addNotification(Notification.DISK_FULL, rh.gs(R.string.disk_full, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL) } return value diff --git a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index 5bf36f822d..b2f27e1b9a 100644 --- a/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/plugins/constraints/src/main/java/info/nightscout/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -3,7 +3,7 @@ package info.nightscout.plugins.constraints.versionChecker import dagger.android.HasAndroidInjector import info.nightscout.interfaces.Config import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription @@ -40,7 +40,7 @@ class VersionCheckerPlugin @Inject constructor( .showInList(false) .pluginName(R.string.version_checker), aapsLogger, rh, injector -), Constraints { +), PluginConstraints { enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) { RELEASE(30, 60, 90), @@ -64,16 +64,16 @@ class VersionCheckerPlugin @Inject constructor( checkWarning() versionCheckerUtils.triggerCheckVersion() if (lastCheckOlderThan(gracePeriod.veryOld.daysToMillis())) - value.set(aapsLogger, false, rh.gs(R.string.very_old_version), this) + value.set(false, rh.gs(R.string.very_old_version), this) val endDate = sp.getLong(rh.gs(info.nightscout.core.utils.R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0) if (endDate != 0L && dateUtil.now() > endDate) - value.set(aapsLogger, false, rh.gs(R.string.application_expired), this) + value.set(false, rh.gs(R.string.application_expired), this) return value } override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint = if (lastCheckOlderThan(gracePeriod.old.daysToMillis())) - maxIob.set(aapsLogger, 0.0, rh.gs(R.string.old_version), this) + maxIob.set(0.0, rh.gs(R.string.old_version), this) else maxIob diff --git a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt index c1e599c8f5..09e07728a2 100644 --- a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt +++ b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt @@ -2,16 +2,15 @@ package info.nightscout.plugins.constraints.bgQualityCheck import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.database.entities.GlucoseValue import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck -import info.nightscout.interfaces.constraints.Constraint import info.nightscout.interfaces.iob.InMemoryGlucoseValue import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.plugins.constraints.R -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.utils.DateUtil import info.nightscout.shared.utils.T @@ -35,7 +34,13 @@ class BgQualityCheckPluginTest : TestBase() { private lateinit var plugin: BgQualityCheckPlugin - private val injector = HasAndroidInjector { AndroidInjector { } } + private val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } private val now = 100000000L //private val autosensDataStore = AutosensDataStoreObject() @@ -46,7 +51,7 @@ class BgQualityCheckPluginTest : TestBase() { injector, aapsLogger, rh, - RxBus(aapsSchedulers, aapsLogger), + rxBus, iobCobCalculator, aapsSchedulers, fabricPrivacy, @@ -75,10 +80,46 @@ class BgQualityCheckPluginTest : TestBase() { Assertions.assertEquals(R.drawable.ic_baseline_warning_24_yellow, plugin.icon()) val superData: MutableList = ArrayList() - superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(20).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(15).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(10).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - superData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = T.mins(5).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) + superData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + superData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + superData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + superData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = T.mins(5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) `when`(autosensDataStore.getBgReadingsDataTableCopy()).thenReturn(superData) `when`(autosensDataStore.lastUsed5minCalculation).thenReturn(true) @@ -205,16 +246,106 @@ class BgQualityCheckPluginTest : TestBase() { // Flat data Libre val flatData: MutableList = ArrayList() - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(0).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-5).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 101.0, timestamp = now + T.mins(-10).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-15).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-20).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-25).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 99.0, timestamp = now + T.mins(-30).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-35).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-40).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-45).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(0).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 101.0, + timestamp = now + T.mins(-10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-25).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 99.0, + timestamp = now + T.mins(-30).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-35).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-40).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-45).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) `when`(autosensDataStore.getBgReadingsDataTableCopy()).thenReturn(flatData) `when`(iobCobCalculator.ads.lastBg()).thenReturn(InMemoryGlucoseValue(flatData[0])) @@ -224,16 +355,106 @@ class BgQualityCheckPluginTest : TestBase() { // Flat data Libre val flatDataDexcom: MutableList = ArrayList() - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(0).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-5).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 101.0, timestamp = now + T.mins(-10).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-15).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-20).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-25).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 99.0, timestamp = now + T.mins(-30).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-35).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-40).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatDataDexcom.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-45).msecs(), sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, trendArrow = GlucoseValue.TrendArrow.FLAT)) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(0).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 101.0, + timestamp = now + T.mins(-10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-25).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 99.0, + timestamp = now + T.mins(-30).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-35).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-40).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatDataDexcom.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-45).msecs(), + sourceSensor = GlucoseValue.SourceSensor.DEXCOM_G6_NATIVE, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) `when`(autosensDataStore.getBgReadingsDataTableCopy()).thenReturn(flatDataDexcom) `when`(iobCobCalculator.ads.lastBg()).thenReturn(InMemoryGlucoseValue(flatDataDexcom[0])) @@ -243,19 +464,100 @@ class BgQualityCheckPluginTest : TestBase() { // not enough data val incompleteData: MutableList = ArrayList() - incompleteData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(0).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - incompleteData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-5).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) + incompleteData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(0).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + incompleteData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-5).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) `when`(autosensDataStore.getBgReadingsDataTableCopy()).thenReturn(incompleteData) `when`(iobCobCalculator.ads.lastBg()).thenReturn(InMemoryGlucoseValue(incompleteData[0])) plugin.processBgData()// must be more than 5 values Assertions.assertNotEquals(BgQualityCheck.State.FLAT, plugin.state) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 101.0, timestamp = now + T.mins(-10).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-15).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-20).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-25).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 99.0, timestamp = now + T.mins(-30).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-35).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) - flatData.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = now + T.mins(-40).msecs(), sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, trendArrow = GlucoseValue.TrendArrow.FLAT)) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 101.0, + timestamp = now + T.mins(-10).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-15).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-20).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-25).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 99.0, + timestamp = now + T.mins(-30).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-35).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) + flatData.add( + GlucoseValue( + raw = 0.0, + noise = 0.0, + value = 100.0, + timestamp = now + T.mins(-40).msecs(), + sourceSensor = GlucoseValue.SourceSensor.LIBRE_1_OTHER, + trendArrow = GlucoseValue.TrendArrow.FLAT + ) + ) plugin.processBgData() // must be at least 45 min old Assertions.assertNotEquals(BgQualityCheck.State.FLAT, plugin.state) } @@ -263,13 +565,13 @@ class BgQualityCheckPluginTest : TestBase() { @Test fun applyMaxIOBConstraintsTest() { plugin.state = BgQualityCheck.State.UNKNOWN - Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(Constraint(10.0)).value(), 0.001) + Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(ConstraintObject(10.0, injector)).value(), 0.001) plugin.state = BgQualityCheck.State.FIVE_MIN_DATA - Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(Constraint(10.0)).value(), 0.001) + Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(ConstraintObject(10.0, injector)).value(), 0.001) plugin.state = BgQualityCheck.State.RECALCULATED - Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(Constraint(10.0)).value(), 0.001) + Assertions.assertEquals(10.0, plugin.applyMaxIOBConstraints(ConstraintObject(10.0, injector)).value(), 0.001) plugin.state = BgQualityCheck.State.DOUBLED - Assertions.assertEquals(0.0, plugin.applyMaxIOBConstraints(Constraint(10.0)).value(), 0.001) + Assertions.assertEquals(0.0, plugin.applyMaxIOBConstraints(ConstraintObject(10.0, injector)).value(), 0.001) } } \ No newline at end of file diff --git a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/ObjectivesPluginTest.kt b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/ObjectivesPluginTest.kt index ea712ceea9..e668b07c09 100644 --- a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/ObjectivesPluginTest.kt +++ b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/objectives/ObjectivesPluginTest.kt @@ -2,8 +2,8 @@ package info.nightscout.plugins.constraints.objectives import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.Config -import info.nightscout.interfaces.constraints.Constraint import info.nightscout.interfaces.constraints.Objectives import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.plugins.constraints.R @@ -35,6 +35,9 @@ class ObjectivesPluginTest : TestBase() { it.rh = rh it.dateUtil = dateUtil } + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } } } @@ -49,34 +52,30 @@ class ObjectivesPluginTest : TestBase() { @Test fun notStartedObjectivesShouldLimitLoopInvocation() { objectivesPlugin.objectives[Objectives.FIRST_OBJECTIVE].startedOn = 0 - var c = Constraint(true) - c = objectivesPlugin.isLoopInvocationAllowed(c) - Assertions.assertEquals("Objectives: Objective 1 not started", c.getReasons(aapsLogger)) + val c = objectivesPlugin.isLoopInvocationAllowed(ConstraintObject(true, injector)) + Assertions.assertEquals("Objectives: Objective 1 not started", c.getReasons()) Assertions.assertEquals(false, c.value()) objectivesPlugin.objectives[Objectives.FIRST_OBJECTIVE].startedOn = dateUtil.now() } @Test fun notStartedObjective6ShouldLimitClosedLoop() { objectivesPlugin.objectives[Objectives.MAXIOB_ZERO_CL_OBJECTIVE].startedOn = 0 - var c = Constraint(true) - c = objectivesPlugin.isClosedLoopAllowed(c) - Assertions.assertEquals(true, c.getReasons(aapsLogger).contains("Objective 6 not started")) + val c = objectivesPlugin.isClosedLoopAllowed(ConstraintObject(true, injector)) + Assertions.assertEquals(true, c.getReasons().contains("Objective 6 not started")) Assertions.assertEquals(false, c.value()) } @Test fun notStartedObjective8ShouldLimitAutosensMode() { objectivesPlugin.objectives[Objectives.AUTOSENS_OBJECTIVE].startedOn = 0 - var c = Constraint(true) - c = objectivesPlugin.isAutosensModeEnabled(c) - Assertions.assertEquals(true, c.getReasons(aapsLogger).contains("Objective 8 not started")) + val c = objectivesPlugin.isAutosensModeEnabled(ConstraintObject(true, injector)) + Assertions.assertEquals(true, c.getReasons().contains("Objective 8 not started")) Assertions.assertEquals(false, c.value()) } @Test fun notStartedObjective10ShouldLimitSMBMode() { objectivesPlugin.objectives[Objectives.SMB_OBJECTIVE].startedOn = 0 - var c = Constraint(true) - c = objectivesPlugin.isSMBModeEnabled(c) - Assertions.assertEquals(true, c.getReasons(aapsLogger).contains("Objective 9 not started")) + val c = objectivesPlugin.isSMBModeEnabled(ConstraintObject(true, injector)) + Assertions.assertEquals(true, c.getReasons().contains("Objective 9 not started")) Assertions.assertEquals(false, c.value()) } } \ No newline at end of file diff --git a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/storage/StorageConstraintPluginTest.kt b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/storage/StorageConstraintPluginTest.kt index 8e917a0652..51c8a130c9 100644 --- a/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/storage/StorageConstraintPluginTest.kt +++ b/plugins/constraints/src/test/java/info/nightscout/plugins/constraints/storage/StorageConstraintPluginTest.kt @@ -2,7 +2,7 @@ package info.nightscout.plugins.constraints.storage import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.rx.logging.AAPSLogger import info.nightscout.shared.interfaces.ResourceHelper @@ -20,6 +20,13 @@ class StorageConstraintPluginTest : TestBase() { @Mock lateinit var rh: ResourceHelper @Mock lateinit var uiInteraction: UiInteraction + private val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } private lateinit var storageConstraintPlugin: StorageConstraintPlugin @BeforeEach fun prepareMock() { @@ -42,9 +49,9 @@ class StorageConstraintPluginTest : TestBase() { val mocked = MockedStorageConstraintPlugin({ AndroidInjector { } }, aapsLogger, rh, uiInteraction) // Set free space under 200(Mb) to disable loop mocked.memSize = 150L - Assertions.assertEquals(false, mocked.isClosedLoopAllowed(Constraint(true)).value()) + Assertions.assertEquals(false, mocked.isClosedLoopAllowed(ConstraintObject(true, injector)).value()) // Set free space over 200(Mb) to enable loop mocked.memSize = 300L - Assertions.assertEquals(true, mocked.isClosedLoopAllowed(Constraint(true)).value()) + Assertions.assertEquals(true, mocked.isClosedLoopAllowed(ConstraintObject(true, injector)).value()) } } \ No newline at end of file diff --git a/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefFreePeakPluginTest.kt b/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefFreePeakPluginTest.kt index f9a2ae62dc..af3df55f01 100644 --- a/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/plugins/insulin/src/test/java/info/nightscout/insulin/InsulinOrefFreePeakPluginTest.kt @@ -7,7 +7,6 @@ import info.nightscout.interfaces.insulin.Insulin import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.utils.HardLimits -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.sharedtests.TestBase @@ -29,7 +28,6 @@ class InsulinOrefFreePeakPluginTest : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var rh: ResourceHelper - @Mock lateinit var rxBus: RxBus @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var config: Config @Mock lateinit var hardLimits: HardLimits diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt index 0a19977f25..1157f7ee2a 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/overview/OverviewFragment.kt @@ -27,6 +27,7 @@ import androidx.recyclerview.widget.LinearLayoutManager import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector import dagger.android.support.DaggerFragment +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.directionToIcon import info.nightscout.core.graph.OverviewData import info.nightscout.core.iob.displayText @@ -49,8 +50,7 @@ import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.aps.VariableSensitivityResult import info.nightscout.interfaces.automation.Automation import info.nightscout.interfaces.bgQualityCheck.BgQualityCheck -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger @@ -121,7 +121,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileUtil: ProfileUtil - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var statusLightHandler: StatusLightHandler @Inject lateinit var processedDeviceStatusData: ProcessedDeviceStatusData @Inject lateinit var nsSettingsStatus: NSSettingsStatus @@ -516,7 +516,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList binding.buttonsLayout.quickWizardButton.visibility = View.VISIBLE val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg) if (wizard.calculatedTotalInsulin > 0.0 && quickWizardEntry.carbs() > 0.0) { - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(quickWizardEntry.carbs(), injector)).value() activity?.let { if (abs(wizard.insulinAfterConstraints - wizard.calculatedTotalInsulin) >= pump.pumpDescription.pumpType.determineCorrectBolusStepSize(wizard.insulinAfterConstraints) || carbsAfterConstraints != quickWizardEntry.carbs()) { OKDialog.show(it, rh.gs(info.nightscout.core.ui.R.string.treatmentdeliveryerror), rh.gs(R.string.constraints_violation) + "\n" + rh.gs(R.string.change_your_input)) diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index b05207344e..ea6a505ea8 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -11,6 +11,7 @@ import androidx.work.WorkerParameters import androidx.work.workDataOf import dagger.android.HasAndroidInjector import info.nightscout.annotations.OpenForTesting +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.events.EventNewNotification import info.nightscout.core.iob.generateCOBString import info.nightscout.core.iob.round @@ -34,8 +35,7 @@ import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.XDripBroadcast import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger @@ -91,7 +91,7 @@ class SmsCommunicatorPlugin @Inject constructor( private val smsManager: SmsManager?, private val aapsSchedulers: AapsSchedulers, private val sp: SP, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val rxBus: RxBus, private val profileFunction: ProfileFunction, private val profileUtil: ProfileUtil, @@ -732,7 +732,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasalPct == 0 && divided[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrong_format))) else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.sms_wrong_tbr_duration, durationStep))) else { - tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() + tempBasalPct = constraintChecker.applyBasalPercentConstraints(ConstraintObject(tempBasalPct, injector), profile).value() val passCode = generatePassCode() val reply = rh.gs(R.string.smscommunicator_basal_pct_reply_with_code, tempBasalPct, duration, passCode) receivedSms.processed = true @@ -787,7 +787,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasal == 0.0 && divided[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrong_format))) else if (duration <= 0 || duration % durationStep != 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.sms_wrong_tbr_duration, durationStep))) else { - tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value() + tempBasal = constraintChecker.applyBasalConstraints(ConstraintObject(tempBasal, injector), profile).value() val passCode = generatePassCode() val reply = rh.gs(R.string.smscommunicator_basal_reply_with_code, tempBasal, duration, passCode) receivedSms.processed = true @@ -864,7 +864,7 @@ class SmsCommunicatorPlugin @Inject constructor( } else { var extended = SafeParse.stringToDouble(divided[1]) val duration = SafeParse.stringToInt(divided[2]) - extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value() + extended = constraintChecker.applyExtendedBolusConstraints(ConstraintObject(extended, injector)).value() if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrong_format))) else { val passCode = generatePassCode() @@ -918,7 +918,7 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processBOLUS(divided: Array, receivedSms: Sms) { var bolus = SafeParse.stringToDouble(divided[1]) val isMeal = divided.size > 2 && divided[2].equals("MEAL", ignoreCase = true) - bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value() + bolus = constraintChecker.applyBolusConstraints(ConstraintObject(bolus, injector)).value() if (divided.size == 3 && !isMeal) { sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrong_format))) } else if (bolus > 0.0) { @@ -1031,7 +1031,7 @@ class SmsCommunicatorPlugin @Inject constructor( return } } - grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value() + grams = constraintChecker.applyCarbsConstraints(ConstraintObject(grams, injector)).value() if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, rh.gs(R.string.wrong_format))) else { val passCode = generatePassCode() diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt index fbb7e0701a..55b368a20f 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -3,6 +3,7 @@ package info.nightscout.plugins.general.wear.wearintegration import android.app.NotificationManager import android.content.Context import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.convertedToAbsolute import info.nightscout.core.extensions.toStringShort import info.nightscout.core.extensions.valueToUnits @@ -33,8 +34,7 @@ import info.nightscout.interfaces.Config import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.InMemoryGlucoseValue @@ -104,7 +104,7 @@ class DataHandlerMobile @Inject constructor( private val defaultValueHelper: DefaultValueHelper, private val trendCalculator: TrendCalculator, private val dateUtil: DateUtil, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val uel: UserEntryLogger, private val activePlugin: ActivePlugin, private val commandQueue: CommandQueue, @@ -269,7 +269,7 @@ class DataHandlerMobile @Inject constructor( .observeOn(aapsSchedulers.io) .subscribe({ aapsLogger.debug(LTag.WEAR, "ActionFillConfirmed received $it from ${it.sourceNodeId}") - if (constraintChecker.applyBolusConstraints(Constraint(it.insulin)).value() - it.insulin != 0.0) { + if (constraintChecker.applyBolusConstraints(ConstraintObject(it.insulin, injector)).value() - it.insulin != 0.0) { ToastUtils.showToastInUiThread(context, "aborting: previously applied constraint changed") sendError("aborting: previously applied constraint changed") } else @@ -383,7 +383,7 @@ class DataHandlerMobile @Inject constructor( return } val carbsBeforeConstraints = command.carbs - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbsBeforeConstraints)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(carbsBeforeConstraints, injector)).value() if (carbsAfterConstraints - carbsBeforeConstraints != 0) { sendError(rh.gs(info.nightscout.core.ui.R.string.wizard_carbs_constraint)) return @@ -480,7 +480,7 @@ class DataHandlerMobile @Inject constructor( val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg) - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(quickWizardEntry.carbs(), injector)).value() if (carbsAfterConstraints != quickWizardEntry.carbs()) { sendError(rh.gs(info.nightscout.core.ui.R.string.wizard_carbs_constraint)) return @@ -506,8 +506,8 @@ class DataHandlerMobile @Inject constructor( } private fun handleBolusPreCheck(command: EventData.ActionBolusPreCheck) { - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(command.insulin)).value() - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(command.carbs)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(command.insulin, injector)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(command.carbs, injector)).value() val pump = activePlugin.activePump if (insulinAfterConstraints > 0 && (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected)) { sendError(rh.gs(info.nightscout.core.ui.R.string.wizard_pump_not_available)) @@ -530,7 +530,7 @@ class DataHandlerMobile @Inject constructor( private fun handleECarbsPreCheck(command: EventData.ActionECarbsPreCheck) { val startTimeStamp = System.currentTimeMillis() + T.mins(command.carbsTimeShift.toLong()).msecs() - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(command.carbs)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(command.carbs, injector)).value() var message = rh.gs(info.nightscout.core.ui.R.string.carbs) + ": " + carbsAfterConstraints + rh.gs(R.string.grams_short) + "\n" + rh.gs(info.nightscout.core.ui.R.string.time) + ": " + dateUtil.timeString(startTimeStamp) + "\n" + rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + command.duration + rh.gs(R.string.hour_short) @@ -558,7 +558,7 @@ class DataHandlerMobile @Inject constructor( 3 -> sp.getDouble("fill_button3", 0.0) else -> return } - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(amount, injector)).value() var message = rh.gs(info.nightscout.core.ui.R.string.prime_fill) + ": " + insulinAfterConstraints + rh.gs(R.string.units_short) if (insulinAfterConstraints - amount != 0.0) message += "\n" + rh.gs(info.nightscout.core.ui.R.string.constraint_applied) rxBus.send( @@ -572,7 +572,7 @@ class DataHandlerMobile @Inject constructor( } private fun handleFillPreCheck(command: EventData.ActionFillPreCheck) { - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(command.insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(command.insulin, injector)).value() var message = rh.gs(info.nightscout.core.ui.R.string.prime_fill) + ": " + insulinAfterConstraints + rh.gs(R.string.units_short) if (insulinAfterConstraints - command.insulin != 0.0) message += "\n" + rh.gs(info.nightscout.core.ui.R.string.constraint_applied) rxBus.send( diff --git a/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index a591e04dc8..825555b7c8 100644 --- a/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/plugins/main/src/test/java/info/nightscout/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -4,6 +4,7 @@ import android.telephony.SmsManager import com.google.common.truth.Truth.assertThat import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.database.entities.GlucoseValue import info.nightscout.database.impl.AppRepository import info.nightscout.database.impl.transactions.CancelCurrentOfflineEventIfAnyTransaction @@ -16,8 +17,7 @@ import info.nightscout.interfaces.Constants import info.nightscout.interfaces.XDripBroadcast import info.nightscout.interfaces.aps.AutosensDataStore import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.CobInfo import info.nightscout.interfaces.iob.InMemoryGlucoseValue import info.nightscout.interfaces.iob.IobTotal @@ -48,7 +48,7 @@ import org.mockito.invocation.InvocationOnMock @Suppress("SpellCheckingInspection") class SmsCommunicatorPluginTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var loop: Loop @Mock lateinit var profileSource: ProfileSource @@ -62,6 +62,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { private var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } if (it is PumpEnactResult) { it.context = context } @@ -836,7 +839,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 20% 20") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") - `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20)) + `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(ConstraintObject(20, injector)) //BASAL 20% 30 smsCommunicatorPlugin.messages = ArrayList() @@ -862,7 +865,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 1 0") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") - `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(ConstraintObject(1.0, injector)) //BASAL 1 20 smsCommunicatorPlugin.messages = ArrayList() @@ -870,7 +873,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BASAL 1 20") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("TBR duration must be a multiple of 30 minutes and greater than 0.") - `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyBasalConstraints(anyObject(), anyObject())).thenReturn(ConstraintObject(1.0, injector)) //BASAL 1 30 smsCommunicatorPlugin.messages = ArrayList() @@ -918,7 +921,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("EXTENDED a%") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") - `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(ConstraintObject(1.0, injector)) //EXTENDED 1 0 smsCommunicatorPlugin.messages = ArrayList() @@ -955,7 +958,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(1.0, injector)) `when`(dateUtilMocked.now()).thenReturn(1000L) `when`(sp.getLong(R.string.key_smscommunicator_remote_bolus_min_distance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L) //BOLUS 1 @@ -964,7 +967,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS 1") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Remote bolus not available. Try again later.") - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) `when`(dateUtilMocked.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L) //BOLUS 0 @@ -980,8 +983,8 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("BOLUS a") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") - `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) + `when`(constraintChecker.applyExtendedBolusConstraints(anyObject())).thenReturn(ConstraintObject(1.0, injector)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(1.0, injector)) //BOLUS 1 smsCommunicatorPlugin.messages = ArrayList() @@ -1078,7 +1081,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") - `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0)) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(ConstraintObject(0, injector)) //CARBS 0 smsCommunicatorPlugin.messages = ArrayList() @@ -1086,7 +1089,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) assertThat(smsCommunicatorPlugin.messages[0].text).isEqualTo("CARBS 0") assertThat(smsCommunicatorPlugin.messages[1].text).isEqualTo("Wrong format") - `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1)) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(ConstraintObject(1, injector)) //CARBS 1 smsCommunicatorPlugin.messages = ArrayList() diff --git a/plugins/main/src/test/java/info/nightscout/plugins/iob/AutosensDataStoreTest.kt b/plugins/main/src/test/java/info/nightscout/plugins/iob/AutosensDataStoreTest.kt index 56f3215545..e342e4eeb9 100644 --- a/plugins/main/src/test/java/info/nightscout/plugins/iob/AutosensDataStoreTest.kt +++ b/plugins/main/src/test/java/info/nightscout/plugins/iob/AutosensDataStoreTest.kt @@ -12,6 +12,7 @@ import info.nightscout.plugins.iob.iobCobCalculator.data.AutosensDataStoreObject import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil +import info.nightscout.shared.utils.DateUtilImpl import info.nightscout.shared.utils.T import info.nightscout.sharedtests.TestBase import org.junit.jupiter.api.Assertions @@ -46,7 +47,7 @@ class AutosensDataStoreTest : TestBase() { @BeforeEach fun mock() { - dateUtil = DateUtil(context) + dateUtil = DateUtilImpl(context) } @Test diff --git a/plugins/sensitivity/src/main/java/info/nightscout/sensitivity/SensitivityOref1Plugin.kt b/plugins/sensitivity/src/main/java/info/nightscout/sensitivity/SensitivityOref1Plugin.kt index f98681d3b8..d77c1de943 100644 --- a/plugins/sensitivity/src/main/java/info/nightscout/sensitivity/SensitivityOref1Plugin.kt +++ b/plugins/sensitivity/src/main/java/info/nightscout/sensitivity/SensitivityOref1Plugin.kt @@ -12,7 +12,7 @@ import info.nightscout.interfaces.aps.AutosensResult import info.nightscout.interfaces.aps.SMBDefaults import info.nightscout.interfaces.aps.Sensitivity.SensitivityType import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.ProfileFunction @@ -51,7 +51,7 @@ class SensitivityOref1Plugin @Inject constructor( .description(R.string.description_sensitivity_oref1) .setDefault(), injector, aapsLogger, rh, sp -), Constraints { +), PluginConstraints { override fun detectSensitivity(ads: AutosensDataStore, fromTime: Long, toTime: Long): AutosensResult { val profile = profileFunction.getProfile() @@ -260,7 +260,7 @@ class SensitivityOref1Plugin @Inject constructor( get() = SensitivityType.SENSITIVITY_OREF1 override fun isUAMEnabled(value: Constraint): Constraint { - if (!isEnabled()) value.set(aapsLogger, false, rh.gs(R.string.uam_disabled_oref1_not_selected), this) + if (!isEnabled()) value.set(false, rh.gs(R.string.uam_disabled_oref1_not_selected), this) return value } } \ No newline at end of file diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclient/ReceiverDelegateTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclient/ReceiverDelegateTest.kt index 3903925b52..ea9149f0c7 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclient/ReceiverDelegateTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclient/ReceiverDelegateTest.kt @@ -3,7 +3,6 @@ package info.nightscout.plugins.sync.nsclient import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.receivers.ReceiverStatusStore import info.nightscout.plugins.sync.R -import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventChargingState import info.nightscout.rx.events.EventNetworkChange import info.nightscout.shared.interfaces.ResourceHelper @@ -20,7 +19,6 @@ class ReceiverDelegateTest : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var rh: ResourceHelper @Mock lateinit var fabricPrivacy: FabricPrivacy - private val rxBus = RxBus(aapsSchedulers, aapsLogger) @Mock private lateinit var receiverStatusStore: ReceiverStatusStore private lateinit var sut: ReceiverDelegate diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/DataSyncWorkerTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/DataSyncWorkerTest.kt index 18eab903ec..4173e6e8e6 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/DataSyncWorkerTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/DataSyncWorkerTest.kt @@ -10,7 +10,6 @@ import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.sync.NsClient import info.nightscout.plugins.sync.nsclientV3.DataSyncSelectorV3 import info.nightscout.plugins.sync.nsclientV3.NSClientV3Plugin -import info.nightscout.rx.bus.RxBus import info.nightscout.sharedtests.TestBase import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest @@ -30,7 +29,6 @@ internal class DataSyncWorkerTest : TestBase() { @Mock lateinit var dataSyncSelectorV3: DataSyncSelectorV3 @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var nsClient: NsClient - @Mock lateinit var rxBus: RxBus @Mock lateinit var nsClientV3Plugin: NSClientV3Plugin @Mock lateinit var context: ContextWithInjector diff --git a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt index 917dd76573..6e88ae34d7 100644 --- a/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt +++ b/plugins/sync/src/test/java/info/nightscout/plugins/sync/nsclientV3/workers/LoadBgWorkerTest.kt @@ -26,7 +26,6 @@ import info.nightscout.plugins.sync.nsclient.data.NSDeviceStatusHandler import info.nightscout.plugins.sync.nsclientV3.DataSyncSelectorV3 import info.nightscout.plugins.sync.nsclientV3.NSClientV3Plugin import info.nightscout.plugins.sync.nsclientV3.extensions.toNSSvgV3 -import info.nightscout.rx.bus.RxBus import info.nightscout.sdk.interfaces.NSAndroidClient import info.nightscout.sdk.remotemodel.LastModified import info.nightscout.shared.interfaces.ResourceHelper @@ -66,7 +65,6 @@ internal class LoadBgWorkerTest : TestBase() { @Mock lateinit var nsIncomingDataProcessor: NsIncomingDataProcessor @Mock lateinit var context: ContextWithInjector - private val rxBus: RxBus = RxBus(aapsSchedulers, aapsLogger) private lateinit var nsClientV3Plugin: NSClientV3Plugin private lateinit var receiverDelegate: ReceiverDelegate private lateinit var dataWorkerStorage: DataWorkerStorage diff --git a/pump/combo/src/main/java/info/nightscout/pump/combo/ComboPlugin.java b/pump/combo/src/main/java/info/nightscout/pump/combo/ComboPlugin.java index e880a9684b..60076f31cd 100644 --- a/pump/combo/src/main/java/info/nightscout/pump/combo/ComboPlugin.java +++ b/pump/combo/src/main/java/info/nightscout/pump/combo/ComboPlugin.java @@ -22,7 +22,7 @@ import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.core.utils.fabric.InstanceId; import info.nightscout.interfaces.constraints.Constraint; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.PluginConstraints; import info.nightscout.interfaces.notifications.Notification; import info.nightscout.interfaces.plugin.PluginDescription; import info.nightscout.interfaces.plugin.PluginType; @@ -86,23 +86,41 @@ import info.nightscout.shared.utils.T; * Created by mike on 05.08.2016. */ @Singleton -public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { +public class ComboPlugin extends PumpPluginBase implements Pump, PluginConstraints { + private final static PumpDescription pumpDescription = new PumpDescription(); + @NonNull + private static final ComboPump pump = new ComboPump(); // collaborators private final ProfileFunction profileFunction; private final SP sp; - private RxBus rxBus; private final CommandQueue commandQueue; private final PumpSync pumpSync; private final DateUtil dateUtil; private final RuffyCommands ruffyScripter; private final UiInteraction uiInteraction; - - private final static PumpDescription pumpDescription = new PumpDescription(); - - - @NonNull - private static final ComboPump pump = new ComboPump(); - + private RxBus rxBus; + private final BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { + EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; + switch (state) { + case PROGRAMMING: + event.setStatus(getRh().gs(R.string.combo_programming_bolus)); + break; + case DELIVERING: + event.setStatus(getRh().gs(info.nightscout.core.ui.R.string.bolus_delivering, delivered)); + break; + case DELIVERED: + event.setStatus(getRh().gs(info.nightscout.core.ui.R.string.bolus_delivered_successfully, delivered)); + break; + case STOPPING: + event.setStatus(getRh().gs(R.string.bolusstopping)); + break; + case STOPPED: + event.setStatus(getRh().gs(R.string.bolusstopped)); + break; + } + event.setPercent(percent); + rxBus.send(event); + }; /** * This is used to determine when to pass a bolus cancel request to the scripter */ @@ -112,7 +130,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { * will reset this flag. */ private volatile boolean cancelBolus; - /** * This is set (in {@link #checkHistory()} whenever a connection to the pump is made and * indicates if new history records on the pump have been found. This effectively blocks @@ -128,7 +145,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { * direction - so that adding more complexity yields little benefit. */ private volatile boolean pumpHistoryChanged = false; - /** * Cache of the last <=2 boluses on the pump. Used to detect changes in pump history, * requiring reading more pump history. This is read/set in {@link #checkHistory()} when changed @@ -136,8 +152,11 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { * after bolus delivery. Newest record is the first one. */ private volatile List recentBoluses = new ArrayList<>(0); - private PumpEnactResult OPERATION_NOT_SUPPORTED; + // Constraints interface + private long lowSuspendOnlyLoopEnforcedUntil = 0; + private long violationWarningRaisedForBolusAt = 0; + private boolean validBasalRateProfileSelectedOnPump = true; @Inject public ComboPlugin( @@ -469,29 +488,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } } - private final BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { - EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; - switch (state) { - case PROGRAMMING: - event.setStatus(getRh().gs(R.string.combo_programming_bolus)); - break; - case DELIVERING: - event.setStatus(getRh().gs(info.nightscout.core.ui.R.string.bolus_delivering, delivered)); - break; - case DELIVERED: - event.setStatus(getRh().gs(info.nightscout.core.ui.R.string.bolus_delivered_successfully, delivered)); - break; - case STOPPING: - event.setStatus(getRh().gs(R.string.bolusstopping)); - break; - case STOPPED: - event.setStatus(getRh().gs(R.string.bolusstopped)); - break; - } - event.setPercent(percent); - rxBus.send(event); - }; - /** * Updates Treatment records with carbs and boluses and delivers a bolus if needed */ @@ -850,10 +846,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return 0; } - private interface CommandExecution { - CommandResult execute(); - } - /** * Runs a command, sets an activity if provided, retries if requested and updates fields * concerned with last connection. @@ -980,7 +972,6 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return null; } - private void checkBasalRate(PumpState state) { if (!pump.initialized) { // no cached profile to compare against @@ -1386,22 +1377,17 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { return result; } - // Constraints interface - private long lowSuspendOnlyLoopEnforcedUntil = 0; - private long violationWarningRaisedForBolusAt = 0; - private boolean validBasalRateProfileSelectedOnPump = true; - @NonNull @Override public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { if (!validBasalRateProfileSelectedOnPump) - value.set(getAapsLogger(), false, getRh().gs(info.nightscout.core.ui.R.string.no_valid_basal_rate), this); + value.set(false, getRh().gs(info.nightscout.core.ui.R.string.no_valid_basal_rate), this); return value; } @NonNull @Override public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { if (lowSuspendOnlyLoopEnforcedUntil > System.currentTimeMillis()) - maxIob.setIfSmaller(getAapsLogger(), 0d, getRh().gs(info.nightscout.core.ui.R.string.limiting_iob, 0d, getRh().gs(R.string.unsafeusage)), this); + maxIob.setIfSmaller(0d, getRh().gs(info.nightscout.core.ui.R.string.limiting_iob, 0d, getRh().gs(R.string.unsafeusage)), this); return maxIob; } @@ -1409,4 +1395,8 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { public boolean canHandleDST() { return false; } + + private interface CommandExecution { + CommandResult execute(); + } } diff --git a/pump/combo/src/test/java/info/nightscout/pump/combo/ComboPluginTest.kt b/pump/combo/src/test/java/info/nightscout/pump/combo/ComboPluginTest.kt index 1d238e0cb4..dee5d1eb5b 100644 --- a/pump/combo/src/test/java/info/nightscout/pump/combo/ComboPluginTest.kt +++ b/pump/combo/src/test/java/info/nightscout/pump/combo/ComboPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.pump.combo import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.PumpEnactResult @@ -12,7 +12,6 @@ import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.combo.ruffyscripter.RuffyScripter import info.nightscout.pump.combo.ruffyscripter.history.Bolus -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -37,6 +36,9 @@ class ComboPluginTest : TestBase() { private val injector = HasAndroidInjector { AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } if (it is PumpEnactResult) { it.context = context } @@ -49,16 +51,15 @@ class ComboPluginTest : TestBase() { fun prepareMocks() { `when`(rh.gs(info.nightscout.core.ui.R.string.no_valid_basal_rate)).thenReturn("No valid basal rate read from pump") `when`(context.getString(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") - comboPlugin = ComboPlugin(injector, aapsLogger, RxBus(aapsSchedulers, aapsLogger), rh, profileFunction, sp, commandQueue, pumpSync, dateUtil, ruffyScripter, uiInteraction) + comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, rh, profileFunction, sp, commandQueue, pumpSync, dateUtil, ruffyScripter, uiInteraction) } @Test fun invalidBasalRateOnComboPumpShouldLimitLoopInvocation() { comboPlugin.setPluginEnabled(PluginType.PUMP, true) comboPlugin.setValidBasalRateProfileSelectedOnPump(false) - var c = Constraint(true) - c = comboPlugin.isLoopInvocationAllowed(c) - Assertions.assertEquals("Combo: No valid basal rate read from pump", c.getReasons(aapsLogger)) + val c = comboPlugin.isLoopInvocationAllowed(ConstraintObject(true, injector)) + Assertions.assertEquals("Combo: No valid basal rate read from pump", c.getReasons()) Assertions.assertEquals(false, c.value()) comboPlugin.setPluginEnabled(PluginType.PUMP, false) } diff --git a/pump/combov2/build.gradle b/pump/combov2/build.gradle index fd35c11a7e..902108af6a 100644 --- a/pump/combov2/build.gradle +++ b/pump/combov2/build.gradle @@ -13,6 +13,7 @@ apply from: "${project.rootDir}/core/main/jacoco_global.gradle" dependencies { implementation project(':core:libraries') implementation project(':core:interfaces') + implementation project(':core:main') implementation project(':core:ui') implementation project(':core:utils') implementation(project(":pump:combov2:comboctl")) diff --git a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt index 4cfac85c8e..b4029a24fd 100644 --- a/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt +++ b/pump/combov2/src/main/kotlin/info/nightscout/pump/combov2/ComboV2Plugin.kt @@ -25,12 +25,14 @@ import info.nightscout.comboctl.parser.AlertScreenContent import info.nightscout.comboctl.parser.AlertScreenException import info.nightscout.comboctl.parser.BatteryState import info.nightscout.comboctl.parser.ReservoirState +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.interfaces.AndroidPermission import info.nightscout.interfaces.Config import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType @@ -101,14 +103,14 @@ import info.nightscout.comboctl.main.PumpManager as ComboCtlPumpManager internal const val PUMP_ERROR_TIMEOUT_INTERVAL_MSECS = 1000L * 60 * 5 @Singleton -class ComboV2Plugin @Inject constructor ( +class ComboV2Plugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rh: ResourceHelper, commandQueue: CommandQueue, private val context: Context, private val rxBus: RxBus, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val sp: SP, private val pumpSync: PumpSync, private val dateUtil: DateUtil, @@ -132,7 +134,7 @@ class ComboV2Plugin @Inject constructor ( commandQueue ), Pump, - Constraints { + PluginConstraints { // Coroutine scope and the associated job. All coroutines // that are started in this plugin are part of this scope. @@ -208,6 +210,7 @@ class ComboV2Plugin @Inject constructor ( // overwritten. This check is performed in checkBasalProfile(). // In setNewBasalProfile(), this value is changed. private var activeBasalProfile: BasalProfile? = null + // This is used for checking that the correct basal profile is // active in the Combo. If not, loop invocation is disallowed. // This is _not_ reset by disconnect(). That's on purpose; it @@ -220,22 +223,28 @@ class ComboV2Plugin @Inject constructor ( /*** Public functions and base class & interface overrides ***/ sealed class DriverState(@Suppress("unused") val label: String) { + // Initial state when the driver is created. - object NotInitialized : DriverState("notInitialized") + data object NotInitialized : DriverState("notInitialized") + // Driver is disconnected from the pump, or no pump // is currently paired. In onStart() the driver state // changes from NotInitialized to this. - object Disconnected : DriverState("disconnected") + data object Disconnected : DriverState("disconnected") + // Driver is currently connecting to the pump. isBusy() // will return true in this state. - object Connecting : DriverState("connecting") + data object Connecting : DriverState("connecting") + // Driver is running checks on the pump, like verifying // that the basal rate is OK, checking for any bolus // and TBR activity that AAPS doesn't know about etc. // isBusy() will return true in this state. - object CheckingPump : DriverState("checkingPump") + data object CheckingPump : DriverState("checkingPump") + // Driver is connected and ready to execute commands. - object Ready : DriverState("ready") + data object Ready : DriverState("ready") + // Driver is connected, but pump is suspended and // cannot currently execute commands. This state is // special in that it technically persists even after @@ -252,11 +261,12 @@ class ComboV2Plugin @Inject constructor ( // the pump is currently suspended or not. Use // isSuspended() instead. See the pumpIsSuspended // documentation for details. - object Suspended : DriverState("suspended") + data object Suspended : DriverState("suspended") + // Driver is currently executing a command. // isBusy() will return true in this state. class ExecutingCommand(val description: ComboCtlPump.CommandDescription) : DriverState("executingCommand") - object Error : DriverState("error") + data object Error : DriverState("error") } private val driverStateFlow = _driverStateFlow.asStateFlow() @@ -264,7 +274,9 @@ class ComboV2Plugin @Inject constructor ( // Used by ComboV2PairingActivity to launch its own // custom activities that have a result. var customDiscoveryActivityStartCallback: ((intent: Intent) -> Unit)? - set(value) { bluetoothInterface?.customDiscoveryActivityStartCallback = value } + set(value) { + bluetoothInterface?.customDiscoveryActivityStartCallback = value + } get() = bluetoothInterface?.customDiscoveryActivityStartCallback init { @@ -494,6 +506,7 @@ class ComboV2Plugin @Inject constructor ( // returning true then causes problems with AAPS' KeepAlive mechanism. DriverState.CheckingPump, is DriverState.ExecutingCommand -> true + else -> false } @@ -509,6 +522,7 @@ class ComboV2Plugin @Inject constructor ( DriverState.Ready, DriverState.Suspended, is DriverState.ExecutingCommand -> true + else -> false } @@ -516,7 +530,8 @@ class ComboV2Plugin @Inject constructor ( when (driverStateFlow.value) { DriverState.Connecting, DriverState.CheckingPump -> true - else -> false + + else -> false } // There is no corresponding indicator for this @@ -554,7 +569,8 @@ class ComboV2Plugin @Inject constructor ( ) return } - else -> Unit + + else -> Unit } if (!isPaired()) { @@ -575,6 +591,7 @@ class ComboV2Plugin @Inject constructor ( unpairDueToPumpDataError() return } + else -> address } @@ -608,13 +625,13 @@ class ComboV2Plugin @Inject constructor ( // the rxBus too early, potentially causing a situation where the connect() // call isn't fully done yet, but the queue gets that event and thinks that // it can try to reconnect now. - ComboCtlPump.State.Disconnected -> return@onEach - ComboCtlPump.State.Connecting -> DriverState.Connecting - ComboCtlPump.State.CheckingPump -> DriverState.CheckingPump - ComboCtlPump.State.ReadyForCommands -> DriverState.Ready + ComboCtlPump.State.Disconnected -> return@onEach + ComboCtlPump.State.Connecting -> DriverState.Connecting + ComboCtlPump.State.CheckingPump -> DriverState.CheckingPump + ComboCtlPump.State.ReadyForCommands -> DriverState.Ready is ComboCtlPump.State.ExecutingCommand -> DriverState.ExecutingCommand(pumpState.description) - ComboCtlPump.State.Suspended -> DriverState.Suspended - is ComboCtlPump.State.Error -> DriverState.Error + ComboCtlPump.State.Suspended -> DriverState.Suspended + is ComboCtlPump.State.Error -> DriverState.Error } setDriverState(driverState) } @@ -686,7 +703,8 @@ class ComboV2Plugin @Inject constructor ( pumpIsSuspended = when (it.stateFlow.value) { ComboCtlPump.State.Suspended, is ComboCtlPump.State.Error -> true - else -> false + + else -> false } aapsLogger.debug(LTag.PUMP, "Pump is suspended: $pumpIsSuspended") @@ -970,8 +988,8 @@ class ComboV2Plugin @Inject constructor ( pumpStatus?.batteryState?.let { newState -> val newLevel = when (newState) { - BatteryState.NO_BATTERY -> 5 - BatteryState.LOW_BATTERY -> 25 + BatteryState.NO_BATTERY -> 5 + BatteryState.LOW_BATTERY -> 25 BatteryState.FULL_BATTERY -> 100 } @@ -996,7 +1014,7 @@ class ComboV2Plugin @Inject constructor ( override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { val oldInsulinAmount = detailedBolusInfo.insulin detailedBolusInfo.insulin = constraintChecker - .applyBolusConstraints(Constraint(detailedBolusInfo.insulin)) + .applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)) .value() aapsLogger.debug( LTag.PUMP, @@ -1015,8 +1033,8 @@ class ComboV2Plugin @Inject constructor ( val requestedBolusAmount = detailedBolusInfo.insulin.iuToCctlBolus() val bolusReason = when (detailedBolusInfo.bolusType) { - DetailedBolusInfo.BolusType.NORMAL -> ComboCtlPump.StandardBolusReason.NORMAL - DetailedBolusInfo.BolusType.SMB -> ComboCtlPump.StandardBolusReason.SUPERBOLUS + DetailedBolusInfo.BolusType.NORMAL -> ComboCtlPump.StandardBolusReason.NORMAL + DetailedBolusInfo.BolusType.SMB -> ComboCtlPump.StandardBolusReason.SUPERBOLUS DetailedBolusInfo.BolusType.PRIMING -> ComboCtlPump.StandardBolusReason.PRIMING_INFUSION_SET } @@ -1055,13 +1073,15 @@ class ComboV2Plugin @Inject constructor ( bolusingEvent.status = rh.gs(info.nightscout.core.ui.R.string.bolus_delivering, detailedBolusInfo.insulin) rxBus.send(bolusingEvent) } - BasicProgressStage.Finished -> { + + BasicProgressStage.Finished -> { val bolusingEvent = EventOverviewBolusProgress bolusingEvent.percent = (progressReport.overallProgress * 100.0).toInt() bolusingEvent.status = "Bolus finished, performing post-bolus checks" rxBus.send(bolusingEvent) } - else -> Unit + + else -> Unit } } } @@ -1190,10 +1210,11 @@ class ComboV2Plugin @Inject constructor ( aapsLogger.debug(LTag.PUMP, "Calculated percentage of $percentage% out of absolute rate $absoluteRate; rounded to: $roundedPercentage%; limited to: $limitedPercentage%") val cctlTbrType = when (tbrType) { - PumpSync.TemporaryBasalType.NORMAL -> ComboCtlTbr.Type.NORMAL + PumpSync.TemporaryBasalType.NORMAL -> ComboCtlTbr.Type.NORMAL PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND -> ComboCtlTbr.Type.EMULATED_COMBO_STOP - PumpSync.TemporaryBasalType.SUPERBOLUS -> ComboCtlTbr.Type.SUPERBOLUS - PumpSync.TemporaryBasalType.PUMP_SUSPEND -> { + PumpSync.TemporaryBasalType.SUPERBOLUS -> ComboCtlTbr.Type.SUPERBOLUS + + PumpSync.TemporaryBasalType.PUMP_SUSPEND -> { aapsLogger.error( LTag.PUMP, "PUMP_SUSPEND TBR type produced by AAPS for the TBR initiation even though this is supposed to only be produced by pump drivers" @@ -1221,10 +1242,11 @@ class ComboV2Plugin @Inject constructor ( aapsLogger.debug(LTag.PUMP, "Got percentage of $percent%; rounded to: $roundedPercentage%; limited to: $limitedPercentage%") val cctlTbrType = when (tbrType) { - PumpSync.TemporaryBasalType.NORMAL -> ComboCtlTbr.Type.NORMAL + PumpSync.TemporaryBasalType.NORMAL -> ComboCtlTbr.Type.NORMAL PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND -> ComboCtlTbr.Type.EMULATED_COMBO_STOP - PumpSync.TemporaryBasalType.SUPERBOLUS -> ComboCtlTbr.Type.SUPERBOLUS - PumpSync.TemporaryBasalType.PUMP_SUSPEND -> { + PumpSync.TemporaryBasalType.SUPERBOLUS -> ComboCtlTbr.Type.SUPERBOLUS + + PumpSync.TemporaryBasalType.PUMP_SUSPEND -> { aapsLogger.error( LTag.PUMP, "PUMP_SUSPEND TBR type produced by AAPS for the TBR initiation even though this is supposed to only be produced by pump drivers" @@ -1277,10 +1299,13 @@ class ComboV2Plugin @Inject constructor ( val tbrComment = when (acquiredPump.setTbr(percentage, durationInMinutes, tbrType, force100Percent)) { ComboCtlPump.SetTbrOutcome.SET_NORMAL_TBR -> rh.gs(R.string.combov2_setting_tbr_succeeded) + ComboCtlPump.SetTbrOutcome.SET_EMULATED_100_TBR -> rh.gs(R.string.combov2_set_emulated_100_tbr) + ComboCtlPump.SetTbrOutcome.LETTING_EMULATED_100_TBR_FINISH -> rh.gs(R.string.combov2_letting_emulated_100_tbr_finish) + ComboCtlPump.SetTbrOutcome.IGNORED_REDUNDANT_100_TBR -> rh.gs(R.string.combov2_ignoring_redundant_100_tbr) } @@ -1381,7 +1406,7 @@ class ComboV2Plugin @Inject constructor ( } ?: aapsLogger.info( LTag.PUMP, "Cannot include reservoir level in JSON status " + - "since no such level is currently known" + "since no such level is currently known" ) put("extended", JSONObject().apply { put("Version", version) @@ -1401,15 +1426,17 @@ class ComboV2Plugin @Inject constructor ( aapsLogger.info( LTag.PUMP, "Cannot include base basal rate in JSON status " + - "since no basal profile is currently active" + "since no basal profile is currently active" ) put("ActiveProfile", profileName) when (val alert = lastComboAlert) { is AlertScreenContent.Warning -> put("WarningCode", alert.code) - is AlertScreenContent.Error -> + + is AlertScreenContent.Error -> put("ErrorCode", alert.code) - else -> Unit + + else -> Unit } }) } @@ -1448,8 +1475,8 @@ class ComboV2Plugin @Inject constructor ( val alertCodeString = when (val alert = lastComboAlert) { is AlertScreenContent.Warning -> "W${alert.code}" - is AlertScreenContent.Error -> "E${alert.code}" - else -> null + is AlertScreenContent.Error -> "E${alert.code}" + else -> null } if (alertCodeString != null) lines += rh.gs(R.string.combov2_short_status_alert, alertCodeString) @@ -1476,8 +1503,8 @@ class ComboV2Plugin @Inject constructor ( it.availableUnitsInReservoir ) val batteryStateDesc = when (it.batteryState) { - BatteryState.NO_BATTERY -> rh.gs(R.string.combov2_short_status_battery_state_empty) - BatteryState.LOW_BATTERY -> rh.gs(R.string.combov2_short_status_battery_state_low) + BatteryState.NO_BATTERY -> rh.gs(R.string.combov2_short_status_battery_state_empty) + BatteryState.LOW_BATTERY -> rh.gs(R.string.combov2_short_status_battery_state_low) BatteryState.FULL_BATTERY -> rh.gs(R.string.combov2_short_status_battery_state_full) } lines += rh.gs( @@ -1562,9 +1589,9 @@ class ComboV2Plugin @Inject constructor ( val reason = when (timeChangeType) { TimeChangeType.TimezoneChanged -> rh.gs(R.string.combov2_timezone_changed) - TimeChangeType.TimeChanged -> rh.gs(R.string.combov2_datetime_changed) - TimeChangeType.DSTStarted -> rh.gs(R.string.combov2_dst_started) - TimeChangeType.DSTEnded -> rh.gs(R.string.combov2_dst_ended) + TimeChangeType.TimeChanged -> rh.gs(R.string.combov2_datetime_changed) + TimeChangeType.DSTStarted -> rh.gs(R.string.combov2_dst_started) + TimeChangeType.DSTEnded -> rh.gs(R.string.combov2_dst_ended) } // Updating pump status implicitly also updates the pump's local datetime, // which is what we want after the system datetime/timezone/DST changed. @@ -1594,12 +1621,7 @@ class ComboV2Plugin @Inject constructor ( ) if (!isAllowed) { - value.set( - aapsLogger, - false, - rh.gs(R.string.combov2_incorrect_active_basal_profile, lastActiveBasalProfileNumber), - this - ) + value.set(false, rh.gs(R.string.combov2_incorrect_active_basal_profile, lastActiveBasalProfileNumber), this) } } else { aapsLogger.info( @@ -1753,7 +1775,6 @@ class ComboV2Plugin @Inject constructor ( // the PumpManager onPumpUnpaired callback. } - /*** User interface flows ***/ // "UI flows" are hot flows that are meant to be used for showing @@ -1788,6 +1809,7 @@ class ComboV2Plugin @Inject constructor ( // establishing a BT connection, or delivering a bolus, setting // a basal rate factor, reading the current pump datetime etc. data class CurrentActivityInfo(val description: String, val overallProgress: Double) + private fun noCurrentActivity() = CurrentActivityInfo("", 0.0) private var _currentActivityUIFlow = MutableStateFlow(noCurrentActivity()) val currentActivityUIFlow = _currentActivityUIFlow.asStateFlow() @@ -1799,6 +1821,7 @@ class ComboV2Plugin @Inject constructor ( val batteryStateUIFlow = _batteryStateUIFlow.asStateFlow() data class ReservoirLevel(val state: ReservoirState, val availableUnits: Int) + private var _reservoirLevelUIFlow = MutableStateFlow(null) val reservoirLevelUIFlow = _reservoirLevelUIFlow.asStateFlow() @@ -1830,7 +1853,6 @@ class ComboV2Plugin @Inject constructor ( private var _displayFrameUIFlow = MutableSharedFlow(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) val displayFrameUIFlow = _displayFrameUIFlow.asSharedFlow() - /*** Misc private functions ***/ private fun setupUiFlows(acquiredPump: ComboCtlPump) { @@ -1845,6 +1867,7 @@ class ComboV2Plugin @Inject constructor ( R.string.combov2_establishing_bt_connection, progStage.currentAttemptNr ) + BasicProgressStage.PerformingConnectionHandshake -> rh.gs(R.string.combov2_pairing_performing_handshake) else -> "" } @@ -1860,10 +1883,12 @@ class ComboV2Plugin @Inject constructor ( val description = when (progressReport.stage) { RTCommandProgressStage.SettingDateTimeHour, RTCommandProgressStage.SettingDateTimeMinute -> rh.gs(R.string.combov2_setting_current_pump_time) + RTCommandProgressStage.SettingDateTimeYear, RTCommandProgressStage.SettingDateTimeMonth, - RTCommandProgressStage.SettingDateTimeDay -> rh.gs(R.string.combov2_setting_current_pump_date) - else -> "" + RTCommandProgressStage.SettingDateTimeDay -> rh.gs(R.string.combov2_setting_current_pump_date) + + else -> "" } _currentActivityUIFlow.value = CurrentActivityInfo( description, @@ -1877,7 +1902,8 @@ class ComboV2Plugin @Inject constructor ( val description = when (val stage = progressReport.stage) { is RTCommandProgressStage.GettingBasalProfile -> rh.gs(R.string.combov2_getting_basal_profile, stage.numSetFactors) - else -> "" + + else -> "" } _currentActivityUIFlow.value = CurrentActivityInfo( description, @@ -1891,7 +1917,8 @@ class ComboV2Plugin @Inject constructor ( val description = when (val stage = progressReport.stage) { is RTCommandProgressStage.SettingBasalProfile -> rh.gs(R.string.combov2_setting_basal_profile, stage.numSetFactors) - else -> "" + + else -> "" } _currentActivityUIFlow.value = CurrentActivityInfo( description, @@ -1906,10 +1933,11 @@ class ComboV2Plugin @Inject constructor ( is RTCommandProgressStage.DeliveringBolus -> rh.gs( R.string.combov2_delivering_bolus, - stage.deliveredImmediateAmount .cctlBolusToIU(), + stage.deliveredImmediateAmount.cctlBolusToIU(), stage.totalImmediateAmount.cctlBolusToIU() ) - else -> "" + + else -> "" } _currentActivityUIFlow.value = CurrentActivityInfo( description, @@ -1981,7 +2009,7 @@ class ComboV2Plugin @Inject constructor ( aapsLogger.debug(LTag.PUMP, "Handling pump event $event") when (event) { - is ComboCtlPump.Event.BatteryLow -> { + is ComboCtlPump.Event.BatteryLow -> { uiInteraction.addNotification( Notification.COMBO_PUMP_ALARM, text = rh.gs(R.string.combov2_battery_low_warning), @@ -1989,7 +2017,7 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.ReservoirLow -> { + is ComboCtlPump.Event.ReservoirLow -> { uiInteraction.addNotification( Notification.COMBO_PUMP_ALARM, text = rh.gs(R.string.combov2_reservoir_low_warning), @@ -1997,7 +2025,7 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.QuickBolusInfused -> { + is ComboCtlPump.Event.QuickBolusInfused -> { pumpSync.syncBolusWithPumpId( event.timestamp.toEpochMilliseconds(), event.bolusAmount.cctlBolusToIU(), @@ -2010,8 +2038,8 @@ class ComboV2Plugin @Inject constructor ( is ComboCtlPump.Event.StandardBolusInfused -> { val bolusType = when (event.standardBolusReason) { - ComboCtlPump.StandardBolusReason.NORMAL -> DetailedBolusInfo.BolusType.NORMAL - ComboCtlPump.StandardBolusReason.SUPERBOLUS -> DetailedBolusInfo.BolusType.SMB + ComboCtlPump.StandardBolusReason.NORMAL -> DetailedBolusInfo.BolusType.NORMAL + ComboCtlPump.StandardBolusReason.SUPERBOLUS -> DetailedBolusInfo.BolusType.SMB ComboCtlPump.StandardBolusReason.PRIMING_INFUSION_SET -> DetailedBolusInfo.BolusType.PRIMING } pumpSync.syncBolusWithPumpId( @@ -2036,7 +2064,7 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.ExtendedBolusEnded -> { + is ComboCtlPump.Event.ExtendedBolusEnded -> { pumpSync.syncStopExtendedBolusWithPumpId( event.timestamp.toEpochMilliseconds(), event.bolusId, @@ -2045,15 +2073,15 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.TbrStarted -> { + is ComboCtlPump.Event.TbrStarted -> { aapsLogger.debug(LTag.PUMP, "Pump reports TBR started; expected state according to AAPS: ${pumpSync.expectedPumpState()}") val tbrStartTimestampInMs = event.tbr.timestamp.toEpochMilliseconds() val tbrType = when (event.tbr.type) { - ComboCtlTbr.Type.NORMAL -> PumpSync.TemporaryBasalType.NORMAL + ComboCtlTbr.Type.NORMAL -> PumpSync.TemporaryBasalType.NORMAL ComboCtlTbr.Type.EMULATED_100_PERCENT -> PumpSync.TemporaryBasalType.NORMAL - ComboCtlTbr.Type.SUPERBOLUS -> PumpSync.TemporaryBasalType.SUPERBOLUS - ComboCtlTbr.Type.EMULATED_COMBO_STOP -> PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND - ComboCtlTbr.Type.COMBO_STOPPED -> PumpSync.TemporaryBasalType.PUMP_SUSPEND + ComboCtlTbr.Type.SUPERBOLUS -> PumpSync.TemporaryBasalType.SUPERBOLUS + ComboCtlTbr.Type.EMULATED_COMBO_STOP -> PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND + ComboCtlTbr.Type.COMBO_STOPPED -> PumpSync.TemporaryBasalType.PUMP_SUSPEND } pumpSync.syncTemporaryBasalWithPumpId( timestamp = tbrStartTimestampInMs, @@ -2067,7 +2095,7 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.TbrEnded -> { + is ComboCtlPump.Event.TbrEnded -> { aapsLogger.debug(LTag.PUMP, "Pump reports TBR ended; expected state according to AAPS: ${pumpSync.expectedPumpState()}") val tbrEndTimestampInMs = event.timestampWhenTbrEnded.toEpochMilliseconds() pumpSync.syncStopTemporaryBasalWithPumpId( @@ -2078,7 +2106,7 @@ class ComboV2Plugin @Inject constructor ( ) } - is ComboCtlPump.Event.UnknownTbrDetected -> { + is ComboCtlPump.Event.UnknownTbrDetected -> { // Inform about this unknown TBR that was observed (and automatically aborted). val remainingDurationString = String.format( "%02d:%02d", @@ -2096,7 +2124,7 @@ class ComboV2Plugin @Inject constructor ( ) } - else -> Unit + else -> Unit } } @@ -2229,9 +2257,11 @@ class ComboV2Plugin @Inject constructor ( when (driverStateUIFlow.value) { DriverState.Error, DriverState.Suspended -> false - else -> true + + else -> true } } + else -> true } if (updateUIState) { @@ -2264,10 +2294,12 @@ class ComboV2Plugin @Inject constructor ( if (oldState != DriverState.Suspended) rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)) } + DriverState.Suspended -> { if (oldState != DriverState.Ready) rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)) } + else -> Unit } } @@ -2336,8 +2368,8 @@ class ComboV2Plugin @Inject constructor ( when (alert) { is AlertScreenContent.Warning -> { val desc = when (alert.code) { - 4 -> rh.gs(R.string.combov2_warning_4) - 10 -> rh.gs(R.string.combov2_warning_10) + 4 -> rh.gs(R.string.combov2_warning_4) + 10 -> rh.gs(R.string.combov2_warning_10) else -> "" } @@ -2345,18 +2377,18 @@ class ComboV2Plugin @Inject constructor ( if (desc.isEmpty()) "" else ": $desc" } - is AlertScreenContent.Error -> { + is AlertScreenContent.Error -> { val desc = when (alert.code) { - 1 -> rh.gs(R.string.combov2_error_1) - 2 -> rh.gs(R.string.combov2_error_2) - 4 -> rh.gs(R.string.combov2_error_4) - 5 -> rh.gs(R.string.combov2_error_5) - 6 -> rh.gs(R.string.combov2_error_6) - 7 -> rh.gs(R.string.combov2_error_7) - 8 -> rh.gs(R.string.combov2_error_8) - 9 -> rh.gs(R.string.combov2_error_9) - 10 -> rh.gs(R.string.combov2_error_10) - 11 -> rh.gs(R.string.combov2_error_11) + 1 -> rh.gs(R.string.combov2_error_1) + 2 -> rh.gs(R.string.combov2_error_2) + 4 -> rh.gs(R.string.combov2_error_4) + 5 -> rh.gs(R.string.combov2_error_5) + 6 -> rh.gs(R.string.combov2_error_6) + 7 -> rh.gs(R.string.combov2_error_7) + 8 -> rh.gs(R.string.combov2_error_8) + 9 -> rh.gs(R.string.combov2_error_9) + 10 -> rh.gs(R.string.combov2_error_10) + 11 -> rh.gs(R.string.combov2_error_11) else -> "" } @@ -2364,7 +2396,7 @@ class ComboV2Plugin @Inject constructor ( if (desc.isEmpty()) "" else ": $desc" } - else -> rh.gs(R.string.combov2_unrecognized_alert) + else -> rh.gs(R.string.combov2_unrecognized_alert) } private fun notifyAboutComboAlert(alert: AlertScreenContent) { @@ -2411,6 +2443,7 @@ class ComboV2Plugin @Inject constructor ( when (driverStateFlow.value) { DriverState.NotInitialized, DriverState.Disconnected -> true - else -> false + + else -> false } } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt index b2f3b92da9..f6936bc825 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt @@ -10,9 +10,9 @@ import info.nightscout.androidaps.danaRKorean.services.DanaRKoreanExecutionServi import info.nightscout.androidaps.danar.AbstractDanaRPlugin import info.nightscout.androidaps.danar.R import info.nightscout.annotations.OpenForTesting +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.fabric.FabricPrivacy -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.pump.DetailedBolusInfo @@ -51,7 +51,7 @@ class DanaRKoreanPlugin @Inject constructor( rxBus: RxBus, private val context: Context, rh: ResourceHelper, - constraintChecker: Constraints, + constraintChecker: ConstraintsChecker, activePlugin: ActivePlugin, sp: SP, commandQueue: CommandQueue, @@ -147,7 +147,7 @@ class DanaRKoreanPlugin @Inject constructor( } override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)).value() require(detailedBolusInfo.carbs > 0) return if (detailedBolusInfo.insulin > 0) { val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.id) @@ -192,7 +192,7 @@ class DanaRKoreanPlugin @Inject constructor( override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: TemporaryBasalType): PumpEnactResult { // Recheck pump status if older than 30 min //This should not be needed while using queue because connection should be done before calling this - val absoluteRateAfterConstraint = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val absoluteRateAfterConstraint = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, injector), profile).value() var doTempOff = baseBasalRate - absoluteRateAfterConstraint == 0.0 && absoluteRateAfterConstraint >= 0.10 val doLowTemp = absoluteRateAfterConstraint < baseBasalRate || absoluteRateAfterConstraint < 0.10 val doHighTemp = absoluteRateAfterConstraint > baseBasalRate && !useExtendedBoluses @@ -266,7 +266,7 @@ class DanaRKoreanPlugin @Inject constructor( val durationInHalfHours = max(durationInMinutes / 30, 1) // We keep current basal running so need to sub current basal var extendedRateToSet: Double = absoluteRateAfterConstraint - baseBasalRate - extendedRateToSet = constraintChecker.applyBasalConstraints(Constraint(extendedRateToSet), profile).value() + extendedRateToSet = constraintChecker.applyBasalConstraints(ConstraintObject(extendedRateToSet, injector), profile).value() // needs to be rounded to 0.1 extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2) // *2 because of half hours diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java index efe68dac24..062262cf4e 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java @@ -34,7 +34,7 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal; import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService; import info.nightscout.interfaces.Constants; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.ConstraintsChecker; import info.nightscout.interfaces.notifications.Notification; import info.nightscout.interfaces.profile.Profile; import info.nightscout.interfaces.profile.ProfileFunction; @@ -62,7 +62,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @Inject RxBus rxBus; @Inject ResourceHelper rh; - @Inject Constraints constraintChecker; + @Inject ConstraintsChecker constraintChecker; @Inject DanaPump danaPump; @Inject DanaRPlugin danaRPlugin; @Inject DanaRKoreanPlugin danaRKoreanPlugin; @@ -83,12 +83,6 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { mBinder = new LocalBinder(); } - public class LocalBinder extends Binder { - public DanaRKoreanExecutionService getServiceInstance() { - return DanaRKoreanExecutionService.this; - } - } - @SuppressLint("MissingPermission") public void connect() { if (mConnectionInProgress) return; @@ -330,4 +324,10 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { return null; } + public class LocalBinder extends Binder { + public DanaRKoreanExecutionService getServiceInstance() { + return DanaRKoreanExecutionService.this; + } + } + } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index 7c35ab543e..77b6cc0aa7 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -16,9 +16,9 @@ import info.nightscout.androidaps.danaRv2.services.DanaRv2ExecutionService; import info.nightscout.androidaps.danar.AbstractDanaRPlugin; import info.nightscout.androidaps.danar.R; import info.nightscout.annotations.OpenForTesting; +import info.nightscout.core.constraints.ConstraintObject; import info.nightscout.core.utils.fabric.FabricPrivacy; -import info.nightscout.interfaces.constraints.Constraint; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.ConstraintsChecker; import info.nightscout.interfaces.plugin.ActivePlugin; import info.nightscout.interfaces.profile.Profile; import info.nightscout.interfaces.pump.DetailedBolusInfo; @@ -53,6 +53,19 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { private final DetailedBolusInfoStorage detailedBolusInfoStorage; private final TemporaryBasalStorage temporaryBasalStorage; private final FabricPrivacy fabricPrivacy; + private final ServiceConnection mConnection = new ServiceConnection() { + + public void onServiceDisconnected(ComponentName name) { + aapsLogger.debug(LTag.PUMP, "Service is disconnected"); + sExecutionService = null; + } + + public void onServiceConnected(ComponentName name, IBinder service) { + aapsLogger.debug(LTag.PUMP, "Service is connected"); + DanaRv2ExecutionService.LocalBinder mLocalBinder = (DanaRv2ExecutionService.LocalBinder) service; + sExecutionService = mLocalBinder.getServiceInstance(); + } + }; @Inject public DanaRv2Plugin( @@ -62,7 +75,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { RxBus rxBus, Context context, ResourceHelper rh, - Constraints constraintChecker, + ConstraintsChecker constraintChecker, ActivePlugin activePlugin, SP sp, CommandQueue commandQueue, @@ -111,20 +124,6 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { super.onStop(); } - private final ServiceConnection mConnection = new ServiceConnection() { - - public void onServiceDisconnected(ComponentName name) { - aapsLogger.debug(LTag.PUMP, "Service is disconnected"); - sExecutionService = null; - } - - public void onServiceConnected(ComponentName name, IBinder service) { - aapsLogger.debug(LTag.PUMP, "Service is connected"); - DanaRv2ExecutionService.LocalBinder mLocalBinder = (DanaRv2ExecutionService.LocalBinder) service; - sExecutionService = mLocalBinder.getServiceInstance(); - } - }; - // Plugin base interface @NonNull @Override @@ -160,7 +159,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { // Pump interface @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new ConstraintObject<>(detailedBolusInfo.insulin, getInjector())).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { // v2 stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U @@ -225,7 +224,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(getInjector()); - absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = constraintChecker.applyBasalConstraints(new ConstraintObject<>(absoluteRate, getInjector()), profile).value(); boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; final boolean doLowTemp = absoluteRate < getBaseBasalRate() || absoluteRate < 0.10d; @@ -291,7 +290,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) { DanaPump pump = danaPump; PumpEnactResult result = new PumpEnactResult(getInjector()); - percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = constraintChecker.applyBasalPercentConstraints(new ConstraintObject<>(percent, getInjector()), profile).value(); if (percent < 0) { result.isTempCancel(false).enacted(false).success(false).comment(info.nightscout.core.ui.R.string.invalid_input); aapsLogger.error("setTempBasalPercent: Invalid input"); @@ -352,7 +351,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { @NonNull @Override public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) { DanaPump pump = danaPump; - insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = constraintChecker.applyExtendedBolusConstraints(new ConstraintObject<>(insulin, getInjector())).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.INSTANCE.roundTo(insulin, getPumpDescription().getExtendedBolusStep()); diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index f5d7c965d4..1304e70ca5 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -7,8 +7,10 @@ import org.json.JSONObject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService; +import info.nightscout.core.constraints.ConstraintObject; import info.nightscout.interfaces.constraints.Constraint; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.ConstraintsChecker; +import info.nightscout.interfaces.constraints.PluginConstraints; import info.nightscout.interfaces.notifications.Notification; import info.nightscout.interfaces.plugin.ActivePlugin; import info.nightscout.interfaces.plugin.OwnDatabasePlugin; @@ -46,7 +48,7 @@ import io.reactivex.rxjava3.disposables.CompositeDisposable; * Created by mike on 28.01.2018. */ -public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump, Dana, Constraints, OwnDatabasePlugin { +public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump, Dana, PluginConstraints, OwnDatabasePlugin { protected AbstractDanaRExecutionService sExecutionService; protected CompositeDisposable disposable = new CompositeDisposable(); @@ -55,7 +57,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected PumpDescription pumpDescription = new PumpDescription(); protected DanaPump danaPump; - protected Constraints constraintChecker; + protected ConstraintsChecker constraintChecker; protected RxBus rxBus; protected ActivePlugin activePlugin; protected SP sp; @@ -65,11 +67,12 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected UiInteraction uiInteraction; protected DanaHistoryDatabase danaHistoryDatabase; protected DecimalFormatter decimalFormatter; + protected AbstractDanaRPlugin( HasAndroidInjector injector, DanaPump danaPump, ResourceHelper rh, - Constraints constraintChecker, + ConstraintsChecker constraintChecker, AAPSLogger aapsLogger, AapsSchedulers aapsSchedulers, CommandQueue commandQueue, @@ -223,7 +226,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NonNull Profile profile, boolean enforceNew, @NonNull PumpSync.TemporaryBasalType tbrType) { PumpEnactResult result = new PumpEnactResult(getInjector()); - percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = constraintChecker.applyBasalPercentConstraints(new ConstraintObject<>(percent, getInjector()), profile).value(); if (percent < 0) { result.isTempCancel(false).enacted(false).success(false).comment(info.nightscout.core.ui.R.string.invalid_input); getAapsLogger().error("setTempBasalPercent: Invalid input"); @@ -270,7 +273,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) { - insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = constraintChecker.applyExtendedBolusConstraints(new ConstraintObject<>(insulin, getInjector())).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.INSTANCE.roundTo(insulin, getPumpDescription().getExtendedBolusStep()); @@ -462,21 +465,21 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump @NonNull @Override public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfSmaller(getAapsLogger(), danaPump.getMaxBasal(), getRh().gs(info.nightscout.core.ui.R.string.limitingbasalratio, danaPump.getMaxBasal(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); + absoluteRate.setIfSmaller(danaPump.getMaxBasal(), getRh().gs(info.nightscout.core.ui.R.string.limitingbasalratio, danaPump.getMaxBasal(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); return absoluteRate; } @NonNull @Override public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, getRh().gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, getRh().gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().getMaxTempPercent(), getRh().gs(info.nightscout.core.ui.R.string.limitingpercentrate, getPumpDescription().getMaxTempPercent(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); + percentRate.setIfGreater(0, getRh().gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, getRh().gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this); + percentRate.setIfSmaller(getPumpDescription().getMaxTempPercent(), getRh().gs(info.nightscout.core.ui.R.string.limitingpercentrate, getPumpDescription().getMaxTempPercent(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); return percentRate; } @NonNull @Override public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(getAapsLogger(), danaPump.getMaxBolus(), getRh().gs(info.nightscout.core.ui.R.string.limitingbolus, danaPump.getMaxBolus(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); + insulin.setIfSmaller(danaPump.getMaxBolus(), getRh().gs(info.nightscout.core.ui.R.string.limitingbolus, danaPump.getMaxBolus(), getRh().gs(info.nightscout.core.ui.R.string.pumplimit)), this); return insulin; } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index ce102e2d25..ff4d9873be 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -14,9 +14,9 @@ import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.danar.services.DanaRExecutionService; import info.nightscout.annotations.OpenForTesting; +import info.nightscout.core.constraints.ConstraintObject; import info.nightscout.core.utils.fabric.FabricPrivacy; -import info.nightscout.interfaces.constraints.Constraint; -import info.nightscout.interfaces.constraints.Constraints; +import info.nightscout.interfaces.constraints.ConstraintsChecker; import info.nightscout.interfaces.plugin.ActivePlugin; import info.nightscout.interfaces.profile.Profile; import info.nightscout.interfaces.pump.DetailedBolusInfo; @@ -46,8 +46,20 @@ public class DanaRPlugin extends AbstractDanaRPlugin { private final AAPSLogger aapsLogger; private final Context context; private final ResourceHelper rh; - private final Constraints constraints; private final FabricPrivacy fabricPrivacy; + private final ServiceConnection mConnection = new ServiceConnection() { + + public void onServiceDisconnected(ComponentName name) { + aapsLogger.debug(LTag.PUMP, "Service is disconnected"); + sExecutionService = null; + } + + public void onServiceConnected(ComponentName name, IBinder service) { + aapsLogger.debug(LTag.PUMP, "Service is connected"); + DanaRExecutionService.LocalBinder mLocalBinder = (DanaRExecutionService.LocalBinder) service; + sExecutionService = mLocalBinder.getServiceInstance(); + } + }; @Inject public DanaRPlugin( @@ -57,7 +69,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { RxBus rxBus, Context context, ResourceHelper rh, - Constraints constraints, + ConstraintsChecker constraintsChecker, ActivePlugin activePlugin, SP sp, CommandQueue commandQueue, @@ -69,11 +81,10 @@ public class DanaRPlugin extends AbstractDanaRPlugin { DanaHistoryDatabase danaHistoryDatabase, DecimalFormatter decimalFormatter ) { - super(injector, danaPump, rh, constraints, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter); + super(injector, danaPump, rh, constraintsChecker, aapsLogger, aapsSchedulers, commandQueue, rxBus, activePlugin, sp, dateUtil, pumpSync, uiInteraction, danaHistoryDatabase, decimalFormatter); this.aapsLogger = aapsLogger; this.context = context; this.rh = rh; - this.constraints = constraints; this.fabricPrivacy = fabricPrivacy; useExtendedBoluses = sp.getBoolean(info.nightscout.core.utils.R.string.key_danar_useextended, false); @@ -114,20 +125,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin { super.onStop(); } - private final ServiceConnection mConnection = new ServiceConnection() { - - public void onServiceDisconnected(ComponentName name) { - aapsLogger.debug(LTag.PUMP, "Service is disconnected"); - sExecutionService = null; - } - - public void onServiceConnected(ComponentName name, IBinder service) { - aapsLogger.debug(LTag.PUMP, "Service is connected"); - DanaRExecutionService.LocalBinder mLocalBinder = (DanaRExecutionService.LocalBinder) service; - sExecutionService = mLocalBinder.getServiceInstance(); - } - }; - // Plugin base interface @NonNull @Override @@ -163,7 +160,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @NonNull @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = constraints.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new ConstraintObject<>(detailedBolusInfo.insulin, getInjector())).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.getId()); boolean connectionOK = false; @@ -210,7 +207,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { //This should not be needed while using queue because connection should be done before calling this PumpEnactResult result = new PumpEnactResult(getInjector()); - absoluteRate = constraints.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = constraintChecker.applyBasalConstraints(new ConstraintObject<>(absoluteRate, getInjector()), profile).value(); boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d && absoluteRate >= 0.10d; final boolean doLowTemp = absoluteRate < getBaseBasalRate() || absoluteRate < 0.10d; @@ -289,7 +286,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { int durationInHalfHours = Math.max(durationInMinutes / 30, 1); // We keep current basal running so need to sub current basal double extendedRateToSet = absoluteRate - getBaseBasalRate(); - extendedRateToSet = constraints.applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); + extendedRateToSet = constraintChecker.applyBasalConstraints(new ConstraintObject<>(extendedRateToSet, getInjector()), profile).value(); // needs to be rounded to 0.1 extendedRateToSet = Round.INSTANCE.roundTo(extendedRateToSet, pumpDescription.getExtendedBolusStep() * 2); // *2 because of half hours diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt index a4e81c0bbf..785bc1c840 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.comm.MessageOriginalNames.getName import info.nightscout.androidaps.utils.CRC.getCrc16 import info.nightscout.interfaces.ConfigBuilder -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync @@ -48,7 +48,7 @@ open class MessageBase(injector: HasAndroidInjector) { @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Inject lateinit var temporaryBasalStorage: TemporaryBasalStorage - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var pumpSync: PumpSync @Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao @Inject lateinit var uiInteraction: UiInteraction diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStart.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStart.kt index d22424bed1..0049f5b93e 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStart.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStart.kt @@ -1,10 +1,9 @@ package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.rx.logging.LTag - class MsgBolusStart( injector: HasAndroidInjector, private var amount: Double @@ -13,7 +12,7 @@ class MsgBolusStart( init { setCommand(0x0102) // HARDCODED LIMIT - amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + amount = constraintChecker.applyBolusConstraints(ConstraintObject(amount, injector)).value() addParamInt((amount * 100).toInt()) aapsLogger.debug(LTag.PUMPBTCOMM, "Bolus start : $amount") } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStartWithSpeed.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStartWithSpeed.kt index caa86a6b6b..3a0c72d41a 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStartWithSpeed.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgBolusStartWithSpeed.kt @@ -1,10 +1,9 @@ package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.rx.logging.LTag - class MsgBolusStartWithSpeed( injector: HasAndroidInjector, private var amount: Double, @@ -14,7 +13,7 @@ class MsgBolusStartWithSpeed( init { setCommand(0x0104) // HARDCODED LIMIT - amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + amount = constraintChecker.applyBolusConstraints(ConstraintObject(amount, injector)).value() addParamInt((amount * 100).toInt()) addParamByte(speed.toByte()) aapsLogger.debug(LTag.PUMPBTCOMM, "Bolus start : $amount speed: $speed") @@ -24,10 +23,10 @@ class MsgBolusStartWithSpeed( val errorCode = intFromBuff(bytes, 0, 1) if (errorCode != 2) { failed = true - aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode FAILED!!") + aapsLogger.debug(LTag.PUMPBTCOMM, "Message response: $errorCode FAILED!!") } else { failed = false - aapsLogger.debug(LTag.PUMPBTCOMM, "Messsage response: $errorCode OK") + aapsLogger.debug(LTag.PUMPBTCOMM, "Message response: $errorCode OK") } danaPump.bolusStartErrorCode = errorCode } diff --git a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStart.kt b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStart.kt index 3bfc0a5aad..9c1f1ed0bc 100644 --- a/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStart.kt +++ b/pump/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgSetExtendedBolusStart.kt @@ -1,14 +1,13 @@ package info.nightscout.androidaps.danar.comm import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.rx.logging.LTag - class MsgSetExtendedBolusStart( injector: HasAndroidInjector, private var amount: Double, - private var halfhours: Byte + private var halfHours: Byte ) : MessageBase(injector) { @@ -16,12 +15,12 @@ class MsgSetExtendedBolusStart( setCommand(0x0407) aapsLogger.debug(LTag.PUMPBTCOMM, "New message") // HARDCODED LIMITS - if (halfhours < 1) halfhours = 1 - if (halfhours > 16) halfhours = 16 - amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + if (halfHours < 1) halfHours = 1 + if (halfHours > 16) halfHours = 16 + amount = constraintChecker.applyBolusConstraints(ConstraintObject(amount, injector)).value() addParamInt((amount * 100).toInt()) - addParamByte(halfhours) - aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start: " + (amount * 100).toInt() / 100.0 + "U halfhours: " + halfhours.toInt()) + addParamByte(halfHours) + aapsLogger.debug(LTag.PUMPBTCOMM, "Set extended bolus start: " + (amount * 100).toInt() / 100.0 + "U halfHours: " + halfHours.toInt()) } override fun handleMessage(bytes: ByteArray) { diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt index 095d7a676e..9f3585447a 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/DanaRPluginTest.kt @@ -3,9 +3,8 @@ package info.nightscout.pump.danaR import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danar.DanaRPlugin -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.pump.PumpSync @@ -22,7 +21,7 @@ import org.mockito.Mockito.`when` class DanaRPluginTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @Mock lateinit var instantiator: Instantiator @@ -34,7 +33,11 @@ class DanaRPluginTest : TestBaseWithProfile() { private lateinit var danaRPlugin: DanaRPlugin val injector = HasAndroidInjector { - AndroidInjector { } + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } } @BeforeEach @@ -57,11 +60,11 @@ class DanaRPluginTest : TestBaseWithProfile() { danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHBASALRATE) + val c = ConstraintObject(Double.MAX_VALUE, injector) danaRPlugin.applyBasalConstraints(c, validProfile) Assertions.assertEquals(0.8, c.value(), 0.01) - Assertions.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaR: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons()) } @Test @Throws(Exception::class) @@ -69,10 +72,10 @@ class DanaRPluginTest : TestBaseWithProfile() { danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) + val c = ConstraintObject(Int.MAX_VALUE, injector) danaRPlugin.applyBasalPercentConstraints(c, validProfile) Assertions.assertEquals(200, c.value()) - Assertions.assertEquals("DanaR: Limiting max percent rate to 200% because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaR: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaR: Limiting max percent rate to 200% because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaR: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons()) } } \ No newline at end of file diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt index 363ccba06c..6f294d210b 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/DanaRTestBase.kt @@ -6,8 +6,9 @@ import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danar.DanaRPlugin import info.nightscout.androidaps.danar.comm.MessageBase +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.ConfigBuilder -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync @@ -15,7 +16,6 @@ import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.dana.DanaPump import info.nightscout.pump.dana.database.DanaHistoryRecordDao -import info.nightscout.rx.bus.RxBus import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.BeforeEach import org.mockito.ArgumentMatchers @@ -32,7 +32,7 @@ open class DanaRTestBase : TestBaseWithProfile() { @Mock lateinit var configBuilder: ConfigBuilder @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var pumpSync: PumpSync @Mock lateinit var danaHistoryRecordDao: DanaHistoryRecordDao @Mock lateinit var instantiator: Instantiator @@ -50,6 +50,9 @@ open class DanaRTestBase : TestBaseWithProfile() { val injector = HasAndroidInjector { AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } if (it is MessageBase) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil @@ -57,7 +60,7 @@ open class DanaRTestBase : TestBaseWithProfile() { it.danaRPlugin = danaRPlugin it.danaRKoreanPlugin = danaRKoreanPlugin it.danaRv2Plugin = danaRv2Plugin - it.rxBus = RxBus(aapsSchedulers, aapsLogger) + it.rxBus = rxBus it.rh = rh it.activePlugin = activePlugin it.configBuilder = configBuilder diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MessageHashTableRTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MessageHashTableRTest.kt index 9f4c683f63..83ac7c65e1 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MessageHashTableRTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MessageHashTableRTest.kt @@ -1,7 +1,7 @@ package info.nightscout.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MessageHashTableR -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito @@ -9,7 +9,7 @@ import org.mockito.Mockito class MessageHashTableRTest : DanaRTestBase() { @Test fun runTest() { - Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val messageHashTable = MessageHashTableR(injector) val testMessage = messageHashTable.findMessage(0x41f2) Assertions.assertEquals("CMD_HISTORY_ALL", testMessage.messageName) diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartTest.kt index da974f3209..daa4a0fb5a 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartTest.kt @@ -1,7 +1,7 @@ package info.nightscout.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MsgBolusStart -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito.`when` @@ -9,7 +9,7 @@ import org.mockito.Mockito.`when` class MsgBolusStartTest : DanaRTestBase() { @Test fun runTest() { - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val packet = MsgBolusStart(injector, 1.0) // test message decoding diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartWithSpeedTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartWithSpeedTest.kt index ff2313a4a5..0493dc8b1e 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartWithSpeedTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgBolusStartWithSpeedTest.kt @@ -1,7 +1,7 @@ package info.nightscout.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MsgBolusStartWithSpeed -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito @@ -9,7 +9,7 @@ import org.mockito.Mockito class MsgBolusStartWithSpeedTest : DanaRTestBase() { @Test fun runTest() { - Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val packet = MsgBolusStartWithSpeed(injector, 0.0, 0) // test message decoding diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgSetExtendedBolusStartTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgSetExtendedBolusStartTest.kt index 2cea8ca437..d881bd911e 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgSetExtendedBolusStartTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaR/comm/MsgSetExtendedBolusStartTest.kt @@ -1,7 +1,7 @@ package info.nightscout.pump.danaR.comm import info.nightscout.androidaps.danar.comm.MsgSetExtendedBolusStart -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.mockito.Mockito.`when` @@ -9,7 +9,7 @@ import org.mockito.Mockito.`when` class MsgSetExtendedBolusStartTest : DanaRTestBase() { @Test fun runTest() { - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val packet = MsgSetExtendedBolusStart(injector, 2.0, 2.toByte()) // test message decoding diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt index 59c583263f..d843b7e67c 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/DanaRKoreanPluginTest.kt @@ -3,9 +3,8 @@ package info.nightscout.pump.danaRKorean import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.pump.PumpSync @@ -22,7 +21,7 @@ import org.mockito.Mockito.`when` class DanaRKoreanPluginTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var pumpSync: PumpSync @Mock lateinit var instantiator: Instantiator @@ -34,7 +33,11 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { private lateinit var danaRPlugin: DanaRKoreanPlugin val injector = HasAndroidInjector { - AndroidInjector { } + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } } @BeforeEach @@ -57,11 +60,11 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHBASALRATE) + val c = ConstraintObject(Double.MAX_VALUE, injector) danaRPlugin.applyBasalConstraints(c, validProfile) Assertions.assertEquals(0.8, c.value(), 0.01) - Assertions.assertEquals("DanaRKorean: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRKorean: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRKorean: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaRKorean: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons()) } @Test @Throws(Exception::class) @@ -69,10 +72,10 @@ class DanaRKoreanPluginTest : TestBaseWithProfile() { danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaRPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) + val c = ConstraintObject(Int.MAX_VALUE, injector) danaRPlugin.applyBasalPercentConstraints(c, validProfile) Assertions.assertEquals(200, c.value()) - Assertions.assertEquals("DanaRKorean: Limiting max percent rate to 200% because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRKorean: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRKorean: Limiting max percent rate to 200% because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaRKorean: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons()) } } \ No newline at end of file diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/comm/MessageHashTableRKoreanTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/comm/MessageHashTableRKoreanTest.kt index 79fca9b748..8b43ed6677 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/comm/MessageHashTableRKoreanTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRKorean/comm/MessageHashTableRKoreanTest.kt @@ -1,7 +1,7 @@ package info.nightscout.pump.danaRKorean.comm import info.nightscout.androidaps.danaRKorean.comm.MessageHashTableRKorean -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.pump.danaR.comm.DanaRTestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test @@ -10,7 +10,7 @@ import org.mockito.Mockito class MessageHashTableRKoreanTest : DanaRTestBase() { @Test fun runTest() { - Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val messageHashTable = MessageHashTableRKorean(injector) val testMessage = messageHashTable.findMessage(0x41f2) Assertions.assertEquals("CMD_HISTORY_ALL", testMessage.messageName) diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt index d19b855b65..a95b45eef0 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/DanaRv2PluginTest.kt @@ -3,9 +3,8 @@ package info.nightscout.pump.danaRv2 import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danaRv2.DanaRv2Plugin -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.pump.DetailedBolusInfoStorage @@ -24,7 +23,7 @@ import org.mockito.Mockito.`when` class DanaRv2PluginTest : TestBaseWithProfile() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -38,7 +37,11 @@ class DanaRv2PluginTest : TestBaseWithProfile() { private lateinit var danaRv2Plugin: DanaRv2Plugin val injector = HasAndroidInjector { - AndroidInjector { } + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } } @BeforeEach @@ -61,11 +64,11 @@ class DanaRv2PluginTest : TestBaseWithProfile() { danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true) danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHBASALRATE) + val c = ConstraintObject(Double.MAX_VALUE, injector) danaRv2Plugin.applyBasalConstraints(c, validProfile) Assertions.assertEquals(0.8, c.value(), 0.01) - Assertions.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaRv2: Limiting max basal rate to 0.80 U/h because of pump limit", c.getMostLimitedReasons()) } @Test @@ -73,10 +76,10 @@ class DanaRv2PluginTest : TestBaseWithProfile() { danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true) danaRv2Plugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) + val c = ConstraintObject(Int.MAX_VALUE, injector) danaRv2Plugin.applyBasalPercentConstraints(c, validProfile) Assertions.assertEquals(200, c.value()) - Assertions.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getReasons()) + Assertions.assertEquals("DanaRv2: Limiting max percent rate to 200% because of pump limit", c.getMostLimitedReasons()) } } \ No newline at end of file diff --git a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/comm/MessageHashTableRv2Test.kt b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/comm/MessageHashTableRv2Test.kt index 178b1488fc..94bfe539a4 100644 --- a/pump/danar/src/test/java/info/nightscout/pump/danaRv2/comm/MessageHashTableRv2Test.kt +++ b/pump/danar/src/test/java/info/nightscout/pump/danaRv2/comm/MessageHashTableRv2Test.kt @@ -3,7 +3,7 @@ package info.nightscout.pump.danaRv2.comm import info.nightscout.androidaps.danaRv2.comm.MessageHashTableRv2 import info.nightscout.androidaps.danaRv2.comm.MsgStatusAPS_v2 import info.nightscout.androidaps.danar.comm.MessageBase -import info.nightscout.interfaces.constraints.Constraint +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.pump.danaR.comm.DanaRTestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test @@ -13,7 +13,7 @@ class MessageHashTableRv2Test : DanaRTestBase() { @Test fun runTest() { - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val messageHashTableRv2 = MessageHashTableRv2(injector) val forTesting: MessageBase = MsgStatusAPS_v2(injector) val testPacket: MessageBase = messageHashTableRv2.findMessage(forTesting.command) diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt index 2374eb15ae..89ce1b2430 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/DanaRSPlugin.kt @@ -8,10 +8,12 @@ import android.os.IBinder import android.text.format.DateFormat import androidx.preference.Preference import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.OwnDatabasePlugin import info.nightscout.interfaces.plugin.PluginDescription @@ -68,7 +70,7 @@ class DanaRSPlugin @Inject constructor( private val rxBus: RxBus, private val context: Context, rh: ResourceHelper, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val profileFunction: ProfileFunction, private val sp: SP, commandQueue: CommandQueue, @@ -92,7 +94,7 @@ class DanaRSPlugin @Inject constructor( .preferencesId(R.xml.pref_danars) .description(info.nightscout.pump.dana.R.string.description_pump_dana_rs), injector, aapsLogger, rh, commandQueue -), Pump, Dana, Constraints, OwnDatabasePlugin { +), Pump, Dana, PluginConstraints, OwnDatabasePlugin { private val disposable = CompositeDisposable() private var danaRSService: DanaRSService? = null @@ -202,18 +204,22 @@ class DanaRSPlugin @Inject constructor( // Constraints interface override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - absoluteRate.setIfSmaller(aapsLogger, danaPump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, danaPump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + absoluteRate.setIfSmaller(danaPump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, danaPump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) return absoluteRate } override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - percentRate.setIfGreater(aapsLogger, 0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) - percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + percentRate.setIfGreater(0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + percentRate.setIfSmaller( + pumpDescription.maxTempPercent, + rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), + this + ) return percentRate } override fun applyBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfSmaller(aapsLogger, danaPump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, danaPump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + insulin.setIfSmaller(danaPump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, danaPump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) return insulin } @@ -282,7 +288,7 @@ class DanaRSPlugin @Inject constructor( @Synchronized override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)).value() return if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { val preferencesSpeed = sp.getInt(info.nightscout.pump.dana.R.string.key_danars_bolusspeed, 0) var speed = 12 @@ -337,7 +343,7 @@ class DanaRSPlugin @Inject constructor( // This is called from APS @Synchronized override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { - val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, injector), profile).value() var doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0 val doLowTemp = absoluteAfterConstrain < baseBasalRate val doHighTemp = absoluteAfterConstrain > baseBasalRate @@ -413,7 +419,7 @@ class DanaRSPlugin @Inject constructor( @Synchronized override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { val result = PumpEnactResult(injector) - var percentAfterConstraint = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value() + var percentAfterConstraint = constraintChecker.applyBasalPercentConstraints(ConstraintObject(percent, injector), profile).value() if (percentAfterConstraint < 0) { result.isTempCancel = false result.enacted = false @@ -483,7 +489,7 @@ class DanaRSPlugin @Inject constructor( @Synchronized override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { - var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(ConstraintObject(insulin, injector)).value() // needs to be rounded val durationInHalfHours = max(durationInMinutes / 30, 1) insulinAfterConstraint = Round.roundTo(insulinAfterConstraint, pumpDescription.extendedBolusStep) diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt index 07c2c171ec..7ded74eea2 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt @@ -2,8 +2,8 @@ package info.nightscout.pump.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.pump.dana.DanaPump import info.nightscout.rx.logging.LTag import javax.inject.Inject @@ -15,13 +15,13 @@ class DanaRSPacketBolusSetStepBolusStart( ) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_STEP_BOLUS_START // Speed 0 => 12 sec/U, 1 => 30 sec/U, 2 => 60 sec/U // HARDCODED LIMIT - if there is one that could be created - amount = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + amount = constraintChecker.applyBolusConstraints(ConstraintObject(amount, injector)).value() aapsLogger.debug(LTag.PUMPCOMM, "Bolus start : $amount speed: $speed") } diff --git a/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt b/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt index a230a49c53..e2e2d8a869 100644 --- a/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt +++ b/pump/danars/src/main/java/info/nightscout/pump/danars/services/DanaRSService.kt @@ -10,7 +10,7 @@ import dagger.android.DaggerService import dagger.android.HasAndroidInjector import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile @@ -103,7 +103,7 @@ class DanaRSService : DaggerService() { @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var danaPump: DanaPump @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var bleComm: BLEComm @Inject lateinit var fabricPrivacy: FabricPrivacy diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt index 958f46f0b4..c2a9d6cc36 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSPluginTest.kt @@ -1,9 +1,8 @@ package info.nightscout.pump.danars import dagger.android.AndroidInjector -import info.nightscout.interfaces.Constants -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.plugin.PluginType import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync @@ -20,7 +19,7 @@ import org.mockito.Mockito @Suppress("SpellCheckingInspection") class DanaRSPluginTest : DanaRSTestBase() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -34,11 +33,11 @@ class DanaRSPluginTest : DanaRSTestBase() { danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHBASALRATE) + val c = ConstraintObject(Double.MAX_VALUE, injector) danaRSPlugin.applyBasalConstraints(c, validProfile) Assertions.assertEquals(java.lang.Double.valueOf(0.8), c.value(), 0.0001) - Assertions.assertEquals("DanaRS: limitingbasalratio", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRS: limitingbasalratio", c.getReasons()) + Assertions.assertEquals("DanaRS: limitingbasalratio", c.getMostLimitedReasons()) } @Test @@ -46,11 +45,11 @@ class DanaRSPluginTest : DanaRSTestBase() { danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaRSPlugin.setPluginEnabled(PluginType.PUMP, true) danaPump.maxBasal = 0.8 - val c = Constraint(Constants.REALLYHIGHPERCENTBASALRATE) + val c = ConstraintObject(Int.MAX_VALUE, injector) danaRSPlugin.applyBasalPercentConstraints(c, validProfile) Assertions.assertEquals(200, c.value()) - Assertions.assertEquals("DanaRS: limitingpercentrate", c.getReasons(aapsLogger)) - Assertions.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons(aapsLogger)) + Assertions.assertEquals("DanaRS: limitingpercentrate", c.getReasons()) + Assertions.assertEquals("DanaRS: limitingpercentrate", c.getMostLimitedReasons()) } @BeforeEach diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt index e64101e1f1..7c56fb2d9c 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/DanaRSTestBase.kt @@ -1,5 +1,8 @@ package info.nightscout.pump.danars +import dagger.android.AndroidInjector +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.dana.DanaPump @@ -17,6 +20,14 @@ open class DanaRSTestBase : TestBaseWithProfile() { lateinit var danaPump: DanaPump + val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } + @BeforeEach fun prepare() { Mockito.`when`(rh.gs(ArgumentMatchers.anyInt())).thenReturn("AnyString") diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsMessageHashTableTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsMessageHashTableTest.kt index 466890cfb9..97a189240c 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsMessageHashTableTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsMessageHashTableTest.kt @@ -3,8 +3,8 @@ package info.nightscout.pump.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.pump.dana.DanaPump import info.nightscout.pump.danars.DanaRSTestBase import org.junit.jupiter.api.Assertions @@ -14,7 +14,7 @@ import org.mockito.Mockito.`when` class DanaRsMessageHashTableTest : DanaRSTestBase() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker private val packetInjector = HasAndroidInjector { AndroidInjector { @@ -36,7 +36,7 @@ class DanaRsMessageHashTableTest : DanaRSTestBase() { @Test fun runTest() { - `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) val danaRSMessageHashTable = DanaRSMessageHashTable(packetInjector) val forTesting: DanaRSPacket = DanaRSPacketAPSSetEventHistory(packetInjector, DanaPump.HistoryEntry.CARBS.value, 0, 0, 0) diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt index b142a13226..27a8dcd7cd 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt @@ -2,8 +2,8 @@ package info.nightscout.pump.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.core.constraints.ConstraintObject +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.TemporaryBasalStorage @@ -18,7 +18,7 @@ import org.mockito.Mockito class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @@ -75,6 +75,6 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { danaHistoryDatabase, decimalFormatter ) - Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) + Mockito.`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(ConstraintObject(0.0, injector)) } } \ No newline at end of file diff --git a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index dc0cdef0e8..08865517af 100644 --- a/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/pump/danars/src/test/java/info/nightscout/pump/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -2,7 +2,7 @@ package info.nightscout.pump.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.pump.DetailedBolusInfoStorage import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.TemporaryBasalStorage @@ -20,7 +20,7 @@ import org.mockito.Mockito.`when` class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { @Mock lateinit var danaHistoryDatabase: DanaHistoryDatabase - @Mock lateinit var constraintChecker: Constraints + @Mock lateinit var constraintChecker: ConstraintsChecker @Mock lateinit var commandQueue: CommandQueue @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage diff --git a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt index caf8c0f2c0..0ed3187bbb 100644 --- a/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt +++ b/pump/diaconn/src/main/java/info/nightscout/pump/diaconn/DiaconnG8Plugin.kt @@ -9,10 +9,12 @@ import android.text.format.DateFormat import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.OwnDatabasePlugin import info.nightscout.interfaces.plugin.PluginDescription @@ -66,7 +68,7 @@ class DiaconnG8Plugin @Inject constructor( private val rxBus: RxBus, private val context: Context, rh: ResourceHelper, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val profileFunction: ProfileFunction, private val sp: SP, commandQueue: CommandQueue, @@ -90,7 +92,7 @@ class DiaconnG8Plugin @Inject constructor( .preferencesId(R.xml.pref_diaconn) .description(R.string.description_pump_diaconn_g8), injector, aapsLogger, rh, commandQueue -), Pump, Diaconn, Constraints, OwnDatabasePlugin { +), Pump, Diaconn, PluginConstraints, OwnDatabasePlugin { private val disposable = CompositeDisposable() private var diaconnG8Service: DiaconnG8Service? = null @@ -185,18 +187,22 @@ class DiaconnG8Plugin @Inject constructor( // Constraints interface override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - absoluteRate.setIfSmaller(aapsLogger, diaconnG8Pump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, diaconnG8Pump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + absoluteRate.setIfSmaller(diaconnG8Pump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.limitingbasalratio, diaconnG8Pump.maxBasal, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) return absoluteRate } override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - percentRate.setIfGreater(aapsLogger, 0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) - percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + percentRate.setIfGreater(0, rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, 0, rh.gs(info.nightscout.core.ui.R.string.itmustbepositivevalue)), this) + percentRate.setIfSmaller( + pumpDescription.maxTempPercent, + rh.gs(info.nightscout.core.ui.R.string.limitingpercentrate, pumpDescription.maxTempPercent, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), + this + ) return percentRate } override fun applyBolusConstraints(insulin: Constraint): Constraint { - insulin.setIfSmaller(aapsLogger, diaconnG8Pump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, diaconnG8Pump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) + insulin.setIfSmaller(diaconnG8Pump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.limitingbolus, diaconnG8Pump.maxBolus, rh.gs(info.nightscout.core.ui.R.string.pumplimit)), this) return insulin } @@ -265,7 +271,7 @@ class DiaconnG8Plugin @Inject constructor( @Synchronized override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)).value() return if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { val carbs = detailedBolusInfo.carbs detailedBolusInfo.carbs = 0.0 @@ -304,7 +310,7 @@ class DiaconnG8Plugin @Inject constructor( @Synchronized override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { val result = PumpEnactResult(injector) - val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val absoluteAfterConstrain = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, injector), profile).value() val doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0 val doLowTemp = absoluteAfterConstrain < baseBasalRate val doHighTemp = absoluteAfterConstrain > baseBasalRate @@ -391,7 +397,7 @@ class DiaconnG8Plugin @Inject constructor( @Synchronized override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { - var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(ConstraintObject(insulin, injector)).value() // needs to be rounded insulinAfterConstraint = Round.roundTo(insulinAfterConstraint, pumpDescription.extendedBolusStep) val result = PumpEnactResult(injector) diff --git a/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicTestBase.kt b/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicTestBase.kt index ced4a4bc8f..f58892816e 100644 --- a/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicTestBase.kt +++ b/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicTestBase.kt @@ -11,8 +11,6 @@ import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.pump.PumpSync import info.nightscout.pump.common.sync.PumpSyncStorage import info.nightscout.pump.core.utils.ByteUtil -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.sharedtests.TestBase @@ -21,7 +19,6 @@ import org.mockito.Mock open class MedtronicTestBase : TestBase() { - var rxBus: RxBus = RxBus(TestAapsSchedulers(), aapsLogger) var byteUtil = ByteUtil() var rileyLinkUtil = RileyLinkUtil() diff --git a/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.kt b/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.kt index 434eb8e8df..dd77853710 100644 --- a/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.kt +++ b/pump/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.kt @@ -14,8 +14,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import info.nightscout.database.impl.serialisation.SealedClassHelper import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.pump.core.utils.ByteUtil -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.bus.RxBus import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mock @@ -37,8 +35,6 @@ import org.mockito.Mock @BeforeEach fun setup() { - rxBus = RxBus(TestAapsSchedulers(), aapsLogger) - medtronicPumpStatus = MedtronicPumpStatus(rh, sp, rxBus, rileyLinkUtil) medtronicUtil = MedtronicUtil(aapsLogger, rxBus, rileyLinkUtil, medtronicPumpStatus, uiInteraction) decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil, byteUtil) diff --git a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt index efcda22669..d4f41f9e74 100644 --- a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt +++ b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/MedtrumPlugin.kt @@ -12,12 +12,12 @@ import androidx.preference.EditTextPreference import androidx.preference.ListPreference import androidx.preference.PreferenceFragmentCompat import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.core.validators.ValidatingEditTextPreference -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType @@ -67,7 +67,7 @@ import kotlin.math.abs aapsLogger: AAPSLogger, rh: ResourceHelper, commandQueue: CommandQueue, - private val constraintChecker: Constraints, + private val constraintChecker: ConstraintsChecker, private val aapsSchedulers: AapsSchedulers, private val rxBus: RxBus, private val context: Context, @@ -348,7 +348,7 @@ import kotlin.math.abs override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { aapsLogger.debug(LTag.PUMP, "deliverTreatment: " + detailedBolusInfo.insulin + "U") if (!isInitialized()) return PumpEnactResult(injector).success(false).enacted(false) - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(ConstraintObject(detailedBolusInfo.insulin, injector)).value() return if (detailedBolusInfo.insulin > 0 && detailedBolusInfo.carbs == 0.0) { aapsLogger.debug(LTag.PUMP, "deliverTreatment: Delivering bolus: " + detailedBolusInfo.insulin + "U") val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB, detailedBolusInfo.id) @@ -388,7 +388,7 @@ import kotlin.math.abs aapsLogger.info(LTag.PUMP, "setTempBasalAbsolute - absoluteRate: $absoluteRate, durationInMinutes: $durationInMinutes, enforceNew: $enforceNew") // round rate to pump rate - val pumpRate = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val pumpRate = constraintChecker.applyBasalConstraints(ConstraintObject(absoluteRate, injector), profile).value() temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil.now(), T.mins(durationInMinutes.toLong()).msecs(), pumpRate, true, tbrType, 0L, 0L)) val connectionOK = medtrumService?.setTempBasal(pumpRate, durationInMinutes) ?: false return if (connectionOK diff --git a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt index a94d4dde69..b5165b47c4 100644 --- a/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt +++ b/pump/medtrum/src/main/java/info/nightscout/pump/medtrum/services/MedtrumService.kt @@ -9,7 +9,7 @@ import android.os.SystemClock import dagger.android.DaggerService import dagger.android.HasAndroidInjector import info.nightscout.core.utils.fabric.FabricPrivacy -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile @@ -86,7 +86,7 @@ class MedtrumService : DaggerService(), BLECommCallback { @Inject lateinit var medtrumPlugin: MedtrumPlugin @Inject lateinit var medtrumPump: MedtrumPump @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var bleComm: BLEComm @Inject lateinit var fabricPrivacy: FabricPrivacy @@ -432,7 +432,7 @@ class MedtrumService : DaggerService(), BLECommCallback { connectionRetryCounter++ } else { communicationLost = true - aapsLogger.warn(LTag.PUMPCOMM, "Retry connection faled, communication stopped") + aapsLogger.warn(LTag.PUMPCOMM, "Retry connection failed, communication stopped") disconnect("Communication stopped") } } else { diff --git a/pump/omnipod-dash/build.gradle b/pump/omnipod-dash/build.gradle index 2021a42fa5..7057f8a12c 100644 --- a/pump/omnipod-dash/build.gradle +++ b/pump/omnipod-dash/build.gradle @@ -41,6 +41,7 @@ dependencies { api "androidx.room:room-rxjava3:$room_version" kapt "androidx.room:room-compiler:$room_version" + androidTestImplementation project(':app-wear-shared:shared-tests') testImplementation project(':app-wear-shared:shared-tests') testImplementation "commons-codec:commons-codec:$commonscodec_version" diff --git a/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt b/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt index 1dfda4ffc1..8c9ea1cd8f 100644 --- a/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt +++ b/pump/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.His import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper import info.nightscout.sharedtests.AAPSLoggerTest import org.junit.Before -import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.runner.RunWith diff --git a/pump/omnipod-eros/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/history/ErosHistoryTest.kt b/pump/omnipod-eros/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/history/ErosHistoryTest.kt index c585f2552e..d8c0da7cae 100644 --- a/pump/omnipod-eros/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/history/ErosHistoryTest.kt +++ b/pump/omnipod-eros/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/history/ErosHistoryTest.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.Ero import org.junit.Assert.assertNotNull import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class ErosHistoryTest { diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt index 9b7bd7e5a3..a4dae6e21f 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt @@ -14,10 +14,9 @@ import info.nightscout.interfaces.queue.CommandQueue import info.nightscout.interfaces.ui.UiInteraction import info.nightscout.interfaces.utils.DecimalFormatter import info.nightscout.pump.common.defs.TempBasalPair -import info.nightscout.rx.TestAapsSchedulers -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.sharedtests.TestBase +import info.nightscout.sharedtests.rx.TestAapsSchedulers import org.joda.time.DateTimeZone import org.joda.time.tz.UTCProvider import org.junit.jupiter.api.Assertions @@ -41,7 +40,6 @@ class OmnipodErosPumpPluginTest : TestBase() { @Mock lateinit var erosHistoryDatabase: ErosHistoryDatabase private lateinit var decimalFormatter: DecimalFormatter - private var rxBusWrapper = RxBus(TestAapsSchedulers(), aapsLogger) @BeforeEach fun prepare() { `when`(rh.gs(ArgumentMatchers.anyInt(), ArgumentMatchers.anyLong())) @@ -54,7 +52,7 @@ class OmnipodErosPumpPluginTest : TestBase() { // mock all the things val plugin = OmnipodErosPumpPlugin( - injector, aapsLogger, TestAapsSchedulers(), rxBusWrapper, null, + injector, aapsLogger, TestAapsSchedulers(), rxBus, null, rh, null, null, aapsOmnipodErosManager, commandQueue, null, null, null, null, rileyLinkUtil, null, null, pumpSync, uiInteraction, erosHistoryDatabase, decimalFormatter diff --git a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt index 9d63fafec5..f798368d1c 100644 --- a/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt +++ b/pump/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManagerTest.kt @@ -2,10 +2,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.manager import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.FirmwareVersion import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus -import info.nightscout.shared.impl.rx.bus.RxBusImpl import info.nightscout.shared.sharedPreferences.SP import info.nightscout.sharedtests.TestBase -import info.nightscout.sharedtests.rx.TestAapsSchedulers import org.joda.time.DateTime import org.joda.time.DateTimeUtils import org.joda.time.DateTimeZone @@ -19,8 +17,6 @@ class AapsErosPodStateManagerTest : TestBase() { @Mock lateinit var sp: SP - private val rxBus = RxBusImpl(TestAapsSchedulers(), aapsLogger) - @Test fun times() { val timeZone = DateTimeZone.UTC DateTimeZone.setDefault(timeZone) diff --git a/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt b/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt index 3c5517200a..fbf9738856 100644 --- a/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt +++ b/pump/pump-common/src/main/java/info/nightscout/pump/common/PumpPluginAbstract.kt @@ -8,7 +8,7 @@ import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.android.HasAndroidInjector import info.nightscout.core.utils.fabric.FabricPrivacy -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.PluginConstraints import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.profile.Profile @@ -63,7 +63,7 @@ abstract class PumpPluginAbstract protected constructor( var pumpSync: PumpSync, var pumpSyncStorage: PumpSyncStorage, var decimalFormatter: DecimalFormatter -) : PumpPluginBase(pluginDescription, injector, aapsLogger, rh, commandQueue), Pump, Constraints, PumpSyncEntriesCreator { +) : PumpPluginBase(pluginDescription, injector, aapsLogger, rh, commandQueue), Pump, PluginConstraints, PumpSyncEntriesCreator { protected val disposable = CompositeDisposable() diff --git a/pump/virtual/src/test/java/info/nightscout/pump/virtual/VirtualPumpPluginUTest.kt b/pump/virtual/src/test/java/info/nightscout/pump/virtual/VirtualPumpPluginUTest.kt index e9c2922e52..87722bf9b4 100644 --- a/pump/virtual/src/test/java/info/nightscout/pump/virtual/VirtualPumpPluginUTest.kt +++ b/pump/virtual/src/test/java/info/nightscout/pump/virtual/VirtualPumpPluginUTest.kt @@ -9,7 +9,6 @@ import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.PumpSync import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.CommandQueue -import info.nightscout.rx.bus.RxBus import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.utils.DateUtil @@ -22,7 +21,6 @@ import org.mockito.Mockito.`when` class VirtualPumpPluginUTest : TestBase() { - private val rxBus = RxBus(aapsSchedulers, aapsLogger) @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var rh: ResourceHelper @Mock lateinit var sp: SP diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt index 927733e1e7..8095e08415 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/CarbsDialog.kt @@ -8,6 +8,8 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper @@ -23,8 +25,7 @@ import info.nightscout.interfaces.Constants.CARBS_FAV2_DEFAULT import info.nightscout.interfaces.Constants.CARBS_FAV3_DEFAULT import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.automation.Automation -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger @@ -54,7 +55,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var ctx: Context @Inject lateinit var rh: ResourceHelper - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileUtil: ProfileUtil @Inject lateinit var iobCobCalculator: IobCobCalculator @@ -66,6 +67,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var decimalFormatter: DecimalFormatter + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private val disposable = CompositeDisposable() @@ -225,7 +227,7 @@ class CarbsDialog : DialogFragmentWithDate() { override fun submit(): Boolean { if (_binding == null) return false val carbs = binding.carbs.value.toInt() - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(carbs, injector)).value() val units = profileUtil.units val activityTTDuration = defaultValueHelper.determineActivityTTDuration() val activityTT = defaultValueHelper.determineActivityTT() diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/ExtendedBolusDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/ExtendedBolusDialog.kt index 10f02b2f0f..49ecf11135 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/ExtendedBolusDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/ExtendedBolusDialog.kt @@ -6,14 +6,15 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper import info.nightscout.core.utils.extensions.formatColor import info.nightscout.database.entities.UserEntry import info.nightscout.database.entities.ValueWithUnit -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.protection.ProtectionCheck @@ -34,12 +35,13 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { @Inject lateinit var ctx: Context @Inject lateinit var rh: ResourceHelper - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var uel: UserEntryLogger @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private var _binding: DialogExtendedbolusBinding? = null @@ -94,7 +96,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(binding.insulin.text) val durationInMinutes = binding.duration.value.toInt() val actions: LinkedList = LinkedList() - val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(ConstraintObject(insulin, injector)).value() actions.add(rh.gs(info.nightscout.core.ui.R.string.format_insulin_units, insulinAfterConstraint)) actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_mins, durationInMinutes)) if (abs(insulinAfterConstraint - insulin) > 0.01) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt index 2b1084f47b..7f149d45d6 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/FillDialog.kt @@ -6,6 +6,8 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper @@ -15,8 +17,7 @@ import info.nightscout.database.entities.UserEntry import info.nightscout.database.entities.ValueWithUnit import info.nightscout.database.impl.AppRepository import info.nightscout.database.impl.transactions.InsertIfNewByTimestampTherapyEventTransaction -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.protection.ProtectionCheck @@ -38,7 +39,7 @@ import kotlin.math.abs class FillDialog : DialogFragmentWithDate() { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var rh: ResourceHelper @Inject lateinit var ctx: Context @Inject lateinit var commandQueue: CommandQueue @@ -48,6 +49,7 @@ class FillDialog : DialogFragmentWithDate() { @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var decimalFormatter: DecimalFormatter + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private val disposable = CompositeDisposable() @@ -116,7 +118,7 @@ class FillDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(binding.fillInsulinAmount.text) val actions: LinkedList = LinkedList() - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(insulin, injector)).value() if (insulinAfterConstraints > 0) { actions.add(rh.gs(R.string.fill_warning)) actions.add("") diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt index c741980f7c..9602f779c1 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/InsulinDialog.kt @@ -8,6 +8,8 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper @@ -23,8 +25,7 @@ import info.nightscout.interfaces.Constants.INSULIN_PLUS2_DEFAULT import info.nightscout.interfaces.Constants.INSULIN_PLUS3_DEFAULT import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.automation.Automation -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin @@ -56,7 +57,7 @@ import kotlin.math.max class InsulinDialog : DialogFragmentWithDate() { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var rh: ResourceHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var profileFunction: ProfileFunction @@ -72,6 +73,7 @@ class InsulinDialog : DialogFragmentWithDate() { @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var persistenceLayer: PersistenceLayer @Inject lateinit var decimalFormatter: DecimalFormatter + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private val disposable = CompositeDisposable() @@ -189,7 +191,7 @@ class InsulinDialog : DialogFragmentWithDate() { if (_binding == null) return false val pumpDescription = activePlugin.activePump.pumpDescription val insulin = SafeParse.stringToDouble(binding.amount.text) - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(insulin, injector)).value() val actions: LinkedList = LinkedList() val units = profileFunction.getUnits() val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(info.nightscout.core.ui.R.string.mmol) else rh.gs(info.nightscout.core.ui.R.string.mgdl) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt index e668f6bee8..eb9ed9bbee 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt @@ -10,7 +10,9 @@ import android.view.ViewGroup import android.view.Window import android.view.WindowManager import androidx.fragment.app.FragmentManager +import dagger.android.HasAndroidInjector import dagger.android.support.DaggerDialogFragment +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.fabric.FabricPrivacy @@ -20,11 +22,10 @@ import info.nightscout.database.entities.ValueWithUnit import info.nightscout.database.impl.AppRepository import info.nightscout.database.impl.transactions.CancelCurrentOfflineEventIfAnyTransaction import info.nightscout.database.impl.transactions.InsertAndCancelCurrentOfflineEventTransaction -import info.nightscout.interfaces.ConfigBuilder import info.nightscout.interfaces.ApsMode +import info.nightscout.interfaces.ConfigBuilder import info.nightscout.interfaces.aps.Loop -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.constraints.Objectives import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin @@ -64,7 +65,7 @@ class LoopDialog : DaggerDialogFragment() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var loop: Loop @Inject lateinit var activePlugin: ActivePlugin - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var configBuilder: ConfigBuilder @Inject lateinit var uel: UserEntryLogger @@ -72,6 +73,7 @@ class LoopDialog : DaggerDialogFragment() { @Inject lateinit var repository: AppRepository @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private var showOkCancel: Boolean = true @@ -152,16 +154,14 @@ class LoopDialog : DaggerDialogFragment() { disposable.clear() } - var task: Runnable? = null - @Synchronized fun updateGUI(from: String) { if (_binding == null) return aapsLogger.debug("UpdateGUI from $from") val pumpDescription: PumpDescription = activePlugin.activePump.pumpDescription - val closedLoopAllowed = constraintChecker.isClosedLoopAllowed(Constraint(true)) + val closedLoopAllowed = constraintChecker.isClosedLoopAllowed(ConstraintObject(true, injector)) val closedLoopAllowed2 = activePlugin.activeObjectives?.isAccomplished(Objectives.MAXIOB_OBJECTIVE) ?: false - val lgsEnabled = constraintChecker.isLgsAllowed(Constraint(true)) + val lgsEnabled = constraintChecker.isLgsAllowed(ConstraintObject(true, injector)) val apsMode = ApsMode.fromString(sp.getString(info.nightscout.core.utils.R.string.key_aps_mode, ApsMode.OPEN.name)) val pump = activePlugin.activePump @@ -279,7 +279,7 @@ class LoopDialog : DaggerDialogFragment() { return true } - fun onClick(v: View): Boolean { + private fun onClick(v: View): Boolean { when (v.id) { R.id.overview_closeloop -> { uel.log(UserEntry.Action.CLOSED_LOOP_MODE, UserEntry.Sources.LoopDialog) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/TempBasalDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/TempBasalDialog.kt index 730af01f57..4cf3cf85d8 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/TempBasalDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/TempBasalDialog.kt @@ -6,14 +6,15 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper import info.nightscout.core.utils.extensions.formatColor import info.nightscout.database.entities.UserEntry import info.nightscout.database.entities.ValueWithUnit -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.ProfileFunction @@ -35,7 +36,7 @@ import kotlin.math.abs class TempBasalDialog : DialogFragmentWithDate() { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin @@ -44,6 +45,7 @@ class TempBasalDialog : DialogFragmentWithDate() { @Inject lateinit var uel: UserEntryLogger @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var uiInteraction: UiInteraction + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false private var isPercentPump = true @@ -118,13 +120,13 @@ class TempBasalDialog : DialogFragmentWithDate() { val actions: LinkedList = LinkedList() if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(binding.basalPercentInput.text) - percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() + percent = constraintChecker.applyBasalPercentConstraints(ConstraintObject(basalPercentInput, injector), profile).value() actions.add(rh.gs(info.nightscout.core.ui.R.string.tempbasal_label) + ": $percent%") actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_mins, durationInMinutes)) if (percent != basalPercentInput) actions.add(rh.gs(info.nightscout.core.ui.R.string.constraint_applied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(binding.basalAbsoluteInput.text) - absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() + absolute = constraintChecker.applyBasalConstraints(ConstraintObject(basalAbsoluteInput, injector), profile).value() actions.add(rh.gs(info.nightscout.core.ui.R.string.tempbasal_label) + ": " + rh.gs(info.nightscout.core.ui.R.string.pump_base_basal_rate, absolute)) actions.add(rh.gs(info.nightscout.core.ui.R.string.duration) + ": " + rh.gs(info.nightscout.core.ui.R.string.format_mins, durationInMinutes)) if (abs(absolute - basalAbsoluteInput) > 0.01) diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt index 7e08d66765..8fe66ed052 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/TempTargetDialog.kt @@ -20,7 +20,7 @@ import info.nightscout.database.impl.transactions.CancelCurrentTemporaryTargetIf import info.nightscout.database.impl.transactions.InsertAndCancelCurrentTemporaryTargetTransaction import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.profile.DefaultValueHelper import info.nightscout.interfaces.profile.ProfileFunction @@ -39,7 +39,7 @@ import javax.inject.Inject class TempTargetDialog : DialogFragmentWithDate() { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileUtil: ProfileUtil diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt index 25e2905bf4..02099655ce 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/TreatmentDialog.kt @@ -8,6 +8,8 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import dagger.android.HasAndroidInjector +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.toast.ToastUtils import info.nightscout.core.utils.HtmlHelper @@ -16,8 +18,7 @@ import info.nightscout.database.entities.UserEntry import info.nightscout.database.entities.ValueWithUnit import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.Config -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin @@ -32,7 +33,6 @@ import info.nightscout.shared.SafeParse import info.nightscout.shared.interfaces.ResourceHelper import info.nightscout.ui.R import info.nightscout.ui.databinding.DialogTreatmentBinding -import io.reactivex.rxjava3.disposables.CompositeDisposable import java.text.DecimalFormat import java.util.LinkedList import javax.inject.Inject @@ -40,7 +40,7 @@ import kotlin.math.abs class TreatmentDialog : DialogFragmentWithDate() { - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var rh: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var commandQueue: CommandQueue @@ -52,9 +52,9 @@ class TreatmentDialog : DialogFragmentWithDate() { @Inject lateinit var uiInteraction: UiInteraction @Inject lateinit var persistenceLayer: PersistenceLayer @Inject lateinit var decimalFormatter: DecimalFormatter + @Inject lateinit var injector: HasAndroidInjector private var queryingProtection = false - private val disposable = CompositeDisposable() private var _binding: DialogTreatmentBinding? = null // This property is only valid between onCreateView and onDestroyView. @@ -138,8 +138,8 @@ class TreatmentDialog : DialogFragmentWithDate() { val carbs = SafeParse.stringToInt(binding.carbs.text) val recordOnlyChecked = binding.recordOnly.isChecked val actions: LinkedList = LinkedList() - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(ConstraintObject(insulin, injector)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(ConstraintObject(carbs, injector)).value() if (insulinAfterConstraints > 0) { actions.add( diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt index 690e6080a1..3b8dd042bf 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt @@ -18,6 +18,7 @@ import android.widget.CompoundButton import androidx.fragment.app.FragmentManager import dagger.android.HasAndroidInjector import dagger.android.support.DaggerDialogFragment +import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.extensions.valueToUnits import info.nightscout.core.iob.round import info.nightscout.core.profile.ProfileSealed @@ -30,8 +31,7 @@ import info.nightscout.database.ValueWrapper import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit -import info.nightscout.interfaces.constraints.Constraint -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.profile.Profile @@ -65,7 +65,7 @@ class WizardDialog : DaggerDialogFragment() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var ctx: Context @Inject lateinit var sp: SP @Inject lateinit var rxBus: RxBus @@ -444,7 +444,7 @@ class WizardDialog : DaggerDialogFragment() { SafeParse.stringToDouble(binding.correctionInput.text) } else sp.getInt(info.nightscout.core.utils.R.string.key_boluswizard_percentage, 100).toDouble() - val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(ConstraintObject(carbs, injector)).value() if (abs(carbs - carbsAfterConstraint) > 0.01) { binding.carbsInput.value = 0.0 ToastUtils.warnToast(ctx, R.string.carbs_constraint_applied) diff --git a/ui/src/main/java/info/nightscout/ui/widget/Widget.kt b/ui/src/main/java/info/nightscout/ui/widget/Widget.kt index beaadb4a0a..972fe0c565 100644 --- a/ui/src/main/java/info/nightscout/ui/widget/Widget.kt +++ b/ui/src/main/java/info/nightscout/ui/widget/Widget.kt @@ -22,7 +22,7 @@ import info.nightscout.interfaces.Config import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.aps.Loop import info.nightscout.interfaces.aps.VariableSensitivityResult -import info.nightscout.interfaces.constraints.Constraints +import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.plugin.ActivePlugin @@ -62,10 +62,11 @@ class Widget : AppWidgetProvider() { @Inject lateinit var loop: Loop @Inject lateinit var config: Config @Inject lateinit var sp: SP - @Inject lateinit var constraintChecker: Constraints + @Inject lateinit var constraintChecker: ConstraintsChecker @Inject lateinit var decimalFormatter: DecimalFormatter companion object { + // This object doesn't behave like singleton, // many threads were created. Making handler static resolve this issue private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) @@ -78,6 +79,7 @@ class Widget : AppWidgetProvider() { }) } } + private val intentAction = "OpenApp" override fun onReceive(context: Context, intent: Intent?) { @@ -133,9 +135,9 @@ class Widget : AppWidgetProvider() { overviewData.lastBg(iobCobCalculator.ads)?.let { profileUtil.fromMgdlToStringInUnits(it.value) } ?: rh.gs(info.nightscout.core.ui.R.string.value_unavailable_short)) views.setTextColor( R.id.bg, when { - overviewData.isLow(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_low) + overviewData.isLow(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_low) overviewData.isHigh(iobCobCalculator.ads) -> rh.gc(info.nightscout.core.ui.R.color.widget_high) - else -> rh.gc(info.nightscout.core.ui.R.color.widget_inrange) + else -> rh.gc(info.nightscout.core.ui.R.color.widget_inrange) } ) trendCalculator.getTrendArrow(iobCobCalculator.ads)?.let { From 1ff6aa7bbf5abae17df4355cef2e8e403f5477db Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 19 Sep 2023 14:36:36 +0200 Subject: [PATCH 6/9] cleanup --- app/src/main/java/info/nightscout/androidaps/MainActivity.kt | 3 +-- .../src/main/java/info/nightscout/interfaces/iob/CobInfo.kt | 2 +- .../interfaces/notifications/NotificationUserMessage.kt | 2 +- .../nightscout/interfaces/smsCommunicator/SmsCommunicator.kt | 1 + .../src/main/java/info/nightscout/core/wizard/BolusWizard.kt | 3 +-- .../main/java/info/nightscout/core/wizard/QuickWizardEntry.kt | 3 +-- .../implementation/queue/commands/CommandSetProfile.kt | 3 +-- .../info/nightscout/automation/actions/ActionLoopDisable.kt | 2 +- .../info/nightscout/automation/actions/ActionLoopEnable.kt | 2 +- .../info/nightscout/configuration/AndroidPermissionImpl.kt | 3 +-- .../activities/DaggerAppCompatActivityWithResult.kt | 1 - .../activities}/OptimizationPermissionContract.kt | 2 +- .../plugins/general/wear/wearintegration/DataHandlerMobile.kt | 4 ++-- ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt | 2 +- 14 files changed, 14 insertions(+), 19 deletions(-) rename {core/interfaces/src/main/java/info/nightscout/interfaces/permissions => plugins/configuration/src/main/java/info/nightscout/configuration/activities}/OptimizationPermissionContract.kt (92%) diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index ffc876d687..468547aa58 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -56,7 +56,6 @@ import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.maintenance.PrefFileListProvider import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.protection.ProtectionCheck import info.nightscout.interfaces.smsCommunicator.SmsCommunicator @@ -283,7 +282,7 @@ class MainActivity : DaggerAppCompatActivityWithResult() { private fun start() { binding.splash.visibility = View.GONE //Check here if loop plugin is disabled. Else check via constraints - if (!(loop as PluginBase).isEnabled()) versionCheckerUtils.triggerCheckVersion() + if (!loop.isEnabled()) versionCheckerUtils.triggerCheckVersion() setUserStats() setupViews() diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/iob/CobInfo.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/iob/CobInfo.kt index 35c70f8d5f..4a52fefcec 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/iob/CobInfo.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/iob/CobInfo.kt @@ -1,4 +1,4 @@ package info.nightscout.interfaces.iob /** All COB up to now, including carbs not yet processed by IobCob calculation. */ -class CobInfo(val timestamp: Long, val displayCob: Double?, val futureCarbs: Double) \ No newline at end of file +data class CobInfo(val timestamp: Long, val displayCob: Double?, val futureCarbs: Double) \ No newline at end of file diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/notifications/NotificationUserMessage.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/notifications/NotificationUserMessage.kt index be39876b5a..3eb2d74945 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/notifications/NotificationUserMessage.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/notifications/NotificationUserMessage.kt @@ -1,6 +1,6 @@ package info.nightscout.interfaces.notifications -class NotificationUserMessage (text :String): Notification() { +class NotificationUserMessage(text: String) : Notification() { init { var hash = text.hashCode() diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/smsCommunicator/SmsCommunicator.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/smsCommunicator/SmsCommunicator.kt index a699169598..ae5484cf6d 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/smsCommunicator/SmsCommunicator.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/smsCommunicator/SmsCommunicator.kt @@ -5,4 +5,5 @@ interface SmsCommunicator { var messages: ArrayList fun sendNotificationToAllNumbers(text: String): Boolean fun sendSMS(sms: Sms): Boolean + fun isEnabled(): Boolean } \ No newline at end of file diff --git a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt index f623f9681e..4bba468c45 100644 --- a/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt +++ b/core/main/src/main/java/info/nightscout/core/wizard/BolusWizard.kt @@ -27,7 +27,6 @@ import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.IobCobCalculator import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.interfaces.pump.DetailedBolusInfo @@ -455,7 +454,7 @@ class BolusWizard @Inject constructor( if (insulinAfterConstraints > 0 || carbs > 0) { if (useSuperBolus) { uel.log(Action.SUPERBOLUS_TBR, Sources.WizardDialog) - if ((loop as PluginBase).isEnabled()) { + if (loop.isEnabled()) { loop.goToZeroTemp(2 * 60, profile, OfflineEvent.Reason.SUPER_BOLUS) rxBus.send(EventRefreshOverview("WizardDialog")) } diff --git a/core/main/src/main/java/info/nightscout/core/wizard/QuickWizardEntry.kt b/core/main/src/main/java/info/nightscout/core/wizard/QuickWizardEntry.kt index eeb936de5d..ff0d7ff78f 100644 --- a/core/main/src/main/java/info/nightscout/core/wizard/QuickWizardEntry.kt +++ b/core/main/src/main/java/info/nightscout/core/wizard/QuickWizardEntry.kt @@ -13,7 +13,6 @@ import info.nightscout.interfaces.db.PersistenceLayer import info.nightscout.interfaces.iob.GlucoseStatusProvider import info.nightscout.interfaces.iob.InMemoryGlucoseValue import info.nightscout.interfaces.iob.IobCobCalculator -import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileFunction import info.nightscout.rx.logging.AAPSLogger @@ -141,7 +140,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec if (useSuperBolus() == YES && sp.getBoolean(info.nightscout.core.utils.R.string.key_usesuperbolus, false)) { superBolus = true } - if ((loop as PluginBase).isEnabled() && loop.isSuperBolus) superBolus = false + if (loop.isEnabled() && loop.isSuperBolus) superBolus = false // Trend val glucoseStatus = glucoseStatusProvider.glucoseStatusData var trend = false diff --git a/implementation/src/main/java/info/nightscout/implementation/queue/commands/CommandSetProfile.kt b/implementation/src/main/java/info/nightscout/implementation/queue/commands/CommandSetProfile.kt index 1167b0a127..eae3887c20 100644 --- a/implementation/src/main/java/info/nightscout/implementation/queue/commands/CommandSetProfile.kt +++ b/implementation/src/main/java/info/nightscout/implementation/queue/commands/CommandSetProfile.kt @@ -5,7 +5,6 @@ import info.nightscout.database.ValueWrapper import info.nightscout.database.impl.AppRepository import info.nightscout.interfaces.Config import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.pump.PumpEnactResult import info.nightscout.interfaces.queue.Callback @@ -42,7 +41,7 @@ class CommandSetProfile constructor( // Send SMS notification if ProfileSwitch is coming from NS val profileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() if (profileSwitch is ValueWrapper.Existing && r.enacted && hasNsId && !config.NSCLIENT) { - if ((smsCommunicator as PluginBase).isEnabled()) + if (smsCommunicator.isEnabled()) smsCommunicator.sendNotificationToAllNumbers(rh.gs(info.nightscout.core.ui.R.string.profile_set_ok)) } } diff --git a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopDisable.kt b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopDisable.kt index d39ff2f888..ee6301043d 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopDisable.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopDisable.kt @@ -30,7 +30,7 @@ class ActionLoopDisable(injector: HasAndroidInjector) : Action(injector) { @DrawableRes override fun icon(): Int = R.drawable.ic_stop_24dp override fun doAction(callback: Callback) { - if ((loopPlugin as PluginBase).isEnabled()) { + if (loopPlugin.isEnabled()) { (loopPlugin as PluginBase).setPluginEnabled(PluginType.LOOP, false) configBuilder.storeSettings("ActionLoopDisable") uel.log(UserEntry.Action.LOOP_DISABLED, Sources.Automation, title) diff --git a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopEnable.kt b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopEnable.kt index 5caad06cad..30617bdd49 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopEnable.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionLoopEnable.kt @@ -28,7 +28,7 @@ class ActionLoopEnable(injector: HasAndroidInjector) : Action(injector) { @DrawableRes override fun icon(): Int = R.drawable.ic_play_circle_outline_24dp override fun doAction(callback: Callback) { - if (!(loopPlugin as PluginBase).isEnabled()) { + if (!loopPlugin.isEnabled()) { (loopPlugin as PluginBase).setPluginEnabled(PluginType.LOOP, true) configBuilder.storeSettings("ActionLoopEnable") rxBus.send(EventRefreshOverview("ActionLoopEnable")) diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/AndroidPermissionImpl.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/AndroidPermissionImpl.kt index d6113c01d8..6e2c57c310 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/AndroidPermissionImpl.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/AndroidPermissionImpl.kt @@ -20,7 +20,6 @@ import info.nightscout.interfaces.AndroidPermission import info.nightscout.interfaces.Config import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.plugin.ActivePlugin -import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.smsCommunicator.SmsCommunicator import info.nightscout.shared.interfaces.ResourceHelper import javax.inject.Inject @@ -86,7 +85,7 @@ class AndroidPermissionImpl @Inject constructor( @Synchronized override fun notifyForSMSPermissions(activity: FragmentActivity, smsCommunicator: SmsCommunicator) { - if ((smsCommunicator as PluginBase).isEnabled()) { + if (smsCommunicator.isEnabled()) { if (permissionNotGranted(activity, Manifest.permission.RECEIVE_SMS)) activePlugin.activeOverview.addNotification( id = Notification.PERMISSION_SMS, diff --git a/plugins/configuration/src/main/java/info/nightscout/configuration/activities/DaggerAppCompatActivityWithResult.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/activities/DaggerAppCompatActivityWithResult.kt index febf53fe67..f13e61ffe9 100644 --- a/plugins/configuration/src/main/java/info/nightscout/configuration/activities/DaggerAppCompatActivityWithResult.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/activities/DaggerAppCompatActivityWithResult.kt @@ -13,7 +13,6 @@ import info.nightscout.configuration.maintenance.PrefsFileContract import info.nightscout.core.ui.dialogs.OKDialog import info.nightscout.core.ui.locale.LocaleHelper import info.nightscout.interfaces.maintenance.ImportExportPrefs -import info.nightscout.interfaces.permissions.OptimizationPermissionContract import info.nightscout.rx.bus.RxBus import info.nightscout.rx.events.EventThemeSwitch import info.nightscout.rx.logging.AAPSLogger diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/permissions/OptimizationPermissionContract.kt b/plugins/configuration/src/main/java/info/nightscout/configuration/activities/OptimizationPermissionContract.kt similarity index 92% rename from core/interfaces/src/main/java/info/nightscout/interfaces/permissions/OptimizationPermissionContract.kt rename to plugins/configuration/src/main/java/info/nightscout/configuration/activities/OptimizationPermissionContract.kt index c28d65c84f..b68ebc579d 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/permissions/OptimizationPermissionContract.kt +++ b/plugins/configuration/src/main/java/info/nightscout/configuration/activities/OptimizationPermissionContract.kt @@ -1,4 +1,4 @@ -package info.nightscout.interfaces.permissions +package info.nightscout.configuration.activities import android.content.Context import android.content.Intent diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt index 55b368a20f..953b7c3f42 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -1038,7 +1038,7 @@ class DataHandlerMobile @Inject constructor( get() { var ret = "" // decide if enabled/disabled closed/open; what Plugin as APS? - if ((loop as PluginBase).isEnabled()) { + if (loop.isEnabled()) { ret += if (constraintChecker.isClosedLoopAllowed().value()) { rh.gs(R.string.loop_status_closed) + "\n" } else { @@ -1137,7 +1137,7 @@ class DataHandlerMobile @Inject constructor( private fun generateStatusString(profile: Profile?): String { var status = "" profile ?: return rh.gs(info.nightscout.core.ui.R.string.noprofile) - if (!(loop as PluginBase).isEnabled()) status += rh.gs(R.string.disabled_loop) + "\n" + if (!loop.isEnabled()) status += rh.gs(R.string.disabled_loop) + "\n" return status } diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt index eb9ed9bbee..00577a4b11 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/LoopDialog.kt @@ -189,7 +189,7 @@ class LoopDialog : DaggerDialogFragment() { binding.overviewReconnect.visibility = View.VISIBLE } - !(loop as PluginBase).isEnabled() -> { + !loop.isEnabled() -> { binding.overviewLoop.visibility = View.VISIBLE binding.overviewEnable.visibility = View.VISIBLE binding.overviewDisable.visibility = View.GONE From 5f92f29f414feaa2428cc874877cbff1f57eacba Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 19 Sep 2023 14:45:27 +0200 Subject: [PATCH 7/9] fix tests --- .../plugins/aps/loop/APSResultTest.kt | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt b/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt index 3f926606f6..43e34c3038 100644 --- a/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt +++ b/plugins/aps/src/test/java/info/nightscout/plugins/aps/loop/APSResultTest.kt @@ -6,8 +6,10 @@ import info.nightscout.core.constraints.ConstraintObject import info.nightscout.core.utils.JsonHelper.safeGetDouble import info.nightscout.database.entities.TemporaryBasal import info.nightscout.interfaces.aps.APSResult +import info.nightscout.interfaces.constraints.Constraint import info.nightscout.interfaces.constraints.ConstraintsChecker import info.nightscout.interfaces.pump.defs.PumpType +import info.nightscout.plugins.aps.APSResultObject import info.nightscout.sharedtests.TestBaseWithProfile import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach @@ -20,9 +22,15 @@ class APSResultTest : TestBaseWithProfile() { @Mock lateinit var constraintsChecker: ConstraintsChecker - private val injector = HasAndroidInjector { AndroidInjector { } } + private val injector = HasAndroidInjector { + AndroidInjector { + if (it is ConstraintObject<*>) { + it.aapsLogger = aapsLogger + } + } + } - private var closedLoopEnabled = ConstraintObject(false, injector) + private lateinit var closedLoopEnabled: Constraint private fun APSResult.percent(percent: Int): APSResult { this.percent = percent @@ -52,7 +60,7 @@ class APSResultTest : TestBaseWithProfile() { @Test fun changeRequestedTest() { - val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } + val apsResult = APSResultObject { AndroidInjector { } } .also { it.aapsLogger = aapsLogger it.constraintChecker = constraintsChecker @@ -293,7 +301,7 @@ class APSResultTest : TestBaseWithProfile() { } @Test fun cloneTest() { - val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } + val apsResult = APSResultObject(injector) .also { it.aapsLogger = aapsLogger it.constraintChecker = constraintsChecker @@ -310,7 +318,7 @@ class APSResultTest : TestBaseWithProfile() { @Test fun jsonTest() { closedLoopEnabled.set(true) - val apsResult = info.nightscout.plugins.aps.APSResultObject { AndroidInjector { } } + val apsResult = APSResultObject(injector) .also { it.aapsLogger = aapsLogger it.constraintChecker = constraintsChecker @@ -328,7 +336,8 @@ class APSResultTest : TestBaseWithProfile() { @BeforeEach fun prepare() { - `when`(constraintsChecker.isClosedLoopAllowed(anyObject())).thenReturn(closedLoopEnabled) + closedLoopEnabled = ConstraintObject(false, injector) + `when`(constraintsChecker.isClosedLoopAllowed()).thenReturn(closedLoopEnabled) `when`(sp.getDouble(ArgumentMatchers.anyInt(), ArgumentMatchers.anyDouble())).thenReturn(30.0) `when`(profileFunction.getProfile()).thenReturn(validProfile) } From fd82ef371b65ee0eb9db08078bd87f0226c6c168 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 19 Sep 2023 16:30:40 +0200 Subject: [PATCH 8/9] optimize mgdl/mmol constants --- .../java/info/nightscout/androidaps/RealPumpTest.kt | 2 +- .../info/nightscout/androidaps/SetupWizardActivityTest.kt | 2 +- .../src/main/java/info/nightscout/interfaces/Constants.kt | 2 -- .../interfaces/userEntry/ValueWithUnitMapper.kt | 8 +++----- .../implementation/profile/ProfileFunctionImpl.kt | 3 +-- .../automation/actions/ActionStartTempTarget.kt | 2 +- .../java/info/nightscout/automation/triggers/TriggerBg.kt | 3 +-- .../info/nightscout/automation/triggers/TriggerDelta.kt | 2 +- .../automation/triggers/TriggerTempTargetValue.kt | 2 +- .../general/wear/wearintegration/DataHandlerMobile.kt | 2 +- .../info/nightscout/plugins/profile/ProfileFragment.kt | 4 ++-- .../java/info/nightscout/plugins/profile/ProfilePlugin.kt | 4 ++-- .../src/main/java/info/nightscout/source/PoctechPlugin.kt | 3 ++- .../plugins/sync/nsShared/StoreDataForDbImpl.kt | 5 +++-- .../sync/nsclient/extensions/TemporaryTargetExtension.kt | 2 +- .../sync/nsclient/extensions/TherapyEventExtension.kt | 4 ++-- .../src/main/java/info/nightscout/pump/dana/DanaPump.kt | 5 +++-- .../pump/dana/activities/DanaUserOptionsActivity.kt | 3 ++- .../java/info/nightscout/pump/common/data/PumpStatus.kt | 2 +- .../main/java/info/nightscout/ui/dialogs/WizardDialog.kt | 2 +- 20 files changed, 30 insertions(+), 32 deletions(-) diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index c248fcbfb3..24135997a4 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -52,7 +52,7 @@ class RealPumpTest { configBuilderPlugin.performPluginSwitch(randomBgPlugin,true, PluginType.BGSOURCE) // Profile configBuilderPlugin.performPluginSwitch(localProfilePlugin, true, PluginType.PROFILE) - val profile = Profile(JSONObject(validProfile), Constants.MGDL) + val profile = Profile(JSONObject(validProfile), GlucoseUnit.MGDL.asText) Assert.assertTrue(profile.isValid("Test")) localProfilePlugin.profiles.clear() localProfilePlugin.numOfProfiles = 0 diff --git a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt index d5efa1841c..933c6c2936 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/SetupWizardActivityTest.kt @@ -154,7 +154,7 @@ class SetupWizardActivityTest { onView(withId(R.id.finish_button)).waitAndPerform(click()) // Verify settings - Assert.assertEquals(Constants.MMOL, ProfileFunctions.getSystemUnits()) + Assert.assertEquals(GlucoseUnit.MMOL.asText, ProfileFunctions.getSystemUnits()) Assert.assertEquals(17.0, HardLimits.maxBolus(), 0.0001) // Adult Assert.assertTrue(RandomBgPlugin.isEnabled(PluginType.BGSOURCE)) Assert.assertTrue(LocalProfilePlugin.isEnabled(PluginType.PROFILE)) diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt index e0c3bacd59..bd006368ed 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/Constants.kt @@ -5,8 +5,6 @@ package info.nightscout.interfaces */ object Constants { - const val MGDL = "mg/dl" // This is Nightscout's representation - const val MMOL = "mmol" const val MMOLL_TO_MGDL = 18.0 // 18.0182; const val MGDL_TO_MMOLL = 1 / MMOLL_TO_MGDL const val defaultDIA = 5.0 diff --git a/core/interfaces/src/main/java/info/nightscout/interfaces/userEntry/ValueWithUnitMapper.kt b/core/interfaces/src/main/java/info/nightscout/interfaces/userEntry/ValueWithUnitMapper.kt index 0261306094..964c59e550 100644 --- a/core/interfaces/src/main/java/info/nightscout/interfaces/userEntry/ValueWithUnitMapper.kt +++ b/core/interfaces/src/main/java/info/nightscout/interfaces/userEntry/ValueWithUnitMapper.kt @@ -4,6 +4,7 @@ import info.nightscout.database.entities.TemporaryTarget import info.nightscout.database.entities.TherapyEvent import info.nightscout.database.entities.ValueWithUnit import info.nightscout.interfaces.Constants +import info.nightscout.interfaces.GlucoseUnit sealed class ValueWithUnitMapper { //I use a sealed class because of StringResource that contains a listOf as second parameter @@ -79,12 +80,9 @@ sealed class ValueWithUnitMapper { //I use a sealed class because of St companion object { - const val MGDL = Constants.MGDL - const val MMOL = Constants.MMOL - fun fromGlucoseUnit(value: Double, string: String): ValueWithUnitMapper? = when (string) { - MGDL, "mgdl" -> Mgdl(value) - MMOL, "mmol/l" -> Mmoll(value) + GlucoseUnit.MGDL.asText, "mgdl" -> Mgdl(value) + GlucoseUnit.MMOL.asText, "mmol/l" -> Mmoll(value) else -> null } } diff --git a/implementation/src/main/java/info/nightscout/implementation/profile/ProfileFunctionImpl.kt b/implementation/src/main/java/info/nightscout/implementation/profile/ProfileFunctionImpl.kt index 008fee161b..5614ccb986 100644 --- a/implementation/src/main/java/info/nightscout/implementation/profile/ProfileFunctionImpl.kt +++ b/implementation/src/main/java/info/nightscout/implementation/profile/ProfileFunctionImpl.kt @@ -8,7 +8,6 @@ import info.nightscout.database.entities.ProfileSwitch import info.nightscout.database.impl.AppRepository import info.nightscout.database.impl.transactions.InsertOrUpdateProfileSwitch import info.nightscout.interfaces.Config -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.nsclient.ProcessedDeviceStatusData import info.nightscout.interfaces.plugin.ActivePlugin @@ -143,7 +142,7 @@ class ProfileFunctionImpl @Inject constructor( } override fun getUnits(): GlucoseUnit = - if (sp.getString(info.nightscout.core.utils.R.string.key_units, Constants.MGDL) == Constants.MGDL) GlucoseUnit.MGDL + if (sp.getString(info.nightscout.core.utils.R.string.key_units, GlucoseUnit.MGDL.asText) == GlucoseUnit.MGDL.asText) GlucoseUnit.MGDL else GlucoseUnit.MMOL override fun buildProfileSwitch(profileStore: ProfileStore, profileName: String, durationInMinutes: Int, percentage: Int, timeShiftInHours: Int, timestamp: Long): ProfileSwitch? { diff --git a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt index da2f074488..336fde4e47 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/actions/ActionStartTempTarget.kt @@ -101,7 +101,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { override fun fromJSON(data: String): Action { val o = JSONObject(data) - value.units = GlucoseUnit.fromText(JsonHelper.safeGetString(o, "units", Constants.MGDL)) + value.units = GlucoseUnit.fromText(JsonHelper.safeGetString(o, "units", GlucoseUnit.MGDL.asText)) value.value = safeGetDouble(o, "value") duration.setMinutes(JsonHelper.safeGetInt(o, "durationInMinutes")) return this diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt index 9076b3980e..d6aff68e4c 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerBg.kt @@ -10,7 +10,6 @@ import info.nightscout.automation.elements.LabelWithElement import info.nightscout.automation.elements.LayoutBuilder import info.nightscout.automation.elements.StaticLabel import info.nightscout.core.utils.JsonHelper -import info.nightscout.interfaces.Constants import info.nightscout.interfaces.GlucoseUnit import info.nightscout.rx.logging.LTag import org.json.JSONObject @@ -71,7 +70,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { override fun fromJSON(data: String): Trigger { val d = JSONObject(data) - bg.setUnits(GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", Constants.MGDL))) + bg.setUnits(GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", GlucoseUnit.MGDL.asText))) bg.value = JsonHelper.safeGetDouble(d, "bg") comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt index 6f0ed7966c..bbcfba28e8 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerDelta.kt @@ -94,7 +94,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { override fun fromJSON(data: String): Trigger { val d = JSONObject(data) - units = GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", Constants.MGDL)) + units = GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", GlucoseUnit.MGDL.asText)) val type = DeltaType.valueOf(JsonHelper.safeGetString(d, "deltaType", "")) val value = JsonHelper.safeGetDouble(d, "value") delta = diff --git a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt index 763219fcb1..6942b5a870 100644 --- a/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt +++ b/plugins/automation/src/main/java/info/nightscout/automation/triggers/TriggerTempTargetValue.kt @@ -68,7 +68,7 @@ class TriggerTempTargetValue(injector: HasAndroidInjector) : Trigger(injector) { override fun fromJSON(data: String): Trigger { val d = JSONObject(data) - ttValue.setUnits(GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", Constants.MGDL))) + ttValue.setUnits(GlucoseUnit.fromText(JsonHelper.safeGetString(d, "units", GlucoseUnit.MGDL.asText))) ttValue.value = JsonHelper.safeGetDouble(d, "tt") comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")!!)) return this diff --git a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt index 953b7c3f42..2cdfde27c6 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -884,7 +884,7 @@ class DataHandlerMobile @Inject constructor( predictions.add( EventData.SingleBg( timeStamp = bg.data.timestamp, - glucoseUnits = Constants.MGDL, + glucoseUnits = GlucoseUnit.MGDL.asText, sgv = bg.data.value, high = 0.0, low = 0.0, diff --git a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt index 1d2b6d4728..9c7f1862e0 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfileFragment.kt @@ -131,7 +131,7 @@ class ProfileFragment : DaggerFragment() { val pumpDescription = activePlugin.activePump.pumpDescription if (profilePlugin.numOfProfiles == 0) profilePlugin.addNewProfile() val currentProfile = profilePlugin.currentProfile() ?: return - val units = if (currentProfile.mgdl) Constants.MGDL else Constants.MMOL + val units = if (currentProfile.mgdl) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText binding.name.removeTextChangedListener(textWatch) binding.name.setText(currentProfile.name) @@ -173,7 +173,7 @@ class ProfileFragment : DaggerFragment() { DecimalFormat("0.00"), save ) - if (units == Constants.MGDL) { + if (units == GlucoseUnit.MGDL.asText) { val isfRange = doubleArrayOf(HardLimits.MIN_ISF, HardLimits.MAX_ISF) TimeListEdit( requireContext(), diff --git a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt index df21a75f78..4b2e7e8b3f 100644 --- a/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt +++ b/plugins/main/src/main/java/info/nightscout/plugins/profile/ProfilePlugin.kt @@ -163,7 +163,7 @@ class ProfilePlugin @Inject constructor( profile.put("basal", basal) profile.put("target_low", targetLow) profile.put("target_high", targetHigh) - profile.put("units", if (mgdl) Constants.MGDL else Constants.MMOL) + profile.put("units", if (mgdl) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText) profile.put("timezone", TimeZone.getDefault().id) } val defaultUnits = JsonHelper.safeGetStringAllowNull(profile, "units", null) @@ -400,7 +400,7 @@ class ProfilePlugin @Inject constructor( profile.put("basal", basal) profile.put("target_low", targetLow) profile.put("target_high", targetHigh) - profile.put("units", if (mgdl) Constants.MGDL else Constants.MMOL) + profile.put("units", if (mgdl) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText) profile.put("timezone", TimeZone.getDefault().id) store.put(name, profile) } diff --git a/plugins/source/src/main/java/info/nightscout/source/PoctechPlugin.kt b/plugins/source/src/main/java/info/nightscout/source/PoctechPlugin.kt index ce62786154..24fe14f324 100644 --- a/plugins/source/src/main/java/info/nightscout/source/PoctechPlugin.kt +++ b/plugins/source/src/main/java/info/nightscout/source/PoctechPlugin.kt @@ -11,6 +11,7 @@ import info.nightscout.database.impl.AppRepository import info.nightscout.database.impl.transactions.CgmSourceTransaction import info.nightscout.database.transactions.TransactionGlucoseValue import info.nightscout.interfaces.Constants +import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.plugin.PluginBase import info.nightscout.interfaces.plugin.PluginDescription import info.nightscout.interfaces.plugin.PluginType @@ -63,7 +64,7 @@ class PoctechPlugin @Inject constructor( val json = jsonArray.getJSONObject(i) glucoseValues += TransactionGlucoseValue( timestamp = json.getLong("date"), - value = if (safeGetString(json, "units", Constants.MGDL) == "mmol/L") json.getDouble("current") * Constants.MMOLL_TO_MGDL + value = if (safeGetString(json, "units", GlucoseUnit.MGDL.asText) == "mmol/L") json.getDouble("current") * Constants.MMOLL_TO_MGDL else json.getDouble("current"), raw = json.getDouble("raw"), noise = null, diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsShared/StoreDataForDbImpl.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsShared/StoreDataForDbImpl.kt index f7fa42799c..80ce4c938c 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsShared/StoreDataForDbImpl.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsShared/StoreDataForDbImpl.kt @@ -56,6 +56,7 @@ import info.nightscout.database.impl.transactions.UpdateNsIdTherapyEventTransact import info.nightscout.database.transactions.TransactionGlucoseValue import info.nightscout.interfaces.Config import info.nightscout.interfaces.Constants +import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.logging.UserEntryLogger import info.nightscout.interfaces.notifications.Notification import info.nightscout.interfaces.nsclient.StoreDataForDb @@ -314,8 +315,8 @@ class StoreDataForDbImpl @Inject constructor( note = "", values = listOf( ValueWithUnit.TherapyEventTTReason(tt.reason), - ValueWithUnit.fromGlucoseUnit(tt.lowTarget, Constants.MGDL), - ValueWithUnit.fromGlucoseUnit(tt.highTarget, Constants.MGDL).takeIf { tt.lowTarget != tt.highTarget }, + ValueWithUnit.fromGlucoseUnit(tt.lowTarget, GlucoseUnit.MGDL.asText), + ValueWithUnit.fromGlucoseUnit(tt.highTarget, GlucoseUnit.MGDL.asText).takeIf { tt.lowTarget != tt.highTarget }, ValueWithUnit.Minute(TimeUnit.MILLISECONDS.toMinutes(tt.duration).toInt()) ) ) diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt index 1fd84ce0b2..564b11cd97 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TemporaryTargetExtension.kt @@ -10,7 +10,7 @@ import info.nightscout.shared.utils.T import org.json.JSONObject fun TemporaryTarget.Companion.fromJson(jsonObject: JSONObject, profileUtil: ProfileUtil): TemporaryTarget? { - val units = GlucoseUnit.fromText(JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL)) + val units = GlucoseUnit.fromText(JsonHelper.safeGetString(jsonObject, "units", GlucoseUnit.MGDL.asText)) val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null val duration = JsonHelper.safeGetLongAllowNull(jsonObject, "duration", null) ?: return null val durationInMilliseconds = JsonHelper.safeGetLongAllowNull(jsonObject, "durationInMilliseconds") diff --git a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TherapyEventExtension.kt b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TherapyEventExtension.kt index 685b50b371..dbc63b6121 100644 --- a/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TherapyEventExtension.kt +++ b/plugins/sync/src/main/java/info/nightscout/plugins/sync/nsclient/extensions/TherapyEventExtension.kt @@ -22,7 +22,7 @@ fun therapyEventFromNsMbg(mbg: NSMbg) = ) fun TherapyEvent.Companion.fromJson(jsonObject: JSONObject): TherapyEvent? { - val glucoseUnit = if (JsonHelper.safeGetString(jsonObject, "units", Constants.MGDL) == Constants.MGDL) TherapyEvent.GlucoseUnit.MGDL else TherapyEvent.GlucoseUnit.MMOL + val glucoseUnit = if (JsonHelper.safeGetString(jsonObject, "units", GlucoseUnit.MGDL.asText) == GlucoseUnit.MGDL.asText) TherapyEvent.GlucoseUnit.MGDL else TherapyEvent.GlucoseUnit.MMOL val timestamp = JsonHelper.safeGetLongAllowNull(jsonObject, "mills", null) ?: return null val type = TherapyEvent.Type.fromString(JsonHelper.safeGetString(jsonObject, "eventType", TherapyEvent.Type.NONE.text)) val duration = JsonHelper.safeGetLong(jsonObject, "duration") @@ -57,7 +57,7 @@ fun TherapyEvent.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject = .put("isValid", isValid) .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", enteredBy) - .put("units", if (glucoseUnit == TherapyEvent.GlucoseUnit.MGDL) Constants.MGDL else Constants.MMOL) + .put("units", if (glucoseUnit == TherapyEvent.GlucoseUnit.MGDL) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText) .also { if (duration != 0L) it.put("duration", T.msecs(duration).mins()) if (duration != 0L) it.put("durationInMilliseconds", duration) diff --git a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt index 64d438997f..43d5608f8c 100644 --- a/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt +++ b/pump/dana/src/main/java/info/nightscout/pump/dana/DanaPump.kt @@ -1,6 +1,7 @@ package info.nightscout.pump.dana import info.nightscout.interfaces.Constants +import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.profile.Instantiator import info.nightscout.interfaces.profile.Profile import info.nightscout.interfaces.profile.ProfileStore @@ -268,7 +269,7 @@ class DanaPump @Inject constructor( var bolusCalculationOption = 0 var missedBolusConfig = 0 fun getUnits(): String { - return if (units == UNITS_MGDL) Constants.MGDL else Constants.MMOL + return if (units == UNITS_MGDL) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText } var bolusStartErrorCode: Int = 0 // last start bolus errorCode @@ -368,7 +369,7 @@ class DanaPump @Inject constructor( .put("value", currentTarget) ) ) - profile.put("units", if (units == UNITS_MGDL) Constants.MGDL else Constants.MMOL) + profile.put("units", if (units == UNITS_MGDL) GlucoseUnit.MGDL.asText else GlucoseUnit.MMOL.asText) store.put(PROFILE_PREFIX + (activeProfile + 1), profile) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) diff --git a/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaUserOptionsActivity.kt b/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaUserOptionsActivity.kt index b410272c48..28320f54da 100644 --- a/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaUserOptionsActivity.kt +++ b/pump/dana/src/main/java/info/nightscout/pump/dana/activities/DanaUserOptionsActivity.kt @@ -5,6 +5,7 @@ import android.os.Bundle import info.nightscout.core.ui.activities.TranslatedDaggerAppCompatActivity import info.nightscout.core.utils.fabric.FabricPrivacy import info.nightscout.interfaces.Constants +import info.nightscout.interfaces.GlucoseUnit import info.nightscout.interfaces.plugin.ActivePlugin import info.nightscout.interfaces.pump.defs.PumpType import info.nightscout.interfaces.queue.Callback @@ -127,7 +128,7 @@ class DanaUserOptionsActivity : TranslatedDaggerAppCompatActivity() { binding.beep.isChecked = danaPump.beepAndAlarm > 4 binding.screenTimeout.value = danaPump.lcdOnTimeSec.toDouble() binding.backlight.value = danaPump.backlightOnTimeSec.toDouble() - binding.units.isChecked = danaPump.getUnits() == Constants.MMOL + binding.units.isChecked = danaPump.getUnits() == GlucoseUnit.MMOL.asText binding.shutdown.value = danaPump.shutdownHour.toDouble() binding.lowReservoir.value = danaPump.lowReservoirRate.toDouble() } diff --git a/pump/pump-common/src/main/java/info/nightscout/pump/common/data/PumpStatus.kt b/pump/pump-common/src/main/java/info/nightscout/pump/common/data/PumpStatus.kt index f2829bb298..311522e5db 100644 --- a/pump/pump-common/src/main/java/info/nightscout/pump/common/data/PumpStatus.kt +++ b/pump/pump-common/src/main/java/info/nightscout/pump/common/data/PumpStatus.kt @@ -32,7 +32,7 @@ abstract class PumpStatus(var pumpType: PumpType) { // TDD var dailyTotalUnits: Double? = null var maxDailyTotalUnits: String? = null - var units: String? = null // Constants.MGDL or Constants.MMOL + var units: String? = null // GlucoseUnit.MGDL.asText or GlucoseUnit.MMOL.asText var pumpRunningState = PumpRunningState.Running var basalsByHour: DoubleArray? = null var tempBasalStart: Long? = null diff --git a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt index 3b8dd042bf..31b4c03bd8 100644 --- a/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt +++ b/ui/src/main/java/info/nightscout/ui/dialogs/WizardDialog.kt @@ -364,7 +364,7 @@ class WizardDialog : DaggerDialogFragment() { } private fun valueToUnitsToString(value: Double, units: String): String = - if (units == Constants.MGDL) decimalFormatter.to0Decimal(value) + if (units == GlucoseUnit.MGDL.asText) decimalFormatter.to0Decimal(value) else decimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) private fun initDialog() { From 12a15b3ad101499c126b603649fc1290b7ce0111 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Sep 2023 14:06:52 +0200 Subject: [PATCH 9/9] fix tests --- .../info/nightscout/implementation/iob/GlucoseStatusTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt b/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt index 8d96814e6e..fa0cbfbcf4 100644 --- a/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt +++ b/implementation/src/test/java/info/nightscout/implementation/iob/GlucoseStatusTest.kt @@ -94,7 +94,7 @@ class GlucoseStatusTest : TestBaseWithProfile() { @Test fun returnOldDataIfAllowed() { Mockito.`when`(autosensDataStore.getBucketedDataTableCopy()).thenReturn(generateOldBgData()) val glucoseStatus: GlucoseStatus? = GlucoseStatusProviderImpl(aapsLogger, iobCobCalculatorPlugin, dateUtil, decimalFormatter).getGlucoseStatusData(true) - assertThat(glucoseStatus).isNull() + assertThat(glucoseStatus).isNotNull() } @Test fun averageShouldNotFailOnEmptyArray() {