diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index 656bdae255..724419e135 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -89,7 +89,7 @@ class RealPumpTest { 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()) + val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, dateUtil._now()) treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch) // Insulin configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt index fa7c8c5ae0..b994405383 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -71,7 +71,7 @@ class MainApp : DaggerApplication() { commitHash = null } disposable += repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe() - disposable += repository.runTransaction(InsertIfNewByTimestampTherapyEventTransaction(timestamp = dateUtil._now(), type = TherapyEvent.Type.NOTE, note = getString(info.nightscout.androidaps.core.R.string.androidaps_start).toString() + " - " + Build.MANUFACTURER + " " + Build.MODEL, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL)).subscribe() + disposable += repository.runTransaction(InsertIfNewByTimestampTherapyEventTransaction(timestamp = dateUtil.now(), type = TherapyEvent.Type.NOTE, note = getString(info.nightscout.androidaps.core.R.string.androidaps_start).toString() + " - " + Build.MANUFACTURER + " " + Build.MODEL, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL)).subscribe() disposable += compatDBHelper.dbChangeDisposable() registerActivityLifecycleCallbacks(activityMonitor) JodaTimeAndroid.init(this) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt index 6d8fffd160..03e6cf9a7c 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt @@ -114,7 +114,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { } // Profile switch - profileSwitch = databaseHelper.getProfileSwitchData(dateUtil._now() - T.months(2).msecs(), true) + profileSwitch = databaseHelper.getProfileSwitchData(dateUtil.now() - T.months(2).msecs(), true) binding.profileswitchList.setOnClickListener { PopupMenu(this, binding.profileswitchList).apply { @@ -141,7 +141,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { profile?.let { OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable { localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " + - dateUtil.dateAndTimeAndSecondsString(dateUtil._now()) + dateUtil.dateAndTimeAndSecondsString(dateUtil.now()) .replace(".", "/") )) rxBus.send(EventLocalProfileChanged()) @@ -210,7 +210,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() { getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 -> ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { - it.putLong("time", DateUtil.now()) + it.putLong("time", dateUtil.now()) it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) it.putString("customProfile", profile0.data.toString()) it.putString("customProfile2", profile1.data.toString()) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index 5286afc33d..6a06bf36e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -30,6 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activityMonitor: ActivityMonitor @Inject lateinit var defaultProfile: DefaultProfile + @Inject lateinit var dateUtil: DateUtil private lateinit var binding: ActivitySurveyBinding @@ -68,7 +69,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile -> ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { - it.putLong("time", DateUtil.now()) + it.putLong("time", dateUtil.now()) it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) it.putString("customProfile", runningProfile.data.toString()) it.putString("customProfile2", profile.data.toString()) diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index e780600aa0..049ea49983 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -52,6 +52,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.PercentageSplitter; /** @@ -69,6 +70,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Inject OpenHumansUploader openHumansUploader; @Inject ActivePluginProvider activePlugin; @Inject NSUpload nsUpload; + @Inject DateUtil dateUtil; public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses"; @@ -886,7 +888,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profileJson = profile.getData().toString(); aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store"); // Update data in NS - nsUpload.updateProfileSwitch(profileSwitch); + nsUpload.updateProfileSwitch(profileSwitch, dateUtil); } else { aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index b02534d36a..ce7fc47e3a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -303,7 +303,7 @@ class CarbsDialog : DialogFragmentWithDate() { }) } if (useAlarm && carbs > 0 && timeOffset > 0) { - carbTimer.scheduleReminder(dateUtil._now() + T.mins(timeOffset.toLong()).msecs()) + carbTimer.scheduleReminder(dateUtil.now() + T.mins(timeOffset.toLong()).msecs()) } }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index 50c8a9b13d..b2ab0b7443 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -175,7 +175,7 @@ class InsulinDialog : DialogFragmentWithDate() { actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + (DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + resourceHelper.gs(R.string.format_mins, eatingSoonTTDuration) + ")").formatColor(resourceHelper, R.color.tempTargetConfirmation)) val timeOffset = binding.time.value.toInt() - val time = dateUtil._now() + T.mins(timeOffset.toLong()).msecs() + val time = dateUtil.now() + T.mins(timeOffset.toLong()).msecs() if (timeOffset != 0) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 3f6a7d9da4..08d470d442 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -16,7 +16,6 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -83,7 +82,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { binding.profile.setSelection(p) } ?: return - treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> + treatmentsPlugin.getProfileSwitchFromHistory(dateUtil.now())?.let { ps -> if (ps.isCPP) { binding.reuselayout.visibility = View.VISIBLE binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, ps.percentage, ps.timeshift) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index 94f4c611fa..556617303d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -88,7 +88,7 @@ class TempTargetDialog : DialogFragmentWithDate() { // temp target context?.let { context -> - if (repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing) + if (repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing) binding.targetCancel.visibility = View.VISIBLE else binding.targetCancel.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index 39dc0165d9..9f4a1d5a65 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -210,7 +210,7 @@ class WizardDialog : DaggerDialogFragment() { private fun onCheckedChanged(buttonView: CompoundButton, @Suppress("UNUSED_PARAMETER") state: Boolean) { saveCheckedStates() - binding.ttcheckbox.isEnabled = binding.bgcheckbox.isChecked && repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing + binding.ttcheckbox.isEnabled = binding.bgcheckbox.isChecked && repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing if (buttonView.id == binding.cobcheckbox.id) processCobCheckBox() calculateInsulin() @@ -268,7 +268,7 @@ class WizardDialog : DaggerDialogFragment() { // Set BG if not old binding.bgInput.value = iobCobCalculator.actualBg()?.valueToUnits(units) ?: 0.0 - binding.ttcheckbox.isEnabled = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing + binding.ttcheckbox.isEnabled = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing // IOB calculation val bolusIob = iobCobCalculator.calculateIobFromBolus().round() @@ -308,7 +308,7 @@ class WizardDialog : DaggerDialogFragment() { } bg = if (binding.bgcheckbox.isChecked) bg else 0.0 - val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = if (binding.ttcheckbox.isChecked && dbRecord is ValueWrapper.Existing) dbRecord.value else null // COB diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index 74f581b298..0c0b592a30 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt @@ -98,7 +98,6 @@ class LoopFragment : DaggerFragment() { binding.constraintsprocessed.text = it.constraintsProcessed?.toSpanned() ?: "" binding.source.text = it.source ?: "" binding.lastrun.text = dateUtil.dateAndTimeString(it.lastAPSRun) - ?: "" binding.smbrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest) binding.smbexecutionTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact) binding.tbrrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index fd5934be9d..e34430c9ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -313,7 +313,7 @@ open class LoopPlugin @Inject constructor( lastRun = (lastRun ?: LastRun()).also { lastRun -> lastRun.request = apsResult lastRun.constraintsProcessed = resultAfterConstraints - lastRun.lastAPSRun = DateUtil.now() + lastRun.lastAPSRun = dateUtil.now() lastRun.source = (usedAPS as PluginBase).name lastRun.tbrSetByPump = null lastRun.smbSetByPump = null @@ -411,7 +411,7 @@ open class LoopPlugin @Inject constructor( if (result.enacted || result.success) { lastRun.tbrSetByPump = result lastRun.lastTBRRequest = lastRun.lastAPSRun - lastRun.lastTBREnact = DateUtil.now() + lastRun.lastTBREnact = dateUtil.now() rxBus.send(EventLoopUpdateGui()) applySMBRequest(resultAfterConstraints, object : Callback() { override fun run() { @@ -419,7 +419,7 @@ open class LoopPlugin @Inject constructor( if (result.enacted || result.success) { lastRun.smbSetByPump = result lastRun.lastSMBRequest = lastRun.lastAPSRun - lastRun.lastSMBEnact = DateUtil.now() + lastRun.lastSMBEnact = dateUtil.now() } else { Thread { SystemClock.sleep(1000) @@ -510,8 +510,8 @@ open class LoopPlugin @Inject constructor( if (result.enacted) { lastRun.tbrSetByPump = result lastRun.lastTBRRequest = lastRun.lastAPSRun - lastRun.lastTBREnact = DateUtil.now() - lastRun.lastOpenModeAccept = DateUtil.now() + lastRun.lastTBREnact = dateUtil.now() + lastRun.lastOpenModeAccept = dateUtil.now() buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction, activePlugin.activePump, receiverStatusStore, runningConfiguration, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { @@ -661,7 +661,7 @@ open class LoopPlugin @Inject constructor( } }) } - if (pump.pumpDescription.isExtendedBolusCapable && iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) { + if (pump.pumpDescription.isExtendedBolusCapable && iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { commandQueue.cancelExtended(object : Callback() { override fun run() { if (!result.success) { @@ -687,7 +687,7 @@ open class LoopPlugin @Inject constructor( override fun createOfflineEvent(durationInMinutes: Int) { disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), type = TherapyEvent.Type.APS_OFFLINE, duration = T.mins(durationInMinutes.toLong()).msecs(), enteredBy = "openaps://" + "AndroidAPS", diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt index 7ab62fe0e7..076618f6b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.kt @@ -194,7 +194,7 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader // as we have non default temps longer than 30 minutes if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now)) - iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) + iobData = iobCobCalculator.convertToJSONArray(iobArray) this.glucoseStatus = JSONObject() this.glucoseStatus.put("glucose", glucoseStatus.glucose) if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt index b93afc5984..6f66dd235f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.kt @@ -13,7 +13,7 @@ class DetermineBasalResultAMA private constructor(injector: HasAndroidInjector) private var snoozeBG = 0.0 internal constructor(injector: HasAndroidInjector, result: NativeObject, j: JSONObject) : this(injector) { - date = dateUtil._now() + date = dateUtil.now() json = j if (result.containsKey("error")) { reason = result["error"].toString() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index 9a4385ee1b..891a14239a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -116,7 +116,7 @@ open class OpenAPSAMAPlugin @Inject constructor( var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.targetHighMgdl, 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MAX_BG[1].toDouble()) var targetBg = hardLimits.verifyHardLimits(profile.targetMgdl, R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble()) var isTempTarget = false - val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { isTempTarget = true minBg = hardLimits.verifyHardLimits(tempTarget.value.lowTarget, R.string.temp_target_low_target, HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1].toDouble()) @@ -160,10 +160,10 @@ open class OpenAPSAMAPlugin @Inject constructor( lastAPSResult = null lastAPSRun = 0 } else { - if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultAMA.tempBasalRequested = false + if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) == null) determineBasalResultAMA.tempBasalRequested = false determineBasalResultAMA.iob = iobArray[0] val now = System.currentTimeMillis() - determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now)) + determineBasalResultAMA.json?.put("timestamp", dateUtil.toISOString(now)) determineBasalResultAMA.inputConstraints = inputConstraints lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS lastAPSResult = determineBasalResultAMA diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index fbaddd7770..355848150e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -237,7 +237,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader: // as we have non default temps longer than 30 mintues if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now)) - iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) + iobData = iobCobCalculator.convertToJSONArray(iobArray) mGlucoseStatus.put("glucose", glucoseStatus.glucose) mGlucoseStatus.put("noise", glucoseStatus.noise) if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt index 589eff449c..996621b8db 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.utils.DateUtil import org.json.JSONException import org.json.JSONObject @@ -13,7 +12,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector) private var snoozeBG = 0.0 internal constructor(injector: HasAndroidInjector, result: JSONObject) : this(injector) { - date = dateUtil._now() + date = dateUtil.now() json = result try { if (result.has("error")) { @@ -47,7 +46,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector) if (result.has("deliverAt")) { val date = result.getString("deliverAt") try { - deliverAt = DateUtil.fromISODateString(date).time + deliverAt = dateUtil.fromISODateString(date) } catch (e: Exception) { aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: $date", e) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 15da422113..6517feb45c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -122,7 +122,7 @@ open class OpenAPSSMBPlugin @Inject constructor( var maxBg = hardLimits.verifyHardLimits(Round.roundTo(profile.targetHighMgdl, 0.1), R.string.profile_high_target, HardLimits.VERY_HARD_LIMIT_MAX_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_MAX_BG[1].toDouble()) var targetBg = hardLimits.verifyHardLimits(profile.targetMgdl, R.string.temp_target_value, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble()) var isTempTarget = false - val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { isTempTarget = true minBg = hardLimits.verifyHardLimits(tempTarget.value.lowTarget, R.string.temp_target_low_target, HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1].toDouble()) @@ -187,9 +187,9 @@ open class OpenAPSSMBPlugin @Inject constructor( } else { // TODO still needed with oref1? // Fix bug determine basal - if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultSMB.tempBasalRequested = false + if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) == null) determineBasalResultSMB.tempBasalRequested = false determineBasalResultSMB.iob = iobArray[0] - determineBasalResultSMB.json?.put("timestamp", DateUtil.toISOString(now)) + determineBasalResultSMB.json?.put("timestamp", dateUtil.toISOString(now)) determineBasalResultSMB.inputConstraints = inputConstraints lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS lastAPSResult = determineBasalResultSMB diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index 52630816cc..8f161e6ae2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -237,7 +237,7 @@ class ObjectivesFragment : DaggerFragment() { holder.binding.verify.setOnClickListener { receiverStatusStore.updateNetworkStatus() if (binding.fake.isChecked) { - objective.accomplishedOn = DateUtil.now() + objective.accomplishedOn = dateUtil.now() scrollToCurrentObjective() startUpdateTimer() rxBus.send(EventObjectivesUpdateGui()) @@ -249,7 +249,7 @@ class ObjectivesFragment : DaggerFragment() { rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { - aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") + aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) @@ -276,7 +276,7 @@ class ObjectivesFragment : DaggerFragment() { holder.binding.start.setOnClickListener { receiverStatusStore.updateNetworkStatus() if (binding.fake.isChecked) { - objective.startedOn = DateUtil.now() + objective.startedOn = dateUtil.now() scrollToCurrentObjective() startUpdateTimer() rxBus.send(EventObjectivesUpdateGui()) @@ -288,7 +288,7 @@ class ObjectivesFragment : DaggerFragment() { rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { - aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") + aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}") SystemClock.sleep(300) if (!networkConnected) { rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 221b453c36..f101ee7037 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -29,6 +29,7 @@ class ObjectivesPlugin @Inject constructor( private val activePlugin: ActivePluginProvider, private val sp: SP, config: Config, + private val dateUtil: DateUtil, private val uel: UserEntryLogger ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -126,22 +127,22 @@ class ObjectivesPlugin @Inject constructor( if (!url.endsWith("/")) url = "$url/" @Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString() if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) { - sp.putLong("Objectives_" + "openloop" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "openloop" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "maxbasal" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "maxbasal" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "maxiobzero" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "maxiobzero" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "maxiob" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "maxiob" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "autosens" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "autosens" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "ama" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "ama" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "smb" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "smb" + "_accomplished", DateUtil.now()) - sp.putLong("Objectives_" + "auto" + "_started", DateUtil.now()) - sp.putLong("Objectives_" + "auto" + "_accomplished", DateUtil.now()) + sp.putLong("Objectives_" + "openloop" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "openloop" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "maxbasal" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "maxbasal" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "maxiobzero" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "maxiobzero" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "maxiob" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "maxiob" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "autosens" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "autosens" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "ama" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "ama" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "smb" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "smb" + "_accomplished", dateUtil.now()) + sp.putLong("Objectives_" + "auto" + "_started", dateUtil.now()) + sp.putLong("Objectives_" + "auto" + "_accomplished", dateUtil.now()) setupObjectives() OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeaccepted)) uel.log(Action.OBJECTIVES_SKIPPED, Sources.Objectives) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt index c45d61bfd4..50c91dd6b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt @@ -108,7 +108,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() { } task.answered = result if (!result) { - task.disabledTo = DateUtil.now() + T.hours(1).msecs() + task.disabledTo = dateUtil.now() + T.hours(1).msecs() ToastUtils.showToastInUiThread(context, R.string.wronganswer) } else task.disabledTo = 0 updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt index 876fb881db..71f258781d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt @@ -21,6 +21,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var dateUtil: DateUtil private val spName: String @StringRes val objective: Int @@ -55,7 +56,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe this.gate = gate startedOn = sp.getLong("Objectives_" + spName + "_started", 0L) accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 0L) - if (accomplishedOn - DateUtil.now() > T.hours(3).msecs() || startedOn - DateUtil.now() > T.hours(3).msecs()) { // more than 3 hours in the future + if (accomplishedOn - dateUtil.now() > T.hours(3).msecs() || startedOn - dateUtil.now() > T.hours(3).msecs()) { // more than 3 hours in the future startedOn = 0 accomplishedOn = 0 } @@ -69,7 +70,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe } val isAccomplished: Boolean - get() = accomplishedOn != 0L && accomplishedOn < DateUtil.now() + get() = accomplishedOn != 0L && accomplishedOn < dateUtil.now() val isStarted: Boolean get() = startedOn != 0L @@ -144,7 +145,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe override fun isCompleted(): Boolean = answered - fun isEnabledAnswer(): Boolean = disabledTo < DateUtil.now() + fun isEnabledAnswer(): Boolean = disabledTo < dateUtil.now() fun option(option: Option): ExamTask { options.add(option) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt index 63eaa326fc..feb7fe73d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective0.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil import javax.inject.Inject class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R.string.objectives_0_objective, R.string.objectives_0_gate) { @@ -65,7 +64,7 @@ class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R }) tasks.add(object : Task(this, R.string.activate_profile) { override fun isCompleted(): Boolean { - return treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()) != null + return treatmentsPlugin.getProfileSwitchFromHistory(dateUtil.now()) != null } }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt index dbd3cc8ea6..1c1407c500 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt @@ -70,7 +70,7 @@ class SafetyPlugin @Inject constructor( value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this } val pump = activePlugin.activePump - if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) { + if (!pump.isFakingTempsByExtendedBoluses && iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_with_eb)] = this } return value diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index 7377ad4c83..473aa35f6c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -164,7 +164,7 @@ class ActionsFragment : DaggerFragment() { } } extendedBolusCancel?.setOnClickListener { - if (iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) { + if (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) { uel.log(Action.CANCEL_EXTENDED_BOLUS, Sources.Actions) commandQueue.cancelExtended(object : Callback() { override fun run() { @@ -179,7 +179,7 @@ class ActionsFragment : DaggerFragment() { TempBasalDialog().show(childFragmentManager, "Actions") } cancelTempBasal?.setOnClickListener { - if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) != null) { + if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) != null) { uel.log(Action.CANCEL_TEMP_BASAL, Sources.Actions) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { @@ -274,7 +274,7 @@ class ActionsFragment : DaggerFragment() { extendedBolus?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE } else { - val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet() + val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet() if (activeExtendedBolus is ValueWrapper.Existing) { extendedBolus?.visibility = View.GONE extendedBolusCancel?.visibility = View.VISIBLE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt index 168cbe5f09..af857b64dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt @@ -41,7 +41,6 @@ import io.reactivex.Single import java.io.File import java.io.FileNotFoundException import java.io.IOException -import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.system.exitProcess @@ -63,7 +62,8 @@ class ImportExportPrefs @Inject constructor( private val classicPrefsFormat: ClassicPrefsFormat, private val encryptedPrefsFormat: EncryptedPrefsFormat, private val prefFileList: PrefFileListProvider, - private val uel: UserEntryLogger + private val uel: UserEntryLogger, + private val dateUtil: DateUtil ) : ImportExportPrefsInterface { override fun prefsFileExists(): Boolean { @@ -95,7 +95,7 @@ class ImportExportPrefs @Inject constructor( val metadata: MutableMap = mutableMapOf() metadata[PrefsMetadataKey.DEVICE_NAME] = PrefMetadata(detectUserName(context), PrefsStatus.OK) - metadata[PrefsMetadataKey.CREATED_AT] = PrefMetadata(DateUtil.toISOString(Date()), PrefsStatus.OK) + metadata[PrefsMetadataKey.CREATED_AT] = PrefMetadata(dateUtil.toISOString(dateUtil.now()), PrefsStatus.OK) metadata[PrefsMetadataKey.AAPS_VERSION] = PrefMetadata(BuildConfig.VERSION_NAME, PrefsStatus.OK) metadata[PrefsMetadataKey.AAPS_FLAVOUR] = PrefMetadata(BuildConfig.FLAVOR, PrefsStatus.OK) metadata[PrefsMetadataKey.DEVICE_MODEL] = PrefMetadata(config.currentDeviceModelString, PrefsStatus.OK) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt index ddd26a64c0..c27b948d62 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt @@ -10,12 +10,14 @@ import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.extensions.toJson +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject class DataSyncSelectorImplementation @Inject constructor( private val sp: SP, private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, private val profileFunction: ProfileFunction, private val nsClientPlugin: NSClientPlugin, private val activePlugin: ActivePluginProvider, @@ -65,10 +67,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", bolus.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolus(bolus.first, bolus.second)) // existing without nsId = create new bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(), DataSyncSelector.PairBolus(bolus.first, bolus.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) // existing with nsId = update bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(), DataSyncSelector.PairBolus(bolus.first, bolus.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", bolus.first.interfaceIDs.nightscoutId, bolus.first.toJson(dateUtil), DataSyncSelector.PairBolus(bolus.first, bolus.second)) } return true } @@ -102,10 +104,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", carb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairCarbs(carb.first, carb.second)) // existing without nsId = create new carb.first.isValid && carb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(), DataSyncSelector.PairCarbs(carb.first, carb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) // existing with nsId = update carb.first.isValid && carb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(), DataSyncSelector.PairCarbs(carb.first, carb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", carb.first.interfaceIDs.nightscoutId, carb.first.toJson(dateUtil), DataSyncSelector.PairCarbs(carb.first, carb.second)) } return true } @@ -139,10 +141,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) // existing without nsId = create new bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", bolusCalculatorResult.first.toJson(), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) // existing with nsId = update bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, bolusCalculatorResult.first.toJson(dateUtil), DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) } return true } @@ -176,10 +178,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) // existing without nsId = create new tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(profileFunction.getUnits()), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) // existing with nsId = update tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits()), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits(), dateUtil), DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) } return true } @@ -251,10 +253,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("entries", gv.first.interfaceIDs.nightscoutId, DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) // existing without nsId = create new gv.first.isValid && gv.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) + nsClientPlugin.nsClientService?.dbAdd("entries", gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) // existing with nsId = update gv.first.isValid && gv.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) + nsClientPlugin.nsClientService?.dbUpdate("entries", gv.first.interfaceIDs.nightscoutId, gv.first.toJson(dateUtil), DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) } return true } @@ -320,7 +322,7 @@ class DataSyncSelectorImplementation @Inject constructor( when { // without nsId = create new deviceStatus.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(), deviceStatus) + nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(dateUtil), deviceStatus) // with nsId = ignore deviceStatus.interfaceIDs.nightscoutId != null -> Any() } @@ -357,10 +359,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", tb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) // existing without nsId = create new tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) // existing with nsId = update tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", tb.first.interfaceIDs.nightscoutId, tb.first.toJson(profile, dateUtil), DataSyncSelector.PairTemporaryBasal(tb.first, tb.second)) } return true } @@ -396,10 +398,10 @@ class DataSyncSelectorImplementation @Inject constructor( nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) // existing without nsId = create new eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> - nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbAdd("treatments", eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) // existing with nsId = update eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> - nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) + nsClientPlugin.nsClientService?.dbUpdate("treatments", eb.first.interfaceIDs.nightscoutId, eb.first.toJson(profile, dateUtil), DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt index 86f860bcb2..ad5ef82d8a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt @@ -71,7 +71,7 @@ class NSClientAddUpdateWorker( //Find latest date in treatment val mills = safeGetLong(json, "mills") - if (mills != 0L && mills < dateutil._now()) + if (mills != 0L && mills < dateutil.now()) if (mills > latestDateInReceivedData) latestDateInReceivedData = mills if (insulin > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt index 5657f1d48e..1ef337e2d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt @@ -164,12 +164,12 @@ class NSDeviceStatus @Inject constructor( // test warning level val level = when { - pumpData.clock + nsSettingsStatus.extendedPumpSettings("urgentClock") * 60 * 1000L < dateUtil._now() -> Levels.URGENT - pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("urgentRes") -> Levels.URGENT + pumpData.clock + nsSettingsStatus.extendedPumpSettings("urgentClock") * 60 * 1000L < dateUtil.now() -> Levels.URGENT + pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("urgentRes") -> Levels.URGENT pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("urgentBattP") -> Levels.URGENT - !pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("urgentBattV") -> Levels.URGENT - pumpData.clock + nsSettingsStatus.extendedPumpSettings("warnClock") * 60 * 1000L < dateUtil._now() -> Levels.WARN - pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("warnRes") -> Levels.WARN + !pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("urgentBattV") -> Levels.URGENT + pumpData.clock + nsSettingsStatus.extendedPumpSettings("warnClock") * 60 * 1000L < dateUtil.now() -> Levels.WARN + pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("warnRes") -> Levels.WARN pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("warnBattP") -> Levels.WARN !pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("warnBattV") -> Levels.WARN else -> Levels.INFO @@ -179,7 +179,7 @@ class NSDeviceStatus @Inject constructor( if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ") if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ") if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ") - if (fields.contains("clock")) string.append(DateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ") + if (fields.contains("clock")) string.append(dateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ") if (fields.contains("status")) string.append(pumpData.status).append(" ") if (fields.contains("device")) string.append(device).append(" ") string.append("") // color @@ -201,7 +201,7 @@ class NSDeviceStatus @Inject constructor( try { val data = this.data ?: return val pump = if (data.has("pump")) data.getJSONObject("pump") else JSONObject() - val clock = if (pump.has("clock")) DateUtil.fromISODateString(pump.getString("clock")).time else 0L + val clock = if (pump.has("clock")) dateUtil.fromISODateString(pump.getString("clock")) else 0L // check if this is new data if (clock == 0L || deviceStatusPumpData != null && clock < deviceStatusPumpData!!.clock) return @@ -247,13 +247,13 @@ class NSDeviceStatus @Inject constructor( val openAps = if (jsonObject.has("openaps")) jsonObject.getJSONObject("openaps") else JSONObject() val suggested = if (openAps.has("suggested")) openAps.getJSONObject("suggested") else JSONObject() val enacted = if (openAps.has("enacted")) openAps.getJSONObject("enacted") else JSONObject() - var clock = if (suggested.has("timestamp")) DateUtil.fromISODateString(suggested.getString("timestamp")).time else 0L + var clock = if (suggested.has("timestamp")) dateUtil.fromISODateString(suggested.getString("timestamp")) else 0L // check if this is new data if (clock != 0L && clock > deviceStatusOpenAPSData.clockSuggested) { deviceStatusOpenAPSData.suggested = suggested deviceStatusOpenAPSData.clockSuggested = clock } - clock = if (enacted.has("timestamp")) DateUtil.fromISODateString(enacted.getString("timestamp")).time else 0L + clock = if (enacted.has("timestamp")) dateUtil.fromISODateString(enacted.getString("timestamp")) else 0L // check if this is new data if (clock != 0L && clock > deviceStatusOpenAPSData.clockEnacted) { deviceStatusOpenAPSData.enacted = enacted @@ -273,12 +273,12 @@ class NSDeviceStatus @Inject constructor( // test warning level val level = when { - deviceStatusOpenAPSData.clockSuggested + T.mins(sp.getLong(R.string.key_nsalarm_urgent_staledatavalue, 31)).msecs() < dateUtil._now() -> Levels.URGENT - deviceStatusOpenAPSData.clockSuggested + T.mins(sp.getLong(R.string.key_nsalarm_staledatavalue, 16)).msecs() < dateUtil._now() -> Levels.WARN - else -> Levels.INFO + deviceStatusOpenAPSData.clockSuggested + T.mins(sp.getLong(R.string.key_nsalarm_urgent_staledatavalue, 31)).msecs() < dateUtil.now() -> Levels.URGENT + deviceStatusOpenAPSData.clockSuggested + T.mins(sp.getLong(R.string.key_nsalarm_staledatavalue, 16)).msecs() < dateUtil.now() -> Levels.WARN + else -> Levels.INFO } string.append("") - if (deviceStatusOpenAPSData.clockSuggested != 0L) string.append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ") + if (deviceStatusOpenAPSData.clockSuggested != 0L) string.append(dateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ") string.append("") // color return fromHtml(string.toString()) } @@ -287,8 +287,8 @@ class NSDeviceStatus @Inject constructor( get() { val string = StringBuilder() try { - if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested) string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append(" ").append(deviceStatusOpenAPSData.enacted!!.getString("reason")).append("
") - if (deviceStatusOpenAPSData.suggested != null) string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ").append(deviceStatusOpenAPSData.suggested!!.getString("reason")).append("
") + if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested) string.append("").append(dateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append(" ").append(deviceStatusOpenAPSData.enacted!!.getString("reason")).append("
") + if (deviceStatusOpenAPSData.suggested != null) string.append("").append(dateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ").append(deviceStatusOpenAPSData.suggested!!.getString("reason")).append("
") return fromHtml(string.toString()) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) @@ -307,7 +307,7 @@ class NSDeviceStatus @Inject constructor( val clock = when { jsonObject.has("mills") -> jsonObject.getLong("mills") - jsonObject.has("created_at") -> DateUtil.fromISODateString(jsonObject.getString("created_at")).time + jsonObject.has("created_at") -> dateUtil.fromISODateString(jsonObject.getString("created_at")) else -> 0L } val device = device diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index bbc8258c8d..35671b20f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -228,7 +228,7 @@ public class NSClientService extends DaggerService { } public void processAddAck(NSAddAck ack) { - lastAckTime = dateUtil._now(); + lastAckTime = dateUtil.now(); // new room way if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) { DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject(); @@ -400,7 +400,7 @@ public class NSClientService extends DaggerService { } public void processUpdateAck(NSUpdateAck ack) { - lastAckTime = dateUtil._now(); + lastAckTime = dateUtil.now(); // new room way if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) { DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject(); @@ -591,7 +591,7 @@ public class NSClientService extends DaggerService { void watchdog() { synchronized (reconnections) { - long now = DateUtil.now(); + long now = dateUtil.now(); reconnections.add(now); for (int i = 0; i < reconnections.size(); i++) { Long r = reconnections.get(i); @@ -833,7 +833,7 @@ public class NSClientService extends DaggerService { if (action == null) addedOrUpdatedTreatments.put(jsonTreatment); else if (action.equals("update")) addedOrUpdatedTreatments.put(jsonTreatment); - else if (action.equals("remove") && mills > dateUtil._now() - T.days(1).msecs()) // handle 1 day old deletions only + else if (action.equals("remove") && mills > dateUtil.now() - T.days(1).msecs()) // handle 1 day old deletions only removedTreatments.put(jsonTreatment); } if (removedTreatments.length() > 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index 5279d4a2ff..4138c4d7b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -309,7 +309,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList R.id.active_profile -> { ProfileViewerDialog().also { pvd -> pvd.arguments = Bundle().also { - it.putLong("time", DateUtil.now()) + it.putLong("time", dateUtil.now()) it.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) } }.show(childFragmentManager, "ProfileViewDialog") @@ -549,7 +549,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (_binding == null) return aapsLogger.debug("UpdateGUI from $from") - binding.infoLayout.time.text = dateUtil.timeString(Date()) + binding.infoLayout.time.text = dateUtil.timeString(dateUtil.now()) if (!profileFunction.isProfileValid("Overview")) { binding.loopPumpStatusLayout.pumpStatus.setText(R.string.noprofileset) @@ -612,8 +612,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } else flag and Paint.STRIKE_THRU_TEXT_FLAG.inv() overview_bg.paintFlags = flag } - binding.infoLayout.timeAgo.text = DateUtil.minAgo(resourceHelper, lastBG.timestamp) - binding.infoLayout.timeAgoShort.text = "(" + DateUtil.minAgoShort(lastBG.timestamp) + ")" + binding.infoLayout.timeAgo.text = dateUtil.minAgo(resourceHelper, lastBG.timestamp) + binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(lastBG.timestamp) + ")" } val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() @@ -625,19 +625,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList when { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus) - binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) + binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.visibility = View.VISIBLE } loopPlugin.isDisconnected -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected) - binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) + binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.visibility = View.VISIBLE } loopPlugin.isEnabled() && loopPlugin.isSuspended -> { binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused) - binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) + binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) binding.infoLayout.apsModeText.visibility = View.VISIBLE } @@ -680,11 +680,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } // temp target - val tempTarget: ValueWrapper = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tempTarget: ValueWrapper = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { binding.loopPumpStatusLayout.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) binding.loopPumpStatusLayout.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) - binding.loopPumpStatusLayout.tempTarget.text = Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.highTarget, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.value.end, resourceHelper) + binding.loopPumpStatusLayout.tempTarget.text = Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.highTarget, Constants.MGDL, units) + " " + dateUtil.untilString(tempTarget.value.end, resourceHelper) } else { // If the target is not the same as set in the profile then oref has overridden it val targetUsed = lastRun?.constraintsProcessed?.targetBG ?: 0.0 @@ -723,7 +723,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (percentRate < 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_low) // Extended bolus - val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet() + val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet() binding.infoLayout.extendedBolus.text = if (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.value.rate) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index b804a84d60..b4c2754a15 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Om import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.extensions.age +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject @@ -24,6 +25,7 @@ import javax.inject.Singleton class StatusLightHandler @Inject constructor( private val resourceHelper: ResourceHelper, private val sp: SP, + private val dateUtil: DateUtil, private val activePlugin: ActivePluginProvider, private val warnColors: WarnColors, private val config: Config, @@ -75,7 +77,7 @@ class StatusLightHandler @Inject constructor( val therapyEvent = repository.getLastTherapyRecord(type).blockingGet() if (therapyEvent is ValueWrapper.Existing) { warnColors.setColorByAge(view, therapyEvent.value, warn, urgent) - view?.text = therapyEvent.value.age(resourceHelper.shortTextMode(), resourceHelper) + view?.text = therapyEvent.value.age(resourceHelper.shortTextMode(), resourceHelper, dateUtil) } else { view?.text = if (resourceHelper.shortTextMode()) "-" else resourceHelper.gs(R.string.notavailable) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt index 237afba172..366850607f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt @@ -83,7 +83,7 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener { // create an OnTimeSetListener val fromTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> fromSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt() - binding.from.text = dateUtil.timeString(DateUtil.toDate(fromSeconds)) + binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(fromSeconds)) } binding.from.setOnClickListener { @@ -96,11 +96,11 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener { } } fromSeconds = entry.validFrom() - binding.from.text = dateUtil.timeString(DateUtil.toDate(fromSeconds)) + binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(fromSeconds)) val toTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> toSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt() - binding.from.text = dateUtil.timeString(DateUtil.toDate(toSeconds)) + binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) } binding.to.setOnClickListener { @@ -113,7 +113,7 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener { } } toSeconds = entry.validFrom() - binding.to.text = dateUtil.timeString(DateUtil.toDate(toSeconds)) + binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) binding.buttonEdit.setText(entry.buttonText()) binding.carbsEdit.setText(entry.carbs().toString()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index 02023a8894..018acf9881 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -415,7 +415,7 @@ class GraphData( if (showPrediction) { val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("GraphData") val lastAutosensResult = autosensData?.autosensResult ?: AutosensResult() - val isTempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() is ValueWrapper.Existing + val isTempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing val iobPrediction: MutableList = ArrayList() val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) for (i in iobPredictionArray) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt index ae454e1f2b..7d19bed23d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt @@ -22,12 +22,14 @@ class AuthRequest internal constructor( @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var otp: OneTimePassword + @Inject lateinit var dateUtil: DateUtil - private val date = DateUtil.now() + private var date = 0L private var processed = false init { injector.androidInjector().inject(this) + date = dateUtil.now() smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, requestText)) } @@ -45,7 +47,7 @@ class AuthRequest internal constructor( smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_wrongcode))) return } - if (DateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { + if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { processed = true aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text) action.run() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt index 5952a0da66..6efac44dbb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt @@ -1,9 +1,9 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator import android.telephony.SmsMessage -import info.nightscout.androidaps.utils.DateUtil class Sms { + var phoneNumber: String var text: String var date: Long @@ -22,7 +22,7 @@ class Sms { internal constructor(phoneNumber: String, text: String) { this.phoneNumber = phoneNumber this.text = text - date = DateUtil.now() + date = System.currentTimeMillis() sent = true } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index ee9fa3c40b..f6b86d2886 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -49,9 +49,11 @@ import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreferen import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.apache.commons.lang3.StringUtils +import org.joda.time.DateTime import java.text.Normalizer import java.util.* import java.util.concurrent.TimeUnit +import java.util.regex.Pattern import javax.inject.Inject import javax.inject.Singleton import kotlin.math.max @@ -274,7 +276,7 @@ class SmsCommunicatorPlugin @Inject constructor( else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) "BOLUS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) - else if (divided.size == 2 && DateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed))) + else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed))) else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended))) else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) @@ -315,7 +317,7 @@ class SmsCommunicatorPlugin @Inject constructor( if (actualBG != null) { reply = resourceHelper.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", " } else if (lastBG != null) { - val agoMilliseconds = System.currentTimeMillis() - lastBG.timestamp + val agoMilliseconds = dateUtil.now() - lastBG.timestamp val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt() reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", " } @@ -429,7 +431,7 @@ class SmsCommunicatorPlugin @Inject constructor( commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { - loopPlugin.suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000) + loopPlugin.suspendTo(dateUtil.now() + anInteger() * 60L * 1000) loopPlugin.createOfflineEvent(anInteger() * 60) rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " + @@ -582,7 +584,7 @@ class SmsCommunicatorPlugin @Inject constructor( val finalPercentage = percentage messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(list[pIndex - 1] as String, finalPercentage) { override fun run() { - activePlugin.activeTreatments.doProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) + activePlugin.activeTreatments.doProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now()) val replyText = resourceHelper.gs(R.string.profileswitchcreated) sendSMS(Sms(receivedSms.phoneNumber, replyText)) uel.log(Action.PROFILE_SWITCH, Sources.SMS, resourceHelper.gs(R.string.profileswitchcreated), @@ -808,7 +810,7 @@ class SmsCommunicatorPlugin @Inject constructor( else String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) replyText += "\n" + activePlugin.activePump.shortStatus(true) - lastRemoteBolusTime = DateUtil.now() + lastRemoteBolusTime = dateUtil.now() if (isMeal) { profileFunction.getProfile()?.let { currentProfile -> var eatingSoonTTDuration = sp.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration) @@ -823,7 +825,7 @@ class SmsCommunicatorPlugin @Inject constructor( else -> Constants.defaultEatingSoonTTmgdl } disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction( - timestamp = System.currentTimeMillis(), + timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), reason = TemporaryTarget.Reason.EATING_SOON, lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), @@ -858,11 +860,30 @@ class SmsCommunicatorPlugin @Inject constructor( } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) } + fun toTodayTime(hh_colon_mm: String): Long { + val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)") + val m = p.matcher(hh_colon_mm) + var retval: Long = 0 + if (m.find()) { + var hours = SafeParse.stringToInt(m.group(1)) + val minutes = SafeParse.stringToInt(m.group(2)) + if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") hours -= 12 + if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") hours += 12 + val t = DateTime() + .withHourOfDay(hours) + .withMinuteOfHour(minutes) + .withSecondOfMinute(0) + .withMillisOfSecond(0) + retval = t.millis + } + return retval + } + private fun processCARBS(divided: Array, receivedSms: Sms) { var grams = SafeParse.stringToInt(divided[1]) - var time = DateUtil.now() + var time = dateUtil.now() if (divided.size > 2) { - time = DateUtil.toTodayTime(divided[2].toUpperCase(Locale.getDefault())) + time = toTodayTime(divided[2].toUpperCase(Locale.getDefault())) if (time == 0L) { sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) return @@ -949,7 +970,7 @@ class SmsCommunicatorPlugin @Inject constructor( tt = Profile.toCurrentUnits(profileFunction, tt) tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction( - timestamp = System.currentTimeMillis(), + timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(ttDuration.toLong()), reason = TemporaryTarget.Reason.EATING_SOON, lowTarget = Profile.toMgdl(tt, profileFunction.getUnits()), @@ -974,7 +995,7 @@ class SmsCommunicatorPlugin @Inject constructor( receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil._now())) + disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now())) .subscribe({ result -> result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } }, { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt index 68018f8f9f..77470340a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt @@ -18,7 +18,8 @@ import javax.inject.Singleton @Singleton class OneTimePassword @Inject constructor( private val sp: SP, - private val resourceHelper: ResourceHelper + private val resourceHelper: ResourceHelper, + private val dateUtil: DateUtil ) { private var key: SecretKey? = null @@ -85,7 +86,7 @@ class OneTimePassword @Inject constructor( return OneTimePasswordValidationResult.ERROR_WRONG_PIN } - val counter: Long = DateUtil.now() / 30000L + val counter: Long = dateUtil.now() / 30000L val acceptableTokens: MutableList = mutableListOf(generateOneTimePassword(counter)) for (i in 0 until Constants.OTP_ACCEPT_OLD_TOKENS_COUNT) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt index 99b86b990d..cd15fac40d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt @@ -151,7 +151,7 @@ class TidepoolUploader @Inject constructor( if (session.datasetReply == null) { rxBus.send(EventTidepoolStatus(("Creating new dataset"))) val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!, - OpenDatasetRequestMessage(activePlugin.activePump.serialNumber()).getBody()) + OpenDatasetRequestMessage(activePlugin.activePump.serialNumber(), dateUtil).getBody()) call.enqueue(TidepoolCallback(aapsLogger, rxBus, session, "Open New Dataset", { connectionStatus = ConnectionStatus.CONNECTED rxBus.send(EventTidepoolStatus(("New dataset OK"))) @@ -232,7 +232,7 @@ class TidepoolUploader @Inject constructor( } private fun uploadNext() { - if (uploadChunk.getLastEnd() < DateUtil.now() - T.mins(1).msecs()) { + if (uploadChunk.getLastEnd() < dateUtil.now() - T.mins(1).msecs()) { SystemClock.sleep(3000) aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd())) doUpload() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index 7fcf269e98..573147c14c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -13,7 +13,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.tidepool.elements.* import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -29,7 +28,6 @@ class UploadChunk @Inject constructor( private val rxBus: RxBusWrapper, private val aapsLogger: AAPSLogger, private val profileFunction: ProfileFunction, - private val treatmentsPlugin: TreatmentsPlugin, private val activePlugin: ActivePluginProvider, private val databaseHelper: DatabaseHelperInterface, private val repository: AppRepository, @@ -43,7 +41,7 @@ class UploadChunk @Inject constructor( return null session.start = getLastEnd() - session.end = min(session.start + maxUploadSize, DateUtil.now()) + session.end = min(session.start + maxUploadSize, dateUtil.now()) val result = get(session.start, session.end) if (result.length < 3) { @@ -83,7 +81,7 @@ class UploadChunk @Inject constructor( fun getLastEnd(): Long { val result = sp.getLong(R.string.key_tidepool_last_end, 0) - return max(result, DateUtil.now() - T.months(2).msecs()) + return max(result, dateUtil.now() - T.months(2).msecs()) } fun setLastEnd(time: Long) { @@ -103,7 +101,7 @@ class UploadChunk @Inject constructor( // TODO we could make sure we include records older than the first bg record for completeness val start: Long = 0 - val end = DateUtil.now() + val end = dateUtil.now() val bgReadingList = repository.compatGetBgReadingsDataFromTime(start, end, true) .blockingGet() @@ -117,19 +115,19 @@ class UploadChunk @Inject constructor( repository.getBolusesDataFromTimeToTime(start, end, true) .blockingGet() .forEach { bolus -> - result.add(BolusElement(bolus)) + result.add(BolusElement(bolus, dateUtil)) } repository.getCarbsDataFromTimeToTimeExpanded(start, end, true) .blockingGet() .forEach { carb -> - result.add(WizardElement(carb)) + result.add(WizardElement(carb, dateUtil)) } return result } private fun getBloodTests(start: Long, end: Long): List { val readings = repository.compatGetTherapyEventDataFromToTime(start, end).blockingGet() - val selection = BloodGlucoseElement.fromCareportalEvents(readings) + val selection = BloodGlucoseElement.fromCareportalEvents(readings, dateUtil) if (selection.isNotEmpty()) rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload")) return selection @@ -139,7 +137,7 @@ class UploadChunk @Inject constructor( private fun getBgReadings(start: Long, end: Long): List { val readings = repository.compatGetBgReadingsDataFromTime(start, end, true) .blockingGet() - val selection = SensorGlucoseElement.fromBgReadings(readings) + val selection = SensorGlucoseElement.fromBgReadings(readings, dateUtil) if (selection.isNotEmpty()) rxBus.send(EventTidepoolStatus("${selection.size} CGMs selected for upload")) return selection @@ -150,7 +148,7 @@ class UploadChunk @Inject constructor( for (tbr in tbrList) { if (tbr.timestamp in start..end) profileFunction.getProfile(tbr.timestamp)?.let { - results.add(BasalElement(tbr, it)) + results.add(BasalElement(tbr, it, dateUtil)) } } return results @@ -165,7 +163,7 @@ class UploadChunk @Inject constructor( } private fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try { - ProfileElement(ps, activePlugin.activePump.serialNumber()) + ProfileElement(ps, activePlugin.activePump.serialNumber(), dateUtil) } catch (e: Throwable) { null } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt index a72e4c15cf..905b3d6cf4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt @@ -4,10 +4,11 @@ import com.google.gson.annotations.Expose import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.entities.TemporaryBasal import info.nightscout.androidaps.extensions.convertedToAbsolute +import info.nightscout.androidaps.utils.DateUtil import java.util.* -class BasalElement(tbr: TemporaryBasal, private val profile: Profile) - : BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString()) { +class BasalElement(tbr: TemporaryBasal, private val profile: Profile, dateUtil: DateUtil) + : BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString(), dateUtil) { internal var timestamp: Long = 0 // not exposed diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BaseElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BaseElement.kt index 96900e62d6..49aa6eae18 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BaseElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BaseElement.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.utils.DateUtil -open class BaseElement(timestamp: Long, uuid: String) { +open class BaseElement(timestamp: Long, uuid: String, dateUtil: DateUtil) { @Expose var deviceTime: String = "" @Expose @@ -16,9 +16,9 @@ open class BaseElement(timestamp: Long, uuid: String) { var origin: Origin? = null init { - deviceTime = DateUtil.toISONoZone(timestamp) - time = DateUtil.toISOAsUTC(timestamp) - timezoneOffset = DateUtil.getTimeZoneOffsetMinutes(timestamp) // TODO + deviceTime = dateUtil.toISONoZone(timestamp) + time = dateUtil.toISOAsUTC(timestamp) + timezoneOffset = dateUtil.getTimeZoneOffsetMinutes(timestamp) // TODO origin = Origin(uuid) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BloodGlucoseElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BloodGlucoseElement.kt index ffee11c3db..9a70c34049 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BloodGlucoseElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BloodGlucoseElement.kt @@ -4,10 +4,11 @@ import com.google.gson.annotations.Expose import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.extensions.toConstant +import info.nightscout.androidaps.utils.DateUtil import java.util.* -class BloodGlucoseElement(therapyEvent: TherapyEvent) - : BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString()) { +class BloodGlucoseElement(therapyEvent: TherapyEvent, dateUtil: DateUtil) + : BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString(), dateUtil) { @Expose var subType: String = "manual" @@ -28,13 +29,13 @@ class BloodGlucoseElement(therapyEvent: TherapyEvent) companion object { - fun fromCareportalEvents(careportalList: List): List { + fun fromCareportalEvents(careportalList: List, dateUtil: DateUtil): List { val results = LinkedList() for (bt in careportalList) { if (bt.type == TherapyEvent.Type.NS_MBG || bt.type == TherapyEvent.Type.FINGER_STICK_BG_VALUE) { - val bge = BloodGlucoseElement(bt) + val bge = BloodGlucoseElement(bt, dateUtil) if (bge.value > 0) - results.add(BloodGlucoseElement(bt)) + results.add(BloodGlucoseElement(bt, dateUtil)) } } return results diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt index 51279c7057..6c3a05b0eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt @@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.database.entities.Bolus +import info.nightscout.androidaps.utils.DateUtil import java.util.* -class BolusElement(bolus: Bolus) - : BaseElement(bolus.timestamp, UUID.nameUUIDFromBytes(("AAPS-bolus" + bolus.timestamp).toByteArray()).toString()) { +class BolusElement(bolus: Bolus, dateUtil: DateUtil) + : BaseElement(bolus.timestamp, UUID.nameUUIDFromBytes(("AAPS-bolus" + bolus.timestamp).toByteArray()).toString(), dateUtil) { @Expose var subType = "normal" @Expose var normal: Double = 0.0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/ProfileElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/ProfileElement.kt index dbc9888e3e..46b63d8663 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/ProfileElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/ProfileElement.kt @@ -4,11 +4,12 @@ import com.google.gson.annotations.Expose import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader +import info.nightscout.androidaps.utils.DateUtil import java.util.* import kotlin.collections.ArrayList -class ProfileElement(ps: ProfileSwitch, serialNumber: String) - : BaseElement(ps.date, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.date).toByteArray()).toString()) { +class ProfileElement(ps: ProfileSwitch, serialNumber: String, dateUtil: DateUtil) + : BaseElement(ps.date, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.date).toByteArray()).toString(), dateUtil) { @Expose internal var activeSchedule = "Normal" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/SensorGlucoseElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/SensorGlucoseElement.kt index da769f902e..cd9538018a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/SensorGlucoseElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/SensorGlucoseElement.kt @@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.database.entities.GlucoseValue +import info.nightscout.androidaps.utils.DateUtil import java.util.* -class SensorGlucoseElement(bgReading: GlucoseValue) - : BaseElement(bgReading.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.timestamp).toByteArray()).toString()) { +class SensorGlucoseElement(bgReading: GlucoseValue, private val dateUtil: DateUtil) + : BaseElement(bgReading.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.timestamp).toByteArray()).toString(), dateUtil) { @Expose internal var units: String = "mg/dL" @@ -20,10 +21,10 @@ class SensorGlucoseElement(bgReading: GlucoseValue) companion object { - internal fun fromBgReadings(bgReadingList: List): List { + internal fun fromBgReadings(bgReadingList: List, dateUtil: DateUtil): List { val results = LinkedList() for (bgReading in bgReadingList) { - results.add(SensorGlucoseElement(bgReading)) + results.add(SensorGlucoseElement(bgReading, dateUtil)) } return results } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt index cb5c0c2136..a6615e45a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt @@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Carbs +import info.nightscout.androidaps.utils.DateUtil import java.util.* -class WizardElement(carbs: Carbs) - : BaseElement(carbs.timestamp, UUID.nameUUIDFromBytes(("AAPS-wizard" + carbs.timestamp).toByteArray()).toString()) { +class WizardElement(carbs: Carbs, dateUtil: DateUtil) + : BaseElement(carbs.timestamp, UUID.nameUUIDFromBytes(("AAPS-wizard" + carbs.timestamp).toByteArray()).toString(), dateUtil) { @Expose var units = "mg/dL" @Expose var carbInput: Double = 0.toDouble() @@ -21,7 +22,7 @@ class WizardElement(carbs: Carbs) timestamp = carbs.timestamp, type = Bolus.Type.NORMAL ) - bolus = BolusElement(fake) // fake insulin record + bolus = BolusElement(fake, dateUtil) // fake insulin record } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt index aff358ba08..e2e0caf8ae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt @@ -1,12 +1,12 @@ package info.nightscout.androidaps.plugins.general.tidepool.events import info.nightscout.androidaps.events.Event -import info.nightscout.androidaps.utils.DateUtil import java.text.SimpleDateFormat import java.util.* class EventTidepoolStatus(val status: String) : Event() { - var date: Long = DateUtil.now() + + var date: Long = System.currentTimeMillis() private var timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/messages/OpenDatasetRequestMessage.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/messages/OpenDatasetRequestMessage.kt index e6fd2c63dd..631a0259bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/messages/OpenDatasetRequestMessage.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/messages/OpenDatasetRequestMessage.kt @@ -7,46 +7,62 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import java.util.* -class OpenDatasetRequestMessage (val serialNumber : String): BaseMessage() { +class OpenDatasetRequestMessage(serialNumber: String, dateUtil: DateUtil) : BaseMessage() { @Expose var deviceId: String = TidepoolUploader.PUMP_TYPE + ":" + serialNumber + @Expose - var time: String = DateUtil.toISOAsUTC(DateUtil.now()) + var time: String = dateUtil.toISOAsUTC(System.currentTimeMillis()) + @Expose - var timezoneOffset = (DateUtil.getTimeZoneOffsetMs() / T.mins(1).msecs()).toInt() + var timezoneOffset = (dateUtil.getTimeZoneOffsetMs() / T.mins(1).msecs()).toInt() + @Expose var type = "upload" + //public String byUser; @Expose var client = ClientInfo() + @Expose - var computerTime: String = DateUtil.toISONoZone(DateUtil.now()) + var computerTime: String = dateUtil.toISONoZone(System.currentTimeMillis()) + @Expose var dataSetType = "continuous" + @Expose var deviceManufacturers = arrayOf(TidepoolUploader.PUMP_TYPE) + @Expose var deviceModel = TidepoolUploader.PUMP_TYPE + @Expose var deviceTags = arrayOf("bgm", "cgm", "insulin-pump") + @Expose var deduplicator = Deduplicator() + @Expose var timeProcessing = "none" + @Expose var timezone: String = TimeZone.getDefault().id + @Expose var version = BuildConfig.VERSION_NAME inner class ClientInfo { + @Expose val name = BuildConfig.APPLICATION_ID + @Expose val version = TidepoolUploader.VERSION } inner class Deduplicator { + @Expose val name = "org.tidepool.deduplicator.dataset.delete.origin" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt index 3169adcd94..020e6714f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/utils/RateLimit.kt @@ -21,13 +21,13 @@ class RateLimit @Inject constructor( fun rateLimit(name: String, seconds: Int): Boolean { // check if over limit rateLimits[name]?.let { - if (dateUtil._now() - it < T.secs(seconds.toLong()).msecs()) { + if (dateUtil.now() - it < T.secs(seconds.toLong()).msecs()) { aapsLogger.debug(LTag.TIDEPOOL, "$name rate limited: $seconds seconds") return false } } // not over limit - rateLimits[name] = dateUtil._now() + rateLimits[name] = dateUtil.now() return true } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 1fe3c26e11..cfc399335d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -220,7 +220,7 @@ class ActionStringHandler @Inject constructor( } val format = DecimalFormat("0.00") val formatInt = DecimalFormat("0") - val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, tempTarget, @@ -457,7 +457,7 @@ class ActionStringHandler @Inject constructor( } val profile = profileFunction.getProfile() ?: return "No profile set :(" //Check for Temp-Target: - val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing) { ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, Constants.MGDL, profileFunction.getUnits()) ret += "\nuntil: " + dateUtil.timeString(tempTarget.value.end) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index f4e8cf6d17..a90de3e18a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -192,7 +192,7 @@ open class IobCobCalculatorPlugin @Inject constructor( var dia = Constants.defaultDIA if (profile != null) dia = profile.dia val start = to - T.hours((24 + dia).toLong()).msecs() - if (DateUtil.isCloseToNow(to)) { + if (dateUtil.isCloseToNow(to)) { // if close to now expect there can be some readings with time in close future (caused by wrong time setting) // so read all records bgReadings = repository.compatGetBgReadingsDataFromTime(start, false).blockingGet() @@ -309,7 +309,7 @@ open class IobCobCalculatorPlugin @Inject constructor( } val bData: MutableList = ArrayList() bData.add(InMemoryGlucoseValue(bgReadings[0])) - aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgReadings[0].timestamp) + " lastBgTime: " + "none-first-value" + " " + bgReadings[0].toString()) + aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgReadings[0].timestamp) + " lastBgTime: " + "none-first-value" + " " + bgReadings[0].toString()) var j = 0 for (i in 1 until bgReadings.size) { val bgTime = bgReadings[i].timestamp @@ -333,7 +333,7 @@ open class IobCobCalculatorPlugin @Inject constructor( val newBgReading = InMemoryGlucoseValue(nextBgTime, nextBg.roundToLong().toDouble(), true) //console.error("Interpolated", bData[j]); bData.add(newBgReading) - aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) + aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) elapsedMinutes -= 5 lastBg = nextBg lastBgTime = nextBgTime @@ -341,14 +341,14 @@ open class IobCobCalculatorPlugin @Inject constructor( j++ val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value) bData.add(newBgReading) - aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) + aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) } abs(elapsedMinutes) > 2 -> { j++ val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value) bData.add(newBgReading) - aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) + aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString()) } else -> { @@ -466,7 +466,7 @@ open class IobCobCalculatorPlugin @Inject constructor( } private fun calculateFromTreatmentsAndTemps(time: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal { - val now = DateUtil.now() + val now = dateUtil.now() val bolusIob = calculateIobFromBolusToTime(time).round() val basalIob = getCalculationToTimeTempBasals(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round() // OpenAPSSMB only @@ -551,7 +551,7 @@ open class IobCobCalculatorPlugin @Inject constructor( val autosensData = if (_synchronized) getLastAutosensDataSynchronized(reason) else getLastAutosensData(reason) var displayCob: Double? = null var futureCarbs = 0.0 - val now = DateUtil.now() + val now = dateUtil.now() val carbs = repository.getCarbsDataFromTimeExpanded(now, true).blockingGet() if (autosensData != null) { displayCob = autosensData.cob @@ -658,7 +658,7 @@ open class IobCobCalculatorPlugin @Inject constructor( override fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array { // predict IOB out to DIA plus 30m - val now = DateUtil.now() + val now = dateUtil.now() val len = 4 * 60 / 5 val array = Array(len) { IobTotal(0) } for ((pos, i) in (0 until len).withIndex()) { @@ -772,21 +772,21 @@ open class IobCobCalculatorPlugin @Inject constructor( return if (lastBg.timestamp > System.currentTimeMillis() - T.mins(9).msecs()) lastBg else null } + // roundup to whole minute + fun roundUpTime(time: Long): Long { + return if (time % 60000 == 0L) time else (time / 60000 + 1) * 60000 + } + + override fun convertToJSONArray(iobArray: Array): JSONArray { + val array = JSONArray() + for (i in iobArray.indices) { + array.put(iobArray[i].determineBasalJson(dateUtil)) + } + return array + } + companion object { - // roundup to whole minute - fun roundUpTime(time: Long): Long { - return if (time % 60000 == 0L) time else (time / 60000 + 1) * 60000 - } - - fun convertToJSONArray(iobArray: Array): JSONArray { - val array = JSONArray() - for (i in iobArray.indices) { - array.put(iobArray[i].determineBasalJson()) - } - return array - } - // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 // Returns the value at a given percentile in a sorted numeric array. // "Linear interpolation between closest ranks" method @@ -809,7 +809,7 @@ open class IobCobCalculatorPlugin @Inject constructor( fun range(): Long = ((profileFunction.getProfile()?.dia ?: Constants.defaultDIA) * 60 * 60 * 1000).toLong() - override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil._now()) + override fun calculateIobFromBolus(): IobTotal = calculateIobFromBolusToTime(dateUtil.now()) override fun calculateIobFromBolusToTime(toTime: Long): IobTotal { val total = IobTotal(toTime) @@ -842,7 +842,7 @@ open class IobCobCalculatorPlugin @Inject constructor( private fun calculateIobToTimeFromExtendedBoluses(toTime: Long): IobTotal { val total = IobTotal(toTime) - val now = dateUtil._now() + val now = dateUtil.now() val pumpInterface = activePlugin.activePump if (!pumpInterface.isFakingTempsByExtendedBoluses) { val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() @@ -906,11 +906,11 @@ open class IobCobCalculatorPlugin @Inject constructor( } override fun calculateIobFromTempBasalsIncludingConvertedExtended(): IobTotal = - calculateIobToTimeFromTempBasalsIncludingConvertedExtended(dateUtil._now()) + calculateIobToTimeFromTempBasalsIncludingConvertedExtended(dateUtil.now()) override fun calculateIobToTimeFromTempBasalsIncludingConvertedExtended(toTime: Long): IobTotal { val total = IobTotal(toTime) - val now = dateUtil._now() + val now = dateUtil.now() val pumpInterface = activePlugin.activePump val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() @@ -947,7 +947,7 @@ open class IobCobCalculatorPlugin @Inject constructor( open fun getCalculationToTimeTempBasals(toTime: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal { val total = IobTotal(toTime) val pumpInterface = activePlugin.activePump - val now = dateUtil._now() + val now = dateUtil.now() val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() for (pos in temporaryBasals.indices) { val t = temporaryBasals[pos] diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt index ab3fe43111..299e7e3f74 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.kt @@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress @@ -67,7 +66,7 @@ class IobCobOref1Thread internal constructor( } override fun run() { - val start = DateUtil.now() + val start = dateUtil.now() mWakeLock?.acquire(T.mins(10).msecs()) try { aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: $from") @@ -89,7 +88,7 @@ class IobCobOref1Thread internal constructor( aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from") return } - val prevDataTime = roundUpTime(bucketedData[bucketedData.size - 3].timestamp) + val prevDataTime = iobCobCalculatorPlugin.roundUpTime(bucketedData[bucketedData.size - 3].timestamp) aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime)) var previous = autosensDataTable[prevDataTime] // start from oldest to be able sub cob @@ -103,8 +102,8 @@ class IobCobOref1Thread internal constructor( } // check if data already exists var bgTime = bucketedData[i].timestamp - bgTime = roundUpTime(bgTime) - if (bgTime > roundUpTime(DateUtil.now())) continue + bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime) + if (bgTime > iobCobCalculatorPlugin.roundUpTime(dateUtil.now())) continue var existing: AutosensData? if (autosensDataTable[bgTime].also { existing = it } != null) { previous = existing @@ -294,7 +293,7 @@ class IobCobOref1Thread internal constructor( // TODO AS-FIX @Suppress("SimplifyBooleanWithConstants") if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { - val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tempTarget is ValueWrapper.Existing && tempTarget.value.target() >= 100) { autosensData.extraDeviation.add(-(tempTarget.value.target() - 100) / 20) } @@ -307,7 +306,7 @@ class IobCobOref1Thread internal constructor( val hours = calendar[Calendar.HOUR_OF_DAY] if (min in 0..4 && hours % 2 == 0) autosensData.extraDeviation.add(0.0) previous = autosensData - if (bgTime < DateUtil.now()) autosensDataTable.put(bgTime, autosensData) + if (bgTime < dateUtil.now()) autosensDataTable.put(bgTime, autosensData) aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()) val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime) aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt index 7d429eda78..ea8af5eb8e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.kt @@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress @@ -66,7 +65,7 @@ class IobCobThread @Inject internal constructor( } override fun run() { - val start = DateUtil.now() + val start = dateUtil.now() mWakeLock?.acquire(T.mins(10).msecs()) try { aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: $from") @@ -88,7 +87,7 @@ class IobCobThread @Inject internal constructor( aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from") return } - val prevDataTime = roundUpTime(bucketedData[bucketedData.size - 3].timestamp) + val prevDataTime = iobCobCalculatorPlugin.roundUpTime(bucketedData[bucketedData.size - 3].timestamp) aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime)) var previous = autosensDataTable[prevDataTime] // start from oldest to be able sub cob @@ -102,8 +101,8 @@ class IobCobThread @Inject internal constructor( } // check if data already exists var bgTime = bucketedData[i].timestamp - bgTime = roundUpTime(bgTime) - if (bgTime > roundUpTime(DateUtil.now())) continue + bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime) + if (bgTime > iobCobCalculatorPlugin.roundUpTime(dateUtil.now())) continue var existing: AutosensData? if (autosensDataTable[bgTime].also { existing = it } != null) { previous = existing @@ -254,7 +253,7 @@ class IobCobThread @Inject internal constructor( autosensData.pastSensitivity += "C" } previous = autosensData - if (bgTime < DateUtil.now()) autosensDataTable.put(bgTime, autosensData) + if (bgTime < dateUtil.now()) autosensDataTable.put(bgTime, autosensData) aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()) val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime) aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index 9976b3a5e8..ff4d41b6b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -34,6 +34,7 @@ class LocalProfilePlugin @Inject constructor( private val sp: SP, private val profileFunction: ProfileFunction, private val nsUpload: NSUpload, + private val dateUtil: DateUtil, private val uel: UserEntryLogger ) : PluginBase(PluginDescription() .mainType(PluginType.PROFILE) @@ -203,7 +204,7 @@ class LocalProfilePlugin @Inject constructor( fun copyFrom(profile: Profile, newName: String): SingleProfile { var verifiedName = newName if (rawProfile?.getSpecificProfile(newName) != null) { - verifiedName += " " + DateUtil.now().toString() + verifiedName += " " + dateUtil.now().toString() } val sp = SingleProfile() sp.name = verifiedName @@ -340,7 +341,7 @@ class LocalProfilePlugin @Inject constructor( } } if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name) - json.put("startDate", DateUtil.toISOAsUTC(DateUtil.now())) + json.put("startDate", dateUtil.toISOAsUTC(dateUtil.now())) json.put("store", store) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index e5f6269b74..d6869ad370 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -36,6 +36,7 @@ class NSProfileFragment : DaggerFragment() { @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var nsProfilePlugin: NSProfilePlugin @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger private var disposable: CompositeDisposable = CompositeDisposable() @@ -67,7 +68,7 @@ class NSProfileFragment : DaggerFragment() { uel.log(Action.PROFILE_SWITCH, Sources.NSProfile, ValueWithUnit.SimpleString(name), ValueWithUnit.Percent(100)) - treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) + treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, dateUtil.now()) }) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt index a260ed0482..609d753704 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt @@ -79,7 +79,7 @@ class MDIPlugin @Inject constructor( timestamp = detailedBolusInfo.timestamp, amount = detailedBolusInfo.insulin, type = detailedBolusInfo.bolusType, - pumpId = dateUtil._now(), + pumpId = dateUtil.now(), pumpType = PumpType.MDI, pumpSerial = serialNumber()) if (detailedBolusInfo.carbs > 0) @@ -142,10 +142,10 @@ class MDIPlugin @Inject constructor( status.put("status", "normal") extended.put("Version", version) extended.put("ActiveProfile", profileName) - status.put("timestamp", DateUtil.toISOString(now)) + status.put("timestamp", dateUtil.toISOString(now)) pump.put("status", status) pump.put("extended", extended) - pump.put("clock", DateUtil.toISOString(now)) + pump.put("clock", dateUtil.toISOString(now)) } catch (e: JSONException) { aapsLogger.error("Exception: ", e) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt index 527e66eb3d..f2eb4bb5e1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt @@ -95,9 +95,9 @@ class VirtualPumpFragment : DaggerFragment() { if (_binding == null) return val profile = profileFunction.getProfile() ?: return binding.basabasalrate.text = resourceHelper.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate) - binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil._now())?.toStringFull(profile, dateUtil) + binding.tempbasal.text = iobCobCalculator.getTempBasal(dateUtil.now())?.toStringFull(profile, dateUtil) ?: "" - binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil._now())?.toStringFull(dateUtil) + binding.extendedbolus.text = iobCobCalculator.getExtendedBolus(dateUtil.now())?.toStringFull(dateUtil) ?: "" binding.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent) binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index bfa0c7a44f..5c15fa88d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -206,7 +206,7 @@ open class VirtualPumpPlugin @Inject constructor( timestamp = detailedBolusInfo.timestamp, amount = detailedBolusInfo.insulin, type = detailedBolusInfo.bolusType, - pumpId = dateUtil._now(), + pumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber()) if (detailedBolusInfo.carbs > 0) @@ -229,12 +229,12 @@ open class VirtualPumpPlugin @Inject constructor( result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) pumpSync.syncTemporaryBasalWithPumpId( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), rate = absoluteRate, duration = T.mins(durationInMinutes.toLong()).msecs(), isAbsolute = true, type = tbrType, - pumpId = dateUtil._now(), + pumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber() ) @@ -254,12 +254,12 @@ open class VirtualPumpPlugin @Inject constructor( result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) pumpSync.syncTemporaryBasalWithPumpId( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), rate = percent.toDouble(), duration = T.mins(durationInMinutes.toLong()).msecs(), isAbsolute = false, type = tbrType, - pumpId = dateUtil._now(), + pumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber() ) @@ -279,11 +279,11 @@ open class VirtualPumpPlugin @Inject constructor( result.duration = durationInMinutes result.comment = resourceHelper.gs(R.string.virtualpump_resultok) pumpSync.syncExtendedBolusWithPumpId( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), amount = insulin, duration = T.mins(durationInMinutes.toLong()).msecs(), isEmulatingTB = false, - pumpId = dateUtil._now(), + pumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber() ) @@ -301,8 +301,8 @@ open class VirtualPumpPlugin @Inject constructor( if (pumpSync.expectedPumpState().temporaryBasal != null) { result.enacted = true pumpSync.syncStopTemporaryBasalWithPumpId( - timestamp = dateUtil._now(), - endPumpId = dateUtil._now(), + timestamp = dateUtil.now(), + endPumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber() ) @@ -317,8 +317,8 @@ open class VirtualPumpPlugin @Inject constructor( val result = PumpEnactResult(injector) if (pumpSync.expectedPumpState().extendedBolus != null) { pumpSync.syncStopExtendedBolusWithPumpId( - timestamp = dateUtil._now(), - endPumpId = dateUtil._now(), + timestamp = dateUtil.now(), + endPumpId = dateUtil.now(), pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpSerial = serialNumber() ) @@ -362,12 +362,12 @@ open class VirtualPumpPlugin @Inject constructor( extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp)) extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) } - status.put("timestamp", DateUtil.toISOString(now)) + status.put("timestamp", dateUtil.toISOString(now)) pump.put("battery", battery) pump.put("status", status) pump.put("extended", extended) pump.put("reservoir", reservoirInUnits) - pump.put("clock", DateUtil.toISOString(now)) + pump.put("clock", dateUtil.toISOString(now)) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt index b232b03db3..7fee06f5a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.extensions.isEvent5minBack import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription @@ -16,9 +17,8 @@ import info.nightscout.androidaps.interfaces.SensitivityInterface.SensitivityTyp import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.extensions.isEvent5minBack import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException @@ -30,10 +30,10 @@ import kotlin.math.roundToInt @Singleton open class SensitivityAAPSPlugin @Inject constructor( - injector: HasAndroidInjector?, - aapsLogger: AAPSLogger?, - resourceHelper: ResourceHelper?, - sp: SP?, + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + sp: SP, private val profileFunction: ProfileFunction, private val dateUtil: DateUtil, private val databaseHelper: DatabaseHelperInterface, @@ -45,7 +45,7 @@ open class SensitivityAAPSPlugin @Inject constructor( .shortName(R.string.sensitivity_shortname) .preferencesId(R.xml.pref_absorption_aaps) .description(R.string.description_sensitivity_aaps), - injector!!, aapsLogger!!, resourceHelper!!, sp!! + injector, aapsLogger, resourceHelper, sp ) { override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult { @@ -116,7 +116,7 @@ open class SensitivityAAPSPlugin @Inject constructor( val sensResult: String aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") Arrays.sort(deviations) - val percentile = percentile(deviations, 0.50) + val percentile = IobCobCalculatorPlugin.percentile(deviations, 0.50) val basalOff = percentile * (60.0 / 5.0) / sens val ratio = 1 + basalOff / profile.maxDailyBasal sensResult = when { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt index 6627a37efe..42cf28d3cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.extensions.isEvent5minBack import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.PluginDescription @@ -17,9 +18,8 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.percentile +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.extensions.isEvent5minBack import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException @@ -163,8 +163,8 @@ open class SensitivityOref1Plugin @Inject constructor( val sens = profile.isfMgdl aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") Arrays.sort(deviations) - val pSensitive = percentile(deviations, 0.50) - val pResistant = percentile(deviations, 0.50) + val pSensitive = IobCobCalculatorPlugin.percentile(deviations, 0.50) + val pResistant = IobCobCalculatorPlugin.percentile(deviations, 0.50) var basalOff = 0.0 when { pSensitive < 0 -> { // sensitive diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 29de0b842c..44046a3258 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -84,6 +84,7 @@ class DexcomPlugin @Inject constructor( @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var dataWorker: DataWorker @Inject lateinit var broadcastToXDrip: XDripBroadcast @Inject lateinit var repository: AppRepository @@ -124,7 +125,7 @@ class DexcomPlugin @Inject constructor( for (i in 0 until meters.size()) { meters.getBundle(i.toString())?.let { val timestamp = it.getLong("timestamp") * 1000 - val now = DateUtil.now() + val now = dateUtil.now() if (timestamp > now - T.months(1).msecs() && timestamp < now) { calibrations.add(CgmSourceTransaction.Calibration( timestamp = it.getLong("timestamp") * 1000, diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index 734bec03f5..ad9fc19c72 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -127,12 +127,12 @@ class NSClientSourcePlugin @Inject constructor( val glucoseValues = mutableListOf() for (i in 0 until sgvs.length()) { val sgv = toGv(sgvs.getJSONObject(i)) ?: continue - if (sgv.timestamp < dateUtil._now() && sgv.timestamp > latestDateInReceivedData) latestDateInReceivedData = sgv.timestamp + if (sgv.timestamp < dateUtil.now() && sgv.timestamp > latestDateInReceivedData) latestDateInReceivedData = sgv.timestamp glucoseValues += sgv } // Was that sgv more less 5 mins ago ? - if (T.msecs(dateUtil._now() - latestDateInReceivedData).mins() < 5L) { + if (T.msecs(dateUtil.now() - latestDateInReceivedData).mins() < 5L) { rxBus.send(EventDismissNotification(Notification.NS_ALARM)) rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM)) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index 49d30ea7f7..a0eaf0ddfd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable @@ -103,7 +102,7 @@ class RandomBgPlugin @Inject constructor( val glucoseValues = mutableListOf() glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), value = bgMgdl, raw = 0.0, noise = null, diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt index ff941b4af9..8d9951c490 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt @@ -127,6 +127,6 @@ class TreatmentsFragment : DaggerFragment() { private fun updateGui() { if (_binding == null) return - binding.extendedBoluses.visibility = (activePlugin.activePump.pumpDescription.isExtendedBolusCapable || iobCobCalculator.getExtendedBolus(dateUtil._now()) != null).toVisibility() + binding.extendedBoluses.visibility = (activePlugin.activePump.pumpDescription.isExtendedBolusCapable || iobCobCalculator.getExtendedBolus(dateUtil.now()) != null).toVisibility() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index ce54206dbe..a665e53368 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -147,7 +147,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private void initializeProfileSwitchData(long range) { getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData"); synchronized (profiles) { - profiles.reset().add(databaseHelper.getProfileSwitchData(DateUtil.now() - range, false)); + profiles.reset().add(databaseHelper.getProfileSwitchData(dateUtil.now() - range, false)); } } @@ -161,7 +161,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Deprecated @Override public List getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) { - return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil._now(), true) + return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil.now(), true) .blockingGet() .stream() .map(bolus -> new Treatment(getInjector(), bolus)) @@ -360,7 +360,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); databaseHelper.createOrUpdate(profileSwitch); - nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date); + nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date, dateUtil); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt index e530d9dc6e..c94a00f068 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusCarbsFragment.kt @@ -113,7 +113,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.deletefuturetreatments) + "?", Runnable { uel.log(Action.DELETE_FUTURE_TREATMENTS, Sources.Treatments) repository - .getBolusesDataFromTime(dateUtil._now(), false) + .getBolusesDataFromTime(dateUtil.now(), false) .observeOn(aapsSchedulers.main) .subscribe { list -> list.forEach { bolus -> @@ -125,7 +125,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { } } repository - .getCarbsDataFromTime(dateUtil._now(), false) + .getCarbsDataFromTime(dateUtil.now(), false) .observeOn(aapsSchedulers.main) .subscribe { list -> list.forEach { carb -> @@ -137,7 +137,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { } } repository - .getBolusCalculatorResultsDataFromTime(dateUtil._now(), false) + .getBolusCalculatorResultsDataFromTime(dateUtil.now(), false) .observeOn(aapsSchedulers.main) .subscribe { list -> list.forEach { bolusCalc -> @@ -281,7 +281,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() { val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia) holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iobContrib) if (iob.iobContrib != 0.0) holder.binding.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.binding.iob.setTextColor(holder.binding.carbs.currentTextColor) - if (bolus.timestamp > dateUtil._now()) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor) + if (bolus.timestamp > dateUtil.now()) holder.binding.date.setTextColor(resourceHelper.gc(R.color.colorScheduled)) else holder.binding.date.setTextColor(holder.binding.carbs.currentTextColor) holder.binding.mealOrCorrection.text = when (ml.bolus.type) { Bolus.Type.SMB -> "SMB" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index 55c12374ef..4c90c80e08 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -165,7 +165,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility() holder.binding.date.text = dateUtil.dateAndTimeString(therapyEvent.timestamp) - holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else DateUtil.niceTimeScalar(therapyEvent.duration, resourceHelper) + holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else dateUtil.niceTimeScalar(therapyEvent.duration, resourceHelper) holder.binding.note.text = therapyEvent.note holder.binding.type.text = translator.translate(therapyEvent.type) holder.binding.remove.tag = therapyEvent diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt index a923b6d02e..b05dfb2b40 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt @@ -69,7 +69,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) binding.recyclerview.setHasFixedSize(true) binding.recyclerview.layoutManager = LinearLayoutManager(view.context) - binding.recyclerview.adapter = RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)) + binding.recyclerview.adapter = RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(dateUtil.now() - T.days(30).msecs(), false)) binding.refreshFromNightscout.setOnClickListener { activity?.let { activity -> @@ -108,7 +108,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { fun updateGUI() { if (_binding == null) return - binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false) + binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(dateUtil.now() - T.days(30).msecs(), false)), false) } inner class RecyclerProfileViewAdapter(private var profileSwitchList: List) : RecyclerView.Adapter() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt index 00e46d1d43..78ead608b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.kt @@ -153,7 +153,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { private inner class RecyclerViewAdapter internal constructor(private var tempTargetList: List) : RecyclerView.Adapter() { - private val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + private val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() private val currentlyActiveTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempTargetsViewHolder = @@ -174,7 +174,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() { holder.binding.date.setTextColor( when { tempTarget.id == currentlyActiveTarget?.id -> resourceHelper.gc(R.color.colorActive) - tempTarget.timestamp > DateUtil.now() -> resourceHelper.gc(R.color.colorScheduled) + tempTarget.timestamp > dateUtil.now() -> resourceHelper.gc(R.color.colorScheduled) else -> holder.binding.reasonColon.currentTextColor }) holder.binding.remove.tag = tempTarget diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt index 7fbd7cbab9..c1dee0908d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -171,7 +171,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins()) if (tempBasal.isAbsolute) holder.binding.rate.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.rate) else holder.binding.rate.text = resourceHelper.gs(R.string.format_percent, tempBasal.rate.toInt()) - val now = DateUtil.now() + val now = dateUtil.now() var iob = IobTotal(now) val profile = profileFunction.getProfile(now) if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin) @@ -194,7 +194,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { init { binding.remove.setOnClickListener { v: View -> val tempBasal = v.tag as TemporaryBasal - val profile = profileFunction.getProfile(dateUtil._now()) + val profile = profileFunction.getProfile(dateUtil.now()) ?: return@setOnClickListener context?.let { OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord), diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index fffb7e59b1..2db33b17d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -201,7 +201,7 @@ open class CommandQueue @Inject constructor( if ((detailedBolusInfo.carbs > 0) && (!activePlugin.get().activePump.pumpDescription.storesCarbInfo || detailedBolusInfo.carbsDuration != 0L || - (detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil._now()) + (detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil.now()) ) { disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) .subscribeBy( diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index 7d937ce0c9..4e425da52b 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -23,7 +23,7 @@ class CommandSMBBolus( override fun execute() { val r: PumpEnactResult val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L - if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > dateUtil._now()) { + if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > dateUtil.now()) { aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval") r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval") } else if (detailedBolusInfo.deliverAtTheLatest != 0L && detailedBolusInfo.deliverAtTheLatest + T.mins(1).msecs() > System.currentTimeMillis()) { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index 4b0bd1f534..8cd383cb6b 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -104,9 +104,9 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { if (config.PUMPCONTROL) shouldUploadStatus = true else if (!loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null) shouldUploadStatus = true - else if (DateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true - if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY_IN_MINUTES) && shouldUploadStatus) { - lastIobUpload = dateUtil._now() + else if (dateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true + if (dateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY_IN_MINUTES) && shouldUploadStatus) { + lastIobUpload = dateUtil.now() buildDeviceStatus(dateUtil, loopPlugin, iobCobCalculatorPlugin, profileFunction, activePlugin.activePump, receiverStatusStore, runningConfiguration, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt index 7364bef9a5..313d82308b 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt @@ -16,7 +16,8 @@ import javax.inject.Singleton class ActivityMonitor @Inject constructor( private var aapsLogger: AAPSLogger, private val resourceHelper: ResourceHelper, - private var sp: SP + private val sp: SP, + private val dateUtil: DateUtil ) : Application.ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity?) { @@ -26,10 +27,10 @@ class ActivityMonitor @Inject constructor( aapsLogger.debug(LTag.UI, "onActivityPaused: $name resumed == 0") return } - val elapsed = DateUtil.now() - resumed + val elapsed = dateUtil.now() - resumed val total = sp.getLong("Monitor_" + name + "_total", 0) if (total == 0L) { - sp.putLong("Monitor_" + name + "_start", DateUtil.now()) + sp.putLong("Monitor_" + name + "_start", dateUtil.now()) } sp.putLong("Monitor_" + name + "_total", total + elapsed) aapsLogger.debug(LTag.UI, "onActivityPaused: $name elapsed=$elapsed total=${total + elapsed}") @@ -38,7 +39,7 @@ class ActivityMonitor @Inject constructor( override fun onActivityResumed(activity: Activity?) { val name = activity?.javaClass?.simpleName ?: return aapsLogger.debug(LTag.UI, "onActivityResumed: $name") - sp.putLong("Monitor_" + name + "_" + "resumed", DateUtil.now()) + sp.putLong("Monitor_" + name + "_" + "resumed", dateUtil.now()) } override fun onActivityStarted(activity: Activity?) { @@ -63,9 +64,9 @@ class ActivityMonitor @Inject constructor( if (key.startsWith("Monitor") && key.endsWith("total")) { val v = if (value is Long) value else SafeParse.stringToLong(value as String) val activity = key.split("_")[1].replace("Activity", "") - val duration = DateUtil.niceTimeScalar(v as Long, resourceHelper) + val duration = dateUtil.niceTimeScalar(v as Long, resourceHelper) val start = sp.getLong(key.replace("total", "start"), 0) - val days = T.msecs(DateUtil.now() - start).days() + val days = T.msecs(dateUtil.now() - start).days() result += resourceHelper.gs(R.string.activitymonitorformat, activity, duration, days) } return result diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 5ea46d24fd..d20e0c0cbd 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -30,8 +30,8 @@ class TddCalculator @Inject constructor( ) { fun calculate(days: Long): LongSparseArray { - val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs()) - val endTime = MidnightTime.calc(DateUtil.now()) + val startTime = MidnightTime.calc(dateUtil.now() - T.days(days).msecs()) + val endTime = MidnightTime.calc(dateUtil.now()) val result = LongSparseArray() repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet() diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt index d1f7c74bf1..eaa702f63f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt @@ -26,8 +26,8 @@ class TirCalculator @Inject constructor( fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray { if (lowMgdl < 39) throw RuntimeException("Low below 39") if (lowMgdl > highMgdl) throw RuntimeException("Low > High") - val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs()) - val endTime = MidnightTime.calc(DateUtil.now()) + val startTime = MidnightTime.calc(dateUtil.now() - T.days(days).msecs()) + val endTime = MidnightTime.calc(dateUtil.now()) val bgReadings = repository.compatGetBgReadingsDataFromTime(startTime, endTime, true).blockingGet() val result = LongSparseArray() diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index ab34971cdd..5e9dfb11b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -249,7 +249,7 @@ class BolusWizard @Inject constructor( private fun createBolusCalculatorResult(): BolusCalculatorResult = BolusCalculatorResult( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), targetBGLow = targetBGLow, targetBGHigh = targetBGHigh, isf = sens, @@ -439,7 +439,7 @@ class BolusWizard @Inject constructor( } if (useAlarm && carbs > 0 && carbTime > 0) { - carbTimer.scheduleReminder(dateUtil._now() + T.mins(carbTime.toLong()).msecs()) + carbTimer.scheduleReminder(dateUtil.now() + T.mins(carbTime.toLong()).msecs()) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index 752a053425..5d3496e7e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.extensions.valueToUnits import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject -import java.util.* import javax.inject.Inject class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjector) { @@ -77,7 +76,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec fun isActive(): Boolean = Profile.secondsFromMidnight() >= validFrom() && Profile.secondsFromMidnight() <= validTo() fun doCalc(profile: Profile, profileName: String, lastBG: GlucoseValue, _synchronized: Boolean): BolusWizard { - val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null //BG var bg = 0.0 @@ -129,9 +128,9 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec fun carbs(): Int = safeGetInt(storage, "carbs") - fun validFromDate(): Date = DateUtil.toDate(validFrom()) + fun validFromDate(): Long = dateUtil.secondsOfTheDayToMilliseconds(validFrom()) - fun validToDate(): Date = DateUtil.toDate(validTo()) + fun validToDate(): Long = dateUtil.secondsOfTheDayToMilliseconds(validTo()) fun validFrom(): Int = safeGetInt(storage, "validFrom") diff --git a/app/src/test/java/info/nightscout/androidaps/TestBase.kt b/app/src/test/java/info/nightscout/androidaps/TestBase.kt index ff88739ba2..0a544ea43d 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBase.kt @@ -1,10 +1,13 @@ package info.nightscout.androidaps +import android.content.Context import info.nightscout.androidaps.logging.AAPSLoggerTest +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import org.junit.Before import org.junit.Rule +import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoRule diff --git a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index bb20d622d0..aaa049d04c 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps +import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.Profile @@ -25,10 +26,10 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction - @Mock lateinit var defaultValueHelper: DefaultValueHelper - @Mock lateinit var dateUtil: DateUtil @Mock lateinit var configInterface: ConfigInterface + @Mock lateinit var context: Context + lateinit var dateUtil: DateUtil val rxBus = RxBusWrapper(aapsSchedulers) val profileInjector = HasAndroidInjector { @@ -40,6 +41,7 @@ open class TestBaseWithProfile : TestBase() { it.rxBus = rxBus it.fabricPrivacy = fabricPrivacy it.configInterface = configInterface + it.dateUtil = dateUtil } if (it is ProfileSwitch) { it.treatmentsPlugin = treatmentsInterface @@ -58,6 +60,7 @@ open class TestBaseWithProfile : TestBase() { @Before fun prepareMock() { validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" + dateUtil = DateUtil(context) validProfile = Profile(profileInjector, JSONObject(validProfileJSON), Constants.MGDL) } diff --git a/app/src/test/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileTest.kt b/app/src/test/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileTest.kt index e97e63bafa..76cf88f4ff 100644 --- a/app/src/test/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileTest.kt @@ -1,29 +1,25 @@ package info.nightscout.androidaps.data.defaultProfile -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.TestBaseWithProfile import org.junit.Assert.assertEquals import org.junit.Test -class DefaultProfileTest : TestBase() { - - val injector = HasAndroidInjector { AndroidInjector { } } +class DefaultProfileTest : TestBaseWithProfile() { @Test fun profile() { - var p = DefaultProfile(injector).profile(5.0, 5.1 / 0.3, 0.0, Constants.MMOL) + var p = DefaultProfile(profileInjector).profile(5.0, 5.1 / 0.3, 0.0, Constants.MMOL) assertEquals(0.150, p!!.getBasalTimeFromMidnight(0), 0.001) assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(11.8, p.getIsfTimeFromMidnight(0), 0.001) - p = DefaultProfile(injector).profile(7.0, 10.0 / 0.4, 0.0, Constants.MMOL) + p = DefaultProfile(profileInjector).profile(7.0, 10.0 / 0.4, 0.0, Constants.MMOL) assertEquals(0.350, p!!.getBasalTimeFromMidnight(0), 0.001) assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(6.8, p.getIsfTimeFromMidnight(0), 0.001) - p = DefaultProfile(injector).profile(12.0, 25.0 / 0.5, 0.0, Constants.MMOL) + p = DefaultProfile(profileInjector).profile(12.0, 25.0 / 0.5, 0.0, Constants.MMOL) assertEquals(0.80, p!!.getBasalTimeFromMidnight(0), 0.001) assertEquals(10.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(2.2, p.getIsfTimeFromMidnight(0), 0.001) diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index 755802360a..41789d524d 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -63,7 +63,6 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage - @Mock lateinit var context: Context @Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var profiler: Profiler @@ -92,6 +91,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { AndroidInjector { if (it is Objective) { it.sp = sp + it.dateUtil = dateUtil } if (it is PumpEnactResult) { it.resourceHelper = resourceHelper @@ -137,13 +137,13 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) constraintChecker = ConstraintChecker(activePlugin) - val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) + val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) - comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), dateUtil, uel) + comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync, dateUtil) danaRPlugin = DanaRPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, activePlugin, sp, commandQueue, danaPump, dateUtil, fabricPrivacy, pumpSync) danaRSPlugin = DanaRSPlugin(injector, aapsLogger, aapsSchedulers, rxBus, context, resourceHelper, constraintChecker, profileFunction, sp, commandQueue, danaPump, pumpSync, detailedBolusInfoStorage, temporaryBasalStorage, fabricPrivacy, dateUtil) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, pumpSync) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index 8d40547190..a940f09a5a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -31,7 +31,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ConstraintChecker::class, ReceiverStatusStore::class, RunningConfiguration::class, UserEntryLogger::class) +@PrepareForTest(ConstraintChecker::class, ReceiverStatusStore::class, RunningConfiguration::class, UserEntryLogger::class, DateUtil::class) class LoopPluginTest : TestBase() { @Mock lateinit var sp: SP diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt index 8c4f0bac87..81c12437cf 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt @@ -21,13 +21,14 @@ import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner -@PrepareForTest(UserEntryLogger::class) @RunWith(PowerMockRunner::class) +@PrepareForTest(UserEntryLogger::class, DateUtil::class) class ObjectivesPluginTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var sp: SP + @Mock lateinit var dateUtil: DateUtil @Mock lateinit var uel: UserEntryLogger private lateinit var objectivesPlugin: ObjectivesPlugin @@ -37,12 +38,13 @@ class ObjectivesPluginTest : TestBase() { if (it is Objective) { it.sp = sp it.resourceHelper = resourceHelper + it.dateUtil = dateUtil } } } @Before fun prepareMock() { - objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) + objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), dateUtil, uel) objectivesPlugin.onStart() `when`(resourceHelper.gs(R.string.objectivenotstarted)).thenReturn("Objective %1\$d not started") } @@ -53,7 +55,7 @@ class ObjectivesPluginTest : TestBase() { c = objectivesPlugin.isLoopInvocationAllowed(c) Assert.assertEquals("Objectives: Objective 1 not started", c.getReasons(aapsLogger)) Assert.assertEquals(false, c.value()) - objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].startedOn = DateUtil.now() + objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].startedOn = dateUtil.now() } @Test fun notStartedObjective6ShouldLimitClosedLoop() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt index 6531cdea1f..ccb9721bb5 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.constraints.safety -import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config @@ -42,7 +41,6 @@ class SafetyPluginTest : TestBaseWithProfile() { @Mock lateinit var buildHelper: BuildHelper @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin - @Mock lateinit var context: Context @Mock lateinit var repository: AppRepository private lateinit var hardLimits: HardLimits diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt index 882cdbecc2..dcc14fabfc 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt @@ -5,7 +5,6 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult import info.nightscout.androidaps.utils.DateUtil @@ -30,6 +29,7 @@ class AuthRequestTest : TestBase() { @Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var otp: OneTimePassword + @Mock lateinit var dateUtil: DateUtil var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { @@ -38,6 +38,7 @@ class AuthRequestTest : TestBase() { it.resourceHelper = resourceHelper it.smsCommunicatorPlugin = smsCommunicatorPlugin it.otp = otp + it.dateUtil = dateUtil } } } @@ -87,10 +88,10 @@ class AuthRequestTest : TestBase() { // test timed out message val now: Long = 10000 PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) authRequest = AuthRequest(injector, requester, "Request text", "ABC", action) actionCalled = false - PowerMockito.`when`(DateUtil.now()).thenReturn(now + T.mins(Constants.SMS_CONFIRM_TIMEOUT).msecs() + 1) + PowerMockito.`when`(dateUtil.now()).thenReturn(now + T.mins(Constants.SMS_CONFIRM_TIMEOUT).msecs() + 1) authRequest.action("ABC") Assert.assertFalse(actionCalled) } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt index fef4d58ca3..8869464e7b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator -import android.content.Context import android.telephony.SmsManager import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector @@ -44,6 +43,7 @@ import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` +import org.mockito.Mockito.anyLong import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import org.powermock.api.mockito.PowerMockito @@ -56,10 +56,9 @@ import java.util.* ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class, SmsManager::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class, IobCobCalculatorPlugin::class, OneTimePassword::class, UserEntryLogger::class, LoopPlugin::class, - AppRepository::class) + AppRepository::class, DateUtil::class) class SmsCommunicatorPluginTest : TestBaseWithProfile() { - @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var activePlugin: ActivePluginProvider @@ -72,6 +71,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { @Mock lateinit var xdripCalibrations: XdripCalibrations @Mock lateinit var uel: UserEntryLogger @Mock lateinit var repository: AppRepository + @Mock lateinit var dateUtilMocked: DateUtil var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { @@ -83,6 +83,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { it.smsCommunicatorPlugin = smsCommunicatorPlugin it.resourceHelper = resourceHelper it.otp = otp + it.dateUtil = dateUtil } } } @@ -100,7 +101,6 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { `when`(iobCobCalculator.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0)) `when`(iobCobCalculator.lastBg()).thenReturn(reading) - PowerMockito.spy(DateUtil::class.java) PowerMockito.mockStatic(SmsManager::class.java) val smsManager = PowerMockito.mock(SmsManager::class.java) `when`(SmsManager.getDefault()).thenReturn(smsManager) @@ -110,9 +110,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { repository.runTransactionForResult(anyObject()) ).thenReturn(Single.just(InsertTemporaryTargetAndCancelCurrentTransaction.TransactionResult().apply { })) - val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) + val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtilMocked) - smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, Config(), DateUtil(context), uel, glucoseStatusProvider, repository) + smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, Config(), dateUtilMocked, uel, glucoseStatusProvider, repository) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true) Mockito.doAnswer { invocation: InvocationOnMock -> val callback = invocation.getArgument(1) @@ -764,7 +764,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text) - `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20)) + `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20)) //BASAL 20% 30 smsCommunicatorPlugin.messages = ArrayList() @@ -884,7 +884,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) - PowerMockito.`when`(DateUtil.now()).thenReturn(1000L) + PowerMockito.`when`(dateUtilMocked.now()).thenReturn(1000L) `when`(sp.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L) //BOLUS 1 smsCommunicatorPlugin.messages = ArrayList() @@ -893,7 +893,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text) `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) - PowerMockito.`when`(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L) + PowerMockito.`when`(dateUtilMocked.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L) //BOLUS 0 smsCommunicatorPlugin.messages = ArrayList() @@ -989,7 +989,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { } @Test fun processCarbsTest() { - PowerMockito.`when`(DateUtil.now()).thenReturn(1000000L) + PowerMockito.`when`(dateUtilMocked.now()).thenReturn(1000000L) `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false) //CAL smsCommunicatorPlugin.messages = ArrayList() @@ -1005,7 +1005,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) - `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0)) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0)) //CARBS 0 smsCommunicatorPlugin.messages = ArrayList() @@ -1013,7 +1013,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { smsCommunicatorPlugin.processSms(sms) Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) - `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1)) + `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1)) //CARBS 1 smsCommunicatorPlugin.messages = ArrayList() @@ -1041,6 +1041,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) //CARBS 1 12:01 + `when`(dateUtilMocked.timeString(anyLong())).thenReturn("12:01PM") smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 12:01") smsCommunicatorPlugin.processSms(sms) @@ -1052,6 +1053,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() { Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) //CARBS 1 3:01AM + `when`(dateUtilMocked.timeString(anyLong())).thenReturn("03:01AM") smsCommunicatorPlugin.messages = ArrayList() sms = Sms("1234", "CARBS 1 3:01AM") smsCommunicatorPlugin.processSms(sms) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt index b7430578ba..66fd6a3112 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPluginTest.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator +import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase @@ -38,9 +39,10 @@ class IobCobCalculatorPluginTest : TestBase() { @Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Mock lateinit var fabricPrivacy: FabricPrivacy - @Mock lateinit var dateUtil: DateUtil @Mock lateinit var repository: AppRepository + @Mock lateinit var context: Context + lateinit var dateUtil: DateUtil lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin val injector = HasAndroidInjector { @@ -50,6 +52,7 @@ class IobCobCalculatorPluginTest : TestBase() { @Before fun mock() { + dateUtil = DateUtil(context) iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) } @@ -218,64 +221,64 @@ class IobCobCalculatorPluginTest : TestBase() { // real data gap test bgReadingList.clear() - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:14:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:09:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:04:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:54:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:49:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:44:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:39:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:29:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:24:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:19:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:14:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:09:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T11:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:34:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:14:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:09:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:04:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:59:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:54:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:49:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:44:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:39:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:34:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:29:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:24:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:19:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:14:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:09:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:04:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T11:59:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:29:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:24:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:19:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:14:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:10:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:59:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:54:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:50:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:44:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:29:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:24:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:19:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:14:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:10:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:04:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:59:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:54:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:50:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:44:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) iobCobCalculatorPlugin.bgReadings = bgReadingList iobCobCalculatorPlugin.referenceTime = -1 Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData) iobCobCalculatorPlugin.createBucketedData() - Assert.assertEquals(DateUtil.fromISODateString("2018-09-05T13:34:57Z").time, iobCobCalculatorPlugin.bucketedData!![0].timestamp) - Assert.assertEquals(DateUtil.fromISODateString("2018-09-05T03:44:57Z").time, iobCobCalculatorPlugin.bucketedData!![iobCobCalculatorPlugin.bucketedData!!.size - 1].timestamp) + Assert.assertEquals(dateUtil.fromISODateString("2018-09-05T13:34:57Z"), iobCobCalculatorPlugin.bucketedData!![0].timestamp) + Assert.assertEquals(dateUtil.fromISODateString("2018-09-05T03:44:57Z"), iobCobCalculatorPlugin.bucketedData!![iobCobCalculatorPlugin.bucketedData!!.size - 1].timestamp) // 5min 4sec data bgReadingList.clear() - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:33:40Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:28:36Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:23:32Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:18:28Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:13:24Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:08:19Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:03:16Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:58:11Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:53:07Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:48:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:42:58Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:37:54Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:32:51Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:27:46Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:22:42Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:17:38Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:12:33Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:07:29Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:02:26Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:57:21Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) - bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:52:17Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:33:40Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:28:36Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:23:32Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:18:28Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:13:24Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:08:19Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:03:16Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:58:11Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:53:07Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:48:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:42:58Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:37:54Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:32:51Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:27:46Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:22:42Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:17:38Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:12:33Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:07:29Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:02:26Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T04:57:21Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) + bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T04:52:17Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT)) iobCobCalculatorPlugin.bgReadings = bgReadingList Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData) } @@ -289,7 +292,7 @@ class IobCobCalculatorPluginTest : TestBase() { @Test fun roundUpTimeTest() { - Assert.assertEquals(T.mins(3).msecs(), IobCobCalculatorPlugin.roundUpTime(T.secs(155).msecs())) + Assert.assertEquals(T.mins(3).msecs(), iobCobCalculatorPlugin.roundUpTime(T.secs(155).msecs())) } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt index fa3bf196fb..a13f4aa227 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt @@ -24,7 +24,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(FabricPrivacy::class) +@PrepareForTest(FabricPrivacy::class, DateUtil::class) class VirtualPumpPluginUTest : TestBase() { private val rxBus = RxBusWrapper(aapsSchedulers) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt index 82e781e01d..4d803ca0e9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments -import android.content.Context import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBaseWithProfile @@ -9,18 +8,12 @@ import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.UploadQueueInterface import info.nightscout.androidaps.plugins.general.nsclient.NSUpload -import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.sharedPreferences.SP -import org.junit.Assert -import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.ArgumentMatchers import org.mockito.Mock -import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @@ -29,7 +22,6 @@ import org.powermock.modules.junit4.PowerMockRunner @PrepareForTest(FabricPrivacy::class, DatabaseHelperInterface::class, AppRepository::class) class TreatmentsPluginTest : TestBaseWithProfile() { - @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var treatmentService: TreatmentService @Mock lateinit var nsUpload: NSUpload @@ -67,7 +59,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() { @Test fun `zero TBR should produce zero absolute insulin`() { - val now = DateUtil.now() + val now = dateUtil._now() val tbrs: MutableList = ArrayList() tbrs.add(TemporaryBasal(injector).date(now - T.hours(30).msecs()).duration(10000).percent(0)) @@ -79,7 +71,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() { @Test fun `90pct TBR and should produce less absolute insulin`() { - val now = DateUtil.now() + val now = dateUtil._now() val tbrs: MutableList = ArrayList() `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) sot.initializeData(T.hours(30).msecs()) @@ -93,7 +85,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() { @Test fun `110pct TBR and should produce 10pct more absolute insulin`() { - val now = DateUtil.now() + val now = dateUtil._now() val tbrs: MutableList = ArrayList() `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) sot.initializeData(T.hours(30).msecs()) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt index be6c9b202b..1149eb380a 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt @@ -50,7 +50,6 @@ class CommandQueueTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var lazyActivePlugin: Lazy @Mock lateinit var activePlugin: ActivePluginProvider - @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var powerManager: PowerManager @@ -226,7 +225,7 @@ class CommandQueueTest : TestBaseWithProfile() { // given Assert.assertEquals(0, commandQueue.size()) val smb = DetailedBolusInfo() - smb.lastKnownBolusTime = DateUtil.now() + smb.lastKnownBolusTime = System.currentTimeMillis() smb.bolusType = DetailedBolusInfo.BolusType.SMB commandQueue.bolus(smb, null) commandQueue.bolus(DetailedBolusInfo(), null) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt index 58ebba63d7..7199418902 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt @@ -41,7 +41,6 @@ class QueueThreadTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var lazyActivePlugin: Lazy @Mock lateinit var activePlugin: ActivePluginProvider - @Mock lateinit var context: Context @Mock lateinit var sp: SP @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var powerManager: PowerManager diff --git a/app/src/test/java/info/nightscout/androidaps/utils/SntpClientTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/SntpClientTest.kt index 79a8541daf..5224a6129c 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/SntpClientTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/SntpClientTest.kt @@ -3,8 +3,14 @@ package info.nightscout.androidaps.utils import info.nightscout.androidaps.TestBase import org.junit.Assert import org.junit.Test +import org.junit.runner.RunWith import org.mockito.Mock +import org.powermock.core.classloader.annotations.PrepareForTest +import org.powermock.modules.junit4.PowerMockRunner + +@RunWith(PowerMockRunner::class) +@PrepareForTest(DateUtil::class) class SntpClientTest : TestBase() { @Mock lateinit var dateUtil: DateUtil @@ -22,7 +28,7 @@ class SntpClientTest : TestBase() { SntpClient(aapsLogger, dateUtil).doNtpTime(object : SntpClient.Callback() { override fun run() { Assert.assertTrue(success) - Assert.assertTrue(Math.abs(time - DateUtil.now()) < 60000) + Assert.assertTrue(Math.abs(time - System.currentTimeMillis()) < 60000) } }) } diff --git a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt index c1c22dc89e..dfca903165 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt @@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert import org.junit.Test @@ -27,7 +28,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) -@PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, IobCobCalculatorPlugin::class) +@PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, IobCobCalculatorPlugin::class, DateUtil::class) class BolusWizardTest : TestBase() { private val pumpBolusStep = 0.1 @@ -42,6 +43,7 @@ class BolusWizardTest : TestBase() { @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin + @Mock lateinit var dateUtil: DateUtil val injector = HasAndroidInjector { AndroidInjector { @@ -55,7 +57,7 @@ class BolusWizardTest : TestBase() { it.commandQueue = commandQueue it.loopPlugin = loopPlugin it.iobCobCalculator = iobCobCalculator - it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) + it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) } } } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt index 4c4b43ba18..ca2ba012e0 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.kt @@ -17,6 +17,7 @@ import javax.inject.Inject class AutomationEvent(private val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var dateUtil: DateUtil var title: String = "" var isEnabled = true @@ -83,6 +84,6 @@ class AutomationEvent(private val injector: HasAndroidInjector) { } fun shouldRun(): Boolean { - return lastRun <= DateUtil.now() - T.mins(5).msecs() + return lastRun <= dateUtil.now() - T.mins(5).msecs() } } \ No newline at end of file diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index 5fefdddeca..3f5790b128 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -208,7 +208,7 @@ class AutomationPlugin @Inject constructor( action.doAction(object : Callback() { override fun run() { val sb = StringBuilder() - sb.append(dateUtil.timeString(DateUtil.now())) + sb.append(dateUtil.timeString(dateUtil.now())) sb.append(" ") sb.append(if (result.success) "☺" else "▼") sb.append(" ") @@ -229,7 +229,7 @@ class AutomationPlugin @Inject constructor( } } SystemClock.sleep(1100) - event.lastRun = DateUtil.now() + event.lastRun = dateUtil.now() if (event.autoRemove) automationEvents.remove(event) } } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt index 8e012f2771..1461e20838 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarm.kt @@ -24,6 +24,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var context: Context + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var timerUtil: TimerUtil var text = InputString() @@ -39,7 +40,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) { override fun isValid(): Boolean = true // empty alarm will show app name override fun doAction(callback: Callback) { - timerUtil.scheduleReminder(DateUtil.now() + T.secs(10L).msecs(), text.value.takeIf { it.isNotBlank() } + timerUtil.scheduleReminder(dateUtil.now() + T.secs(10L).msecs(), text.value.takeIf { it.isNotBlank() } ?: resourceHelper.gs(R.string.app_name)) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt index c3623775ea..5c2dadb9ca 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt @@ -26,6 +26,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger var inputProfileName: InputProfileName = InputProfileName(resourceHelper, activePlugin, "") @@ -61,7 +62,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { uel.log(UserEntry.Action.PROFILE_SWITCH, Sources.Automation, title, ValueWithUnit.SimpleString(inputProfileName.value), ValueWithUnit.Percent(100)) - activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, DateUtil.now()) + activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, dateUtil.now()) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index 310008067f..4512a16034 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -41,6 +41,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var repository: AppRepository @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var uel: UserEntryLogger private val disposable = CompositeDisposable() @@ -105,7 +106,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { } fun tt() = TemporaryTarget( - timestamp = DateUtil.now(), + timestamp = dateUtil.now(), duration = TimeUnit.MINUTES.toMillis(duration.getMinutes().toLong()), reason = TemporaryTarget.Reason.AUTOMATION, lowTarget = Profile.toMgdl(value.value, value.units), diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt index 932d7d9d0a..9d4443d466 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.kt @@ -30,7 +30,7 @@ class ActionStopTempTarget(injector: HasAndroidInjector) : Action(injector) { override fun icon(): Int = R.drawable.ic_stop_24dp override fun doAction(callback: Callback) { - disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil._now())) + disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now())) .subscribe({ result -> uel.log(UserEntry.Action.CANCEL_TT, Sources.Automation, title) result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt index c78b8e5e3c..df0939bfa7 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt @@ -12,13 +12,13 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* -class InputDateTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil, var value: Long = DateUtil.now()) : Element() { +class InputDateTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() { override fun addToLayout(root: LinearLayout) { val label = TextView(root.context) val dateButton = TextView(root.context) val timeButton = TextView(root.context) - dateButton.text = DateUtil.dateString(value) + dateButton.text = dateUtil.dateString(value) timeButton.text = dateUtil.timeString(value) // create an OnDateSetListener @@ -29,7 +29,7 @@ class InputDateTime(private val resourceHelper: ResourceHelper, private val date cal.set(Calendar.MONTH, monthOfYear) cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) value = cal.timeInMillis - dateButton.text = DateUtil.dateString(value) + dateButton.text = dateUtil.dateString(value) } dateButton.setOnClickListener { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt index aee207cf5a..d73b5150b6 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt @@ -15,7 +15,7 @@ import java.util.* class InputTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() { - var value: Int = getMinSinceMidnight(DateUtil.now()) + var value: Int = getMinSinceMidnight(dateUtil.now()) override fun addToLayout(root: LinearLayout) { val label = TextView(root.context) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt index 8e5ffd0a8e..6511eb8194 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt @@ -15,8 +15,8 @@ import java.util.* class InputTimeRange(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() { - var start: Int = getMinSinceMidnight(DateUtil.now()) - var end: Int = getMinSinceMidnight(DateUtil.now()) + var start: Int = getMinSinceMidnight(dateUtil.now()) + var end: Int = getMinSinceMidnight(dateUtil.now()) override fun addToLayout(root: LinearLayout) { val label = TextView(root.context) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt index 2ac5203aec..b7b47aa66f 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt @@ -45,7 +45,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { aapsLogger.debug(LTag.AUTOMATION, "NOT ready for execution: " + friendlyDescription()) false } - val last = (dateUtil._now() - lastBolusTime).toDouble() / (60 * 1000) + val last = (dateUtil.now() - lastBolusTime).toDouble() / (60 * 1000) aapsLogger.debug(LTag.AUTOMATION, "LastBolus min ago: $minutesAgo") val doRun = comparator.value.check(last.toInt(), minutesAgo.getMinutes()) if (doRun) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt index e8fffc13f8..a4e62d090e 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputInsul import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject @@ -35,7 +34,7 @@ class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) { override fun shouldRun(): Boolean { val profile = profileFunction.getProfile() ?: return false - val iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(DateUtil.now(), profile) + val iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(dateUtil.now(), profile) if (comparator.value.check(iob.iob, insulin.value)) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt index 4d852d7b23..cfcdd788ba 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputDurat import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.JsonHelper.safeGetString import org.json.JSONObject @@ -47,7 +46,7 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } - val connectionAgo = (DateUtil.now() - lastConnection) / (60 * 1000) + val connectionAgo = (dateUtil.now() - lastConnection) / (60 * 1000) aapsLogger.debug(LTag.AUTOMATION, "Last connection min ago: $connectionAgo") if (comparator.value.check(connectionAgo.toInt(), minutesAgo.value)) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt index c382803c21..383adcce50 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt @@ -32,7 +32,7 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val currentMinSinceMidnight = getMinSinceMidnight(dateUtil._now()) + val currentMinSinceMidnight = getMinSinceMidnight(dateUtil.now()) val scheduledDayOfWeek = Calendar.getInstance()[Calendar.DAY_OF_WEEK] if (days.isSet(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(scheduledDayOfWeek)))) { if (currentMinSinceMidnight >= time.value && currentMinSinceMidnight - time.value < 5) { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt index 9c7d64add0..216e84871d 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt @@ -30,7 +30,7 @@ class TriggerTempTarget(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val tt = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() + val tt = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() if (tt is ValueWrapper.Absent && comparator.value == ComparatorExists.Compare.NOT_EXISTS) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt index 304e57799f..f03c35c6fc 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt @@ -8,7 +8,6 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.InputDateTime import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import org.json.JSONObject @@ -32,7 +31,7 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val now = DateUtil.now() + val now = dateUtil.now() if (now >= time.value && now - time.value < T.mins(5).msecs()) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt index 13fa083581..494b3980cf 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt @@ -9,7 +9,6 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.automation.elements.InputTimeRange import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.MidnightTime import org.json.JSONObject @@ -38,7 +37,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val currentMinSinceMidnight = getMinSinceMidnight(DateUtil.now()) + val currentMinSinceMidnight = getMinSinceMidnight(dateUtil.now()) var doRun = false if (range.start < range.end && range.start < currentMinSinceMidnight && currentMinSinceMidnight < range.end) doRun = true else if (range.start > range.end && (range.start < currentMinSinceMidnight || currentMinSinceMidnight < range.end)) doRun = true diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt index 1639de19bb..b3d62498e4 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.TimerUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert @@ -30,6 +31,7 @@ class ActionAlarmTest : TestBase() { @Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var context: Context @Mock lateinit var timerUtil: TimerUtil + @Mock lateinit var dateUtil: DateUtil private lateinit var sut: ActionAlarm var injector: HasAndroidInjector = HasAndroidInjector { @@ -39,6 +41,7 @@ class ActionAlarmTest : TestBase() { it.rxBus = rxBus it.context = context it.timerUtil = timerUtil + it.dateUtil = dateUtil } if (it is PumpEnactResult) { it.resourceHelper = resourceHelper diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt index cecef90241..b920cc453f 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt @@ -66,6 +66,7 @@ open class ActionsTestBase : TestBaseWithProfile() { it.repository = repository it.profileFunction = profileFunction it.uel = uel + it.dateUtil = dateUtil } if (it is ActionSendSMS) { it.aapsLogger = aapsLogger @@ -78,6 +79,7 @@ open class ActionsTestBase : TestBaseWithProfile() { it.activePlugin = activePlugin it.profileFunction = profileFunction it.uel = uel + it.dateUtil = dateUtil } if (it is ActionProfileSwitchPercent) { it.resourceHelper = resourceHelper diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt index ea9bf09a54..a8c803c8ff 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.kt @@ -114,8 +114,7 @@ class TriggerAutosensValueTest : TriggerTestBase() { @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } private fun generateAutosensData(): AutosensData { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt index 96496011ed..fe0e9049ba 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.kt @@ -13,7 +13,6 @@ import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.`when` -import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.util.* @@ -28,8 +27,7 @@ class TriggerBgTest : TriggerTestBase() { fun prepare() { `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) - PowerMockito.mockStatic(DateUtil::class.java) - `when`(DateUtil.now()).thenReturn(now) + `when`(dateUtil.now()).thenReturn(now) } @Test diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt index d8d85e5e50..29beab1464 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.kt @@ -24,8 +24,7 @@ class TriggerBolusAgoTest : TriggerTestBase() { @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test @@ -37,7 +36,7 @@ class TriggerBolusAgoTest : TriggerTestBase() { type = Bolus.Type.NORMAL ) ) // Set last bolus time to now - `when`(dateUtil._now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min + `when`(dateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min var t = TriggerBolusAgo(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL) Assert.assertEquals(110, t.minutesAgo.value) Assert.assertEquals(Comparator.Compare.IS_EQUAL, t.comparator.value) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.kt index 553af7b411..d194c50b1b 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.kt @@ -22,8 +22,7 @@ class TriggerCOBTest : TriggerTestBase() { var now = 1514766900000L @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) PowerMockito.`when`(sp.getInt(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(48) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt index 477c843c23..9a9107ec4b 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.kt @@ -27,8 +27,7 @@ class TriggerDeltaTest : TriggerTestBase() { @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) `when`(profileFunction.getUnits()).thenReturn(Constants.MGDL) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.kt index d654915598..d013e2f9c4 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.data.IobTotal -import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.utils.DateUtil import org.json.JSONObject @@ -13,7 +12,6 @@ import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.mockito.Mockito.`when` -import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @@ -24,8 +22,7 @@ class TriggerIobTest : TriggerTestBase() { var now = 1514766900000L @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - `when`(DateUtil.now()).thenReturn(now) + `when`(dateUtil.now()).thenReturn(now) `when`(profileFunction.getProfile()).thenReturn(validProfile) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt index 35890dad32..c533c8f257 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.kt @@ -24,9 +24,8 @@ class TriggerLocationTest : TriggerTestBase() { var now = 1514766900000L @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) PowerMockito.mockStatic(LocationService::class.java) - `when`(DateUtil.now()).thenReturn(now) + `when`(dateUtil.now()).thenReturn(now) PowerMockito.spy(LocationService::class.java) `when`(locationDataContainer.lastLocation).thenReturn(mockedLocation()) } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt index 6f6dbd8b08..27c910ca78 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.kt @@ -23,8 +23,7 @@ class TriggerProfilePercentTest : TriggerTestBase() { @Before fun mock() { `when`(profileFunction.getProfile()).thenReturn(validProfile) - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test fun shouldRunTest() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt index 527bd30f47..bddce94217 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.kt @@ -21,8 +21,7 @@ class TriggerPumpLastConnectionTest : TriggerTestBase() { @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test @@ -30,7 +29,7 @@ class TriggerPumpLastConnectionTest : TriggerTestBase() { // System.currentTimeMillis() is always 0 // and so is every last connection time Assert.assertEquals(0L, testPumpPlugin.lastDataTime()) - PowerMockito.`when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min + PowerMockito.`when`(dateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min var t = TriggerPumpLastConnection(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL) Assert.assertEquals(110, t.minutesAgo.value) Assert.assertEquals(Comparator.Compare.IS_EQUAL, t.comparator.value) diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.kt index b76fc0bd90..e764e22747 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.kt @@ -20,7 +20,7 @@ class TriggerRecurringTimeTest : TriggerTestBase() { @Before fun mock() { now = MidnightTime.calc() + T.mins(95).msecs() // 95 min from midnight - PowerMockito.`when`(dateUtil._now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test fun shouldRunTest() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt index 6877de5f3f..64ba71fd14 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.kt @@ -20,8 +20,7 @@ class TriggerTempTargetTest : TriggerTestBase() { var now = 1514766900000L @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } /* @Test fun shouldRunTest() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt index f589bfcdea..2dbca12360 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTestBase.kt @@ -54,7 +54,7 @@ open class TriggerTestBase : TestBaseWithProfile() { it.repository = repository it.activePlugin = activePlugin it.iobCobCalculatorPlugin = iobCobCalculatorPlugin - it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin) + it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil) it.dateUtil = dateUtil } if (it is TriggerBg) { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.kt index 2c62f6341c..3e01059aa6 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.kt @@ -22,9 +22,8 @@ class TriggerTimeRangeTest : TriggerTestBase() { @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) val nowMills = MidnightTime.calcPlusMinutes(now) - PowerMockito.`when`(DateUtil.now()).thenReturn(nowMills) + PowerMockito.`when`(dateUtil.now()).thenReturn(nowMills) } @Test diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.kt index 7151fa6b57..8c38c37761 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.kt @@ -21,8 +21,7 @@ class TriggerTimeTest : TriggerTestBase() { var now = 1514766900000L @Before fun mock() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test fun shouldRunTest() { diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.kt index c2fab5b28c..4b38476f98 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.kt @@ -24,8 +24,7 @@ class TriggerWifiSsidTest : TriggerTestBase() { @Before fun mock() { PowerMockito.mockStatic(NetworkChangeReceiver::class.java) - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(now) + PowerMockito.`when`(dateUtil.now()).thenReturn(now) } @Test fun shouldRunTest() { diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index d2358de9d7..159e637eaa 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -37,6 +37,7 @@ public class ComboFragment extends DaggerFragment { @Inject ResourceHelper resourceHelper; @Inject RxBusWrapper rxBus; @Inject SP sp; + @Inject DateUtil dateUtil; @Inject FabricPrivacy fabricPrivacy; @Inject AapsSchedulers aapsSchedulers; @@ -192,7 +193,7 @@ public class ComboFragment extends DaggerFragment { } // last connection - String minAgo = DateUtil.minAgo(resourceHelper, comboPlugin.getPump().lastSuccessfulCmdTime); + String minAgo = dateUtil.minAgo(resourceHelper, comboPlugin.getPump().lastSuccessfulCmdTime); long min = (System.currentTimeMillis() - comboPlugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; if (comboPlugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { lastConnectionView.setText(R.string.combo_pump_connected_now); @@ -215,9 +216,9 @@ public class ComboFragment extends DaggerFragment { if ((agoMsc < 60 * 1000)) { ago = resourceHelper.gs(R.string.combo_pump_connected_now); } else if (bolusMinAgo < 60) { - ago = DateUtil.minAgo(resourceHelper, bolus.timestamp); + ago = dateUtil.minAgo(resourceHelper, bolus.timestamp); } else { - ago = DateUtil.hourAgo(bolus.timestamp, resourceHelper); + ago = dateUtil.hourAgo(bolus.timestamp, resourceHelper); } lastBolusView.setText(resourceHelper.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); } else { diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 26c23e8e9d..aa4bfba45a 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -25,9 +25,7 @@ import info.nightscout.androidaps.combo.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; -import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -41,7 +39,6 @@ import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpPluginBase; import info.nightscout.androidaps.interfaces.PumpSync; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -66,7 +63,6 @@ import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.InstanceId; - import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -86,6 +82,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr private final Context context; private final DatabaseHelperInterface databaseHelper; private final PumpSync pumpSync; + private final DateUtil dateUtil; private final static PumpDescription pumpDescription = new PumpDescription(); @@ -141,7 +138,8 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr CommandQueueProvider commandQueue, Context context, DatabaseHelperInterface databaseHelper, - PumpSync pumpSync + PumpSync pumpSync, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.PUMP) @@ -159,6 +157,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr this.context = context; this.databaseHelper = databaseHelper; this.pumpSync = pumpSync; + this.dateUtil = dateUtil; pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_COMBO); } @@ -970,7 +969,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr // so update the var with it, so the check routines below can work on it preCheckResult = alertConfirmationResult; } else if (activeAlert.errorCode != null) { - Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, DateUtil.now(), getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message), Notification.URGENT, 0); + Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, dateUtil.now(), getResourceHelper().gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message), Notification.URGENT, 0); rxBus.send(new EventNewNotification(notification)); return preCheckResult.success(false); } @@ -1068,7 +1067,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr throw new IllegalArgumentException(activeAlert.toString()); } Notification notification = new Notification(); - notification.setDate(DateUtil.now()); + notification.setDate(dateUtil.now()); notification.setId(Notification.COMBO_PUMP_ALARM); notification.setLevel(Notification.NORMAL); if (activeAlert.warningCode == PumpWarningCodes.CARTRIDGE_LOW) { @@ -1295,7 +1294,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr try { JSONObject pumpJson = new JSONObject(); - pumpJson.put("clock", DateUtil.toISOString(pump.lastSuccessfulCmdTime)); + pumpJson.put("clock", dateUtil.toISOString(pump.lastSuccessfulCmdTime)); int level; if (pump.reservoirLevel != -1) level = pump.reservoirLevel; diff --git a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt index 7ff9cd82e1..63e328b222 100644 --- a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt +++ b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt @@ -9,6 +9,7 @@ import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert @@ -32,6 +33,7 @@ class ComboPluginTest : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var context: Context @Mock lateinit var databaseHelper: DatabaseHelperInterface + @Mock lateinit var dateUtil: DateUtil val injector = HasAndroidInjector { AndroidInjector { @@ -47,7 +49,7 @@ class ComboPluginTest : TestBase() { fun prepareMocks() { `when`(resourceHelper.gs(R.string.novalidbasalrate)).thenReturn("No valid basal rate read from pump") `when`(resourceHelper.gs(R.string.combo_pump_unsupported_operation)).thenReturn("Requested operation not supported by pump") - comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync) + comboPlugin = ComboPlugin(injector, aapsLogger, RxBusWrapper(aapsSchedulers), resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync, dateUtil) } @Test diff --git a/core/src/main/java/info/nightscout/androidaps/core/di/CoreModule.kt b/core/src/main/java/info/nightscout/androidaps/core/di/CoreModule.kt index 013e0459c2..1ea1ddda52 100644 --- a/core/src/main/java/info/nightscout/androidaps/core/di/CoreModule.kt +++ b/core/src/main/java/info/nightscout/androidaps/core/di/CoreModule.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLoggerProduction import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation @@ -27,8 +28,8 @@ open class CoreModule { @Provides @Singleton - fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction { - return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy) + fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy, dateUtil: DateUtil): ProfileFunction { + return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy, dateUtil) } @Provides diff --git a/core/src/main/java/info/nightscout/androidaps/data/IobTotal.kt b/core/src/main/java/info/nightscout/androidaps/data/IobTotal.kt index b295f66416..93ee6f5f64 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/IobTotal.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/IobTotal.kt @@ -64,19 +64,19 @@ class IobTotal(var time: Long) : DataPointWithLabelInterface { return this } - fun json(): JSONObject { + fun json(dateUtil: DateUtil): JSONObject { val json = JSONObject() try { json.put("iob", iob) json.put("basaliob", basaliob) json.put("activity", activity) - json.put("time", DateUtil.toISOString(Date())) + json.put("time", dateUtil.toISOString(time)) } catch (ignored: JSONException) { } return json } - fun determineBasalJson(): JSONObject { + fun determineBasalJson(dateUtil: DateUtil): JSONObject { val json = JSONObject() try { json.put("iob", iob) @@ -84,7 +84,7 @@ class IobTotal(var time: Long) : DataPointWithLabelInterface { json.put("bolussnooze", bolussnooze) json.put("activity", activity) json.put("lastBolusTime", lastBolusTime) - json.put("time", DateUtil.toISOString(Date(time))) + json.put("time", dateUtil.toISOString(time)) /* This is requested by SMB determine_basal but by based on Scott's info @@ -98,7 +98,7 @@ class IobTotal(var time: Long) : DataPointWithLabelInterface { json.put("lastTemp", lastTemp); */ if (iobWithZeroTemp != null) { - val iwzt = iobWithZeroTemp!!.determineBasalJson() + val iwzt = iobWithZeroTemp!!.determineBasalJson(dateUtil) json.put("iobWithZeroTemp", iwzt) } } catch (ignored: JSONException) { diff --git a/core/src/main/java/info/nightscout/androidaps/data/Profile.java b/core/src/main/java/info/nightscout/androidaps/data/Profile.java index 06eba8d212..a79cb5daff 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/core/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -38,6 +38,7 @@ public class Profile { @Inject public RxBusWrapper rxBus; @Inject public FabricPrivacy fabricPrivacy; @Inject public ConfigInterface configInterface; + @Inject public DateUtil dateUtil; private final HasAndroidInjector injector; @@ -188,7 +189,7 @@ public class Profile { long tas; try { String time = o.getString("time"); - tas = getShitfTimeSecs(DateUtil.toSeconds(time)); + tas = getShitfTimeSecs(dateUtil.toSeconds(time)); } catch (JSONException e) { //log.debug(">>>>>>>>>>>> Used recalculated timeAsSecons: " + time + " " + tas); tas = getShitfTimeSecs((int) o.getLong("timeAsSeconds")); @@ -628,7 +629,7 @@ public class Profile { } public static int secondsFromMidnight() { - // long passed = DateUtil.now() - MidnightTime.calc(); + // long passed = dateUtil._now() - MidnightTime.calc(); long passed = new DateTime().getMillisOfDay(); return (int) (passed / 1000); } diff --git a/core/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/core/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index 6e011e869d..7f4477e13d 100644 --- a/core/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/core/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -235,7 +235,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface { @Override public boolean isValid() { boolean isValid = getProfileObject() != null && getProfileObject().isValid(dateUtil.dateAndTimeString(date)); - ProfileSwitch active = treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()); + ProfileSwitch active = treatmentsPlugin.getProfileSwitchFromHistory(dateUtil.now()); long activeProfileSwitchDate = active != null ? active.date : -1L; if (!isValid && date == activeProfileSwitchDate) createNotificationInvalidProfile(dateUtil.dateAndTimeString(date)); diff --git a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java index ddf85afcab..19e1fc2771 100644 --- a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java @@ -92,33 +92,6 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase { isSMB = bolus.getType() == Bolus.Type.SMB; } - public static Treatment createFromJson(JSONObject json) throws JSONException { - Treatment treatment = new Treatment(); - treatment.source = Source.NIGHTSCOUT; - treatment.date = DateUtil.roundDateToSec(JsonHelper.safeGetLong(json, "mills")); - if (treatment.date == 0L) - return null; - treatment.carbs = JsonHelper.safeGetDouble(json, "carbs"); - treatment.insulin = JsonHelper.safeGetDouble(json, "insulin"); - treatment.pumpId = JsonHelper.safeGetLong(json, "pumpId"); - treatment._id = json.getString("_id"); - treatment.isSMB = JsonHelper.safeGetBoolean(json, "isSMB"); - if (json.has("eventType")) { - treatment.mealBolus = !json.get("eventType").equals("Correction Bolus"); - double carbs = treatment.carbs; - if (json.has("boluscalc")) { - JSONObject boluscalc = json.getJSONObject("boluscalc"); - treatment.boluscalc = boluscalc.toString(); - if (boluscalc.has("carbs")) { - carbs = Math.max(boluscalc.getDouble("carbs"), carbs); - } - } - if (carbs <= 0) - treatment.mealBolus = false; - } - return treatment; - } - @NonNull public String toString() { return "Treatment{" + "date= " + date + diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index 45b69f4a7c..0ad6a55114 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -63,7 +63,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { eventTime = savedInstanceState?.getLong("eventTime") ?: dateUtil.nowWithoutMilliseconds() eventTimeChanged = savedInstanceState?.getBoolean("eventTimeChanged") ?: false - eventDateView?.text = DateUtil.dateString(eventTime) + eventDateView?.text = dateUtil.dateString(eventTime) eventTimeView?.text = dateUtil.timeString(eventTime) // create an OnDateSetListener @@ -75,7 +75,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) eventTime = cal.timeInMillis eventTimeChanged = true - eventDateView?.text = DateUtil.dateString(eventTime) + eventDateView?.text = dateUtil.dateString(eventTime) } eventDateView?.setOnClickListener { diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/BolusCalculatorResultExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/BolusCalculatorResultExtension.kt index d5ffeb9566..786f9c7d13 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/BolusCalculatorResultExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/BolusCalculatorResultExtension.kt @@ -7,10 +7,10 @@ import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.utils.DateUtil import org.json.JSONObject -fun BolusCalculatorResult.toJson(): JSONObject = +fun BolusCalculatorResult.toJson(dateUtil: DateUtil): JSONObject = JSONObject() .put("eventType", TherapyEvent.Type.BOLUS_WIZARD.text) - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("bolusCalculatorResult", Gson().toJson(this)) .put("date", timestamp) .put("glucose", glucoseValue) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/BolusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/BolusExtension.kt index 8f837ed800..c395a203f8 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/BolusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/BolusExtension.kt @@ -16,11 +16,11 @@ fun Bolus.iobCalc(activePlugin: ActivePluginProvider, time: Long, dia: Double): return insulinInterface.iobCalcForTreatment(this, time, dia) } -fun Bolus.toJson(): JSONObject = +fun Bolus.toJson(dateUtil: DateUtil): JSONObject = JSONObject() .put("eventType", if (type == Bolus.Type.SMB) TherapyEvent.Type.CORRECTION_BOLUS.text else TherapyEvent.Type.MEAL_BOLUS.text) .put("insulin", amount) - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("date", timestamp) .put("type", type.name) .put("isValid", isValid) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/CarbsExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/CarbsExtension.kt index 954c4d1b6a..54d200e9f6 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/CarbsExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/CarbsExtension.kt @@ -7,11 +7,11 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject -fun Carbs.toJson(): JSONObject = +fun Carbs.toJson(dateUtil: DateUtil): JSONObject = JSONObject() .put("eventType", if (amount < 12) TherapyEvent.Type.CARBS_CORRECTION.text else TherapyEvent.Type.MEAL_BOLUS.text) .put("carbs", amount) - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("date", timestamp).also { if (duration != 0L) it.put("duration", duration) if (interfaceIDs.pumpId != null) it.put("pumpId", interfaceIDs.pumpId) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt index 23e500a2dd..d7496fafe6 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt @@ -11,9 +11,9 @@ import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.DateUtil import org.json.JSONObject -fun DeviceStatus.toJson(): JSONObject = +fun DeviceStatus.toJson(dateUtil: DateUtil): JSONObject = JSONObject() - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .also { if (device != null) it.put("device", device) if (pump != null) it.put("pump", JSONObject(pump)) @@ -43,13 +43,13 @@ fun buildDeviceStatus( var apsResult: JSONObject? = null var iob: JSONObject? = null var enacted: JSONObject? = null - if (lastRun != null && lastRun.lastAPSRun > dateUtil._now() - 300 * 1000L) { + if (lastRun != null && lastRun.lastAPSRun > dateUtil.now() - 300 * 1000L) { // do not send if result is older than 1 min apsResult = lastRun.request?.json()?.also { - it.put("timestamp", DateUtil.toISOString(lastRun.lastAPSRun)) + it.put("timestamp", dateUtil.toISOString(lastRun.lastAPSRun)) } - iob = lastRun.request?.iob?.json()?.also { - it.put("time", DateUtil.toISOString(lastRun.lastAPSRun)) + iob = lastRun.request?.iob?.json(dateUtil)?.also { + it.put("time", dateUtil.toISOString(lastRun.lastAPSRun)) } val requested = JSONObject() if (lastRun.tbrSetByPump?.enacted == true) { // enacted @@ -68,12 +68,12 @@ fun buildDeviceStatus( } else { val calcIob = iobCobCalculatorPlugin.calculateIobArrayInDia(profile) if (calcIob.isNotEmpty()) { - iob = calcIob[0].json() - iob.put("time", DateUtil.toISOString(dateUtil._now())) + iob = calcIob[0].json(dateUtil) + iob.put("time", dateUtil.toISOString(dateUtil.now())) } } return DeviceStatus( - timestamp = dateUtil._now(), + timestamp = dateUtil.now(), suggested = apsResult?.toString(), iob = iob?.toString(), enacted = enacted?.toString(), diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt index 3de657864b..6c75f72cd0 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/ExtendedBolusExtension.kt @@ -22,17 +22,17 @@ import kotlin.math.round import kotlin.math.roundToInt fun ExtendedBolus.isInProgress(dateUtil: DateUtil): Boolean = - dateUtil._now() in timestamp..timestamp + duration + dateUtil.now() in timestamp..timestamp + duration val ExtendedBolus.plannedRemainingMinutes: Int get() = max(round((end - System.currentTimeMillis()) / 1000.0 / 60).toInt(), 0) fun ExtendedBolus.toStringFull(dateUtil: DateUtil): String = "E " + to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + T.msecs(duration).mins() + "min" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "min" fun ExtendedBolus.toStringMedium(dateUtil: DateUtil): String = - to2Decimal(rate) + "U/h " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + T.msecs(duration).mins() + "'" + to2Decimal(rate) + "U/h " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "'" fun ExtendedBolus.toStringTotal(): String = "${to2Decimal(amount)}U ( ${to2Decimal(rate)} U/h )" @@ -50,16 +50,16 @@ fun ExtendedBolus.toTemporaryBasal(profile: Profile): TemporaryBasal = type = TemporaryBasal.Type.FAKE_EXTENDED ) -fun ExtendedBolus.toJson(profile: Profile): JSONObject = +fun ExtendedBolus.toJson(profile: Profile, dateUtil: DateUtil): JSONObject = if (isEmulatingTempBasal) toTemporaryBasal(profile) - .toJson(profile) - .put("extendedEmulated", toRealJson()) - else toRealJson() + .toJson(profile, dateUtil) + .put("extendedEmulated", toRealJson(dateUtil)) + else toRealJson(dateUtil) -fun ExtendedBolus.toRealJson(): JSONObject = +fun ExtendedBolus.toRealJson(dateUtil: DateUtil): JSONObject = JSONObject() - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", "openaps://" + "AndroidAPS") .put("eventType", TherapyEvent.Type.COMBO_BOLUS.text) .put("duration", T.msecs(duration).mins()) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/GlucoseValueExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/GlucoseValueExtension.kt index 8ffc9a93c5..1396c99c4a 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/GlucoseValueExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/GlucoseValueExtension.kt @@ -14,11 +14,11 @@ fun GlucoseValue.valueToUnitsString(units: String): String = if (units == Constants.MGDL) DecimalFormatter.to0Decimal(value) else DecimalFormatter.to1Decimal(value * Constants.MGDL_TO_MMOLL) -fun GlucoseValue.toJson(): JSONObject = +fun GlucoseValue.toJson(dateUtil: DateUtil): JSONObject = JSONObject() .put("device", sourceSensor.text) .put("date", timestamp) - .put("dateString", DateUtil.toISOString(timestamp)) + .put("dateString", dateUtil.toISOString(timestamp)) .put("sgv", value) .put("direction", trendArrow.text) .put("type", "sgv").also { diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/PumpStateExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/PumpStateExtension.kt index f6c6994dfb..beb349d3d6 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/PumpStateExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/PumpStateExtension.kt @@ -35,13 +35,13 @@ fun PumpSync.PumpState.TemporaryBasal.toStringFull(dateUtil: DateUtil): String { isAbsolute -> { DecimalFormatter.to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + durationInMinutes + "'" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } else -> { // percent rate.toString() + "% @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + durationInMinutes + "'" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } } } @@ -58,5 +58,5 @@ fun PumpSync.PumpState.ExtendedBolus.getPassedDurationToTimeInMinutes(time: Long fun PumpSync.PumpState.ExtendedBolus.toStringFull(dateUtil: DateUtil): String = "E " + to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + T.msecs(duration).mins() + "min" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + T.msecs(duration).mins() + "min" diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt index cbbcc73d14..549792a109 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryBasalExtension.kt @@ -45,26 +45,26 @@ fun TemporaryBasal.toStringFull(profile: Profile, dateUtil: DateUtil): String { type == TemporaryBasal.Type.FAKE_EXTENDED -> { to2Decimal(rate) + "U/h (" + to2Decimal(netExtendedRate(profile)) + "E) @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + durationInMinutes + "'" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } isAbsolute -> { to2Decimal(rate) + "U/h @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + durationInMinutes + "'" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } else -> { // percent rate.toString() + "% @" + dateUtil.timeString(timestamp) + - " " + getPassedDurationToTimeInMinutes(dateUtil._now()) + "/" + durationInMinutes + "'" + " " + getPassedDurationToTimeInMinutes(dateUtil.now()) + "/" + durationInMinutes + "'" } } } -fun TemporaryBasal.toJson(profile: Profile): JSONObject = +fun TemporaryBasal.toJson(profile: Profile, dateUtil: DateUtil): JSONObject = JSONObject() - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", "openaps://" + "AndroidAPS") .put("eventType", TherapyEvent.Type.TEMPORARY_BASAL.text) .put("duration", T.msecs(duration).mins()) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt index 0dab08e390..4cea998153 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt @@ -87,12 +87,12 @@ fun temporaryTargetFromJson(jsonObject: JSONObject): TemporaryTarget? { return tt } -fun TemporaryTarget.toJson(units: String): JSONObject = +fun TemporaryTarget.toJson(units: String, dateUtil: DateUtil): JSONObject = JSONObject() .put("eventType", TherapyEvent.Type.TEMPORARY_TARGET.text) .put("duration", T.msecs(duration).mins()) .put("isValid", isValid) - .put("created_at", DateUtil.toISOString(timestamp)) + .put("created_at", dateUtil.toISOString(timestamp)) .put("enteredBy", "AndroidAPS").also { if (lowTarget > 0) it .put("reason", reason.text) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt index df425c3bde..6dcc11867f 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt @@ -11,8 +11,8 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import org.json.JSONObject import java.util.concurrent.TimeUnit -fun TherapyEvent.age(useShortText: Boolean, resourceHelper: ResourceHelper): String { - val diff = DateUtil.computeDiff(timestamp, System.currentTimeMillis()) +fun TherapyEvent.age(useShortText: Boolean, resourceHelper: ResourceHelper, dateUtil: DateUtil): String { + val diff = dateUtil.computeDiff(timestamp, System.currentTimeMillis()) var days = " " + resourceHelper.gs(R.string.days) + " " var hours = " " + resourceHelper.gs(R.string.hours) + " " if (useShortText) { diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt index 5e31a3bbef..cea8cab55a 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.BasalData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData +import org.json.JSONArray interface IobCobCalculator { @@ -30,6 +31,7 @@ interface IobCobCalculator { fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array fun iobArrayToString(array: Array): String fun slowAbsorptionPercentage(timeInMinutes: Int): Double + fun convertToJSONArray(iobArray: Array): JSONArray /** * Return last valid (>39) GlucoseValue from database or null if db is empty diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/LoopInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/LoopInterface.kt index 1aac4769b2..fb6cb46594 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/LoopInterface.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/LoopInterface.kt @@ -2,17 +2,17 @@ package info.nightscout.androidaps.interfaces import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.utils.DateUtil interface LoopInterface { class LastRun { + var request: APSResult? = null var constraintsProcessed: APSResult? = null var tbrSetByPump: PumpEnactResult? = null var smbSetByPump: PumpEnactResult? = null var source: String? = null - var lastAPSRun = DateUtil.now() + var lastAPSRun = System.currentTimeMillis() var lastTBREnact: Long = 0 var lastSMBEnact: Long = 0 var lastTBRRequest: Long = 0 diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index 4966ccc85a..9145214ea9 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -28,7 +28,8 @@ class ProfileFunctionImplementation @Inject constructor( private val sp: SP, private val resourceHelper: ResourceHelper, private val activePlugin: ActivePluginProvider, - private val fabricPrivacy: FabricPrivacy + private val fabricPrivacy: FabricPrivacy, + private val dateUtil: DateUtil ) : ProfileFunction { override fun getProfileName(): String = @@ -56,7 +57,7 @@ class ProfileFunctionImplementation @Inject constructor( } if (showRemainingTime && profileSwitch.durationInMinutes != 0) { - profileName += DateUtil.untilString(profileSwitch.originalEnd(), resourceHelper) + profileName += dateUtil.untilString(profileSwitch.originalEnd(), resourceHelper) } } return profileName diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java index e93a671301..85a2ef044b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java @@ -36,9 +36,9 @@ public class NSUpload { this.uploadQueue = uploadQueue; } - public void uploadProfileSwitch(ProfileSwitch profileSwitch, long nsClientId) { + public void uploadProfileSwitch(ProfileSwitch profileSwitch, long nsClientId, DateUtil dateUtil) { try { - JSONObject data = getJson(profileSwitch); + JSONObject data = getJson(profileSwitch, dateUtil); DbRequest dbr = new DbRequest("dbAdd", "treatments", data, nsClientId); aapsLogger.debug("Prepared: " + dbr.log()); uploadQueue.add(dbr); @@ -47,9 +47,9 @@ public class NSUpload { } } - public void updateProfileSwitch(ProfileSwitch profileSwitch) { + public void updateProfileSwitch(ProfileSwitch profileSwitch, DateUtil dateUtil) { try { - JSONObject data = getJson(profileSwitch); + JSONObject data = getJson(profileSwitch, dateUtil); if (profileSwitch._id != null) { uploadQueue.add(new DbRequest("dbUpdate", "treatments", profileSwitch._id, data, profileSwitch.date)); } @@ -58,7 +58,7 @@ public class NSUpload { } } - private static JSONObject getJson(ProfileSwitch profileSwitch) throws JSONException { + private static JSONObject getJson(ProfileSwitch profileSwitch, DateUtil dateUtil) throws JSONException { JSONObject data = new JSONObject(); data.put("eventType", TherapyEvent.Type.PROFILE_SWITCH.getText()); data.put("duration", profileSwitch.durationInMinutes); @@ -70,7 +70,7 @@ public class NSUpload { data.put("timeshift", profileSwitch.timeshift); data.put("percentage", profileSwitch.percentage); } - data.put("created_at", DateUtil.toISOString(profileSwitch.date)); + data.put("created_at", dateUtil.toISOString(profileSwitch.date)); data.put("enteredBy", "AndroidAPS"); return data; diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt index 227280950e..544c1b4d9c 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatusProvider.kt @@ -10,7 +10,11 @@ import javax.inject.Inject import kotlin.math.roundToLong @Reusable -class GlucoseStatusProvider @Inject constructor(private val aapsLogger: AAPSLogger, private val iobCobCalculator: IobCobCalculator) { +class GlucoseStatusProvider @Inject constructor( + private val aapsLogger: AAPSLogger, + private val iobCobCalculator: IobCobCalculator, + private val dateUtil: DateUtil +) { val glucoseStatusData: GlucoseStatus? get() = getGlucoseStatusData() @@ -23,7 +27,7 @@ class GlucoseStatusProvider @Inject constructor(private val aapsLogger: AAPSLogg aapsLogger.debug(LTag.GLUCOSE, "sizeRecords==0") return null } - if (data[0].timestamp < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) { + if (data[0].timestamp < dateUtil.now() - 7 * 60 * 1000L && !allowOldData) { aapsLogger.debug(LTag.GLUCOSE, "oldData") return null } diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index 20d4f3a47b..f51cbcedc7 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -63,8 +63,8 @@ class PumpSyncImplementation @Inject constructor( aapsLogger.debug(LTag.PUMP, "Registering new pump ${type.description} $serialNumber") sp.putString(R.string.key_active_pump_type, type.description) sp.putString(R.string.key_active_pump_serial_number, serialNumber) - sp.putLong(R.string.key_active_pump_change_timestamp, dateUtil._now()) // allow only data newer than register time (ie. ignore older history) - return timestamp > dateUtil._now() - T.mins(1).msecs() // allow first record to be 1 min old + sp.putLong(R.string.key_active_pump_change_timestamp, dateUtil.now()) // allow only data newer than register time (ie. ignore older history) + return timestamp > dateUtil.now() - T.mins(1).msecs() // allow first record to be 1 min old } if (type.description == storedType && serialNumber == storedSerial && timestamp >= storedTimestamp) { @@ -80,8 +80,8 @@ class PumpSyncImplementation @Inject constructor( override fun expectedPumpState(): PumpSync.PumpState { val bolus = repository.getLastBolusRecord() - val temporaryBasal = repository.getTemporaryBasalActiveAt(dateUtil._now()).blockingGet() - val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet() + val temporaryBasal = repository.getTemporaryBasalActiveAt(dateUtil.now()).blockingGet() + val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet() return PumpSync.PumpState( temporaryBasal = @@ -229,7 +229,7 @@ class PumpSyncImplementation @Inject constructor( } override fun insertAnnouncement(error: String, pumpId: Long?, pumpType: PumpType, pumpSerial: String) { - if (!confirmActivePump(dateUtil._now(), pumpType, pumpSerial)) return + if (!confirmActivePump(dateUtil.now(), pumpType, pumpSerial)) return disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(error, pumpId, pumpType.toDbPumpType(), pumpSerial)) .subscribe() } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.java b/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.java deleted file mode 100644 index fde7122293..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.java +++ /dev/null @@ -1,394 +0,0 @@ -package info.nightscout.androidaps.utils; - -import android.content.Context; - -import androidx.collection.LongSparseArray; - -import org.joda.time.DateTime; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.GregorianCalendar; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.core.R; -import info.nightscout.androidaps.utils.resources.ResourceHelper; - -/** - * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj - * with TZ - */ - -@Singleton -public class DateUtil { - private final Context context; - - @Inject - public DateUtil(Context context) { - this.context = context; - } - - /** - * The date format in iso. - */ - private static final String 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 - */ - public static Date fromISODateString(String isoDateString) { - - DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser(); - DateTime dateTime = DateTime.parse(isoDateString, parser); - return dateTime.toDate(); - } - - /** - * Render date - * - * @param date the date obj - * @param format - if not specified, will use FORMAT_DATE_ISO - * @param tz - tz to set to, if not specified uses local timezone - * @return the iso-formatted date string - */ - public static String toISOString(Date date, String format, TimeZone tz) { - if (format == null) format = FORMAT_DATE_ISO_OUT; - if (tz == null) tz = TimeZone.getDefault(); - DateFormat f = new SimpleDateFormat(format, Locale.getDefault()); - f.setTimeZone(tz); - return f.format(date); - } - - public static String toISOString(Date date) { - return toISOString(date, FORMAT_DATE_ISO_OUT, TimeZone.getTimeZone("UTC")); - } - - public static String toISOString(long date) { - return toISOString(new Date(date), FORMAT_DATE_ISO_OUT, TimeZone.getTimeZone("UTC")); - } - - public static String toISOAsUTC(final long timestamp) { - final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'", Locale.US); - format.setTimeZone(TimeZone.getTimeZone("UTC")); - return format.format(timestamp); - } - - public static String toISONoZone(final long timestamp) { - final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); - format.setTimeZone(TimeZone.getDefault()); - return format.format(timestamp); - } - - public static Date toDate(Integer seconds) { - Calendar calendar = new GregorianCalendar(); - calendar.set(Calendar.MONTH, 0); // Set january to be sure we miss DST changing - calendar.set(Calendar.HOUR_OF_DAY, seconds / 60 / 60); - calendar.set(Calendar.MINUTE, (seconds / 60) % 60); - calendar.set(Calendar.SECOND, 0); - return calendar.getTime(); - } - - public static int toSeconds(String hh_colon_mm) { - Pattern p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)"); - Matcher m = p.matcher(hh_colon_mm); - int retval = 0; - - if (m.find()) { - retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60; - if ((m.group(3).equals(" a.m.") || m.group(3).equals(" AM") || m.group(3).equals("AM")) && m.group(1).equals("12")) - retval -= 12 * 60 * 60; - if ((m.group(3).equals(" p.m.") || m.group(3).equals(" PM") || m.group(3).equals("PM")) && !(m.group(1).equals("12"))) - retval += 12 * 60 * 60; - } - return retval; - } - - public static long toTodayTime(String hh_colon_mm) { - Pattern p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)"); - Matcher m = p.matcher(hh_colon_mm); - long retval = 0; - - if (m.find()) { - int hours = SafeParse.stringToInt(m.group(1)); - int minutes = SafeParse.stringToInt(m.group(2)); - if ((m.group(3).equals(" a.m.") || m.group(3).equals(" AM") || m.group(3).equals("AM")) && m.group(1).equals("12")) - hours -= 12; - if ((m.group(3).equals(" p.m.") || m.group(3).equals(" PM") || m.group(3).equals("PM")) && !(m.group(1).equals("12"))) - hours += 12; - DateTime t = new DateTime() - .withHourOfDay(hours) - .withMinuteOfHour(minutes) - .withSecondOfMinute(0) - .withMillisOfSecond(0); - retval = t.getMillis(); - } - return retval; - } - - public static String dateString(Date date) { - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); - return df.format(date); - } - - public static String dateString(long mills) { - DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); - return df.format(mills); - } - - public String dateStringShort(long mills) { - String format = "MM/dd"; - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "dd/MM"; - } - return new DateTime(mills).toString(DateTimeFormat.forPattern(format)); - } - - public String timeString(Date date) { - String format = "hh:mma"; - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH:mm"; - } - return new DateTime(date).toString(DateTimeFormat.forPattern(format)); - } - - public String timeString(long mills) { - String format = "hh:mma"; - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH:mm"; - } - return new DateTime(mills).toString(DateTimeFormat.forPattern(format)); - } - - public String timeStringWithSeconds(long mills) { - String format = "hh:mm:ssa"; - if (android.text.format.DateFormat.is24HourFormat(context)) { - format = "HH:mm:ss"; - } - return new DateTime(mills).toString(DateTimeFormat.forPattern(format)); - } - - public String dateAndTimeString(Date date) { - return dateString(date) + " " + timeString(date); - } - - public String dateAndTimeRangeString(long start, long end) { - return dateAndTimeString(start) + " - " + timeString(end); - } - - public String dateAndTimeString(long mills) { - if (mills == 0) return ""; - return dateString(mills) + " " + timeString(mills); - } - - public String dateAndTimeAndSecondsString(long mills) { - if (mills == 0) return ""; - return dateString(mills) + " " + timeStringWithSeconds(mills); - } - - public static String minAgo(ResourceHelper resourceHelper, long time) { - int mins = (int) ((now() - time) / 1000 / 60); - return resourceHelper.gs(R.string.minago, mins); - } - - public static String minAgoShort(long time) { - int mins = (int) ((time - now()) / 1000 / 60); - return (mins > 0 ? "+" : "") + mins; - } - - public static String hourAgo(long time, ResourceHelper resourceHelper) { - double hours = (now() - time) / 1000d / 60 / 60; - return resourceHelper.gs(R.string.hoursago, hours); - } - - private static final LongSparseArray timeStrings = new LongSparseArray<>(); - - public String timeStringFromSeconds(int seconds) { - String cached = timeStrings.get(seconds); - if (cached != null) - return cached; - String t = timeString(toDate(seconds)); - timeStrings.put(seconds, t); - return t; - } - - - public static String timeFrameString(long timeInMillis, ResourceHelper resourceHelper) { - long remainingTimeMinutes = timeInMillis / (1000 * 60); - long remainingTimeHours = remainingTimeMinutes / 60; - remainingTimeMinutes = remainingTimeMinutes % 60; - return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + resourceHelper.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')"; - } - - public static String sinceString(long timestamp, ResourceHelper resourceHelper) { - return timeFrameString(System.currentTimeMillis() - timestamp, resourceHelper); - } - - public static String untilString(long timestamp, ResourceHelper resourceHelper) { - return timeFrameString(timestamp - System.currentTimeMillis(), resourceHelper); - } - - public long _now() { - return System.currentTimeMillis(); - } - - public long nowWithoutMilliseconds() { - long n = System.currentTimeMillis(); - n = n - n % 1000; - return n; - } - - public static long now() { - return System.currentTimeMillis(); - } - - public static long roundDateToSec(long date) { - return date - date % 1000; - } - - public static boolean isCloseToNow(long date) { - long diff = Math.abs(date - now()); - return diff < T.mins(2L).msecs(); - } - - public static boolean isOlderThan(long date, long minutes) { - long diff = now() - date; - return diff > T.mins(minutes).msecs(); - } - - public static long getTimeZoneOffsetMs() { - return new GregorianCalendar().getTimeZone().getRawOffset(); - } - - public static int getTimeZoneOffsetMinutes(final long timestamp) { - return TimeZone.getDefault().getOffset(timestamp) / 60000; - } - - //Map:{DAYS=1, HOURS=3, MINUTES=46, SECONDS=40, MILLISECONDS=0, MICROSECONDS=0, NANOSECONDS=0} - public static Map computeDiff(long date1, long date2) { - long diffInMillies = date2 - date1; - List units = new ArrayList<>(EnumSet.allOf(TimeUnit.class)); - Collections.reverse(units); - Map result = new LinkedHashMap<>(); - long milliesRest = diffInMillies; - for (TimeUnit unit : units) { - long diff = unit.convert(milliesRest, TimeUnit.MILLISECONDS); - long diffInMilliesForUnit = unit.toMillis(diff); - milliesRest = milliesRest - diffInMilliesForUnit; - result.put(unit, diff); - } - return result; - } - - public static String age(long milliseconds, boolean useShortText, ResourceHelper resourceHelper) { - Map diff = computeDiff(0L, milliseconds); - - String days = " " + resourceHelper.gs(R.string.days) + " "; - String hours = " " + resourceHelper.gs(R.string.hours) + " "; - String minutes = " " + resourceHelper.gs(R.string.unit_minutes) + " "; - - if (useShortText) { - days = resourceHelper.gs(R.string.shortday); - hours = resourceHelper.gs(R.string.shorthour); - minutes = resourceHelper.gs(R.string.shortminute); - } - - String result = ""; - if (diff.get(TimeUnit.DAYS) > 0) result += diff.get(TimeUnit.DAYS) + days; - if (diff.get(TimeUnit.HOURS) > 0) result += diff.get(TimeUnit.HOURS) + hours; - if (diff.get(TimeUnit.DAYS) == 0) result += diff.get(TimeUnit.MINUTES) + minutes; - return result; - } - - public static String niceTimeScalar(long t, ResourceHelper resourceHelper) { - String unit = resourceHelper.gs(R.string.unit_second); - t = t / 1000; - if (t != 1) unit = resourceHelper.gs(R.string.unit_seconds); - if (t > 59) { - unit = resourceHelper.gs(R.string.unit_minute); - t = t / 60; - if (t != 1) unit = resourceHelper.gs(R.string.unit_minutes); - if (t > 59) { - unit = resourceHelper.gs(R.string.unit_hour); - t = t / 60; - if (t != 1) unit = resourceHelper.gs(R.string.unit_hours); - if (t > 24) { - unit = resourceHelper.gs(R.string.unit_day); - t = t / 24; - if (t != 1) unit = resourceHelper.gs(R.string.unit_days); - if (t > 28) { - unit = resourceHelper.gs(R.string.unit_week); - t = t / 7; - if (t != 1) unit = resourceHelper.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((double) t, 0) + " " + unit; - } - - // singletons to avoid repeated allocation - private static DecimalFormatSymbols dfs; - private static DecimalFormat df; - - public static String qs(double x, int digits) { - - if (digits == -1) { - digits = 0; - if (((int) x != x)) { - digits++; - if ((((int) x * 10) / 10 != x)) { - digits++; - if ((((int) x * 100) / 100 != x)) digits++; - } - } - } - - if (dfs == null) { - final DecimalFormatSymbols local_dfs = new DecimalFormatSymbols(); - local_dfs.setDecimalSeparator('.'); - dfs = local_dfs; // avoid race condition - } - - final DecimalFormat this_df; - // use singleton if on ui thread otherwise allocate new as DecimalFormat is not thread safe - if (Thread.currentThread().getId() == 1) { - if (df == null) { - final DecimalFormat local_df = new DecimalFormat("#", dfs); - local_df.setMinimumIntegerDigits(1); - df = local_df; // avoid race condition - } - this_df = df; - } else { - this_df = new DecimalFormat("#", dfs); - } - - this_df.setMaximumFractionDigits(digits); - return this_df.format(x); - } - -} diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt new file mode 100644 index 0000000000..f5ef60d7f1 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -0,0 +1,304 @@ +package info.nightscout.androidaps.utils + +import android.content.Context +import androidx.collection.LongSparseArray +import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.joda.time.DateTime +import org.joda.time.format.DateTimeFormat +import org.joda.time.format.ISODateTimeFormat +import java.text.DateFormat +import java.text.DecimalFormat +import java.text.DecimalFormatSymbols +import java.text.SimpleDateFormat +import java.util.* +import java.util.concurrent.TimeUnit +import java.util.regex.Pattern +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.abs + +/** + * The Class DateUtil. A simple wrapper around SimpleDateFormat to ease the handling of iso date string <-> date obj + * with TZ + */ +@Singleton +open class DateUtil @Inject constructor(private val context: Context) { + + /** + * The date format in iso. + */ + @Suppress("PrivatePropertyName") + 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 + */ + 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 + * @param format - if not specified, will use FORMAT_DATE_ISO + * @param tz - tz to set to, if not specified uses local timezone + * @return the iso-formatted date string + */ + @JvmOverloads + fun toISOString(date: Long, format: String = FORMAT_DATE_ISO_OUT, tz: TimeZone = TimeZone.getTimeZone("UTC")): String { + val f: DateFormat = SimpleDateFormat(format, Locale.getDefault()) + f.timeZone = tz + return f.format(date) + } + + 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) + } + + 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(hh_colon_mm: String): Int { + val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)") + val m = p.matcher(hh_colon_mm) + 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 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(mills: Long): String { + var format = "hh:mma" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "HH:mm" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + private 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 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(resourceHelper: ResourceHelper, time: Long): String { + val mins = ((now() - time) / 1000 / 60).toInt() + return resourceHelper.gs(R.string.minago, mins) + } + + fun minAgoShort(time: Long): String { + val mins = ((time - now()) / 1000 / 60).toInt() + return (if (mins > 0) "+" else "") + mins + } + + fun hourAgo(time: Long, resourceHelper: ResourceHelper): String { + val hours = (now() - time) / 1000.0 / 60 / 60 + return resourceHelper.gs(R.string.hoursago, hours) + } + + 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, resourceHelper: ResourceHelper): String { + var remainingTimeMinutes = timeInMillis / (1000 * 60) + val remainingTimeHours = remainingTimeMinutes / 60 + remainingTimeMinutes %= 60 + return "(" + (if (remainingTimeHours > 0) remainingTimeHours.toString() + resourceHelper.gs(R.string.shorthour) + " " else "") + remainingTimeMinutes + "')" + } + + fun sinceString(timestamp: Long, resourceHelper: ResourceHelper): String { + return timeFrameString(System.currentTimeMillis() - timestamp, resourceHelper) + } + + fun untilString(timestamp: Long, resourceHelper: ResourceHelper): String { + return timeFrameString(timestamp - System.currentTimeMillis(), resourceHelper) + } + + fun now(): Long { + return System.currentTimeMillis() + } + + fun nowWithoutMilliseconds(): Long { + var n = System.currentTimeMillis() + n -= n % 1000 + return n + } + + fun isCloseToNow(date: Long): Boolean { + val diff = abs(date - now()) + return diff < T.mins(2L).msecs() + } + + 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 + } + + //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, resourceHelper: ResourceHelper): String { + val diff = computeDiff(0L, milliseconds) + var days = " " + resourceHelper.gs(R.string.days) + " " + var hours = " " + resourceHelper.gs(R.string.hours) + " " + var minutes = " " + resourceHelper.gs(R.string.unit_minutes) + " " + if (useShortText) { + days = resourceHelper.gs(R.string.shortday) + hours = resourceHelper.gs(R.string.shorthour) + minutes = resourceHelper.gs(R.string.shortminute) + } + var result = "" + if (diff[TimeUnit.DAYS]!! > 0) result += diff[TimeUnit.DAYS].toString() + days + if (diff[TimeUnit.HOURS]!! > 0) result += diff[TimeUnit.HOURS].toString() + hours + if (diff[TimeUnit.DAYS] == 0L) result += diff[TimeUnit.MINUTES].toString() + minutes + return result + } + + fun niceTimeScalar(time: Long, resourceHelper: ResourceHelper): String { + var t = time + var unit = resourceHelper.gs(R.string.unit_second) + t /= 1000 + if (t != 1L) unit = resourceHelper.gs(R.string.unit_seconds) + if (t > 59) { + unit = resourceHelper.gs(R.string.unit_minute) + t /= 60 + if (t != 1L) unit = resourceHelper.gs(R.string.unit_minutes) + if (t > 59) { + unit = resourceHelper.gs(R.string.unit_hour) + t /= 60 + if (t != 1L) unit = resourceHelper.gs(R.string.unit_hours) + if (t > 24) { + unit = resourceHelper.gs(R.string.unit_day) + t /= 24 + if (t != 1L) unit = resourceHelper.gs(R.string.unit_days) + if (t > 28) { + unit = resourceHelper.gs(R.string.unit_week) + t /= 7 + if (t != 1L) unit = resourceHelper.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) + } + + companion object { + + private val timeStrings = LongSparseArray() + + // singletons to avoid repeated allocation + private var dfs: DecimalFormatSymbols? = null + private var df: DecimalFormat? = null + } +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt index 054064efe0..d1977090ac 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt @@ -12,11 +12,12 @@ import javax.inject.Singleton class TimerUtil @Inject constructor( private val context: Context, private val resourceHelper: ResourceHelper, + private val dateUtil: DateUtil ) { fun scheduleReminder(time: Long, text: String? = null) { Intent(AlarmClock.ACTION_SET_TIMER).apply { - val length: Int = ((time - DateUtil.now()) / 1000).toInt() + val length: Int = ((time - dateUtil.now()) / 1000).toInt() flags = flags or Intent.FLAG_ACTIVITY_NEW_TASK putExtra(AlarmClock.EXTRA_LENGTH, length) putExtra(AlarmClock.EXTRA_SKIP_UI, true) diff --git a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index be4e29d439..f6a8baeb83 100644 --- a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -43,6 +43,7 @@ open class TestBaseWithProfile : TestBase() { it.rxBus = rxBus it.fabricPrivacy = fabricPrivacy it.configInterface = configInterface + it.dateUtil = dateUtil } if (it is ProfileSwitch) { it.treatmentsPlugin = treatmentsInterface diff --git a/core/src/test/java/info/nightscout/androidaps/data/IobTotalTest.kt b/core/src/test/java/info/nightscout/androidaps/data/IobTotalTest.kt index ebcf20c4af..bfe97bc80a 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/IobTotalTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/IobTotalTest.kt @@ -1,16 +1,29 @@ package info.nightscout.androidaps.data +import android.content.Context import info.nightscout.androidaps.utils.DateUtil import org.junit.Assert +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith +import org.mockito.Mock import org.powermock.modules.junit4.PowerMockRunner @Suppress("SpellCheckingInspection") @RunWith(PowerMockRunner::class) class IobTotalTest { - var now = DateUtil.now() + @Mock lateinit var context: Context + + lateinit var dateUtil: DateUtil + var now = 0L + + @Before + fun prepare() { + dateUtil = DateUtil(context) + now = dateUtil.now() + } + @Test fun copyTest() { val a = IobTotal(now) a.iob = 10.0 @@ -94,11 +107,11 @@ class IobTotalTest { a.netInsulin = 16.0 a.extendedBolusInsulin = 17.0 try { - val j = a.json() + val j = a.json(dateUtil) Assert.assertEquals(a.iob, j.getDouble("iob"), 0.0000001) Assert.assertEquals(a.basaliob, j.getDouble("basaliob"), 0.0000001) Assert.assertEquals(a.activity, j.getDouble("activity"), 0.0000001) - Assert.assertEquals(now.toFloat(), DateUtil.fromISODateString(j.getString("time")).time.toFloat(), 1000f) + Assert.assertEquals(now, dateUtil.fromISODateString(j.getString("time"))) } catch (e: Exception) { Assert.fail("Exception: " + e.message) } @@ -116,13 +129,13 @@ class IobTotalTest { a.extendedBolusInsulin = 17.0 a.iobWithZeroTemp = IobTotal(now) try { - val j = a.determineBasalJson() + val j = a.determineBasalJson(dateUtil) Assert.assertEquals(a.iob, j.getDouble("iob"), 0.0000001) Assert.assertEquals(a.basaliob, j.getDouble("basaliob"), 0.0000001) Assert.assertEquals(a.bolussnooze, j.getDouble("bolussnooze"), 0.0000001) Assert.assertEquals(a.activity, j.getDouble("activity"), 0.0000001) Assert.assertEquals(0, j.getLong("lastBolusTime")) - Assert.assertEquals(now.toFloat(), DateUtil.fromISODateString(j.getString("time")).time.toFloat(), 1000f) + Assert.assertEquals(now, dateUtil.fromISODateString(j.getString("time"))) Assert.assertNotNull(j.getJSONObject("iobWithZeroTemp")) } catch (e: Exception) { Assert.fail("Exception: " + e.message) diff --git a/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt index 2fe370aa9c..2f0c580b83 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt @@ -4,7 +4,6 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import org.junit.Assert import org.junit.Test @@ -14,7 +13,7 @@ import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class NonOverlappingIntervalsTest : TestBase() { - private val startDate = DateUtil.now() + private val startDate = System.currentTimeMillis() var list = NonOverlappingIntervals() val injector = HasAndroidInjector { AndroidInjector {} } diff --git a/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt index 9973fb69dc..09b41eb0fb 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.data -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import org.junit.Assert import org.junit.Test @@ -11,7 +10,7 @@ import java.util.* @RunWith(PowerMockRunner::class) class OverlappingIntervalsTest { - private val startDate = DateUtil.now() + private val startDate = System.currentTimeMillis() private var list = OverlappingIntervals() @Test fun doTests() { // create one 10h interval and test value in and out diff --git a/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt index 422634c5cc..c1b1b25323 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.data import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin import info.nightscout.androidaps.db.ProfileSwitch -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import org.junit.Assert import org.junit.Before @@ -17,7 +16,7 @@ import java.util.* class ProfileIntervalsTest : TestBaseWithProfile() { lateinit var testPumpPlugin: TestPumpPlugin - private val startDate = DateUtil.now() + private val startDate = System.currentTimeMillis() var list = ProfileIntervals() @Before @@ -32,12 +31,12 @@ class ProfileIntervalsTest : TestBaseWithProfile() { list.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(10).mins().toInt()).profileName("1").profile(validProfile)) // for older date first record should be returned only if has zero duration Assert.assertEquals(null, list.getValueToTime(startDate - T.secs(1).msecs())) - Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch?)!!.profileName) + Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch).profileName) Assert.assertEquals(null, list.getValueToTime(startDate + T.hours(10).msecs() + 1)) list.reset() list.add(ProfileSwitch(profileInjector).date(startDate).profileName("1").profile(validProfile)) Assert.assertEquals("1", (list.getValueToTime(startDate - T.secs(1).msecs()) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch?)!!.profileName) + Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch).profileName) Assert.assertEquals("1", (list.getValueToTime(startDate + T.hours(10).msecs() + 1) as ProfileSwitch?)!!.profileName) // switch to different profile after 5h diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt index dbfc9aa809..d443f2d603 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/iob/iobCalculator/GlucoseStatusTest.kt @@ -42,7 +42,7 @@ class GlucoseStatusTest : TestBase() { @Test fun calculateValidGlucoseStatus() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateValidBgData()) - val glucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData!! + val glucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! Assert.assertEquals(214.0, glucoseStatus.glucose, 0.001) Assert.assertEquals(-2.0, glucoseStatus.delta, 0.001) Assert.assertEquals(-2.5, glucoseStatus.shortAvgDelta, 0.001) // -2 -2.5 -3 deltas are relative to current value @@ -52,7 +52,7 @@ class GlucoseStatusTest : TestBase() { @Test fun calculateMostRecentGlucoseStatus() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateMostRecentBgData()) - val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData!! + val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! Assert.assertEquals(215.0, glucoseStatus.glucose, 0.001) // (214+216) / 2 Assert.assertEquals(-1.0, glucoseStatus.delta, 0.001) Assert.assertEquals(-1.0, glucoseStatus.shortAvgDelta, 0.001) @@ -62,7 +62,7 @@ class GlucoseStatusTest : TestBase() { @Test fun oneRecordShouldProduceZeroDeltas() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateOneCurrentRecordBgData()) - val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData!! + val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! Assert.assertEquals(214.0, glucoseStatus.glucose, 0.001) Assert.assertEquals(0.0, glucoseStatus.delta, 0.001) Assert.assertEquals(0.0, glucoseStatus.shortAvgDelta, 0.001) // -2 -2.5 -3 deltas are relative to current value @@ -72,19 +72,19 @@ class GlucoseStatusTest : TestBase() { @Test fun insufficientDataShouldReturnNull() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateInsufficientBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData + val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData Assert.assertEquals(null, glucoseStatus) } @Test fun oldDataShouldReturnNull() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateOldBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData + val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData Assert.assertEquals(null, glucoseStatus) } @Test fun returnOldDataIfAllowed() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateOldBgData()) - val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).getGlucoseStatusData(true) + val glucoseStatus: GlucoseStatus? = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).getGlucoseStatusData(true) Assert.assertNotEquals(null, glucoseStatus) } @@ -94,7 +94,7 @@ class GlucoseStatusTest : TestBase() { @Test fun calculateGlucoseStatusForLibreTestBgData() { PowerMockito.`when`(iobCobCalculatorPlugin.bgReadings).thenReturn(generateLibreTestData()) - val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin).glucoseStatusData!! + val glucoseStatus: GlucoseStatus = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil).glucoseStatusData!! Assert.assertEquals(100.0, glucoseStatus.glucose, 0.001) // Assert.assertEquals(-10.0, glucoseStatus.delta, 0.001) Assert.assertEquals(-10.0, glucoseStatus.shortAvgDelta, 0.001) @@ -104,8 +104,7 @@ class GlucoseStatusTest : TestBase() { @Before fun initMocking() { - PowerMockito.mockStatic(DateUtil::class.java) - PowerMockito.`when`(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()) + PowerMockito.`when`(dateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()) `when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any()) } diff --git a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt index 41590e7b48..57119d66bd 100644 --- a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt @@ -20,43 +20,38 @@ class DateUtilTest : TestBase() { @Test fun fromISODateStringTest() { - Assert.assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").time) - Assert.assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").time) - Assert.assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").time) - Assert.assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").time) + Assert.assertEquals(1511124634417L, DateUtil(context).fromISODateString("2017-11-19T22:50:34.417+0200")) + Assert.assertEquals(1511124634000L, DateUtil(context).fromISODateString("2017-11-19T22:50:34+0200")) + Assert.assertEquals(1512317365000L, DateUtil(context).fromISODateString("2017-12-03T16:09:25.000Z")) + Assert.assertEquals(1513902750000L, DateUtil(context).fromISODateString("2017-12-22T00:32:30Z")) } @Test fun toISOStringTest() { - Assert.assertEquals("2017-12-22T00:32:30.000Z", DateUtil.toISOString(Date(1513902750000L))) - Assert.assertEquals("2017-12-22T00:32:30.000Z", DateUtil.toISOString(1513902750000L)) + Assert.assertEquals("2017-12-22T00:32:30.000Z", DateUtil(context).toISOString(1513902750000L)) } - @Test fun toDateTest() { - Assert.assertTrue(DateUtil.toDate((T.hours(1).secs() + T.mins(1).secs() + 1).toInt()).toString().contains("01:01:00")) + @Test fun secondsOfTheDayToMillisecondsTest() { + Assert.assertTrue(Date(DateUtil(context).secondsOfTheDayToMilliseconds((T.hours(1).secs() + T.mins(1).secs() + 1).toInt())).toString().contains("01:01:00")) } @Test fun toSecondsTest() { - Assert.assertEquals(3600, DateUtil.toSeconds("01:00").toLong()) - Assert.assertEquals(3600, DateUtil.toSeconds("01:00 a.m.").toLong()) - Assert.assertEquals(3600, DateUtil.toSeconds("01:00 AM").toLong()) + Assert.assertEquals(3600, DateUtil(context).toSeconds("01:00").toLong()) + Assert.assertEquals(3600, DateUtil(context).toSeconds("01:00 a.m.").toLong()) + Assert.assertEquals(3600, DateUtil(context).toSeconds("01:00 AM").toLong()) } @Test fun dateStringTest() { - Assert.assertTrue(DateUtil.dateString(Date(1513902750000L)).contains("22")) - Assert.assertTrue(DateUtil.dateString(1513902750000L).contains("22")) + Assert.assertTrue(DateUtil(context).dateString(1513902750000L).contains("22")) } @Test fun timeStringTest() { - Assert.assertTrue(DateUtil(context).timeString(Date(1513902750000L)).contains("32")) Assert.assertTrue(DateUtil(context).timeString(1513902750000L).contains("32")) } @Test fun dateAndTimeStringTest() { Assert.assertTrue(DateUtil(context).dateAndTimeString(1513902750000L).contains("22")) Assert.assertTrue(DateUtil(context).dateAndTimeString(1513902750000L).contains("32")) - Assert.assertTrue(DateUtil(context).dateAndTimeString(Date(1513902750000L)).contains("22")) - Assert.assertTrue(DateUtil(context).dateAndTimeString(Date(1513902750000L)).contains("32")) } @Test fun dateAndTimeRangeStringTest() { @@ -74,6 +69,6 @@ class DateUtilTest : TestBase() { */ @Test fun timeFrameStringTest() { `when`(resourceHelper.gs(R.string.shorthour)).thenReturn("h") - Assert.assertEquals("(1h 1')", DateUtil.timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), resourceHelper)) + Assert.assertEquals("(1h 1')", DateUtil(context).timeFrameString(T.hours(1).msecs() + T.mins(1).msecs(), resourceHelper)) } } \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java b/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java deleted file mode 100644 index 28a6b1cc31..0000000000 --- a/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package info.nightscout.androidaps.utils; - - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import java.util.Calendar; - -/** - * Created by mike on 20.11.2017. - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({Calendar.class}) -public class MidnightTimeTest { - - @Test - public void calc() { - // We get real midnight - long now = DateUtil.now(); - Assert.assertTrue(now >= MidnightTime.calc()); - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(MidnightTime.calc()); - Assert.assertEquals(c.get(Calendar.HOUR_OF_DAY), 0); - Assert.assertEquals(c.get(Calendar.MINUTE), 0); - Assert.assertEquals(c.get(Calendar.SECOND), 0); - Assert.assertEquals(c.get(Calendar.MILLISECOND), 0); - } - - @Test - public void calc_time() { - // We get real midnight - long now = DateUtil.now(); - long midnight = MidnightTime.calc(now); - Assert.assertTrue(now >= midnight); - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(MidnightTime.calc(now)); - Assert.assertEquals(c.get(Calendar.HOUR_OF_DAY), 0); - Assert.assertEquals(c.get(Calendar.MINUTE), 0); - Assert.assertEquals(c.get(Calendar.SECOND), 0); - Assert.assertEquals(c.get(Calendar.MILLISECOND), 0); - // Assure we get the same time from cache - Assert.assertEquals(midnight, MidnightTime.calc(now)); - } - - @Test - public void resetCache() { - long now = DateUtil.now(); - MidnightTime.calc(now); - MidnightTime.resetCache(); - Assert.assertEquals(0, MidnightTime.times.size()); - } - - @Test - public void log() { - long now = DateUtil.now(); - MidnightTime.calc(now); - Assert.assertTrue(MidnightTime.log().startsWith("Hits:")); - } -} diff --git a/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.kt new file mode 100644 index 0000000000..528dc1c094 --- /dev/null +++ b/core/src/test/java/info/nightscout/androidaps/utils/MidnightTimeTest.kt @@ -0,0 +1,48 @@ +package info.nightscout.androidaps.utils + +import org.junit.Assert +import org.junit.Test +import java.util.* + +class MidnightTimeTest { + + @Test fun calc() { + // We get real midnight + val now = System.currentTimeMillis() + Assert.assertTrue(now >= MidnightTime.calc()) + val c = Calendar.getInstance() + c.timeInMillis = MidnightTime.calc() + Assert.assertEquals(c[Calendar.HOUR_OF_DAY].toLong(), 0) + Assert.assertEquals(c[Calendar.MINUTE].toLong(), 0) + Assert.assertEquals(c[Calendar.SECOND].toLong(), 0) + Assert.assertEquals(c[Calendar.MILLISECOND].toLong(), 0) + } + + @Test fun calc_time() { + // We get real midnight + val now = System.currentTimeMillis() + val midnight = MidnightTime.calc(now) + Assert.assertTrue(now >= midnight) + val c = Calendar.getInstance() + c.timeInMillis = MidnightTime.calc(now) + Assert.assertEquals(c[Calendar.HOUR_OF_DAY].toLong(), 0) + Assert.assertEquals(c[Calendar.MINUTE].toLong(), 0) + Assert.assertEquals(c[Calendar.SECOND].toLong(), 0) + Assert.assertEquals(c[Calendar.MILLISECOND].toLong(), 0) + // Assure we get the same time from cache + Assert.assertEquals(midnight, MidnightTime.calc(now)) + } + + @Test fun resetCache() { + val now = System.currentTimeMillis() + MidnightTime.calc(now) + MidnightTime.resetCache() + Assert.assertEquals(0, MidnightTime.times.size().toLong()) + } + + @Test fun log() { + val now = System.currentTimeMillis() + MidnightTime.calc(now) + Assert.assertTrue(MidnightTime.log().startsWith("Hits:")) + } +} \ No newline at end of file diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt index 0152e83c48..1c6e3d152d 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt @@ -91,7 +91,7 @@ class DanaFragment : DaggerFragment() { val profileName = danaPump.createConvertedProfile()?.getDefaultProfileName() ?: return@setOnClickListener val args = Bundle() - args.putLong("time", DateUtil.now()) + args.putLong("time", dateUtil.now()) args.putInt("mode", ProfileViewerDialog.Mode.CUSTOM_PROFILE.ordinal) args.putString("customProfile", profile.data.toString()) args.putString("customProfileUnits", profile.units) @@ -201,7 +201,7 @@ class DanaFragment : DaggerFragment() { val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 if (agoHours < 6) // max 6h back - binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) else binding.lastbolus.text = "" } diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt index 5713c7788b..09f961eb2a 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt @@ -132,7 +132,7 @@ class DanaPump @Inject constructor( } get() = T.msecs(tempBasalDuration).mins() var isTempBasalInProgress: Boolean - get() = tempBasalStart != 0L && dateUtil._now() in tempBasalStart..tempBasalStart + tempBasalDuration + get() = tempBasalStart != 0L && dateUtil.now() in tempBasalStart..tempBasalStart + tempBasalDuration set(isRunning) { if (isRunning) throw IllegalArgumentException("Use to cancel TBR only") else { @@ -142,12 +142,12 @@ class DanaPump @Inject constructor( } } val tempBasalRemainingMin: Int - get() = max(T.msecs(tempBasalStart + tempBasalDuration - dateUtil._now()).mins().toInt(), 0) + get() = max(T.msecs(tempBasalStart + tempBasalDuration - dateUtil.now()).mins().toInt(), 0) fun temporaryBasalToString(): String { if (!isTempBasalInProgress) return "" - val passedMin = ((min(dateUtil._now(), tempBasalStart + tempBasalDuration) - tempBasalStart) / 60.0 / 1000).roundToInt() + val passedMin = ((min(dateUtil.now(), tempBasalStart + tempBasalDuration) - tempBasalStart) / 60.0 / 1000).roundToInt() return tempBasalPercent.toString() + "% @" + dateUtil.timeString(tempBasalStart) + " " + passedMin + "/" + T.msecs(tempBasalDuration).mins() + "'" @@ -174,7 +174,7 @@ class DanaPump @Inject constructor( var extendedBolusAmount = 0.0 var isExtendedInProgress: Boolean - get() = extendedBolusStart != 0L && dateUtil._now() in extendedBolusStart..extendedBolusStart + extendedBolusDuration + get() = extendedBolusStart != 0L && dateUtil.now() in extendedBolusStart..extendedBolusStart + extendedBolusDuration set(isRunning) { if (isRunning) throw IllegalArgumentException("Use to cancel EB only") else { @@ -184,9 +184,9 @@ class DanaPump @Inject constructor( } } val extendedBolusPassedMinutes: Int - get() = T.msecs(max(0, dateUtil._now() - extendedBolusStart)).mins().toInt() + get() = T.msecs(max(0, dateUtil.now() - extendedBolusStart)).mins().toInt() val extendedBolusRemainingMinutes: Int - get() = max(T.msecs(extendedBolusStart + extendedBolusDuration - dateUtil._now()).mins().toInt(), 0) + get() = max(T.msecs(extendedBolusStart + extendedBolusDuration - dateUtil.now()).mins().toInt(), 0) private val extendedBolusDurationInMinutes: Int get() = T.msecs(extendedBolusDuration).mins().toInt() var extendedBolusAbsoluteRate: Double diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt index 2ce2c0164b..b631b05efa 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/activities/DanaHistoryActivity.kt @@ -185,7 +185,7 @@ class DanaHistoryActivity : NoSplashAppCompatActivity() { holder.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBasal) holder.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBolus) holder.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.recordDailyBolus + record.recordDailyBasal) - holder.time.text = DateUtil.dateString(record.recordDate) + holder.time.text = dateUtil.dateString(record.recordDate) holder.time.visibility = View.VISIBLE holder.value.visibility = View.GONE holder.stringValue.visibility = View.GONE diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java index 2b5ad8633e..76b614df6e 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.java @@ -185,7 +185,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { detailedBolusInfo.timestamp, detailedBolusInfo.insulin, detailedBolusInfo.getBolusType(), - dateUtil._now(), + dateUtil.now(), PumpType.DANA_R_KOREAN, serialNumber() ); @@ -348,8 +348,8 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { sExecutionService.tempBasalStop(); if (!danaPump.isTempBasalInProgress()) { pumpSync.syncStopTemporaryBasalWithPumpId( - dateUtil._now(), - dateUtil._now(), + dateUtil.now(), + dateUtil.now(), getPumpDescription().getPumpType(), serialNumber() ); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java index 735eaa3c77..02ae08ec28 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java @@ -72,6 +72,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject ActivePluginProvider activePlugin; @Inject ProfileFunction profileFunction; @Inject PumpSync pumpSync; + @Inject DateUtil dateUtil; public DanaRKoreanExecutionService() { } @@ -183,7 +184,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (Math.abs(timeDiff) > 10) { waitForWholeMinute(); // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cut off anyway) - mSerialIOThread.sendMessage(new MsgSetTime(injector, DateUtil.now() + T.secs(10).msecs())); + mSerialIOThread.sendMessage(new MsgSetTime(injector, dateUtil.now() + T.secs(10).msecs())); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index 2da5d829d5..72d70a14ab 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -175,7 +175,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { speed = 60; break; } - detailedBolusInfo.timestamp = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000); + detailedBolusInfo.timestamp = dateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000); // clean carbs to prevent counting them as twice because they will picked up as another record // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records double carbs = detailedBolusInfo.carbs; @@ -189,7 +189,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { EventOverviewBolusProgress.Treatment t = new EventOverviewBolusProgress.Treatment(0, 0, detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB); boolean connectionOK = false; if (detailedBolusInfo.insulin > 0 || carbs > 0) - connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); + connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) carbs, dateUtil.now() + T.mins(carbTime).msecs(), t); PumpEnactResult result = new PumpEnactResult(getInjector()); result.success(connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.getBolusStep()) .bolusDelivered(t.insulin) @@ -260,7 +260,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } } } - temporaryBasalStorage.add(new PumpSync.PumpState.TemporaryBasal(dateUtil._now(), T.mins(durationInMinutes).msecs(), percentRate, false, tbrType, 0L, 0L)); + temporaryBasalStorage.add(new PumpSync.PumpState.TemporaryBasal(dateUtil.now(), T.mins(durationInMinutes).msecs(), percentRate, false, tbrType, 0L, 0L)); // Convert duration from minutes to hours aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " minutes (doLowTemp || doHighTemp)"); if (percentRate == 0 && durationInMinutes > 30) { @@ -299,7 +299,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { aapsLogger.debug(LTag.PUMP, "setTempBasalPercent: Correct value already set"); return result; } - temporaryBasalStorage.add(new PumpSync.PumpState.TemporaryBasal(dateUtil._now(), T.mins(durationInMinutes).msecs(), percent, false, tbrType, 0L, 0L)); + temporaryBasalStorage.add(new PumpSync.PumpState.TemporaryBasal(dateUtil.now(), T.mins(durationInMinutes).msecs(), percent, false, tbrType, 0L, 0L)); boolean connectionOK; if (durationInMinutes == 15 || durationInMinutes == 30) { connectionOK = sExecutionService.tempBasalShortDuration(percent, durationInMinutes); diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt index 34ebfb0787..0cd213a56a 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt @@ -6,7 +6,6 @@ import info.nightscout.androidaps.danar.comm.MessageBase import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.common.defs.PumpType -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import java.util.* @@ -22,7 +21,7 @@ class MsgHistoryEvents_v2 constructor( init { SetCommand(0xE003) - if (from > DateUtil.now()) { + if (from > dateUtil.now()) { aapsLogger.error("Asked to load from the future") from = 0 } diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java index a88a52346f..73532ab9b1 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java @@ -203,7 +203,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } else { waitForWholeMinute(); // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cutted off anyway) - mSerialIOThread.sendMessage(new MsgSetTime(injector, DateUtil.now() + T.secs(10).msecs())); + mSerialIOThread.sendMessage(new MsgSetTime(injector, dateUtil.now() + T.secs(10).msecs())); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index 9958f99b43..e6136df269 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -5,8 +5,6 @@ import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; -import java.util.Date; - import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.dana.DanaFragment; import info.nightscout.androidaps.dana.DanaPump; @@ -328,8 +326,8 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump if (!danaPump.isExtendedInProgress()) { result.success(true).enacted(true).isTempCancel(true); pumpSync.syncStopExtendedBolusWithPumpId( - dateUtil._now(), - dateUtil._now(), + dateUtil.now(), + dateUtil.now(), getPumpDescription().getPumpType(), serialNumber() ); @@ -394,7 +392,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump try { battery.put("percent", pump.getBatteryRemaining()); status.put("status", pump.getPumpSuspended() ? "suspended" : "normal"); - status.put("timestamp", DateUtil.toISOString(pump.getLastConnection())); + status.put("timestamp", dateUtil.toISOString(pump.getLastConnection())); extended.put("Version", version); if (pump.getLastBolusTime() != 0) { extended.put("LastBolus", dateUtil.dateAndTimeString(pump.getLastBolusTime())); @@ -421,7 +419,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump pumpJson.put("status", status); pumpJson.put("extended", extended); pumpJson.put("reservoir", (int) pump.getReservoirRemainingUnits()); - pumpJson.put("clock", DateUtil.toISOString(new Date())); + pumpJson.put("clock", dateUtil.toISOString(dateUtil.now())); } catch (JSONException e) { getAapsLogger().error("Unhandled exception", e); } diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index a4b20df5bc..3cc4aa1154 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -182,7 +182,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { detailedBolusInfo.timestamp, detailedBolusInfo.insulin, detailedBolusInfo.getBolusType(), - dateUtil._now(), + dateUtil.now(), PumpType.DANA_R, serialNumber()); if (detailedBolusInfo.carbs > 0) @@ -342,8 +342,8 @@ public class DanaRPlugin extends AbstractDanaRPlugin { sExecutionService.tempBasalStop(); if (!danaPump.isTempBasalInProgress()) { pumpSync.syncStopTemporaryBasalWithPumpId( - dateUtil._now(), - dateUtil._now(), + dateUtil.now(), + dateUtil.now(), getPumpDescription().getPumpType(), serialNumber() ); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusTempBasal.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusTempBasal.kt index 69df6d4157..6196357bce 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusTempBasal.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusTempBasal.kt @@ -4,7 +4,6 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.T import kotlin.math.abs -import kotlin.math.ceil import kotlin.math.floor class MsgStatusTempBasal( @@ -49,7 +48,7 @@ class MsgStatusTempBasal( } private fun getDateFromSecAgo(tempBasalAgoSecs: Int): Long { - return (floor(dateUtil._now() / 1000.0) - tempBasalAgoSecs).toLong() * 1000 + return (floor(dateUtil.now() / 1000.0) - tempBasalAgoSecs).toLong() * 1000 } // because there is no fixed timestamp of start allow update of tbr only if tbr start differs more diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java index aad07e6a3f..2eac4030e9 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java @@ -279,7 +279,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { protected void waitForWholeMinute() { while (true) { - long time = DateUtil.now(); + long time = dateUtil.now(); long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 3000) break; @@ -312,8 +312,8 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { } } else { pumpSync.syncStopTemporaryBasalWithPumpId( - dateUtil._now(), - dateUtil._now(), + dateUtil.now(), + dateUtil.now(), activePlugin.getActivePump().model(), activePlugin.getActivePump().serialNumber() ); @@ -358,8 +358,8 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { } } else { pumpSync.syncStopExtendedBolusWithPumpId( - dateUtil._now(), - dateUtil._now(), + dateUtil.now(), + dateUtil.now(), activePlugin.getActivePump().model(), activePlugin.getActivePump().serialNumber() ); diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java index 136a98bb34..bd12d27e2d 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java @@ -61,7 +61,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -191,7 +190,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { long timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { - mSerialIOThread.sendMessage(new MsgSetTime(injector, DateUtil.now())); + mSerialIOThread.sendMessage(new MsgSetTime(injector, dateUtil.now())); mSerialIOThread.sendMessage(new MsgSettingPumpTime(injector)); timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt index fd48e38078..0b9379bfa2 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -274,7 +274,7 @@ class DanaRSPlugin @Inject constructor( } // RS stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U - detailedBolusInfo.timestamp = DateUtil.now() + (speed * detailedBolusInfo.insulin * 1000).toLong() + detailedBolusInfo.timestamp = dateUtil.now() + (speed * detailedBolusInfo.insulin * 1000).toLong() // clean carbs to prevent counting them as twice because they will picked up as another record // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records val carbs = detailedBolusInfo.carbs @@ -285,7 +285,7 @@ class DanaRSPlugin @Inject constructor( detailedBolusInfoStorage.add(detailedBolusInfo) // will be picked up on reading history val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) var connectionOK = false - if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = danaRSService?.bolus(detailedBolusInfo.insulin, carbs.toInt(), DateUtil.now() + T.mins(carbTime.toLong()).msecs(), t) + if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = danaRSService?.bolus(detailedBolusInfo.insulin, carbs.toInt(), dateUtil.now() + T.mins(carbTime.toLong()).msecs(), t) ?: false val result = PumpEnactResult(injector) result.success = connectionOK && abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep @@ -368,7 +368,7 @@ class DanaRSPlugin @Inject constructor( } } } - temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil._now(), mins(durationInMinutes.toLong()).msecs(), percentRate.toDouble(), false, tbrType, 0L, 0L)) + temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil.now(), mins(durationInMinutes.toLong()).msecs(), percentRate.toDouble(), false, tbrType, 0L, 0L)) // Convert duration from minutes to hours aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal $percentRate% for $durationInMinutes minutes (doLowTemp || doHighTemp)") result = if (percentRate == 0 && durationInMinutes > 30) { @@ -415,7 +415,7 @@ class DanaRSPlugin @Inject constructor( aapsLogger.debug(LTag.PUMP, "setTempBasalPercent: Correct value already set") return result } - temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil._now(), mins(durationInMinutes.toLong()).msecs(), percent.toDouble(), false, tbrType, 0L, 0L)) + temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil.now(), mins(durationInMinutes.toLong()).msecs(), percent.toDouble(), false, tbrType, 0L, 0L)) val connectionOK: Boolean = if (durationInMinutes == 15 || durationInMinutes == 30) { danaRSService?.tempBasalShortDuration(percentAfterConstraint, durationInMinutes) ?: false @@ -546,7 +546,7 @@ class DanaRSPlugin @Inject constructor( try { battery.put("percent", danaPump.batteryRemaining) status.put("status", if (danaPump.pumpSuspended) "suspended" else "normal") - status.put("timestamp", DateUtil.toISOString(danaPump.lastConnection)) + status.put("timestamp", dateUtil.toISOString(danaPump.lastConnection)) extended.put("Version", version) if (danaPump.lastBolusTime != 0L) { extended.put("LastBolus", dateUtil.dateAndTimeString(danaPump.lastBolusTime)) @@ -574,7 +574,7 @@ class DanaRSPlugin @Inject constructor( pumpJson.put("status", status) pumpJson.put("extended", extended) pumpJson.put("reservoir", danaPump.reservoirRemainingUnits.toInt()) - pumpJson.put("clock", DateUtil.toISOString(now)) + pumpJson.put("clock", dateUtil.toISOString(now)) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt index 8d5efb853e..5e6b49a66a 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt @@ -12,7 +12,6 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage import info.nightscout.androidaps.plugins.pump.common.defs.PumpType -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -40,7 +39,7 @@ open class DanaRS_Packet_APS_History_Events( init { opCode = BleEncryption.DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS - if (from > DateUtil.now()) { + if (from > dateUtil.now()) { aapsLogger.debug(LTag.PUMPCOMM, "Asked to load from the future") from = 0 } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index d2abeed7a6..abd5cf6eb2 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -48,7 +48,8 @@ class BLEComm @Inject internal constructor( private val danaPump: DanaPump, private val danaRSPlugin: DanaRSPlugin, private val bleEncryption: BleEncryption, - private val pumpSync: PumpSync + private val pumpSync: PumpSync, + private val dateUtil: DateUtil ) { companion object { @@ -140,7 +141,7 @@ class BLEComm @Inject internal constructor( // there was no response from pump after started encryption // assume pairing keys are invalid val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0) - if (lastClearRequest != 0L && DateUtil.isOlderThan(lastClearRequest, 5)) { + if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) { aapsLogger.error("Clearing pairing keys !!!") sp.remove(resourceHelper.gs(R.string.key_danars_v3_randompairingkey) + danaRSPlugin.mDeviceName) sp.remove(resourceHelper.gs(R.string.key_danars_v3_pairingkey) + danaRSPlugin.mDeviceName) @@ -149,7 +150,7 @@ class BLEComm @Inject internal constructor( danaRSPlugin.changePump() } else if (lastClearRequest == 0L) { aapsLogger.error("Clearing pairing keys postponed") - sp.putLong(R.string.key_rs_last_clear_key_request, DateUtil.now()) + sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now()) } } // cancel previous scheduled disconnection to prevent closing upcoming connection diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index 6df71516d6..f3b6f159d1 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -171,17 +171,17 @@ class DanaRSService : DaggerService() { } else { when { danaPump.usingUTC -> { - sendMessage(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector, DateUtil.now(), offset)) + sendMessage(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector, dateUtil.now(), offset)) } danaPump.protocol >= 6 -> { // can set seconds - sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now())) + sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, dateUtil.now())) } else -> { waitForWholeMinute() // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cut off anyway) - sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now() + T.secs(10).msecs())) + sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, dateUtil.now() + T.secs(10).msecs())) } } if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) @@ -255,7 +255,7 @@ class DanaRSService : DaggerService() { danaPump.bolusAmountToBeDelivered = insulin danaPump.bolusStopped = false danaPump.bolusStopForced = false - danaPump.bolusProgressLastTimeStamp = DateUtil.now() + danaPump.bolusProgressLastTimeStamp = dateUtil.now() val start = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(injector, insulin, preferencesSpeed) if (carbs > 0) { // MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbTime, carbs); #### @@ -481,7 +481,7 @@ class DanaRSService : DaggerService() { private fun waitForWholeMinute() { while (true) { - val time = DateUtil.now() + val time = dateUtil.now() val timeToWholeMinute = 60000 - time % 60000 if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt()))) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt index 9f55683786..0ec370e381 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage -import info.nightscout.androidaps.utils.DateUtil import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -48,7 +47,7 @@ class DanaRsPacketApsHistoryEventsTest : DanaRSTestBase() { } @Test fun runTest() { - val now = DateUtil.now() + val now = dateUtil.now() val testPacket = DanaRS_Packet_APS_History_Events(packetInjector, now) // test getRequestedParams diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt index c62418d039..07809e9dc5 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.danars.comm import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.danars.DanaRSTestBase -import info.nightscout.androidaps.utils.DateUtil import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @@ -25,7 +24,7 @@ class DanaRsPacketApsSetEventHistoryTest : DanaRSTestBase() { } @Test fun runTest() { // test for negative carbs - val now = DateUtil.now() + val now = dateUtil.now() var historyTest = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, -1, 0) var testParams = historyTest.requestParams Assert.assertEquals(0.toByte(), testParams[8]) 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 7d4a3a0193..8a924272ff 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 @@ -983,7 +983,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, final JSONObject status = new JSONObject(); final JSONObject extended = new JSONObject(); try { - status.put("timestamp", DateUtil.toISOString(connectionService.getLastConnected())); + status.put("timestamp", dateUtil.toISOString(connectionService.getLastConnected())); extended.put("Version", version); try { extended.put("ActiveProfile", profileFunction.getProfileName()); @@ -1003,7 +1003,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, extended.put("ExtendedBolusRemaining", getPlannedRemainingMinutes(eb)); } extended.put("BaseBasalRate", getBaseBasalRate()); - status.put("timestamp", DateUtil.toISOString(now)); + status.put("timestamp", dateUtil.toISOString(now)); pump.put("extended", extended); if (statusLoaded) { @@ -1013,7 +1013,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, pump.put("battery", battery); pump.put("reservoir", cartridgeStatus.getRemainingAmount()); } - pump.put("clock", DateUtil.toISOString(now)); + pump.put("clock", dateUtil.toISOString(now)); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index ad18d2543b..7023f8f06c 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -12,8 +12,6 @@ import androidx.annotation.NonNull; import org.json.JSONException; import org.json.JSONObject; -import java.util.Date; - import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.core.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -355,13 +353,13 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI extended.put("ExtendedBolusRemaining", getPlannedRemainingMinutes(eb)); } - status.put("timestamp", DateUtil.toISOString(new Date())); + status.put("timestamp", dateUtil.toISOString(dateUtil.now())); pump.put("battery", battery); pump.put("status", status); pump.put("extended", extended); pump.put("reservoir", getPumpStatusData().reservoirRemainingUnits); - pump.put("clock", DateUtil.toISOString(new Date())); + pump.put("clock", dateUtil.toISOString(dateUtil.now())); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } @@ -388,7 +386,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI } PumpSync.PumpState.ExtendedBolus activeExtendedBolus = pumpSync.expectedPumpState().getExtendedBolus(); if (activeExtendedBolus != null) { - ret += "Extended: " + PumpStateExtensionKt.toStringFull(activeTemp, dateUtil) + "\n"; + ret += "Extended: " + PumpStateExtensionKt.toStringFull(activeExtendedBolus, dateUtil) + "\n"; } // if (!veryShort) { // ret += "TDD: " + DecimalFormatter.to0Decimal(pumpStatus.dailyTotalUnits) + " / " diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java index bd30efd423..505cd1388f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java @@ -62,7 +62,7 @@ public abstract class PumpStatus { public abstract void initSettings(); public void setLastCommunicationToNow() { - this.lastDataTime = DateUtil.now(); + this.lastDataTime = System.currentTimeMillis(); this.lastConnection = System.currentTimeMillis(); } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index dab3c800f1..fea2656607 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -9,10 +9,10 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.extensions.toStringFull import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventTempBasalChange +import info.nightscout.androidaps.extensions.toStringFull import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PumpSync @@ -47,8 +47,6 @@ import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import javax.inject.Inject -import kotlin.math.min -import kotlin.math.roundToInt class MedtronicFragment : DaggerFragment() { @@ -269,7 +267,7 @@ class MedtronicFragment : DaggerFragment() { // last connection if (medtronicPumpStatus.lastConnection != 0L) { - val minAgo = DateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastConnection) + val minAgo = dateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastConnection) val min = (System.currentTimeMillis() - medtronicPumpStatus.lastConnection) / 1000 / 60 if (medtronicPumpStatus.lastConnection + 60 * 1000 > System.currentTimeMillis()) { binding.lastConnection.setText(R.string.medtronic_pump_connected_now) @@ -305,8 +303,8 @@ class MedtronicFragment : DaggerFragment() { val unit = resourceHelper.gs(R.string.insulin_unit_shortname) val ago = when { agoMsc < 60 * 1000 -> resourceHelper.gs(R.string.medtronic_pump_connected_now) - bolusMinAgo < 60 -> DateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastBolusTime.time) - else -> DateUtil.hourAgo(medtronicPumpStatus.lastBolusTime.time, resourceHelper) + bolusMinAgo < 60 -> dateUtil.minAgo(resourceHelper, medtronicPumpStatus.lastBolusTime.time) + else -> dateUtil.hourAgo(medtronicPumpStatus.lastBolusTime.time, resourceHelper) } binding.lastBolus.text = resourceHelper.gs(R.string.mdt_last_bolus, bolus, unit, ago) } else { diff --git a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java index 7564a9edc2..125e067164 100644 --- a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java +++ b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileUTest.java @@ -17,7 +17,7 @@ public class BasalProfileUTest { public void initMocking() { PowerMockito.mockStatic(DateUtil.class); - when(DateUtil.now()).thenReturn(1514766900000L + T.mins(1).msecs()); + when(dateUtil._now()).thenReturn(1514766900000L + T.mins(1).msecs()); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index 2286b61052..cecd69564d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -23,7 +23,6 @@ import org.joda.time.Duration; import org.json.JSONException; import org.json.JSONObject; -import java.util.Date; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -726,7 +725,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa JSONObject extended = new JSONObject(); try { status.put("status", podStateManager.isPodRunning() ? (podStateManager.isSuspended() ? "suspended" : "normal") : "no active Pod"); - status.put("timestamp", DateUtil.toISOString(new Date())); + status.put("timestamp", dateUtil.toISOString(dateUtil.now())); battery.put("percent", getBatteryLevel()); @@ -749,7 +748,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa extended.put("ExtendedBolusRemaining", getPlannedRemainingMinutes(eb)); } - status.put("timestamp", DateUtil.toISOString(new Date())); + status.put("timestamp", dateUtil.toISOString(dateUtil.now())); if (isUseRileyLinkBatteryLevel()) { pump.put("battery", battery); @@ -766,7 +765,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa pump.put("reservoir", reservoirLevel); } - pump.put("clock", DateUtil.toISOString(podStateManager.getTime().toDate())); + pump.put("clock", dateUtil.toISOString(podStateManager.getTime().getMillis())); } catch (JSONException e) { aapsLogger.error(LTag.PUMP, "Unhandled exception", e); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt index 356f3d0444..747b5fb86c 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt @@ -567,13 +567,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() { val timeAsJavaData = time.toLocalDateTime().toDate() val timeZone = podStateManager.timeZone.toTimeZone() if (timeZone == TimeZone.getDefault()) { - return dateUtil.dateAndTimeString(timeAsJavaData) + return dateUtil.dateAndTimeString(timeAsJavaData.time) } val isDaylightTime = timeZone.inDaylightTime(timeAsJavaData) val locale = resources.configuration.locales.get(0) val timeZoneDisplayName = timeZone.getDisplayName(isDaylightTime, TimeZone.SHORT, locale) + " " + timeZone.getDisplayName(isDaylightTime, TimeZone.LONG, locale) - return resourceHelper.gs(R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData), timeZoneDisplayName) + return resourceHelper.gs(R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData.time), timeZoneDisplayName) } private fun readableDuration(dateTime: DateTime): String {