Merge branch 'meallink' of https://github.com/nightscout/AndroidAPS into meallink

This commit is contained in:
Milos Kozak 2021-04-11 20:38:17 +02:00
commit 5a4733dbdc
204 changed files with 1209 additions and 1189 deletions

View file

@ -89,7 +89,7 @@ class RealPumpTest {
localProfilePlugin.numOfProfiles = 0 localProfilePlugin.numOfProfiles = 0
val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile") val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile")
localProfilePlugin.addProfile(singleProfile) 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) treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch)
// Insulin // Insulin
configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN) configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN)

View file

@ -32,6 +32,8 @@ import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.activities.ProfileHelperActivity import info.nightscout.androidaps.activities.ProfileHelperActivity
import info.nightscout.androidaps.activities.SingleFragmentActivity import info.nightscout.androidaps.activities.SingleFragmentActivity
import info.nightscout.androidaps.activities.StatsActivity import info.nightscout.androidaps.activities.StatsActivity
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.ActivityMainBinding import info.nightscout.androidaps.databinding.ActivityMainBinding
import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventAppExit
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
@ -41,6 +43,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
@ -87,6 +90,7 @@ class MainActivity : NoSplashAppCompatActivity() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin @Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin
@Inject lateinit var config: Config @Inject lateinit var config: Config
@Inject lateinit var uel: UserEntryLogger
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private var pluginPreferencesMenuItem: MenuItem? = null private var pluginPreferencesMenuItem: MenuItem? = null
@ -316,6 +320,7 @@ class MainActivity : NoSplashAppCompatActivity() {
R.id.nav_exit -> { R.id.nav_exit -> {
aapsLogger.debug(LTag.CORE, "Exiting") aapsLogger.debug(LTag.CORE, "Exiting")
uel.log(Action.EXIT_AAPS, Sources.Aaps)
rxBus.send(EventAppExit()) rxBus.send(EventAppExit())
finish() finish()
System.runFinalization() System.runFinalization()

View file

@ -11,6 +11,7 @@ import dagger.android.AndroidInjector
import dagger.android.DaggerApplication import dagger.android.DaggerApplication
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.VersionChangeTransaction import info.nightscout.androidaps.database.transactions.VersionChangeTransaction
import info.nightscout.androidaps.db.CompatDBHelper import info.nightscout.androidaps.db.CompatDBHelper
@ -20,6 +21,7 @@ import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils
@ -54,6 +56,7 @@ class MainApp : DaggerApplication() {
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var dateUtil: DateUtil @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize @Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize
@Inject lateinit var uel: UserEntryLogger
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
@ -68,7 +71,7 @@ class MainApp : DaggerApplication() {
commitHash = null commitHash = null
} }
disposable += repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe() 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() disposable += compatDBHelper.dbChangeDisposable()
registerActivityLifecycleCallbacks(activityMonitor) registerActivityLifecycleCallbacks(activityMonitor)
JodaTimeAndroid.init(this) JodaTimeAndroid.init(this)
@ -85,6 +88,7 @@ class MainApp : DaggerApplication() {
configBuilderPlugin.initialize() configBuilderPlugin.initialize()
keepAliveManager.setAlarm(this) keepAliveManager.setAlarm(this)
doMigrations() doMigrations()
uel.log(UserEntry.Action.START_AAPS, UserEntry.Sources.Aaps)
} }
private fun doMigrations() { private fun doMigrations() {

View file

@ -114,7 +114,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
} }
// Profile switch // 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 { binding.profileswitchList.setOnClickListener {
PopupMenu(this, binding.profileswitchList).apply { PopupMenu(this, binding.profileswitchList).apply {
@ -141,7 +141,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
profile?.let { profile?.let {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable { OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable {
localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " + localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " +
dateUtil.dateAndTimeAndSecondsString(dateUtil._now()) dateUtil.dateAndTimeAndSecondsString(dateUtil.now())
.replace(".", "/") .replace(".", "/")
)) ))
rxBus.send(EventLocalProfileChanged()) rxBus.send(EventLocalProfileChanged())
@ -210,7 +210,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 -> getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 ->
ProfileViewerDialog().also { pvd -> ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also { pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now()) it.putLong("time", dateUtil.now())
it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
it.putString("customProfile", profile0.data.toString()) it.putString("customProfile", profile0.data.toString())
it.putString("customProfile2", profile1.data.toString()) it.putString("customProfile2", profile1.data.toString())

View file

@ -30,6 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var activityMonitor: ActivityMonitor @Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var defaultProfile: DefaultProfile @Inject lateinit var defaultProfile: DefaultProfile
@Inject lateinit var dateUtil: DateUtil
private lateinit var binding: ActivitySurveyBinding private lateinit var binding: ActivitySurveyBinding
@ -68,7 +69,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile -> defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile ->
ProfileViewerDialog().also { pvd -> ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also { pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now()) it.putLong("time", dateUtil.now())
it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
it.putString("customProfile", runningProfile.data.toString()) it.putString("customProfile", runningProfile.data.toString())
it.putString("customProfile2", profile.data.toString()) it.putString("customProfile2", profile.data.toString())

View file

@ -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.general.openhumans.OpenHumansUploader;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.PercentageSplitter; import info.nightscout.androidaps.utils.PercentageSplitter;
/** /**
@ -69,6 +70,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Inject OpenHumansUploader openHumansUploader; @Inject OpenHumansUploader openHumansUploader;
@Inject ActivePluginProvider activePlugin; @Inject ActivePluginProvider activePlugin;
@Inject NSUpload nsUpload; @Inject NSUpload nsUpload;
@Inject DateUtil dateUtil;
public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses"; public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
@ -886,7 +888,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitch.profileJson = profile.getData().toString(); profileSwitch.profileJson = profile.getData().toString();
aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store"); aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store");
// Update data in NS // Update data in NS
nsUpload.updateProfileSwitch(profileSwitch); nsUpload.updateProfileSwitch(profileSwitch, dateUtil);
} else { } else {
aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return; return;

View file

@ -303,7 +303,7 @@ class CarbsDialog : DialogFragmentWithDate() {
}) })
} }
if (useAlarm && carbs > 0 && timeOffset > 0) { 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) }, null)
} }

View file

@ -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)) 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 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) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))

View file

@ -16,7 +16,6 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -83,7 +82,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
binding.profile.setSelection(p) binding.profile.setSelection(p)
} ?: return } ?: return
treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> treatmentsPlugin.getProfileSwitchFromHistory(dateUtil.now())?.let { ps ->
if (ps.isCPP) { if (ps.isCPP) {
binding.reuselayout.visibility = View.VISIBLE binding.reuselayout.visibility = View.VISIBLE
binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, ps.percentage, ps.timeshift) binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, ps.percentage, ps.timeshift)

View file

@ -88,7 +88,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
// temp target // temp target
context?.let { context -> 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 binding.targetCancel.visibility = View.VISIBLE
else else
binding.targetCancel.visibility = View.GONE binding.targetCancel.visibility = View.GONE

View file

@ -167,18 +167,18 @@ class TreatmentDialog : DialogFragmentWithDate() {
{ aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) } { aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) }
) )
} else { } else {
if (detailedBolusInfo.insulin > 0) if (detailedBolusInfo.insulin > 0) {
uel.log(action, Sources.TreatmentDialog,
ValueWithUnit.Insulin(insulinAfterConstraints),
ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbsAfterConstraints != 0 })
commandQueue.bolus(detailedBolusInfo, object : Callback() { commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror) ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
} else }
uel.log(action, Sources.TreatmentDialog,
ValueWithUnit.Insulin(insulinAfterConstraints),
ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbsAfterConstraints != 0 })
} }
}) })
else } else
uel.log(action, Sources.TreatmentDialog, uel.log(action, Sources.TreatmentDialog,
ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbs != 0 }) ValueWithUnit.Gram(carbsAfterConstraints).takeIf { carbs != 0 })
} }

View file

@ -210,7 +210,7 @@ class WizardDialog : DaggerDialogFragment() {
private fun onCheckedChanged(buttonView: CompoundButton, @Suppress("UNUSED_PARAMETER") state: Boolean) { private fun onCheckedChanged(buttonView: CompoundButton, @Suppress("UNUSED_PARAMETER") state: Boolean) {
saveCheckedStates() 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) if (buttonView.id == binding.cobcheckbox.id)
processCobCheckBox() processCobCheckBox()
calculateInsulin() calculateInsulin()
@ -268,7 +268,7 @@ class WizardDialog : DaggerDialogFragment() {
// Set BG if not old // Set BG if not old
binding.bgInput.value = iobCobCalculator.actualBg()?.valueToUnits(units) ?: 0.0 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 // IOB calculation
val bolusIob = iobCobCalculator.calculateIobFromBolus().round() val bolusIob = iobCobCalculator.calculateIobFromBolus().round()
@ -308,7 +308,7 @@ class WizardDialog : DaggerDialogFragment() {
} }
bg = if (binding.bgcheckbox.isChecked) bg else 0.0 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 val tempTarget = if (binding.ttcheckbox.isChecked && dbRecord is ValueWrapper.Existing) dbRecord.value else null
// COB // COB

View file

@ -98,7 +98,6 @@ class LoopFragment : DaggerFragment() {
binding.constraintsprocessed.text = it.constraintsProcessed?.toSpanned() ?: "" binding.constraintsprocessed.text = it.constraintsProcessed?.toSpanned() ?: ""
binding.source.text = it.source ?: "" binding.source.text = it.source ?: ""
binding.lastrun.text = dateUtil.dateAndTimeString(it.lastAPSRun) binding.lastrun.text = dateUtil.dateAndTimeString(it.lastAPSRun)
?: ""
binding.smbrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest) binding.smbrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest)
binding.smbexecutionTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact) binding.smbexecutionTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact)
binding.tbrrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) binding.tbrrequestTime.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest)

View file

@ -313,7 +313,7 @@ open class LoopPlugin @Inject constructor(
lastRun = (lastRun ?: LastRun()).also { lastRun -> lastRun = (lastRun ?: LastRun()).also { lastRun ->
lastRun.request = apsResult lastRun.request = apsResult
lastRun.constraintsProcessed = resultAfterConstraints lastRun.constraintsProcessed = resultAfterConstraints
lastRun.lastAPSRun = DateUtil.now() lastRun.lastAPSRun = dateUtil.now()
lastRun.source = (usedAPS as PluginBase).name lastRun.source = (usedAPS as PluginBase).name
lastRun.tbrSetByPump = null lastRun.tbrSetByPump = null
lastRun.smbSetByPump = null lastRun.smbSetByPump = null
@ -378,6 +378,8 @@ open class LoopPlugin @Inject constructor(
// mId allows you to update the notification later on. // mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build()) mNotificationManager.notify(Constants.notificationID, builder.build())
uel.log(Action.CAREPORTAL, Sources.Loop,
ValueWithUnit.StringResource(info.nightscout.androidaps.core.R.string.carbsreq, listOf(ValueWithUnit.Gram(resultAfterConstraints.carbsReq), ValueWithUnit.Minute(resultAfterConstraints.carbsReqWithin))))
rxBus.send(EventNewOpenLoopNotification()) rxBus.send(EventNewOpenLoopNotification())
//only send to wear if Native notifications are turned off //only send to wear if Native notifications are turned off
@ -408,7 +410,7 @@ open class LoopPlugin @Inject constructor(
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.tbrSetByPump = result lastRun.tbrSetByPump = result
lastRun.lastTBRRequest = lastRun.lastAPSRun lastRun.lastTBRRequest = lastRun.lastAPSRun
lastRun.lastTBREnact = DateUtil.now() lastRun.lastTBREnact = dateUtil.now()
rxBus.send(EventLoopUpdateGui()) rxBus.send(EventLoopUpdateGui())
applySMBRequest(resultAfterConstraints, object : Callback() { applySMBRequest(resultAfterConstraints, object : Callback() {
override fun run() { override fun run() {
@ -416,7 +418,7 @@ open class LoopPlugin @Inject constructor(
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.smbSetByPump = result lastRun.smbSetByPump = result
lastRun.lastSMBRequest = lastRun.lastAPSRun lastRun.lastSMBRequest = lastRun.lastAPSRun
lastRun.lastSMBEnact = DateUtil.now() lastRun.lastSMBEnact = dateUtil.now()
} else { } else {
Thread { Thread {
SystemClock.sleep(1000) SystemClock.sleep(1000)
@ -507,8 +509,8 @@ open class LoopPlugin @Inject constructor(
if (result.enacted) { if (result.enacted) {
lastRun.tbrSetByPump = result lastRun.tbrSetByPump = result
lastRun.lastTBRRequest = lastRun.lastAPSRun lastRun.lastTBRRequest = lastRun.lastAPSRun
lastRun.lastTBREnact = DateUtil.now() lastRun.lastTBREnact = dateUtil.now()
lastRun.lastOpenModeAccept = DateUtil.now() lastRun.lastOpenModeAccept = dateUtil.now()
buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction, buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction,
activePlugin.activePump, receiverStatusStore, runningConfiguration, activePlugin.activePump, receiverStatusStore, runningConfiguration,
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {
@ -658,7 +660,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() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {
@ -684,7 +686,7 @@ open class LoopPlugin @Inject constructor(
override fun createOfflineEvent(durationInMinutes: Int) { override fun createOfflineEvent(durationInMinutes: Int) {
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction( disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
type = TherapyEvent.Type.APS_OFFLINE, type = TherapyEvent.Type.APS_OFFLINE,
duration = T.mins(durationInMinutes.toLong()).msecs(), duration = T.mins(durationInMinutes.toLong()).msecs(),
enteredBy = "openaps://" + "AndroidAPS", enteredBy = "openaps://" + "AndroidAPS",

View file

@ -194,7 +194,7 @@ class DetermineBasalAdapterAMAJS internal constructor(scriptReader: ScriptReader
// as we have non default temps longer than 30 minutes // as we have non default temps longer than 30 minutes
if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now)) if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) iobData = iobCobCalculator.convertToJSONArray(iobArray)
this.glucoseStatus = JSONObject() this.glucoseStatus = JSONObject()
this.glucoseStatus.put("glucose", glucoseStatus.glucose) this.glucoseStatus.put("glucose", glucoseStatus.glucose)
if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { if (sp.getBoolean(R.string.key_always_use_shortavg, false)) {

View file

@ -13,7 +13,7 @@ class DetermineBasalResultAMA private constructor(injector: HasAndroidInjector)
private var snoozeBG = 0.0 private var snoozeBG = 0.0
internal constructor(injector: HasAndroidInjector, result: NativeObject, j: JSONObject) : this(injector) { internal constructor(injector: HasAndroidInjector, result: NativeObject, j: JSONObject) : this(injector) {
date = dateUtil._now() date = dateUtil.now()
json = j json = j
if (result.containsKey("error")) { if (result.containsKey("error")) {
reason = result["error"].toString() reason = result["error"].toString()

View file

@ -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 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 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 var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
isTempTarget = true 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()) 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 lastAPSResult = null
lastAPSRun = 0 lastAPSRun = 0
} else { } 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] determineBasalResultAMA.iob = iobArray[0]
val now = System.currentTimeMillis() val now = System.currentTimeMillis()
determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now)) determineBasalResultAMA.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultAMA.inputConstraints = inputConstraints determineBasalResultAMA.inputConstraints = inputConstraints
lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS
lastAPSResult = determineBasalResultAMA lastAPSResult = determineBasalResultAMA

View file

@ -237,7 +237,7 @@ class DetermineBasalAdapterSMBJS internal constructor(private val scriptReader:
// as we have non default temps longer than 30 mintues // as we have non default temps longer than 30 mintues
if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now)) if (tb != null) currentTemp.put("minutesrunning", tb.getPassedDurationToTimeInMinutes(now))
iobData = IobCobCalculatorPlugin.convertToJSONArray(iobArray) iobData = iobCobCalculator.convertToJSONArray(iobArray)
mGlucoseStatus.put("glucose", glucoseStatus.glucose) mGlucoseStatus.put("glucose", glucoseStatus.glucose)
mGlucoseStatus.put("noise", glucoseStatus.noise) mGlucoseStatus.put("noise", glucoseStatus.noise)
if (sp.getBoolean(R.string.key_always_use_shortavg, false)) { if (sp.getBoolean(R.string.key_always_use_shortavg, false)) {

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.loop.APSResult import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
@ -13,7 +12,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector)
private var snoozeBG = 0.0 private var snoozeBG = 0.0
internal constructor(injector: HasAndroidInjector, result: JSONObject) : this(injector) { internal constructor(injector: HasAndroidInjector, result: JSONObject) : this(injector) {
date = dateUtil._now() date = dateUtil.now()
json = result json = result
try { try {
if (result.has("error")) { if (result.has("error")) {
@ -47,7 +46,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector)
if (result.has("deliverAt")) { if (result.has("deliverAt")) {
val date = result.getString("deliverAt") val date = result.getString("deliverAt")
try { try {
deliverAt = DateUtil.fromISODateString(date).time deliverAt = dateUtil.fromISODateString(date)
} catch (e: Exception) { } catch (e: Exception) {
aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: $date", e) aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: $date", e)
} }

View file

@ -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 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 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 var isTempTarget = false
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
isTempTarget = true 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()) 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 { } else {
// TODO still needed with oref1? // TODO still needed with oref1?
// Fix bug determine basal // 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.iob = iobArray[0]
determineBasalResultSMB.json?.put("timestamp", DateUtil.toISOString(now)) determineBasalResultSMB.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultSMB.inputConstraints = inputConstraints determineBasalResultSMB.inputConstraints = inputConstraints
lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS
lastAPSResult = determineBasalResultSMB lastAPSResult = determineBasalResultSMB

View file

@ -5,6 +5,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.events.EventAppInitialized import info.nightscout.androidaps.events.EventAppInitialized
import info.nightscout.androidaps.events.EventConfigBuilderChange import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.events.EventRebuildTabs
@ -147,7 +148,8 @@ class ConfigBuilderPlugin @Inject constructor(
performPluginSwitch(changedPlugin, newState, type) performPluginSwitch(changedPlugin, newState, type)
pumpSync.connectNewPump() pumpSync.connectNewPump()
sp.putBoolean("allow_hardware_pump", true) sp.putBoolean("allow_hardware_pump", true)
uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder) uel.log(Action.HW_PUMP_ALLOWED, Sources.ConfigBuilder,
ValueWithUnit.StringResource(changedPlugin.pluginDescription.pluginName))
aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!") aapsLogger.debug(LTag.PUMP, "First time HW pump allowed!")
}, { }, {
rxBus.send(EventConfigBuilderUpdateGui()) rxBus.send(EventConfigBuilderUpdateGui())
@ -157,6 +159,14 @@ class ConfigBuilderPlugin @Inject constructor(
} }
override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) { override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
if(enabled && !changedPlugin.isEnabled()) {
uel.log(Action.PLUGIN_ENABLED, Sources.ConfigBuilder,
ValueWithUnit.StringResource(changedPlugin.pluginDescription.pluginName))
}
else if(!enabled) {
uel.log(Action.PLUGIN_DISABLED, Sources.ConfigBuilder,
ValueWithUnit.StringResource(changedPlugin.pluginDescription.pluginName))
}
changedPlugin.setPluginEnabled(type, enabled) changedPlugin.setPluginEnabled(type, enabled)
changedPlugin.setFragmentVisible(type, enabled) changedPlugin.setFragmentVisible(type, enabled)
processOnEnabledCategoryChanged(changedPlugin, type) processOnEnabledCategoryChanged(changedPlugin, type)

View file

@ -237,7 +237,7 @@ class ObjectivesFragment : DaggerFragment() {
holder.binding.verify.setOnClickListener { holder.binding.verify.setOnClickListener {
receiverStatusStore.updateNetworkStatus() receiverStatusStore.updateNetworkStatus()
if (binding.fake.isChecked) { if (binding.fake.isChecked) {
objective.accomplishedOn = DateUtil.now() objective.accomplishedOn = dateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()
startUpdateTimer() startUpdateTimer()
rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventObjectivesUpdateGui())
@ -249,7 +249,7 @@ class ObjectivesFragment : DaggerFragment() {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
sntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)
if (!networkConnected) { if (!networkConnected) {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99))
@ -276,7 +276,7 @@ class ObjectivesFragment : DaggerFragment() {
holder.binding.start.setOnClickListener { holder.binding.start.setOnClickListener {
receiverStatusStore.updateNetworkStatus() receiverStatusStore.updateNetworkStatus()
if (binding.fake.isChecked) { if (binding.fake.isChecked) {
objective.startedOn = DateUtil.now() objective.startedOn = dateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()
startUpdateTimer() startUpdateTimer()
rxBus.send(EventObjectivesUpdateGui()) rxBus.send(EventObjectivesUpdateGui())
@ -288,7 +288,7 @@ class ObjectivesFragment : DaggerFragment() {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
sntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${dateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)
if (!networkConnected) { if (!networkConnected) {
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99))

View file

@ -29,6 +29,7 @@ class ObjectivesPlugin @Inject constructor(
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val sp: SP, private val sp: SP,
config: Config, config: Config,
private val dateUtil: DateUtil,
private val uel: UserEntryLogger private val uel: UserEntryLogger
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
@ -126,22 +127,22 @@ class ObjectivesPlugin @Inject constructor(
if (!url.endsWith("/")) url = "$url/" if (!url.endsWith("/")) url = "$url/"
@Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString() @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)) { if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) {
sp.putLong("Objectives_" + "openloop" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "openloop" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "openloop" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "openloop" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "maxbasal" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "maxbasal" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "maxbasal" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "maxbasal" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "maxiobzero" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "maxiobzero" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "maxiobzero" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "maxiobzero" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "maxiob" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "maxiob" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "maxiob" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "maxiob" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "autosens" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "autosens" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "autosens" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "autosens" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "ama" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "ama" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "ama" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "ama" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "smb" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "smb" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "smb" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "smb" + "_accomplished", dateUtil.now())
sp.putLong("Objectives_" + "auto" + "_started", DateUtil.now()) sp.putLong("Objectives_" + "auto" + "_started", dateUtil.now())
sp.putLong("Objectives_" + "auto" + "_accomplished", DateUtil.now()) sp.putLong("Objectives_" + "auto" + "_accomplished", dateUtil.now())
setupObjectives() setupObjectives()
OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeaccepted)) OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeaccepted))
uel.log(Action.OBJECTIVES_SKIPPED, Sources.Objectives) uel.log(Action.OBJECTIVES_SKIPPED, Sources.Objectives)

View file

@ -108,7 +108,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() {
} }
task.answered = result task.answered = result
if (!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) ToastUtils.showToastInUiThread(context, R.string.wronganswer)
} else task.disabledTo = 0 } else task.disabledTo = 0
updateGui() updateGui()

View file

@ -21,6 +21,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
private val spName: String private val spName: String
@StringRes val objective: Int @StringRes val objective: Int
@ -55,7 +56,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
this.gate = gate this.gate = gate
startedOn = sp.getLong("Objectives_" + spName + "_started", 0L) startedOn = sp.getLong("Objectives_" + spName + "_started", 0L)
accomplishedOn = sp.getLong("Objectives_" + spName + "_accomplished", 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 startedOn = 0
accomplishedOn = 0 accomplishedOn = 0
} }
@ -69,7 +70,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
} }
val isAccomplished: Boolean val isAccomplished: Boolean
get() = accomplishedOn != 0L && accomplishedOn < DateUtil.now() get() = accomplishedOn != 0L && accomplishedOn < dateUtil.now()
val isStarted: Boolean val isStarted: Boolean
get() = startedOn != 0L get() = startedOn != 0L
@ -144,7 +145,7 @@ abstract class Objective(injector: HasAndroidInjector, spName: String, @StringRe
override fun isCompleted(): Boolean = answered override fun isCompleted(): Boolean = answered
fun isEnabledAnswer(): Boolean = disabledTo < DateUtil.now() fun isEnabledAnswer(): Boolean = disabledTo < dateUtil.now()
fun option(option: Option): ExamTask { fun option(option: Option): ExamTask {
options.add(option) options.add(option)

View file

@ -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.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import javax.inject.Inject import javax.inject.Inject
class Objective0(injector: HasAndroidInjector) : Objective(injector, "config", R.string.objectives_0_objective, R.string.objectives_0_gate) { 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) { tasks.add(object : Task(this, R.string.activate_profile) {
override fun isCompleted(): Boolean { override fun isCompleted(): Boolean {
return treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()) != null return treatmentsPlugin.getProfileSwitchFromHistory(dateUtil.now()) != null
} }
}) })
} }

View file

@ -70,7 +70,7 @@ class SafetyPlugin @Inject constructor(
value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_on_dev_branch)] = this
} }
val pump = activePlugin.activePump 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 value[aapsLogger, false, resourceHelper.gs(R.string.closed_loop_disabled_with_eb)] = this
} }
return value return value

View file

@ -164,7 +164,7 @@ class ActionsFragment : DaggerFragment() {
} }
} }
extendedBolusCancel?.setOnClickListener { extendedBolusCancel?.setOnClickListener {
if (iobCobCalculator.getExtendedBolus(dateUtil._now()) != null) { if (iobCobCalculator.getExtendedBolus(dateUtil.now()) != null) {
uel.log(Action.CANCEL_EXTENDED_BOLUS, Sources.Actions) uel.log(Action.CANCEL_EXTENDED_BOLUS, Sources.Actions)
commandQueue.cancelExtended(object : Callback() { commandQueue.cancelExtended(object : Callback() {
override fun run() { override fun run() {
@ -179,7 +179,7 @@ class ActionsFragment : DaggerFragment() {
TempBasalDialog().show(childFragmentManager, "Actions") TempBasalDialog().show(childFragmentManager, "Actions")
} }
cancelTempBasal?.setOnClickListener { cancelTempBasal?.setOnClickListener {
if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) != null) { if (iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil.now()) != null) {
uel.log(Action.CANCEL_TEMP_BASAL, Sources.Actions) uel.log(Action.CANCEL_TEMP_BASAL, Sources.Actions)
commandQueue.cancelTempBasal(true, object : Callback() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
@ -274,7 +274,7 @@ class ActionsFragment : DaggerFragment() {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.GONE extendedBolusCancel?.visibility = View.GONE
} else { } else {
val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet() val activeExtendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet()
if (activeExtendedBolus is ValueWrapper.Existing) { if (activeExtendedBolus is ValueWrapper.Existing) {
extendedBolus?.visibility = View.GONE extendedBolus?.visibility = View.GONE
extendedBolusCancel?.visibility = View.VISIBLE extendedBolusCancel?.visibility = View.VISIBLE

View file

@ -41,7 +41,6 @@ import io.reactivex.Single
import java.io.File import java.io.File
import java.io.FileNotFoundException import java.io.FileNotFoundException
import java.io.IOException import java.io.IOException
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.system.exitProcess import kotlin.system.exitProcess
@ -63,7 +62,8 @@ class ImportExportPrefs @Inject constructor(
private val classicPrefsFormat: ClassicPrefsFormat, private val classicPrefsFormat: ClassicPrefsFormat,
private val encryptedPrefsFormat: EncryptedPrefsFormat, private val encryptedPrefsFormat: EncryptedPrefsFormat,
private val prefFileList: PrefFileListProvider, private val prefFileList: PrefFileListProvider,
private val uel: UserEntryLogger private val uel: UserEntryLogger,
private val dateUtil: DateUtil
) : ImportExportPrefsInterface { ) : ImportExportPrefsInterface {
override fun prefsFileExists(): Boolean { override fun prefsFileExists(): Boolean {
@ -95,7 +95,7 @@ class ImportExportPrefs @Inject constructor(
val metadata: MutableMap<PrefsMetadataKey, PrefMetadata> = mutableMapOf() val metadata: MutableMap<PrefsMetadataKey, PrefMetadata> = mutableMapOf()
metadata[PrefsMetadataKey.DEVICE_NAME] = PrefMetadata(detectUserName(context), PrefsStatus.OK) 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_VERSION] = PrefMetadata(BuildConfig.VERSION_NAME, PrefsStatus.OK)
metadata[PrefsMetadataKey.AAPS_FLAVOUR] = PrefMetadata(BuildConfig.FLAVOR, PrefsStatus.OK) metadata[PrefsMetadataKey.AAPS_FLAVOUR] = PrefMetadata(BuildConfig.FLAVOR, PrefsStatus.OK)
metadata[PrefsMetadataKey.DEVICE_MODEL] = PrefMetadata(config.currentDeviceModelString, PrefsStatus.OK) metadata[PrefsMetadataKey.DEVICE_MODEL] = PrefMetadata(config.currentDeviceModelString, PrefsStatus.OK)

View file

@ -10,12 +10,14 @@ import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.extensions.toJson import info.nightscout.androidaps.extensions.toJson
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
class DataSyncSelectorImplementation @Inject constructor( class DataSyncSelectorImplementation @Inject constructor(
private val sp: SP, private val sp: SP,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val dateUtil: DateUtil,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val nsClientPlugin: NSClientPlugin, private val nsClientPlugin: NSClientPlugin,
private val activePlugin: ActivePluginProvider, 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)) nsClientPlugin.nsClientService?.dbRemove("treatments", bolus.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolus(bolus.first, bolus.second))
// existing without nsId = create new // existing without nsId = create new
bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
bolus.first.isValid && bolus.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -102,10 +104,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("treatments", carb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairCarbs(carb.first, carb.second)) nsClientPlugin.nsClientService?.dbRemove("treatments", carb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairCarbs(carb.first, carb.second))
// existing without nsId = create new // existing without nsId = create new
carb.first.isValid && carb.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
carb.first.isValid && carb.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -139,10 +141,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second)) nsClientPlugin.nsClientService?.dbRemove("treatments", bolusCalculatorResult.first.interfaceIDs.nightscoutId, DataSyncSelector.PairBolusCalculatorResult(bolusCalculatorResult.first, bolusCalculatorResult.second))
// existing without nsId = create new // existing without nsId = create new
bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
bolusCalculatorResult.first.isValid && bolusCalculatorResult.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -176,10 +178,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("treatments", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryTarget(tt.first, tt.second)) nsClientPlugin.nsClientService?.dbRemove("treatments", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryTarget(tt.first, tt.second))
// existing without nsId = create new // existing without nsId = create new
tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -251,10 +253,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("entries", gv.first.interfaceIDs.nightscoutId, DataSyncSelector.PairGlucoseValue(gv.first, gv.second)) nsClientPlugin.nsClientService?.dbRemove("entries", gv.first.interfaceIDs.nightscoutId, DataSyncSelector.PairGlucoseValue(gv.first, gv.second))
// existing without nsId = create new // existing without nsId = create new
gv.first.isValid && gv.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
gv.first.isValid && gv.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -320,7 +322,7 @@ class DataSyncSelectorImplementation @Inject constructor(
when { when {
// without nsId = create new // without nsId = create new
deviceStatus.interfaceIDs.nightscoutId == null -> deviceStatus.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(), deviceStatus) nsClientPlugin.nsClientService?.dbAdd("devicestatus", deviceStatus.toJson(dateUtil), deviceStatus)
// with nsId = ignore // with nsId = ignore
deviceStatus.interfaceIDs.nightscoutId != null -> Any() 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)) nsClientPlugin.nsClientService?.dbRemove("treatments", tb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairTemporaryBasal(tb.first, tb.second))
// existing without nsId = create new // existing without nsId = create new
tb.first.isValid && tb.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
tb.first.isValid && tb.first.interfaceIDs.nightscoutId != null -> 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 return true
} }
@ -396,10 +398,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second)) nsClientPlugin.nsClientService?.dbRemove("treatments", eb.first.interfaceIDs.nightscoutId, DataSyncSelector.PairExtendedBolus(eb.first, eb.second))
// existing without nsId = create new // existing without nsId = create new
eb.first.isValid && eb.first.interfaceIDs.nightscoutId == null -> 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 // existing with nsId = update
eb.first.isValid && eb.first.interfaceIDs.nightscoutId != null -> 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 return true
} }

View file

@ -71,7 +71,7 @@ class NSClientAddUpdateWorker(
//Find latest date in treatment //Find latest date in treatment
val mills = safeGetLong(json, "mills") val mills = safeGetLong(json, "mills")
if (mills != 0L && mills < dateutil._now()) if (mills != 0L && mills < dateutil.now())
if (mills > latestDateInReceivedData) latestDateInReceivedData = mills if (mills > latestDateInReceivedData) latestDateInReceivedData = mills
if (insulin > 0) { if (insulin > 0) {

View file

@ -164,12 +164,12 @@ class NSDeviceStatus @Inject constructor(
// test warning level // test warning level
val level = when { val level = when {
pumpData.clock + nsSettingsStatus.extendedPumpSettings("urgentClock") * 60 * 1000L < dateUtil._now() -> Levels.URGENT pumpData.clock + nsSettingsStatus.extendedPumpSettings("urgentClock") * 60 * 1000L < dateUtil.now() -> Levels.URGENT
pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("urgentRes") -> Levels.URGENT pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("urgentRes") -> Levels.URGENT
pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("urgentBattP") -> Levels.URGENT pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("urgentBattP") -> Levels.URGENT
!pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("urgentBattV") -> Levels.URGENT !pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("urgentBattV") -> Levels.URGENT
pumpData.clock + nsSettingsStatus.extendedPumpSettings("warnClock") * 60 * 1000L < dateUtil._now() -> Levels.WARN pumpData.clock + nsSettingsStatus.extendedPumpSettings("warnClock") * 60 * 1000L < dateUtil.now() -> Levels.WARN
pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("warnRes") -> Levels.WARN pumpData.reservoir < nsSettingsStatus.extendedPumpSettings("warnRes") -> Levels.WARN
pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("warnBattP") -> Levels.WARN pumpData.isPercent && pumpData.percent < nsSettingsStatus.extendedPumpSettings("warnBattP") -> Levels.WARN
!pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("warnBattV") -> Levels.WARN !pumpData.isPercent && pumpData.voltage < nsSettingsStatus.extendedPumpSettings("warnBattV") -> Levels.WARN
else -> Levels.INFO 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("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(pumpData.percent).append("% ")
if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).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("status")) string.append(pumpData.status).append(" ")
if (fields.contains("device")) string.append(device).append(" ") if (fields.contains("device")) string.append(device).append(" ")
string.append("</span>") // color string.append("</span>") // color
@ -201,7 +201,7 @@ class NSDeviceStatus @Inject constructor(
try { try {
val data = this.data ?: return val data = this.data ?: return
val pump = if (data.has("pump")) data.getJSONObject("pump") else JSONObject() 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 // check if this is new data
if (clock == 0L || deviceStatusPumpData != null && clock < deviceStatusPumpData!!.clock) return 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 openAps = if (jsonObject.has("openaps")) jsonObject.getJSONObject("openaps") else JSONObject()
val suggested = if (openAps.has("suggested")) openAps.getJSONObject("suggested") else JSONObject() val suggested = if (openAps.has("suggested")) openAps.getJSONObject("suggested") else JSONObject()
val enacted = if (openAps.has("enacted")) openAps.getJSONObject("enacted") 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 // check if this is new data
if (clock != 0L && clock > deviceStatusOpenAPSData.clockSuggested) { if (clock != 0L && clock > deviceStatusOpenAPSData.clockSuggested) {
deviceStatusOpenAPSData.suggested = suggested deviceStatusOpenAPSData.suggested = suggested
deviceStatusOpenAPSData.clockSuggested = clock 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 // check if this is new data
if (clock != 0L && clock > deviceStatusOpenAPSData.clockEnacted) { if (clock != 0L && clock > deviceStatusOpenAPSData.clockEnacted) {
deviceStatusOpenAPSData.enacted = enacted deviceStatusOpenAPSData.enacted = enacted
@ -273,12 +273,12 @@ class NSDeviceStatus @Inject constructor(
// test warning level // test warning level
val level = when { 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_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 deviceStatusOpenAPSData.clockSuggested + T.mins(sp.getLong(R.string.key_nsalarm_staledatavalue, 16)).msecs() < dateUtil.now() -> Levels.WARN
else -> Levels.INFO else -> Levels.INFO
} }
string.append("<span style=\"color:${level.toColor()}\">") string.append("<span style=\"color:${level.toColor()}\">")
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("</span>") // color string.append("</span>") // color
return fromHtml(string.toString()) return fromHtml(string.toString())
} }
@ -287,8 +287,8 @@ class NSDeviceStatus @Inject constructor(
get() { get() {
val string = StringBuilder() val string = StringBuilder()
try { try {
if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested) string.append("<b>").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append("</b> ").append(deviceStatusOpenAPSData.enacted!!.getString("reason")).append("<br>") if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append("</b> ").append(deviceStatusOpenAPSData.enacted!!.getString("reason")).append("<br>")
if (deviceStatusOpenAPSData.suggested != null) string.append("<b>").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append("</b> ").append(deviceStatusOpenAPSData.suggested!!.getString("reason")).append("<br>") if (deviceStatusOpenAPSData.suggested != null) string.append("<b>").append(dateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append("</b> ").append(deviceStatusOpenAPSData.suggested!!.getString("reason")).append("<br>")
return fromHtml(string.toString()) return fromHtml(string.toString())
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
@ -307,7 +307,7 @@ class NSDeviceStatus @Inject constructor(
val clock = val clock =
when { when {
jsonObject.has("mills") -> jsonObject.getLong("mills") 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 else -> 0L
} }
val device = device val device = device

View file

@ -228,7 +228,7 @@ public class NSClientService extends DaggerService {
} }
public void processAddAck(NSAddAck ack) { public void processAddAck(NSAddAck ack) {
lastAckTime = dateUtil._now(); lastAckTime = dateUtil.now();
// new room way // new room way
if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) { if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) {
DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject(); DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject();
@ -400,7 +400,7 @@ public class NSClientService extends DaggerService {
} }
public void processUpdateAck(NSUpdateAck ack) { public void processUpdateAck(NSUpdateAck ack) {
lastAckTime = dateUtil._now(); lastAckTime = dateUtil.now();
// new room way // new room way
if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) { if (ack.getOriginalObject() instanceof DataSyncSelector.PairTemporaryTarget) {
DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject(); DataSyncSelector.PairTemporaryTarget pair = (DataSyncSelector.PairTemporaryTarget) ack.getOriginalObject();
@ -591,7 +591,7 @@ public class NSClientService extends DaggerService {
void watchdog() { void watchdog() {
synchronized (reconnections) { synchronized (reconnections) {
long now = DateUtil.now(); long now = dateUtil.now();
reconnections.add(now); reconnections.add(now);
for (int i = 0; i < reconnections.size(); i++) { for (int i = 0; i < reconnections.size(); i++) {
Long r = reconnections.get(i); Long r = reconnections.get(i);
@ -833,7 +833,7 @@ public class NSClientService extends DaggerService {
if (action == null) addedOrUpdatedTreatments.put(jsonTreatment); if (action == null) addedOrUpdatedTreatments.put(jsonTreatment);
else if (action.equals("update")) else if (action.equals("update"))
addedOrUpdatedTreatments.put(jsonTreatment); 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); removedTreatments.put(jsonTreatment);
} }
if (removedTreatments.length() > 0) { if (removedTreatments.length() > 0) {

View file

@ -309,7 +309,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
R.id.active_profile -> { R.id.active_profile -> {
ProfileViewerDialog().also { pvd -> ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also { pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now()) it.putLong("time", dateUtil.now())
it.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) it.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal)
} }
}.show(childFragmentManager, "ProfileViewDialog") }.show(childFragmentManager, "ProfileViewDialog")
@ -549,7 +549,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (_binding == null) return if (_binding == null) return
aapsLogger.debug("UpdateGUI from $from") aapsLogger.debug("UpdateGUI from $from")
binding.infoLayout.time.text = dateUtil.timeString(Date()) binding.infoLayout.time.text = dateUtil.timeString(dateUtil.now())
if (!profileFunction.isProfileValid("Overview")) { if (!profileFunction.isProfileValid("Overview")) {
binding.loopPumpStatusLayout.pumpStatus.setText(R.string.noprofileset) 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() } else flag and Paint.STRIKE_THRU_TEXT_FLAG.inv()
overview_bg.paintFlags = flag overview_bg.paintFlags = flag
} }
binding.infoLayout.timeAgo.text = DateUtil.minAgo(resourceHelper, lastBG.timestamp) binding.infoLayout.timeAgo.text = dateUtil.minAgo(resourceHelper, lastBG.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + DateUtil.minAgoShort(lastBG.timestamp) + ")" binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(lastBG.timestamp) + ")"
} }
val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() val closedLoopEnabled = constraintChecker.isClosedLoopAllowed()
@ -625,19 +625,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
when { when {
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus) 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 binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isDisconnected -> { loopPlugin.isDisconnected -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected) 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 binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
loopPlugin.isEnabled() && loopPlugin.isSuspended -> { loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused) 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 binding.infoLayout.apsModeText.visibility = View.VISIBLE
} }
@ -680,11 +680,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} }
// temp target // temp target
val tempTarget: ValueWrapper<TemporaryTarget> = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() val tempTarget: ValueWrapper<TemporaryTarget> = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
binding.loopPumpStatusLayout.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) binding.loopPumpStatusLayout.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning))
binding.loopPumpStatusLayout.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) 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 { } else {
// If the target is not the same as set in the profile then oref has overridden it // If the target is not the same as set in the profile then oref has overridden it
val targetUsed = lastRun?.constraintsProcessed?.targetBG ?: 0.0 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) if (percentRate < 100) binding.infoLayout.baseBasalIcon.setImageResource(R.drawable.ic_cp_basal_tbr_low)
// Extended bolus // Extended bolus
val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil._now()).blockingGet() val extendedBolus = repository.getExtendedBolusActiveAt(dateUtil.now()).blockingGet()
binding.infoLayout.extendedBolus.text = binding.infoLayout.extendedBolus.text =
if (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses) if (extendedBolus is ValueWrapper.Existing && !pump.isFakingTempsByExtendedBoluses)
resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.value.rate) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.value.rate)

View file

@ -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.DecimalFormatter
import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.WarnColors
import info.nightscout.androidaps.extensions.age import info.nightscout.androidaps.extensions.age
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
@ -24,6 +25,7 @@ import javax.inject.Singleton
class StatusLightHandler @Inject constructor( class StatusLightHandler @Inject constructor(
private val resourceHelper: ResourceHelper, private val resourceHelper: ResourceHelper,
private val sp: SP, private val sp: SP,
private val dateUtil: DateUtil,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val warnColors: WarnColors, private val warnColors: WarnColors,
private val config: Config, private val config: Config,
@ -75,7 +77,7 @@ class StatusLightHandler @Inject constructor(
val therapyEvent = repository.getLastTherapyRecord(type).blockingGet() val therapyEvent = repository.getLastTherapyRecord(type).blockingGet()
if (therapyEvent is ValueWrapper.Existing) { if (therapyEvent is ValueWrapper.Existing) {
warnColors.setColorByAge(view, therapyEvent.value, warn, urgent) 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 { } else {
view?.text = if (resourceHelper.shortTextMode()) "-" else resourceHelper.gs(R.string.notavailable) view?.text = if (resourceHelper.shortTextMode()) "-" else resourceHelper.gs(R.string.notavailable)
} }

View file

@ -83,7 +83,7 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener {
// create an OnTimeSetListener // create an OnTimeSetListener
val fromTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> val fromTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
fromSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt() 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 { binding.from.setOnClickListener {
@ -96,11 +96,11 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener {
} }
} }
fromSeconds = entry.validFrom() 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 -> val toTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
toSeconds = (T.hours(hour.toLong()).secs() + T.mins(minute.toLong()).secs()).toInt() 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 { binding.to.setOnClickListener {
@ -113,7 +113,7 @@ class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener {
} }
} }
toSeconds = entry.validFrom() 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.buttonEdit.setText(entry.buttonText())
binding.carbsEdit.setText(entry.carbs().toString()) binding.carbsEdit.setText(entry.carbs().toString())

View file

@ -415,7 +415,7 @@ class GraphData(
if (showPrediction) { if (showPrediction) {
val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("GraphData") val autosensData = iobCobCalculator.getLastAutosensDataSynchronized("GraphData")
val lastAutosensResult = autosensData?.autosensResult ?: AutosensResult() 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<DataPointWithLabelInterface> = ArrayList() val iobPrediction: MutableList<DataPointWithLabelInterface> = ArrayList()
val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget) val iobPredictionArray = iobCobCalculator.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget)
for (i in iobPredictionArray) { for (i in iobPredictionArray) {

View file

@ -22,12 +22,14 @@ class AuthRequest internal constructor(
@Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var otp: OneTimePassword @Inject lateinit var otp: OneTimePassword
@Inject lateinit var dateUtil: DateUtil
private val date = DateUtil.now() private var date = 0L
private var processed = false private var processed = false
init { init {
injector.androidInjector().inject(this) injector.androidInjector().inject(this)
date = dateUtil.now()
smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, requestText)) 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))) smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_wrongcode)))
return return
} }
if (DateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) { if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
processed = true processed = true
aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text) aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text)
action.run() action.run()

View file

@ -1,9 +1,9 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.telephony.SmsMessage import android.telephony.SmsMessage
import info.nightscout.androidaps.utils.DateUtil
class Sms { class Sms {
var phoneNumber: String var phoneNumber: String
var text: String var text: String
var date: Long var date: Long
@ -22,7 +22,7 @@ class Sms {
internal constructor(phoneNumber: String, text: String) { internal constructor(phoneNumber: String, text: String) {
this.phoneNumber = phoneNumber this.phoneNumber = phoneNumber
this.text = text this.text = text
date = DateUtil.now() date = System.currentTimeMillis()
sent = true sent = true
} }

View file

@ -49,9 +49,11 @@ import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreferen
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.plusAssign
import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.StringUtils
import org.joda.time.DateTime
import java.text.Normalizer import java.text.Normalizer
import java.util.* import java.util.*
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.regex.Pattern
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.math.max import kotlin.math.max
@ -274,7 +276,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
"BOLUS" -> "BOLUS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) 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 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended)))
else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms) else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms)
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
@ -315,7 +317,7 @@ class SmsCommunicatorPlugin @Inject constructor(
if (actualBG != null) { if (actualBG != null) {
reply = resourceHelper.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", " reply = resourceHelper.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsString(units) + ", "
} else if (lastBG != null) { } else if (lastBG != null) {
val agoMilliseconds = System.currentTimeMillis() - lastBG.timestamp val agoMilliseconds = dateUtil.now() - lastBG.timestamp
val agoMin = (agoMilliseconds / 60.0 / 1000.0).toInt() 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) + ", " 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() { commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() { override fun run() {
if (result.success) { if (result.success) {
loopPlugin.suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000) loopPlugin.suspendTo(dateUtil.now() + anInteger() * 60L * 1000)
loopPlugin.createOfflineEvent(anInteger() * 60) loopPlugin.createOfflineEvent(anInteger() * 60)
rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) rxBus.send(EventRefreshOverview("SMS_LOOP_SUSPENDED"))
val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " + val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " +
@ -582,7 +584,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val finalPercentage = percentage val finalPercentage = percentage
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(list[pIndex - 1] as String, finalPercentage) { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(list[pIndex - 1] as String, finalPercentage) {
override fun run() { 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) val replyText = resourceHelper.gs(R.string.profileswitchcreated)
sendSMS(Sms(receivedSms.phoneNumber, replyText)) sendSMS(Sms(receivedSms.phoneNumber, replyText))
uel.log(Action.PROFILE_SWITCH, Sources.SMS, uel.log(Action.PROFILE_SWITCH, Sources.SMS,
@ -802,7 +804,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else else
String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered)
replyText += "\n" + activePlugin.activePump.shortStatus(true) replyText += "\n" + activePlugin.activePump.shortStatus(true)
lastRemoteBolusTime = DateUtil.now() lastRemoteBolusTime = dateUtil.now()
if (isMeal) { if (isMeal) {
profileFunction.getProfile()?.let { currentProfile -> profileFunction.getProfile()?.let { currentProfile ->
var eatingSoonTTDuration = sp.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration) var eatingSoonTTDuration = sp.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration)
@ -817,7 +819,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else -> Constants.defaultEatingSoonTTmgdl else -> Constants.defaultEatingSoonTTmgdl
} }
disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction( disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction(
timestamp = System.currentTimeMillis(), timestamp = dateUtil.now(),
duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()), duration = TimeUnit.MINUTES.toMillis(eatingSoonTTDuration.toLong()),
reason = TemporaryTarget.Reason.EATING_SOON, reason = TemporaryTarget.Reason.EATING_SOON,
lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()), lowTarget = Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()),
@ -852,11 +854,30 @@ class SmsCommunicatorPlugin @Inject constructor(
} else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) } 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<String>, receivedSms: Sms) { private fun processCARBS(divided: Array<String>, receivedSms: Sms) {
var grams = SafeParse.stringToInt(divided[1]) var grams = SafeParse.stringToInt(divided[1])
var time = DateUtil.now() var time = dateUtil.now()
if (divided.size > 2) { if (divided.size > 2) {
time = DateUtil.toTodayTime(divided[2].toUpperCase(Locale.getDefault())) time = toTodayTime(divided[2].toUpperCase(Locale.getDefault()))
if (time == 0L) { if (time == 0L) {
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
return return
@ -943,7 +964,7 @@ class SmsCommunicatorPlugin @Inject constructor(
tt = Profile.toCurrentUnits(profileFunction, tt) tt = Profile.toCurrentUnits(profileFunction, tt)
tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL
disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction( disposable += repository.runTransactionForResult(InsertTemporaryTargetAndCancelCurrentTransaction(
timestamp = System.currentTimeMillis(), timestamp = dateUtil.now(),
duration = TimeUnit.MINUTES.toMillis(ttDuration.toLong()), duration = TimeUnit.MINUTES.toMillis(ttDuration.toLong()),
reason = TemporaryTarget.Reason.EATING_SOON, reason = TemporaryTarget.Reason.EATING_SOON,
lowTarget = Profile.toMgdl(tt, profileFunction.getUnits()), lowTarget = Profile.toMgdl(tt, profileFunction.getUnits()),
@ -968,7 +989,7 @@ class SmsCommunicatorPlugin @Inject constructor(
receivedSms.processed = true receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
override fun run() { override fun run() {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil._now())) disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now()))
.subscribe({ result -> .subscribe({ result ->
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") }
}, { }, {

View file

@ -18,7 +18,8 @@ import javax.inject.Singleton
@Singleton @Singleton
class OneTimePassword @Inject constructor( class OneTimePassword @Inject constructor(
private val sp: SP, private val sp: SP,
private val resourceHelper: ResourceHelper private val resourceHelper: ResourceHelper,
private val dateUtil: DateUtil
) { ) {
private var key: SecretKey? = null private var key: SecretKey? = null
@ -85,7 +86,7 @@ class OneTimePassword @Inject constructor(
return OneTimePasswordValidationResult.ERROR_WRONG_PIN return OneTimePasswordValidationResult.ERROR_WRONG_PIN
} }
val counter: Long = DateUtil.now() / 30000L val counter: Long = dateUtil.now() / 30000L
val acceptableTokens: MutableList<String> = mutableListOf(generateOneTimePassword(counter)) val acceptableTokens: MutableList<String> = mutableListOf(generateOneTimePassword(counter))
for (i in 0 until Constants.OTP_ACCEPT_OLD_TOKENS_COUNT) { for (i in 0 until Constants.OTP_ACCEPT_OLD_TOKENS_COUNT) {

View file

@ -151,7 +151,7 @@ class TidepoolUploader @Inject constructor(
if (session.datasetReply == null) { if (session.datasetReply == null) {
rxBus.send(EventTidepoolStatus(("Creating new dataset"))) rxBus.send(EventTidepoolStatus(("Creating new dataset")))
val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!, val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!,
OpenDatasetRequestMessage(activePlugin.activePump.serialNumber()).getBody()) OpenDatasetRequestMessage(activePlugin.activePump.serialNumber(), dateUtil).getBody())
call.enqueue(TidepoolCallback<DatasetReplyMessage>(aapsLogger, rxBus, session, "Open New Dataset", { call.enqueue(TidepoolCallback<DatasetReplyMessage>(aapsLogger, rxBus, session, "Open New Dataset", {
connectionStatus = ConnectionStatus.CONNECTED connectionStatus = ConnectionStatus.CONNECTED
rxBus.send(EventTidepoolStatus(("New dataset OK"))) rxBus.send(EventTidepoolStatus(("New dataset OK")))
@ -232,7 +232,7 @@ class TidepoolUploader @Inject constructor(
} }
private fun uploadNext() { private fun uploadNext() {
if (uploadChunk.getLastEnd() < DateUtil.now() - T.mins(1).msecs()) { if (uploadChunk.getLastEnd() < dateUtil.now() - T.mins(1).msecs()) {
SystemClock.sleep(3000) SystemClock.sleep(3000)
aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd())) aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd()))
doUpload() doUpload()

View file

@ -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.elements.*
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance 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.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -29,7 +28,6 @@ class UploadChunk @Inject constructor(
private val rxBus: RxBusWrapper, private val rxBus: RxBusWrapper,
private val aapsLogger: AAPSLogger, private val aapsLogger: AAPSLogger,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val treatmentsPlugin: TreatmentsPlugin,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val databaseHelper: DatabaseHelperInterface, private val databaseHelper: DatabaseHelperInterface,
private val repository: AppRepository, private val repository: AppRepository,
@ -43,7 +41,7 @@ class UploadChunk @Inject constructor(
return null return null
session.start = getLastEnd() 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) val result = get(session.start, session.end)
if (result.length < 3) { if (result.length < 3) {
@ -83,7 +81,7 @@ class UploadChunk @Inject constructor(
fun getLastEnd(): Long { fun getLastEnd(): Long {
val result = sp.getLong(R.string.key_tidepool_last_end, 0) 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) { 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 // TODO we could make sure we include records older than the first bg record for completeness
val start: Long = 0 val start: Long = 0
val end = DateUtil.now() val end = dateUtil.now()
val bgReadingList = repository.compatGetBgReadingsDataFromTime(start, end, true) val bgReadingList = repository.compatGetBgReadingsDataFromTime(start, end, true)
.blockingGet() .blockingGet()
@ -117,19 +115,19 @@ class UploadChunk @Inject constructor(
repository.getBolusesDataFromTimeToTime(start, end, true) repository.getBolusesDataFromTimeToTime(start, end, true)
.blockingGet() .blockingGet()
.forEach { bolus -> .forEach { bolus ->
result.add(BolusElement(bolus)) result.add(BolusElement(bolus, dateUtil))
} }
repository.getCarbsDataFromTimeToTimeExpanded(start, end, true) repository.getCarbsDataFromTimeToTimeExpanded(start, end, true)
.blockingGet() .blockingGet()
.forEach { carb -> .forEach { carb ->
result.add(WizardElement(carb)) result.add(WizardElement(carb, dateUtil))
} }
return result return result
} }
private fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> { private fun getBloodTests(start: Long, end: Long): List<BloodGlucoseElement> {
val readings = repository.compatGetTherapyEventDataFromToTime(start, end).blockingGet() val readings = repository.compatGetTherapyEventDataFromToTime(start, end).blockingGet()
val selection = BloodGlucoseElement.fromCareportalEvents(readings) val selection = BloodGlucoseElement.fromCareportalEvents(readings, dateUtil)
if (selection.isNotEmpty()) if (selection.isNotEmpty())
rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload")) rxBus.send(EventTidepoolStatus("${selection.size} BGs selected for upload"))
return selection return selection
@ -139,7 +137,7 @@ class UploadChunk @Inject constructor(
private fun getBgReadings(start: Long, end: Long): List<SensorGlucoseElement> { private fun getBgReadings(start: Long, end: Long): List<SensorGlucoseElement> {
val readings = repository.compatGetBgReadingsDataFromTime(start, end, true) val readings = repository.compatGetBgReadingsDataFromTime(start, end, true)
.blockingGet() .blockingGet()
val selection = SensorGlucoseElement.fromBgReadings(readings) val selection = SensorGlucoseElement.fromBgReadings(readings, dateUtil)
if (selection.isNotEmpty()) if (selection.isNotEmpty())
rxBus.send(EventTidepoolStatus("${selection.size} CGMs selected for upload")) rxBus.send(EventTidepoolStatus("${selection.size} CGMs selected for upload"))
return selection return selection
@ -150,7 +148,7 @@ class UploadChunk @Inject constructor(
for (tbr in tbrList) { for (tbr in tbrList) {
if (tbr.timestamp in start..end) if (tbr.timestamp in start..end)
profileFunction.getProfile(tbr.timestamp)?.let { profileFunction.getProfile(tbr.timestamp)?.let {
results.add(BasalElement(tbr, it)) results.add(BasalElement(tbr, it, dateUtil))
} }
} }
return results return results
@ -165,7 +163,7 @@ class UploadChunk @Inject constructor(
} }
private fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try { private fun newInstanceOrNull(ps: ProfileSwitch): ProfileElement? = try {
ProfileElement(ps, activePlugin.activePump.serialNumber()) ProfileElement(ps, activePlugin.activePump.serialNumber(), dateUtil)
} catch (e: Throwable) { } catch (e: Throwable) {
null null
} }

View file

@ -4,10 +4,11 @@ import com.google.gson.annotations.Expose
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.entities.TemporaryBasal import info.nightscout.androidaps.database.entities.TemporaryBasal
import info.nightscout.androidaps.extensions.convertedToAbsolute import info.nightscout.androidaps.extensions.convertedToAbsolute
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
class BasalElement(tbr: TemporaryBasal, private val profile: Profile) class BasalElement(tbr: TemporaryBasal, private val profile: Profile, dateUtil: DateUtil)
: BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString()) { : BaseElement(tbr.timestamp, UUID.nameUUIDFromBytes(("AAPS-basal" + tbr.timestamp).toByteArray()).toString(), dateUtil) {
internal var timestamp: Long = 0 // not exposed internal var timestamp: Long = 0 // not exposed

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
open class BaseElement(timestamp: Long, uuid: String) { open class BaseElement(timestamp: Long, uuid: String, dateUtil: DateUtil) {
@Expose @Expose
var deviceTime: String = "" var deviceTime: String = ""
@Expose @Expose
@ -16,9 +16,9 @@ open class BaseElement(timestamp: Long, uuid: String) {
var origin: Origin? = null var origin: Origin? = null
init { init {
deviceTime = DateUtil.toISONoZone(timestamp) deviceTime = dateUtil.toISONoZone(timestamp)
time = DateUtil.toISOAsUTC(timestamp) time = dateUtil.toISOAsUTC(timestamp)
timezoneOffset = DateUtil.getTimeZoneOffsetMinutes(timestamp) // TODO timezoneOffset = dateUtil.getTimeZoneOffsetMinutes(timestamp) // TODO
origin = Origin(uuid) origin = Origin(uuid)
} }

View file

@ -4,10 +4,11 @@ import com.google.gson.annotations.Expose
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.extensions.toConstant import info.nightscout.androidaps.extensions.toConstant
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
class BloodGlucoseElement(therapyEvent: TherapyEvent) class BloodGlucoseElement(therapyEvent: TherapyEvent, dateUtil: DateUtil)
: BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString()) { : BaseElement(therapyEvent.timestamp, UUID.nameUUIDFromBytes(("AAPS-bg" + therapyEvent.timestamp).toByteArray()).toString(), dateUtil) {
@Expose @Expose
var subType: String = "manual" var subType: String = "manual"
@ -28,13 +29,13 @@ class BloodGlucoseElement(therapyEvent: TherapyEvent)
companion object { companion object {
fun fromCareportalEvents(careportalList: List<TherapyEvent>): List<BloodGlucoseElement> { fun fromCareportalEvents(careportalList: List<TherapyEvent>, dateUtil: DateUtil): List<BloodGlucoseElement> {
val results = LinkedList<BloodGlucoseElement>() val results = LinkedList<BloodGlucoseElement>()
for (bt in careportalList) { for (bt in careportalList) {
if (bt.type == TherapyEvent.Type.NS_MBG || bt.type == TherapyEvent.Type.FINGER_STICK_BG_VALUE) { 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) if (bge.value > 0)
results.add(BloodGlucoseElement(bt)) results.add(BloodGlucoseElement(bt, dateUtil))
} }
} }
return results return results

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
class BolusElement(bolus: Bolus) class BolusElement(bolus: Bolus, dateUtil: DateUtil)
: BaseElement(bolus.timestamp, UUID.nameUUIDFromBytes(("AAPS-bolus" + bolus.timestamp).toByteArray()).toString()) { : BaseElement(bolus.timestamp, UUID.nameUUIDFromBytes(("AAPS-bolus" + bolus.timestamp).toByteArray()).toString(), dateUtil) {
@Expose var subType = "normal" @Expose var subType = "normal"
@Expose var normal: Double = 0.0 @Expose var normal: Double = 0.0

View file

@ -4,11 +4,12 @@ import com.google.gson.annotations.Expose
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
import kotlin.collections.ArrayList import kotlin.collections.ArrayList
class ProfileElement(ps: ProfileSwitch, serialNumber: String) class ProfileElement(ps: ProfileSwitch, serialNumber: String, dateUtil: DateUtil)
: BaseElement(ps.date, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.date).toByteArray()).toString()) { : BaseElement(ps.date, UUID.nameUUIDFromBytes(("AAPS-profile" + ps.date).toByteArray()).toString(), dateUtil) {
@Expose @Expose
internal var activeSchedule = "Normal" internal var activeSchedule = "Normal"

View file

@ -2,10 +2,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
class SensorGlucoseElement(bgReading: GlucoseValue) class SensorGlucoseElement(bgReading: GlucoseValue, private val dateUtil: DateUtil)
: BaseElement(bgReading.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.timestamp).toByteArray()).toString()) { : BaseElement(bgReading.timestamp, UUID.nameUUIDFromBytes(("AAPS-cgm" + bgReading.timestamp).toByteArray()).toString(), dateUtil) {
@Expose @Expose
internal var units: String = "mg/dL" internal var units: String = "mg/dL"
@ -20,10 +21,10 @@ class SensorGlucoseElement(bgReading: GlucoseValue)
companion object { companion object {
internal fun fromBgReadings(bgReadingList: List<GlucoseValue>): List<SensorGlucoseElement> { internal fun fromBgReadings(bgReadingList: List<GlucoseValue>, dateUtil: DateUtil): List<SensorGlucoseElement> {
val results = LinkedList<SensorGlucoseElement>() val results = LinkedList<SensorGlucoseElement>()
for (bgReading in bgReadingList) { for (bgReading in bgReadingList) {
results.add(SensorGlucoseElement(bgReading)) results.add(SensorGlucoseElement(bgReading, dateUtil))
} }
return results return results
} }

View file

@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements
import com.google.gson.annotations.Expose import com.google.gson.annotations.Expose
import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.Carbs import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.utils.DateUtil
import java.util.* import java.util.*
class WizardElement(carbs: Carbs) class WizardElement(carbs: Carbs, dateUtil: DateUtil)
: BaseElement(carbs.timestamp, UUID.nameUUIDFromBytes(("AAPS-wizard" + carbs.timestamp).toByteArray()).toString()) { : BaseElement(carbs.timestamp, UUID.nameUUIDFromBytes(("AAPS-wizard" + carbs.timestamp).toByteArray()).toString(), dateUtil) {
@Expose var units = "mg/dL" @Expose var units = "mg/dL"
@Expose var carbInput: Double = 0.toDouble() @Expose var carbInput: Double = 0.toDouble()
@ -21,7 +22,7 @@ class WizardElement(carbs: Carbs)
timestamp = carbs.timestamp, timestamp = carbs.timestamp,
type = Bolus.Type.NORMAL type = Bolus.Type.NORMAL
) )
bolus = BolusElement(fake) // fake insulin record bolus = BolusElement(fake, dateUtil) // fake insulin record
} }
} }

View file

@ -1,12 +1,12 @@
package info.nightscout.androidaps.plugins.general.tidepool.events package info.nightscout.androidaps.plugins.general.tidepool.events
import info.nightscout.androidaps.events.Event import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.utils.DateUtil
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
class EventTidepoolStatus(val status: String) : Event() { 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()) private var timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

View file

@ -7,46 +7,62 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import java.util.* import java.util.*
class OpenDatasetRequestMessage (val serialNumber : String): BaseMessage() { class OpenDatasetRequestMessage(serialNumber: String, dateUtil: DateUtil) : BaseMessage() {
@Expose @Expose
var deviceId: String = TidepoolUploader.PUMP_TYPE + ":" + serialNumber var deviceId: String = TidepoolUploader.PUMP_TYPE + ":" + serialNumber
@Expose @Expose
var time: String = DateUtil.toISOAsUTC(DateUtil.now()) var time: String = dateUtil.toISOAsUTC(System.currentTimeMillis())
@Expose @Expose
var timezoneOffset = (DateUtil.getTimeZoneOffsetMs() / T.mins(1).msecs()).toInt() var timezoneOffset = (dateUtil.getTimeZoneOffsetMs() / T.mins(1).msecs()).toInt()
@Expose @Expose
var type = "upload" var type = "upload"
//public String byUser; //public String byUser;
@Expose @Expose
var client = ClientInfo() var client = ClientInfo()
@Expose @Expose
var computerTime: String = DateUtil.toISONoZone(DateUtil.now()) var computerTime: String = dateUtil.toISONoZone(System.currentTimeMillis())
@Expose @Expose
var dataSetType = "continuous" var dataSetType = "continuous"
@Expose @Expose
var deviceManufacturers = arrayOf(TidepoolUploader.PUMP_TYPE) var deviceManufacturers = arrayOf(TidepoolUploader.PUMP_TYPE)
@Expose @Expose
var deviceModel = TidepoolUploader.PUMP_TYPE var deviceModel = TidepoolUploader.PUMP_TYPE
@Expose @Expose
var deviceTags = arrayOf("bgm", "cgm", "insulin-pump") var deviceTags = arrayOf("bgm", "cgm", "insulin-pump")
@Expose @Expose
var deduplicator = Deduplicator() var deduplicator = Deduplicator()
@Expose @Expose
var timeProcessing = "none" var timeProcessing = "none"
@Expose @Expose
var timezone: String = TimeZone.getDefault().id var timezone: String = TimeZone.getDefault().id
@Expose @Expose
var version = BuildConfig.VERSION_NAME var version = BuildConfig.VERSION_NAME
inner class ClientInfo { inner class ClientInfo {
@Expose @Expose
val name = BuildConfig.APPLICATION_ID val name = BuildConfig.APPLICATION_ID
@Expose @Expose
val version = TidepoolUploader.VERSION val version = TidepoolUploader.VERSION
} }
inner class Deduplicator { inner class Deduplicator {
@Expose @Expose
val name = "org.tidepool.deduplicator.dataset.delete.origin" val name = "org.tidepool.deduplicator.dataset.delete.origin"
} }

View file

@ -21,13 +21,13 @@ class RateLimit @Inject constructor(
fun rateLimit(name: String, seconds: Int): Boolean { fun rateLimit(name: String, seconds: Int): Boolean {
// check if over limit // check if over limit
rateLimits[name]?.let { 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") aapsLogger.debug(LTag.TIDEPOOL, "$name rate limited: $seconds seconds")
return false return false
} }
} }
// not over limit // not over limit
rateLimits[name] = dateUtil._now() rateLimits[name] = dateUtil.now()
return true return true
} }
} }

View file

@ -220,7 +220,7 @@ class ActionStringHandler @Inject constructor(
} }
val format = DecimalFormat("0.00") val format = DecimalFormat("0.00")
val formatInt = DecimalFormat("0") 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 tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null
val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, tempTarget, val bolusWizard = BolusWizard(injector).doCalc(profile, profileName, tempTarget,
@ -457,7 +457,7 @@ class ActionStringHandler @Inject constructor(
} }
val profile = profileFunction.getProfile() ?: return "No profile set :(" val profile = profileFunction.getProfile() ?: return "No profile set :("
//Check for Temp-Target: //Check for Temp-Target:
val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil._now()).blockingGet() val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet()
if (tempTarget is ValueWrapper.Existing) { if (tempTarget is ValueWrapper.Existing) {
ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, Constants.MGDL, profileFunction.getUnits()) ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, Constants.MGDL, profileFunction.getUnits())
ret += "\nuntil: " + dateUtil.timeString(tempTarget.value.end) ret += "\nuntil: " + dateUtil.timeString(tempTarget.value.end)

View file

@ -192,7 +192,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
var dia = Constants.defaultDIA var dia = Constants.defaultDIA
if (profile != null) dia = profile.dia if (profile != null) dia = profile.dia
val start = to - T.hours((24 + dia).toLong()).msecs() 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) // if close to now expect there can be some readings with time in close future (caused by wrong time setting)
// so read all records // so read all records
bgReadings = repository.compatGetBgReadingsDataFromTime(start, false).blockingGet() bgReadings = repository.compatGetBgReadingsDataFromTime(start, false).blockingGet()
@ -309,7 +309,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
} }
val bData: MutableList<InMemoryGlucoseValue> = ArrayList() val bData: MutableList<InMemoryGlucoseValue> = ArrayList()
bData.add(InMemoryGlucoseValue(bgReadings[0])) 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 var j = 0
for (i in 1 until bgReadings.size) { for (i in 1 until bgReadings.size) {
val bgTime = bgReadings[i].timestamp val bgTime = bgReadings[i].timestamp
@ -333,7 +333,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val newBgReading = InMemoryGlucoseValue(nextBgTime, nextBg.roundToLong().toDouble(), true) val newBgReading = InMemoryGlucoseValue(nextBgTime, nextBg.roundToLong().toDouble(), true)
//console.error("Interpolated", bData[j]); //console.error("Interpolated", bData[j]);
bData.add(newBgReading) 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 elapsedMinutes -= 5
lastBg = nextBg lastBg = nextBg
lastBgTime = nextBgTime lastBgTime = nextBgTime
@ -341,14 +341,14 @@ open class IobCobCalculatorPlugin @Inject constructor(
j++ j++
val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value) val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value)
bData.add(newBgReading) 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 -> { abs(elapsedMinutes) > 2 -> {
j++ j++
val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value) val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value)
bData.add(newBgReading) 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 -> { 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 { 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 bolusIob = calculateIobFromBolusToTime(time).round()
val basalIob = getCalculationToTimeTempBasals(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round() val basalIob = getCalculationToTimeTempBasals(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round()
// OpenAPSSMB only // OpenAPSSMB only
@ -551,7 +551,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val autosensData = if (_synchronized) getLastAutosensDataSynchronized(reason) else getLastAutosensData(reason) val autosensData = if (_synchronized) getLastAutosensDataSynchronized(reason) else getLastAutosensData(reason)
var displayCob: Double? = null var displayCob: Double? = null
var futureCarbs = 0.0 var futureCarbs = 0.0
val now = DateUtil.now() val now = dateUtil.now()
val carbs = repository.getCarbsDataFromTimeExpanded(now, true).blockingGet() val carbs = repository.getCarbsDataFromTimeExpanded(now, true).blockingGet()
if (autosensData != null) { if (autosensData != null) {
displayCob = autosensData.cob 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<IobTotal> { override fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array<IobTotal> {
// predict IOB out to DIA plus 30m // predict IOB out to DIA plus 30m
val now = DateUtil.now() val now = dateUtil.now()
val len = 4 * 60 / 5 val len = 4 * 60 / 5
val array = Array(len) { IobTotal(0) } val array = Array(len) { IobTotal(0) }
for ((pos, i) in (0 until len).withIndex()) { 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 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<IobTotal>): JSONArray {
val array = JSONArray()
for (i in iobArray.indices) {
array.put(iobArray[i].determineBasalJson(dateUtil))
}
return array
}
companion object { 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<IobTotal>): JSONArray {
val array = JSONArray()
for (i in iobArray.indices) {
array.put(iobArray[i].determineBasalJson())
}
return array
}
// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2 // From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
// Returns the value at a given percentile in a sorted numeric array. // Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method // "Linear interpolation between closest ranks" method
@ -809,7 +809,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
fun range(): Long = ((profileFunction.getProfile()?.dia fun range(): Long = ((profileFunction.getProfile()?.dia
?: Constants.defaultDIA) * 60 * 60 * 1000).toLong() ?: 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 { override fun calculateIobFromBolusToTime(toTime: Long): IobTotal {
val total = IobTotal(toTime) val total = IobTotal(toTime)
@ -842,7 +842,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
private fun calculateIobToTimeFromExtendedBoluses(toTime: Long): IobTotal { private fun calculateIobToTimeFromExtendedBoluses(toTime: Long): IobTotal {
val total = IobTotal(toTime) val total = IobTotal(toTime)
val now = dateUtil._now() val now = dateUtil.now()
val pumpInterface = activePlugin.activePump val pumpInterface = activePlugin.activePump
if (!pumpInterface.isFakingTempsByExtendedBoluses) { if (!pumpInterface.isFakingTempsByExtendedBoluses) {
val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() val extendedBoluses = repository.getExtendedBolusDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
@ -906,11 +906,11 @@ open class IobCobCalculatorPlugin @Inject constructor(
} }
override fun calculateIobFromTempBasalsIncludingConvertedExtended(): IobTotal = override fun calculateIobFromTempBasalsIncludingConvertedExtended(): IobTotal =
calculateIobToTimeFromTempBasalsIncludingConvertedExtended(dateUtil._now()) calculateIobToTimeFromTempBasalsIncludingConvertedExtended(dateUtil.now())
override fun calculateIobToTimeFromTempBasalsIncludingConvertedExtended(toTime: Long): IobTotal { override fun calculateIobToTimeFromTempBasalsIncludingConvertedExtended(toTime: Long): IobTotal {
val total = IobTotal(toTime) val total = IobTotal(toTime)
val now = dateUtil._now() val now = dateUtil.now()
val pumpInterface = activePlugin.activePump val pumpInterface = activePlugin.activePump
val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() 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 { open fun getCalculationToTimeTempBasals(toTime: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal {
val total = IobTotal(toTime) val total = IobTotal(toTime)
val pumpInterface = activePlugin.activePump val pumpInterface = activePlugin.activePump
val now = dateUtil._now() val now = dateUtil.now()
val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet() val temporaryBasals = repository.getTemporaryBasalsDataFromTimeToTime(toTime - range(), toTime, true).blockingGet()
for (pos in temporaryBasals.indices) { for (pos in temporaryBasals.indices) {
val t = temporaryBasals[pos] val t = temporaryBasals[pos]

View file

@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification 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.data.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
@ -67,7 +66,7 @@ class IobCobOref1Thread internal constructor(
} }
override fun run() { override fun run() {
val start = DateUtil.now() val start = dateUtil.now()
mWakeLock?.acquire(T.mins(10).msecs()) mWakeLock?.acquire(T.mins(10).msecs())
try { try {
aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: $from") 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") aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from")
return 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)) aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime))
var previous = autosensDataTable[prevDataTime] var previous = autosensDataTable[prevDataTime]
// start from oldest to be able sub cob // start from oldest to be able sub cob
@ -103,8 +102,8 @@ class IobCobOref1Thread internal constructor(
} }
// check if data already exists // check if data already exists
var bgTime = bucketedData[i].timestamp var bgTime = bucketedData[i].timestamp
bgTime = roundUpTime(bgTime) bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime)
if (bgTime > roundUpTime(DateUtil.now())) continue if (bgTime > iobCobCalculatorPlugin.roundUpTime(dateUtil.now())) continue
var existing: AutosensData? var existing: AutosensData?
if (autosensDataTable[bgTime].also { existing = it } != null) { if (autosensDataTable[bgTime].also { existing = it } != null) {
previous = existing previous = existing
@ -294,7 +293,7 @@ class IobCobOref1Thread internal constructor(
// TODO AS-FIX // TODO AS-FIX
@Suppress("SimplifyBooleanWithConstants") @Suppress("SimplifyBooleanWithConstants")
if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { 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) { if (tempTarget is ValueWrapper.Existing && tempTarget.value.target() >= 100) {
autosensData.extraDeviation.add(-(tempTarget.value.target() - 100) / 20) autosensData.extraDeviation.add(-(tempTarget.value.target() - 100) / 20)
} }
@ -307,7 +306,7 @@ class IobCobOref1Thread internal constructor(
val hours = calendar[Calendar.HOUR_OF_DAY] val hours = calendar[Calendar.HOUR_OF_DAY]
if (min in 0..4 && hours % 2 == 0) autosensData.extraDeviation.add(0.0) if (min in 0..4 && hours % 2 == 0) autosensData.extraDeviation.add(0.0)
previous = autosensData 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()) aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime())
val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime) val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime)
aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity") aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity")

View file

@ -17,7 +17,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification 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.data.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
@ -66,7 +65,7 @@ class IobCobThread @Inject internal constructor(
} }
override fun run() { override fun run() {
val start = DateUtil.now() val start = dateUtil.now()
mWakeLock?.acquire(T.mins(10).msecs()) mWakeLock?.acquire(T.mins(10).msecs())
try { try {
aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: $from") 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") aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from")
return 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)) aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime))
var previous = autosensDataTable[prevDataTime] var previous = autosensDataTable[prevDataTime]
// start from oldest to be able sub cob // start from oldest to be able sub cob
@ -102,8 +101,8 @@ class IobCobThread @Inject internal constructor(
} }
// check if data already exists // check if data already exists
var bgTime = bucketedData[i].timestamp var bgTime = bucketedData[i].timestamp
bgTime = roundUpTime(bgTime) bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime)
if (bgTime > roundUpTime(DateUtil.now())) continue if (bgTime > iobCobCalculatorPlugin.roundUpTime(dateUtil.now())) continue
var existing: AutosensData? var existing: AutosensData?
if (autosensDataTable[bgTime].also { existing = it } != null) { if (autosensDataTable[bgTime].also { existing = it } != null) {
previous = existing previous = existing
@ -254,7 +253,7 @@ class IobCobThread @Inject internal constructor(
autosensData.pastSensitivity += "C" autosensData.pastSensitivity += "C"
} }
previous = autosensData 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()) aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime())
val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime) val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime)
aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity") aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity")

View file

@ -34,6 +34,7 @@ class LocalProfilePlugin @Inject constructor(
private val sp: SP, private val sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val nsUpload: NSUpload, private val nsUpload: NSUpload,
private val dateUtil: DateUtil,
private val uel: UserEntryLogger private val uel: UserEntryLogger
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.PROFILE) .mainType(PluginType.PROFILE)
@ -203,7 +204,7 @@ class LocalProfilePlugin @Inject constructor(
fun copyFrom(profile: Profile, newName: String): SingleProfile { fun copyFrom(profile: Profile, newName: String): SingleProfile {
var verifiedName = newName var verifiedName = newName
if (rawProfile?.getSpecificProfile(newName) != null) { if (rawProfile?.getSpecificProfile(newName) != null) {
verifiedName += " " + DateUtil.now().toString() verifiedName += " " + dateUtil.now().toString()
} }
val sp = SingleProfile() val sp = SingleProfile()
sp.name = verifiedName sp.name = verifiedName
@ -340,7 +341,7 @@ class LocalProfilePlugin @Inject constructor(
} }
} }
if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name) 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) json.put("store", store)
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)

View file

@ -36,6 +36,7 @@ class NSProfileFragment : DaggerFragment() {
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var nsProfilePlugin: NSProfilePlugin @Inject lateinit var nsProfilePlugin: NSProfilePlugin
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -67,7 +68,7 @@ class NSProfileFragment : DaggerFragment() {
uel.log(Action.PROFILE_SWITCH, Sources.NSProfile, uel.log(Action.PROFILE_SWITCH, Sources.NSProfile,
ValueWithUnit.SimpleString(name), ValueWithUnit.SimpleString(name),
ValueWithUnit.Percent(100)) ValueWithUnit.Percent(100))
treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, dateUtil.now())
}) })
} }
} }

View file

@ -79,7 +79,7 @@ class MDIPlugin @Inject constructor(
timestamp = detailedBolusInfo.timestamp, timestamp = detailedBolusInfo.timestamp,
amount = detailedBolusInfo.insulin, amount = detailedBolusInfo.insulin,
type = detailedBolusInfo.bolusType, type = detailedBolusInfo.bolusType,
pumpId = dateUtil._now(), pumpId = dateUtil.now(),
pumpType = PumpType.MDI, pumpType = PumpType.MDI,
pumpSerial = serialNumber()) pumpSerial = serialNumber())
if (detailedBolusInfo.carbs > 0) if (detailedBolusInfo.carbs > 0)
@ -142,10 +142,10 @@ class MDIPlugin @Inject constructor(
status.put("status", "normal") status.put("status", "normal")
extended.put("Version", version) extended.put("Version", version)
extended.put("ActiveProfile", profileName) extended.put("ActiveProfile", profileName)
status.put("timestamp", DateUtil.toISOString(now)) status.put("timestamp", dateUtil.toISOString(now))
pump.put("status", status) pump.put("status", status)
pump.put("extended", extended) pump.put("extended", extended)
pump.put("clock", DateUtil.toISOString(now)) pump.put("clock", dateUtil.toISOString(now))
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Exception: ", e) aapsLogger.error("Exception: ", e)
} }

View file

@ -95,9 +95,9 @@ class VirtualPumpFragment : DaggerFragment() {
if (_binding == null) return if (_binding == null) return
val profile = profileFunction.getProfile() ?: return val profile = profileFunction.getProfile() ?: return
binding.basabasalrate.text = resourceHelper.gs(R.string.pump_basebasalrate, virtualPumpPlugin.baseBasalRate) 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.battery.text = resourceHelper.gs(R.string.format_percent, virtualPumpPlugin.batteryPercent)
binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble()) binding.reservoir.text = resourceHelper.gs(R.string.formatinsulinunits, virtualPumpPlugin.reservoirInUnits.toDouble())

View file

@ -206,7 +206,7 @@ open class VirtualPumpPlugin @Inject constructor(
timestamp = detailedBolusInfo.timestamp, timestamp = detailedBolusInfo.timestamp,
amount = detailedBolusInfo.insulin, amount = detailedBolusInfo.insulin,
type = detailedBolusInfo.bolusType, type = detailedBolusInfo.bolusType,
pumpId = dateUtil._now(), pumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber()) pumpSerial = serialNumber())
if (detailedBolusInfo.carbs > 0) if (detailedBolusInfo.carbs > 0)
@ -229,12 +229,12 @@ open class VirtualPumpPlugin @Inject constructor(
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
rate = absoluteRate, rate = absoluteRate,
duration = T.mins(durationInMinutes.toLong()).msecs(), duration = T.mins(durationInMinutes.toLong()).msecs(),
isAbsolute = true, isAbsolute = true,
type = tbrType, type = tbrType,
pumpId = dateUtil._now(), pumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber() pumpSerial = serialNumber()
) )
@ -254,12 +254,12 @@ open class VirtualPumpPlugin @Inject constructor(
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
pumpSync.syncTemporaryBasalWithPumpId( pumpSync.syncTemporaryBasalWithPumpId(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
rate = percent.toDouble(), rate = percent.toDouble(),
duration = T.mins(durationInMinutes.toLong()).msecs(), duration = T.mins(durationInMinutes.toLong()).msecs(),
isAbsolute = false, isAbsolute = false,
type = tbrType, type = tbrType,
pumpId = dateUtil._now(), pumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber() pumpSerial = serialNumber()
) )
@ -279,11 +279,11 @@ open class VirtualPumpPlugin @Inject constructor(
result.duration = durationInMinutes result.duration = durationInMinutes
result.comment = resourceHelper.gs(R.string.virtualpump_resultok) result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
pumpSync.syncExtendedBolusWithPumpId( pumpSync.syncExtendedBolusWithPumpId(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
amount = insulin, amount = insulin,
duration = T.mins(durationInMinutes.toLong()).msecs(), duration = T.mins(durationInMinutes.toLong()).msecs(),
isEmulatingTB = false, isEmulatingTB = false,
pumpId = dateUtil._now(), pumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber() pumpSerial = serialNumber()
) )
@ -301,8 +301,8 @@ open class VirtualPumpPlugin @Inject constructor(
if (pumpSync.expectedPumpState().temporaryBasal != null) { if (pumpSync.expectedPumpState().temporaryBasal != null) {
result.enacted = true result.enacted = true
pumpSync.syncStopTemporaryBasalWithPumpId( pumpSync.syncStopTemporaryBasalWithPumpId(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
endPumpId = dateUtil._now(), endPumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber() pumpSerial = serialNumber()
) )
@ -317,8 +317,8 @@ open class VirtualPumpPlugin @Inject constructor(
val result = PumpEnactResult(injector) val result = PumpEnactResult(injector)
if (pumpSync.expectedPumpState().extendedBolus != null) { if (pumpSync.expectedPumpState().extendedBolus != null) {
pumpSync.syncStopExtendedBolusWithPumpId( pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
endPumpId = dateUtil._now(), endPumpId = dateUtil.now(),
pumpType = pumpType ?: PumpType.GENERIC_AAPS, pumpType = pumpType ?: PumpType.GENERIC_AAPS,
pumpSerial = serialNumber() pumpSerial = serialNumber()
) )
@ -362,12 +362,12 @@ open class VirtualPumpPlugin @Inject constructor(
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp)) extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp))
extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes)
} }
status.put("timestamp", DateUtil.toISOString(now)) status.put("timestamp", dateUtil.toISOString(now))
pump.put("battery", battery) pump.put("battery", battery)
pump.put("status", status) pump.put("status", status)
pump.put("extended", extended) pump.put("extended", extended)
pump.put("reservoir", reservoirInUnits) pump.put("reservoir", reservoirInUnits)
pump.put("clock", DateUtil.toISOString(now)) pump.put("clock", dateUtil.toISOString(now))
} catch (e: JSONException) { } catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e) aapsLogger.error("Unhandled exception", e)
} }

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.PluginDescription 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.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult 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.utils.DateUtil
import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException
@ -30,10 +30,10 @@ import kotlin.math.roundToInt
@Singleton @Singleton
open class SensitivityAAPSPlugin @Inject constructor( open class SensitivityAAPSPlugin @Inject constructor(
injector: HasAndroidInjector?, injector: HasAndroidInjector,
aapsLogger: AAPSLogger?, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper?, resourceHelper: ResourceHelper,
sp: SP?, sp: SP,
private val profileFunction: ProfileFunction, private val profileFunction: ProfileFunction,
private val dateUtil: DateUtil, private val dateUtil: DateUtil,
private val databaseHelper: DatabaseHelperInterface, private val databaseHelper: DatabaseHelperInterface,
@ -45,7 +45,7 @@ open class SensitivityAAPSPlugin @Inject constructor(
.shortName(R.string.sensitivity_shortname) .shortName(R.string.sensitivity_shortname)
.preferencesId(R.xml.pref_absorption_aaps) .preferencesId(R.xml.pref_absorption_aaps)
.description(R.string.description_sensitivity_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 { override fun detectSensitivity(plugin: IobCobCalculator, fromTime: Long, toTime: Long): AutosensResult {
@ -116,7 +116,7 @@ open class SensitivityAAPSPlugin @Inject constructor(
val sensResult: String val sensResult: String
aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity")
Arrays.sort(deviations) 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 basalOff = percentile * (60.0 / 5.0) / sens
val ratio = 1 + basalOff / profile.maxDailyBasal val ratio = 1 + basalOff / profile.maxDailyBasal
sensResult = when { sensResult = when {

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.IobCobCalculator import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.PluginDescription 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.logging.LTag
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult 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.utils.DateUtil
import info.nightscout.androidaps.extensions.isEvent5minBack
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException
@ -163,8 +163,8 @@ open class SensitivityOref1Plugin @Inject constructor(
val sens = profile.isfMgdl val sens = profile.isfMgdl
aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity") aapsLogger.debug(LTag.AUTOSENS, "Records: $index $pastSensitivity")
Arrays.sort(deviations) Arrays.sort(deviations)
val pSensitive = percentile(deviations, 0.50) val pSensitive = IobCobCalculatorPlugin.percentile(deviations, 0.50)
val pResistant = percentile(deviations, 0.50) val pResistant = IobCobCalculatorPlugin.percentile(deviations, 0.50)
var basalOff = 0.0 var basalOff = 0.0
when { when {
pSensitive < 0 -> { // sensitive pSensitive < 0 -> { // sensitive

View file

@ -29,6 +29,8 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.extensions.directionToIcon import info.nightscout.androidaps.extensions.directionToIcon
import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.extensions.valueToUnitsString import info.nightscout.androidaps.extensions.valueToUnitsString
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.AapsSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -47,6 +49,7 @@ class BGSourceFragment : DaggerFragment() {
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var uel: UserEntryLogger @Inject lateinit var uel: UserEntryLogger
@Inject lateinit var activePlugin: ActivePluginProvider
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
private val millsToThePast = T.hours(12).msecs() private val millsToThePast = T.hours(12).msecs()
@ -131,8 +134,18 @@ class BGSourceFragment : DaggerFragment() {
activity?.let { activity -> activity?.let { activity ->
val text = dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + glucoseValue.valueToUnitsString(profileFunction.getUnits()) val text = dateUtil.dateAndTimeString(glucoseValue.timestamp) + "\n" + glucoseValue.valueToUnitsString(profileFunction.getUnits())
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable {
//uel.log(Action.BG_REMOVED, XXXValueWithUnit.Timestamp(glucoseValue.timestamp)) val source = when((activePlugin.activeBgSource as PluginBase).pluginDescription.pluginName) {
uel.log(Action.BG_REMOVED, Sources.BG, R.string.dexcom_app_patched -> Sources.Dexcom
R.string.eversense -> Sources.Eversense
R.string.Glimp -> Sources.Glimp
R.string.MM640g -> Sources.MM640g
R.string.nsclientbg -> Sources.NSClientSource
R.string.poctech -> Sources.PocTech
R.string.tomato -> Sources.Tomato
R.string.xdrip -> Sources.Xdrip
else -> Sources.Unknown
}
uel.log(Action.BG_REMOVED, source,
ValueWithUnit.Timestamp(glucoseValue.timestamp)) ValueWithUnit.Timestamp(glucoseValue.timestamp))
disposable += repository.runTransaction(InvalidateGlucoseValueTransaction(glucoseValue.id)).subscribe() disposable += repository.runTransaction(InvalidateGlucoseValueTransaction(glucoseValue.id)).subscribe()
}) })

View file

@ -14,6 +14,9 @@ import info.nightscout.androidaps.activities.RequestDexcomPermissionActivity
import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.interfaces.BgSourceInterface import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
@ -21,6 +24,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.receivers.DataWorker
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
@ -80,9 +84,11 @@ class DexcomPlugin @Inject constructor(
@Inject lateinit var injector: HasAndroidInjector @Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var dexcomPlugin: DexcomPlugin @Inject lateinit var dexcomPlugin: DexcomPlugin
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var dataWorker: DataWorker @Inject lateinit var dataWorker: DataWorker
@Inject lateinit var broadcastToXDrip: XDripBroadcast @Inject lateinit var broadcastToXDrip: XDripBroadcast
@Inject lateinit var repository: AppRepository @Inject lateinit var repository: AppRepository
@Inject lateinit var uel: UserEntryLogger
init { init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this) (context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
@ -119,7 +125,7 @@ class DexcomPlugin @Inject constructor(
for (i in 0 until meters.size()) { for (i in 0 until meters.size()) {
meters.getBundle(i.toString())?.let { meters.getBundle(i.toString())?.let {
val timestamp = it.getLong("timestamp") * 1000 val timestamp = it.getLong("timestamp") * 1000
val now = DateUtil.now() val now = dateUtil.now()
if (timestamp > now - T.months(1).msecs() && timestamp < now) { if (timestamp > now - T.months(1).msecs() && timestamp < now) {
calibrations.add(CgmSourceTransaction.Calibration( calibrations.add(CgmSourceTransaction.Calibration(
timestamp = it.getLong("timestamp") * 1000, timestamp = it.getLong("timestamp") * 1000,
@ -150,8 +156,20 @@ class DexcomPlugin @Inject constructor(
broadcastToXDrip(it) broadcastToXDrip(it)
aapsLogger.debug(LTag.DATABASE, "Updated bg $it") aapsLogger.debug(LTag.DATABASE, "Updated bg $it")
} }
result.sensorInsertionsInserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted sensor insertion $it") } result.sensorInsertionsInserted.forEach {
result.calibrationsInserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted calibration $it") } uel.log(Action.CAREPORTAL,
Sources.BG,
ValueWithUnit.Timestamp(it.timestamp),
ValueWithUnit.TherapyEventType(it.type))
aapsLogger.debug(LTag.DATABASE, "Inserted sensor insertion $it")
}
result.calibrationsInserted.forEach {
uel.log(Action.CAREPORTAL,
Sources.BG,
ValueWithUnit.Timestamp(it.timestamp),
ValueWithUnit.TherapyEventType(it.type))
aapsLogger.debug(LTag.DATABASE, "Inserted calibration $it")
}
} }
} catch (e: Exception) { } catch (e: Exception) {
aapsLogger.error("Error while processing intent from Dexcom App", e) aapsLogger.error("Error while processing intent from Dexcom App", e)

View file

@ -127,12 +127,12 @@ class NSClientSourcePlugin @Inject constructor(
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>() val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
for (i in 0 until sgvs.length()) { for (i in 0 until sgvs.length()) {
val sgv = toGv(sgvs.getJSONObject(i)) ?: continue 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 glucoseValues += sgv
} }
// Was that sgv more less 5 mins ago ? // 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_ALARM))
rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM)) rxBus.send(EventDismissNotification(Notification.NS_URGENT_ALARM))
} }

View file

@ -18,7 +18,6 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.XDripBroadcast
import info.nightscout.androidaps.utils.buildHelper.BuildHelper 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.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
@ -103,7 +102,7 @@ class RandomBgPlugin @Inject constructor(
val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>() val glucoseValues = mutableListOf<CgmSourceTransaction.TransactionGlucoseValue>()
glucoseValues += CgmSourceTransaction.TransactionGlucoseValue( glucoseValues += CgmSourceTransaction.TransactionGlucoseValue(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
value = bgMgdl, value = bgMgdl,
raw = 0.0, raw = 0.0,
noise = null, noise = null,

View file

@ -127,6 +127,6 @@ class TreatmentsFragment : DaggerFragment() {
private fun updateGui() { private fun updateGui() {
if (_binding == null) return 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()
} }
} }

View file

@ -147,7 +147,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private void initializeProfileSwitchData(long range) { private void initializeProfileSwitchData(long range) {
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData"); getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData");
synchronized (profiles) { 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 @Deprecated
@Override @Override
public List<Treatment> getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) { public List<Treatment> getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) {
return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil._now(), true) return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil.now(), true)
.blockingGet() .blockingGet()
.stream() .stream()
.map(bolus -> new Treatment(getInjector(), bolus)) .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()); //log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING));
databaseHelper.createOrUpdate(profileSwitch); databaseHelper.createOrUpdate(profileSwitch);
nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date); nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date, dateUtil);
} }
@Override @Override

View file

@ -113,7 +113,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.deletefuturetreatments) + "?", Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.deletefuturetreatments) + "?", Runnable {
uel.log(Action.DELETE_FUTURE_TREATMENTS, Sources.Treatments) uel.log(Action.DELETE_FUTURE_TREATMENTS, Sources.Treatments)
repository repository
.getBolusesDataFromTime(dateUtil._now(), false) .getBolusesDataFromTime(dateUtil.now(), false)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe { list -> .subscribe { list ->
list.forEach { bolus -> list.forEach { bolus ->
@ -125,7 +125,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
} }
} }
repository repository
.getCarbsDataFromTime(dateUtil._now(), false) .getCarbsDataFromTime(dateUtil.now(), false)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe { list -> .subscribe { list ->
list.forEach { carb -> list.forEach { carb ->
@ -137,7 +137,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
} }
} }
repository repository
.getBolusCalculatorResultsDataFromTime(dateUtil._now(), false) .getBolusCalculatorResultsDataFromTime(dateUtil.now(), false)
.observeOn(aapsSchedulers.main) .observeOn(aapsSchedulers.main)
.subscribe { list -> .subscribe { list ->
list.forEach { bolusCalc -> list.forEach { bolusCalc ->
@ -281,7 +281,7 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia) val iob = bolus.iobCalc(activePlugin, System.currentTimeMillis(), profile.dia)
holder.binding.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iobContrib) 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 (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 = holder.binding.mealOrCorrection.text =
when (ml.bolus.type) { when (ml.bolus.type) {
Bolus.Type.SMB -> "SMB" Bolus.Type.SMB -> "SMB"

View file

@ -165,7 +165,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility() holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility() holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(therapyEvent.timestamp) 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.note.text = therapyEvent.note
holder.binding.type.text = translator.translate(therapyEvent.type) holder.binding.type.text = translator.translate(therapyEvent.type)
holder.binding.remove.tag = therapyEvent holder.binding.remove.tag = therapyEvent

View file

@ -69,7 +69,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
binding.recyclerview.setHasFixedSize(true) binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context) 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 { binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity -> activity?.let { activity ->
@ -108,7 +108,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
fun updateGUI() { fun updateGUI() {
if (_binding == null) return 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<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() { inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() {

View file

@ -153,7 +153,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
private inner class RecyclerViewAdapter internal constructor(private var tempTargetList: List<TemporaryTarget>) : RecyclerView.Adapter<TempTargetsViewHolder>() { private inner class RecyclerViewAdapter internal constructor(private var tempTargetList: List<TemporaryTarget>) : RecyclerView.Adapter<TempTargetsViewHolder>() {
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 private val currentlyActiveTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempTargetsViewHolder = override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): TempTargetsViewHolder =
@ -174,7 +174,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
holder.binding.date.setTextColor( holder.binding.date.setTextColor(
when { when {
tempTarget.id == currentlyActiveTarget?.id -> resourceHelper.gc(R.color.colorActive) 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 else -> holder.binding.reasonColon.currentTextColor
}) })
holder.binding.remove.tag = tempTarget holder.binding.remove.tag = tempTarget

View file

@ -171,7 +171,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins()) 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) 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()) 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) var iob = IobTotal(now)
val profile = profileFunction.getProfile(now) val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin) if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin)
@ -194,7 +194,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
init { init {
binding.remove.setOnClickListener { v: View -> binding.remove.setOnClickListener { v: View ->
val tempBasal = v.tag as TemporaryBasal val tempBasal = v.tag as TemporaryBasal
val profile = profileFunction.getProfile(dateUtil._now()) val profile = profileFunction.getProfile(dateUtil.now())
?: return@setOnClickListener ?: return@setOnClickListener
context?.let { context?.let {
OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord), OKDialog.showConfirmation(it, resourceHelper.gs(R.string.removerecord),

View file

@ -201,7 +201,7 @@ open class CommandQueue @Inject constructor(
if ((detailedBolusInfo.carbs > 0) && if ((detailedBolusInfo.carbs > 0) &&
(!activePlugin.get().activePump.pumpDescription.storesCarbInfo || (!activePlugin.get().activePump.pumpDescription.storesCarbInfo ||
detailedBolusInfo.carbsDuration != 0L || detailedBolusInfo.carbsDuration != 0L ||
(detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil._now()) (detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp) > dateUtil.now())
) { ) {
disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction()) disposable += repository.runTransactionForResult(detailedBolusInfo.insertCarbsTransaction())
.subscribeBy( .subscribeBy(

View file

@ -23,7 +23,7 @@ class CommandSMBBolus(
override fun execute() { override fun execute() {
val r: PumpEnactResult val r: PumpEnactResult
val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L 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") 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") 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()) { } else if (detailedBolusInfo.deliverAtTheLatest != 0L && detailedBolusInfo.deliverAtTheLatest + T.mins(1).msecs() > System.currentTimeMillis()) {

View file

@ -104,9 +104,9 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() {
if (config.PUMPCONTROL) shouldUploadStatus = true if (config.PUMPCONTROL) shouldUploadStatus = true
else if (!loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null) else if (!loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null)
shouldUploadStatus = true shouldUploadStatus = true
else if (DateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true else if (dateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true
if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY_IN_MINUTES) && shouldUploadStatus) { if (dateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY_IN_MINUTES) && shouldUploadStatus) {
lastIobUpload = dateUtil._now() lastIobUpload = dateUtil.now()
buildDeviceStatus(dateUtil, loopPlugin, iobCobCalculatorPlugin, profileFunction, buildDeviceStatus(dateUtil, loopPlugin, iobCobCalculatorPlugin, profileFunction,
activePlugin.activePump, receiverStatusStore, runningConfiguration, activePlugin.activePump, receiverStatusStore, runningConfiguration,
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also { BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {

View file

@ -16,7 +16,8 @@ import javax.inject.Singleton
class ActivityMonitor @Inject constructor( class ActivityMonitor @Inject constructor(
private var aapsLogger: AAPSLogger, private var aapsLogger: AAPSLogger,
private val resourceHelper: ResourceHelper, private val resourceHelper: ResourceHelper,
private var sp: SP private val sp: SP,
private val dateUtil: DateUtil
) : Application.ActivityLifecycleCallbacks { ) : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) { override fun onActivityPaused(activity: Activity?) {
@ -26,10 +27,10 @@ class ActivityMonitor @Inject constructor(
aapsLogger.debug(LTag.UI, "onActivityPaused: $name resumed == 0") aapsLogger.debug(LTag.UI, "onActivityPaused: $name resumed == 0")
return return
} }
val elapsed = DateUtil.now() - resumed val elapsed = dateUtil.now() - resumed
val total = sp.getLong("Monitor_" + name + "_total", 0) val total = sp.getLong("Monitor_" + name + "_total", 0)
if (total == 0L) { if (total == 0L) {
sp.putLong("Monitor_" + name + "_start", DateUtil.now()) sp.putLong("Monitor_" + name + "_start", dateUtil.now())
} }
sp.putLong("Monitor_" + name + "_total", total + elapsed) sp.putLong("Monitor_" + name + "_total", total + elapsed)
aapsLogger.debug(LTag.UI, "onActivityPaused: $name elapsed=$elapsed 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?) { override fun onActivityResumed(activity: Activity?) {
val name = activity?.javaClass?.simpleName ?: return val name = activity?.javaClass?.simpleName ?: return
aapsLogger.debug(LTag.UI, "onActivityResumed: $name") 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?) { override fun onActivityStarted(activity: Activity?) {
@ -63,9 +64,9 @@ class ActivityMonitor @Inject constructor(
if (key.startsWith("Monitor") && key.endsWith("total")) { if (key.startsWith("Monitor") && key.endsWith("total")) {
val v = if (value is Long) value else SafeParse.stringToLong(value as String) val v = if (value is Long) value else SafeParse.stringToLong(value as String)
val activity = key.split("_")[1].replace("Activity", "") 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 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) result += resourceHelper.gs(R.string.activitymonitorformat, activity, duration, days)
} }
return result return result

View file

@ -30,8 +30,8 @@ class TddCalculator @Inject constructor(
) { ) {
fun calculate(days: Long): LongSparseArray<TDD> { fun calculate(days: Long): LongSparseArray<TDD> {
val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs()) val startTime = MidnightTime.calc(dateUtil.now() - T.days(days).msecs())
val endTime = MidnightTime.calc(DateUtil.now()) val endTime = MidnightTime.calc(dateUtil.now())
val result = LongSparseArray<TDD>() val result = LongSparseArray<TDD>()
repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet() repository.getBolusesDataFromTimeToTime(startTime, endTime, true).blockingGet()

View file

@ -26,8 +26,8 @@ class TirCalculator @Inject constructor(
fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray<TIR> { fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray<TIR> {
if (lowMgdl < 39) throw RuntimeException("Low below 39") if (lowMgdl < 39) throw RuntimeException("Low below 39")
if (lowMgdl > highMgdl) throw RuntimeException("Low > High") if (lowMgdl > highMgdl) throw RuntimeException("Low > High")
val startTime = MidnightTime.calc(DateUtil.now() - T.days(days).msecs()) val startTime = MidnightTime.calc(dateUtil.now() - T.days(days).msecs())
val endTime = MidnightTime.calc(DateUtil.now()) val endTime = MidnightTime.calc(dateUtil.now())
val bgReadings = repository.compatGetBgReadingsDataFromTime(startTime, endTime, true).blockingGet() val bgReadings = repository.compatGetBgReadingsDataFromTime(startTime, endTime, true).blockingGet()
val result = LongSparseArray<TIR>() val result = LongSparseArray<TIR>()

View file

@ -249,7 +249,7 @@ class BolusWizard @Inject constructor(
private fun createBolusCalculatorResult(): BolusCalculatorResult = private fun createBolusCalculatorResult(): BolusCalculatorResult =
BolusCalculatorResult( BolusCalculatorResult(
timestamp = dateUtil._now(), timestamp = dateUtil.now(),
targetBGLow = targetBGLow, targetBGLow = targetBGLow,
targetBGHigh = targetBGHigh, targetBGHigh = targetBGHigh,
isf = sens, isf = sens,
@ -439,7 +439,7 @@ class BolusWizard @Inject constructor(
} }
if (useAlarm && carbs > 0 && carbTime > 0) { if (useAlarm && carbs > 0 && carbTime > 0) {
carbTimer.scheduleReminder(dateUtil._now() + T.mins(carbTime.toLong()).msecs()) carbTimer.scheduleReminder(dateUtil.now() + T.mins(carbTime.toLong()).msecs())
} }
} }
}) })

View file

@ -18,7 +18,6 @@ import info.nightscout.androidaps.extensions.valueToUnits
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.util.*
import javax.inject.Inject import javax.inject.Inject
class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjector) { 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 isActive(): Boolean = Profile.secondsFromMidnight() >= validFrom() && Profile.secondsFromMidnight() <= validTo()
fun doCalc(profile: Profile, profileName: String, lastBG: GlucoseValue, _synchronized: Boolean): BolusWizard { 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 val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null
//BG //BG
var bg = 0.0 var bg = 0.0
@ -129,9 +128,9 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
fun carbs(): Int = safeGetInt(storage, "carbs") 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") fun validFrom(): Int = safeGetInt(storage, "validFrom")

View file

@ -1,10 +1,13 @@
package info.nightscout.androidaps package info.nightscout.androidaps
import android.content.Context
import info.nightscout.androidaps.logging.AAPSLoggerTest 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.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule import org.mockito.junit.MockitoRule

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps package info.nightscout.androidaps
import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
@ -25,10 +26,10 @@ open class TestBaseWithProfile : TestBase() {
@Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var configInterface: ConfigInterface @Mock lateinit var configInterface: ConfigInterface
@Mock lateinit var context: Context
lateinit var dateUtil: DateUtil
val rxBus = RxBusWrapper(aapsSchedulers) val rxBus = RxBusWrapper(aapsSchedulers)
val profileInjector = HasAndroidInjector { val profileInjector = HasAndroidInjector {
@ -40,6 +41,7 @@ open class TestBaseWithProfile : TestBase() {
it.rxBus = rxBus it.rxBus = rxBus
it.fabricPrivacy = fabricPrivacy it.fabricPrivacy = fabricPrivacy
it.configInterface = configInterface it.configInterface = configInterface
it.dateUtil = dateUtil
} }
if (it is ProfileSwitch) { if (it is ProfileSwitch) {
it.treatmentsPlugin = treatmentsInterface it.treatmentsPlugin = treatmentsInterface
@ -58,6 +60,7 @@ open class TestBaseWithProfile : TestBase() {
@Before @Before
fun prepareMock() { 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\"}" 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) validProfile = Profile(profileInjector, JSONObject(validProfileJSON), Constants.MGDL)
} }

View file

@ -1,29 +1,25 @@
package info.nightscout.androidaps.data.defaultProfile 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.Constants
import info.nightscout.androidaps.TestBaseWithProfile
import org.junit.Assert.assertEquals import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class DefaultProfileTest : TestBase() { class DefaultProfileTest : TestBaseWithProfile() {
val injector = HasAndroidInjector { AndroidInjector { } }
@Test @Test
fun profile() { 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(0.150, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(11.8, p.getIsfTimeFromMidnight(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(0.350, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(6.8, p.getIsfTimeFromMidnight(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(0.80, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(10.0, p.getIcTimeFromMidnight(0), 0.001) assertEquals(10.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(2.2, p.getIsfTimeFromMidnight(0), 0.001) assertEquals(2.2, p.getIsfTimeFromMidnight(0), 0.001)

View file

@ -63,7 +63,6 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
@Mock lateinit var commandQueue: CommandQueueProvider @Mock lateinit var commandQueue: CommandQueueProvider
@Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Mock lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage @Mock lateinit var temporaryBasalStorage: TemporaryBasalStorage
@Mock lateinit var context: Context
@Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin
@Mock lateinit var profiler: Profiler @Mock lateinit var profiler: Profiler
@ -92,6 +91,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
AndroidInjector { AndroidInjector {
if (it is Objective) { if (it is Objective) {
it.sp = sp it.sp = sp
it.dateUtil = dateUtil
} }
if (it is PumpEnactResult) { if (it is PumpEnactResult) {
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
@ -137,13 +137,13 @@ class ConstraintsCheckerTest : TestBaseWithProfile() {
`when`(activePlugin.activePump).thenReturn(virtualPumpPlugin) `when`(activePlugin.activePump).thenReturn(virtualPumpPlugin)
constraintChecker = ConstraintChecker(activePlugin) 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) danaPump = DanaPump(aapsLogger, sp, dateUtil, injector)
hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository) hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context, repository)
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), dateUtil, uel)
comboPlugin = ComboPlugin(injector, aapsLogger, rxBus, resourceHelper, profileFunction, sp, commandQueue, context, databaseHelper, pumpSync) 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) 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) 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) insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, treatmentsInterface, sp, commandQueue, profileFunction, nsUpload, context, uploadQueue, Config(), dateUtil, databaseHelper, pumpSync)

View file

@ -31,7 +31,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @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() { class LoopPluginTest : TestBase() {
@Mock lateinit var sp: SP @Mock lateinit var sp: SP

View file

@ -21,13 +21,14 @@ import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@PrepareForTest(UserEntryLogger::class)
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(UserEntryLogger::class, DateUtil::class)
class ObjectivesPluginTest : TestBase() { class ObjectivesPluginTest : TestBase() {
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var uel: UserEntryLogger @Mock lateinit var uel: UserEntryLogger
private lateinit var objectivesPlugin: ObjectivesPlugin private lateinit var objectivesPlugin: ObjectivesPlugin
@ -37,12 +38,13 @@ class ObjectivesPluginTest : TestBase() {
if (it is Objective) { if (it is Objective) {
it.sp = sp it.sp = sp
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.dateUtil = dateUtil
} }
} }
} }
@Before fun prepareMock() { @Before fun prepareMock() {
objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), uel) objectivesPlugin = ObjectivesPlugin(injector, aapsLogger, resourceHelper, activePlugin, sp, Config(), dateUtil, uel)
objectivesPlugin.onStart() objectivesPlugin.onStart()
`when`(resourceHelper.gs(R.string.objectivenotstarted)).thenReturn("Objective %1\$d not started") `when`(resourceHelper.gs(R.string.objectivenotstarted)).thenReturn("Objective %1\$d not started")
} }
@ -53,7 +55,7 @@ class ObjectivesPluginTest : TestBase() {
c = objectivesPlugin.isLoopInvocationAllowed(c) c = objectivesPlugin.isLoopInvocationAllowed(c)
Assert.assertEquals("Objectives: Objective 1 not started", c.getReasons(aapsLogger)) Assert.assertEquals("Objectives: Objective 1 not started", c.getReasons(aapsLogger))
Assert.assertEquals(false, c.value()) Assert.assertEquals(false, c.value())
objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].startedOn = DateUtil.now() objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].startedOn = dateUtil.now()
} }
@Test fun notStartedObjective6ShouldLimitClosedLoop() { @Test fun notStartedObjective6ShouldLimitClosedLoop() {

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.constraints.safety package info.nightscout.androidaps.plugins.constraints.safety
import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
@ -42,7 +41,6 @@ class SafetyPluginTest : TestBaseWithProfile() {
@Mock lateinit var buildHelper: BuildHelper @Mock lateinit var buildHelper: BuildHelper
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var glimpPlugin: GlimpPlugin @Mock lateinit var glimpPlugin: GlimpPlugin
@Mock lateinit var context: Context
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
private lateinit var hardLimits: HardLimits private lateinit var hardLimits: HardLimits

View file

@ -5,7 +5,6 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.TestBase 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.OneTimePassword
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -30,6 +29,7 @@ class AuthRequestTest : TestBase() {
@Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var otp: OneTimePassword @Mock lateinit var otp: OneTimePassword
@Mock lateinit var dateUtil: DateUtil
var injector: HasAndroidInjector = HasAndroidInjector { var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -38,6 +38,7 @@ class AuthRequestTest : TestBase() {
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.smsCommunicatorPlugin = smsCommunicatorPlugin it.smsCommunicatorPlugin = smsCommunicatorPlugin
it.otp = otp it.otp = otp
it.dateUtil = dateUtil
} }
} }
} }
@ -87,10 +88,10 @@ class AuthRequestTest : TestBase() {
// test timed out message // test timed out message
val now: Long = 10000 val now: Long = 10000
PowerMockito.mockStatic(DateUtil::class.java) 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) authRequest = AuthRequest(injector, requester, "Request text", "ABC", action)
actionCalled = false 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") authRequest.action("ABC")
Assert.assertFalse(actionCalled) Assert.assertFalse(actionCalled)
} }

View file

@ -2,7 +2,6 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.content.Context
import android.telephony.SmsManager import android.telephony.SmsManager
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
@ -44,6 +43,7 @@ import org.mockito.ArgumentMatchers
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito import org.mockito.Mockito
import org.mockito.Mockito.`when` import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyLong
import org.mockito.invocation.InvocationOnMock import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer import org.mockito.stubbing.Answer
import org.powermock.api.mockito.PowerMockito import org.powermock.api.mockito.PowerMockito
@ -56,10 +56,9 @@ import java.util.*
ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class, ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class,
SmsManager::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class, SmsManager::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class,
IobCobCalculatorPlugin::class, OneTimePassword::class, UserEntryLogger::class, LoopPlugin::class, IobCobCalculatorPlugin::class, OneTimePassword::class, UserEntryLogger::class, LoopPlugin::class,
AppRepository::class) AppRepository::class, DateUtil::class)
class SmsCommunicatorPluginTest : TestBaseWithProfile() { class SmsCommunicatorPluginTest : TestBaseWithProfile() {
@Mock lateinit var context: Context
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@ -72,6 +71,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
@Mock lateinit var xdripCalibrations: XdripCalibrations @Mock lateinit var xdripCalibrations: XdripCalibrations
@Mock lateinit var uel: UserEntryLogger @Mock lateinit var uel: UserEntryLogger
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
@Mock lateinit var dateUtilMocked: DateUtil
var injector: HasAndroidInjector = HasAndroidInjector { var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -83,6 +83,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
it.smsCommunicatorPlugin = smsCommunicatorPlugin it.smsCommunicatorPlugin = smsCommunicatorPlugin
it.resourceHelper = resourceHelper it.resourceHelper = resourceHelper
it.otp = otp 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.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0))
`when`(iobCobCalculator.lastBg()).thenReturn(reading) `when`(iobCobCalculator.lastBg()).thenReturn(reading)
PowerMockito.spy(DateUtil::class.java)
PowerMockito.mockStatic(SmsManager::class.java) PowerMockito.mockStatic(SmsManager::class.java)
val smsManager = PowerMockito.mock(SmsManager::class.java) val smsManager = PowerMockito.mock(SmsManager::class.java)
`when`(SmsManager.getDefault()).thenReturn(smsManager) `when`(SmsManager.getDefault()).thenReturn(smsManager)
@ -110,9 +110,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
repository.runTransactionForResult(anyObject<InsertTemporaryTargetAndCancelCurrentTransaction>()) repository.runTransactionForResult(anyObject<InsertTemporaryTargetAndCancelCurrentTransaction>())
).thenReturn(Single.just(InsertTemporaryTargetAndCancelCurrentTransaction.TransactionResult().apply { ).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) smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true)
Mockito.doAnswer { invocation: InvocationOnMock -> Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(1) val callback = invocation.getArgument<Callback>(1)
@ -764,7 +764,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms) smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages[0].text) 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) 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<Int>(20)) `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20))
//BASAL 20% 30 //BASAL 20% 30
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -884,7 +884,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0)) `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) `when`(sp.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L)
//BOLUS 1 //BOLUS 1
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -893,7 +893,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text) Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) `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 //BOLUS 0
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -989,7 +989,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
} }
@Test fun processCarbsTest() { @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) `when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false)
//CAL //CAL
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -1005,7 +1005,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms) smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint<Int>(0)) `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0))
//CARBS 0 //CARBS 0
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -1013,7 +1013,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms) smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text) Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text) Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint<Int>(1)) `when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1))
//CARBS 1 //CARBS 1
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
@ -1041,6 +1041,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format")) Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format"))
//CARBS 1 12:01 //CARBS 1 12:01
`when`(dateUtilMocked.timeString(anyLong())).thenReturn("12:01PM")
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
sms = Sms("1234", "CARBS 1 12:01") sms = Sms("1234", "CARBS 1 12:01")
smsCommunicatorPlugin.processSms(sms) smsCommunicatorPlugin.processSms(sms)
@ -1052,6 +1053,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully")) Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully"))
//CARBS 1 3:01AM //CARBS 1 3:01AM
`when`(dateUtilMocked.timeString(anyLong())).thenReturn("03:01AM")
smsCommunicatorPlugin.messages = ArrayList() smsCommunicatorPlugin.messages = ArrayList()
sms = Sms("1234", "CARBS 1 3:01AM") sms = Sms("1234", "CARBS 1 3:01AM")
smsCommunicatorPlugin.processSms(sms) smsCommunicatorPlugin.processSms(sms)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.iob.iobCobCalculator package info.nightscout.androidaps.plugins.iob.iobCobCalculator
import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
@ -38,9 +39,10 @@ class IobCobCalculatorPluginTest : TestBase() {
@Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin @Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin @Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
@Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var repository: AppRepository @Mock lateinit var repository: AppRepository
@Mock lateinit var context: Context
lateinit var dateUtil: DateUtil
lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
@ -50,6 +52,7 @@ class IobCobCalculatorPluginTest : TestBase() {
@Before @Before
fun mock() { fun mock() {
dateUtil = DateUtil(context)
iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository) 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 // real data gap test
bgReadingList.clear() 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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-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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList iobCobCalculatorPlugin.bgReadings = bgReadingList
iobCobCalculatorPlugin.referenceTime = -1 iobCobCalculatorPlugin.referenceTime = -1
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData) Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData() iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(DateUtil.fromISODateString("2018-09-05T13:34:57Z").time, iobCobCalculatorPlugin.bucketedData!![0].timestamp) Assert.assertEquals(dateUtil.fromISODateString("2018-09-05T13:34:57Z"), 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-05T03:44:57Z"), iobCobCalculatorPlugin.bucketedData!![iobCobCalculatorPlugin.bucketedData!!.size - 1].timestamp)
// 5min 4sec data // 5min 4sec data
bgReadingList.clear() 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: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").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"), 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: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").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"), 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: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").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"), 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-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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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: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").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"), 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-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").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"), 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-05T04:52:17Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData) Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
} }
@ -289,7 +292,7 @@ class IobCobCalculatorPluginTest : TestBase() {
@Test @Test
fun roundUpTimeTest() { 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 @Test

View file

@ -24,7 +24,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(FabricPrivacy::class) @PrepareForTest(FabricPrivacy::class, DateUtil::class)
class VirtualPumpPluginUTest : TestBase() { class VirtualPumpPluginUTest : TestBase() {
private val rxBus = RxBusWrapper(aapsSchedulers) private val rxBus = RxBusWrapper(aapsSchedulers)

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.treatments package info.nightscout.androidaps.plugins.treatments
import android.content.Context
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBaseWithProfile 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.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.UploadQueueInterface import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload 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.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.junit.Assert
import org.junit.Before
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mock import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@ -29,7 +22,6 @@ import org.powermock.modules.junit4.PowerMockRunner
@PrepareForTest(FabricPrivacy::class, DatabaseHelperInterface::class, AppRepository::class) @PrepareForTest(FabricPrivacy::class, DatabaseHelperInterface::class, AppRepository::class)
class TreatmentsPluginTest : TestBaseWithProfile() { class TreatmentsPluginTest : TestBaseWithProfile() {
@Mock lateinit var context: Context
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var treatmentService: TreatmentService @Mock lateinit var treatmentService: TreatmentService
@Mock lateinit var nsUpload: NSUpload @Mock lateinit var nsUpload: NSUpload
@ -67,7 +59,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Test @Test
fun `zero TBR should produce zero absolute insulin`() { fun `zero TBR should produce zero absolute insulin`() {
val now = DateUtil.now() val now = dateUtil._now()
val tbrs: MutableList<TemporaryBasal> = ArrayList() val tbrs: MutableList<TemporaryBasal> = ArrayList()
tbrs.add(TemporaryBasal(injector).date(now - T.hours(30).msecs()).duration(10000).percent(0)) tbrs.add(TemporaryBasal(injector).date(now - T.hours(30).msecs()).duration(10000).percent(0))
@ -79,7 +71,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Test @Test
fun `90pct TBR and should produce less absolute insulin`() { fun `90pct TBR and should produce less absolute insulin`() {
val now = DateUtil.now() val now = dateUtil._now()
val tbrs: MutableList<TemporaryBasal> = ArrayList() val tbrs: MutableList<TemporaryBasal> = ArrayList()
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)
sot.initializeData(T.hours(30).msecs()) sot.initializeData(T.hours(30).msecs())
@ -93,7 +85,7 @@ class TreatmentsPluginTest : TestBaseWithProfile() {
@Test @Test
fun `110pct TBR and should produce 10pct more absolute insulin`() { fun `110pct TBR and should produce 10pct more absolute insulin`() {
val now = DateUtil.now() val now = dateUtil._now()
val tbrs: MutableList<TemporaryBasal> = ArrayList() val tbrs: MutableList<TemporaryBasal> = ArrayList()
`when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs) `when`(databaseHelper.getTemporaryBasalsDataFromTime(ArgumentMatchers.anyLong(), ArgumentMatchers.anyBoolean())).thenReturn(tbrs)
sot.initializeData(T.hours(30).msecs()) sot.initializeData(T.hours(30).msecs())

View file

@ -50,7 +50,6 @@ class CommandQueueTest : TestBaseWithProfile() {
@Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var lazyActivePlugin: Lazy<ActivePluginProvider> @Mock lateinit var lazyActivePlugin: Lazy<ActivePluginProvider>
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var context: Context
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var loggerUtils: LoggerUtils
@Mock lateinit var powerManager: PowerManager @Mock lateinit var powerManager: PowerManager
@ -226,7 +225,7 @@ class CommandQueueTest : TestBaseWithProfile() {
// given // given
Assert.assertEquals(0, commandQueue.size()) Assert.assertEquals(0, commandQueue.size())
val smb = DetailedBolusInfo() val smb = DetailedBolusInfo()
smb.lastKnownBolusTime = DateUtil.now() smb.lastKnownBolusTime = System.currentTimeMillis()
smb.bolusType = DetailedBolusInfo.BolusType.SMB smb.bolusType = DetailedBolusInfo.BolusType.SMB
commandQueue.bolus(smb, null) commandQueue.bolus(smb, null)
commandQueue.bolus(DetailedBolusInfo(), null) commandQueue.bolus(DetailedBolusInfo(), null)

View file

@ -41,7 +41,6 @@ class QueueThreadTest : TestBaseWithProfile() {
@Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var lazyActivePlugin: Lazy<ActivePluginProvider> @Mock lateinit var lazyActivePlugin: Lazy<ActivePluginProvider>
@Mock lateinit var activePlugin: ActivePluginProvider @Mock lateinit var activePlugin: ActivePluginProvider
@Mock lateinit var context: Context
@Mock lateinit var sp: SP @Mock lateinit var sp: SP
@Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var loggerUtils: LoggerUtils
@Mock lateinit var powerManager: PowerManager @Mock lateinit var powerManager: PowerManager

View file

@ -3,8 +3,14 @@ package info.nightscout.androidaps.utils
import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.TestBase
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock 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() { class SntpClientTest : TestBase() {
@Mock lateinit var dateUtil: DateUtil @Mock lateinit var dateUtil: DateUtil
@ -22,7 +28,7 @@ class SntpClientTest : TestBase() {
SntpClient(aapsLogger, dateUtil).doNtpTime(object : SntpClient.Callback() { SntpClient(aapsLogger, dateUtil).doNtpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
Assert.assertTrue(success) Assert.assertTrue(success)
Assert.assertTrue(Math.abs(time - DateUtil.now()) < 60000) Assert.assertTrue(Math.abs(time - System.currentTimeMillis()) < 60000)
} }
}) })
} }

View file

@ -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.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert import org.junit.Assert
import org.junit.Test import org.junit.Test
@ -27,7 +28,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class) @RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, IobCobCalculatorPlugin::class) @PrepareForTest(ConstraintChecker::class, VirtualPumpPlugin::class, IobCobCalculatorPlugin::class, DateUtil::class)
class BolusWizardTest : TestBase() { class BolusWizardTest : TestBase() {
private val pumpBolusStep = 0.1 private val pumpBolusStep = 0.1
@ -42,6 +43,7 @@ class BolusWizardTest : TestBase() {
@Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var treatmentsPlugin: TreatmentsPlugin @Mock lateinit var treatmentsPlugin: TreatmentsPlugin
@Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin @Mock lateinit var virtualPumpPlugin: VirtualPumpPlugin
@Mock lateinit var dateUtil: DateUtil
val injector = HasAndroidInjector { val injector = HasAndroidInjector {
AndroidInjector { AndroidInjector {
@ -55,7 +57,7 @@ class BolusWizardTest : TestBase() {
it.commandQueue = commandQueue it.commandQueue = commandQueue
it.loopPlugin = loopPlugin it.loopPlugin = loopPlugin
it.iobCobCalculator = iobCobCalculator it.iobCobCalculator = iobCobCalculator
it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator) it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil)
} }
} }
} }

View file

@ -17,6 +17,7 @@ import javax.inject.Inject
class AutomationEvent(private val injector: HasAndroidInjector) { class AutomationEvent(private val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var dateUtil: DateUtil
var title: String = "" var title: String = ""
var isEnabled = true var isEnabled = true
@ -83,6 +84,6 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
} }
fun shouldRun(): Boolean { fun shouldRun(): Boolean {
return lastRun <= DateUtil.now() - T.mins(5).msecs() return lastRun <= dateUtil.now() - T.mins(5).msecs()
} }
} }

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