DateUtil -> kt, static funcs removed

This commit is contained in:
Milos Kozak 2021-04-11 17:47:55 +02:00
parent d898a374e6
commit 998eba8b9f
160 changed files with 935 additions and 991 deletions

View file

@ -89,7 +89,7 @@ class RealPumpTest {
localProfilePlugin.numOfProfiles = 0
val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile")
localProfilePlugin.addProfile(singleProfile)
val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, DateUtil.now())
val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, dateUtil._now())
treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch)
// Insulin
configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN)

View file

@ -210,7 +210,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 ->
ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now())
it.putLong("time", dateUtil._now())
it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
it.putString("customProfile", profile0.data.toString())
it.putString("customProfile2", profile1.data.toString())

View file

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

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

View file

@ -83,7 +83,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
binding.profile.setSelection(p)
} ?: return
treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps ->
treatmentsPlugin.getProfileSwitchFromHistory(dateUtil._now())?.let { ps ->
if (ps.isCPP) {
binding.reuselayout.visibility = View.VISIBLE
binding.reusebutton.text = resourceHelper.gs(R.string.reuse_profile_pct_hours, ps.percentage, ps.timeshift)

View file

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

View file

@ -313,7 +313,7 @@ open class LoopPlugin @Inject constructor(
lastRun = (lastRun ?: LastRun()).also { lastRun ->
lastRun.request = apsResult
lastRun.constraintsProcessed = resultAfterConstraints
lastRun.lastAPSRun = DateUtil.now()
lastRun.lastAPSRun = dateUtil._now()
lastRun.source = (usedAPS as PluginBase).name
lastRun.tbrSetByPump = null
lastRun.smbSetByPump = null
@ -408,7 +408,7 @@ open class LoopPlugin @Inject constructor(
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result
lastRun.lastTBRRequest = lastRun.lastAPSRun
lastRun.lastTBREnact = DateUtil.now()
lastRun.lastTBREnact = dateUtil._now()
rxBus.send(EventLoopUpdateGui())
applySMBRequest(resultAfterConstraints, object : Callback() {
override fun run() {
@ -416,7 +416,7 @@ open class LoopPlugin @Inject constructor(
if (result.enacted || result.success) {
lastRun.smbSetByPump = result
lastRun.lastSMBRequest = lastRun.lastAPSRun
lastRun.lastSMBEnact = DateUtil.now()
lastRun.lastSMBEnact = dateUtil._now()
} else {
Thread {
SystemClock.sleep(1000)
@ -507,8 +507,8 @@ open class LoopPlugin @Inject constructor(
if (result.enacted) {
lastRun.tbrSetByPump = result
lastRun.lastTBRRequest = lastRun.lastAPSRun
lastRun.lastTBREnact = DateUtil.now()
lastRun.lastOpenModeAccept = DateUtil.now()
lastRun.lastTBREnact = dateUtil._now()
lastRun.lastOpenModeAccept = dateUtil._now()
buildDeviceStatus(dateUtil, this@LoopPlugin, iobCobCalculator, profileFunction,
activePlugin.activePump, receiverStatusStore, runningConfiguration,
BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION)?.also {

View file

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

View file

@ -163,7 +163,7 @@ open class OpenAPSAMAPlugin @Inject constructor(
if (determineBasalResultAMA.rate == 0.0 && determineBasalResultAMA.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultAMA.tempBasalRequested = false
determineBasalResultAMA.iob = iobArray[0]
val now = System.currentTimeMillis()
determineBasalResultAMA.json?.put("timestamp", DateUtil.toISOString(now))
determineBasalResultAMA.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultAMA.inputConstraints = inputConstraints
lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS
lastAPSResult = determineBasalResultAMA

View file

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

View file

@ -47,7 +47,7 @@ class DetermineBasalResultSMB private constructor(injector: HasAndroidInjector)
if (result.has("deliverAt")) {
val date = result.getString("deliverAt")
try {
deliverAt = DateUtil.fromISODateString(date).time
deliverAt = dateUtil.fromISODateString(date)
} catch (e: Exception) {
aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: $date", e)
}

View file

@ -189,7 +189,7 @@ open class OpenAPSSMBPlugin @Inject constructor(
// Fix bug determine basal
if (determineBasalResultSMB.rate == 0.0 && determineBasalResultSMB.duration == 0 && iobCobCalculator.getTempBasalIncludingConvertedExtended(dateUtil._now()) == null) determineBasalResultSMB.tempBasalRequested = false
determineBasalResultSMB.iob = iobArray[0]
determineBasalResultSMB.json?.put("timestamp", DateUtil.toISOString(now))
determineBasalResultSMB.json?.put("timestamp", dateUtil.toISOString(now))
determineBasalResultSMB.inputConstraints = inputConstraints
lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS
lastAPSResult = determineBasalResultSMB

View file

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

View file

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

View file

@ -108,7 +108,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() {
}
task.answered = result
if (!result) {
task.disabledTo = DateUtil.now() + T.hours(1).msecs()
task.disabledTo = dateUtil._now() + T.hours(1).msecs()
ToastUtils.showToastInUiThread(context, R.string.wronganswer)
} else task.disabledTo = 0
updateGui()

View file

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

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

View file

@ -63,7 +63,8 @@ class ImportExportPrefs @Inject constructor(
private val classicPrefsFormat: ClassicPrefsFormat,
private val encryptedPrefsFormat: EncryptedPrefsFormat,
private val prefFileList: PrefFileListProvider,
private val uel: UserEntryLogger
private val uel: UserEntryLogger,
private val dateUtil: DateUtil
) : ImportExportPrefsInterface {
override fun prefsFileExists(): Boolean {
@ -95,7 +96,7 @@ class ImportExportPrefs @Inject constructor(
val metadata: MutableMap<PrefsMetadataKey, PrefMetadata> = mutableMapOf()
metadata[PrefsMetadataKey.DEVICE_NAME] = PrefMetadata(detectUserName(context), PrefsStatus.OK)
metadata[PrefsMetadataKey.CREATED_AT] = PrefMetadata(DateUtil.toISOString(Date()), PrefsStatus.OK)
metadata[PrefsMetadataKey.CREATED_AT] = PrefMetadata(dateUtil.toISOString(dateUtil._now()), PrefsStatus.OK)
metadata[PrefsMetadataKey.AAPS_VERSION] = PrefMetadata(BuildConfig.VERSION_NAME, PrefsStatus.OK)
metadata[PrefsMetadataKey.AAPS_FLAVOUR] = PrefMetadata(BuildConfig.FLAVOR, PrefsStatus.OK)
metadata[PrefsMetadataKey.DEVICE_MODEL] = PrefMetadata(config.currentDeviceModelString, PrefsStatus.OK)

View file

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

View file

@ -179,7 +179,7 @@ class NSDeviceStatus @Inject constructor(
if (fields.contains("reservoir")) string.append(pumpData.reservoir.toInt()).append("U ")
if (fields.contains("battery") && pumpData.isPercent) string.append(pumpData.percent).append("% ")
if (fields.contains("battery") && !pumpData.isPercent) string.append(Round.roundTo(pumpData.voltage, 0.001)).append(" ")
if (fields.contains("clock")) string.append(DateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ")
if (fields.contains("clock")) string.append(dateUtil.minAgo(resourceHelper, pumpData.clock)).append(" ")
if (fields.contains("status")) string.append(pumpData.status).append(" ")
if (fields.contains("device")) string.append(device).append(" ")
string.append("</span>") // color
@ -201,7 +201,7 @@ class NSDeviceStatus @Inject constructor(
try {
val data = this.data ?: return
val pump = if (data.has("pump")) data.getJSONObject("pump") else JSONObject()
val clock = if (pump.has("clock")) DateUtil.fromISODateString(pump.getString("clock")).time else 0L
val clock = if (pump.has("clock")) dateUtil.fromISODateString(pump.getString("clock")) else 0L
// check if this is new data
if (clock == 0L || deviceStatusPumpData != null && clock < deviceStatusPumpData!!.clock) return
@ -247,13 +247,13 @@ class NSDeviceStatus @Inject constructor(
val openAps = if (jsonObject.has("openaps")) jsonObject.getJSONObject("openaps") else JSONObject()
val suggested = if (openAps.has("suggested")) openAps.getJSONObject("suggested") else JSONObject()
val enacted = if (openAps.has("enacted")) openAps.getJSONObject("enacted") else JSONObject()
var clock = if (suggested.has("timestamp")) DateUtil.fromISODateString(suggested.getString("timestamp")).time else 0L
var clock = if (suggested.has("timestamp")) dateUtil.fromISODateString(suggested.getString("timestamp")) else 0L
// check if this is new data
if (clock != 0L && clock > deviceStatusOpenAPSData.clockSuggested) {
deviceStatusOpenAPSData.suggested = suggested
deviceStatusOpenAPSData.clockSuggested = clock
}
clock = if (enacted.has("timestamp")) DateUtil.fromISODateString(enacted.getString("timestamp")).time else 0L
clock = if (enacted.has("timestamp")) dateUtil.fromISODateString(enacted.getString("timestamp")) else 0L
// check if this is new data
if (clock != 0L && clock > deviceStatusOpenAPSData.clockEnacted) {
deviceStatusOpenAPSData.enacted = enacted
@ -278,7 +278,7 @@ class NSDeviceStatus @Inject constructor(
else -> Levels.INFO
}
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
return fromHtml(string.toString())
}
@ -287,8 +287,8 @@ class NSDeviceStatus @Inject constructor(
get() {
val string = StringBuilder()
try {
if (deviceStatusOpenAPSData.enacted != null && deviceStatusOpenAPSData.clockEnacted != deviceStatusOpenAPSData.clockSuggested) string.append("<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.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>")
return fromHtml(string.toString())
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
@ -307,7 +307,7 @@ class NSDeviceStatus @Inject constructor(
val clock =
when {
jsonObject.has("mills") -> jsonObject.getLong("mills")
jsonObject.has("created_at") -> DateUtil.fromISODateString(jsonObject.getString("created_at")).time
jsonObject.has("created_at") -> dateUtil.fromISODateString(jsonObject.getString("created_at"))
else -> 0L
}
val device = device

View file

@ -591,7 +591,7 @@ public class NSClientService extends DaggerService {
void watchdog() {
synchronized (reconnections) {
long now = DateUtil.now();
long now = dateUtil._now();
reconnections.add(now);
for (int i = 0; i < reconnections.size(); i++) {
Long r = reconnections.get(i);

View file

@ -309,7 +309,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
R.id.active_profile -> {
ProfileViewerDialog().also { pvd ->
pvd.arguments = Bundle().also {
it.putLong("time", DateUtil.now())
it.putLong("time", dateUtil._now())
it.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal)
}
}.show(childFragmentManager, "ProfileViewDialog")
@ -549,7 +549,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (_binding == null) return
aapsLogger.debug("UpdateGUI from $from")
binding.infoLayout.time.text = dateUtil.timeString(Date())
binding.infoLayout.time.text = dateUtil.timeString(dateUtil._now())
if (!profileFunction.isProfileValid("Overview")) {
binding.loopPumpStatusLayout.pumpStatus.setText(R.string.noprofileset)
@ -612,8 +612,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} else flag and Paint.STRIKE_THRU_TEXT_FLAG.inv()
overview_bg.paintFlags = flag
}
binding.infoLayout.timeAgo.text = DateUtil.minAgo(resourceHelper, lastBG.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + DateUtil.minAgoShort(lastBG.timestamp) + ")"
binding.infoLayout.timeAgo.text = dateUtil.minAgo(resourceHelper, lastBG.timestamp)
binding.infoLayout.timeAgoShort.text = "(" + dateUtil.minAgoShort(lastBG.timestamp) + ")"
}
val closedLoopEnabled = constraintChecker.isClosedLoopAllowed()
@ -625,19 +625,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
when {
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_superbolus)
binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.visibility = View.VISIBLE
}
loopPlugin.isDisconnected -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_disconnected)
binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.visibility = View.VISIBLE
}
loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
binding.infoLayout.apsMode.setImageResource(R.drawable.ic_loop_paused)
binding.infoLayout.apsModeText.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.text = dateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
binding.infoLayout.apsModeText.visibility = View.VISIBLE
}
@ -684,7 +684,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (tempTarget is ValueWrapper.Existing) {
binding.loopPumpStatusLayout.tempTarget.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning))
binding.loopPumpStatusLayout.tempTarget.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning))
binding.loopPumpStatusLayout.tempTarget.text = Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.highTarget, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.value.end, resourceHelper)
binding.loopPumpStatusLayout.tempTarget.text = Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.highTarget, Constants.MGDL, units) + " " + dateUtil.untilString(tempTarget.value.end, resourceHelper)
} else {
// If the target is not the same as set in the profile then oref has overridden it
val targetUsed = lastRun?.constraintsProcessed?.targetBG ?: 0.0

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,8 @@ import javax.inject.Singleton
@Singleton
class OneTimePassword @Inject constructor(
private val sp: SP,
private val resourceHelper: ResourceHelper
private val resourceHelper: ResourceHelper,
private val dateUtil: DateUtil
) {
private var key: SecretKey? = null
@ -85,7 +86,7 @@ class OneTimePassword @Inject constructor(
return OneTimePasswordValidationResult.ERROR_WRONG_PIN
}
val counter: Long = DateUtil.now() / 30000L
val counter: Long = dateUtil._now() / 30000L
val acceptableTokens: MutableList<String> = mutableListOf(generateOneTimePassword(counter))
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) {
rxBus.send(EventTidepoolStatus(("Creating new dataset")))
val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!,
OpenDatasetRequestMessage(activePlugin.activePump.serialNumber()).getBody())
OpenDatasetRequestMessage(activePlugin.activePump.serialNumber(), dateUtil).getBody())
call.enqueue(TidepoolCallback<DatasetReplyMessage>(aapsLogger, rxBus, session, "Open New Dataset", {
connectionStatus = ConnectionStatus.CONNECTED
rxBus.send(EventTidepoolStatus(("New dataset OK")))
@ -232,7 +232,7 @@ class TidepoolUploader @Inject constructor(
}
private fun uploadNext() {
if (uploadChunk.getLastEnd() < DateUtil.now() - T.mins(1).msecs()) {
if (uploadChunk.getLastEnd() < dateUtil._now() - T.mins(1).msecs()) {
SystemClock.sleep(3000)
aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd()))
doUpload()

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,12 +1,12 @@
package info.nightscout.androidaps.plugins.general.tidepool.events
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.utils.DateUtil
import java.text.SimpleDateFormat
import java.util.*
class EventTidepoolStatus(val status: String) : Event() {
var date: Long = DateUtil.now()
var date: Long = System.currentTimeMillis()
private var timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())

View file

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

View file

@ -192,7 +192,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
var dia = Constants.defaultDIA
if (profile != null) dia = profile.dia
val start = to - T.hours((24 + dia).toLong()).msecs()
if (DateUtil.isCloseToNow(to)) {
if (dateUtil.isCloseToNow(to)) {
// if close to now expect there can be some readings with time in close future (caused by wrong time setting)
// so read all records
bgReadings = repository.compatGetBgReadingsDataFromTime(start, false).blockingGet()
@ -309,7 +309,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
}
val bData: MutableList<InMemoryGlucoseValue> = ArrayList()
bData.add(InMemoryGlucoseValue(bgReadings[0]))
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgReadings[0].timestamp) + " lastBgTime: " + "none-first-value" + " " + bgReadings[0].toString())
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgReadings[0].timestamp) + " lastBgTime: " + "none-first-value" + " " + bgReadings[0].toString())
var j = 0
for (i in 1 until bgReadings.size) {
val bgTime = bgReadings[i].timestamp
@ -333,7 +333,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val newBgReading = InMemoryGlucoseValue(nextBgTime, nextBg.roundToLong().toDouble(), true)
//console.error("Interpolated", bData[j]);
bData.add(newBgReading)
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
elapsedMinutes -= 5
lastBg = nextBg
lastBgTime = nextBgTime
@ -341,14 +341,14 @@ open class IobCobCalculatorPlugin @Inject constructor(
j++
val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value)
bData.add(newBgReading)
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
}
abs(elapsedMinutes) > 2 -> {
j++
val newBgReading = InMemoryGlucoseValue(bgTime, bgReadings[i].value)
bData.add(newBgReading)
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastBgTime: " + DateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
aapsLogger.debug(LTag.AUTOSENS, "Adding. bgTime: " + dateUtil.toISOString(bgTime) + " lastBgTime: " + dateUtil.toISOString(lastBgTime) + " " + newBgReading.toString())
}
else -> {
@ -466,7 +466,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
}
private fun calculateFromTreatmentsAndTemps(time: Long, lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): IobTotal {
val now = DateUtil.now()
val now = dateUtil._now()
val bolusIob = calculateIobFromBolusToTime(time).round()
val basalIob = getCalculationToTimeTempBasals(time, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget).round()
// OpenAPSSMB only
@ -551,7 +551,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val autosensData = if (_synchronized) getLastAutosensDataSynchronized(reason) else getLastAutosensData(reason)
var displayCob: Double? = null
var futureCarbs = 0.0
val now = DateUtil.now()
val now = dateUtil._now()
val carbs = repository.getCarbsDataFromTimeExpanded(now, true).blockingGet()
if (autosensData != null) {
displayCob = autosensData.cob
@ -658,7 +658,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
override fun calculateIobArrayForSMB(lastAutosensResult: AutosensResult, exercise_mode: Boolean, half_basal_exercise_target: Int, isTempTarget: Boolean): Array<IobTotal> {
// predict IOB out to DIA plus 30m
val now = DateUtil.now()
val now = dateUtil._now()
val len = 4 * 60 / 5
val array = Array(len) { IobTotal(0) }
for ((pos, i) in (0 until len).withIndex()) {
@ -772,21 +772,21 @@ open class IobCobCalculatorPlugin @Inject constructor(
return if (lastBg.timestamp > System.currentTimeMillis() - T.mins(9).msecs()) lastBg else null
}
// roundup to whole minute
fun roundUpTime(time: Long): Long {
return if (time % 60000 == 0L) time else (time / 60000 + 1) * 60000
}
override fun convertToJSONArray(iobArray: Array<IobTotal>): JSONArray {
val array = JSONArray()
for (i in iobArray.indices) {
array.put(iobArray[i].determineBasalJson(dateUtil))
}
return array
}
companion object {
// roundup to whole minute
fun roundUpTime(time: Long): Long {
return if (time % 60000 == 0L) time else (time / 60000 + 1) * 60000
}
fun convertToJSONArray(iobArray: Array<IobTotal>): JSONArray {
val array = JSONArray()
for (i in iobArray.indices) {
array.put(iobArray[i].determineBasalJson())
}
return array
}
// From https://gist.github.com/IceCreamYou/6ffa1b18c4c8f6aeaad2
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method

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.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin.Companion.roundUpTime
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
@ -67,7 +66,7 @@ class IobCobOref1Thread internal constructor(
}
override fun run() {
val start = DateUtil.now()
val start = dateUtil._now()
mWakeLock?.acquire(T.mins(10).msecs())
try {
aapsLogger.debug(LTag.AUTOSENS, "AUTOSENSDATA thread started: $from")
@ -89,7 +88,7 @@ class IobCobOref1Thread internal constructor(
aapsLogger.debug(LTag.AUTOSENS, "Aborting calculation thread (No bucketed data available): $from")
return
}
val prevDataTime = roundUpTime(bucketedData[bucketedData.size - 3].timestamp)
val prevDataTime = iobCobCalculatorPlugin.roundUpTime(bucketedData[bucketedData.size - 3].timestamp)
aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime))
var previous = autosensDataTable[prevDataTime]
// start from oldest to be able sub cob
@ -103,8 +102,8 @@ class IobCobOref1Thread internal constructor(
}
// check if data already exists
var bgTime = bucketedData[i].timestamp
bgTime = roundUpTime(bgTime)
if (bgTime > roundUpTime(DateUtil.now())) continue
bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime)
if (bgTime > iobCobCalculatorPlugin.roundUpTime(dateUtil._now())) continue
var existing: AutosensData?
if (autosensDataTable[bgTime].also { existing = it } != null) {
previous = existing
@ -307,7 +306,7 @@ class IobCobOref1Thread internal constructor(
val hours = calendar[Calendar.HOUR_OF_DAY]
if (min in 0..4 && hours % 2 == 0) autosensData.extraDeviation.add(0.0)
previous = autosensData
if (bgTime < DateUtil.now()) autosensDataTable.put(bgTime, autosensData)
if (bgTime < dateUtil._now()) autosensDataTable.put(bgTime, autosensData)
aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime())
val sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime)
aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: $sensitivity")

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

View file

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

View file

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

View file

@ -142,10 +142,10 @@ class MDIPlugin @Inject constructor(
status.put("status", "normal")
extended.put("Version", version)
extended.put("ActiveProfile", profileName)
status.put("timestamp", DateUtil.toISOString(now))
status.put("timestamp", dateUtil.toISOString(now))
pump.put("status", status)
pump.put("extended", extended)
pump.put("clock", DateUtil.toISOString(now))
pump.put("clock", dateUtil.toISOString(now))
} catch (e: JSONException) {
aapsLogger.error("Exception: ", e)
}

View file

@ -362,12 +362,12 @@ open class VirtualPumpPlugin @Inject constructor(
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp))
extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes)
}
status.put("timestamp", DateUtil.toISOString(now))
status.put("timestamp", dateUtil.toISOString(now))
pump.put("battery", battery)
pump.put("status", status)
pump.put("extended", extended)
pump.put("reservoir", reservoirInUnits)
pump.put("clock", DateUtil.toISOString(now))
pump.put("clock", dateUtil.toISOString(now))
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}

View file

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

View file

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

View file

@ -80,6 +80,7 @@ class DexcomPlugin @Inject constructor(
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var dexcomPlugin: DexcomPlugin
@Inject lateinit var sp: SP
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var dataWorker: DataWorker
@Inject lateinit var broadcastToXDrip: XDripBroadcast
@Inject lateinit var repository: AppRepository
@ -119,7 +120,7 @@ class DexcomPlugin @Inject constructor(
for (i in 0 until meters.size()) {
meters.getBundle(i.toString())?.let {
val timestamp = it.getLong("timestamp") * 1000
val now = DateUtil.now()
val now = dateUtil._now()
if (timestamp > now - T.months(1).msecs() && timestamp < now) {
calibrations.add(CgmSourceTransaction.Calibration(
timestamp = it.getLong("timestamp") * 1000,

View file

@ -147,7 +147,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private void initializeProfileSwitchData(long range) {
getAapsLogger().debug(LTag.DATATREATMENTS, "initializeProfileSwitchData");
synchronized (profiles) {
profiles.reset().add(databaseHelper.getProfileSwitchData(DateUtil.now() - range, false));
profiles.reset().add(databaseHelper.getProfileSwitchData(dateUtil._now() - range, false));
}
}
@ -360,7 +360,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
//log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING));
databaseHelper.createOrUpdate(profileSwitch);
nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date);
nsUpload.uploadProfileSwitch(profileSwitch, profileSwitch.date, dateUtil);
}
@Override

View file

@ -165,7 +165,7 @@ class TreatmentsCareportalFragment : DaggerFragment() {
holder.binding.ns.visibility = (therapyEvent.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.invalid.visibility = therapyEvent.isValid.not().toVisibility()
holder.binding.date.text = dateUtil.dateAndTimeString(therapyEvent.timestamp)
holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else DateUtil.niceTimeScalar(therapyEvent.duration, resourceHelper)
holder.binding.duration.text = if (therapyEvent.duration == 0L) "" else dateUtil.niceTimeScalar(therapyEvent.duration, resourceHelper)
holder.binding.note.text = therapyEvent.note
holder.binding.type.text = translator.translate(therapyEvent.type)
holder.binding.remove.tag = therapyEvent

View file

@ -69,7 +69,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState)
binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.recyclerview.adapter = RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false))
binding.recyclerview.adapter = RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(dateUtil._now() - T.days(30).msecs(), false))
binding.refreshFromNightscout.setOnClickListener {
activity?.let { activity ->
@ -108,7 +108,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() {
fun updateGUI() {
if (_binding == null) return
binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(DateUtil.now() - T.days(30).msecs(), false)), false)
binding.recyclerview.swapAdapter(RecyclerProfileViewAdapter(databaseHelper.getProfileSwitchData(dateUtil._now() - T.days(30).msecs(), false)), false)
}
inner class RecyclerProfileViewAdapter(private var profileSwitchList: List<ProfileSwitch>) : RecyclerView.Adapter<ProfileSwitchViewHolder>() {

View file

@ -174,7 +174,7 @@ class TreatmentsTempTargetFragment : DaggerFragment() {
holder.binding.date.setTextColor(
when {
tempTarget.id == currentlyActiveTarget?.id -> resourceHelper.gc(R.color.colorActive)
tempTarget.timestamp > DateUtil.now() -> resourceHelper.gc(R.color.colorScheduled)
tempTarget.timestamp > dateUtil._now() -> resourceHelper.gc(R.color.colorScheduled)
else -> holder.binding.reasonColon.currentTextColor
})
holder.binding.remove.tag = tempTarget

View file

@ -171,7 +171,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() {
holder.binding.duration.text = resourceHelper.gs(R.string.format_mins, T.msecs(tempBasal.duration).mins())
if (tempBasal.isAbsolute) holder.binding.rate.text = resourceHelper.gs(R.string.pump_basebasalrate, tempBasal.rate)
else holder.binding.rate.text = resourceHelper.gs(R.string.format_percent, tempBasal.rate.toInt())
val now = DateUtil.now()
val now = dateUtil._now()
var iob = IobTotal(now)
val profile = profileFunction.getProfile(now)
if (profile != null) iob = tempBasal.iobCalc(now, profile, activePlugin.activeInsulin)

View file

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

View file

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

View file

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

View file

@ -129,9 +129,9 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
fun carbs(): Int = safeGetInt(storage, "carbs")
fun validFromDate(): Date = DateUtil.toDate(validFrom())
fun validFromDate(): Long = dateUtil.secondsOfTheDayToMilliseconds(validFrom())
fun validToDate(): Date = DateUtil.toDate(validTo())
fun validToDate(): Long = dateUtil.secondsOfTheDayToMilliseconds(validTo())
fun validFrom(): Int = safeGetInt(storage, "validFrom")

View file

@ -1,10 +1,13 @@
package info.nightscout.androidaps
import android.content.Context
import info.nightscout.androidaps.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import org.junit.Before
import org.junit.Rule
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.data.Profile
@ -25,10 +26,10 @@ open class TestBaseWithProfile : TestBase() {
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var profileFunction: ProfileFunction
@Mock lateinit var defaultValueHelper: DefaultValueHelper
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var configInterface: ConfigInterface
@Mock lateinit var context: Context
lateinit var dateUtil: DateUtil
val rxBus = RxBusWrapper(aapsSchedulers)
val profileInjector = HasAndroidInjector {
@ -40,6 +41,7 @@ open class TestBaseWithProfile : TestBase() {
it.rxBus = rxBus
it.fabricPrivacy = fabricPrivacy
it.configInterface = configInterface
it.dateUtil = dateUtil
}
if (it is ProfileSwitch) {
it.treatmentsPlugin = treatmentsInterface
@ -58,6 +60,7 @@ open class TestBaseWithProfile : TestBase() {
@Before
fun prepareMock() {
validProfileJSON = "{\"dia\":\"3\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"100\"},{\"time\":\"2:00\",\"value\":\"110\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
dateUtil = DateUtil(context)
validProfile = Profile(profileInjector, JSONObject(validProfileJSON), Constants.MGDL)
}

View file

@ -1,29 +1,25 @@
package info.nightscout.androidaps.data.defaultProfile
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.TestBaseWithProfile
import org.junit.Assert.assertEquals
import org.junit.Test
class DefaultProfileTest : TestBase() {
val injector = HasAndroidInjector { AndroidInjector { } }
class DefaultProfileTest : TestBaseWithProfile() {
@Test
fun profile() {
var p = DefaultProfile(injector).profile(5.0, 5.1 / 0.3, 0.0, Constants.MMOL)
var p = DefaultProfile(profileInjector).profile(5.0, 5.1 / 0.3, 0.0, Constants.MMOL)
assertEquals(0.150, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(11.8, p.getIsfTimeFromMidnight(0), 0.001)
p = DefaultProfile(injector).profile(7.0, 10.0 / 0.4, 0.0, Constants.MMOL)
p = DefaultProfile(profileInjector).profile(7.0, 10.0 / 0.4, 0.0, Constants.MMOL)
assertEquals(0.350, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(15.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(6.8, p.getIsfTimeFromMidnight(0), 0.001)
p = DefaultProfile(injector).profile(12.0, 25.0 / 0.5, 0.0, Constants.MMOL)
p = DefaultProfile(profileInjector).profile(12.0, 25.0 / 0.5, 0.0, Constants.MMOL)
assertEquals(0.80, p!!.getBasalTimeFromMidnight(0), 0.001)
assertEquals(10.0, p.getIcTimeFromMidnight(0), 0.001)
assertEquals(2.2, p.getIsfTimeFromMidnight(0), 0.001)

View file

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

View file

@ -31,7 +31,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@RunWith(PowerMockRunner::class)
@PrepareForTest(ConstraintChecker::class, ReceiverStatusStore::class, RunningConfiguration::class, UserEntryLogger::class)
@PrepareForTest(ConstraintChecker::class, ReceiverStatusStore::class, RunningConfiguration::class, UserEntryLogger::class, DateUtil::class)
class LoopPluginTest : TestBase() {
@Mock lateinit var sp: SP

View file

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

View file

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

View file

@ -30,6 +30,7 @@ class AuthRequestTest : TestBase() {
@Mock lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
@Mock lateinit var resourceHelper: ResourceHelper
@Mock lateinit var otp: OneTimePassword
@Mock lateinit var dateUtil: DateUtil
var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector {
@ -38,6 +39,7 @@ class AuthRequestTest : TestBase() {
it.resourceHelper = resourceHelper
it.smsCommunicatorPlugin = smsCommunicatorPlugin
it.otp = otp
it.dateUtil = dateUtil
}
}
}
@ -87,10 +89,10 @@ class AuthRequestTest : TestBase() {
// test timed out message
val now: Long = 10000
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
authRequest = AuthRequest(injector, requester, "Request text", "ABC", action)
actionCalled = false
PowerMockito.`when`(DateUtil.now()).thenReturn(now + T.mins(Constants.SMS_CONFIRM_TIMEOUT).msecs() + 1)
PowerMockito.`when`(dateUtil._now()).thenReturn(now + T.mins(Constants.SMS_CONFIRM_TIMEOUT).msecs() + 1)
authRequest.action("ABC")
Assert.assertFalse(actionCalled)
}

View file

@ -44,6 +44,7 @@ import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.anyLong
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.powermock.api.mockito.PowerMockito
@ -56,10 +57,9 @@ import java.util.*
ConstraintChecker::class, FabricPrivacy::class, VirtualPumpPlugin::class, XdripCalibrations::class,
SmsManager::class, CommandQueue::class, LocalProfilePlugin::class, DateUtil::class,
IobCobCalculatorPlugin::class, OneTimePassword::class, UserEntryLogger::class, LoopPlugin::class,
AppRepository::class)
AppRepository::class, DateUtil::class)
class SmsCommunicatorPluginTest : TestBaseWithProfile() {
@Mock lateinit var context: Context
@Mock lateinit var sp: SP
@Mock lateinit var constraintChecker: ConstraintChecker
@Mock lateinit var activePlugin: ActivePluginProvider
@ -72,6 +72,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
@Mock lateinit var xdripCalibrations: XdripCalibrations
@Mock lateinit var uel: UserEntryLogger
@Mock lateinit var repository: AppRepository
@Mock lateinit var dateUtilMocked: DateUtil
var injector: HasAndroidInjector = HasAndroidInjector {
AndroidInjector {
@ -83,6 +84,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
it.smsCommunicatorPlugin = smsCommunicatorPlugin
it.resourceHelper = resourceHelper
it.otp = otp
it.dateUtil = dateUtil
}
}
}
@ -100,7 +102,6 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
`when`(iobCobCalculator.getCobInfo(false, "SMS COB")).thenReturn(CobInfo(10.0, 2.0))
`when`(iobCobCalculator.lastBg()).thenReturn(reading)
PowerMockito.spy(DateUtil::class.java)
PowerMockito.mockStatic(SmsManager::class.java)
val smsManager = PowerMockito.mock(SmsManager::class.java)
`when`(SmsManager.getDefault()).thenReturn(smsManager)
@ -110,9 +111,9 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
repository.runTransactionForResult(anyObject<InsertTemporaryTargetAndCancelCurrentTransaction>())
).thenReturn(Single.just(InsertTemporaryTargetAndCancelCurrentTransaction.TransactionResult().apply {
}))
val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator)
val glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtilMocked)
smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, Config(), DateUtil(context), uel, glucoseStatusProvider, repository)
smsCommunicatorPlugin = SmsCommunicatorPlugin(injector, aapsLogger, resourceHelper, aapsSchedulers, sp, constraintChecker, rxBus, profileFunction, fabricPrivacy, activePlugin, commandQueue, loopPlugin, iobCobCalculator, xdripCalibrations, otp, Config(), dateUtilMocked, uel, glucoseStatusProvider, repository)
smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true)
Mockito.doAnswer { invocation: InvocationOnMock ->
val callback = invocation.getArgument<Callback>(1)
@ -764,7 +765,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("TBR duration must be a multiple of 30 minutes and greater than 0.", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint<Int>(20))
`when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(Constraint(20))
//BASAL 20% 30
smsCommunicatorPlugin.messages = ArrayList()
@ -884,7 +885,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(1.0))
PowerMockito.`when`(DateUtil.now()).thenReturn(1000L)
PowerMockito.`when`(dateUtilMocked._now()).thenReturn(1000L)
`when`(sp.getLong(R.string.key_smscommunicator_remotebolusmindistance, T.msecs(Constants.remoteBolusMinDistance).mins())).thenReturn(15L)
//BOLUS 1
smsCommunicatorPlugin.messages = ArrayList()
@ -893,7 +894,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0))
PowerMockito.`when`(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L)
PowerMockito.`when`(dateUtilMocked._now()).thenReturn(Constants.remoteBolusMinDistance + 1002L)
//BOLUS 0
smsCommunicatorPlugin.messages = ArrayList()
@ -989,7 +990,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
}
@Test fun processCarbsTest() {
PowerMockito.`when`(DateUtil.now()).thenReturn(1000000L)
PowerMockito.`when`(dateUtilMocked._now()).thenReturn(1000000L)
`when`(sp.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false)
//CAL
smsCommunicatorPlugin.messages = ArrayList()
@ -1005,7 +1006,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("CARBS", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint<Int>(0))
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(0))
//CARBS 0
smsCommunicatorPlugin.messages = ArrayList()
@ -1013,7 +1014,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
smsCommunicatorPlugin.processSms(sms)
Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.messages[0].text)
Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages[1].text)
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint<Int>(1))
`when`(constraintChecker.applyCarbsConstraints(anyObject())).thenReturn(Constraint(1))
//CARBS 1
smsCommunicatorPlugin.messages = ArrayList()
@ -1041,6 +1042,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.messages[1].text.contains("Wrong format"))
//CARBS 1 12:01
`when`(dateUtilMocked.timeString(anyLong())).thenReturn("12:01PM")
smsCommunicatorPlugin.messages = ArrayList()
sms = Sms("1234", "CARBS 1 12:01")
smsCommunicatorPlugin.processSms(sms)
@ -1052,6 +1054,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.messages[3].text.startsWith("Carbs 1g entered successfully"))
//CARBS 1 3:01AM
`when`(dateUtilMocked.timeString(anyLong())).thenReturn("03:01AM")
smsCommunicatorPlugin.messages = ArrayList()
sms = Sms("1234", "CARBS 1 3:01AM")
smsCommunicatorPlugin.processSms(sms)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.iob.iobCobCalculator
import android.content.Context
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.TestBase
@ -38,9 +39,10 @@ class IobCobCalculatorPluginTest : TestBase() {
@Mock lateinit var sensitivityAAPSPlugin: SensitivityAAPSPlugin
@Mock lateinit var sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin
@Mock lateinit var fabricPrivacy: FabricPrivacy
@Mock lateinit var dateUtil: DateUtil
@Mock lateinit var repository: AppRepository
@Mock lateinit var context: Context
lateinit var dateUtil: DateUtil
lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
val injector = HasAndroidInjector {
@ -50,6 +52,7 @@ class IobCobCalculatorPluginTest : TestBase() {
@Before
fun mock() {
dateUtil = DateUtil(context)
iobCobCalculatorPlugin = IobCobCalculatorPlugin(injector, aapsLogger, aapsSchedulers, rxBus, sp, resourceHelper, profileFunction, activePlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil, repository)
}
@ -218,64 +221,64 @@ class IobCobCalculatorPluginTest : TestBase() {
// real data gap test
bgReadingList.clear()
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:14:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:09:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T13:04:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:54:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:49:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:44:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:39:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:34:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:29:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:24:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:19:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:14:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:09:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T12:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T11:59:55Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:34:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:14:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:09:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T13:04:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:59:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:54:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:49:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:44:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:39:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:34:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:29:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:24:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:19:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:14:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:09:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T12:04:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T11:59:55Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:29:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:24:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:19:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:14:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:10:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T04:04:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:59:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:54:56Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:50:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-09-05T03:44:57Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:29:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:24:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:19:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:14:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:10:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T04:04:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:59:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:54:56Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:50:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-09-05T03:44:57Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
iobCobCalculatorPlugin.referenceTime = -1
Assert.assertEquals(true, iobCobCalculatorPlugin.isAbout5minData)
iobCobCalculatorPlugin.createBucketedData()
Assert.assertEquals(DateUtil.fromISODateString("2018-09-05T13:34:57Z").time, iobCobCalculatorPlugin.bucketedData!![0].timestamp)
Assert.assertEquals(DateUtil.fromISODateString("2018-09-05T03:44:57Z").time, iobCobCalculatorPlugin.bucketedData!![iobCobCalculatorPlugin.bucketedData!!.size - 1].timestamp)
Assert.assertEquals(dateUtil.fromISODateString("2018-09-05T13:34:57Z"), iobCobCalculatorPlugin.bucketedData!![0].timestamp)
Assert.assertEquals(dateUtil.fromISODateString("2018-09-05T03:44:57Z"), iobCobCalculatorPlugin.bucketedData!![iobCobCalculatorPlugin.bucketedData!!.size - 1].timestamp)
// 5min 4sec data
bgReadingList.clear()
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:33:40Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:28:36Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:23:32Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:18:28Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:13:24Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:08:19Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T06:03:16Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:58:11Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:53:07Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:48:03Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:42:58Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:37:54Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:32:51Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:27:46Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:22:42Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:17:38Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:12:33Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:07:29Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T05:02:26Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:57:21Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = DateUtil.fromISODateString("2018-10-05T04:52:17Z").time, sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:33:40Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:28:36Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:23:32Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:18:28Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:13:24Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:08:19Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T06:03:16Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:58:11Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:53:07Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:48:03Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:42:58Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:37:54Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:32:51Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:27:46Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:22:42Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:17:38Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:12:33Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:07:29Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T05:02:26Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T04:57:21Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
bgReadingList.add(GlucoseValue(raw = 0.0, noise = 0.0, value = 100.0, timestamp = dateUtil.fromISODateString("2018-10-05T04:52:17Z"), sourceSensor = GlucoseValue.SourceSensor.UNKNOWN, trendArrow = GlucoseValue.TrendArrow.FLAT))
iobCobCalculatorPlugin.bgReadings = bgReadingList
Assert.assertEquals(false, iobCobCalculatorPlugin.isAbout5minData)
}
@ -289,7 +292,7 @@ class IobCobCalculatorPluginTest : TestBase() {
@Test
fun roundUpTimeTest() {
Assert.assertEquals(T.mins(3).msecs(), IobCobCalculatorPlugin.roundUpTime(T.secs(155).msecs()))
Assert.assertEquals(T.mins(3).msecs(), iobCobCalculatorPlugin.roundUpTime(T.secs(155).msecs()))
}
@Test

View file

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

View file

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

View file

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

View file

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

View file

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

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

View file

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

View file

@ -208,7 +208,7 @@ class AutomationPlugin @Inject constructor(
action.doAction(object : Callback() {
override fun run() {
val sb = StringBuilder()
sb.append(dateUtil.timeString(DateUtil.now()))
sb.append(dateUtil.timeString(dateUtil._now()))
sb.append(" ")
sb.append(if (result.success) "" else "")
sb.append(" <b>")
@ -229,7 +229,7 @@ class AutomationPlugin @Inject constructor(
}
}
SystemClock.sleep(1100)
event.lastRun = DateUtil.now()
event.lastRun = dateUtil._now()
if (event.autoRemove) automationEvents.remove(event)
}
}

View file

@ -24,6 +24,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var context: Context
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var timerUtil: TimerUtil
var text = InputString()
@ -39,7 +40,7 @@ class ActionAlarm(injector: HasAndroidInjector) : Action(injector) {
override fun isValid(): Boolean = true // empty alarm will show app name
override fun doAction(callback: Callback) {
timerUtil.scheduleReminder(DateUtil.now() + T.secs(10L).msecs(), text.value.takeIf { it.isNotBlank() }
timerUtil.scheduleReminder(dateUtil._now() + T.secs(10L).msecs(), text.value.takeIf { it.isNotBlank() }
?: resourceHelper.gs(R.string.app_name))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
}

View file

@ -26,6 +26,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var uel: UserEntryLogger
var inputProfileName: InputProfileName = InputProfileName(resourceHelper, activePlugin, "")
@ -61,7 +62,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) {
uel.log(UserEntry.Action.PROFILE_SWITCH, Sources.Automation, title,
ValueWithUnit.SimpleString(inputProfileName.value),
ValueWithUnit.Percent(100))
activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, DateUtil.now())
activePlugin.activeTreatments.doProfileSwitch(profileStore, inputProfileName.value, 0, 100, 0, dateUtil._now())
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
}

View file

@ -41,6 +41,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var repository: AppRepository
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var uel: UserEntryLogger
private val disposable = CompositeDisposable()
@ -105,7 +106,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
}
fun tt() = TemporaryTarget(
timestamp = DateUtil.now(),
timestamp = dateUtil._now(),
duration = TimeUnit.MINUTES.toMillis(duration.getMinutes().toLong()),
reason = TemporaryTarget.Reason.AUTOMATION,
lowTarget = Profile.toMgdl(value.value, value.units),

View file

@ -12,13 +12,13 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
class InputDateTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil, var value: Long = DateUtil.now()) : Element() {
class InputDateTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil._now()) : Element() {
override fun addToLayout(root: LinearLayout) {
val label = TextView(root.context)
val dateButton = TextView(root.context)
val timeButton = TextView(root.context)
dateButton.text = DateUtil.dateString(value)
dateButton.text = dateUtil.dateString(value)
timeButton.text = dateUtil.timeString(value)
// create an OnDateSetListener
@ -29,7 +29,7 @@ class InputDateTime(private val resourceHelper: ResourceHelper, private val date
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
value = cal.timeInMillis
dateButton.text = DateUtil.dateString(value)
dateButton.text = dateUtil.dateString(value)
}
dateButton.setOnClickListener {

View file

@ -15,7 +15,7 @@ import java.util.*
class InputTime(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() {
var value: Int = getMinSinceMidnight(DateUtil.now())
var value: Int = getMinSinceMidnight(dateUtil._now())
override fun addToLayout(root: LinearLayout) {
val label = TextView(root.context)

View file

@ -15,8 +15,8 @@ import java.util.*
class InputTimeRange(private val resourceHelper: ResourceHelper, private val dateUtil: DateUtil) : Element() {
var start: Int = getMinSinceMidnight(DateUtil.now())
var end: Int = getMinSinceMidnight(DateUtil.now())
var start: Int = getMinSinceMidnight(dateUtil._now())
var end: Int = getMinSinceMidnight(dateUtil._now())
override fun addToLayout(root: LinearLayout) {
val label = TextView(root.context)

View file

@ -35,7 +35,7 @@ class TriggerIob(injector: HasAndroidInjector) : Trigger(injector) {
override fun shouldRun(): Boolean {
val profile = profileFunction.getProfile() ?: return false
val iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(DateUtil.now(), profile)
val iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(dateUtil._now(), profile)
if (comparator.value.check(iob.iob, insulin.value)) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true

View file

@ -47,7 +47,7 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true
}
val connectionAgo = (DateUtil.now() - lastConnection) / (60 * 1000)
val connectionAgo = (dateUtil._now() - lastConnection) / (60 * 1000)
aapsLogger.debug(LTag.AUTOMATION, "Last connection min ago: $connectionAgo")
if (comparator.value.check(connectionAgo.toInt(), minutesAgo.value)) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())

View file

@ -32,7 +32,7 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) {
}
override fun shouldRun(): Boolean {
val now = DateUtil.now()
val now = dateUtil._now()
if (now >= time.value && now - time.value < T.mins(5).msecs()) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true

View file

@ -38,7 +38,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) {
}
override fun shouldRun(): Boolean {
val currentMinSinceMidnight = getMinSinceMidnight(DateUtil.now())
val currentMinSinceMidnight = getMinSinceMidnight(dateUtil._now())
var doRun = false
if (range.start < range.end && range.start < currentMinSinceMidnight && currentMinSinceMidnight < range.end) doRun = true
else if (range.start > range.end && (range.start < currentMinSinceMidnight || currentMinSinceMidnight < range.end)) doRun = true

View file

@ -10,6 +10,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.elements.InputString
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.TimerUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.junit.Assert
@ -30,6 +31,7 @@ class ActionAlarmTest : TestBase() {
@Mock lateinit var rxBus: RxBusWrapper
@Mock lateinit var context: Context
@Mock lateinit var timerUtil: TimerUtil
@Mock lateinit var dateUtil: DateUtil
private lateinit var sut: ActionAlarm
var injector: HasAndroidInjector = HasAndroidInjector {
@ -39,6 +41,7 @@ class ActionAlarmTest : TestBase() {
it.rxBus = rxBus
it.context = context
it.timerUtil = timerUtil
it.dateUtil = dateUtil
}
if (it is PumpEnactResult) {
it.resourceHelper = resourceHelper

View file

@ -66,6 +66,7 @@ open class ActionsTestBase : TestBaseWithProfile() {
it.repository = repository
it.profileFunction = profileFunction
it.uel = uel
it.dateUtil = dateUtil
}
if (it is ActionSendSMS) {
it.aapsLogger = aapsLogger
@ -78,6 +79,7 @@ open class ActionsTestBase : TestBaseWithProfile() {
it.activePlugin = activePlugin
it.profileFunction = profileFunction
it.uel = uel
it.dateUtil = dateUtil
}
if (it is ActionProfileSwitchPercent) {
it.resourceHelper = resourceHelper

View file

@ -114,8 +114,7 @@ class TriggerAutosensValueTest : TriggerTestBase() {
@Before
fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
}
private fun generateAutosensData(): AutosensData {

View file

@ -28,8 +28,7 @@ class TriggerBgTest : TriggerTestBase() {
fun prepare() {
`when`(profileFunction.getUnits()).thenReturn(Constants.MGDL)
`when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any())
PowerMockito.mockStatic(DateUtil::class.java)
`when`(DateUtil.now()).thenReturn(now)
`when`(dateUtil._now()).thenReturn(now)
}
@Test

View file

@ -24,8 +24,7 @@ class TriggerBolusAgoTest : TriggerTestBase() {
@Before
fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
}
@Test

View file

@ -22,8 +22,7 @@ class TriggerCOBTest : TriggerTestBase() {
var now = 1514766900000L
@Before fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
PowerMockito.`when`(sp.getInt(ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(48)
}

View file

@ -27,8 +27,7 @@ class TriggerDeltaTest : TriggerTestBase() {
@Before
fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
`when`(iobCobCalculatorPlugin.dataLock).thenReturn(Any())
`when`(profileFunction.getUnits()).thenReturn(Constants.MGDL)
}

View file

@ -24,8 +24,7 @@ class TriggerIobTest : TriggerTestBase() {
var now = 1514766900000L
@Before fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
`when`(DateUtil.now()).thenReturn(now)
`when`(dateUtil._now()).thenReturn(now)
`when`(profileFunction.getProfile()).thenReturn(validProfile)
}

View file

@ -24,9 +24,8 @@ class TriggerLocationTest : TriggerTestBase() {
var now = 1514766900000L
@Before fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.mockStatic(LocationService::class.java)
`when`(DateUtil.now()).thenReturn(now)
`when`(dateUtil._now()).thenReturn(now)
PowerMockito.spy(LocationService::class.java)
`when`(locationDataContainer.lastLocation).thenReturn(mockedLocation())
}

View file

@ -23,8 +23,7 @@ class TriggerProfilePercentTest : TriggerTestBase() {
@Before fun mock() {
`when`(profileFunction.getProfile()).thenReturn(validProfile)
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
}
@Test fun shouldRunTest() {

View file

@ -21,8 +21,7 @@ class TriggerPumpLastConnectionTest : TriggerTestBase() {
@Before
fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
}
@Test
@ -30,7 +29,7 @@ class TriggerPumpLastConnectionTest : TriggerTestBase() {
// System.currentTimeMillis() is always 0
// and so is every last connection time
Assert.assertEquals(0L, testPumpPlugin.lastDataTime())
PowerMockito.`when`(DateUtil.now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min
PowerMockito.`when`(dateUtil._now()).thenReturn(now + 10 * 60 * 1000) // set current time to now + 10 min
var t = TriggerPumpLastConnection(injector).setValue(110).comparator(Comparator.Compare.IS_EQUAL)
Assert.assertEquals(110, t.minutesAgo.value)
Assert.assertEquals(Comparator.Compare.IS_EQUAL, t.comparator.value)

View file

@ -20,8 +20,7 @@ class TriggerTempTargetTest : TriggerTestBase() {
var now = 1514766900000L
@Before fun mock() {
PowerMockito.mockStatic(DateUtil::class.java)
PowerMockito.`when`(DateUtil.now()).thenReturn(now)
PowerMockito.`when`(dateUtil._now()).thenReturn(now)
}
/*
@Test fun shouldRunTest() {

View file

@ -54,7 +54,7 @@ open class TriggerTestBase : TestBaseWithProfile() {
it.repository = repository
it.activePlugin = activePlugin
it.iobCobCalculatorPlugin = iobCobCalculatorPlugin
it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin)
it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger, iobCobCalculatorPlugin, dateUtil)
it.dateUtil = dateUtil
}
if (it is TriggerBg) {

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